@pie-players/pie-assessment-toolkit 0.3.58 → 0.3.60

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.
@@ -21,6 +21,13 @@ export interface AssessmentToolkitRuntimeContext {
21
21
  assessmentId: string;
22
22
  sectionId: string;
23
23
  itemPlayer: ItemPlayerConfig;
24
+ /**
25
+ * Opt-in flag: context consumers render the vendored `<nds-icon-button>`
26
+ * only when this is `true`; otherwise (unset/`false`, the default) they
27
+ * render plain `<button>` controls. Sourced from the host's
28
+ * `runtime.ndsIcons` (or the `nds-icons` attribute on the toolkit).
29
+ */
30
+ ndsIcons?: boolean;
24
31
  reportSessionChanged?: (itemId: string, detail: unknown) => void;
25
32
  }
26
33
  export declare const assessmentToolkitRuntimeContext: {
@@ -1 +1 @@
1
- {"version":3,"file":"assessment-toolkit-context.js","sourceRoot":"","sources":["../../src/context/assessment-toolkit-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAqCzD,MAAM,CAAC,MAAM,+BAA+B,GAC3C,aAAa,CACZ,MAAM,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAClD,CAAC;AAOH,MAAM,CAAC,MAAM,mCAAmC,GAC/C,aAAa,CACZ,MAAM,CAAC,GAAG,CAAC,0CAA0C,CAAC,CACtD,CAAC;AAeH,MAAM,CAAC,MAAM,6BAA6B,GACzC,aAAa,CACZ,MAAM,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAChD,CAAC;AAOH,MAAM,CAAC,MAAM,mCAAmC,GAC/C,aAAa,CACZ,MAAM,CAAC,GAAG,CAAC,0CAA0C,CAAC,CACtD,CAAC","sourcesContent":["import { createContext } from \"@pie-players/pie-context\";\nimport type { LoaderConfig } from \"@pie-players/pie-players-shared/loader-config\";\nimport type {\n\tAccessibilityCatalogResolverApi,\n\tElementToolStateStoreApi,\n\tHighlightCoordinatorApi,\n\tToolCoordinatorApi,\n\tToolkitCoordinatorApi,\n\tTtsServiceApi,\n} from \"../services/interfaces.js\";\nimport type { TTSHighlightTargetResolver } from \"../services/tts/highlight-target-resolver.js\";\n\nexport type ItemPlayerType = \"iife\" | \"esm\" | \"preloaded\" | \"custom\";\n\nexport interface ItemPlayerConfig {\n\ttype: ItemPlayerType;\n\ttagName: string;\n\tversion?: string;\n\tsource?: string;\n\tloaderConfig?: LoaderConfig;\n\tloaderOptions?: Record<string, unknown>;\n\tisDefault: boolean;\n}\n\nexport interface AssessmentToolkitRuntimeContext {\n\ttoolkitCoordinator: ToolkitCoordinatorApi;\n\ttoolCoordinator: ToolCoordinatorApi;\n\tttsService: TtsServiceApi;\n\thighlightCoordinator: HighlightCoordinatorApi;\n\tcatalogResolver: AccessibilityCatalogResolverApi;\n\telementToolStateStore: ElementToolStateStoreApi;\n\tassessmentId: string;\n\tsectionId: string;\n\titemPlayer: ItemPlayerConfig;\n\treportSessionChanged?: (itemId: string, detail: unknown) => void;\n}\n\nexport const assessmentToolkitRuntimeContext =\n\tcreateContext<AssessmentToolkitRuntimeContext>(\n\t\tSymbol.for(\"pie.assessmentToolkit.runtimeContext\"),\n\t);\n\nexport interface AssessmentToolkitHostRuntimeContext {\n\truntimeId: string;\n\tcoordinator: ToolkitCoordinatorApi;\n}\n\nexport const assessmentToolkitHostRuntimeContext =\n\tcreateContext<AssessmentToolkitHostRuntimeContext>(\n\t\tSymbol.for(\"pie.assessmentToolkit.hostRuntimeContext\"),\n\t);\n\nexport type ShellContextKind = \"item\" | \"passage\";\n\nexport interface AssessmentToolkitShellContext {\n\tkind: ShellContextKind;\n\titemId: string;\n\tcanonicalItemId: string;\n\tcontentKind: string;\n\tregionPolicy: string;\n\tscopeElement: HTMLElement | null;\n\titem: unknown;\n\tcontextVersion: number;\n}\n\nexport const assessmentToolkitShellContext =\n\tcreateContext<AssessmentToolkitShellContext>(\n\t\tSymbol.for(\"pie.assessmentToolkit.shellContext\"),\n\t);\n\nexport interface AssessmentToolkitRegionScopeContext {\n\tscopeElement: HTMLElement | null;\n\tttsHighlightTargetResolver?: TTSHighlightTargetResolver | null;\n}\n\nexport const assessmentToolkitRegionScopeContext =\n\tcreateContext<AssessmentToolkitRegionScopeContext>(\n\t\tSymbol.for(\"pie.assessmentToolkit.regionScopeContext\"),\n\t);\n"]}
1
+ {"version":3,"file":"assessment-toolkit-context.js","sourceRoot":"","sources":["../../src/context/assessment-toolkit-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AA4CzD,MAAM,CAAC,MAAM,+BAA+B,GAC3C,aAAa,CACZ,MAAM,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAClD,CAAC;AAOH,MAAM,CAAC,MAAM,mCAAmC,GAC/C,aAAa,CACZ,MAAM,CAAC,GAAG,CAAC,0CAA0C,CAAC,CACtD,CAAC;AAeH,MAAM,CAAC,MAAM,6BAA6B,GACzC,aAAa,CACZ,MAAM,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAChD,CAAC;AAOH,MAAM,CAAC,MAAM,mCAAmC,GAC/C,aAAa,CACZ,MAAM,CAAC,GAAG,CAAC,0CAA0C,CAAC,CACtD,CAAC","sourcesContent":["import { createContext } from \"@pie-players/pie-context\";\nimport type { LoaderConfig } from \"@pie-players/pie-players-shared/loader-config\";\nimport type {\n\tAccessibilityCatalogResolverApi,\n\tElementToolStateStoreApi,\n\tHighlightCoordinatorApi,\n\tToolCoordinatorApi,\n\tToolkitCoordinatorApi,\n\tTtsServiceApi,\n} from \"../services/interfaces.js\";\nimport type { TTSHighlightTargetResolver } from \"../services/tts/highlight-target-resolver.js\";\n\nexport type ItemPlayerType = \"iife\" | \"esm\" | \"preloaded\" | \"custom\";\n\nexport interface ItemPlayerConfig {\n\ttype: ItemPlayerType;\n\ttagName: string;\n\tversion?: string;\n\tsource?: string;\n\tloaderConfig?: LoaderConfig;\n\tloaderOptions?: Record<string, unknown>;\n\tisDefault: boolean;\n}\n\nexport interface AssessmentToolkitRuntimeContext {\n\ttoolkitCoordinator: ToolkitCoordinatorApi;\n\ttoolCoordinator: ToolCoordinatorApi;\n\tttsService: TtsServiceApi;\n\thighlightCoordinator: HighlightCoordinatorApi;\n\tcatalogResolver: AccessibilityCatalogResolverApi;\n\telementToolStateStore: ElementToolStateStoreApi;\n\tassessmentId: string;\n\tsectionId: string;\n\titemPlayer: ItemPlayerConfig;\n\t/**\n\t * Opt-in flag: context consumers render the vendored `<nds-icon-button>`\n\t * only when this is `true`; otherwise (unset/`false`, the default) they\n\t * render plain `<button>` controls. Sourced from the host's\n\t * `runtime.ndsIcons` (or the `nds-icons` attribute on the toolkit).\n\t */\n\tndsIcons?: boolean;\n\treportSessionChanged?: (itemId: string, detail: unknown) => void;\n}\n\nexport const assessmentToolkitRuntimeContext =\n\tcreateContext<AssessmentToolkitRuntimeContext>(\n\t\tSymbol.for(\"pie.assessmentToolkit.runtimeContext\"),\n\t);\n\nexport interface AssessmentToolkitHostRuntimeContext {\n\truntimeId: string;\n\tcoordinator: ToolkitCoordinatorApi;\n}\n\nexport const assessmentToolkitHostRuntimeContext =\n\tcreateContext<AssessmentToolkitHostRuntimeContext>(\n\t\tSymbol.for(\"pie.assessmentToolkit.hostRuntimeContext\"),\n\t);\n\nexport type ShellContextKind = \"item\" | \"passage\";\n\nexport interface AssessmentToolkitShellContext {\n\tkind: ShellContextKind;\n\titemId: string;\n\tcanonicalItemId: string;\n\tcontentKind: string;\n\tregionPolicy: string;\n\tscopeElement: HTMLElement | null;\n\titem: unknown;\n\tcontextVersion: number;\n}\n\nexport const assessmentToolkitShellContext =\n\tcreateContext<AssessmentToolkitShellContext>(\n\t\tSymbol.for(\"pie.assessmentToolkit.shellContext\"),\n\t);\n\nexport interface AssessmentToolkitRegionScopeContext {\n\tscopeElement: HTMLElement | null;\n\tttsHighlightTargetResolver?: TTSHighlightTargetResolver | null;\n}\n\nexport const assessmentToolkitRegionScopeContext =\n\tcreateContext<AssessmentToolkitRegionScopeContext>(\n\t\tSymbol.for(\"pie.assessmentToolkit.regionScopeContext\"),\n\t);\n"]}
@@ -60,6 +60,14 @@ export type RuntimeConfig = {
60
60
  createSectionController?: unknown;
61
61
  isolation?: string;
62
62
  env?: Record<string, unknown>;
63
+ /**
64
+ * Presentation flag: opt-in to the vendored `<nds-icon-button>` for the
65
+ * toolbar tool buttons, the calculator shell controls, inline-TTS
66
+ * play/pause, and the section scroll-hint. NDS icons render only when
67
+ * this is explicitly `true`; unset/`false` keeps the plain `<button>`
68
+ * markup (the default). Purely visual — no engine effect.
69
+ */
70
+ ndsIcons?: boolean;
63
71
  toolConfigStrictness?: ToolConfigStrictness;
64
72
  onFrameworkError?: FrameworkErrorHandler;
65
73
  onStageChange?: StageChangeHandler;
@@ -118,6 +126,14 @@ export declare function resolveRuntime(args: {
118
126
  onLoadingComplete: LoadingCompleteHandler | undefined;
119
127
  tools: unknown;
120
128
  toolContextResolvers?: Record<string, unknown> | null;
129
+ /**
130
+ * Presentation flag: opt-in to the vendored `<nds-icon-button>` for the
131
+ * toolbar tool buttons, the calculator shell controls, inline-TTS
132
+ * play/pause, and the section scroll-hint. NDS icons render only when
133
+ * this is explicitly `true`; unset/`false` keeps the plain `<button>`
134
+ * markup (the default). Purely visual — no engine effect.
135
+ */
136
+ ndsIcons?: boolean;
121
137
  };
122
138
  /**
123
139
  * Effective runtime returned by `resolveRuntime`. The shape is exposed
@@ -1 +1 @@
1
- {"version":3,"file":"engine-resolver.js","sourceRoot":"","sources":["../../../src/runtime/core/engine-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAUH,MAAM,CAAC,MAAM,qBAAqB,GAAG,qBAAqB,CAAC;AAC3D,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAC1C,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AACtC,MAAM,CAAC,MAAM,iBAAiB,GAAG,SAAS,CAAC;AAC3C,MAAM,CAAC,MAAM,W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AAE,IAAI,CAAC,aAAa;QACjC,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;KACzC,CAAC,CAAC;IACH,MAAM,aAAa,GAAG,IAAI,CAAC,oBAAoB,CAAC;QAC/C,gBAAgB,EAAE,gBAA2C;QAC7D,UAAU,EAAE,MAAM,CAAC,gBAAgB,CAAC,UAAU,IAAI,mBAAmB,CAAC;QACtE,GAAG,EAAG,gBAAgB,CAAC,GAAsC,IAAI,IAAI;KACrE,CAAC,CAAC;IACH,OAAO;QACN,oBAAoB;QACpB,gBAAgB;QAChB,aAAa;KACb,CAAC;AACH,CAAC","sourcesContent":["/**\n * Section runtime engine resolver (M7).\n *\n * Canonical home of `resolveRuntime`, `resolveToolsConfig`, and their\n * supporting helpers/types. As of M7 PR 7 the previous duplicates in\n * `packages/section-player/src/components/shared/section-player-runtime.ts`\n * have been deleted; section-player now consumes these helpers via\n * `@pie-players/pie-assessment-toolkit/runtime/internal`.\n *\n * What is NOT absorbed in this module:\n * - `resolvePlayerRuntime` stays in section-player because it depends on\n * `DEFAULT_PLAYER_DEFINITIONS` (which side-effect-imports the\n * item-player package). The toolkit core stays free of that\n * dependency by exposing a parametrized orchestrator —\n * `resolveSectionEngineRuntimeState` — that takes a `resolvePlayerRuntime`\n * callable. The section-player wrapper\n * (`resolveSectionPlayerRuntimeState` in\n * `packages/section-player/src/components/shared/section-player-host-runtime.ts`)\n * hands its local implementation in.\n *\n * Runtime-owned configuration flows through `runtime.<key>`. Layout-only\n * inputs stay on the section-player host elements.\n */\n\nimport type { LoaderConfig } from \"@pie-players/pie-players-shared/loader-config\";\nimport type {\n\tLoadingCompleteDetail,\n\tStageChangeDetail,\n} from \"@pie-players/pie-players-shared/pie\";\nimport type { FrameworkErrorModel } from \"../../services/framework-error.js\";\nimport type { ToolConfigStrictness } from \"../../services/tool-config-validation.js\";\n\nexport const DEFAULT_ASSESSMENT_ID = \"section-demo-direct\";\nexport const DEFAULT_PLAYER_TYPE = \"iife\";\nexport const DEFAULT_LAZY_INIT = true;\nexport const DEFAULT_ISOLATION = \"inherit\";\nexport const DEFAULT_ENV = { mode: \"gather\", role: \"student\" } as Record<\n\tstring,\n\tunknown\n>;\n\nexport type PlayerOverrides = {\n\tloaderConfig?: LoaderConfig;\n\tloaderOptions?: Record<string, unknown>;\n\t[key: string]: unknown;\n};\n\nexport type FrameworkErrorHandler = (model: FrameworkErrorModel) => void;\nexport type StageChangeHandler = (detail: StageChangeDetail) => void;\nexport type LoadingCompleteHandler = (detail: LoadingCompleteDetail) => void;\n\n/**\n * Section runtime config.\n *\n * Documented exceptions (no runtime mirror, by design): identity\n * (`section-id`, `attempt-id`, `section`); layout-only shell knobs\n * (`show-toolbar`, `toolbar-position`, etc.); and layout-shell host\n * data (`policies`, `hooks`, `toolRegistry`, `*HostButtons`). Those\n * surfaces are layout-shell concerns; the runtime engine does not see\n * them. See section-player's ARCHITECTURE.md for the full policy.\n */\nexport type RuntimeConfig = {\n\tassessmentId?: string;\n\tplayerType?: string;\n\tplayer?: PlayerOverrides | null;\n\tlazyInit?: boolean;\n\ttools?: Record<string, unknown> | null;\n\ttoolContextResolvers?: Record<string, unknown> | null;\n\taccessibility?: Record<string, unknown> | null;\n\tcoordinator?: unknown;\n\tcreateSectionController?: unknown;\n\tisolation?: string;\n\tenv?: Record<string, unknown>;\n\ttoolConfigStrictness?: ToolConfigStrictness;\n\n\t// Canonical framework-error callback.\n\tonFrameworkError?: FrameworkErrorHandler;\n\n\t// Canonical stage-change callback. The DOM event\n\t// `pie-stage-change` remains the primary channel; this callback is\n\t// the convenience surface that mirrors the event one-to-one.\n\tonStageChange?: StageChangeHandler;\n\n\t// Canonical loading-complete callback. Mirrors the\n\t// `pie-loading-complete` DOM event, which the engine dispatches\n\t// once per cohort when every item has finished loading.\n\tonLoadingComplete?: LoadingCompleteHandler;\n};\n\nexport type RuntimeInputs = {\n\tassessmentId?: string;\n\ttoolConfigStrictness?: ToolConfigStrictness;\n\tonFrameworkError?: FrameworkErrorHandler;\n\tonStageChange?: StageChangeHandler;\n\tonLoadingComplete?: LoadingCompleteHandler;\n\truntime: RuntimeConfig | null;\n};\n\n/**\n * Pick the runtime-tier value when defined, otherwise the prop/attribute\n * value. The strict mirror rule means every tier-1 surface is resolved\n * with this single helper; per-feature special-casing is forbidden.\n */\nfunction pick<T>(\n\truntimeVal: T | undefined,\n\tattrVal: T | undefined,\n): T | undefined {\n\treturn runtimeVal !== undefined ? runtimeVal : attrVal;\n}\n\n/**\n * Resolve the canonical `onFrameworkError` handler from the two-tier\n * surface. Precedence (highest first): `runtime.onFrameworkError`,\n * then top-level `onFrameworkError`. Layout CEs and the kernel call\n * this so every entry point converges on the same handler.\n */\nexport function resolveOnFrameworkError(args: {\n\truntime: RuntimeConfig | null;\n\tonFrameworkError?: FrameworkErrorHandler;\n}): FrameworkErrorHandler | undefined {\n\tconst r = args.runtime ?? {};\n\tif (r.onFrameworkError !== undefined) return r.onFrameworkError;\n\treturn args.onFrameworkError;\n}\n\nexport function resolveToolsConfig(args: { runtime: RuntimeConfig | null }) {\n\tconst runtimeTools = (args.runtime?.tools || {}) as Record<string, unknown>;\n\tconst placement = (runtimeTools.placement || {}) as Record<string, unknown>;\n\tconst overlayToolsConfig = { ...runtimeTools, placement: { ...placement } };\n\t// Keep host-provided shape intact; framework-owned validation surfaces malformed config.\n\treturn overlayToolsConfig;\n}\n\nexport function resolveRuntime(args: {\n\tassessmentId: string;\n\truntime: RuntimeConfig | null;\n\teffectiveToolsConfig: unknown;\n\ttoolConfigStrictness?: ToolConfigStrictness;\n\tonFrameworkError?: FrameworkErrorHandler;\n\tonStageChange?: StageChangeHandler;\n\tonLoadingComplete?: LoadingCompleteHandler;\n}) {\n\tconst r = args.runtime || {};\n\tconst runtimePlayer = r.player ? { ...r.player } : null;\n\treturn {\n\t\t...r,\n\t\tassessmentId: pick(r.assessmentId, args.assessmentId),\n\t\tplayerType: r.playerType ?? DEFAULT_PLAYER_TYPE,\n\t\tplayer: runtimePlayer,\n\t\tlazyInit: r.lazyInit ?? DEFAULT_LAZY_INIT,\n\t\taccessibility: r.accessibility ?? null,\n\t\tcoordinator: r.coordinator ?? null,\n\t\tcreateSectionController: r.createSectionController,\n\t\tisolation: r.isolation ?? DEFAULT_ISOLATION,\n\t\tenv: r.env ?? DEFAULT_ENV,\n\t\ttoolConfigStrictness:\n\t\t\tpick(r.toolConfigStrictness, args.toolConfigStrictness) ?? \"error\",\n\n\t\t// Runtime callback wins; top-level callback remains a layout CE event\n\t\t// convenience for hosts that do not use DOM listeners.\n\t\tonFrameworkError: resolveOnFrameworkError({\n\t\t\truntime: args.runtime,\n\t\t\tonFrameworkError: args.onFrameworkError,\n\t\t}),\n\n\t\t// Runtime callback wins over the top-level callback prop.\n\t\tonStageChange: pick(r.onStageChange, args.onStageChange),\n\n\t\t// Runtime callback wins over the top-level callback prop.\n\t\tonLoadingComplete: pick(r.onLoadingComplete, args.onLoadingComplete),\n\n\t\ttools: args.effectiveToolsConfig,\n\t};\n}\n\n/**\n * Effective runtime returned by `resolveRuntime`. The shape is exposed\n * as `unknown` at the public boundary because consumers spread it into\n * arbitrary host props; downstream call sites narrow with the specific\n * keys they need.\n */\nexport type EffectiveRuntime = ReturnType<typeof resolveRuntime>;\n\n/**\n * Engine-side orchestrator that powers `resolveSectionPlayerRuntimeState`\n * from section-player and takes\n * `resolvePlayerRuntime` as an injected callable so the toolkit core\n * stays free of host-coupled defaults (`DEFAULT_PLAYER_DEFINITIONS`).\n */\nexport function resolveSectionEngineRuntimeState<P>(\n\targs: RuntimeInputs,\n\tdeps: {\n\t\tresolvePlayerRuntime: (resolverArgs: {\n\t\t\teffectiveRuntime: Record<string, unknown>;\n\t\t\tplayerType: string;\n\t\t\tenv: Record<string, unknown> | null;\n\t\t}) => P;\n\t},\n): {\n\teffectiveToolsConfig: unknown;\n\teffectiveRuntime: EffectiveRuntime;\n\tplayerRuntime: P;\n} {\n\tconst assessmentId = args.assessmentId ?? DEFAULT_ASSESSMENT_ID;\n\n\tconst effectiveToolsConfig = resolveToolsConfig({\n\t\truntime: args.runtime,\n\t});\n\tconst effectiveRuntime = resolveRuntime({\n\t\tassessmentId,\n\t\truntime: args.runtime,\n\t\teffectiveToolsConfig,\n\t\ttoolConfigStrictness: args.toolConfigStrictness,\n\t\tonFrameworkError: args.onFrameworkError,\n\t\tonStageChange: args.onStageChange,\n\t\tonLoadingComplete: args.onLoadingComplete,\n\t});\n\tconst playerRuntime = deps.resolvePlayerRuntime({\n\t\teffectiveRuntime: effectiveRuntime as Record<string, unknown>,\n\t\tplayerType: String(effectiveRuntime.playerType ?? DEFAULT_PLAYER_TYPE),\n\t\tenv: (effectiveRuntime.env as Record<string, unknown> | null) ?? null,\n\t});\n\treturn {\n\t\teffectiveToolsConfig,\n\t\teffectiveRuntime,\n\t\tplayerRuntime,\n\t};\n}\n"]}
1
+ {"version":3,"file":"engine-resolver.js","sourceRoot":"","sources":["../../../src/runtime/core/engine-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAUH,MAAM,CAAC,MAAM,qBAAqB,GAAG,qBAAqB,CAAC;AAC3D,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAC1C,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AACtC,MAAM,CAAC,MAAM,iBAAiB,GAAG,SAAS,CAAC;AAC3C,MAAM,CAAC,MAAM,WAAW,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAG3D,CAAC;AAmEF;;;;GAIG;AACH,SAAS,IAAI,CACZ,UAAyB,EACzB,OAAsB;IAEtB,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC;AACxD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CAAC,IAGvC;IACA,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;IAC7B,IAAI,CAAC,C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AACH,CAAC","sourcesContent":["/**\n * Section runtime engine resolver (M7).\n *\n * Canonical home of `resolveRuntime`, `resolveToolsConfig`, and their\n * supporting helpers/types. As of M7 PR 7 the previous duplicates in\n * `packages/section-player/src/components/shared/section-player-runtime.ts`\n * have been deleted; section-player now consumes these helpers via\n * `@pie-players/pie-assessment-toolkit/runtime/internal`.\n *\n * What is NOT absorbed in this module:\n * - `resolvePlayerRuntime` stays in section-player because it depends on\n * `DEFAULT_PLAYER_DEFINITIONS` (which side-effect-imports the\n * item-player package). The toolkit core stays free of that\n * dependency by exposing a parametrized orchestrator —\n * `resolveSectionEngineRuntimeState` — that takes a `resolvePlayerRuntime`\n * callable. The section-player wrapper\n * (`resolveSectionPlayerRuntimeState` in\n * `packages/section-player/src/components/shared/section-player-host-runtime.ts`)\n * hands its local implementation in.\n *\n * Runtime-owned configuration flows through `runtime.<key>`. Layout-only\n * inputs stay on the section-player host elements.\n */\n\nimport type { LoaderConfig } from \"@pie-players/pie-players-shared/loader-config\";\nimport type {\n\tLoadingCompleteDetail,\n\tStageChangeDetail,\n} from \"@pie-players/pie-players-shared/pie\";\nimport type { FrameworkErrorModel } from \"../../services/framework-error.js\";\nimport type { ToolConfigStrictness } from \"../../services/tool-config-validation.js\";\n\nexport const DEFAULT_ASSESSMENT_ID = \"section-demo-direct\";\nexport const DEFAULT_PLAYER_TYPE = \"iife\";\nexport const DEFAULT_LAZY_INIT = true;\nexport const DEFAULT_ISOLATION = \"inherit\";\nexport const DEFAULT_ENV = { mode: \"gather\", role: \"student\" } as Record<\n\tstring,\n\tunknown\n>;\n\nexport type PlayerOverrides = {\n\tloaderConfig?: LoaderConfig;\n\tloaderOptions?: Record<string, unknown>;\n\t[key: string]: unknown;\n};\n\nexport type FrameworkErrorHandler = (model: FrameworkErrorModel) => void;\nexport type StageChangeHandler = (detail: StageChangeDetail) => void;\nexport type LoadingCompleteHandler = (detail: LoadingCompleteDetail) => void;\n\n/**\n * Section runtime config.\n *\n * Documented exceptions (no runtime mirror, by design): identity\n * (`section-id`, `attempt-id`, `section`); layout-only shell knobs\n * (`show-toolbar`, `toolbar-position`, etc.); and layout-shell host\n * data (`policies`, `hooks`, `toolRegistry`, `*HostButtons`). Those\n * surfaces are layout-shell concerns; the runtime engine does not see\n * them. See section-player's ARCHITECTURE.md for the full policy.\n */\nexport type RuntimeConfig = {\n\tassessmentId?: string;\n\tplayerType?: string;\n\tplayer?: PlayerOverrides | null;\n\tlazyInit?: boolean;\n\ttools?: Record<string, unknown> | null;\n\ttoolContextResolvers?: Record<string, unknown> | null;\n\taccessibility?: Record<string, unknown> | null;\n\tcoordinator?: unknown;\n\tcreateSectionController?: unknown;\n\tisolation?: string;\n\tenv?: Record<string, unknown>;\n\t/**\n\t * Presentation flag: opt-in to the vendored `<nds-icon-button>` for the\n\t * toolbar tool buttons, the calculator shell controls, inline-TTS\n\t * play/pause, and the section scroll-hint. NDS icons render only when\n\t * this is explicitly `true`; unset/`false` keeps the plain `<button>`\n\t * markup (the default). Purely visual — no engine effect.\n\t */\n\tndsIcons?: boolean;\n\ttoolConfigStrictness?: ToolConfigStrictness;\n\n\t// Canonical framework-error callback.\n\tonFrameworkError?: FrameworkErrorHandler;\n\n\t// Canonical stage-change callback. The DOM event\n\t// `pie-stage-change` remains the primary channel; this callback is\n\t// the convenience surface that mirrors the event one-to-one.\n\tonStageChange?: StageChangeHandler;\n\n\t// Canonical loading-complete callback. Mirrors the\n\t// `pie-loading-complete` DOM event, which the engine dispatches\n\t// once per cohort when every item has finished loading.\n\tonLoadingComplete?: LoadingCompleteHandler;\n};\n\nexport type RuntimeInputs = {\n\tassessmentId?: string;\n\ttoolConfigStrictness?: ToolConfigStrictness;\n\tonFrameworkError?: FrameworkErrorHandler;\n\tonStageChange?: StageChangeHandler;\n\tonLoadingComplete?: LoadingCompleteHandler;\n\truntime: RuntimeConfig | null;\n};\n\n/**\n * Pick the runtime-tier value when defined, otherwise the prop/attribute\n * value. The strict mirror rule means every tier-1 surface is resolved\n * with this single helper; per-feature special-casing is forbidden.\n */\nfunction pick<T>(\n\truntimeVal: T | undefined,\n\tattrVal: T | undefined,\n): T | undefined {\n\treturn runtimeVal !== undefined ? runtimeVal : attrVal;\n}\n\n/**\n * Resolve the canonical `onFrameworkError` handler from the two-tier\n * surface. Precedence (highest first): `runtime.onFrameworkError`,\n * then top-level `onFrameworkError`. Layout CEs and the kernel call\n * this so every entry point converges on the same handler.\n */\nexport function resolveOnFrameworkError(args: {\n\truntime: RuntimeConfig | null;\n\tonFrameworkError?: FrameworkErrorHandler;\n}): FrameworkErrorHandler | undefined {\n\tconst r = args.runtime ?? {};\n\tif (r.onFrameworkError !== undefined) return r.onFrameworkError;\n\treturn args.onFrameworkError;\n}\n\nexport function resolveToolsConfig(args: { runtime: RuntimeConfig | null }) {\n\tconst runtimeTools = (args.runtime?.tools || {}) as Record<string, unknown>;\n\tconst placement = (runtimeTools.placement || {}) as Record<string, unknown>;\n\tconst overlayToolsConfig = { ...runtimeTools, placement: { ...placement } };\n\t// Keep host-provided shape intact; framework-owned validation surfaces malformed config.\n\treturn overlayToolsConfig;\n}\n\nexport function resolveRuntime(args: {\n\tassessmentId: string;\n\truntime: RuntimeConfig | null;\n\teffectiveToolsConfig: unknown;\n\ttoolConfigStrictness?: ToolConfigStrictness;\n\tonFrameworkError?: FrameworkErrorHandler;\n\tonStageChange?: StageChangeHandler;\n\tonLoadingComplete?: LoadingCompleteHandler;\n}) {\n\tconst r = args.runtime || {};\n\tconst runtimePlayer = r.player ? { ...r.player } : null;\n\treturn {\n\t\t...r,\n\t\tassessmentId: pick(r.assessmentId, args.assessmentId),\n\t\tplayerType: r.playerType ?? DEFAULT_PLAYER_TYPE,\n\t\tplayer: runtimePlayer,\n\t\tlazyInit: r.lazyInit ?? DEFAULT_LAZY_INIT,\n\t\taccessibility: r.accessibility ?? null,\n\t\tcoordinator: r.coordinator ?? null,\n\t\tcreateSectionController: r.createSectionController,\n\t\tisolation: r.isolation ?? DEFAULT_ISOLATION,\n\t\tenv: r.env ?? DEFAULT_ENV,\n\t\ttoolConfigStrictness:\n\t\t\tpick(r.toolConfigStrictness, args.toolConfigStrictness) ?? \"error\",\n\n\t\t// Runtime callback wins; top-level callback remains a layout CE event\n\t\t// convenience for hosts that do not use DOM listeners.\n\t\tonFrameworkError: resolveOnFrameworkError({\n\t\t\truntime: args.runtime,\n\t\t\tonFrameworkError: args.onFrameworkError,\n\t\t}),\n\n\t\t// Runtime callback wins over the top-level callback prop.\n\t\tonStageChange: pick(r.onStageChange, args.onStageChange),\n\n\t\t// Runtime callback wins over the top-level callback prop.\n\t\tonLoadingComplete: pick(r.onLoadingComplete, args.onLoadingComplete),\n\n\t\ttools: args.effectiveToolsConfig,\n\t};\n}\n\n/**\n * Effective runtime returned by `resolveRuntime`. The shape is exposed\n * as `unknown` at the public boundary because consumers spread it into\n * arbitrary host props; downstream call sites narrow with the specific\n * keys they need.\n */\nexport type EffectiveRuntime = ReturnType<typeof resolveRuntime>;\n\n/**\n * Engine-side orchestrator that powers `resolveSectionPlayerRuntimeState`\n * from section-player and takes\n * `resolvePlayerRuntime` as an injected callable so the toolkit core\n * stays free of host-coupled defaults (`DEFAULT_PLAYER_DEFINITIONS`).\n */\nexport function resolveSectionEngineRuntimeState<P>(\n\targs: RuntimeInputs,\n\tdeps: {\n\t\tresolvePlayerRuntime: (resolverArgs: {\n\t\t\teffectiveRuntime: Record<string, unknown>;\n\t\t\tplayerType: string;\n\t\t\tenv: Record<string, unknown> | null;\n\t\t}) => P;\n\t},\n): {\n\teffectiveToolsConfig: unknown;\n\teffectiveRuntime: EffectiveRuntime;\n\tplayerRuntime: P;\n} {\n\tconst assessmentId = args.assessmentId ?? DEFAULT_ASSESSMENT_ID;\n\n\tconst effectiveToolsConfig = resolveToolsConfig({\n\t\truntime: args.runtime,\n\t});\n\tconst effectiveRuntime = resolveRuntime({\n\t\tassessmentId,\n\t\truntime: args.runtime,\n\t\teffectiveToolsConfig,\n\t\ttoolConfigStrictness: args.toolConfigStrictness,\n\t\tonFrameworkError: args.onFrameworkError,\n\t\tonStageChange: args.onStageChange,\n\t\tonLoadingComplete: args.onLoadingComplete,\n\t});\n\tconst playerRuntime = deps.resolvePlayerRuntime({\n\t\teffectiveRuntime: effectiveRuntime as Record<string, unknown>,\n\t\tplayerType: String(effectiveRuntime.playerType ?? DEFAULT_PLAYER_TYPE),\n\t\tenv: (effectiveRuntime.env as Record<string, unknown> | null) ?? null,\n\t});\n\treturn {\n\t\teffectiveToolsConfig,\n\t\teffectiveRuntime,\n\t\tplayerRuntime,\n\t};\n}\n"]}
@@ -33,6 +33,15 @@ export declare class ToolCoordinator implements ToolCoordinatorApi {
33
33
  private tools;
34
34
  private layerCounters;
35
35
  private listeners;
36
+ /**
37
+ * Activation (on/off) state keyed by tool id, kept independent of the
38
+ * element registration lifecycle. A tool's DOM element can be unregistered
39
+ * and re-registered as the item re-renders (e.g. a model change re-mounts
40
+ * the toolbar overlay); when that happens the on/off state must survive so
41
+ * that only an explicit toggle — the toolbar button — turns a tool off.
42
+ * Cleared on genuine teardown via {@link releaseTool}.
43
+ */
44
+ private visibilityState;
36
45
  constructor(config?: ToolCoordinatorConfig);
37
46
  /**
38
47
  * Subscribe to tool state changes
@@ -55,9 +64,24 @@ export declare class ToolCoordinator implements ToolCoordinatorApi {
55
64
  /**
56
65
  * Unregister a tool
57
66
  *
67
+ * Detaches the element binding (listeners, registration) but intentionally
68
+ * preserves the tool's activation state in {@link visibilityState}, so a
69
+ * subsequent re-registration of the same id (e.g. after an item re-render)
70
+ * restores whether the tool was on or off. Use {@link releaseTool} to also
71
+ * discard the activation state on genuine teardown.
72
+ *
58
73
  * @param id Tool identifier
59
74
  */
60
75
  unregisterTool(id: string): void;
76
+ /**
77
+ * Fully release a tool: unregister its element binding AND discard its
78
+ * preserved activation state. Call this on genuine teardown (e.g. leaving
79
+ * the item/section that owns the tool) rather than {@link unregisterTool},
80
+ * which keeps the on/off state alive across element re-registration.
81
+ *
82
+ * @param id Tool identifier
83
+ */
84
+ releaseTool(id: string): void;
61
85
  /**
62
86
  * Show a tool
63
87
  *
@@ -30,6 +30,15 @@ export class ToolCoordinator {
30
30
  tools = new Map();
31
31
  layerCounters = new Map();
32
32
  listeners = new Set();
33
+ /**
34
+ * Activation (on/off) state keyed by tool id, kept independent of the
35
+ * element registration lifecycle. A tool's DOM element can be unregistered
36
+ * and re-registered as the item re-renders (e.g. a model change re-mounts
37
+ * the toolbar overlay); when that happens the on/off state must survive so
38
+ * that only an explicit toggle — the toolbar button — turns a tool off.
39
+ * Cleared on genuine teardown via {@link releaseTool}.
40
+ */
41
+ visibilityState = new Map();
33
42
  constructor(config = {}) {
34
43
  this.config = config;
35
44
  // Initialize layer counters
@@ -69,6 +78,10 @@ export class ToolCoordinator {
69
78
  log(`Tool ${id} is already registered`);
70
79
  return;
71
80
  }
81
+ // Restore prior on/off state. A re-registration (e.g. after an item
82
+ // re-render unmounts and re-mounts the tool element) must preserve the
83
+ // tool's activation state so only an explicit toggle can turn it off.
84
+ const isVisible = this.visibilityState.get(id) ?? false;
72
85
  // If no element provided, create a placeholder registration
73
86
  if (!element) {
74
87
  this.tools.set(id, {
@@ -76,7 +89,7 @@ export class ToolCoordinator {
76
89
  name,
77
90
  element: null,
78
91
  layer,
79
- isVisible: false,
92
+ isVisible,
80
93
  baseZIndex: layer,
81
94
  });
82
95
  log("Tool registered without element:", id);
@@ -86,6 +99,8 @@ export class ToolCoordinator {
86
99
  const baseZIndex = layer + this.getNextLayerOffset(layer);
87
100
  // Apply z-index
88
101
  element.style.zIndex = String(baseZIndex);
102
+ // Reflect restored visibility onto the freshly registered element.
103
+ element.style.display = isVisible ? "" : "none";
89
104
  // Create and store event handler to enable proper cleanup
90
105
  const mouseDownHandler = () => this.bringToFront(element);
91
106
  element.addEventListener("mousedown", mouseDownHandler);
@@ -95,15 +110,24 @@ export class ToolCoordinator {
95
110
  name,
96
111
  element,
97
112
  layer,
98
- isVisible: false,
113
+ isVisible,
99
114
  baseZIndex,
100
115
  mouseDownHandler,
101
116
  });
117
+ if (isVisible) {
118
+ this.bringToFront(element);
119
+ }
102
120
  log("Tool registered with element:", id);
103
121
  }
104
122
  /**
105
123
  * Unregister a tool
106
124
  *
125
+ * Detaches the element binding (listeners, registration) but intentionally
126
+ * preserves the tool's activation state in {@link visibilityState}, so a
127
+ * subsequent re-registration of the same id (e.g. after an item re-render)
128
+ * restores whether the tool was on or off. Use {@link releaseTool} to also
129
+ * discard the activation state on genuine teardown.
130
+ *
107
131
  * @param id Tool identifier
108
132
  */
109
133
  unregisterTool(id) {
@@ -116,6 +140,18 @@ export class ToolCoordinator {
116
140
  }
117
141
  this.tools.delete(id);
118
142
  }
143
+ /**
144
+ * Fully release a tool: unregister its element binding AND discard its
145
+ * preserved activation state. Call this on genuine teardown (e.g. leaving
146
+ * the item/section that owns the tool) rather than {@link unregisterTool},
147
+ * which keeps the on/off state alive across element re-registration.
148
+ *
149
+ * @param id Tool identifier
150
+ */
151
+ releaseTool(id) {
152
+ this.unregisterTool(id);
153
+ this.visibilityState.delete(id);
154
+ }
119
155
  /**
120
156
  * Show a tool
121
157
  *
@@ -132,6 +168,7 @@ export class ToolCoordinator {
132
168
  this.bringToFront(tool.element);
133
169
  }
134
170
  tool.isVisible = true;
171
+ this.visibilityState.set(id, true);
135
172
  this.notifyListeners();
136
173
  }
137
174
  /**
@@ -149,6 +186,7 @@ export class ToolCoordinator {
149
186
  tool.element.style.display = "none";
150
187
  }
151
188
  tool.isVisible = false;
189
+ this.visibilityState.set(id, false);
152
190
  this.notifyListeners();
153
191
  }
154
192
  /**
@@ -179,7 +217,12 @@ export class ToolCoordinator {
179
217
  */
180
218
  isToolVisible(id) {
181
219
  const tool = this.tools.get(id);
182
- return tool?.isVisible ?? false;
220
+ if (tool)
221
+ return tool.isVisible;
222
+ // No live element registration (e.g. mid re-render, between unmount and
223
+ // re-mount): fall back to the preserved activation state so the tool
224
+ // doesn't read as "off" during the gap.
225
+ return this.visibilityState.get(id) ?? false;
183
226
  }
184
227
  /**
185
228
  * Bring element to front of its layer
@@ -1 +1 @@
1
- {"version":3,"file":"ToolCoordinator.js","sourceRoot":"","sources":["../../src/services/ToolCoordinator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD,MAAM,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAAC,CAAC;AAE5C;;GAEG;AACH,MAAM,CAAN,IAAY,WAMX;AAND,WAAY,WAAW;IACtB,6CAAQ,CAAA;IACR,gDAAW,CAAA;IACX,kDAAY,CAAA;IACZ,sDAAc,CAAA;IACd,0DAAgB,CAAA;AACjB,CAAC,EANW,WAAW,KAAX,WAAW,QAMtB;AAqBD,MAAM,OAAO,eAAe;IACnB,MAAM,CAAwB;IAC9B,KAAK,GAAG,IAAI,GAAG,EAA4B,CAAC;IAC5C,aAAa,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC/C,SAAS,GAAG,IAAI,GAAG,EAAc,CAAC;IAE1C,YAAY,SAAgC,EAAE;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,4BAA4B;QAC5B,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC5C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC5C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAC7C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;QAC/C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;IAClD,CAAC;IAED;;;OAGG;IACH,SAAS,CAAC,QAAoB;QAC7B,IAAI,CAAC,SAAS,CAAC,GAAG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YAC7B,KAAK,EAAE,IAAI,CAAC,KAAK;SACjB,CAAC,CAAC,CAAC;IACN,CAAC;CACD","sourcesContent":["/**\n * ToolCoordinator\n *\n * Manages z-index layering and visibility for floating tools.\n * Prevents conflicts between calculator, ruler, protractor, etc.\n *\n * Features:\n * - Centralized z-index management with defined layers\n * - Tool visibility state tracking\n * - Bring-to-front on interaction\n * - Framework-agnostic (works with any DOM element)\n *\n * Part of PIE Assessment Toolkit.\n */\n\nimport { createLogger } from \"../utils/logger.js\";\nimport type { ToolCoordinatorApi, ToolState } from \"./interfaces.js\";\n\nconst log = createLogger(\"ToolCoordinator\");\n\n/**\n * Z-index layers for assessment components\n */\nexport enum ZIndexLayer {\n\tBASE = 0, // PIE content, player chrome (0-999)\n\tTOOL = 1000, // Non-modal tools (ruler, protractor) (1000-1999)\n\tMODAL = 2000, // Modal tools (calculator) (2000-2999)\n\tCONTROL = 3000, // Drag handles, resize controls (3000-3999)\n\tHIGHLIGHT = 4000, // TTS and annotation highlights (4000-4999)\n}\n\n/**\n * Tool registration info\n */\ninterface ToolRegistration {\n\tid: string;\n\tname: string;\n\telement: HTMLElement | null;\n\tlayer: ZIndexLayer;\n\tisVisible: boolean;\n\tbaseZIndex: number;\n\tmouseDownHandler?: (e: MouseEvent) => void;\n}\n\n/**\n * Configuration for ToolCoordinator\n * Currently empty but allows future extension without breaking changes\n */\nexport type ToolCoordinatorConfig = Record<string, never>;\n\nexport class ToolCoordinator implements ToolCoordinatorApi {\n\tprivate config: ToolCoordinatorConfig;\n\tprivate tools = new Map<string, ToolRegistration>();\n\tprivate layerCounters = new Map<ZIndexLayer, number>();\n\tprivate listeners = new Set<() => void>();\n\n\tconstructor(config: ToolCoordinatorConfig = {}) {\n\t\tthis.config = config;\n\t\t// Initialize layer counters\n\t\tthis.layerCounters.set(ZIndexLayer.BASE, 0);\n\t\tthis.layerCounters.set(ZIndexLayer.TOOL, 0);\n\t\tthis.layerCounters.set(ZIndexLayer.MODAL, 0);\n\t\tthis.layerCounters.set(ZIndexLayer.CONTROL, 0);\n\t\tthis.layerCounters.set(ZIndexLayer.HIGHLIGHT, 0);\n\t}\n\n\t/**\n\t * Subscribe to tool state changes\n\t * Returns unsubscribe function\n\t */\n\tsubscribe(listener: () => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Notify all listeners of state change\n\t */\n\tprivate notifyListeners(): void {\n\t\tthis.listeners.forEach((listener) => listener());\n\t}\n\n\t/**\n\t * Register a tool with the coordinator\n\t *\n\t * @param id Unique tool identifier\n\t * @param name Display name\n\t * @param element DOM element for the tool (optional)\n\t * @param layer Z-index layer (defaults to MODAL)\n\t */\n\tregisterTool(\n\t\tid: string,\n\t\tname: string,\n\t\telement?: HTMLElement,\n\t\tlayer: ZIndexLayer = ZIndexLayer.MODAL,\n\t): void {\n\t\tlog(\"registerTool called:\", { id, name, hasElement: !!element, layer });\n\n\t\tif (this.tools.has(id)) {\n\t\t\tlog(`Tool ${id} is already registered`);\n\t\t\treturn;\n\t\t}\n\n\t\t// If no element provided, create a placeholder registration\n\t\tif (!element) {\n\t\t\tthis.tools.set(id, {\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\telement: null,\n\t\t\t\tlayer,\n\t\t\t\tisVisible: false,\n\t\t\t\tbaseZIndex: layer,\n\t\t\t});\n\t\t\tlog(\"Tool registered without element:\", id);\n\t\t\treturn;\n\t\t}\n\n\t\t// Calculate base z-index for this layer\n\t\tconst baseZIndex = layer + this.getNextLayerOffset(layer);\n\n\t\t// Apply z-index\n\t\telement.style.zIndex = String(baseZIndex);\n\n\t\t// Create and store event handler to enable proper cleanup\n\t\tconst mouseDownHandler = () => this.bringToFront(element);\n\t\telement.addEventListener(\"mousedown\", mouseDownHandler);\n\n\t\t// Register tool with handler reference\n\t\tthis.tools.set(id, {\n\t\t\tid,\n\t\t\tname,\n\t\t\telement,\n\t\t\tlayer,\n\t\t\tisVisible: false,\n\t\t\tbaseZIndex,\n\t\t\tmouseDownHandler,\n\t\t});\n\n\t\tlog(\"Tool registered with element:\", id);\n\t}\n\n\t/**\n\t * Unregister a tool\n\t *\n\t * @param id Tool identifier\n\t */\n\tunregisterTool(id: string): void {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) return;\n\n\t\t// Remove event listeners using stored handler reference\n\t\tif (tool.element && tool.mouseDownHandler) {\n\t\t\ttool.element.removeEventListener(\"mousedown\", tool.mouseDownHandler);\n\t\t}\n\n\t\tthis.tools.delete(id);\n\t}\n\n\t/**\n\t * Show a tool\n\t *\n\t * @param id Tool identifier\n\t */\n\tshowTool(id: string): void {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) {\n\t\t\tlog(`Tool ${id} not found`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (tool.element) {\n\t\t\ttool.element.style.display = \"\";\n\t\t\tthis.bringToFront(tool.element);\n\t\t}\n\t\ttool.isVisible = true;\n\t\tthis.notifyListeners();\n\t}\n\n\t/**\n\t * Hide a tool\n\t *\n\t * @param id Tool identifier\n\t */\n\thideTool(id: string): void {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) {\n\t\t\tlog(`Tool ${id} not found`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (tool.element) {\n\t\t\ttool.element.style.display = \"none\";\n\t\t}\n\t\ttool.isVisible = false;\n\t\tthis.notifyListeners();\n\t}\n\n\t/**\n\t * Toggle tool visibility\n\t *\n\t * @param id Tool identifier\n\t */\n\ttoggleTool(id: string): void {\n\t\tlog(\"toggleTool called for:\", id);\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) {\n\t\t\tlog(\n\t\t\t\t`Tool ${id} not found. Registered tools:`,\n\t\t\t\tArray.from(this.tools.keys()),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tlog(\"Tool found, current visibility:\", tool.isVisible);\n\t\tif (tool.isVisible) {\n\t\t\tthis.hideTool(id);\n\t\t} else {\n\t\t\tthis.showTool(id);\n\t\t}\n\t}\n\n\t/**\n\t * Check if tool is visible\n\t *\n\t * @param id Tool identifier\n\t * @returns true if tool is visible\n\t */\n\tisToolVisible(id: string): boolean {\n\t\tconst tool = this.tools.get(id);\n\t\treturn tool?.isVisible ?? false;\n\t}\n\n\t/**\n\t * Bring element to front of its layer\n\t *\n\t * @param element DOM element to bring forward\n\t */\n\tbringToFront(element: HTMLElement): void {\n\t\t// Find tool registration\n\t\tconst tool = Array.from(this.tools.values()).find(\n\t\t\t(t) => t.element === element,\n\t\t);\n\t\tif (!tool) return;\n\n\t\t// Calculate new z-index (highest in layer + 1)\n\t\tconst maxZIndexInLayer = this.getMaxZIndexInLayer(tool.layer);\n\t\tconst newZIndex = Math.max(maxZIndexInLayer + 1, tool.layer + 1);\n\n\t\t// Update z-index\n\t\telement.style.zIndex = String(newZIndex);\n\t\ttool.baseZIndex = newZIndex;\n\t}\n\n\t/**\n\t * Get all registered tool IDs\n\t */\n\tgetRegisteredTools(): string[] {\n\t\treturn Array.from(this.tools.keys());\n\t}\n\n\t/**\n\t * Get tool element by ID\n\t */\n\tgetToolElement(id: string): HTMLElement | null {\n\t\treturn this.tools.get(id)?.element ?? null;\n\t}\n\n\t/**\n\t * Get next offset within a layer\n\t */\n\tprivate getNextLayerOffset(layer: ZIndexLayer): number {\n\t\tconst current = this.layerCounters.get(layer) ?? 0;\n\t\tthis.layerCounters.set(layer, current + 1);\n\t\treturn current;\n\t}\n\n\t/**\n\t * Get maximum z-index currently in use in a layer\n\t */\n\tprivate getMaxZIndexInLayer(layer: ZIndexLayer): number {\n\t\tlet max = layer;\n\n\t\tfor (const tool of this.tools.values()) {\n\t\t\tif (tool.layer === layer) {\n\t\t\t\tmax = Math.max(max, tool.baseZIndex);\n\t\t\t}\n\t\t}\n\n\t\treturn max;\n\t}\n\n\t/**\n\t * Reset all tools to their base z-indices\n\t */\n\tresetZIndices(): void {\n\t\tfor (const tool of this.tools.values()) {\n\t\t\tif (tool.element) {\n\t\t\t\ttool.element.style.zIndex = String(tool.baseZIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Update tool element reference\n\t *\n\t * @param id Tool identifier\n\t * @param element New DOM element\n\t */\n\tupdateToolElement(id: string, element: HTMLElement): void {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) {\n\t\t\tlog(`Tool ${id} not found`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Remove old event listener using stored handler reference\n\t\tif (tool.element && tool.mouseDownHandler) {\n\t\t\ttool.element.removeEventListener(\"mousedown\", tool.mouseDownHandler);\n\t\t}\n\n\t\t// Create new handler and add listener\n\t\tconst mouseDownHandler = () => this.bringToFront(element);\n\t\telement.addEventListener(\"mousedown\", mouseDownHandler);\n\n\t\t// Update element and handler reference\n\t\ttool.element = element;\n\t\ttool.mouseDownHandler = mouseDownHandler;\n\n\t\t// Apply z-index to new element\n\t\telement.style.zIndex = String(tool.baseZIndex);\n\t\tif (tool.isVisible) {\n\t\t\telement.style.display = \"\";\n\t\t} else {\n\t\t\telement.style.display = \"none\";\n\t\t}\n\t}\n\n\t/**\n\t * Hide all tools\n\t */\n\thideAllTools(): void {\n\t\tfor (const id of this.tools.keys()) {\n\t\t\tthis.hideTool(id);\n\t\t}\n\t\tthis.notifyListeners();\n\t}\n\n\t/**\n\t * Get tool state (interface method)\n\t *\n\t * @param id Tool identifier\n\t * @returns Tool state or undefined\n\t */\n\tgetToolState(id: string): ToolState | undefined {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) return undefined;\n\n\t\treturn {\n\t\t\tid: tool.id,\n\t\t\tname: tool.name,\n\t\t\tisVisible: tool.isVisible,\n\t\t\telement: tool.element ?? null,\n\t\t\tlayer: tool.layer,\n\t\t};\n\t}\n\n\t/**\n\t * Get all visible tools (interface method)\n\t *\n\t * @returns Array of visible tool states\n\t */\n\tgetVisibleTools(): ToolState[] {\n\t\treturn Array.from(this.tools.values())\n\t\t\t.filter((tool) => tool.isVisible)\n\t\t\t.map((tool) => ({\n\t\t\t\tid: tool.id,\n\t\t\t\tname: tool.name,\n\t\t\t\tisVisible: tool.isVisible,\n\t\t\t\telement: tool.element ?? null,\n\t\t\t\tlayer: tool.layer,\n\t\t\t}));\n\t}\n}\n"]}
1
+ {"version":3,"file":"ToolCoordinator.js","sourceRoot":"","sources":["../../src/services/ToolCoordinator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD,MAAM,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAAC,CAAC;AAE5C;;GAEG;AACH,MAAM,CAAN,IAAY,WAMX;AAND,WAAY,WAAW;IACtB,6CAAQ,CAAA;IACR,gDAAW,CAAA;IACX,kDAAY,CAAA;IACZ,sDAAc,CAAA;IACd,0DAAgB,CAAA;AACjB,CAAC,EANW,WAAW,KAAX,WAAW,QAMtB;AAqBD,MAAM,OAAO,eAAe;IACnB,MAAM,CAAwB;IAC9B,KAAK,GAAG,IAAI,GAAG,EAA4B,CAAC;IAC5C,aAAa,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC/C,SAAS,GAAG,IAAI,GAAG,EAAc,CAAC;IAC1C;;;;;;;OAOG;IACK,eAAe,GAAG,IAAI,GAAG,EAAmB,CAAC;IAErD,YAAY,SAAgC,EAAE;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,4BAA4B;QAC5B,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC5C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC5C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAC7C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC,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AE,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC;YACpC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACnB,CAAC;QACD,IAAI,CAAC,eAAe,EAAE,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,YAAY,CAAC,EAAU;QACtB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChC,IAAI,CAAC,IAAI;YAAE,OAAO,SAAS,CAAC;QAE5B,OAAO;YACN,EAAE,EAAE,IAAI,CAAC,EAAE;YACX,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO,IAAI,IAAI;YAC7B,KAAK,EAAE,IAAI,CAAC,KAAK;SACjB,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,eAAe;QACd,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;aACpC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC;aAChC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACf,EAAE,EAAE,IAAI,CAAC,EAAE;YACX,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO,IAAI,IAAI;YAC7B,KAAK,EAAE,IAAI,CAAC,KAAK;SACjB,CAAC,CAAC,CAAC;IACN,CAAC;CACD","sourcesContent":["/**\n * ToolCoordinator\n *\n * Manages z-index layering and visibility for floating tools.\n * Prevents conflicts between calculator, ruler, protractor, etc.\n *\n * Features:\n * - Centralized z-index management with defined layers\n * - Tool visibility state tracking\n * - Bring-to-front on interaction\n * - Framework-agnostic (works with any DOM element)\n *\n * Part of PIE Assessment Toolkit.\n */\n\nimport { createLogger } from \"../utils/logger.js\";\nimport type { ToolCoordinatorApi, ToolState } from \"./interfaces.js\";\n\nconst log = createLogger(\"ToolCoordinator\");\n\n/**\n * Z-index layers for assessment components\n */\nexport enum ZIndexLayer {\n\tBASE = 0, // PIE content, player chrome (0-999)\n\tTOOL = 1000, // Non-modal tools (ruler, protractor) (1000-1999)\n\tMODAL = 2000, // Modal tools (calculator) (2000-2999)\n\tCONTROL = 3000, // Drag handles, resize controls (3000-3999)\n\tHIGHLIGHT = 4000, // TTS and annotation highlights (4000-4999)\n}\n\n/**\n * Tool registration info\n */\ninterface ToolRegistration {\n\tid: string;\n\tname: string;\n\telement: HTMLElement | null;\n\tlayer: ZIndexLayer;\n\tisVisible: boolean;\n\tbaseZIndex: number;\n\tmouseDownHandler?: (e: MouseEvent) => void;\n}\n\n/**\n * Configuration for ToolCoordinator\n * Currently empty but allows future extension without breaking changes\n */\nexport type ToolCoordinatorConfig = Record<string, never>;\n\nexport class ToolCoordinator implements ToolCoordinatorApi {\n\tprivate config: ToolCoordinatorConfig;\n\tprivate tools = new Map<string, ToolRegistration>();\n\tprivate layerCounters = new Map<ZIndexLayer, number>();\n\tprivate listeners = new Set<() => void>();\n\t/**\n\t * Activation (on/off) state keyed by tool id, kept independent of the\n\t * element registration lifecycle. A tool's DOM element can be unregistered\n\t * and re-registered as the item re-renders (e.g. a model change re-mounts\n\t * the toolbar overlay); when that happens the on/off state must survive so\n\t * that only an explicit toggle — the toolbar button — turns a tool off.\n\t * Cleared on genuine teardown via {@link releaseTool}.\n\t */\n\tprivate visibilityState = new Map<string, boolean>();\n\n\tconstructor(config: ToolCoordinatorConfig = {}) {\n\t\tthis.config = config;\n\t\t// Initialize layer counters\n\t\tthis.layerCounters.set(ZIndexLayer.BASE, 0);\n\t\tthis.layerCounters.set(ZIndexLayer.TOOL, 0);\n\t\tthis.layerCounters.set(ZIndexLayer.MODAL, 0);\n\t\tthis.layerCounters.set(ZIndexLayer.CONTROL, 0);\n\t\tthis.layerCounters.set(ZIndexLayer.HIGHLIGHT, 0);\n\t}\n\n\t/**\n\t * Subscribe to tool state changes\n\t * Returns unsubscribe function\n\t */\n\tsubscribe(listener: () => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Notify all listeners of state change\n\t */\n\tprivate notifyListeners(): void {\n\t\tthis.listeners.forEach((listener) => listener());\n\t}\n\n\t/**\n\t * Register a tool with the coordinator\n\t *\n\t * @param id Unique tool identifier\n\t * @param name Display name\n\t * @param element DOM element for the tool (optional)\n\t * @param layer Z-index layer (defaults to MODAL)\n\t */\n\tregisterTool(\n\t\tid: string,\n\t\tname: string,\n\t\telement?: HTMLElement,\n\t\tlayer: ZIndexLayer = ZIndexLayer.MODAL,\n\t): void {\n\t\tlog(\"registerTool called:\", { id, name, hasElement: !!element, layer });\n\n\t\tif (this.tools.has(id)) {\n\t\t\tlog(`Tool ${id} is already registered`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Restore prior on/off state. A re-registration (e.g. after an item\n\t\t// re-render unmounts and re-mounts the tool element) must preserve the\n\t\t// tool's activation state so only an explicit toggle can turn it off.\n\t\tconst isVisible = this.visibilityState.get(id) ?? false;\n\n\t\t// If no element provided, create a placeholder registration\n\t\tif (!element) {\n\t\t\tthis.tools.set(id, {\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\telement: null,\n\t\t\t\tlayer,\n\t\t\t\tisVisible,\n\t\t\t\tbaseZIndex: layer,\n\t\t\t});\n\t\t\tlog(\"Tool registered without element:\", id);\n\t\t\treturn;\n\t\t}\n\n\t\t// Calculate base z-index for this layer\n\t\tconst baseZIndex = layer + this.getNextLayerOffset(layer);\n\n\t\t// Apply z-index\n\t\telement.style.zIndex = String(baseZIndex);\n\n\t\t// Reflect restored visibility onto the freshly registered element.\n\t\telement.style.display = isVisible ? \"\" : \"none\";\n\n\t\t// Create and store event handler to enable proper cleanup\n\t\tconst mouseDownHandler = () => this.bringToFront(element);\n\t\telement.addEventListener(\"mousedown\", mouseDownHandler);\n\n\t\t// Register tool with handler reference\n\t\tthis.tools.set(id, {\n\t\t\tid,\n\t\t\tname,\n\t\t\telement,\n\t\t\tlayer,\n\t\t\tisVisible,\n\t\t\tbaseZIndex,\n\t\t\tmouseDownHandler,\n\t\t});\n\n\t\tif (isVisible) {\n\t\t\tthis.bringToFront(element);\n\t\t}\n\n\t\tlog(\"Tool registered with element:\", id);\n\t}\n\n\t/**\n\t * Unregister a tool\n\t *\n\t * Detaches the element binding (listeners, registration) but intentionally\n\t * preserves the tool's activation state in {@link visibilityState}, so a\n\t * subsequent re-registration of the same id (e.g. after an item re-render)\n\t * restores whether the tool was on or off. Use {@link releaseTool} to also\n\t * discard the activation state on genuine teardown.\n\t *\n\t * @param id Tool identifier\n\t */\n\tunregisterTool(id: string): void {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) return;\n\n\t\t// Remove event listeners using stored handler reference\n\t\tif (tool.element && tool.mouseDownHandler) {\n\t\t\ttool.element.removeEventListener(\"mousedown\", tool.mouseDownHandler);\n\t\t}\n\n\t\tthis.tools.delete(id);\n\t}\n\n\t/**\n\t * Fully release a tool: unregister its element binding AND discard its\n\t * preserved activation state. Call this on genuine teardown (e.g. leaving\n\t * the item/section that owns the tool) rather than {@link unregisterTool},\n\t * which keeps the on/off state alive across element re-registration.\n\t *\n\t * @param id Tool identifier\n\t */\n\treleaseTool(id: string): void {\n\t\tthis.unregisterTool(id);\n\t\tthis.visibilityState.delete(id);\n\t}\n\n\t/**\n\t * Show a tool\n\t *\n\t * @param id Tool identifier\n\t */\n\tshowTool(id: string): void {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) {\n\t\t\tlog(`Tool ${id} not found`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (tool.element) {\n\t\t\ttool.element.style.display = \"\";\n\t\t\tthis.bringToFront(tool.element);\n\t\t}\n\t\ttool.isVisible = true;\n\t\tthis.visibilityState.set(id, true);\n\t\tthis.notifyListeners();\n\t}\n\n\t/**\n\t * Hide a tool\n\t *\n\t * @param id Tool identifier\n\t */\n\thideTool(id: string): void {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) {\n\t\t\tlog(`Tool ${id} not found`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (tool.element) {\n\t\t\ttool.element.style.display = \"none\";\n\t\t}\n\t\ttool.isVisible = false;\n\t\tthis.visibilityState.set(id, false);\n\t\tthis.notifyListeners();\n\t}\n\n\t/**\n\t * Toggle tool visibility\n\t *\n\t * @param id Tool identifier\n\t */\n\ttoggleTool(id: string): void {\n\t\tlog(\"toggleTool called for:\", id);\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) {\n\t\t\tlog(\n\t\t\t\t`Tool ${id} not found. Registered tools:`,\n\t\t\t\tArray.from(this.tools.keys()),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tlog(\"Tool found, current visibility:\", tool.isVisible);\n\t\tif (tool.isVisible) {\n\t\t\tthis.hideTool(id);\n\t\t} else {\n\t\t\tthis.showTool(id);\n\t\t}\n\t}\n\n\t/**\n\t * Check if tool is visible\n\t *\n\t * @param id Tool identifier\n\t * @returns true if tool is visible\n\t */\n\tisToolVisible(id: string): boolean {\n\t\tconst tool = this.tools.get(id);\n\t\tif (tool) return tool.isVisible;\n\t\t// No live element registration (e.g. mid re-render, between unmount and\n\t\t// re-mount): fall back to the preserved activation state so the tool\n\t\t// doesn't read as \"off\" during the gap.\n\t\treturn this.visibilityState.get(id) ?? false;\n\t}\n\n\t/**\n\t * Bring element to front of its layer\n\t *\n\t * @param element DOM element to bring forward\n\t */\n\tbringToFront(element: HTMLElement): void {\n\t\t// Find tool registration\n\t\tconst tool = Array.from(this.tools.values()).find(\n\t\t\t(t) => t.element === element,\n\t\t);\n\t\tif (!tool) return;\n\n\t\t// Calculate new z-index (highest in layer + 1)\n\t\tconst maxZIndexInLayer = this.getMaxZIndexInLayer(tool.layer);\n\t\tconst newZIndex = Math.max(maxZIndexInLayer + 1, tool.layer + 1);\n\n\t\t// Update z-index\n\t\telement.style.zIndex = String(newZIndex);\n\t\ttool.baseZIndex = newZIndex;\n\t}\n\n\t/**\n\t * Get all registered tool IDs\n\t */\n\tgetRegisteredTools(): string[] {\n\t\treturn Array.from(this.tools.keys());\n\t}\n\n\t/**\n\t * Get tool element by ID\n\t */\n\tgetToolElement(id: string): HTMLElement | null {\n\t\treturn this.tools.get(id)?.element ?? null;\n\t}\n\n\t/**\n\t * Get next offset within a layer\n\t */\n\tprivate getNextLayerOffset(layer: ZIndexLayer): number {\n\t\tconst current = this.layerCounters.get(layer) ?? 0;\n\t\tthis.layerCounters.set(layer, current + 1);\n\t\treturn current;\n\t}\n\n\t/**\n\t * Get maximum z-index currently in use in a layer\n\t */\n\tprivate getMaxZIndexInLayer(layer: ZIndexLayer): number {\n\t\tlet max = layer;\n\n\t\tfor (const tool of this.tools.values()) {\n\t\t\tif (tool.layer === layer) {\n\t\t\t\tmax = Math.max(max, tool.baseZIndex);\n\t\t\t}\n\t\t}\n\n\t\treturn max;\n\t}\n\n\t/**\n\t * Reset all tools to their base z-indices\n\t */\n\tresetZIndices(): void {\n\t\tfor (const tool of this.tools.values()) {\n\t\t\tif (tool.element) {\n\t\t\t\ttool.element.style.zIndex = String(tool.baseZIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Update tool element reference\n\t *\n\t * @param id Tool identifier\n\t * @param element New DOM element\n\t */\n\tupdateToolElement(id: string, element: HTMLElement): void {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) {\n\t\t\tlog(`Tool ${id} not found`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Remove old event listener using stored handler reference\n\t\tif (tool.element && tool.mouseDownHandler) {\n\t\t\ttool.element.removeEventListener(\"mousedown\", tool.mouseDownHandler);\n\t\t}\n\n\t\t// Create new handler and add listener\n\t\tconst mouseDownHandler = () => this.bringToFront(element);\n\t\telement.addEventListener(\"mousedown\", mouseDownHandler);\n\n\t\t// Update element and handler reference\n\t\ttool.element = element;\n\t\ttool.mouseDownHandler = mouseDownHandler;\n\n\t\t// Apply z-index to new element\n\t\telement.style.zIndex = String(tool.baseZIndex);\n\t\tif (tool.isVisible) {\n\t\t\telement.style.display = \"\";\n\t\t} else {\n\t\t\telement.style.display = \"none\";\n\t\t}\n\t}\n\n\t/**\n\t * Hide all tools\n\t */\n\thideAllTools(): void {\n\t\tfor (const id of this.tools.keys()) {\n\t\t\tthis.hideTool(id);\n\t\t}\n\t\tthis.notifyListeners();\n\t}\n\n\t/**\n\t * Get tool state (interface method)\n\t *\n\t * @param id Tool identifier\n\t * @returns Tool state or undefined\n\t */\n\tgetToolState(id: string): ToolState | undefined {\n\t\tconst tool = this.tools.get(id);\n\t\tif (!tool) return undefined;\n\n\t\treturn {\n\t\t\tid: tool.id,\n\t\t\tname: tool.name,\n\t\t\tisVisible: tool.isVisible,\n\t\t\telement: tool.element ?? null,\n\t\t\tlayer: tool.layer,\n\t\t};\n\t}\n\n\t/**\n\t * Get all visible tools (interface method)\n\t *\n\t * @returns Array of visible tool states\n\t */\n\tgetVisibleTools(): ToolState[] {\n\t\treturn Array.from(this.tools.values())\n\t\t\t.filter((tool) => tool.isVisible)\n\t\t\t.map((tool) => ({\n\t\t\t\tid: tool.id,\n\t\t\t\tname: tool.name,\n\t\t\t\tisVisible: tool.isVisible,\n\t\t\t\telement: tool.element ?? null,\n\t\t\t\tlayer: tool.layer,\n\t\t\t}));\n\t}\n}\n"]}
@@ -125,9 +125,15 @@ export interface ToolCoordinatorApi {
125
125
  */
126
126
  registerTool(id: string, name: string, element?: HTMLElement, layer?: ZIndexLayer): void;
127
127
  /**
128
- * Unregister a tool
128
+ * Unregister a tool's element binding while preserving its activation
129
+ * (on/off) state, so a re-registration of the same id restores it.
129
130
  */
130
131
  unregisterTool(id: string): void;
132
+ /**
133
+ * Fully release a tool: unregister and discard its preserved activation
134
+ * state. Use on genuine teardown rather than `unregisterTool`.
135
+ */
136
+ releaseTool(id: string): void;
131
137
  /**
132
138
  * Show a tool
133
139
  */
@@ -1 +1 @@
1
- {"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/services/interfaces.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;;AAi2BH,0EAA0E","sourcesContent":["/**\n * Service Interfaces\n *\n * Public interfaces for all core assessment toolkit services.\n * These interfaces define the contracts that service implementations must fulfill,\n * enabling dependency injection, testing, and custom implementations.\n *\n * Part of PIE Assessment Toolkit.\n */\n\nimport type { I18nServiceApi } from \"@pie-players/pie-players-shared/i18n\";\nimport type {\n\tAccessibilityCatalogResolver,\n\tCatalogLookupContext,\n\tCatalogLookupOptions,\n\tCatalogOwnerContext,\n\tCatalogStatistics,\n\tCatalogType,\n\tResolvedCatalog,\n} from \"./AccessibilityCatalogResolver.js\";\nimport type { FrameworkErrorListener } from \"./framework-error-bus.js\";\nimport type { HighlightColor, HighlightType } from \"./HighlightCoordinator.js\";\nimport type {\n\tSectionControllerHandle,\n\tSectionItemEventSubscriptionArgs,\n\tSectionScopedEventSubscriptionArgs,\n\tSectionEventSubscriptionArgs,\n\tToolkitCoordinatorHooks,\n\tToolkitInitStatus,\n} from \"./ToolkitCoordinator.js\";\nimport type { FontSize, ThemeConfig } from \"./ThemeProvider.js\";\nimport type { ZIndexLayer } from \"./ToolCoordinator.js\";\nimport type { PlaybackState, TTSConfig } from \"./TTSService.js\";\nimport type { TTSHighlightTargetResolverProvider } from \"./tts/highlight-target-resolver.js\";\nimport type {\n\tToolPlacementConfig,\n\tToolPlacementLevel,\n\tToolProviderConfig,\n} from \"./tools-config-normalizer.js\";\nimport type { ToolProviderRegistry } from \"./tool-providers/ToolProviderRegistry.js\";\nimport type {\n\tPolicySource,\n\tPnpEnforcementMode,\n\tResolvedEngineInputs,\n\tToolPolicyChangeListener,\n\tToolPolicyDecision,\n\tToolPolicyDecisionRequest,\n} from \"../policy/engine.js\";\nimport type {\n\tAssessmentEntity,\n\tAssessmentItemRef,\n} from \"@pie-players/pie-players-shared/types\";\nimport type {\n\tITTSProvider,\n\tTTSProviderCapabilities,\n} from \"@pie-players/pie-tts\";\nimport type {\n\tResolvedToolContext,\n\tToolContextResolver,\n\tToolContextResolverContext,\n\tToolContextResolverMap,\n} from \"./ToolRegistry.js\";\n\n// Re-export I18nServiceApi from players-shared\nexport type { I18nServiceApi };\n\n/**\n * Theme provider interface\n *\n * Applies consistent accessibility theming across items and tools.\n */\nexport interface ThemeProviderApi {\n\t/**\n\t * Apply theme configuration\n\t */\n\tapplyTheme(config: ThemeConfig): void;\n\n\t/**\n\t * Get current theme configuration\n\t */\n\tgetCurrentTheme(): Required<ThemeConfig>;\n\n\t/**\n\t * Reset to default theme\n\t */\n\treset(): void;\n\n\t/**\n\t * Clean up and remove theme styles\n\t */\n\tdestroy(): void;\n}\n\n/**\n * Highlight coordinator interface\n *\n * Manages content highlighting for TTS, annotations, and selections.\n */\nexport interface HighlightCoordinatorApi {\n\t/**\n\t * Highlight a text range\n\t */\n\thighlightRange(\n\t\trange: Range,\n\t\ttype: HighlightType,\n\t\tcolor: HighlightColor,\n\t): void;\n\n\t/**\n\t * Highlight a word for TTS (temporary)\n\t */\n\thighlightTTSWord(\n\t\ttextNode: Text,\n\t\tstartOffset: number,\n\t\tendOffset: number,\n\t): void;\n\n\t/**\n\t * Highlight a single element as the active TTS word (temporary).\n\t *\n\t * Marks exactly the supplied element (via `data-pie-tts-word-element`)\n\t * without walking up to a containing ancestor. Used for atomic targets that\n\t * have no direct text node to range over — most notably MathJax CHTML tokens\n\t * (e.g. `<mjx-mi><mjx-c/></mjx-mi>`) and whole-expression fallbacks. Painting\n\t * the element itself is what lets a resolved math token highlight as a token\n\t * rather than escalating to the full `<math>` / `<mjx-container>`.\n\t *\n\t * Optional so lightweight coordinator mocks can omit it.\n\t */\n\thighlightTTSWordElement?(element: Element): void;\n\n\t/**\n\t * Highlight sentence(s) for TTS (background layer)\n\t */\n\thighlightTTSSentence(ranges: Range[]): void;\n\n\t/**\n\t * Highlight sentence/block element targets for TTS (background layer).\n\t *\n\t * Optional so lightweight coordinator mocks can omit it.\n\t */\n\thighlightTTSSentenceElements?(elements: Element[]): void;\n\n\t/**\n\t * Clear all TTS highlights (word and sentence)\n\t */\n\tclearTTS(): void;\n\n\t/**\n\t * Clear highlights of a specific type\n\t */\n\tclearHighlights(type: HighlightType): void;\n\n\t/**\n\t * Clear all highlights\n\t */\n\tclearAll(): void;\n\n\t/**\n\t * Check if highlighting is supported in current environment\n\t */\n\tisSupported(): boolean;\n\n\t/**\n\t * Update TTS highlight style dynamically\n\t */\n\tupdateTTSHighlightStyle(color: string, opacity: number): void;\n}\n\n/**\n * Tool state interface\n */\nexport interface ToolState {\n\tid: string;\n\tname: string;\n\tisVisible: boolean;\n\telement: HTMLElement | null;\n\tlayer: ZIndexLayer;\n}\n\n/**\n * Tool coordinator interface\n *\n * Manages z-index layering and visibility for floating tools.\n */\nexport interface ToolCoordinatorApi {\n\t/**\n\t * Register a tool with the coordinator\n\t */\n\tregisterTool(\n\t\tid: string,\n\t\tname: string,\n\t\telement?: HTMLElement,\n\t\tlayer?: ZIndexLayer,\n\t): void;\n\n\t/**\n\t * Unregister a tool\n\t */\n\tunregisterTool(id: string): void;\n\n\t/**\n\t * Show a tool\n\t */\n\tshowTool(id: string): void;\n\n\t/**\n\t * Hide a tool\n\t */\n\thideTool(id: string): void;\n\n\t/**\n\t * Toggle tool visibility\n\t */\n\ttoggleTool(id: string): void;\n\n\t/**\n\t * Check if tool is visible\n\t */\n\tisToolVisible(id: string): boolean;\n\n\t/**\n\t * Bring an element to the front of its layer\n\t */\n\tbringToFront(element: HTMLElement): void;\n\n\t/**\n\t * Update the element reference for a tool\n\t */\n\tupdateToolElement(id: string, element: HTMLElement): void;\n\n\t/**\n\t * Get state for a specific tool\n\t */\n\tgetToolState(id: string): ToolState | undefined;\n\n\t/**\n\t * Get all visible tools\n\t */\n\tgetVisibleTools(): ToolState[];\n\n\t/**\n\t * Subscribe to tool state changes\n\t */\n\tsubscribe(listener: () => void): () => void;\n}\n\n/**\n * TTS service interface\n *\n * Provides text-to-speech functionality with provider-based architecture.\n * Supports QTI 3.0 accessibility catalogs for pre-authored spoken content.\n */\nexport interface TtsServiceApi {\n\t/**\n\t * Initialize TTS with a provider\n\t */\n\tinitialize(\n\t\tprovider: ITTSProvider,\n\t\tconfig?: Partial<TTSConfig>,\n\t): Promise<void>;\n\n\t/**\n\t * Speak text with optional catalog support\n\t */\n\tspeak(\n\t\ttext: string,\n\t\toptions?: {\n\t\t\tcatalogId?: string;\n\t\t\tcatalogContext?: CatalogLookupContext;\n\t\t\tlanguage?: string;\n\t\t\tcontentElement?: Element;\n\t\t},\n\t): Promise<void>;\n\n\t/**\n\t * Speak a text range\n\t */\n\tspeakRange(\n\t\trange: Range,\n\t\toptions?: { contentRoot?: Element | null },\n\t): Promise<void>;\n\n\t/**\n\t * Pause playback\n\t */\n\tpause(): void;\n\n\t/**\n\t * Resume playback\n\t */\n\tresume(): void;\n\n\t/**\n\t * Stop playback\n\t */\n\tstop(): void;\n\n\t/**\n\t * Request active TTS controls to hand off/deactivate their UI state.\n\t *\n\t * This is an orchestration hint for TTS tool chrome and does not replace\n\t * playback controls such as stop/pause/resume.\n\t */\n\trequestControlHandoff(): void;\n\n\t/**\n\t * Seek forward by sentence units\n\t */\n\tseekForward(units?: number): Promise<void>;\n\n\t/**\n\t * Seek backward by sentence units\n\t */\n\tseekBackward(units?: number): Promise<void>;\n\n\t/**\n\t * Check if currently playing\n\t */\n\tisPlaying(): boolean;\n\n\t/**\n\t * Check if paused\n\t */\n\tisPaused(): boolean;\n\n\t/**\n\t * Get current playback state\n\t */\n\tgetState(): PlaybackState;\n\n\t/**\n\t * Get currently speaking text\n\t */\n\tgetCurrentText(): string | null;\n\n\t/**\n\t * Subscribe to state changes\n\t */\n\tonStateChange(id: string, callback: (state: PlaybackState) => void): void;\n\n\t/**\n\t * Unsubscribe from state changes\n\t */\n\toffStateChange(id: string, callback: (state: PlaybackState) => void): void;\n\n\t/**\n\t * Get capabilities of current provider\n\t */\n\tgetCapabilities(): TTSProviderCapabilities | null;\n\n\t/**\n\t * Update TTS settings dynamically (rate, pitch, voice)\n\t */\n\tupdateSettings(settings: Partial<TTSConfig>): Promise<void>;\n\n\t/**\n\t * Update playback speed and apply it to active planned playback.\n\t */\n\tsetPlaybackRate(rate: number): Promise<void>;\n\n\t/**\n\t * Set highlight coordinator for word highlighting\n\t */\n\tsetHighlightCoordinator(coordinator: HighlightCoordinatorApi): void;\n\n\t/**\n\t * Set a late-bound provider for optional host TTS highlight target remapping.\n\t */\n\tsetHighlightTargetResolverProvider?(\n\t\tprovider: TTSHighlightTargetResolverProvider | null,\n\t): () => void;\n\n\t/**\n\t * Set accessibility catalog resolver for spoken content\n\t */\n\tsetCatalogResolver(resolver: AccessibilityCatalogResolver): void;\n}\n\n/**\n * Accessibility catalog resolver interface\n *\n * Manages QTI 3.0 accessibility catalogs at assessment and item levels.\n * Provides lookup and resolution services for alternative content representations.\n */\nexport interface AccessibilityCatalogResolverApi {\n\t/**\n\t * Set the default language for fallback resolution\n\t */\n\tsetDefaultLanguage(language: string): void;\n\n\t/**\n\t * Get the default language\n\t */\n\tgetDefaultLanguage(): string;\n\n\t/**\n\t * Add item-level catalogs (called when rendering a new item)\n\t */\n\taddItemCatalogs(catalogs: any[]): void;\n\n\t/**\n\t * Register catalogs scoped to a mounted content owner.\n\t */\n\tregisterCatalogs?(context: CatalogOwnerContext, catalogs: any[]): () => void;\n\n\t/**\n\t * Clear item-level catalogs (called when leaving an item)\n\t */\n\tclearItemCatalogs(): void;\n\n\t/**\n\t * Check if a catalog exists\n\t */\n\thasCatalog(catalogId: string): boolean;\n\n\t/**\n\t * Get alternative content for a catalog identifier\n\t */\n\tgetAlternative(\n\t\tcatalogId: string,\n\t\toptions: CatalogLookupOptions,\n\t): ResolvedCatalog | null;\n\n\t/**\n\t * Get all available alternatives for a catalog identifier\n\t */\n\tgetAllAlternatives(catalogId: string): ResolvedCatalog[];\n\n\t/**\n\t * Get all catalog identifiers available\n\t */\n\tgetAllCatalogIds(): string[];\n\n\t/**\n\t * Get statistics about available catalogs\n\t */\n\tgetStatistics(): CatalogStatistics;\n\n\t/**\n\t * Check if a specific catalog type is available\n\t */\n\thasAlternativeType(catalogId: string, type: CatalogType): boolean;\n\n\t/**\n\t * Get all catalog IDs that have a specific type of alternative\n\t */\n\tgetCatalogsByType(type: CatalogType): string[];\n\n\t/**\n\t * Reset all catalogs\n\t */\n\treset(): void;\n\n\t/**\n\t * Destroy and cleanup\n\t */\n\tdestroy(): void;\n}\n\n/**\n * Element tool state store interface\n *\n * Manages element-level ephemeral tool state using composite keys for global uniqueness.\n * Tool state is client-only and separate from PIE session data (which is sent to server for scoring).\n */\nexport interface ElementToolStateStoreApi {\n\t/**\n\t * Generate a globally unique element ID from components\n\t */\n\tgetGlobalElementId(\n\t\tassessmentId: string,\n\t\tsectionId: string,\n\t\titemId: string,\n\t\telementId: string,\n\t): string;\n\n\t/**\n\t * Parse a global element ID into its components\n\t */\n\tparseGlobalElementId(globalElementId: string): {\n\t\tassessmentId: string;\n\t\tsectionId: string;\n\t\titemId: string;\n\t\telementId: string;\n\t} | null;\n\n\t/**\n\t * Set state for a specific tool on an element\n\t */\n\tsetState(globalElementId: string, toolId: string, state: any): void;\n\n\t/**\n\t * Get state for a specific tool on an element\n\t */\n\tgetState(globalElementId: string, toolId: string): any | undefined;\n\n\t/**\n\t * Get all tool states for a specific element\n\t */\n\tgetElementState(globalElementId: string): Record<string, any>;\n\n\t/**\n\t * Get all element states\n\t */\n\tgetAllState(): Record<string, Record<string, any>>;\n\n\t/**\n\t * Subscribe to state changes\n\t */\n\tsubscribe(\n\t\tcallback: (state: Map<string, Map<string, any>>) => void,\n\t): () => void;\n\n\t/**\n\t * Set callback for persistence integration\n\t */\n\tsetOnStateChange(\n\t\tcallback: (state: Record<string, Record<string, any>>) => void,\n\t): void;\n\n\t/**\n\t * Load state from persistence\n\t */\n\tloadState(state: Record<string, Record<string, any>>): void;\n\n\t/**\n\t * Clear state for a specific element\n\t */\n\tclearElement(globalElementId: string): void;\n\n\t/**\n\t * Clear state for a specific tool across all elements\n\t */\n\tclearTool(toolId: string): void;\n\n\t/**\n\t * Clear all elements in a specific section\n\t */\n\tclearSection(assessmentId: string, sectionId: string): void;\n\n\t/**\n\t * Clear all state\n\t */\n\tclearAll(): void;\n}\n\n/**\n * Toolkit coordinator interface\n *\n * Orchestrates all toolkit services (TTS, tools, accessibility, state management) from a single entry point.\n * Provides centralized configuration for tool availability and settings.\n */\nexport interface ToolkitCoordinatorApi {\n\t/**\n\t * Assessment identifier\n\t */\n\treadonly assessmentId: string;\n\n\t/**\n\t * Configuration\n\t */\n\treadonly config: {\n\t\ttools?: {\n\t\t\tproviders?: Record<string, ToolProviderConfig | undefined>;\n\t\t};\n\t};\n\n\t/**\n\t * TTS service\n\t */\n\treadonly ttsService: TtsServiceApi;\n\n\t/**\n\t * Tool coordinator\n\t */\n\treadonly toolCoordinator: ToolCoordinatorApi;\n\n\t/**\n\t * Highlight coordinator\n\t */\n\treadonly highlightCoordinator: HighlightCoordinatorApi;\n\n\t/**\n\t * Element tool state store\n\t */\n\treadonly elementToolStateStore: ElementToolStateStoreApi;\n\n\t/**\n\t * Catalog resolver\n\t */\n\treadonly catalogResolver: AccessibilityCatalogResolverApi;\n\n\t/**\n\t * Tool provider registry\n\t */\n\treadonly toolProviderRegistry: ToolProviderRegistry;\n\n\t/**\n\t * Get all services as a bundle\n\t */\n\tgetServiceBundle(): {\n\t\tttsService: TtsServiceApi;\n\t\ttoolCoordinator: ToolCoordinatorApi;\n\t\thighlightCoordinator: HighlightCoordinatorApi;\n\t\telementToolStateStore: ElementToolStateStoreApi;\n\t\tcatalogResolver: AccessibilityCatalogResolverApi;\n\t\ttoolProviderRegistry: ToolProviderRegistry;\n\t};\n\n\t/**\n\t * Ensure TTS service is initialized and ready.\n\t */\n\tensureTTSReady(config?: Record<string, unknown>): Promise<void>;\n\n\t/**\n\t * Ensure a provider is initialized and ready.\n\t */\n\tensureProviderReady(providerId: string): Promise<unknown>;\n\n\t/**\n\t * Wait until coordinator initialization is complete.\n\t */\n\twaitUntilReady(): Promise<void>;\n\n\t/**\n\t * Check if coordinator has completed initialization.\n\t */\n\tisReady(): boolean;\n\n\t/**\n\t * Read current initialization status.\n\t */\n\tgetInitStatus(): ToolkitInitStatus;\n\n\t/**\n\t * Check if a tool is enabled\n\t */\n\tisToolEnabled(toolId: string): boolean;\n\n\t/**\n\t * Get tool configuration\n\t */\n\tgetToolConfig(toolId: string): ToolProviderConfig | null;\n\n\t/**\n\t * Update tool configuration\n\t */\n\tupdateToolConfig(toolId: string, updates: Partial<ToolProviderConfig>): void;\n\n\t/**\n\t * Update the enabled tool list for one placement level.\n\t */\n\tupdateToolPlacement(level: ToolPlacementLevel, toolIds: string[]): void;\n\n\t/**\n\t * Patch one or more placement levels in the canonical tools config.\n\t */\n\tupdateToolsPlacement(partial: ToolPlacementConfig): void;\n\n\t/**\n\t * Register or update lifecycle hooks at runtime.\n\t */\n\tsetHooks(hooks: ToolkitCoordinatorHooks): void;\n\n\t/**\n\t * Return a section controller if already created.\n\t */\n\tgetSectionController(args: {\n\t\tsectionId: string;\n\t\tattemptId?: string;\n\t}): SectionControllerHandle | undefined;\n\n\t/**\n\t * Subscribe to section controller events.\n\t *\n\t * The listener is bound to the toolkit's *active section cohort* and\n\t * automatically migrates across cohort transitions\n\t * (`getOrCreateSectionController` for a different cohort). On every\n\t * migration the listener receives a snapshot replay of the new\n\t * cohort's already-loaded `content-loaded` events followed by the\n\t * aggregate `section-loading-complete`, in the canonical order a\n\t * fresh subscriber would have observed.\n\t *\n\t * Throws if no active section cohort exists; host code must call\n\t * `getOrCreateSectionController(...)` at least once before\n\t * subscribing. (`toolkit-ready` alone is not sufficient — it fires\n\t * once toolkit state has loaded but before any section controller\n\t * has been created.) The typical pattern is to subscribe once\n\t * immediately after the first `getOrCreateSectionController(...)`\n\t * resolves; the subscription then follows the active cohort across\n\t * all subsequent navigation without further wiring.\n\t *\n\t * Subscribing the same `listener` reference twice replaces the prior\n\t * subscription with the new one (filter args from the second call\n\t * win); calling the returned disposer twice is a no-op.\n\t *\n\t * A listener that throws is caught and `console.warn`-logged; the\n\t * throw does not interrupt fan-out to the remaining listeners.\n\t */\n\tsubscribeSectionEvents(args: SectionEventSubscriptionArgs): () => void;\n\n\t/**\n\t * Subscribe to item-scoped section controller events.\n\t *\n\t * Same active-cohort binding contract as {@link subscribeSectionEvents};\n\t * defaults `eventTypes` to the item-scoped subset.\n\t */\n\tsubscribeItemEvents(args: SectionItemEventSubscriptionArgs): () => void;\n\n\t/**\n\t * Subscribe to section-scoped lifecycle/loading/completion/error events.\n\t *\n\t * Same active-cohort binding contract as {@link subscribeSectionEvents};\n\t * defaults `eventTypes` to the section-scoped subset.\n\t */\n\tsubscribeSectionLifecycleEvents(\n\t\targs: SectionScopedEventSubscriptionArgs,\n\t): () => void;\n\n\t/**\n\t * Create or reuse a section controller with single-flight deduplication.\n\t */\n\tgetOrCreateSectionController(args: {\n\t\tsectionId: string;\n\t\tattemptId?: string;\n\t\tinput?: unknown;\n\t\tupdateExisting?: boolean;\n\t\tcreateDefaultController: () =>\n\t\t\t| SectionControllerHandle\n\t\t\t| Promise<SectionControllerHandle>;\n\t}): Promise<SectionControllerHandle>;\n\n\t/**\n\t * Dispose an existing section controller.\n\t */\n\tdisposeSectionController(args: {\n\t\tsectionId: string;\n\t\tattemptId?: string;\n\t\tpersistBeforeDispose?: boolean;\n\t\tclearPersistence?: boolean;\n\t}): Promise<void>;\n\n\t/**\n\t * Subscribe to framework-error events emitted by the coordinator.\n\t *\n\t * Mirrors the shape of {@link subscribeTelemetry} (see\n\t * `ToolkitCoordinator.subscribeTelemetry`): a synchronous,\n\t * multi-subscriber stream where each call to the internal bus's\n\t * `reportFrameworkError` fans out to every active listener exactly once.\n\t *\n\t * The returned function detaches the listener; calling it twice is a\n\t * no-op. A listener that throws is caught and logged; the throw does\n\t * not break fan-out to the remaining listeners.\n\t *\n\t * Use this to wire framework errors into Sentry / Datadog / a custom\n\t * banner without listening on a DOM event. The DOM event\n\t * (`framework-error`) and the canonical `onFrameworkError` prop on\n\t * `<pie-assessment-toolkit>` consume the same bus.\n\t */\n\tsubscribeFrameworkErrors(listener: FrameworkErrorListener): () => void;\n\n\t// ----------------------------------------------------------------\n\t// Tool Policy Engine — public surface (M8 PR 2 / PR 3).\n\t//\n\t// The coordinator owns a single `ToolPolicyEngine` instance and\n\t// exposes its decision and subscription surface through the API\n\t// so that toolbar custom elements (`pie-item-toolbar`,\n\t// `pie-section-toolbar`), the base section player, and bespoke\n\t// host instrumentation (PNP debugger, etc.) all flow through the\n\t// same engine. Hosts that want to drive PNP/profile inputs imperatively\n\t// (instead of binding props on `<pie-assessment-toolkit>`) call\n\t// `updateAssessment` / `updateCurrentItemRef` /\n\t// `setPnpEnforcement` directly.\n\t// ----------------------------------------------------------------\n\n\t/**\n\t * Resolve the visible tool set for a given placement level + scope.\n\t * Returns the engine's full decision (visible tools, diagnostics,\n\t * provenance). Hosts that only need the IDs may map\n\t * `decision.visibleTools` themselves.\n\t */\n\tdecideToolPolicy(request: ToolPolicyDecisionRequest): ToolPolicyDecision;\n\n\t/**\n\t * Subscribe to policy-engine change events. Fires whenever the\n\t * coordinator's bound policy inputs change (`updateToolConfig`,\n\t * `updateToolPlacement`, `updateAssessment`, `updateCurrentItemRef`,\n\t * `setPnpEnforcement`) or a custom `PolicySource` is registered /\n\t * removed. Listeners that need the new visible tool set should\n\t * call `decideToolPolicy(...)` with their level / scope.\n\t */\n\tonPolicyChange(listener: ToolPolicyChangeListener): () => void;\n\n\t/**\n\t * Bind (or clear) the active assessment for PNP/profile policy decisions.\n\t *\n\t * Under auto-mode (no host override via {@link setPnpEnforcement}),\n\t * the engine flips to `pnpEnforcement: \"on\"` iff the assessment\n\t * carries profile precedence material (`personalNeedsProfile`,\n\t * `settings.districtPolicy`, `settings.testAdministration`) or the\n\t * currently-bound item ref carries item-level profile inputs. A bare\n\t * assessment record (just `id` / `name`) keeps `\"off\"`.\n\t *\n\t * The host override set via {@link setPnpEnforcement} is sticky\n\t * across assessment swaps.\n\t */\n\tupdateAssessment(assessment: AssessmentEntity | null): void;\n\n\t/**\n\t * Bind (or clear) the current item reference for policy decisions.\n\t * Used by item-level profile gates (item `requiredTools` /\n\t * `restrictedTools` / `toolParameters`). Item-level profile material\n\t * also feeds the auto-mode helper — navigating to an item with\n\t * profile settings can flip auto-mode to `\"on\"` even when the parent\n\t * assessment carries no profile block of its own.\n\t */\n\tupdateCurrentItemRef(itemRef: AssessmentItemRef | null): void;\n\n\t/**\n\t * Override the auto-mode PNP/profile enforcement decision. Pass `\"on\"` /\n\t * `\"off\"` to pin the mode, or `null` to clear the override and\n\t * return to auto-mode (`\"on\"` iff the bound assessment / item ref\n\t * carries profile material, otherwise `\"off\"`).\n\t */\n\tsetPnpEnforcement(mode: PnpEnforcementMode | null): void;\n\n\t/**\n\t * Read the engine inputs currently driving decisions. Useful for\n\t * debugging / instrumentation; do not mutate.\n\t */\n\tgetPolicyInputs(): Readonly<ResolvedEngineInputs>;\n\n\t/**\n\t * Register a custom `PolicySource`. The source participates in\n\t * every subsequent `decideToolPolicy(...)` call until disposed\n\t * (the returned function detaches).\n\t */\n\tregisterPolicySource(source: PolicySource): () => void;\n\n\t/**\n\t * Register a host-owned resolver for scoped tool render context.\n\t */\n\tregisterToolContextResolver(\n\t\ttoolId: string,\n\t\tresolver: ToolContextResolver,\n\t): () => void;\n\n\t/**\n\t * Replace all host-owned render-context resolvers.\n\t */\n\tsetToolContextResolvers(\n\t\tresolvers: ToolContextResolverMap | null | undefined,\n\t): void;\n\n\t/**\n\t * Whether a host resolver is registered for this tool.\n\t */\n\thasToolContextResolver(toolId: string): boolean;\n\n\t/**\n\t * Resolve render visibility/params for a tool that already survived policy gates.\n\t */\n\tresolveToolContext(\n\t\tcontext: ToolContextResolverContext,\n\t): ResolvedToolContext | null;\n\n\t/**\n\t * Subscribe to resolver registration/removal changes.\n\t */\n\tonToolContextResolverChange(listener: () => void): () => void;\n}\n\n// I18nServiceApi is re-exported from @pie-players/pie-players-shared/i18n\n"]}
1
+ {"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/services/interfaces.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;;AAw2BH,0EAA0E","sourcesContent":["/**\n * Service Interfaces\n *\n * Public interfaces for all core assessment toolkit services.\n * These interfaces define the contracts that service implementations must fulfill,\n * enabling dependency injection, testing, and custom implementations.\n *\n * Part of PIE Assessment Toolkit.\n */\n\nimport type { I18nServiceApi } from \"@pie-players/pie-players-shared/i18n\";\nimport type {\n\tAccessibilityCatalogResolver,\n\tCatalogLookupContext,\n\tCatalogLookupOptions,\n\tCatalogOwnerContext,\n\tCatalogStatistics,\n\tCatalogType,\n\tResolvedCatalog,\n} from \"./AccessibilityCatalogResolver.js\";\nimport type { FrameworkErrorListener } from \"./framework-error-bus.js\";\nimport type { HighlightColor, HighlightType } from \"./HighlightCoordinator.js\";\nimport type {\n\tSectionControllerHandle,\n\tSectionItemEventSubscriptionArgs,\n\tSectionScopedEventSubscriptionArgs,\n\tSectionEventSubscriptionArgs,\n\tToolkitCoordinatorHooks,\n\tToolkitInitStatus,\n} from \"./ToolkitCoordinator.js\";\nimport type { FontSize, ThemeConfig } from \"./ThemeProvider.js\";\nimport type { ZIndexLayer } from \"./ToolCoordinator.js\";\nimport type { PlaybackState, TTSConfig } from \"./TTSService.js\";\nimport type { TTSHighlightTargetResolverProvider } from \"./tts/highlight-target-resolver.js\";\nimport type {\n\tToolPlacementConfig,\n\tToolPlacementLevel,\n\tToolProviderConfig,\n} from \"./tools-config-normalizer.js\";\nimport type { ToolProviderRegistry } from \"./tool-providers/ToolProviderRegistry.js\";\nimport type {\n\tPolicySource,\n\tPnpEnforcementMode,\n\tResolvedEngineInputs,\n\tToolPolicyChangeListener,\n\tToolPolicyDecision,\n\tToolPolicyDecisionRequest,\n} from \"../policy/engine.js\";\nimport type {\n\tAssessmentEntity,\n\tAssessmentItemRef,\n} from \"@pie-players/pie-players-shared/types\";\nimport type {\n\tITTSProvider,\n\tTTSProviderCapabilities,\n} from \"@pie-players/pie-tts\";\nimport type {\n\tResolvedToolContext,\n\tToolContextResolver,\n\tToolContextResolverContext,\n\tToolContextResolverMap,\n} from \"./ToolRegistry.js\";\n\n// Re-export I18nServiceApi from players-shared\nexport type { I18nServiceApi };\n\n/**\n * Theme provider interface\n *\n * Applies consistent accessibility theming across items and tools.\n */\nexport interface ThemeProviderApi {\n\t/**\n\t * Apply theme configuration\n\t */\n\tapplyTheme(config: ThemeConfig): void;\n\n\t/**\n\t * Get current theme configuration\n\t */\n\tgetCurrentTheme(): Required<ThemeConfig>;\n\n\t/**\n\t * Reset to default theme\n\t */\n\treset(): void;\n\n\t/**\n\t * Clean up and remove theme styles\n\t */\n\tdestroy(): void;\n}\n\n/**\n * Highlight coordinator interface\n *\n * Manages content highlighting for TTS, annotations, and selections.\n */\nexport interface HighlightCoordinatorApi {\n\t/**\n\t * Highlight a text range\n\t */\n\thighlightRange(\n\t\trange: Range,\n\t\ttype: HighlightType,\n\t\tcolor: HighlightColor,\n\t): void;\n\n\t/**\n\t * Highlight a word for TTS (temporary)\n\t */\n\thighlightTTSWord(\n\t\ttextNode: Text,\n\t\tstartOffset: number,\n\t\tendOffset: number,\n\t): void;\n\n\t/**\n\t * Highlight a single element as the active TTS word (temporary).\n\t *\n\t * Marks exactly the supplied element (via `data-pie-tts-word-element`)\n\t * without walking up to a containing ancestor. Used for atomic targets that\n\t * have no direct text node to range over — most notably MathJax CHTML tokens\n\t * (e.g. `<mjx-mi><mjx-c/></mjx-mi>`) and whole-expression fallbacks. Painting\n\t * the element itself is what lets a resolved math token highlight as a token\n\t * rather than escalating to the full `<math>` / `<mjx-container>`.\n\t *\n\t * Optional so lightweight coordinator mocks can omit it.\n\t */\n\thighlightTTSWordElement?(element: Element): void;\n\n\t/**\n\t * Highlight sentence(s) for TTS (background layer)\n\t */\n\thighlightTTSSentence(ranges: Range[]): void;\n\n\t/**\n\t * Highlight sentence/block element targets for TTS (background layer).\n\t *\n\t * Optional so lightweight coordinator mocks can omit it.\n\t */\n\thighlightTTSSentenceElements?(elements: Element[]): void;\n\n\t/**\n\t * Clear all TTS highlights (word and sentence)\n\t */\n\tclearTTS(): void;\n\n\t/**\n\t * Clear highlights of a specific type\n\t */\n\tclearHighlights(type: HighlightType): void;\n\n\t/**\n\t * Clear all highlights\n\t */\n\tclearAll(): void;\n\n\t/**\n\t * Check if highlighting is supported in current environment\n\t */\n\tisSupported(): boolean;\n\n\t/**\n\t * Update TTS highlight style dynamically\n\t */\n\tupdateTTSHighlightStyle(color: string, opacity: number): void;\n}\n\n/**\n * Tool state interface\n */\nexport interface ToolState {\n\tid: string;\n\tname: string;\n\tisVisible: boolean;\n\telement: HTMLElement | null;\n\tlayer: ZIndexLayer;\n}\n\n/**\n * Tool coordinator interface\n *\n * Manages z-index layering and visibility for floating tools.\n */\nexport interface ToolCoordinatorApi {\n\t/**\n\t * Register a tool with the coordinator\n\t */\n\tregisterTool(\n\t\tid: string,\n\t\tname: string,\n\t\telement?: HTMLElement,\n\t\tlayer?: ZIndexLayer,\n\t): void;\n\n\t/**\n\t * Unregister a tool's element binding while preserving its activation\n\t * (on/off) state, so a re-registration of the same id restores it.\n\t */\n\tunregisterTool(id: string): void;\n\n\t/**\n\t * Fully release a tool: unregister and discard its preserved activation\n\t * state. Use on genuine teardown rather than `unregisterTool`.\n\t */\n\treleaseTool(id: string): void;\n\n\t/**\n\t * Show a tool\n\t */\n\tshowTool(id: string): void;\n\n\t/**\n\t * Hide a tool\n\t */\n\thideTool(id: string): void;\n\n\t/**\n\t * Toggle tool visibility\n\t */\n\ttoggleTool(id: string): void;\n\n\t/**\n\t * Check if tool is visible\n\t */\n\tisToolVisible(id: string): boolean;\n\n\t/**\n\t * Bring an element to the front of its layer\n\t */\n\tbringToFront(element: HTMLElement): void;\n\n\t/**\n\t * Update the element reference for a tool\n\t */\n\tupdateToolElement(id: string, element: HTMLElement): void;\n\n\t/**\n\t * Get state for a specific tool\n\t */\n\tgetToolState(id: string): ToolState | undefined;\n\n\t/**\n\t * Get all visible tools\n\t */\n\tgetVisibleTools(): ToolState[];\n\n\t/**\n\t * Subscribe to tool state changes\n\t */\n\tsubscribe(listener: () => void): () => void;\n}\n\n/**\n * TTS service interface\n *\n * Provides text-to-speech functionality with provider-based architecture.\n * Supports QTI 3.0 accessibility catalogs for pre-authored spoken content.\n */\nexport interface TtsServiceApi {\n\t/**\n\t * Initialize TTS with a provider\n\t */\n\tinitialize(\n\t\tprovider: ITTSProvider,\n\t\tconfig?: Partial<TTSConfig>,\n\t): Promise<void>;\n\n\t/**\n\t * Speak text with optional catalog support\n\t */\n\tspeak(\n\t\ttext: string,\n\t\toptions?: {\n\t\t\tcatalogId?: string;\n\t\t\tcatalogContext?: CatalogLookupContext;\n\t\t\tlanguage?: string;\n\t\t\tcontentElement?: Element;\n\t\t},\n\t): Promise<void>;\n\n\t/**\n\t * Speak a text range\n\t */\n\tspeakRange(\n\t\trange: Range,\n\t\toptions?: { contentRoot?: Element | null },\n\t): Promise<void>;\n\n\t/**\n\t * Pause playback\n\t */\n\tpause(): void;\n\n\t/**\n\t * Resume playback\n\t */\n\tresume(): void;\n\n\t/**\n\t * Stop playback\n\t */\n\tstop(): void;\n\n\t/**\n\t * Request active TTS controls to hand off/deactivate their UI state.\n\t *\n\t * This is an orchestration hint for TTS tool chrome and does not replace\n\t * playback controls such as stop/pause/resume.\n\t */\n\trequestControlHandoff(): void;\n\n\t/**\n\t * Seek forward by sentence units\n\t */\n\tseekForward(units?: number): Promise<void>;\n\n\t/**\n\t * Seek backward by sentence units\n\t */\n\tseekBackward(units?: number): Promise<void>;\n\n\t/**\n\t * Check if currently playing\n\t */\n\tisPlaying(): boolean;\n\n\t/**\n\t * Check if paused\n\t */\n\tisPaused(): boolean;\n\n\t/**\n\t * Get current playback state\n\t */\n\tgetState(): PlaybackState;\n\n\t/**\n\t * Get currently speaking text\n\t */\n\tgetCurrentText(): string | null;\n\n\t/**\n\t * Subscribe to state changes\n\t */\n\tonStateChange(id: string, callback: (state: PlaybackState) => void): void;\n\n\t/**\n\t * Unsubscribe from state changes\n\t */\n\toffStateChange(id: string, callback: (state: PlaybackState) => void): void;\n\n\t/**\n\t * Get capabilities of current provider\n\t */\n\tgetCapabilities(): TTSProviderCapabilities | null;\n\n\t/**\n\t * Update TTS settings dynamically (rate, pitch, voice)\n\t */\n\tupdateSettings(settings: Partial<TTSConfig>): Promise<void>;\n\n\t/**\n\t * Update playback speed and apply it to active planned playback.\n\t */\n\tsetPlaybackRate(rate: number): Promise<void>;\n\n\t/**\n\t * Set highlight coordinator for word highlighting\n\t */\n\tsetHighlightCoordinator(coordinator: HighlightCoordinatorApi): void;\n\n\t/**\n\t * Set a late-bound provider for optional host TTS highlight target remapping.\n\t */\n\tsetHighlightTargetResolverProvider?(\n\t\tprovider: TTSHighlightTargetResolverProvider | null,\n\t): () => void;\n\n\t/**\n\t * Set accessibility catalog resolver for spoken content\n\t */\n\tsetCatalogResolver(resolver: AccessibilityCatalogResolver): void;\n}\n\n/**\n * Accessibility catalog resolver interface\n *\n * Manages QTI 3.0 accessibility catalogs at assessment and item levels.\n * Provides lookup and resolution services for alternative content representations.\n */\nexport interface AccessibilityCatalogResolverApi {\n\t/**\n\t * Set the default language for fallback resolution\n\t */\n\tsetDefaultLanguage(language: string): void;\n\n\t/**\n\t * Get the default language\n\t */\n\tgetDefaultLanguage(): string;\n\n\t/**\n\t * Add item-level catalogs (called when rendering a new item)\n\t */\n\taddItemCatalogs(catalogs: any[]): void;\n\n\t/**\n\t * Register catalogs scoped to a mounted content owner.\n\t */\n\tregisterCatalogs?(context: CatalogOwnerContext, catalogs: any[]): () => void;\n\n\t/**\n\t * Clear item-level catalogs (called when leaving an item)\n\t */\n\tclearItemCatalogs(): void;\n\n\t/**\n\t * Check if a catalog exists\n\t */\n\thasCatalog(catalogId: string): boolean;\n\n\t/**\n\t * Get alternative content for a catalog identifier\n\t */\n\tgetAlternative(\n\t\tcatalogId: string,\n\t\toptions: CatalogLookupOptions,\n\t): ResolvedCatalog | null;\n\n\t/**\n\t * Get all available alternatives for a catalog identifier\n\t */\n\tgetAllAlternatives(catalogId: string): ResolvedCatalog[];\n\n\t/**\n\t * Get all catalog identifiers available\n\t */\n\tgetAllCatalogIds(): string[];\n\n\t/**\n\t * Get statistics about available catalogs\n\t */\n\tgetStatistics(): CatalogStatistics;\n\n\t/**\n\t * Check if a specific catalog type is available\n\t */\n\thasAlternativeType(catalogId: string, type: CatalogType): boolean;\n\n\t/**\n\t * Get all catalog IDs that have a specific type of alternative\n\t */\n\tgetCatalogsByType(type: CatalogType): string[];\n\n\t/**\n\t * Reset all catalogs\n\t */\n\treset(): void;\n\n\t/**\n\t * Destroy and cleanup\n\t */\n\tdestroy(): void;\n}\n\n/**\n * Element tool state store interface\n *\n * Manages element-level ephemeral tool state using composite keys for global uniqueness.\n * Tool state is client-only and separate from PIE session data (which is sent to server for scoring).\n */\nexport interface ElementToolStateStoreApi {\n\t/**\n\t * Generate a globally unique element ID from components\n\t */\n\tgetGlobalElementId(\n\t\tassessmentId: string,\n\t\tsectionId: string,\n\t\titemId: string,\n\t\telementId: string,\n\t): string;\n\n\t/**\n\t * Parse a global element ID into its components\n\t */\n\tparseGlobalElementId(globalElementId: string): {\n\t\tassessmentId: string;\n\t\tsectionId: string;\n\t\titemId: string;\n\t\telementId: string;\n\t} | null;\n\n\t/**\n\t * Set state for a specific tool on an element\n\t */\n\tsetState(globalElementId: string, toolId: string, state: any): void;\n\n\t/**\n\t * Get state for a specific tool on an element\n\t */\n\tgetState(globalElementId: string, toolId: string): any | undefined;\n\n\t/**\n\t * Get all tool states for a specific element\n\t */\n\tgetElementState(globalElementId: string): Record<string, any>;\n\n\t/**\n\t * Get all element states\n\t */\n\tgetAllState(): Record<string, Record<string, any>>;\n\n\t/**\n\t * Subscribe to state changes\n\t */\n\tsubscribe(\n\t\tcallback: (state: Map<string, Map<string, any>>) => void,\n\t): () => void;\n\n\t/**\n\t * Set callback for persistence integration\n\t */\n\tsetOnStateChange(\n\t\tcallback: (state: Record<string, Record<string, any>>) => void,\n\t): void;\n\n\t/**\n\t * Load state from persistence\n\t */\n\tloadState(state: Record<string, Record<string, any>>): void;\n\n\t/**\n\t * Clear state for a specific element\n\t */\n\tclearElement(globalElementId: string): void;\n\n\t/**\n\t * Clear state for a specific tool across all elements\n\t */\n\tclearTool(toolId: string): void;\n\n\t/**\n\t * Clear all elements in a specific section\n\t */\n\tclearSection(assessmentId: string, sectionId: string): void;\n\n\t/**\n\t * Clear all state\n\t */\n\tclearAll(): void;\n}\n\n/**\n * Toolkit coordinator interface\n *\n * Orchestrates all toolkit services (TTS, tools, accessibility, state management) from a single entry point.\n * Provides centralized configuration for tool availability and settings.\n */\nexport interface ToolkitCoordinatorApi {\n\t/**\n\t * Assessment identifier\n\t */\n\treadonly assessmentId: string;\n\n\t/**\n\t * Configuration\n\t */\n\treadonly config: {\n\t\ttools?: {\n\t\t\tproviders?: Record<string, ToolProviderConfig | undefined>;\n\t\t};\n\t};\n\n\t/**\n\t * TTS service\n\t */\n\treadonly ttsService: TtsServiceApi;\n\n\t/**\n\t * Tool coordinator\n\t */\n\treadonly toolCoordinator: ToolCoordinatorApi;\n\n\t/**\n\t * Highlight coordinator\n\t */\n\treadonly highlightCoordinator: HighlightCoordinatorApi;\n\n\t/**\n\t * Element tool state store\n\t */\n\treadonly elementToolStateStore: ElementToolStateStoreApi;\n\n\t/**\n\t * Catalog resolver\n\t */\n\treadonly catalogResolver: AccessibilityCatalogResolverApi;\n\n\t/**\n\t * Tool provider registry\n\t */\n\treadonly toolProviderRegistry: ToolProviderRegistry;\n\n\t/**\n\t * Get all services as a bundle\n\t */\n\tgetServiceBundle(): {\n\t\tttsService: TtsServiceApi;\n\t\ttoolCoordinator: ToolCoordinatorApi;\n\t\thighlightCoordinator: HighlightCoordinatorApi;\n\t\telementToolStateStore: ElementToolStateStoreApi;\n\t\tcatalogResolver: AccessibilityCatalogResolverApi;\n\t\ttoolProviderRegistry: ToolProviderRegistry;\n\t};\n\n\t/**\n\t * Ensure TTS service is initialized and ready.\n\t */\n\tensureTTSReady(config?: Record<string, unknown>): Promise<void>;\n\n\t/**\n\t * Ensure a provider is initialized and ready.\n\t */\n\tensureProviderReady(providerId: string): Promise<unknown>;\n\n\t/**\n\t * Wait until coordinator initialization is complete.\n\t */\n\twaitUntilReady(): Promise<void>;\n\n\t/**\n\t * Check if coordinator has completed initialization.\n\t */\n\tisReady(): boolean;\n\n\t/**\n\t * Read current initialization status.\n\t */\n\tgetInitStatus(): ToolkitInitStatus;\n\n\t/**\n\t * Check if a tool is enabled\n\t */\n\tisToolEnabled(toolId: string): boolean;\n\n\t/**\n\t * Get tool configuration\n\t */\n\tgetToolConfig(toolId: string): ToolProviderConfig | null;\n\n\t/**\n\t * Update tool configuration\n\t */\n\tupdateToolConfig(toolId: string, updates: Partial<ToolProviderConfig>): void;\n\n\t/**\n\t * Update the enabled tool list for one placement level.\n\t */\n\tupdateToolPlacement(level: ToolPlacementLevel, toolIds: string[]): void;\n\n\t/**\n\t * Patch one or more placement levels in the canonical tools config.\n\t */\n\tupdateToolsPlacement(partial: ToolPlacementConfig): void;\n\n\t/**\n\t * Register or update lifecycle hooks at runtime.\n\t */\n\tsetHooks(hooks: ToolkitCoordinatorHooks): void;\n\n\t/**\n\t * Return a section controller if already created.\n\t */\n\tgetSectionController(args: {\n\t\tsectionId: string;\n\t\tattemptId?: string;\n\t}): SectionControllerHandle | undefined;\n\n\t/**\n\t * Subscribe to section controller events.\n\t *\n\t * The listener is bound to the toolkit's *active section cohort* and\n\t * automatically migrates across cohort transitions\n\t * (`getOrCreateSectionController` for a different cohort). On every\n\t * migration the listener receives a snapshot replay of the new\n\t * cohort's already-loaded `content-loaded` events followed by the\n\t * aggregate `section-loading-complete`, in the canonical order a\n\t * fresh subscriber would have observed.\n\t *\n\t * Throws if no active section cohort exists; host code must call\n\t * `getOrCreateSectionController(...)` at least once before\n\t * subscribing. (`toolkit-ready` alone is not sufficient — it fires\n\t * once toolkit state has loaded but before any section controller\n\t * has been created.) The typical pattern is to subscribe once\n\t * immediately after the first `getOrCreateSectionController(...)`\n\t * resolves; the subscription then follows the active cohort across\n\t * all subsequent navigation without further wiring.\n\t *\n\t * Subscribing the same `listener` reference twice replaces the prior\n\t * subscription with the new one (filter args from the second call\n\t * win); calling the returned disposer twice is a no-op.\n\t *\n\t * A listener that throws is caught and `console.warn`-logged; the\n\t * throw does not interrupt fan-out to the remaining listeners.\n\t */\n\tsubscribeSectionEvents(args: SectionEventSubscriptionArgs): () => void;\n\n\t/**\n\t * Subscribe to item-scoped section controller events.\n\t *\n\t * Same active-cohort binding contract as {@link subscribeSectionEvents};\n\t * defaults `eventTypes` to the item-scoped subset.\n\t */\n\tsubscribeItemEvents(args: SectionItemEventSubscriptionArgs): () => void;\n\n\t/**\n\t * Subscribe to section-scoped lifecycle/loading/completion/error events.\n\t *\n\t * Same active-cohort binding contract as {@link subscribeSectionEvents};\n\t * defaults `eventTypes` to the section-scoped subset.\n\t */\n\tsubscribeSectionLifecycleEvents(\n\t\targs: SectionScopedEventSubscriptionArgs,\n\t): () => void;\n\n\t/**\n\t * Create or reuse a section controller with single-flight deduplication.\n\t */\n\tgetOrCreateSectionController(args: {\n\t\tsectionId: string;\n\t\tattemptId?: string;\n\t\tinput?: unknown;\n\t\tupdateExisting?: boolean;\n\t\tcreateDefaultController: () =>\n\t\t\t| SectionControllerHandle\n\t\t\t| Promise<SectionControllerHandle>;\n\t}): Promise<SectionControllerHandle>;\n\n\t/**\n\t * Dispose an existing section controller.\n\t */\n\tdisposeSectionController(args: {\n\t\tsectionId: string;\n\t\tattemptId?: string;\n\t\tpersistBeforeDispose?: boolean;\n\t\tclearPersistence?: boolean;\n\t}): Promise<void>;\n\n\t/**\n\t * Subscribe to framework-error events emitted by the coordinator.\n\t *\n\t * Mirrors the shape of {@link subscribeTelemetry} (see\n\t * `ToolkitCoordinator.subscribeTelemetry`): a synchronous,\n\t * multi-subscriber stream where each call to the internal bus's\n\t * `reportFrameworkError` fans out to every active listener exactly once.\n\t *\n\t * The returned function detaches the listener; calling it twice is a\n\t * no-op. A listener that throws is caught and logged; the throw does\n\t * not break fan-out to the remaining listeners.\n\t *\n\t * Use this to wire framework errors into Sentry / Datadog / a custom\n\t * banner without listening on a DOM event. The DOM event\n\t * (`framework-error`) and the canonical `onFrameworkError` prop on\n\t * `<pie-assessment-toolkit>` consume the same bus.\n\t */\n\tsubscribeFrameworkErrors(listener: FrameworkErrorListener): () => void;\n\n\t// ----------------------------------------------------------------\n\t// Tool Policy Engine — public surface (M8 PR 2 / PR 3).\n\t//\n\t// The coordinator owns a single `ToolPolicyEngine` instance and\n\t// exposes its decision and subscription surface through the API\n\t// so that toolbar custom elements (`pie-item-toolbar`,\n\t// `pie-section-toolbar`), the base section player, and bespoke\n\t// host instrumentation (PNP debugger, etc.) all flow through the\n\t// same engine. Hosts that want to drive PNP/profile inputs imperatively\n\t// (instead of binding props on `<pie-assessment-toolkit>`) call\n\t// `updateAssessment` / `updateCurrentItemRef` /\n\t// `setPnpEnforcement` directly.\n\t// ----------------------------------------------------------------\n\n\t/**\n\t * Resolve the visible tool set for a given placement level + scope.\n\t * Returns the engine's full decision (visible tools, diagnostics,\n\t * provenance). Hosts that only need the IDs may map\n\t * `decision.visibleTools` themselves.\n\t */\n\tdecideToolPolicy(request: ToolPolicyDecisionRequest): ToolPolicyDecision;\n\n\t/**\n\t * Subscribe to policy-engine change events. Fires whenever the\n\t * coordinator's bound policy inputs change (`updateToolConfig`,\n\t * `updateToolPlacement`, `updateAssessment`, `updateCurrentItemRef`,\n\t * `setPnpEnforcement`) or a custom `PolicySource` is registered /\n\t * removed. Listeners that need the new visible tool set should\n\t * call `decideToolPolicy(...)` with their level / scope.\n\t */\n\tonPolicyChange(listener: ToolPolicyChangeListener): () => void;\n\n\t/**\n\t * Bind (or clear) the active assessment for PNP/profile policy decisions.\n\t *\n\t * Under auto-mode (no host override via {@link setPnpEnforcement}),\n\t * the engine flips to `pnpEnforcement: \"on\"` iff the assessment\n\t * carries profile precedence material (`personalNeedsProfile`,\n\t * `settings.districtPolicy`, `settings.testAdministration`) or the\n\t * currently-bound item ref carries item-level profile inputs. A bare\n\t * assessment record (just `id` / `name`) keeps `\"off\"`.\n\t *\n\t * The host override set via {@link setPnpEnforcement} is sticky\n\t * across assessment swaps.\n\t */\n\tupdateAssessment(assessment: AssessmentEntity | null): void;\n\n\t/**\n\t * Bind (or clear) the current item reference for policy decisions.\n\t * Used by item-level profile gates (item `requiredTools` /\n\t * `restrictedTools` / `toolParameters`). Item-level profile material\n\t * also feeds the auto-mode helper — navigating to an item with\n\t * profile settings can flip auto-mode to `\"on\"` even when the parent\n\t * assessment carries no profile block of its own.\n\t */\n\tupdateCurrentItemRef(itemRef: AssessmentItemRef | null): void;\n\n\t/**\n\t * Override the auto-mode PNP/profile enforcement decision. Pass `\"on\"` /\n\t * `\"off\"` to pin the mode, or `null` to clear the override and\n\t * return to auto-mode (`\"on\"` iff the bound assessment / item ref\n\t * carries profile material, otherwise `\"off\"`).\n\t */\n\tsetPnpEnforcement(mode: PnpEnforcementMode | null): void;\n\n\t/**\n\t * Read the engine inputs currently driving decisions. Useful for\n\t * debugging / instrumentation; do not mutate.\n\t */\n\tgetPolicyInputs(): Readonly<ResolvedEngineInputs>;\n\n\t/**\n\t * Register a custom `PolicySource`. The source participates in\n\t * every subsequent `decideToolPolicy(...)` call until disposed\n\t * (the returned function detaches).\n\t */\n\tregisterPolicySource(source: PolicySource): () => void;\n\n\t/**\n\t * Register a host-owned resolver for scoped tool render context.\n\t */\n\tregisterToolContextResolver(\n\t\ttoolId: string,\n\t\tresolver: ToolContextResolver,\n\t): () => void;\n\n\t/**\n\t * Replace all host-owned render-context resolvers.\n\t */\n\tsetToolContextResolvers(\n\t\tresolvers: ToolContextResolverMap | null | undefined,\n\t): void;\n\n\t/**\n\t * Whether a host resolver is registered for this tool.\n\t */\n\thasToolContextResolver(toolId: string): boolean;\n\n\t/**\n\t * Resolve render visibility/params for a tool that already survived policy gates.\n\t */\n\tresolveToolContext(\n\t\tcontext: ToolContextResolverContext,\n\t): ResolvedToolContext | null;\n\n\t/**\n\t * Subscribe to resolver registration/removal changes.\n\t */\n\tonToolContextResolverChange(listener: () => void): () => void;\n}\n\n// I18nServiceApi is re-exported from @pie-players/pie-players-shared/i18n\n"]}
@@ -228,9 +228,11 @@ export function hasChoiceInteraction(context) {
228
228
  "pie-multiple-choice",
229
229
  "pie-inline-choice",
230
230
  "pie-select-text",
231
+ "pie-ebsr",
231
232
  "multiple-choice",
232
233
  "inline-choice",
233
234
  "select-text",
235
+ "ebsr",
234
236
  ];
235
237
  if (isElementContext(context)) {
236
238
  const config = context.item.config;