@astl/player 0.0.0-stage → 0.1.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.
Files changed (107) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/LICENSE +202 -0
  3. package/README.md +36 -2
  4. package/dist/a11y.d.ts +41 -0
  5. package/dist/a11y.d.ts.map +1 -0
  6. package/dist/a11y.js +101 -0
  7. package/dist/a11y.js.map +1 -0
  8. package/dist/attempt/controller.d.ts +104 -0
  9. package/dist/attempt/controller.d.ts.map +1 -0
  10. package/dist/attempt/controller.js +325 -0
  11. package/dist/attempt/controller.js.map +1 -0
  12. package/dist/checker/http.d.ts +17 -0
  13. package/dist/checker/http.d.ts.map +1 -0
  14. package/dist/checker/http.js +115 -0
  15. package/dist/checker/http.js.map +1 -0
  16. package/dist/define.d.ts +35 -0
  17. package/dist/define.d.ts.map +1 -0
  18. package/dist/define.js +84 -0
  19. package/dist/define.js.map +1 -0
  20. package/dist/element/base.d.ts +83 -0
  21. package/dist/element/base.d.ts.map +1 -0
  22. package/dist/element/base.js +239 -0
  23. package/dist/element/base.js.map +1 -0
  24. package/dist/index.d.ts +14 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +8 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/interaction/index.d.ts +12 -0
  29. package/dist/interaction/index.d.ts.map +1 -0
  30. package/dist/interaction/index.js +4 -0
  31. package/dist/interaction/index.js.map +1 -0
  32. package/dist/interaction/keys.d.ts +11 -0
  33. package/dist/interaction/keys.d.ts.map +1 -0
  34. package/dist/interaction/keys.js +13 -0
  35. package/dist/interaction/keys.js.map +1 -0
  36. package/dist/interaction/pick-and-place.d.ts +120 -0
  37. package/dist/interaction/pick-and-place.d.ts.map +1 -0
  38. package/dist/interaction/pick-and-place.js +395 -0
  39. package/dist/interaction/pick-and-place.js.map +1 -0
  40. package/dist/interaction/roving-focus.d.ts +44 -0
  41. package/dist/interaction/roving-focus.d.ts.map +1 -0
  42. package/dist/interaction/roving-focus.js +115 -0
  43. package/dist/interaction/roving-focus.js.map +1 -0
  44. package/dist/messages/en.json +53 -0
  45. package/dist/messages/help/en.json +14 -0
  46. package/dist/messages/help/pl.json +14 -0
  47. package/dist/messages/pl.json +53 -0
  48. package/dist/messages.d.ts +7 -0
  49. package/dist/messages.d.ts.map +1 -0
  50. package/dist/messages.js +18 -0
  51. package/dist/messages.js.map +1 -0
  52. package/dist/player/book.d.ts +13 -0
  53. package/dist/player/book.d.ts.map +1 -0
  54. package/dist/player/book.js +65 -0
  55. package/dist/player/book.js.map +1 -0
  56. package/dist/player/help.d.ts +55 -0
  57. package/dist/player/help.d.ts.map +1 -0
  58. package/dist/player/help.js +484 -0
  59. package/dist/player/help.js.map +1 -0
  60. package/dist/player/player.d.ts +87 -0
  61. package/dist/player/player.d.ts.map +1 -0
  62. package/dist/player/player.js +1229 -0
  63. package/dist/player/player.js.map +1 -0
  64. package/dist/player/styled.d.ts +10 -0
  65. package/dist/player/styled.d.ts.map +1 -0
  66. package/dist/player/styled.js +213 -0
  67. package/dist/player/styled.js.map +1 -0
  68. package/dist/player/styles.d.ts +3 -0
  69. package/dist/player/styles.d.ts.map +1 -0
  70. package/dist/player/styles.js +355 -0
  71. package/dist/player/styles.js.map +1 -0
  72. package/dist/player/templates.d.ts +25 -0
  73. package/dist/player/templates.d.ts.map +1 -0
  74. package/dist/player/templates.js +101 -0
  75. package/dist/player/templates.js.map +1 -0
  76. package/dist/player/view.d.ts +44 -0
  77. package/dist/player/view.d.ts.map +1 -0
  78. package/dist/player/view.js +231 -0
  79. package/dist/player/view.js.map +1 -0
  80. package/dist/runtime.d.ts +45 -0
  81. package/dist/runtime.d.ts.map +1 -0
  82. package/dist/runtime.js +48 -0
  83. package/dist/runtime.js.map +1 -0
  84. package/package.json +45 -3
  85. package/src/a11y.ts +134 -0
  86. package/src/attempt/controller.ts +381 -0
  87. package/src/checker/http.ts +149 -0
  88. package/src/define.ts +114 -0
  89. package/src/element/base.ts +310 -0
  90. package/src/index.ts +18 -0
  91. package/src/interaction/index.ts +11 -0
  92. package/src/interaction/keys.ts +16 -0
  93. package/src/interaction/pick-and-place.ts +464 -0
  94. package/src/interaction/roving-focus.ts +133 -0
  95. package/src/messages/en.json +53 -0
  96. package/src/messages/help/en.json +14 -0
  97. package/src/messages/help/pl.json +14 -0
  98. package/src/messages/pl.json +53 -0
  99. package/src/messages.ts +21 -0
  100. package/src/player/book.ts +70 -0
  101. package/src/player/help.ts +585 -0
  102. package/src/player/player.ts +1368 -0
  103. package/src/player/styled.ts +247 -0
  104. package/src/player/styles.ts +355 -0
  105. package/src/player/templates.ts +142 -0
  106. package/src/player/view.ts +294 -0
  107. package/src/runtime.ts +95 -0
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Base classes for component elements. They implement the parts of PlayerElementApi every element shares, so an
3
+ * component author writes rendering and answer mapping only. Elements also work outside a player: until
4
+ * `attach()` is called they use an English context built from their own catalogs.
5
+ */
6
+ import {
7
+ type Answers,
8
+ type AttributeSpec,
9
+ allAttributes,
10
+ type ChangeDetail,
11
+ type ComponentManifest,
12
+ createI18n,
13
+ type Direction,
14
+ directionOf,
15
+ type ElementContext,
16
+ type ElementFeedback,
17
+ type GroupVerdict,
18
+ type MessageCatalog,
19
+ type MessageParams,
20
+ type PlayerElementApi,
21
+ PlayerEvent,
22
+ type SlotId,
23
+ type SlotVerdict,
24
+ type Solution,
25
+ type Translate,
26
+ type Units,
27
+ } from '@astl/core';
28
+ import { html, LitElement, nothing, type PropertyDeclarations, type TemplateResult } from 'lit';
29
+ import { announce, documentLiveRegion, renderVerdict, type VerdictOptions } from '../a11y.js';
30
+ import { elementTranslator, PLAYER_NAMESPACE, playerMessages } from '../messages.js';
31
+
32
+ function defaultContext(type: typeof AstlElement): ElementContext {
33
+ const i18n = createI18n({ catalogs: [...playerMessages, ...type.messages] });
34
+ return {
35
+ locale: 'en',
36
+ t: elementTranslator(i18n, 'en', type.manifest?.messages ?? PLAYER_NAMESPACE),
37
+ announce: (message) => announce(documentLiveRegion(), message),
38
+ number: 0,
39
+ seed: null,
40
+ };
41
+ }
42
+
43
+ /** 32-bit FNV-1a hash of a string. */
44
+ function hash(value: string): number {
45
+ let h = 0x811c9dc5;
46
+ for (let i = 0; i < value.length; i++) {
47
+ h ^= value.charCodeAt(i);
48
+ h = Math.imul(h, 0x01000193);
49
+ }
50
+ return h >>> 0;
51
+ }
52
+
53
+ /** mulberry32: a small, good-enough PRNG for UI shuffles (not for anything secret). */
54
+ function random(seed: number): () => number {
55
+ let a = seed;
56
+ return () => {
57
+ a = (a + 0x6d2b79f5) | 0;
58
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
59
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
60
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
61
+ };
62
+ }
63
+
64
+ /** Deterministic Fisher-Yates shuffle: the same seed always gives the same order. */
65
+ export function seededShuffle<T>(items: readonly T[], seed: string): T[] {
66
+ const next = random(hash(seed));
67
+ const out = [...items];
68
+ for (let i = out.length - 1; i > 0; i--) {
69
+ const j = Math.floor(next() * (i + 1));
70
+ [out[i], out[j]] = [out[j] as T, out[i] as T];
71
+ }
72
+ return out;
73
+ }
74
+
75
+ export abstract class AstlElement extends LitElement implements PlayerElementApi {
76
+ /** The element type's manifest: drives the typed attribute getters and the default message namespace. */
77
+ static manifest: ComponentManifest | null = null;
78
+ /** Catalogs of the manifest's namespace, used until a player attaches its own context. */
79
+ static messages: readonly MessageCatalog[] = [];
80
+
81
+ static override properties: PropertyDeclarations = {
82
+ feedback: { attribute: false },
83
+ solution: { attribute: false },
84
+ disabled: { type: Boolean },
85
+ };
86
+
87
+ /** Verdicts to show; null clears them. Editing a slot clears its own verdict and the group verdict. */
88
+ declare feedback: ElementFeedback | null;
89
+ /** Correct answers to show next to the student's; null hides them. */
90
+ declare solution: Solution | null;
91
+ declare disabled: boolean;
92
+ #context: ElementContext | null = null;
93
+ /** `t` as a value, for `renderVerdict`. */
94
+ readonly #t: Translate = (key, params) => this.t(key, params);
95
+
96
+ constructor() {
97
+ super();
98
+ this.feedback = null;
99
+ this.solution = null;
100
+ this.disabled = false;
101
+ // A controller runs after every render, before the element's own `updated()`, which need not call super.
102
+ this.addController({ hostUpdated: () => this.#assignSlots() });
103
+ }
104
+
105
+ /**
106
+ * Source content in a player's light DOM (HTML with answers) is input for the compiler and never shown: such
107
+ * elements stay inert, with no shadow root and no render. The player mounts its own copy of the compiled view.
108
+ */
109
+ override connectedCallback(): void {
110
+ if (this.closest('astl-player') !== null) return;
111
+ super.connectedCallback();
112
+ }
113
+
114
+ abstract get slotIds(): readonly SlotId[];
115
+ abstract getAnswers(): Answers;
116
+ abstract setAnswers(answers: Answers): void;
117
+ abstract units(): Units;
118
+
119
+ /** The player's context, or the default English one. */
120
+ get context(): ElementContext {
121
+ this.#context ??= defaultContext(this.constructor as typeof AstlElement);
122
+ return this.#context;
123
+ }
124
+
125
+ attach(context: ElementContext): void {
126
+ this.#context = context;
127
+ this.requestUpdate();
128
+ }
129
+
130
+ /** A message in the UI locale: the element's namespace first, then the shared `astl.player` one. */
131
+ protected t(key: string, params?: MessageParams): string {
132
+ return this.context.t(key, params);
133
+ }
134
+
135
+ protected announce(message: string): void {
136
+ this.context.announce(message);
137
+ }
138
+
139
+ /** UI language and direction (the context locale), for UI strings rendered inside content. */
140
+ protected get uiLanguage(): { readonly lang: string; readonly dir: Direction } {
141
+ const lang = this.context.locale;
142
+ return { lang, dir: directionOf(lang) };
143
+ }
144
+
145
+ /** Content language at this element (closest `lang`), for inputs and spell checking. */
146
+ protected get contentLang(): string {
147
+ return this.closest('[lang]')?.getAttribute('lang') ?? '';
148
+ }
149
+
150
+ /** Reports changed slots (`''` = cleared) to the player and clears their verdicts. */
151
+ protected emitChange(answers: Answers): void {
152
+ const feedback = this.feedback;
153
+ if (feedback) {
154
+ const slots = { ...feedback.slots };
155
+ for (const id of Object.keys(answers)) delete slots[id];
156
+ this.feedback = { slots, group: null };
157
+ }
158
+ this.dispatchEvent(
159
+ new CustomEvent<ChangeDetail>(PlayerEvent.change, {
160
+ detail: { answers },
161
+ bubbles: true,
162
+ composed: true,
163
+ }),
164
+ );
165
+ }
166
+
167
+ protected slotVerdict(id: SlotId): SlotVerdict | null {
168
+ return this.feedback?.slots[id] ?? null;
169
+ }
170
+
171
+ protected get groupVerdict(): GroupVerdict | null {
172
+ return this.feedback?.group ?? null;
173
+ }
174
+
175
+ /** A verdict's icon and word (`renderVerdict`) in the UI language, as part `verdict`; nothing without a verdict. */
176
+ protected renderVerdict(
177
+ verdict: GroupVerdict | null,
178
+ options: VerdictOptions = {},
179
+ ): TemplateResult | typeof nothing {
180
+ return verdict === null
181
+ ? nothing
182
+ : renderVerdict(verdict, this.#t, { part: 'verdict', ...this.uiLanguage, ...options });
183
+ }
184
+
185
+ /** The group verdict line of a block (`p.group-verdict`, part `verdict`); nothing without a verdict. */
186
+ protected renderGroupVerdict(
187
+ verdict: GroupVerdict | null = this.groupVerdict,
188
+ ): TemplateResult | typeof nothing {
189
+ return verdict === null
190
+ ? nothing
191
+ : html`<p class="group-verdict" part="verdict" data-verdict=${verdict}>
192
+ ${renderVerdict(verdict, this.#t, this.uiLanguage)}
193
+ </p>`;
194
+ }
195
+
196
+ /** The light-DOM children with this tag and an id, in view order. */
197
+ protected childElements(tag: string): HTMLElement[] {
198
+ return Array.from(this.children).filter(
199
+ (child): child is HTMLElement => child.localName === tag && child.id !== '',
200
+ );
201
+ }
202
+
203
+ /**
204
+ * Manual slot assignment (a shadow root with `slotAssignment: 'manual'`): the light DOM is projected as it is, never
205
+ * moved or rewritten. `<slot data-tag="astl-prompt">` shows the first child with that tag; any other
206
+ * `<slot data-<name>="<id>">` (`data-option`, `data-card`) the child with that id (child ids are unique in an element).
207
+ */
208
+ #assignSlots(): void {
209
+ const root = this.shadowRoot;
210
+ if (root?.slotAssignment !== 'manual') return;
211
+ const children = Array.from(this.children);
212
+ for (const slot of root.querySelectorAll('slot')) {
213
+ const { tag, ...named } = slot.dataset;
214
+ const [id] = Object.values(named);
215
+ const child = children.find((c) =>
216
+ tag === undefined ? id !== '' && c.id === id : c.localName === tag,
217
+ );
218
+ slot.assign(...(child === undefined ? [] : [child]));
219
+ }
220
+ }
221
+
222
+ /** `items` in view order, or shuffled per attempt when the context has a seed (stable per seed and id). */
223
+ protected shuffled<T>(items: readonly T[]): readonly T[] {
224
+ const seed = this.context.seed;
225
+ return seed === null ? items : seededShuffle(items, `${seed}:${this.id}`);
226
+ }
227
+
228
+ protected attributeSpec(name: string): AttributeSpec | undefined {
229
+ const manifest = (this.constructor as typeof AstlElement).manifest;
230
+ return manifest ? allAttributes(manifest).find((a) => a.name === name) : undefined;
231
+ }
232
+
233
+ /** A string, id or enum attribute; enum values outside the manifest's list give the default. */
234
+ protected stringAttribute(name: string): string | null {
235
+ const spec = this.attributeSpec(name);
236
+ const value = this.getAttribute(name);
237
+ const fallback = spec?.default === undefined ? null : String(spec.default);
238
+ if (value === null) return fallback;
239
+ if (spec?.type === 'enum' && !(spec.values ?? []).includes(value)) return fallback;
240
+ return value;
241
+ }
242
+
243
+ /** An integer or number attribute within the manifest's bounds, else the default (or null). */
244
+ protected numberAttribute(name: string): number | null {
245
+ const spec = this.attributeSpec(name);
246
+ const fallback = typeof spec?.default === 'number' ? spec.default : null;
247
+ const raw = this.getAttribute(name);
248
+ if (raw === null || raw.trim() === '') return fallback;
249
+ const value = Number(raw);
250
+ if (!Number.isFinite(value) || (spec?.type === 'integer' && !Number.isInteger(value))) return fallback;
251
+ if ((spec?.min !== undefined && value < spec.min) || (spec?.max !== undefined && value > spec.max)) {
252
+ return fallback;
253
+ }
254
+ return value;
255
+ }
256
+
257
+ /** An HTML boolean attribute: present = true. */
258
+ protected booleanAttribute(name: string): boolean {
259
+ return this.hasAttribute(name);
260
+ }
261
+ }
262
+
263
+ /** An element with exactly one slot whose id is the element id (a gap, a single choice, a slider). */
264
+ export abstract class SingleSlotElement extends AstlElement {
265
+ static override properties: PropertyDeclarations = {
266
+ value: { state: true },
267
+ };
268
+
269
+ /** The current answer; `''` = unanswered. */
270
+ declare protected value: string;
271
+
272
+ constructor() {
273
+ super();
274
+ this.value = '';
275
+ }
276
+
277
+ get slotIds(): readonly SlotId[] {
278
+ return this.id === '' ? [] : [this.id];
279
+ }
280
+
281
+ getAnswers(): Answers {
282
+ return this.id === '' || this.value === '' ? {} : { [this.id]: this.value };
283
+ }
284
+
285
+ setAnswers(answers: Answers): void {
286
+ const value = answers[this.id];
287
+ if (value !== undefined) this.value = value;
288
+ }
289
+
290
+ units(): Units {
291
+ return { answered: this.value.trim() === '' ? 0 : 1, total: 1 };
292
+ }
293
+
294
+ /** Sets the answer from student input and reports it. */
295
+ protected updateValue(value: string): void {
296
+ if (value === this.value) return;
297
+ this.value = value;
298
+ this.emitChange({ [this.id]: value });
299
+ }
300
+
301
+ /** The slot verdict, else the group verdict (e.g. `empty`). */
302
+ protected get verdict(): GroupVerdict | null {
303
+ return this.slotVerdict(this.id) ?? this.groupVerdict;
304
+ }
305
+
306
+ /** The correct answer for this slot, when shown. */
307
+ protected get solutionValue(): string | null {
308
+ return this.solution?.[this.id] ?? null;
309
+ }
310
+ }
package/src/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ export type { Verdict, VerdictOptions } from './a11y.js';
2
+ export { announce, renderVerdict, verdictIcon, verdictStyles, visuallyHidden } from './a11y.js';
3
+ export type {
4
+ AttemptChange,
5
+ AttemptControllerOptions,
6
+ AttemptListener,
7
+ AttemptPage,
8
+ } from './attempt/controller.js';
9
+ export { AttemptController } from './attempt/controller.js';
10
+ export type { HttpCheckerOptions } from './checker/http.js';
11
+ export { httpChecker } from './checker/http.js';
12
+ export type { DefinePlayerOptions } from './define.js';
13
+ export { definePlayer } from './define.js';
14
+ export { AstlElement, SingleSlotElement, seededShuffle } from './element/base.js';
15
+ export { PLAYER_NAMESPACE, playerMessages } from './messages.js';
16
+ export type { LoadInput } from './player/player.js';
17
+ export { AstlPlayer } from './player/player.js';
18
+ export type { ElementEntry, ElementRegistration, LazyElement } from './runtime.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@astl/player/interaction`: Lit reactive controllers for component elements that move things (pick and place)
3
+ * or move a roving focus, with keyboard, tap and tap, pointer, touch and announcements done once. A subpath of its
4
+ * own, not the main entry: bundles load it with the element chunks that use it, never with the player.
5
+ */
6
+ export type { Axis } from './keys.js';
7
+ export { arrowDelta } from './keys.js';
8
+ export type { PickAndPlaceHost, PickAndPlaceOptions, PickMoment } from './pick-and-place.js';
9
+ export { DRAG_THRESHOLD, PickAndPlace } from './pick-and-place.js';
10
+ export type { RovingFocusOptions } from './roving-focus.js';
11
+ export { RovingFocus } from './roving-focus.js';
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Arrow keys that move: Up and Down (`block`), Left and Right (`inline`, in the writing direction) or all four
3
+ * (`both`, for destinations laid out in two dimensions).
4
+ */
5
+ export type Axis = 'block' | 'inline' | 'both';
6
+
7
+ /**
8
+ * The step an arrow key makes along `axis`: 1 forward (Down, or Right in left-to-right text), -1 back, 0 for any other
9
+ * key. Left and Right swap when `host` is laid out right to left, so the next item is always the one read next.
10
+ */
11
+ export function arrowDelta(event: KeyboardEvent, axis: Axis, host: Element): -1 | 0 | 1 {
12
+ const key = event.key;
13
+ if (axis !== 'inline' && (key === 'ArrowDown' || key === 'ArrowUp')) return key === 'ArrowDown' ? 1 : -1;
14
+ if (axis === 'block' || (key !== 'ArrowRight' && key !== 'ArrowLeft')) return 0;
15
+ return (key === 'ArrowRight') === (getComputedStyle(host).direction !== 'rtl') ? 1 : -1;
16
+ }