@pie-qti/default-components 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +9 -1
  4. package/dist/plugins/index.d.ts +1 -0
  5. package/dist/plugins/index.d.ts.map +1 -1
  6. package/dist/plugins/index.js +1 -0
  7. package/dist/shared/utils/matchGroupUtils.d.ts +8 -0
  8. package/dist/shared/utils/matchGroupUtils.d.ts.map +1 -0
  9. package/dist/shared/utils/matchGroupUtils.js +13 -0
  10. package/package.json +8 -4
  11. package/src/catalog/CatalogPopup.svelte +162 -0
  12. package/src/index.ts +10 -1
  13. package/src/plugins/associate/AssociateInteraction.svelte +18 -1
  14. package/src/plugins/choice/ChoiceInteraction.svelte +143 -4
  15. package/src/plugins/drawing/DrawingInteraction.svelte +9 -0
  16. package/src/plugins/extended-text/ExtendedTextInteraction.svelte +56 -1
  17. package/src/plugins/gap-match/GapMatchInteraction.svelte +174 -12
  18. package/src/plugins/graphic-associate/GraphicAssociateInteraction.svelte +85 -9
  19. package/src/plugins/graphic-gap-match/GraphicGapMatchInteraction.svelte +197 -107
  20. package/src/plugins/hotspot/HotspotInteraction.svelte +50 -7
  21. package/src/plugins/hottext/HottextInteraction.svelte +33 -4
  22. package/src/plugins/index.ts +1 -0
  23. package/src/plugins/match/MatchInteraction.svelte +13 -1
  24. package/src/plugins/order/OrderInteraction.svelte +132 -11
  25. package/src/plugins/position-object/PositionObjectInteraction.svelte +247 -9
  26. package/src/plugins/select-point/SelectPointInteraction.svelte +139 -7
  27. package/src/shared/components/GraphicGapMatch.svelte +5 -3
  28. package/src/shared/components/GraphicGapMatchAdapter.svelte +10 -1
  29. package/src/shared/components/InlineInteractionRenderer.svelte +11 -6
  30. package/src/shared/components/MatchDragDrop.svelte +48 -2
  31. package/src/shared/styles/qti-shared-vocabulary.css +320 -0
  32. package/src/shared/utils/matchGroupUtils.ts +14 -0
@@ -37,6 +37,12 @@
37
37
  let imageContainer: HTMLDivElement | null = $state(null);
38
38
  let imageElement: HTMLElement | null = $state(null);
39
39
 
40
+ // Keyboard crosshair state (K-01)
41
+ let crosshairActive = $state(false);
42
+ let crosshairX = $state(0.5); // normalized 0-1
43
+ let crosshairY = $state(0.5); // normalized 0-1
44
+ let liveRegionText = $state('');
45
+
40
46
  /**
41
47
  * Parse correct response points (same format as user response)
42
48
  */
@@ -126,7 +132,12 @@
126
132
  /**
127
133
  * Check if selection limit has been reached
128
134
  */
129
- const canSelectMore = $derived(!parsedInteraction || selectedPoints.length < parsedInteraction.maxChoices);
135
+ // maxChoices=0 means unlimited per QTI spec
136
+ const canSelectMore = $derived(
137
+ !parsedInteraction ||
138
+ parsedInteraction.maxChoices === 0 ||
139
+ selectedPoints.length < parsedInteraction.maxChoices
140
+ );
130
141
 
