@intellectif/lk-react 5.0.0 → 6.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 (94) hide show
  1. package/CHANGELOG.md +330 -0
  2. package/README.md +43 -12
  3. package/dist/{WrittenResponse-DqQ0NjPK.d.cts → WrittenResponse-BXHidIaK.d.cts} +8 -2
  4. package/dist/{WrittenResponse-Dkg7FUt-.d.ts → WrittenResponse-DJYGuMKk.d.ts} +8 -2
  5. package/dist/{chunk-E4MNA2IQ.js → chunk-2TW6WLBC.js} +3 -2
  6. package/dist/chunk-2TW6WLBC.js.map +1 -0
  7. package/dist/chunk-4HZ7LQIH.cjs +1 -0
  8. package/dist/{chunk-3DNJDP73.js → chunk-57E3E2H4.js} +18 -5
  9. package/dist/chunk-57E3E2H4.js.map +1 -0
  10. package/dist/chunk-6F4X2NKL.js +1 -0
  11. package/dist/{chunk-5HVUKXF3.js → chunk-6N43WDVG.js} +7 -6
  12. package/dist/chunk-6N43WDVG.js.map +1 -0
  13. package/dist/{chunk-CPF2JJG6.cjs → chunk-AMGK7DDM.cjs} +32 -2
  14. package/dist/chunk-AMGK7DDM.cjs.map +1 -0
  15. package/dist/{chunk-WCVD5LVG.cjs → chunk-BE7R2X3S.cjs} +18 -6
  16. package/dist/chunk-BE7R2X3S.cjs.map +1 -0
  17. package/dist/{chunk-B3FUUKZ2.js → chunk-DQNVAXG6.js} +32 -3
  18. package/dist/chunk-DQNVAXG6.js.map +1 -0
  19. package/dist/{chunk-3B4ACY4K.cjs → chunk-DUIWK272.cjs} +64 -10
  20. package/dist/chunk-DUIWK272.cjs.map +1 -0
  21. package/dist/chunk-GB5URWM4.js +1 -0
  22. package/dist/{chunk-NBFTCGQ5.js → chunk-IUODGQXE.js} +62 -8
  23. package/dist/chunk-IUODGQXE.js.map +1 -0
  24. package/dist/{chunk-6COTYW77.cjs → chunk-MDYKYDRN.cjs} +18 -5
  25. package/dist/chunk-MDYKYDRN.cjs.map +1 -0
  26. package/dist/{chunk-67WDTQMG.js → chunk-MDZMKC27.js} +18 -5
  27. package/dist/chunk-MDZMKC27.js.map +1 -0
  28. package/dist/chunk-NEWGUDA5.cjs +1 -0
  29. package/dist/{chunk-67RIIDZX.cjs → chunk-NPY2F7F6.cjs} +18 -5
  30. package/dist/chunk-NPY2F7F6.cjs.map +1 -0
  31. package/dist/chunk-PGEG7UZJ.cjs +1 -0
  32. package/dist/{chunk-IYLQSNLE.cjs → chunk-PNNUPUH4.cjs} +3 -2
  33. package/dist/chunk-PNNUPUH4.cjs.map +1 -0
  34. package/dist/chunk-UQ3BBEIT.js +1 -0
  35. package/dist/{chunk-HD2AIQRD.cjs → chunk-XOR4MPEN.cjs} +7 -6
  36. package/dist/chunk-XOR4MPEN.cjs.map +1 -0
  37. package/dist/{chunk-5SYL5CJ2.js → chunk-ZLUMUJUQ.js} +18 -6
  38. package/dist/chunk-ZLUMUJUQ.js.map +1 -0
  39. package/dist/components/ActivitySequence.cjs +7 -6
  40. package/dist/components/ActivitySequence.d.cts +66 -12
  41. package/dist/components/ActivitySequence.d.ts +66 -12
  42. package/dist/components/ActivitySequence.js +6 -5
  43. package/dist/components/FillInTheBlanks.cjs +4 -3
  44. package/dist/components/FillInTheBlanks.d.cts +1 -1
  45. package/dist/components/FillInTheBlanks.d.ts +1 -1
  46. package/dist/components/FillInTheBlanks.js +3 -2
  47. package/dist/components/MultipleChoice.cjs +4 -3
  48. package/dist/components/MultipleChoice.d.cts +2 -2
  49. package/dist/components/MultipleChoice.d.ts +2 -2
  50. package/dist/components/MultipleChoice.js +3 -2
  51. package/dist/components/StimulusPanel.cjs +1 -0
  52. package/dist/components/StimulusPanel.d.cts +1 -1
  53. package/dist/components/StimulusPanel.d.ts +1 -1
  54. package/dist/components/StimulusPanel.js +1 -0
  55. package/dist/components/WrittenResponse.cjs +4 -3
  56. package/dist/components/WrittenResponse.d.cts +3 -3
  57. package/dist/components/WrittenResponse.d.ts +3 -3
  58. package/dist/components/WrittenResponse.js +3 -2
  59. package/dist/hooks/useActivityState.cjs +3 -2
  60. package/dist/hooks/useActivityState.d.cts +10 -3
  61. package/dist/hooks/useActivityState.d.ts +10 -3
  62. package/dist/hooks/useActivityState.js +2 -1
  63. package/dist/hooks/useXAPI.cjs +3 -2
  64. package/dist/hooks/useXAPI.d.cts +31 -0
  65. package/dist/hooks/useXAPI.d.ts +31 -0
  66. package/dist/hooks/useXAPI.js +2 -1
  67. package/dist/index.cjs +22 -17
  68. package/dist/index.cjs.map +1 -1
  69. package/dist/index.d.cts +3 -3
  70. package/dist/index.d.ts +3 -3
  71. package/dist/index.js +8 -7
  72. package/dist/index.js.map +1 -1
  73. package/dist/theme/ThemeProvider.cjs +10 -5
  74. package/dist/theme/ThemeProvider.d.cts +21 -1
  75. package/dist/theme/ThemeProvider.d.ts +21 -1
  76. package/dist/theme/ThemeProvider.js +2 -1
  77. package/dist/theme/skin.css +7 -7
  78. package/dist/{types-CrURyd9-.d.cts → types-9iS1Vs2I.d.cts} +38 -13
  79. package/dist/{types-CrURyd9-.d.ts → types-9iS1Vs2I.d.ts} +38 -13
  80. package/package.json +28 -5
  81. package/dist/chunk-3B4ACY4K.cjs.map +0 -1
  82. package/dist/chunk-3DNJDP73.js.map +0 -1
  83. package/dist/chunk-5HVUKXF3.js.map +0 -1
  84. package/dist/chunk-5SYL5CJ2.js.map +0 -1
  85. package/dist/chunk-67RIIDZX.cjs.map +0 -1
  86. package/dist/chunk-67WDTQMG.js.map +0 -1
  87. package/dist/chunk-6COTYW77.cjs.map +0 -1
  88. package/dist/chunk-B3FUUKZ2.js.map +0 -1
  89. package/dist/chunk-CPF2JJG6.cjs.map +0 -1
  90. package/dist/chunk-E4MNA2IQ.js.map +0 -1
  91. package/dist/chunk-HD2AIQRD.cjs.map +0 -1
  92. package/dist/chunk-IYLQSNLE.cjs.map +0 -1
  93. package/dist/chunk-NBFTCGQ5.js.map +0 -1
  94. package/dist/chunk-WCVD5LVG.cjs.map +0 -1
@@ -1,8 +1,9 @@
1
+ 'use client';
1
2
  'use strict';
2
3
 
3
4
  var chunkPGEG7UZJ_cjs = require('./chunk-PGEG7UZJ.cjs');
4
5
  var chunk4HZ7LQIH_cjs = require('./chunk-4HZ7LQIH.cjs');
5
- var chunkHD2AIQRD_cjs = require('./chunk-HD2AIQRD.cjs');
6
+ var chunkXOR4MPEN_cjs = require('./chunk-XOR4MPEN.cjs');
6
7
  var lkCore = require('@intellectif/lk-core');
7
8
  var react = require('react');
8
9
  var jsxRuntime = require('react/jsx-runtime');
@@ -50,6 +51,7 @@ function FillInTheBlanks({
50
51
  onInteraction,
51
52
  value,
52
53
  defaultValue,
54
+ defaultSubmitted,
53
55
  renderMode = "practice",
54
56
  outcome,
55
57
  sanitizeHtml,
@@ -75,7 +77,9 @@ function FillInTheBlanks({
75
77
  const result2 = lkCore.validateActivity("fill-in-the-blanks", data);
76
78
  return result2.success ? null : new lkCore.ActivitySchemaError("fill-in-the-blanks", result2.errors);
77
79
  }, [data]);
78
- const { state, start, complete, getTimeSpent, reset } = chunkHD2AIQRD_cjs.useActivityState();
80
+ const { state, start, complete, getTimeSpent, reset } = chunkXOR4MPEN_cjs.useActivityState(
81
+ defaultSubmitted === true ? "completed" : "idle"
82
+ );
79
83
  const isControlled = value !== void 0;
80
84
  const [internalAnswers, setInternalAnswers] = react.useState(
81
85
  () => answersOf(defaultValue)
@@ -89,13 +93,22 @@ function FillInTheBlanks({
89
93
  react.useEffect(() => {
90
94
  defaultValueRef.current = defaultValue;
91
95
  }, [defaultValue]);
96
+ const defaultSubmittedRef = react.useRef(defaultSubmitted);
97
+ react.useEffect(() => {
98
+ defaultSubmittedRef.current = defaultSubmitted;
99
+ }, [defaultSubmitted]);
100
+ const lastDataRef = react.useRef(data);
92
101
  react.useEffect(() => {
102
+ if (lastDataRef.current === data) {
103
+ return;
104
+ }
105
+ lastDataRef.current = data;
93
106
  setInternalAnswers(answersOf(defaultValueRef.current));
94
107
  setRevealed(/* @__PURE__ */ new Set());
95
108
  setResult(null);
96
109
  setSummary(null);
97
110
  setFeedbackHidden(false);
98
- reset();
111
+ reset(defaultSubmittedRef.current === true ? "completed" : "idle");
99
112
  }, [data, reset]);
100
113
  react.useEffect(() => {
101
114
  if (chunkPGEG7UZJ_cjs.isDevelopment() && sanitizeHtml !== void 0 && data.passageHtml !== void 0) {
@@ -321,5 +334,5 @@ function FillInTheBlanks2(props) {
321
334
  }
322
335
 
323
336
  exports.FillInTheBlanks = FillInTheBlanks2;
324
- //# sourceMappingURL=chunk-67RIIDZX.cjs.map
325
- //# sourceMappingURL=chunk-67RIIDZX.cjs.map
337
+ //# sourceMappingURL=chunk-NPY2F7F6.cjs.map
338
+ //# sourceMappingURL=chunk-NPY2F7F6.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/FillInTheBlanks/FillInTheBlanks.tsx","../src/components/FillInTheBlanks/index.tsx"],"names":["useMemo","isDevelopment","assertRedacted","result","validateActivity","ActivitySchemaError","useActivityState","useState","useRef","useEffect","score","xAPIBuilder","ANONYMOUS_ACTOR","objectIdFor","xapiDefinitionFor","jsxs","jsx","ActivityMedia","Fragment","FeedbackRegion","FillInTheBlanks","ActivityErrorBoundary"],"mappings":";;;;;;;;;AAqCA,IAAM,WAAA,GAAc,0BAAA;AAIpB,SAAS,aAAa,OAAA,EAA4B;AAChD,EAAA,MAAM,WAAsB,EAAC;AAC7B,EAAA,MAAM,EAAA,GAAK,IAAI,MAAA,CAAO,WAAW,CAAA;AACjC,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,IAAI,OAAA,GAAU,CAAA;AACd,EAAA,IAAI,KAAA,GAAQ,EAAA,CAAG,IAAA,CAAK,OAAO,CAAA;AAC3B,EAAA,OAAO,UAAU,IAAA,EAAM;AACrB,IAAA,IAAI,KAAA,CAAM,QAAQ,IAAA,EAAM;AACtB,MAAA,QAAA,CAAS,IAAA,CAAK,EAAE,IAAA,EAAM,MAAA,EAAQ,KAAA,EAAO,OAA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,CAAC,CAAA,EACH,CAAA;AAAA,UAEC,QAAA,GAAW,IAAA,mBACVA,cAAA,CAAC,QAAA,EAAA,EAAO,IAAA,EAAK,UAAS,QAAA,EAAU,QAAA,EAC7B,QAAA,EAAA,MAAA,GAAS,gBAAA,GAAmB,eAAA,EAC/B;AAAA,SAAA,EAEJ,CAAA;AAAA,QACC,SAAA,IAAa,KAAK,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,QAAQ,CAAA,mBAC9CA,cAAA;AAAA,UAAC,QAAA;AAAA,UAAA;AAAA,YACC,IAAA,EAAK,QAAA;AAAA,YACL,SAAA,EAAU,wBAAA;AAAA,YACV,iBAAe,CAAC,cAAA;AAAA,YAChB,SAAS,MAAM,iBAAA,CAAkB,CAAC,CAAA,KAAM,CAAC,CAAC,CAAA;AAAA,YAEzC,2BAAiB,eAAA,GAAkB;AAAA;AAAA,SACtC,GACE,IAAA;AAAA,wBACJA,cAAA,CAACG,oCAAe,EAAA,EAAI,CAAA,EAAG,KAAK,EAAE,CAAA,SAAA,CAAA,EAC3B,QAAA,EAAA,QAAA,GAAW,aAAA,GAAgB,OAAA,EAC9B;AAAA;AAAA;AAAA,GACF;AAEJ;ACngBO,SAASC,iBAAgB,KAAA,EAA6B;AAC3D,EAAA,uBACEJ,cAAAA,CAACK,uCAAA,EAAA,EAAsB,aAAA,EAAe,KAAA,CAAM,IAAA,EAAM,KAAA,EAChD,QAAA,kBAAAL,cAAAA,CAAC,eAAA,EAAA,EAAqB,GAAG,KAAA,EAAO,CAAA,EAClC,CAAA;AAEJ","file":"chunk-NPY2F7F6.cjs","sourcesContent":["'use client';\n\nimport {\n ActivitySchemaError,\n assertRedacted,\n type FillInTheBlanksData,\n type FillInTheBlanksLearnerResponse,\n type LearnerResponse,\n type ScoringDetail,\n type ScoringResult,\n score,\n validateActivity,\n xAPIBuilder,\n xapiDefinitionFor,\n} from '@intellectif/lk-core';\nimport { type CSSProperties, useEffect, useMemo, useRef, useState } from 'react';\nimport { useActivityState } from '../../hooks/useActivityState.js';\nimport { ANONYMOUS_ACTOR, isDevelopment, objectIdFor } from '../_internal.js';\nimport { ActivityMedia } from '../shared/ActivityMedia.js';\nimport { FeedbackRegion } from '../shared/FeedbackRegion.js';\nimport type { ActivityProps } from '../types.js';\n\nexport interface FillInTheBlanksProps extends ActivityProps<FillInTheBlanksData> {\n /**\n * After submission, replace each incorrectly-answered blank with its first\n * accepted answer, styled distinctly (Req 5.7). Component-specific prop: it\n * is presentation, not activity data, and is outside the fixed Req-3.1 set.\n *\n * Ignored in `exam` mode — revealing the key is precisely what an exam must\n * not do, and on a `redact()` projection there is no key to reveal. In\n * `review` mode it applies only to blanks the supplied `outcome` marks\n * incorrect, and only when the caller passed data that still carries the key\n * (e.g. `redact(data, { reveal: 'after-submit' })`).\n */\n showCorrectAnswers?: boolean;\n}\n\nconst PLACEHOLDER = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\ntype Segment = { kind: 'text'; value: string } | { kind: 'blank'; id: string; ordinal: number };\n\nfunction parsePassage(passage: string): Segment[] {\n const segments: Segment[] = [];\n const re = new RegExp(PLACEHOLDER);\n let last = 0;\n let ordinal = 0;\n let match = re.exec(passage);\n while (match !== null) {\n if (match.index > last) {\n segments.push({ kind: 'text', value: passage.slice(last, match.index) });\n }\n ordinal += 1;\n segments.push({ kind: 'blank', id: match[1] as string, ordinal });\n last = match.index + match[0].length;\n match = re.exec(passage);\n }\n if (last < passage.length) {\n segments.push({ kind: 'text', value: passage.slice(last) });\n }\n return segments;\n}\n\n/** Shared empty map: keeps the \"no response supplied\" path allocation-free. */\nconst NO_ANSWERS: Record<string, string> = {};\n\n/**\n * Reads the answer map out of a `LearnerResponse`. A response of another\n * activity type is treated as \"no answers\" rather than throwing: a controlled\n * host that has not yet swapped its state on an activity change would\n * otherwise crash the attempt.\n */\nfunction answersOf(response: LearnerResponse | undefined): Record<string, string> {\n return response !== undefined && response.type === 'fill-in-the-blanks'\n ? response.answers\n : NO_ANSWERS;\n}\n\n/**\n * Per-item correctness keyed by blank id. Prefers the unambiguous `outcome`\n * field (always written by the built-in scorers since lk-core 0.3.0) and\n * falls back to the deprecated `correct` boolean so a 0.2-era\n * consumer-constructed `ItemOutcome` still marks correctly in `review`.\n */\nfunction correctnessByItem(details: readonly ScoringDetail[]): Map<string, boolean> {\n const map = new Map<string, boolean>();\n for (const detail of details) {\n map.set(\n detail.itemId,\n detail.outcome !== undefined ? detail.outcome === 'correct' : detail.correct,\n );\n }\n return map;\n}\n\nexport function FillInTheBlanks({\n data,\n onComplete,\n onSubmit,\n onChange,\n onInteraction,\n value,\n defaultValue,\n defaultSubmitted,\n renderMode = 'practice',\n outcome,\n sanitizeHtml,\n theme,\n locale,\n disabled,\n showCorrectAnswers,\n}: FillInTheBlanksProps) {\n const isExam = renderMode === 'exam';\n const isReview = renderMode === 'review';\n\n // Dev-only boundary validation (Req 2.3); throws in render so the wrapping\n // ActivityErrorBoundary catches it. Re-runs only when data changes.\n const devError = useMemo(() => {\n if (!isDevelopment()) {\n return null;\n }\n if (data.redacted === true) {\n // A redact() projection cannot satisfy the full content schema — the\n // answer key is gone by design. Validate it against the STRICT redacted\n // schema instead, which additionally proves the payload is learner-safe.\n try {\n assertRedacted(data);\n return null;\n } catch (error) {\n return error instanceof Error ? error : new Error(String(error));\n }\n }\n const result = validateActivity('fill-in-the-blanks', data);\n return result.success ? null : new ActivitySchemaError('fill-in-the-blanks', result.errors);\n }, [data]);\n\n const { state, start, complete, getTimeSpent, reset } = useActivityState(\n defaultSubmitted === true ? 'completed' : 'idle',\n );\n // Controlled when `value` is supplied: the answers rendered are ALWAYS the\n // caller's, and internal state is never read. Uncontrolled otherwise,\n // seeded from `defaultValue`.\n const isControlled = value !== undefined;\n const [internalAnswers, setInternalAnswers] = useState<Record<string, string>>(() =>\n answersOf(defaultValue),\n );\n const [revealed, setRevealed] = useState<Set<string>>(() => new Set());\n const [result, setResult] = useState<ScoringResult | null>(null);\n const [summary, setSummary] = useState<string | null>(null);\n const [feedbackHidden, setFeedbackHidden] = useState(false);\n\n const answers = isControlled ? answersOf(value) : internalAnswers;\n\n // `defaultValue` is read only by the reset effect, and it is commonly an\n // inline object literal — putting it in that effect's deps would re-seed\n // (and wipe) the learner's typing on every render. Mirror it into a ref in\n // its own effect, which commits before the reset effect below.\n const defaultValueRef = useRef(defaultValue);\n useEffect(() => {\n defaultValueRef.current = defaultValue;\n }, [defaultValue]);\n\n // Mirror `defaultSubmitted` so the reset below returns to the SEEDED state.\n // Resetting unconditionally to idle unlocked an item the learner had already\n // committed — which made `defaultSubmitted` a no-op here, since this effect\n // runs right after the first paint.\n const defaultSubmittedRef = useRef(defaultSubmitted);\n useEffect(() => {\n defaultSubmittedRef.current = defaultSubmitted;\n }, [defaultSubmitted]);\n\n // Identity guard so the MOUNT run is a no-op. Without it this effect fires\n // after the first paint and undoes every seed it was just given; with it,\n // only a real `data` change resets. A parent that rebuilds structurally\n // identical entries in render (`activities={raw.map(redact)}`) must not\n // unlock or revert a restored answer — the pager already remounts a slot\n // whose activity actually changed, via its key.\n const lastDataRef = useRef(data);\n // `data` is an intentional reset trigger (Req 3.7), not read in the body.\n // biome-ignore lint/correctness/useExhaustiveDependencies: data is the reset trigger (Req 3.7)\n useEffect(() => {\n if (lastDataRef.current === data) {\n return;\n }\n lastDataRef.current = data;\n setInternalAnswers(answersOf(defaultValueRef.current));\n setRevealed(new Set());\n setResult(null);\n setSummary(null);\n setFeedbackHidden(false);\n reset(defaultSubmittedRef.current === true ? 'completed' : 'idle');\n }, [data, reset]);\n\n /*\n * RICH TEXT — deliberate, documented limitation (see `sanitizeHtml`).\n *\n * Every other activity can render its `*Html` field through the caller's\n * sanitiser, because the rich text is a LEAF: the sanitised string is\n * handed to one `dangerouslySetInnerHTML` node and nothing is inserted into\n * it. A fill-in-the-blanks passage is not a leaf — it is the CONTAINER of\n * the React-controlled `<input>`s, one per `{{id}}` placeholder.\n *\n * Placing those inputs inside sanitised HTML means slicing the sanitised\n * string at the placeholders and injecting each slice as its own HTML\n * fragment, which is unsafe and broken on both counts:\n * 1. Broken: the slices are unbalanced. `<p>A {{x}} B</p>` yields `<p>A `\n * and ` B</p>`; the fragment parser auto-closes both, so the input\n * lands OUTSIDE the paragraph and the authored block structure is\n * destroyed.\n * 2. Unsafe: the sanitiser's guarantee covers the document it returned,\n * not arbitrary substrings of it. A placeholder inside an attribute\n * (`<img alt=\"{{x}}\">`) splits mid-attribute, and re-parsing the\n * halves in a fresh context is exactly the mutation (mXSS) class of\n * transformation that voids a sanitiser's output guarantee. An exam\n * runner must never depend on that.\n *\n * The safe alternative — parse the sanitised string once into a detached\n * DOM, split only TEXT nodes at placeholders, and portal the inputs into\n * anchors — needs a DOM at render time (no SSR) and a large imperative\n * subsystem. Until that lands, the plain-text `passage` is rendered (always\n * escaped by React), which is correct, answerable, and safe in every mode.\n * `data.passageHtml` is carried and redacted by lk-core regardless, so no\n * authored content is lost — only this component declines to render it.\n */\n useEffect(() => {\n if (isDevelopment() && sanitizeHtml !== undefined && data.passageHtml !== undefined) {\n console.warn(\n '[lk-react] FillInTheBlanks ignores `passageHtml`: the passage hosts the answer inputs, ' +\n 'so rich HTML cannot be split at {{placeholders}} without voiding the sanitiser. ' +\n 'Rendering the plain `passage` instead.',\n );\n }\n }, [sanitizeHtml, data.passageHtml]);\n\n const segments = useMemo(() => parsePassage(data.passage), [data.passage]);\n const blankById = useMemo(() => new Map(data.blanks.map((b) => [b.id, b])), [data.blanks]);\n\n if (devError) {\n throw devError;\n }\n // Practice grades locally, which a redacted projection cannot support: the\n // submit handler below calls `score()`, which throws RedactedScoringError —\n // from an event handler, where no error boundary can catch it, AFTER the\n // learner has typed their answers. Fail loudly at render instead, in\n // production too. This mirrors the identical guard in MultipleChoice;\n // without it the two built-ins disagreed about the same accident, and\n // wiring an exam item into the self-grading mode is precisely what\n // `renderMode` exists to prevent.\n if (data.redacted === true && renderMode === 'practice') {\n throw new Error(\n `Fill-in-the-Blanks \"${data.id}\" received redacted activity data in renderMode \"practice\", ` +\n 'which grades locally and has no answer key to grade against. ' +\n 'Render redacted data with renderMode=\"exam\" (server grades) or \"review\" (pass `outcome`).',\n );\n }\n\n const submitted = state === 'completed';\n const inactive = disabled === true || submitted || isReview;\n\n /**\n * Whether the component may show answer-key-derived information (per-blank\n * correctness, authored feedback, correct answers). NEVER in `exam`; in\n * `practice` only after the component scored locally; in `review` only once\n * the caller supplies a SCORED outcome — an item that is still awaiting a\n * grade must not have its key revealed just because it is being read back.\n */\n const revealing = isReview ? outcome?.status === 'scored' : !isExam && submitted;\n\n const fireInteraction = (\n type: 'blank-filled' | 'hint-requested' | 'submitted',\n payload: Record<string, unknown>,\n ): void => {\n onInteraction?.({ type, activityId: data.id, timestamp: Date.now(), payload });\n };\n\n const handleChange = (blankId: string, text: string): void => {\n if (inactive) {\n return;\n }\n if (state === 'idle') {\n start();\n }\n const next = { ...answers, [blankId]: text };\n if (!isControlled) {\n setInternalAnswers(next);\n }\n onChange?.({ type: 'fill-in-the-blanks', answers: next });\n fireInteraction('blank-filled', { blankId, value: text });\n };\n\n const toggleHint = (blankId: string): void => {\n if (inactive) {\n return;\n }\n if (state === 'idle') {\n start();\n }\n setRevealed((prev) => {\n const next = new Set(prev);\n if (next.has(blankId)) {\n next.delete(blankId);\n return next;\n }\n next.add(blankId);\n return next;\n });\n // Only a reveal is a \"hint requested\"; hiding is not a new request.\n if (!revealed.has(blankId)) {\n fireInteraction('hint-requested', { blankId });\n }\n };\n\n const handleSubmit = (event: React.FormEvent): void => {\n event.preventDefault();\n if (inactive) {\n return;\n }\n const response: FillInTheBlanksLearnerResponse = { type: 'fill-in-the-blanks', answers };\n // Fires in every submitting mode and always BEFORE onComplete, so an exam\n // runner can persist the raw response regardless of local grading.\n onSubmit?.(response);\n\n if (isExam) {\n // EXAM: the client neither grades nor reveals. No score()/evaluate(), no\n // read of any answer-key field, no onComplete — and no xAPI statement,\n // because its `correctResponsesPattern` IS the answer key. The server\n // owns the grade; it emits the statement.\n complete();\n setSummary('Answer submitted.');\n fireInteraction('submitted', { answers });\n return;\n }\n\n // PRACTICE: unchanged v1 behaviour. `data` carries the key here — exam\n // mode is the only path that may be handed a redact() projection.\n const scoringResult = score('fill-in-the-blanks', data as FillInTheBlanksData, response);\n complete();\n const timeSpent = getTimeSpent();\n const xapiStatement = xAPIBuilder.buildAnsweredStatement({\n actor: ANONYMOUS_ACTOR,\n object: {\n id: objectIdFor(data.id),\n name: { [data.locale ?? 'en-US']: data.title },\n ...xapiDefinitionFor(data),\n },\n scoringResult,\n timeSpentMs: timeSpent,\n response: JSON.stringify(answers),\n });\n setResult(scoringResult);\n onComplete?.({\n score: scoringResult.score,\n maxScore: scoringResult.maxScore,\n passed: scoringResult.passed,\n timeSpent,\n xapiStatement,\n });\n // Core selects the authored overall feedback on `passed` (B3 fix).\n const overall = scoringResult.feedback;\n setSummary(\n `Answer submitted. Score ${Math.round(scoringResult.score * 100)}%. ${\n scoringResult.passed ? 'Passed.' : 'Not passed.'\n }${overall ? ` ${overall}` : ''}`,\n );\n fireInteraction('submitted', { answers, score: scoringResult.score });\n };\n\n const correctByBlank = useMemo(() => {\n if (isExam) {\n // Nothing is ever marked client-side in an exam.\n return new Map<string, boolean>();\n }\n if (isReview) {\n // Correctness comes ONLY from the server-computed outcome; the component\n // never scores in review, so an absent/ungraded outcome marks nothing.\n return outcome?.status === 'scored'\n ? correctnessByItem(outcome.details)\n : new Map<string, boolean>();\n }\n return correctnessByItem(result?.details ?? []);\n }, [isExam, isReview, outcome, result]);\n\n /** Review has no local score: its summary is read off `outcome`, or nothing. */\n const reviewSummary = useMemo(() => {\n if (!isReview || outcome === undefined) {\n return null;\n }\n if (outcome.status === 'scored') {\n return `Score ${Math.round(outcome.score * 100)}%. ${\n outcome.passed ? 'Passed.' : 'Not passed.'\n }${outcome.feedback ? ` ${outcome.feedback}` : ''}`;\n }\n return outcome.status === 'deferred' ? 'Not graded yet.' : 'No grade available.';\n }, [isReview, outcome]);\n\n return (\n <form\n className=\"lk-fib\"\n aria-label={data.title}\n lang={locale}\n data-render-mode={renderMode}\n style={theme as CSSProperties | undefined}\n onSubmit={handleSubmit}\n >\n {data.media ? <ActivityMedia media={data.media} /> : null}\n <fieldset disabled={inactive}>\n <p className=\"lk-fib-passage\">\n {segments.map((seg, i) => {\n if (seg.kind === 'text') {\n // biome-ignore lint/suspicious/noArrayIndexKey: passage segments are positional and static\n return <span key={`t${i}`}>{seg.value}</span>;\n }\n const blank = blankById.get(seg.id);\n if (!blank) {\n return null;\n }\n // `Renderable` only widens `scoringStrategy` at the type level, so\n // the answer-key fields still LOOK required here while a redact()\n // projection omits them at runtime. Read them defensively, and\n // never at all in exam mode.\n const acceptedAnswers: string[] | undefined = isExam\n ? undefined\n : blank.acceptedAnswers;\n const blankFeedback = isExam ? undefined : blank.feedback;\n const correctness = correctByBlank.get(seg.id);\n const hintId = `${data.id}-hint-${seg.id}`;\n const correctAnswer = acceptedAnswers?.[0];\n if (revealing && showCorrectAnswers && correctness === false && correctAnswer) {\n return (\n <span key={seg.id} className=\"lk-fib-answer\" data-correct=\"false\">\n {correctAnswer}\n </span>\n );\n }\n return (\n <span key={seg.id} className=\"lk-fib-blank\">\n <input\n type=\"text\"\n aria-label={`Fill in blank ${seg.ordinal}`}\n aria-describedby={blank.hint ? hintId : undefined}\n value={answers[seg.id] ?? ''}\n disabled={inactive}\n aria-disabled={inactive || undefined}\n data-correct={\n revealing && correctness !== undefined ? String(correctness) : undefined\n }\n onChange={(e) => handleChange(seg.id, e.target.value)}\n />\n {/*\n Hints stay available in exam mode by design: lk-core's field\n policy classifies `blanks.hint` as `public`, so it survives\n redact() and is not part of the answer key.\n */}\n {blank.hint ? (\n <>\n {/*\n Default affordance is an icon; the accessible NAME stays\n text via aria-label (screen readers + tests rely on it).\n The glyph is restylable/replaceable via .lk-fib-hint-btn.\n */}\n <button\n type=\"button\"\n className=\"lk-fib-hint-btn\"\n aria-controls={hintId}\n aria-expanded={revealed.has(seg.id)}\n aria-label={revealed.has(seg.id) ? 'Hide hint' : 'Show hint'}\n disabled={inactive}\n onClick={() => toggleHint(seg.id)}\n >\n <svg\n className=\"lk-fib-hint-icon\"\n viewBox=\"0 0 24 24\"\n width=\"16\"\n height=\"16\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <path\n fill=\"currentColor\"\n d=\"M9 21h6v-1H9v1Zm3-19a7 7 0 0 0-4 12.74V17h8v-2.26A7 7 0 0 0 12 2Z\"\n />\n </svg>\n </button>\n {/*\n Not role=\"tooltip\": a real ARIA tooltip is a named\n hover/focus popup with strict WCAG 1.4.13 constraints.\n This is an accessible click-to-toggle disclosure that is\n the input's aria-describedby target and is announced via\n aria-live; the skin gives it a tooltip-like *visual*\n without the tooltip *semantics*. (Refines Task 15.3.)\n */}\n <span id={hintId} aria-live=\"polite\">\n {revealed.has(seg.id) ? blank.hint : ''}\n </span>\n </>\n ) : null}\n {revealing && !feedbackHidden && blankFeedback ? (\n <span\n className=\"lk-fib-blank-feedback\"\n role=\"note\"\n data-correct={correctness !== undefined ? String(correctness) : undefined}\n >\n {blankFeedback}\n </span>\n ) : null}\n </span>\n );\n })}\n </p>\n {/* Review is read-only: there is nothing to submit. */}\n {isReview ? null : (\n <button type=\"submit\" disabled={inactive}>\n {isExam ? 'Submit answers' : 'Check answers'}\n </button>\n )}\n </fieldset>\n {revealing && data.blanks.some((b) => b.feedback) ? (\n <button\n type=\"button\"\n className=\"lk-fib-feedback-toggle\"\n aria-expanded={!feedbackHidden}\n onClick={() => setFeedbackHidden((h) => !h)}\n >\n {feedbackHidden ? 'Show feedback' : 'Hide feedback'}\n </button>\n ) : null}\n <FeedbackRegion id={`${data.id}-feedback`}>\n {isReview ? reviewSummary : summary}\n </FeedbackRegion>\n </form>\n );\n}\n","'use client';\n\nimport { ActivityErrorBoundary } from '../ActivityErrorBoundary.js';\nimport {\n FillInTheBlanks as FillInTheBlanksCore,\n type FillInTheBlanksProps,\n} from './FillInTheBlanks.js';\n\nexport type { FillInTheBlanksProps } from './FillInTheBlanks.js';\n\n/**\n * Public Fill-in-the-Blanks activity: the core wrapped in\n * `ActivityErrorBoundary` so a render failure (incl. the dev schema-validation\n * throw) degrades to an accessible fallback instead of crashing the host.\n */\nexport function FillInTheBlanks(props: FillInTheBlanksProps) {\n return (\n <ActivityErrorBoundary activityTitle={props.data?.title}>\n <FillInTheBlanksCore {...props} />\n </ActivityErrorBoundary>\n );\n}\n"]}
@@ -1,3 +1,4 @@
1
+ 'use client';
1
2
  'use strict';
2
3
 
3
4
  var react = require('react');
@@ -1,3 +1,4 @@
1
+ 'use client';
1
2
  'use strict';
2
3
 
3
4
  var react = require('react');
@@ -77,5 +78,5 @@ function useXAPI(config) {
77
78
  }
78
79
 
79
80
  exports.useXAPI = useXAPI;
80
- //# sourceMappingURL=chunk-IYLQSNLE.cjs.map
81
- //# sourceMappingURL=chunk-IYLQSNLE.cjs.map
81
+ //# sourceMappingURL=chunk-PNNUPUH4.cjs.map
82
+ //# sourceMappingURL=chunk-PNNUPUH4.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/useXAPI.ts"],"names":["useRef","useCallback"],"mappings":";;;;;AAMA,IAAM,UAAA,GAAa,CAAC,GAAA,EAAM,GAAA,EAAM,GAAI,CAAA;AAYpC,SAAS,aAAA,CAAc,WAA0B,GAAA,EAAgC;AAC/E,EAAA,MAAM,WAAA,GACJ,UAAU,KAAA,EAAO,OAAA,EAAS,SAAS,WAAA,IACnC,SAAA,CAAU,KAAA,CAAM,OAAA,CAAQ,QAAA,KAAa,6CAAA;AACvC,EAAA,MAAM,aAAA,GACJ,SAAA,CAAU,MAAA,EAAQ,UAAA,KAAe,cACjC,OAAO,SAAA,CAAU,MAAA,CAAO,EAAA,KAAO,QAAA,IAC/B,SAAA,CAAU,MAAA,CAAO,EAAA,CAAG,WAAW,4BAA4B,CAAA;AAE7D,EAAA,IAAI,CAAC,WAAA,IAAe,CAAC,aAAA,EAAe;AAClC,IAAA,O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OAAA,GAAU,eAAA;AAAA,MACrD;AAEA,MAAA,IAAI,YAAY,WAAA,EAAa;AAC3B,QAAA,GAAA,CAAI,OAAA,GAAU;AAAA,UACZ,SAAA;AAAA,UACA,OAAA;AAAA,UACA,GAAI,UAAA,KAAe,MAAA,GAAY,EAAE,UAAA,KAAe,EAAC;AAAA,UACjD;AAAA,SACD,CAAA;AACD,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,KAAA,CAAM,UAAA,CAAW,OAAA,GAAU,CAAC,CAAC,CAAA;AAAA,IACrC;AAAA,EACF,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO,EAAE,aAAA,EAAc;AACzB","file":"chunk-PNNUPUH4.cjs","sourcesContent":["'use client';\n\nimport type { XAPIConfig, XAPIStatement } from '@intellectif/lk-core';\nimport { useCallback, useRef } from 'react';\n\n/** Backoff before retry 1 / 2 / 3 (Req 10.4). */\nconst BACKOFF_MS = [1000, 2000, 4000] as const;\n\n/**\n * Applies the configured learner identity to a statement built by an activity\n * component. Components emit an anonymous placeholder actor and a\n * `urn:learning-kit:activity:*` object id (they cannot know identity — Req\n * 3.1); this hook is the documented place where `XAPIConfig.actor` and\n * `XAPIConfig.activityId` take over. Conservative on purpose: the actor is\n * replaced only when the statement still carries the SDK's anonymous\n * placeholder, and the object id only when it is still the SDK URN — a\n * consumer that already rewrote either keeps its own values.\n */\nfunction applyIdentity(statement: XAPIStatement, cfg: XAPIConfig): XAPIStatement {\n const isAnonymous =\n statement.actor?.account?.name === 'anonymous' &&\n statement.actor.account.homePage === 'https://github.com/intellectif/learning-kit';\n const isSdkObjectId =\n statement.object?.objectType === 'Activity' &&\n typeof statement.object.id === 'string' &&\n statement.object.id.startsWith('urn:learning-kit:activity:');\n\n if (!isAnonymous && !isSdkObjectId) {\n return statement;\n }\n const mappedId =\n isSdkObjectId && cfg.activityId\n ? typeof cfg.activityId === 'function'\n ? cfg.activityId(statement.object.id)\n : cfg.activityId\n : undefined;\n return {\n ...statement,\n ...(isAnonymous && cfg.actor !== undefined ? { actor: cfg.actor } : {}),\n ...(mappedId !== undefined ? { object: { ...statement.object, id: mappedId } } : {}),\n };\n}\n\n/** UTF-8-safe base64 (`btoa` is Latin1-only and breaks on non-ASCII creds). */\nfunction toBase64Utf8(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n\nfunction authHeader(auth: XAPIConfig['auth']): string {\n return auth.type === 'basic'\n ? `Basic ${toBase64Utf8(`${auth.username}:${auth.password}`)}`\n : `Bearer ${auth.token}`;\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport interface UseXAPIResult {\n /**\n * Sends a statement to the configured LRS. **Never rejects** — xAPI is\n * fire-and-forget telemetry that must not break the learner's activity\n * flow. Network errors and 5xx responses are retried (backoff 1s/2s/4s,\n * up to 3 retries); a 4xx fails immediately. Any final failure is delivered\n * to `config.onError`.\n */\n sendStatement: (statement: XAPIStatement) => Promise<void>;\n}\n\n/**\n * Delivers xAPI statements to a Learning Record Store, fire-and-forget.\n *\n * Telemetry must never break the learner's attempt, so\n * {@link UseXAPIResult.sendStatement} **never rejects**: network errors and 5xx\n * responses are retried (backoff 1s / 2s / 4s, up to 3 retries), a 4xx fails\n * immediately, and any final failure is reported to `config.onError` instead of\n * throwing. See `XAPIConfig` in `@intellectif/lk-core` for the options.\n *\n * The hook is also where learner identity is applied. Activity components\n * cannot know who the learner is, so they emit an anonymous placeholder actor\n * and a `urn:learning-kit:activity:*` object id; this hook substitutes\n * `config.actor` and `config.activityId` on the way out — and only while those\n * placeholders are still in place, so a statement you rewrote yourself is left\n * alone.\n *\n * `sendStatement` keeps a stable identity across renders even when `config` is\n * an inline object, so it is safe in a dependency array.\n *\n * ```tsx\n * const { sendStatement } = useXAPI({\n * endpoint: 'https://your-lrs.example/xapi/statements',\n * auth: { type: 'bearer', token: 'YOUR_TOKEN' },\n * activityId: 'https://your-app.example/quiz/capital-jp',\n * actor: { objectType: 'Agent', mbox: 'mailto:learner@example.com' },\n * onError: (e) => console.error('xAPI send failed', e),\n * });\n *\n * <MultipleChoice data={quiz} onComplete={(r) => void sendStatement(r.xapiStatement)} />\n * ```\n */\nexport function useXAPI(config: XAPIConfig): UseXAPIResult {\n // Keep the latest config without changing `sendStatement`'s identity when\n // callers pass an inline config object.\n const configRef = useRef(config);\n configRef.current = config;\n\n const sendStatement = useCallback(async (rawStatement: XAPIStatement): Promise<void> => {\n const cfg = configRef.current;\n const statement = applyIdentity(rawStatement, cfg);\n const maxAttempts = 1 + BACKOFF_MS.length;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n let statusCode: number | undefined;\n let message = 'Request failed';\n\n try {\n const response = await fetch(cfg.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Experience-API-Version': '1.0.3',\n Authorization: authHeader(cfg.auth),\n },\n body: JSON.stringify(statement),\n });\n\n if (response.ok) {\n return;\n }\n\n statusCode = response.status;\n message = `LRS responded with ${response.status}`;\n\n // Only network errors and 5xx are retryable (Req 10.4). A 4xx is a\n // client error — fail immediately rather than waste retries.\n if (response.status < 500) {\n cfg.onError?.({ statement, attempt, statusCode, message });\n return;\n }\n } catch (error) {\n message = error instanceof Error ? error.message : 'Network error';\n }\n\n if (attempt === maxAttempts) {\n cfg.onError?.({\n statement,\n attempt,\n ...(statusCode !== undefined ? { statusCode } : {}),\n message,\n });\n return;\n }\n\n await sleep(BACKOFF_MS[attempt - 1]);\n }\n }, []);\n\n return { sendStatement };\n}\n"]}
@@ -1,3 +1,4 @@
1
+ 'use client';
1
2
  import { ActivityMedia } from './chunk-GB5URWM4.js';
2
3
  import { useId, useMemo } from 'react';
3
4
  import { jsxs, jsx } from 'react/jsx-runtime';
@@ -1,10 +1,11 @@
1
+ 'use client';
1
2
  'use strict';
2
3
 
3
4
  var react = require('react');
4
5
 
5
6
  // src/hooks/useActivityState.ts
6
- function useActivityState() {
7
- const [state, setState] = react.useState("idle");
7
+ function useActivityState(initialState = "idle") {
8
+ const [state, setState] = react.useState(initialState);
8
9
  const startTimeRef = react.useRef(null);
9
10
  const start = react.useCallback(() => {
10
11
  if (startTimeRef.current === null) {
@@ -14,9 +15,9 @@ function useActivityState() {
14
15
  }, []);
15
16
  const complete = react.useCallback(() => setState("completed"), []);
16
17
  const review = react.useCallback(() => setState("reviewing"), []);
17
- const reset = react.useCallback(() => {
18
+ const reset = react.useCallback((to = "idle") => {
18
19
  startTimeRef.current = null;
19
- setState("idle");
20
+ setState(to);
20
21
  }, []);
21
22
  const getTimeSpent = react.useCallback(
22
23
  () => startTimeRef.current === null ? 0 : Date.now() - startTimeRef.current,
@@ -26,5 +27,5 @@ function useActivityState() {
26
27
  }
27
28
 
28
29
  exports.useActivityState = useActivityState;
29
- //# sourceMappingURL=chunk-HD2AIQRD.cjs.map
30
- //# sourceMappingURL=chunk-HD2AIQRD.cjs.map
30
+ //# sourceMappingURL=chunk-XOR4MPEN.cjs.map
31
+ //# sourceMappingURL=chunk-XOR4MPEN.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/useActivityState.ts"],"names":["useState","useRef","useCallback"],"mappings":";;;;;AAgCO,SAAS,gBAAA,CAAiB,eAA8B,MAAA,EAAgC;AAM7F,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAIA,eAAwB,YAAY,CAAA;AAC9D,EAAA,MAAM,YAAA,GAAeC,aAAsB,IAAI,CAAA;AAE/C,EAAA,MAAM,KAAA,GAAQC,kBAAY,MAAM;AAG9B,IAAA,IAAI,YAAA,CAAa,YAAY,IAAA,EAAM;AACjC,MAAA,YAAA,CAAa,OAAA,GAAU,KAAK,GAAA,EAAI;AAAA,IAClC;AACA,IAAA,QAAA,CAAS,CAAC,IAAA,KAAU,IAAA,KAAS,MAAA,GAAS,gBAAgB,IAAK,CAAA;AAAA,EAC7D,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,MAAM,WAAWA,iBAAA,CAAY,MAAM,SAAS,WAAW,CAAA,EAAG,EAAE,CAAA;AAE5D,EAAA,MAAM,SAASA,iBAAA,CAAY,MAAM,SAAS,WAAW,CAAA,EAAG,EAAE,CAAA;AAE1D,EAAA,MAAM,KAAA,GAAQA,iBAAA,CAAY,CAAC,EAAA,GAAoB,MAAA,KAAW;AACxD,IAAA,YAAA,CAAa,OAAA,GAAU,IAAA;AACvB,IAAA,QAAA,CAAS,EAAE,CAAA;AAAA,EACb,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,MAAM,YAAA,GAAeA,iBAAA;AAAA,IACnB,MAAO,aAAa,OAAA,KAAY,IAAA,GAAO,IAAI,IAAA,CAAK,GAAA,KAAQ,YAAA,CAAa,OAAA;AAAA,IACrE;AAAC,GACH;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,QAAA,EAAU,MAAA,EAAQ,OAAO,YAAA,EAAa;AAC/D","file":"chunk-XOR4MPEN.cjs","sourcesContent":["'use client';\n\nimport { useCallback, useRef, useState } from 'react';\n\nexport type ActivityState = 'idle' | 'in-progress' | 'completed' | 'reviewing';\n\nexport interface UseActivityStateResult {\n state: ActivityState;\n /** idle → in-progress; records start time once. Idempotent: repeated calls\n * (e.g. every learner interaction) neither restart timing nor regress state. */\n start: () => void;\n /** → completed. */\n complete: () => void;\n /** → reviewing (e.g. when showing correct answers). */\n review: () => void;\n /**\n * Clears timing and returns to `to`, defaulting to `idle`. Call when the\n * activity `data` prop changes.\n *\n * The target is a parameter because \"reset\" for a RESTORED item does not\n * mean idle: an item the learner had already submitted must come back\n * submitted, or a data-prop change quietly unlocks committed work.\n */\n reset: (to?: ActivityState) => void;\n /** Elapsed ms since `start()`; 0 when not started (or after `reset()`). */\n getTimeSpent: () => number;\n}\n\n/**\n * Tracks an activity's lifecycle state and elapsed time. Timing is held in a\n * ref (no re-render) and `getTimeSpent()` is read imperatively at submission.\n */\nexport function useActivityState(initialState: ActivityState = 'idle'): UseActivityStateResult {\n // `initialState` seeds the MOUNT only, like any `default*` value. It exists\n // so a resumed attempt can reopen a question the learner had already\n // submitted as submitted — without it, an exam that locks each question on\n // submit silently unlocks every one of them after a crash, and the learner\n // can answer and submit the same question twice.\n const [state, setState] = useState<ActivityState>(initialState);\n const startTimeRef = useRef<number | null>(null);\n\n const start = useCallback(() => {\n // Ref guard makes timing idempotent without a side effect in the updater\n // (StrictMode double-invokes updaters); the updater itself stays pure.\n if (startTimeRef.current === null) {\n startTimeRef.current = Date.now();\n }\n setState((prev) => (prev === 'idle' ? 'in-progress' : prev));\n }, []);\n\n const complete = useCallback(() => setState('completed'), []);\n\n const review = useCallback(() => setState('reviewing'), []);\n\n const reset = useCallback((to: ActivityState = 'idle') => {\n startTimeRef.current = null;\n setState(to);\n }, []);\n\n const getTimeSpent = useCallback(\n () => (startTimeRef.current === null ? 0 : Date.now() - startTimeRef.current),\n [],\n );\n\n return { state, start, complete, review, reset, getTimeSpent };\n}\n"]}
@@ -1,6 +1,7 @@
1
+ 'use client';
1
2
  import { ActivityErrorBoundary, isDevelopment, randomSessionId, FeedbackRegion, ANONYMOUS_ACTOR, objectIdFor } from './chunk-6F4X2NKL.js';
2
3
  import { ActivityMedia } from './chunk-GB5URWM4.js';
3
- import { useActivityState } from './chunk-5HVUKXF3.js';
4
+ import { useActivityState } from './chunk-6N43WDVG.js';
4
5
  import { validateActivity, ActivitySchemaError, seededShuffle, score, xAPIBuilder, xapiDefinitionFor } from '@intellectif/lk-core';
5
6
  import { useMemo, useRef, useState, useEffect } from 'react';
6
7
  import { jsx, jsxs } from 'react/jsx-runtime';
@@ -39,6 +40,7 @@ function MultipleChoice({
39
40
  onSubmit,
40
41
  value,
41
42
  defaultValue,
43
+ defaultSubmitted,
42
44
  onChange,
43
45
  renderMode = "practice",
44
46
  outcome,
@@ -60,20 +62,30 @@ function MultipleChoice({
60
62
  return result.success ? null : new ActivitySchemaError("multiple-choice", result.errors);
61
63
  }, [data]);
62
64
  const sessionIdRef = useRef(null);
63
- const { state, start, complete, getTimeSpent, reset } = useActivityState();
65
+ const { state, start, complete, getTimeSpent, reset } = useActivityState(
66
+ defaultSubmitted === true ? "completed" : "idle"
67
+ );
64
68
  const [internalSelection, setInternalSelection] = useState(
65
69
  () => selectionOf(defaultValue)
66
70
  );
67
71
  const [summary, setSummary] = useState(null);
72
+ const defaultValueRef = useRef(defaultValue);
73
+ useEffect(() => {
74
+ defaultValueRef.current = defaultValue;
75
+ }, [defaultValue]);
76
+ const defaultSubmittedRef = useRef(defaultSubmitted);
77
+ useEffect(() => {
78
+ defaultSubmittedRef.current = defaultSubmitted;
79
+ }, [defaultSubmitted]);
68
80
  const lastDataRef = useRef(data);
69
81
  useEffect(() => {
70
82
  if (lastDataRef.current === data) {
71
83
  return;
72
84
  }
73
85
  lastDataRef.current = data;
74
- setInternalSelection([]);
86
+ setInternalSelection(selectionOf(defaultValueRef.current));
75
87
  setSummary(null);
76
- reset();
88
+ reset(defaultSubmittedRef.current === true ? "completed" : "idle");
77
89
  }, [data, reset]);
78
90
  const displayedOptions = useMemo(() => {
79
91
  if (!data.shuffle) {
@@ -235,5 +247,5 @@ function MultipleChoice2(props) {
235
247
  }
236
248
 
237
249
  export { MultipleChoice2 as MultipleChoice };
238
- //# sourceMappingURL=chunk-5SYL5CJ2.js.map
239
- //# sourceMappingURL=chunk-5SYL5CJ2.js.map
250
+ //# sourceMappingURL=chunk-ZLUMUJUQ.js.map
251
+ //# sourceMappingURL=chunk-ZLUMUJUQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/MultipleChoice/MultipleChoice.tsx","../src/components/MultipleChoice/index.tsx"],"names":["MultipleChoice","jsx"],"mappings":";;;;;;;AA4BA,SAAS,YAAY,QAAA,EAAiD;AACpE,EAAA,OAAO,QAAA,EAAU,IAAA,KAAS,iBAAA,GAAoB,QAAA,CAAS,oBAAoB,EAAC;AAC9E;AAWA,SAAS,cAAA,CAAe,Q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AA;AAAA,oBACA,GAAA,CAAC,cAAA,EAAA,EAAe,EAAA,EAAI,CAAA,EAAG,IAAA,CAAK,EAAE,CAAA,SAAA,CAAA,EAC3B,QAAA,EAAA,QAAA,GAAW,kBAAA,CAAmB,OAAO,CAAA,GAAI,OAAA,EAC5C;AAAA,GAAA,EACF,CAAA;AAEJ;AC9XO,SAASA,gBAAe,KAAA,EAA4B;AACzD,EAAA,uBACEC,GAAAA,CAAC,qBAAA,EAAA,EAAsB,aAAA,EAAe,KAAA,CAAM,IAAA,EAAM,KAAA,EAChD,QAAA,kBAAAA,GAAAA,CAAC,cAAA,EAAA,EAAoB,GAAG,KAAA,EAAO,CAAA,EACjC,CAAA;AAEJ","file":"chunk-ZLUMUJUQ.js","sourcesContent":["'use client';\n\nimport {\n ActivitySchemaError,\n type ItemOutcome,\n type LearnerResponse,\n type MultipleChoiceData,\n type MultipleChoiceLearnerResponse,\n type MultipleChoiceOption,\n type ScoringDetail,\n score,\n seededShuffle,\n validateActivity,\n xAPIBuilder,\n xapiDefinitionFor,\n} from '@intellectif/lk-core';\nimport { type CSSProperties, useEffect, useMemo, useRef, useState } from 'react';\nimport { useActivityState } from '../../hooks/useActivityState.js';\nimport { ANONYMOUS_ACTOR, isDevelopment, objectIdFor, randomSessionId } from '../_internal.js';\nimport { ActivityMedia } from '../shared/ActivityMedia.js';\nimport { FeedbackRegion } from '../shared/FeedbackRegion.js';\nimport type { ActivityProps } from '../types.js';\n\n/**\n * Selected option ids carried by a learner response. Any other response shape\n * (a caller wiring the wrong item's state through `value`) reads as \"nothing\n * selected\" rather than throwing mid-exam.\n */\nfunction selectionOf(response: LearnerResponse | undefined): string[] {\n return response?.type === 'multiple-choice' ? response.selectedOptionIds : [];\n}\n\n/**\n * Whether an option is part of the correct answer, derived from the SERVER's\n * outcome — review mode never holds an answer key of its own.\n * {@link ScoringDetail.outcome} states this unambiguously. For 0.2-era details\n * that carry only the deprecated `correct` flag (which means \"the learner\n * ACTED correctly on this option\", not \"this option is the answer\") the fact\n * is still recoverable, because we know whether the learner selected it:\n * `isCorrect = wasSelected ? correct : !correct`.\n */\nfunction isAnswerOption(detail: ScoringDetail, wasSelected: boolean): boolean {\n switch (detail.outcome) {\n case 'correct':\n case 'incorrect-omission':\n return true;\n case 'incorrect':\n case 'correct-omission':\n return false;\n default:\n return wasSelected ? detail.correct : !detail.correct;\n }\n}\n\n/** Announcement for `review` mode, built only from the server-supplied outcome. */\nfunction reviewAnnouncement(outcome: ItemOutcome | undefined): string | null {\n if (outcome === undefined) {\n return null;\n }\n if (outcome.status === 'scored') {\n const overall = outcome.feedback;\n return `Score ${Math.round(outcome.score * 100)}%. ${\n outcome.passed ? 'Passed.' : 'Not passed.'\n }${overall ? ` ${overall}` : ''}`;\n }\n if (outcome.status === 'deferred') {\n // Never \"0%\": ungraded is not the same as wrong.\n return 'Not graded yet.';\n }\n return null;\n}\n\nexport interface MultipleChoiceProps extends ActivityProps<MultipleChoiceData> {\n /**\n * Seed for the deterministic option shuffle. Supply one (e.g. the attempt\n * id) to make the shuffled order reproducible server-side, stable across\n * page reloads, and identical between SSR and hydration. When absent, a\n * random per-mount session seed is used (order stable within the mount\n * only — the behaviour before `shuffleSeed` existed).\n */\n shuffleSeed?: string;\n}\n\nexport function MultipleChoice({\n data,\n onComplete,\n onSubmit,\n value,\n defaultValue,\n defaultSubmitted,\n onChange,\n renderMode = 'practice',\n outcome,\n sanitizeHtml,\n onInteraction,\n theme,\n locale,\n disabled,\n shuffleSeed,\n}: MultipleChoiceProps) {\n // Dev-only boundary validation (Req 2.3). Throwing during render lets\n // ActivityErrorBoundary catch it. Memoised so it only re-runs on data change.\n const devError = useMemo(() => {\n if (!isDevelopment()) {\n return null;\n }\n // A `redact()` projection cannot satisfy the full content schema — the\n // answer key is gone by design — and must not be checked against the\n // strict redacted schema either, since a `reveal: 'after-submit'`\n // projection legitimately carries answer-key fields for review renders.\n if (data.redacted === true) {\n return null;\n }\n const result = validateActivity('multiple-choice', data);\n return result.success ? null : new ActivitySchemaError('multiple-choice', result.errors);\n }, [data]);\n\n // Lazily created only when shuffling without a caller seed: avoids calling\n // crypto.randomUUID (absent on non-secure http origins) unless needed.\n const sessionIdRef = useRef<string | null>(null);\n const { state, start, complete, getTimeSpent, reset } = useActivityState(\n defaultSubmitted === true ? 'completed' : 'idle',\n );\n // Uncontrolled state. `defaultValue` seeds the mount only (React convention);\n // to re-seed later, remount with a `key` or drive the component with `value`.\n const [internalSelection, setInternalSelection] = useState<string[]>(() =>\n selectionOf(defaultValue),\n );\n const [summary, setSummary] = useState<string | null>(null);\n\n // Reset on data-prop CHANGE (Req 3.7). The identity guard makes the mount\n // run a no-op, which it always was before `defaultValue` existed — without\n // it this effect would wipe the seed immediately after the first render.\n // (It also makes the reset StrictMode-safe: a remount with unchanged data\n // no longer discards the learner's selection.)\n // Resets back to `defaultValue`, not to empty. Clearing looked safer — it\n // cannot carry a stale answer into a different question — but `data`\n // identity is a poor proxy for \"different question\": a parent that builds\n // entries in render (`activities={raw.map(redact)}`, the documented exam\n // pattern) hands over a new object every render, and clearing wiped every\n // RESTORED answer on the first unrelated re-render, silently. `defaultValue`\n // is by definition the caller's seed for the CURRENT data, which is what\n // FillInTheBlanks already reset to; the two now agree.\n const defaultValueRef = useRef(defaultValue);\n useEffect(() => {\n defaultValueRef.current = defaultValue;\n }, [defaultValue]);\n // A data change must return the item to its SEED, submitted state included —\n // resetting to idle unlocked work the learner had already committed.\n const defaultSubmittedRef = useRef(defaultSubmitted);\n useEffect(() => {\n defaultSubmittedRef.current = defaultSubmitted;\n }, [defaultSubmitted]);\n const lastDataRef = useRef(data);\n useEffect(() => {\n if (lastDataRef.current === data) {\n return;\n }\n lastDataRef.current = data;\n setInternalSelection(selectionOf(defaultValueRef.current));\n setSummary(null);\n reset(defaultSubmittedRef.current === true ? 'completed' : 'idle');\n }, [data, reset]);\n\n const displayedOptions = useMemo<MultipleChoiceOption[]>(() => {\n if (!data.shuffle) {\n return [...data.options];\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: sanctioned lazy ref initialization\n const seedSource = shuffleSeed ?? (sessionIdRef.current ??= randomSessionId());\n // The seed string is unchanged from when the algorithm lived in this file,\n // so an order a consumer recorded against a seed still reproduces.\n return seededShuffle(data.options, `${seedSource}:${data.id}`);\n }, [data, shuffleSeed]);\n\n // Per-option correctness for `review`, indexed by option id. Null unless the\n // caller supplied a SCORED outcome — the only source of truth this mode has.\n const reviewDetails = useMemo(() => {\n if (renderMode !== 'review' || outcome === undefined || outcome.status !== 'scored') {\n return null;\n }\n return new Map(outcome.details.map((detail) => [detail.itemId, detail]));\n }, [renderMode, outcome]);\n\n // All hooks are called before these throws, so hook order stays stable.\n if (devError) {\n throw devError;\n }\n // Practice grades locally, which a redacted projection cannot support:\n // `score()` would throw from the submit handler — where no error boundary\n // can catch it — AFTER the learner has answered. Fail loudly at render\n // instead, in production too. Wiring an exam item into the self-grading\n // mode is precisely the accident `renderMode` exists to prevent.\n if (data.redacted === true && renderMode === 'practice') {\n throw new Error(\n `Multiple Choice \"${data.id}\" received redacted activity data in renderMode \"practice\", ` +\n 'which grades locally and has no answer key to grade against. ' +\n 'Render redacted data with renderMode=\"exam\" (server grades) or \"review\" (pass `outcome`).',\n );\n }\n\n const isSingle = data.mode === 'single';\n const isExam = renderMode === 'exam';\n const isReview = renderMode === 'review';\n const submitted = state === 'completed';\n const inactive = disabled === true || submitted || isReview;\n const isControlled = value !== undefined;\n const selected = isControlled ? selectionOf(value) : internalSelection;\n /**\n * Whether correctness and authored feedback may be shown. Practice earns it\n * by grading locally after submit; review shows what the server already\n * graded. Exam never reveals anything — not before, not after submit.\n */\n const reveal = isReview || (renderMode === 'practice' && submitted);\n\n const fireInteraction = (\n type: 'option-selected' | 'option-deselected' | 'submitted',\n payload: Record<string, unknown>,\n ): void => {\n onInteraction?.({ type, activityId: data.id, timestamp: Date.now(), payload });\n };\n\n /** Single funnel for every response change: owns state only when uncontrolled. */\n const emitChange = (selectedOptionIds: string[]): void => {\n if (!isControlled) {\n setInternalSelection(selectedOptionIds);\n }\n onChange?.({ type: 'multiple-choice', selectedOptionIds });\n };\n\n const selectSingle = (optionId: string): void => {\n if (inactive) {\n return;\n }\n if (state === 'idle') {\n start();\n }\n emitChange([optionId]);\n fireInteraction('option-selected', { optionId });\n };\n\n const toggleMulti = (optionId: string, checked: boolean): void => {\n if (inactive) {\n return;\n }\n if (state === 'idle') {\n start();\n }\n emitChange(checked ? [...selected, optionId] : selected.filter((id) => id !== optionId));\n fireInteraction(checked ? 'option-selected' : 'option-deselected', { optionId });\n };\n\n const handleSubmit = (event: React.FormEvent): void => {\n event.preventDefault();\n if (inactive) {\n return;\n }\n const response: MultipleChoiceLearnerResponse = {\n type: 'multiple-choice',\n selectedOptionIds: selected,\n };\n // Always first, and before anything that can throw: an exam runner must be\n // able to persist the raw response no matter what happens after.\n onSubmit?.(response);\n\n if (isExam) {\n // No score(), no answer key read, no onComplete, no xAPI — the server\n // grades. The announcement deliberately carries no correctness signal.\n complete();\n setSummary('Answer submitted.');\n fireInteraction('submitted', { selectedOptionIds: selected });\n return;\n }\n\n const scoringResult = score('multiple-choice', data as MultipleChoiceData, response);\n complete();\n const timeSpent = getTimeSpent();\n const xapiStatement = xAPIBuilder.buildAnsweredStatement({\n actor: ANONYMOUS_ACTOR,\n object: {\n id: objectIdFor(data.id),\n name: { [data.locale ?? 'en-US']: data.title },\n // Activity-type IRI, interaction type and correct-responses pattern\n // come from the REGISTERED descriptor, so a consumer-registered type\n // gets correct interop without touching this component.\n ...xapiDefinitionFor(data),\n choices: data.options.map((option) => ({\n id: option.id,\n description: { [data.locale ?? 'en-US']: option.text },\n })),\n },\n scoringResult,\n timeSpentMs: timeSpent,\n response: selected.join(','),\n });\n onComplete?.({\n score: scoringResult.score,\n maxScore: scoringResult.maxScore,\n passed: scoringResult.passed,\n timeSpent,\n xapiStatement,\n });\n // Core selects the authored overall feedback on `passed` (B3 fix).\n const overall = scoringResult.feedback;\n setSummary(\n `Answer submitted. Score ${Math.round(scoringResult.score * 100)}%. ${\n scoringResult.passed ? 'Passed.' : 'Not passed.'\n }${overall ? ` ${overall}` : ''}`,\n );\n fireInteraction('submitted', {\n selectedOptionIds: selected,\n score: scoringResult.score,\n });\n };\n\n const questionId = `${data.id}-question`;\n // Rich text renders ONLY through a caller-supplied sanitiser; without one we\n // fall back to the plain-text field, escaped by React (types.ts HtmlSanitizer).\n const questionHtml =\n sanitizeHtml !== undefined && data.questionHtml !== undefined\n ? sanitizeHtml(data.questionHtml)\n : null;\n\n const optionList = displayedOptions.map((option) => {\n const checked = selected.includes(option.id);\n // `data-correct` means \"this option is part of the correct answer\".\n let correctness: string | undefined;\n if (isReview) {\n const detail = reviewDetails?.get(option.id);\n correctness = detail === undefined ? undefined : String(isAnswerOption(detail, checked));\n } else if (reveal) {\n correctness = String(option.isCorrect);\n }\n return (\n <label key={option.id} className=\"lk-mc-option\" data-correct={correctness}>\n <input\n type={isSingle ? 'radio' : 'checkbox'}\n name={isSingle ? `${data.id}-options` : undefined}\n value={option.id}\n checked={checked}\n disabled={inactive}\n aria-disabled={inactive || undefined}\n onChange={(e) =>\n isSingle ? selectSingle(option.id) : toggleMulti(option.id, e.target.checked)\n }\n />\n <span>{option.text}</span>\n {reveal && option.feedback ? (\n <span className=\"lk-mc-option-feedback\" role=\"note\">\n {option.feedback}\n </span>\n ) : null}\n </label>\n );\n });\n\n return (\n <div className=\"lk-mc\" lang={locale} style={theme as CSSProperties | undefined}>\n {data.media ? <ActivityMedia media={data.media} /> : null}\n <form onSubmit={handleSubmit}>\n <fieldset disabled={inactive}>\n {questionHtml === null ? (\n <legend id={questionId}>{data.question}</legend>\n ) : (\n <legend\n id={questionId}\n // biome-ignore lint/security/noDangerouslySetInnerHtml: HTML is the output of the caller-supplied sanitizeHtml (types.ts HtmlSanitizer contract)\n dangerouslySetInnerHTML={{ __html: questionHtml }}\n />\n )}\n {/*\n single: an explicit radiogroup is meaningful (fieldset's implicit\n role is `group`, not `radiogroup`). multi: the fieldset + legend\n already provide a named group — an explicit role=\"group\" here would\n be a redundant, duplicate same-named group in the a11y tree, so we\n use a plain layout div. (Refines the design ARIA sketch.)\n */}\n {isSingle ? (\n <div role=\"radiogroup\" aria-labelledby={questionId}>\n {optionList}\n </div>\n ) : (\n <div>{optionList}</div>\n )}\n {/* review is read-only: there is nothing left to submit. */}\n {isReview ? null : (\n <button type=\"submit\" disabled={inactive}>\n Submit\n </button>\n )}\n </fieldset>\n </form>\n <FeedbackRegion id={`${data.id}-feedback`}>\n {isReview ? reviewAnnouncement(outcome) : summary}\n </FeedbackRegion>\n </div>\n );\n}\n","'use client';\n\nimport { ActivityErrorBoundary } from '../ActivityErrorBoundary.js';\nimport {\n MultipleChoice as MultipleChoiceCore,\n type MultipleChoiceProps,\n} from './MultipleChoice.js';\n\nexport type { MultipleChoiceProps } from './MultipleChoice.js';\n\n/**\n * Public Multiple Choice activity: the core component wrapped in\n * `ActivityErrorBoundary` so a render failure (incl. the dev schema-validation\n * throw) degrades to an accessible fallback instead of crashing the host.\n */\nexport function MultipleChoice(props: MultipleChoiceProps) {\n return (\n <ActivityErrorBoundary activityTitle={props.data?.title}>\n <MultipleChoiceCore {...props} />\n </ActivityErrorBoundary>\n );\n}\n"]}
@@ -1,19 +1,20 @@
1
+ 'use client';
1
2
  'use strict';
2
3
 
3
- var chunk3B4ACY4K_cjs = require('../chunk-3B4ACY4K.cjs');
4
- require('../chunk-WCVD5LVG.cjs');
5
- require('../chunk-67RIIDZX.cjs');
6
- require('../chunk-6COTYW77.cjs');
4
+ var chunkDUIWK272_cjs = require('../chunk-DUIWK272.cjs');
5
+ require('../chunk-BE7R2X3S.cjs');
6
+ require('../chunk-NPY2F7F6.cjs');
7
+ require('../chunk-MDYKYDRN.cjs');
7
8
  require('../chunk-PGEG7UZJ.cjs');
8
9
  require('../chunk-NEWGUDA5.cjs');
9
10
  require('../chunk-4HZ7LQIH.cjs');
10
- require('../chunk-HD2AIQRD.cjs');
11
+ require('../chunk-XOR4MPEN.cjs');
11
12
 
12
13
 
13
14
 
14
15
  Object.defineProperty(exports, "ActivitySequence", {
15
16
  enumerable: true,
16
- get: function () { return chunk3B4ACY4K_cjs.ActivitySequence; }
17
+ get: function () { return chunkDUIWK272_cjs.ActivitySequence; }
17
18
  });
18
19
  //# sourceMappingURL=ActivitySequence.cjs.map
19
20
  //# sourceMappingURL=ActivitySequence.cjs.map
@@ -1,7 +1,7 @@
1
- import { SequenceEntry, ActivityResult, LearnerResponse, InteractionEvent, ThemeTokens } from '@intellectif/lk-core';
1
+ import { SequenceEntry, ActivityResult, LearnerResponse, InteractionEvent, ItemOutcome, ThemeTokens } from '@intellectif/lk-core';
2
2
  import { ComponentType } from 'react';
3
- import { A as ActivityProps, b as RenderableActivity, R as RenderMode, H as HtmlSanitizer } from '../types-CrURyd9-.cjs';
4
- import { a as WrittenResponseSubmission } from '../WrittenResponse-DqQ0NjPK.cjs';
3
+ import { A as ActivityProps, b as RenderableActivity, R as RenderMode, H as HtmlSanitizer } from '../types-9iS1Vs2I.cjs';
4
+ import { a as WrittenResponseSubmission } from '../WrittenResponse-BXHidIaK.cjs';
5
5
 
6
6
  /**
7
7
  * What one finished slot in a sequence produced. Two kinds, because two kinds
@@ -24,6 +24,17 @@ type SequenceItemOutcome = {
24
24
  activityId: string;
25
25
  /** Ungraded submission; the grade arrives asynchronously. */
26
26
  submission: WrittenResponseSubmission;
27
+ } | {
28
+ kind: 'restored';
29
+ index: number;
30
+ slotId: string;
31
+ activityId: string;
32
+ /**
33
+ * The answer as restored, when one was. A slot can be submitted with no
34
+ * stored response (a blank the learner committed), so this is optional —
35
+ * inventing one would be worse than admitting it is absent.
36
+ */
37
+ response?: LearnerResponse;
27
38
  } | {
28
39
  kind: 'responded';
29
40
  index: number;
@@ -118,16 +129,59 @@ interface ActivitySequenceProps {
118
129
  * server's `flattenSequence(entries, { seed })` derives the same order this
119
130
  * pager shows.
120
131
  *
121
- * **Required in `exam` and `review` mode** — omitting it throws. An order
122
- * nobody can reproduce cannot be reconciled with a recorded attempt, and
123
- * failing at render is the only way that mistake surfaces before a learner
124
- * sits the paper. In `practice` mode it stays optional: a random per-mount
125
- * seed is used, which is stable within the mount and deliberately not
126
- * reproducible. That fallback is also not SSR-safe (server and client would
127
- * invent different orders and hydration would mismatch), so supply a seed
128
- * for any server-rendered sequence regardless of mode.
132
+ * **Required whenever this sequence shuffles** — `shuffle: 'entries'`, or any
133
+ * group with `shuffle: 'within-group'` in `exam` or `review` mode; omitting
134
+ * it then throws. An order nobody can reproduce cannot be reconciled with a
135
+ * recorded attempt, and failing at render is the only way that mistake
136
+ * surfaces before a learner sits the paper. A sequence that does not shuffle
137
+ * needs no seed in any mode.
138
+ *
139
+ * Note the guard does NOT cover an activity's own `data.shuffle`:
140
+ * `<MultipleChoice>` falls back to a per-mount seed there in every mode, so
141
+ * pass this whenever any item shuffles its options.
142
+ *
143
+ * In `practice` mode it stays optional: a random per-mount seed is used,
144
+ * stable within the mount and deliberately not reproducible. That fallback is
145
+ * also not SSR-safe (server and client would invent different orders and
146
+ * hydration would mismatch), so supply a seed for any server-rendered
147
+ * sequence regardless of mode.
129
148
  */
130
149
  shuffleSeed?: string;
150
+ /**
151
+ * Where to open. Defaults to the first question; pass a stored
152
+ * `AttemptState.index` to reopen an interrupted attempt where it was left.
153
+ * Read at mount only, like any `default*` prop.
154
+ */
155
+ defaultIndex?: number;
156
+ /**
157
+ * Fires whenever the learner moves. Persist it and the next resume reopens
158
+ * on the right question — without it, the pager's position is the one piece
159
+ * of an attempt a consumer cannot recover.
160
+ */
161
+ onIndexChange?: (index: number) => void;
162
+ /**
163
+ * Answers to restore, keyed by `slotId`, seeded into each slot as its
164
+ * `defaultValue`. This is the other half of resume: `AttemptState.responses`
165
+ * goes straight in.
166
+ *
167
+ * Read at mount only. To restore a different attempt, remount with a `key`.
168
+ */
169
+ responses?: Readonly<Record<string, LearnerResponse>>;
170
+ /**
171
+ * Slots the learner had already submitted, from `AttemptState.submittedSlotIds`.
172
+ * Each is mounted already submitted, so a resumed paper does not reopen a
173
+ * locked question as answerable — without this a learner can change and
174
+ * re-submit work they had already committed.
175
+ *
176
+ * Read at mount only, alongside `responses`.
177
+ */
178
+ submittedSlotIds?: readonly string[];
179
+ /**
180
+ * Server-computed outcomes keyed by `slotId`, forwarded to each slot. In
181
+ * `review` mode this is what marks correctness — the client never scores, so
182
+ * without it a review render has nothing to show.
183
+ */
184
+ outcomes?: Readonly<Record<string, ItemOutcome>>;
131
185
  /** Renders author-supplied rich text; forwarded to the stimulus panel and every activity. */
132
186
  sanitizeHtml?: HtmlSanitizer;
133
187
  theme?: Partial<ThemeTokens>;
@@ -146,6 +200,6 @@ interface ActivitySequenceProps {
146
200
  * alongside every question in the group — so a passage stays put, and a
147
201
  * recording keeps its position, as the learner moves between its questions.
148
202
  */
149
- declare function ActivitySequence({ activities, renderers, onActivityComplete, onComplete, onFinished, onSubmit, onInteraction, renderMode, shuffle, shuffleSeed, sanitizeHtml, theme, locale, disabled, }: ActivitySequenceProps): React.JSX.Element;
203
+ declare function ActivitySequence({ activities, renderers, onActivityComplete, onComplete, onFinished, onSubmit, onInteraction, renderMode, shuffle, shuffleSeed, defaultIndex, onIndexChange, responses, submittedSlotIds, outcomes, sanitizeHtml, theme, locale, disabled, }: ActivitySequenceProps): React.JSX.Element;
150
204
 
151
205
  export { type ActivityRenderer, ActivitySequence, type ActivitySequenceProps, type SequenceItemOutcome };
@@ -1,7 +1,7 @@
1
- import { SequenceEntry, ActivityResult, LearnerResponse, InteractionEvent, ThemeTokens } from '@intellectif/lk-core';
1
+ import { SequenceEntry, ActivityResult, LearnerResponse, InteractionEvent, ItemOutcome, ThemeTokens } from '@intellectif/lk-core';
2
2
  import { ComponentType } from 'react';
3
- import { A as ActivityProps, b as RenderableActivity, R as RenderMode, H as HtmlSanitizer } from '../types-CrURyd9-.js';
4
- import { a as WrittenResponseSubmission } from '../WrittenResponse-Dkg7FUt-.js';
3
+ import { A as ActivityProps, b as RenderableActivity, R as RenderMode, H as HtmlSanitizer } from '../types-9iS1Vs2I.js';
4
+ import { a as WrittenResponseSubmission } from '../WrittenResponse-DJYGuMKk.js';
5
5
 
6
6
  /**
7
7
  * What one finished slot in a sequence produced. Two kinds, because two kinds
@@ -24,6 +24,17 @@ type SequenceItemOutcome = {
24
24
  activityId: string;
25
25
  /** Ungraded submission; the grade arrives asynchronously. */
26
26
  submission: WrittenResponseSubmission;
27
+ } | {
28
+ kind: 'restored';
29
+ index: number;
30
+ slotId: string;
31
+ activityId: string;
32
+ /**
33
+ * The answer as restored, when one was. A slot can be submitted with no
34
+ * stored response (a blank the learner committed), so this is optional —
35
+ * inventing one would be worse than admitting it is absent.
36
+ */
37
+ response?: LearnerResponse;
27
38
  } | {
28
39
  kind: 'responded';
29
40
  index: number;
@@ -118,16 +129,59 @@ interface ActivitySequenceProps {
118
129
  * server's `flattenSequence(entries, { seed })` derives the same order this
119
130
  * pager shows.
120
131
  *
121
- * **Required in `exam` and `review` mode** — omitting it throws. An order
122
- * nobody can reproduce cannot be reconciled with a recorded attempt, and
123
- * failing at render is the only way that mistake surfaces before a learner
124
- * sits the paper. In `practice` mode it stays optional: a random per-mount
125
- * seed is used, which is stable within the mount and deliberately not
126
- * reproducible. That fallback is also not SSR-safe (server and client would
127
- * invent different orders and hydration would mismatch), so supply a seed
128
- * for any server-rendered sequence regardless of mode.
132
+ * **Required whenever this sequence shuffles** — `shuffle: 'entries'`, or any
133
+ * group with `shuffle: 'within-group'` in `exam` or `review` mode; omitting
134
+ * it then throws. An order nobody can reproduce cannot be reconciled with a
135
+ * recorded attempt, and failing at render is the only way that mistake
136
+ * surfaces before a learner sits the paper. A sequence that does not shuffle
137
+ * needs no seed in any mode.
138
+ *
139
+ * Note the guard does NOT cover an activity's own `data.shuffle`:
140
+ * `<MultipleChoice>` falls back to a per-mount seed there in every mode, so
141
+ * pass this whenever any item shuffles its options.
142
+ *
143
+ * In `practice` mode it stays optional: a random per-mount seed is used,
144
+ * stable within the mount and deliberately not reproducible. That fallback is
145
+ * also not SSR-safe (server and client would invent different orders and
146
+ * hydration would mismatch), so supply a seed for any server-rendered
147
+ * sequence regardless of mode.
129
148
  */
130
149
  shuffleSeed?: string;
150
+ /**
151
+ * Where to open. Defaults to the first question; pass a stored
152
+ * `AttemptState.index` to reopen an interrupted attempt where it was left.
153
+ * Read at mount only, like any `default*` prop.
154
+ */
155
+ defaultIndex?: number;
156
+ /**
157
+ * Fires whenever the learner moves. Persist it and the next resume reopens
158
+ * on the right question — without it, the pager's position is the one piece
159
+ * of an attempt a consumer cannot recover.
160
+ */
161
+ onIndexChange?: (index: number) => void;
162
+ /**
163
+ * Answers to restore, keyed by `slotId`, seeded into each slot as its
164
+ * `defaultValue`. This is the other half of resume: `AttemptState.responses`
165
+ * goes straight in.
166
+ *
167
+ * Read at mount only. To restore a different attempt, remount with a `key`.
168
+ */
169
+ responses?: Readonly<Record<string, LearnerResponse>>;
170
+ /**
171
+ * Slots the learner had already submitted, from `AttemptState.submittedSlotIds`.
172
+ * Each is mounted already submitted, so a resumed paper does not reopen a
173
+ * locked question as answerable — without this a learner can change and
174
+ * re-submit work they had already committed.
175
+ *
176
+ * Read at mount only, alongside `responses`.
177
+ */
178
+ submittedSlotIds?: readonly string[];
179
+ /**
180
+ * Server-computed outcomes keyed by `slotId`, forwarded to each slot. In
181
+ * `review` mode this is what marks correctness — the client never scores, so
182
+ * without it a review render has nothing to show.
183
+ */
184
+ outcomes?: Readonly<Record<string, ItemOutcome>>;
131
185
  /** Renders author-supplied rich text; forwarded to the stimulus panel and every activity. */
132
186
  sanitizeHtml?: HtmlSanitizer;
133
187
  theme?: Partial<ThemeTokens>;
@@ -146,6 +200,6 @@ interface ActivitySequenceProps {
146
200
  * alongside every question in the group — so a passage stays put, and a
147
201
  * recording keeps its position, as the learner moves between its questions.
148
202
  */
149
- declare function ActivitySequence({ activities, renderers, onActivityComplete, onComplete, onFinished, onSubmit, onInteraction, renderMode, shuffle, shuffleSeed, sanitizeHtml, theme, locale, disabled, }: ActivitySequenceProps): React.JSX.Element;
203
+ declare function ActivitySequence({ activities, renderers, onActivityComplete, onComplete, onFinished, onSubmit, onInteraction, renderMode, shuffle, shuffleSeed, defaultIndex, onIndexChange, responses, submittedSlotIds, outcomes, sanitizeHtml, theme, locale, disabled, }: ActivitySequenceProps): React.JSX.Element;
150
204
 
151
205
  export { type ActivityRenderer, ActivitySequence, type ActivitySequenceProps, type SequenceItemOutcome };
@@ -1,10 +1,11 @@
1
- export { ActivitySequence } from '../chunk-NBFTCGQ5.js';
2
- import '../chunk-5SYL5CJ2.js';
3
- import '../chunk-3DNJDP73.js';
4
- import '../chunk-67WDTQMG.js';
1
+ 'use client';
2
+ export { ActivitySequence } from '../chunk-IUODGQXE.js';
3
+ import '../chunk-ZLUMUJUQ.js';
4
+ import '../chunk-57E3E2H4.js';
5
+ import '../chunk-MDZMKC27.js';
5
6
  import '../chunk-6F4X2NKL.js';
6
7
  import '../chunk-UQ3BBEIT.js';
7
8
  import '../chunk-GB5URWM4.js';
8
- import '../chunk-5HVUKXF3.js';
9
+ import '../chunk-6N43WDVG.js';
9
10
  //# sourceMappingURL=ActivitySequence.js.map
10
11
  //# sourceMappingURL=ActivitySequence.js.map