131
142
  /**
132
143
  * Check if minimum selection requirement has been met
@@ -211,6 +222,79 @@
211
222
  }
212
223
  }
213
224
  });
225
+
226
+ /**
227
+ * Place a point at the current crosshair position (K-01).
228
+ * Converts normalized crosshair coords to intrinsic pixel coords.
229
+ */
230
+ function placePointAtCrosshair() {
231
+ if (!canSelectMore || !parsedInteraction?.imageData) return;
232
+
233
+ const intrinsicWidth = parseInt(parsedInteraction.imageData.width) || 500;
234
+ const intrinsicHeight = parseInt(parsedInteraction.imageData.height) || 300;
235
+
236
+ const x = Math.round(crosshairX * intrinsicWidth);
237
+ const y = Math.round(crosshairY * intrinsicHeight);
238
+
239
+ selectedPoints = [...selectedPoints, { x, y }];
240
+
241
+ const canonicalValue =
242
+ parsedInteraction.maxChoices === 1
243
+ ? (selectedPoints[0] ? `${selectedPoints[0].x} ${selectedPoints[0].y}` : null)
244
+ : selectedPoints.map((p) => `${p.x} ${p.y}`);
245
+ response = canonicalValue;
246
+ onChange?.(canonicalValue);
247
+ rootElement?.dispatchEvent(createQtiChangeEvent(parsedInteraction?.responseId, canonicalValue));
248
+ }
249
+
250
+ /**
251
+ * Handle keyboard events on the image container (K-01).
252
+ * Arrow keys move the crosshair; Enter/Space place a point.
253
+ */
254
+ function handleKeydown(e: KeyboardEvent) {
255
+ if (disabled) return;
256
+
257
+ const LARGE_STEP = 0.05; // 5% per arrow key press
258
+ const SMALL_STEP = 0.01; // 1% with Shift for fine control
259
+
260
+ switch (e.key) {
261
+ case 'ArrowLeft':
262
+ case 'ArrowRight':
263
+ case 'ArrowUp':
264
+ case 'ArrowDown': {
265
+ e.preventDefault();
266
+ const step = e.shiftKey ? SMALL_STEP : LARGE_STEP;
267
+ if (e.key === 'ArrowLeft') crosshairX = Math.max(0, crosshairX - step);
268
+ if (e.key === 'ArrowRight') crosshairX = Math.min(1, crosshairX + step);
269
+ if (e.key === 'ArrowUp') crosshairY = Math.max(0, crosshairY - step);
270
+ if (e.key === 'ArrowDown') crosshairY = Math.min(1, crosshairY + step);
271
+
272
+ const xPct = Math.round(crosshairX * 100);
273
+ const yPct = Math.round(crosshairY * 100);
274
+ liveRegionText = `Position: ${xPct}%, ${yPct}%`;
275
+ break;
276
+ }
277
+ case 'Enter':
278
+ case ' ':
279
+ e.preventDefault();
280
+ if (canSelectMore) {
281
+ placePointAtCrosshair();
282
+ }
283
+ break;
284
+ }
285
+ }
286
+
287
+ function handleFocus() {
288
+ crosshairActive = true;
289
+ crosshairX = 0.5;
290
+ crosshairY = 0.5;
291
+ liveRegionText = 'Position: 50%, 50%';
292
+ }
293
+
294
+ function handleBlur() {
295
+ crosshairActive = false;
296
+ liveRegionText = '';
297
+ }
214
298
  </script>
215
299
 
216
300
  <ShadowBaseStyles />
@@ -225,19 +309,24 @@
225
309
 
226
310
  <div class="space-y-3">
227
311
 
312
+ <!-- Visually-hidden live region announces crosshair position to screen readers -->
313
+ <span
314
+ aria-live="polite"
315
+ aria-atomic="true"
316
+ style="position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;"
317
+ >{liveRegionText}</span>
318
+
228
319
  <div
229
320
  bind:this={imageContainer}
230
321
  class="image-container relative inline-block"
231
322
  style={disabled ? 'cursor: default;' : 'cursor: crosshair;'}
232
323
  role="button"
233
324
  tabindex={disabled ? -1 : 0}
234
- aria-label={i18n?.t('interactions.selectPoint.instructionAria') ?? 'Click to select points on the image'}
325
+ aria-label={i18n?.t('interactions.selectPoint.instructionAria') ?? 'Click or use arrow keys to position crosshair, then press Enter or Space to select a point on the image'}
235
326
  onclick={handleImageClick}
236
- onkeydown={(e) => {
237
- if (e.key === 'Enter' || e.key === ' ') {
238
- e.preventDefault();
239
- }
240
- }}
327
+ onkeydown={handleKeydown}
328
+ onfocus={handleFocus}
329
+ onblur={handleBlur}
241
330
  >
242
331
  {#if parsedInteraction.imageData}
243
332
  {#if parsedInteraction.imageData.type === 'svg'}
@@ -306,6 +395,28 @@
306
395
  <p class="text-base-content/50">{i18n?.t('interactions.selectPoint.noImage') ?? 'No image provided'}</p>
307
396
  </div>
308
397
  {/if}
398
+
399
+ <!-- Keyboard crosshair overlay (K-01) — visible only when container has focus -->
400
+ {#if crosshairActive && !disabled && parsedInteraction?.imageData}
401
+ {@const imgW = parseInt(parsedInteraction.imageData.width) || 500}
402
+ {@const imgH = parseInt(parsedInteraction.imageData.height) || 300}
403
+ {@const cx = crosshairX * imgW}
404
+ {@const cy = crosshairY * imgH}
405
+ <svg
406
+ aria-hidden="true"
407
+ class="crosshair-overlay"
408
+ style="width: {imgW}px; height: {imgH}px;"
409
+ viewBox="0 0 {imgW} {imgH}"
410
+ xmlns="http://www.w3.org/2000/svg"
411
+ >
412
+ <!-- Horizontal line -->
413
+ <line x1="0" y1={cy} x2={imgW} y2={cy} class="crosshair-line" />
414
+ <!-- Vertical line -->
415
+ <line x1={cx} y1="0" x2={cx} y2={imgH} class="crosshair-line" />
416
+ <!-- Centre dot -->
417
+ <circle cx={cx} cy={cy} r="5" class="crosshair-dot" />
418
+ </svg>
419
+ {/if}
309
420
  </div>
310
421
 
311
422
  <div class="flex items-center justify-between text-sm text-base-content/70">
@@ -436,4 +547,25 @@
436
547
  border: 2px dashed hsl(var(--bc) / 0.2);
437
548
  border-radius: 8px;
438
549
  }
550
+
551
+ /* K-01 keyboard crosshair overlay */
552
+ .crosshair-overlay {
553
+ position: absolute;
554
+ top: 0;
555
+ left: 0;
556
+ pointer-events: none;
557
+ z-index: 150;
558
+ }
559
+
560
+ .crosshair-line {
561
+ stroke: #2563eb;
562
+ stroke-width: 1.5;
563
+ stroke-dasharray: 4 3;
564
+ opacity: 0.85;
565
+ }
566
+
567
+ .crosshair-dot {
568
+ fill: #2563eb;
569
+ opacity: 0.9;
570
+ }
439
571
  </style>
@@ -149,8 +149,8 @@ function parseCoords(hotspot: Hotspot): { x: number; y: number; width: number; h
149
149
  const [cx, cy, r] = coords;
150
150
  return { x: cx - r, y: cy - r, width: r * 2, height: r * 2 };
151
151
  } else if (hotspot.shape === 'rect') {
152
- const [x, y, width, height] = coords;
153
- return { x, y, width, height };
152
+ const [x, y, right, bottom] = coords;
153
+ return { x, y, width: right - x, height: bottom - y };
154
154
  }
155
155
  // For poly, use bounding box (simplified)
156
156
  return { x: coords[0], y: coords[1], width: 40, height: 40 };
@@ -256,7 +256,9 @@ function parseCoords(hotspot: Hotspot): { x: number; y: number; width: number; h
256
256
  onkeydown={(e) => handleHotspotKeyDown(e, hotspot.identifier)}
257
257
  />
258
258
  {:else if hotspot.shape === 'rect'}
259
- {@const [x, y, width, height] = hotspot.coords.split(',').map(Number)}
259
+ {@const [x, y, right, bottom] = hotspot.coords.split(',').map(Number)}
260
+ {@const width = right - x}
261
+ {@const height = bottom - y}
260
262
  {@const hotspotIndex = hotspots.findIndex((h) => h.identifier === hotspot.identifier)}
261
263
  <rect
262
264
  role="button"
@@ -19,6 +19,15 @@ const { interaction, response = null, disabled = false, typeset, onChange }: Pro
19
19
  // Transform response format: string[] to the pairs format GraphicGapMatch expects
20
20
  const pairs = $derived(response ?? []);
21
21
 
22
+ // Build imageData HTML string: inline SVG content or an <img> tag for raster images
23
+ const imageDataHtml = $derived.by(() => {
24
+ const img = interaction.imageData;
25
+ if (!img) return '';
26
+ if (img.content) return img.content as string;
27
+ if (img.src) return `<img src="${img.src}" alt="" style="width: 100%; height: 100%; display: block; position: absolute; top: 0; left: 0;" />`;
28
+ return '';
29
+ });
30
+
22
31
  function handlePairsChange(newPairs: string[]) {
23
32
  onChange(newPairs);
24
33
  }
@@ -28,7 +37,7 @@ function handlePairsChange(newPairs: string[]) {
28
37
  gapTexts={interaction.gapTexts}
29
38
  hotspots={interaction.hotspots}
30
39
  {pairs}
31
- imageData={interaction.imageData?.content ?? ''}
40
+ imageData={imageDataHtml}
32
41
  imageWidth={interaction.imageData?.width ?? '600'}
33
42
  imageHeight={interaction.imageData?.height ?? '500'}
34
43
  {disabled}
@@ -86,24 +86,29 @@ const segments = $derived.by(() => {
86
86
  {#if segment.type === 'html'}
87
87
  {@html segment.content}
88
88
  {:else if segment.type === 'textEntry'}
89
+ {@const inputWidthClass = (segment.interaction.interactionClasses ?? []).find((c: string) => c.startsWith('qti-input-width-'))}
90
+ {@const inputWidthCh = inputWidthClass ? parseInt(inputWidthClass.replace('qti-input-width-', ''), 10) : null}
89
91
  <input
90
92
  type="text"
91
- class="input input-bordered input-sm inline-input"
92
- style="width: {segment.interaction.expectedLength * 8}px; min-width: 100px; display: inline-block; margin: 0 4px;"
93
- placeholder="..."
93
+ class={['input input-bordered input-sm inline-input', ...(segment.interaction.interactionClasses ?? [])].join(' ')}
94
+ style={inputWidthCh ? `width: ${inputWidthCh}ch; display: inline-block; margin: 0 4px;` : `width: ${(segment.interaction.expectedLength ?? 15) * 8}px; min-width: 100px; display: inline-block; margin: 0 4px;`}
95
+ placeholder={segment.interaction.placeholderText || ''}
94
96
  aria-label={`Text entry ${segment.interaction.responseId}`}
95
97
  value={responses[segment.interaction.responseId] || ''}
96
98
  oninput={(e) => onResponseChange(segment.interaction.responseId, e.currentTarget.value)}
97
99
  />
98
100
  {:else if segment.type === 'inlineChoice'}
101
+ {@const inputWidthClass = (segment.interaction.interactionClasses ?? []).find((c: string) => c.startsWith('qti-input-width-'))}
102
+ {@const inputWidthCh = inputWidthClass ? parseInt(inputWidthClass.replace('qti-input-width-', ''), 10) : null}
103
+ {@const placeholder = segment.interaction.dataPrompt ?? segment.interaction.label ?? 'Select...'}
99
104
  <select
100
- class="select select-bordered select-sm inline-select"
101
- style="display: inline-block; margin: 0 4px; width: auto; min-width: 120px;"
105
+ class={['select select-bordered select-sm inline-select', ...(segment.interaction.interactionClasses ?? [])].join(' ')}
106
+ style={inputWidthCh ? `width: ${inputWidthCh}ch; display: inline-block; margin: 0 4px;` : `display: inline-block; margin: 0 4px; width: auto; min-width: 120px;`}
102
107
  aria-label={`Inline choice ${segment.interaction.responseId}`}
103
108
  value={responses[segment.interaction.responseId] || ''}
104
109
  onchange={(e) => onResponseChange(segment.interaction.responseId, e.currentTarget.value)}
105
110
  >
106
- <option value="">Select...</option>
111
+ <option value="" disabled>{placeholder}</option>
107
112
  {#each segment.interaction.choices as choice}
108
113
  <option value={choice.identifier}>{choice.text}</option>
109
114
  {/each}
@@ -9,6 +9,7 @@ import type { AssociableChoice } from '@pie-qti/item-player';
9
9
  import type { I18nProvider } from '@pie-qti/i18n';
10
10
  import { createOrUpdatePair, getSourceForTarget, getTargetsForSource, removePairBySource } from '../utils/pairHelpers.js';
11
11
  import { touchDrag } from '../utils/touchDragHelper.js';
12
+ import { isCompatibleMatchGroup } from '../utils/matchGroupUtils.js';
12
13
  import DragHandle from './DragHandle.svelte';
13
14
  import '../styles/shared.css';
14
15
 
@@ -16,13 +17,29 @@ interface Props {
16
17
  sourceSet: AssociableChoice[];
17
18
  targetSet: AssociableChoice[];
18
19
  pairs: string[]; // Array of "sourceId targetId" pairs
20
+ maxAssociations?: number; // 0 = unlimited per QTI spec
19
21
  correctPairs?: string[]; // Array of correct "sourceId targetId" pairs
20
22
  disabled?: boolean;
21
23
  i18n?: I18nProvider;
22
24
  onPairsChange: (newPairs: string[]) => void;
23
25
  }
24
26
 
25
- const { sourceSet, targetSet, pairs, correctPairs = [], disabled = false, i18n, onPairsChange }: Props = $props();
27
+ const { sourceSet, targetSet, pairs, maxAssociations = 0, correctPairs = [], disabled = false, i18n, onPairsChange }: Props = $props();
28
+
29
+ // maxAssociations=0 means unlimited; otherwise cap total pairs
30
+ const canAddMorePairs = $derived(maxAssociations === 0 || pairs.length < maxAssociations);
31
+
32
+ // Targets incompatible with the active source due to matchGroup constraints
33
+ const blockedTargetIds = $derived.by(() => {
34
+ const activeSourceId = draggedSourceId ?? keyboardSelectedSourceId;
35
+ if (!activeSourceId) return new Set<string>();
36
+ const src = sourceSet.find((s) => s.identifier === activeSourceId);
37
+ return new Set(
38
+ targetSet
39
+ .filter((t) => !isCompatibleMatchGroup(src?.matchGroup, t.matchGroup))
40
+ .map((t) => t.identifier)
41
+ );
42
+ });
26
43
 
27
44
  let draggedSourceId = $state<string | null>(null);
28
45
  let keyboardSelectedSourceId = $state<string | null>(null); // Source selected via keyboard
@@ -43,6 +60,18 @@ function handleDrop(event: DragEvent, targetId: string) {
43
60
  if (disabled || !draggedSourceId) return;
44
61
  event.preventDefault();
45
62
 
63
+ if (blockedTargetIds.has(targetId)) {
64
+ draggedSourceId = null;
65
+ return;
66
+ }
67
+
68
+ // Allow replacing an existing pair for this source, but block new pairs when at limit
69
+ const existingPair = pairs.find((p) => p.startsWith(draggedSourceId + ' '));
70
+ if (!existingPair && !canAddMorePairs) {
71
+ draggedSourceId = null;
72
+ return;
73
+ }
74
+
46
75
  createMatch(draggedSourceId, targetId);
47
76
  draggedSourceId = null;
48
77
  }
@@ -87,9 +116,22 @@ function handleTargetKeyDown(event: KeyboardEvent, targetId: string) {
87
116
  if ((event.key === ' ' || event.key === 'Enter') && keyboardSelectedSourceId) {
88
117
  event.preventDefault();
89
118
 
119
+ if (blockedTargetIds.has(targetId)) {
120
+ announceText = `This target cannot be matched with the selected source.`;
121
+ return;
122
+ }
123
+
90
124
  const source = sourceSet.find((s) => s.identifier === keyboardSelectedSourceId);
91
125
  const sourceName = source?.text || 'Item';
92
126
 
127
+ // Allow replacing an existing pair for this source, but block new pairs when at limit
128
+ const existingPair = pairs.find((p) => p.startsWith(keyboardSelectedSourceId + ' '));
129
+ if (!existingPair && !canAddMorePairs) {
130
+ announceText = `Maximum associations reached. Remove a pair to add a new one.`;
131
+ keyboardSelectedSourceId = null;
132
+ return;
133
+ }
134
+
93
135
  createMatch(keyboardSelectedSourceId, targetId);
94
136
  announceText = `${sourceName} matched with ${targetName}`;
95
137
  keyboardSelectedSourceId = null;
@@ -219,6 +261,7 @@ function clearMatch(sourceId: string) {
219
261
  {@const isHighlight = (draggedSourceId && !matchedSource) || (keyboardSelectedSourceId && !matchedSource)}
220
262
  {@const correctSource = getSourceForTarget(correctPairs, target.identifier)}
221
263
  {@const isCorrect = correctSource !== null}
264
+ {@const isBlocked = blockedTargetIds.has(target.identifier)}
222
265
 
223
266
  <button
224
267
  type="button"
@@ -226,7 +269,8 @@ function clearMatch(sourceId: string) {
226
269
  ondrop={(e) => handleDrop(e, target.identifier)}
227
270
  onkeydown={(e) => handleTargetKeyDown(e, target.identifier)}
228
271
  disabled={disabled || !keyboardSelectedSourceId}
229
- aria-label="{target.text}{matchedSource && sourceItem ? '. Matched with ' + sourceItem.text : '. Available for matching'}{isCorrect ? '. Correct answer' : ''}"
272
+ aria-disabled={isBlocked ? 'true' : undefined}
273
+ aria-label="{target.text}{matchedSource && sourceItem ? '. Matched with ' + sourceItem.text : '. Available for matching'}{isCorrect ? '. Correct answer' : ''}{isBlocked ? '. Not compatible with selected source' : ''}"
230
274
  data-matched={!!matchedSource}
231
275
  data-highlight={isHighlight}
232
276
  data-correct={isCorrect}
@@ -243,6 +287,8 @@ function clearMatch(sourceId: string) {
243
287
  class:border-accent={draggedSourceId && !matchedSource || (keyboardSelectedSourceId && !matchedSource)}
244
288
  class:bg-accent={draggedSourceId && !matchedSource || (keyboardSelectedSourceId && !matchedSource)}
245
289
  class:bg-opacity-5={draggedSourceId && !matchedSource || (keyboardSelectedSourceId && !matchedSource)}
290
+ class:opacity-40={isBlocked}
291
+ class:cursor-not-allowed={isBlocked}
246
292
  >
247
293
  <div class="qti-match-target-content flex flex-col gap-1">
248
294
  <div class="qti-match-target-title font-medium text-base-content/70">{target.text}</div>