@pie-qti/default-components 0.1.1 → 0.1.4

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 (36) hide show
  1. package/dist/shared/extensions/MathLiveEditor.d.ts +1 -0
  2. package/dist/shared/extensions/MathLiveEditor.d.ts.map +1 -1
  3. package/dist/shared/extensions/MathLiveEditor.js +3 -7
  4. package/dist/shared/utils/eventHelpers.d.ts +3 -11
  5. package/dist/shared/utils/eventHelpers.d.ts.map +1 -1
  6. package/dist/shared/utils/eventHelpers.js +7 -1
  7. package/dist/shared/utils/pairHelpers.d.ts +15 -2
  8. package/dist/shared/utils/pairHelpers.d.ts.map +1 -1
  9. package/dist/shared/utils/pairHelpers.js +30 -8
  10. package/dist/shared/utils/touchDragHelper.d.ts +1 -32
  11. package/dist/shared/utils/touchDragHelper.d.ts.map +1 -1
  12. package/dist/shared/utils/touchDragHelper.js +1 -168
  13. package/dist/shared/utils/webComponentHelpers.d.ts +1 -1
  14. package/dist/shared/utils/webComponentHelpers.d.ts.map +1 -1
  15. package/dist/shared/utils/webComponentHelpers.js +3 -3
  16. package/package.json +113 -91
  17. package/src/plugins/gap-match/GapMatchInteraction.svelte +25 -10
  18. package/src/plugins/graphic-gap-match/GraphicGapMatchInteraction.svelte +32 -37
  19. package/src/plugins/hottext/HottextInteraction.svelte +1 -1
  20. package/src/plugins/media/MediaInteraction.svelte +2 -2
  21. package/src/plugins/position-object/PositionObjectInteraction.svelte +0 -6
  22. package/src/plugins/select-point/SelectPointInteraction.svelte +0 -14
  23. package/src/shared/components/DrawingCanvas.svelte +17 -1
  24. package/src/shared/components/MatchDragDrop.svelte +24 -23
  25. package/src/shared/components/ShadowBaseStyles.svelte +1 -2
  26. package/src/shared/extensions/MathLiveEditor.ts +3 -8
  27. package/src/shared/utils/eventHelpers.ts +12 -3
  28. package/src/shared/utils/pairHelpers.ts +32 -9
  29. package/src/shared/utils/touchDragHelper.ts +1 -211
  30. package/src/shared/utils/webComponentHelpers.ts +5 -5
  31. package/.turbo/turbo-build.log +0 -1
  32. package/CHANGELOG.md +0 -9
  33. package/STYLING.md +0 -226
  34. package/svelte.config.js +0 -9
  35. package/tests/index.test.ts +0 -8
  36. package/tsconfig.json +0 -20
@@ -1,3 +1,5 @@
1
+ import type { QTIChangeEventDetail } from '@pie-qti/item-player/web-components';
2
+
1
3
  /**
2
4
  * Event emission helpers for QTI components
3
5
  */
@@ -8,10 +10,17 @@
8
10
  * @param value - The response value
9
11
  * @returns A CustomEvent that can be dispatched
10
12
  */
11
- export function createQtiChangeEvent(responseId: string | undefined, value: any): CustomEvent {
13
+ function requireResponseId(responseId: string | undefined): string {
14
+ if (!responseId || responseId.trim().length === 0) {
15
+ throw new Error('qti-change event requires a non-empty responseId');
16
+ }
17
+ return responseId;
18
+ }
19
+
20
+ export function createQtiChangeEvent(responseId: string | undefined, value: unknown): CustomEvent<QTIChangeEventDetail> {
12
21
  return new CustomEvent('qti-change', {
13
22
  detail: {
14
- responseId,
23
+ responseId: requireResponseId(responseId),
15
24
  value,
16
25
  timestamp: Date.now(),
17
26
  },
@@ -29,7 +38,7 @@ export function createQtiChangeEvent(responseId: string | undefined, value: any)
29
38
  export function emitQtiChange(
30
39
  element: HTMLElement | EventTarget,
31
40
  responseId: string | undefined,
32
- value: any
41
+ value: unknown
33
42
  ): void {
34
43
  const event = createQtiChangeEvent(responseId, value);
35
44
  element.dispatchEvent(event);
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  /**
7
- * Gets the target ID matched with a source ID
7
+ * Gets the target ID matched with a source ID (first match only, for one-to-one display)
8
8
  * @param pairs - Array of "sourceId targetId" pair strings
9
9
  * @param sourceId - The source identifier to search for
10
10
  * @returns The matched target ID, or null if not found
@@ -14,6 +14,19 @@ export function getTargetForSource(pairs: string[], sourceId: string): string |
14
14
  return pair ? pair.split(' ')[1] : null;
15
15
  }
16
16
 
17
+ /**
18
+ * Gets all target IDs matched with a source ID (for many-to-many)
19
+ * @param pairs - Array of "sourceId targetId" pair strings
20
+ * @param sourceId - The source identifier to search for
21
+ * @returns Array of matched target IDs
22
+ */
23
+ export function getTargetsForSource(pairs: string[], sourceId: string): string[] {
24
+ return pairs
25
+ .filter((p) => p.startsWith(`${sourceId} `))
26
+ .map((p) => p.split(' ')[1])
27
+ .filter((t): t is string => !!t);
28
+ }
29
+
17
30
  /**
18
31
  * Gets the source ID matched with a target ID
19
32
  * @param pairs - Array of "sourceId targetId" pair strings
@@ -26,21 +39,24 @@ export function getSourceForTarget(pairs: string[], targetId: string): string |
26
39
  }
27
40
 
28
41
  /**
29
- * Creates or updates a pair, removing any existing pairs for the source or target
42
+ * Creates or updates a pair.
43
+ * - Removes any existing pair for the target (target receives at most one when matchMax=1)
44
+ * - Does NOT remove other pairs for the source (allows many-to-many: one source → multiple targets)
30
45
  * @param pairs - Array of existing pair strings
31
46
  * @param sourceId - The source identifier
32
47
  * @param targetId - The target identifier
33
48
  * @returns A new array with the pair created/updated
34
49
  */
35
50
  export function createOrUpdatePair(pairs: string[], sourceId: string, targetId: string): string[] {
36
- // Remove any existing pair for this source
37
- let newPairs = pairs.filter((p) => !p.startsWith(`${sourceId} `));
51
+ // Remove any existing pair for this target (target gets "replaced")
52
+ let newPairs = pairs.filter((p) => !p.endsWith(` ${targetId}`));
38
53
 
39
- // Remove any existing pair for this target
40
- newPairs = newPairs.filter((p) => !p.endsWith(` ${targetId}`));
41
-
42
- // Add new pair
43
- newPairs.push(`${sourceId} ${targetId}`);
54
+ // Don't remove source pairs - allows one source to match multiple targets (many-to-many)
55
+ // Add new pair (avoid duplicate if same pair already exists)
56
+ const newPair = `${sourceId} ${targetId}`;
57
+ if (!newPairs.includes(newPair)) {
58
+ newPairs.push(newPair);
59
+ }
44
60
 
45
61
  return newPairs;
46
62
  }
@@ -55,6 +71,13 @@ export function removePairBySource(pairs: string[], sourceId: string): string[]
55
71
  return pairs.filter((p) => !p.startsWith(`${sourceId} `));
56
72
  }
57
73
 
74
+ /**
75
+ * Removes a specific pair by source and target ID
76
+ */
77
+ export function removePair(pairs: string[], sourceId: string, targetId: string): string[] {
78
+ return pairs.filter((p) => p !== `${sourceId} ${targetId}`);
79
+ }
80
+
58
81
  /**
59
82
  * Removes a pair by target ID
60
83
  * @param pairs - Array of existing pair strings
@@ -1,211 +1 @@
1
- /**
2
- * Touch-enabled drag helper for making HTML5 drag-and-drop work with touch devices
3
- *
4
- * HTML5 drag-and-drop API doesn't work on touch devices by default.
5
- * This helper translates touch events to pointer events for unified handling.
6
- *
7
- * Usage:
8
- * ```svelte
9
- * <div
10
- * use:touchDrag
11
- * draggable="true"
12
- * ondragstart={...}
13
- * >
14
- * ```
15
- */
16
-
17
- interface TouchDragState {
18
- element: HTMLElement;
19
- touchId: number | null;
20
- isDragging: boolean;
21
- startX: number;
22
- startY: number;
23
- currentX: number;
24
- currentY: number;
25
- dragThreshold: number;
26
- }
27
-
28
- /**
29
- * Svelte action to enable touch drag on draggable elements
30
- */
31
- export function touchDrag(node: HTMLElement) {
32
- const state: TouchDragState = {
33
- element: node,
34
- touchId: null,
35
- isDragging: false,
36
- startX: 0,
37
- startY: 0,
38
- currentX: 0,
39
- currentY: 0,
40
- dragThreshold: 10 // px movement to initiate drag
41
- };
42
-
43
- function handleTouchStart(e: TouchEvent) {
44
- // Only handle single touch
45
- if (e.touches.length !== 1) return;
46
-
47
- // Check if element is draggable
48
- const draggable = node.getAttribute('draggable');
49
- if (draggable !== 'true') return;
50
-
51
- const touch = e.touches[0];
52
- state.touchId = touch.identifier;
53
- state.startX = touch.clientX;
54
- state.startY = touch.clientY;
55
- state.currentX = touch.clientX;
56
- state.currentY = touch.clientY;
57
- state.isDragging = false;
58
-
59
- // Add move and end listeners to document for consistent tracking
60
- document.addEventListener('touchmove', handleTouchMove, { passive: false });
61
- document.addEventListener('touchend', handleTouchEnd);
62
- document.addEventListener('touchcancel', handleTouchCancel);
63
- }
64
-
65
- function handleTouchMove(e: TouchEvent) {
66
- if (state.touchId === null) return;
67
-
68
- // Find the touch we're tracking
69
- const touch = Array.from(e.changedTouches).find(t => t.identifier === state.touchId);
70
- if (!touch) return;
71
-
72
- state.currentX = touch.clientX;
73
- state.currentY = touch.clientY;
74
-
75
- // Check if we've moved enough to start dragging
76
- const deltaX = state.currentX - state.startX;
77
- const deltaY = state.currentY - state.startY;
78
- const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
79
-
80
- if (!state.isDragging && distance > state.dragThreshold) {
81
- // Start drag
82
- state.isDragging = true;
83
-
84
- // Trigger dragstart event
85
- const dragStartEvent = new DragEvent('dragstart', {
86
- bubbles: true,
87
- cancelable: true,
88
- clientX: state.startX,
89
- clientY: state.startY
90
- });
91
-
92
- node.dispatchEvent(dragStartEvent);
93
-
94
- // Add visual feedback
95
- node.style.opacity = '0.5';
96
- e.preventDefault(); // Prevent scrolling
97
- }
98
-
99
- if (state.isDragging) {
100
- e.preventDefault(); // Prevent scrolling while dragging
101
-
102
- // Find element under touch point
103
- const elementUnder = document.elementFromPoint(state.currentX, state.currentY);
104
-
105
- if (elementUnder && elementUnder !== node) {
106
- // Trigger dragover on the element under touch
107
- const dragOverEvent = new DragEvent('dragover', {
108
- bubbles: true,
109
- cancelable: true,
110
- clientX: state.currentX,
111
- clientY: state.currentY
112
- });
113
-
114
- elementUnder.dispatchEvent(dragOverEvent);
115
- }
116
- }
117
- }
118
-
119
- function handleTouchEnd(e: TouchEvent) {
120
- if (state.touchId === null) return;
121
-
122
- // Find the touch we're tracking
123
- const touch = Array.from(e.changedTouches).find(t => t.identifier === state.touchId);
124
- if (!touch) return;
125
-
126
- if (state.isDragging) {
127
- // Find element under touch point at drop location
128
- const elementUnder = document.elementFromPoint(touch.clientX, touch.clientY);
129
-
130
- if (elementUnder) {
131
- // Trigger drop event
132
- const dropEvent = new DragEvent('drop', {
133
- bubbles: true,
134
- cancelable: true,
135
- clientX: touch.clientX,
136
- clientY: touch.clientY
137
- });
138
-
139
- elementUnder.dispatchEvent(dropEvent);
140
- }
141
-
142
- // Trigger dragend
143
- const dragEndEvent = new DragEvent('dragend', {
144
- bubbles: true,
145
- cancelable: true
146
- });
147
-
148
- node.dispatchEvent(dragEndEvent);
149
-
150
- // Reset visual feedback
151
- node.style.opacity = '';
152
- }
153
-
154
- cleanup();
155
- }
156
-
157
- function handleTouchCancel() {
158
- if (state.isDragging) {
159
- // Trigger dragend
160
- const dragEndEvent = new DragEvent('dragend', {
161
- bubbles: true,
162
- cancelable: true
163
- });
164
-
165
- node.dispatchEvent(dragEndEvent);
166
-
167
- // Reset visual feedback
168
- node.style.opacity = '';
169
- }
170
-
171
- cleanup();
172
- }
173
-
174
- function cleanup() {
175
- state.touchId = null;
176
- state.isDragging = false;
177
-
178
- document.removeEventListener('touchmove', handleTouchMove);
179
- document.removeEventListener('touchend', handleTouchEnd);
180
- document.removeEventListener('touchcancel', handleTouchCancel);
181
- }
182
-
183
- // Attach initial touch listener
184
- node.addEventListener('touchstart', handleTouchStart, { passive: true });
185
-
186
- return {
187
- destroy() {
188
- node.removeEventListener('touchstart', handleTouchStart);
189
- cleanup();
190
- }
191
- };
192
- }
193
-
194
- /**
195
- * CSS helper for touch-friendly drag interactions
196
- * Returns CSS that should be applied to draggable elements
197
- */
198
- export const touchDragStyles = {
199
- /* Prevent text selection during drag */
200
- userSelect: 'none',
201
- webkitUserSelect: 'none',
202
-
203
- /* Allow touch events */
204
- touchAction: 'none',
205
-
206
- /* Cursor feedback */
207
- cursor: 'grab',
208
-
209
- /* Smooth transitions */
210
- transition: 'opacity 0.2s ease'
211
- } as const;
1
+ export { touchDrag, touchDragStyles } from '@pie-qti/qti-common';
@@ -6,17 +6,17 @@
6
6
  * Parse a prop that may be a JSON string or an object
7
7
  * Used when components are used as web components and receive JSON strings
8
8
  */
9
- export function parseJsonProp<T>(prop: T | string | null | undefined): T | null {
10
- if (prop === null || prop === undefined) return null;
9
+ export function parseJsonProp<T>(prop: T | string | null | undefined): T | undefined {
10
+ if (prop === null || prop === undefined) return undefined;
11
11
 
12
12
  if (typeof prop === 'string') {
13
13
  // Handle "null" string
14
- if (prop === 'null') return null;
14
+ if (prop === 'null') return undefined;
15
15
 
16
16
  // Try to parse as JSON
17
17
  try {
18
- return JSON.parse(prop);
19
- } catch (e) {
18
+ return JSON.parse(prop) as T;
19
+ } catch {
20
20
  // If it's not valid JSON, return the string as-is
21
21
  // This handles simple string identifiers
22
22
  return prop as unknown as T;
@@ -1 +0,0 @@
1
- $ tsc
package/CHANGELOG.md DELETED
@@ -1,9 +0,0 @@
1
- # @pie-qti/default-components
2
-
3
- ## 0.1.1
4
-
5
- ### Patch Changes
6
-
7
- - 2243643: Publish the initial public release of all publishable PIE-QTI packages.
8
- - Updated dependencies [2243643]
9
- - @pie-qti/item-player@0.1.1
package/STYLING.md DELETED
@@ -1,226 +0,0 @@
1
- # Styling Contract (Option A: Shadow DOM + CSS Variables + ::part)
2
-
3
- This package ships QTI interaction renderers as **web components** (Svelte custom elements). They render in **Shadow DOM** for encapsulation and portability.
4
-
5
- To make them themeable by the host (e.g. a QTI player shell using DaisyUI) while remaining framework-agnostic, the styling contract is:
6
-
7
- - Components **own layout/accessibility CSS** (so they render correctly with *zero* host CSS).
8
- - Components **consume theme tokens via CSS variables** (so the host controls colors/typography/radii).
9
- - Components expose stable **`part="..."` hooks** so host pages can refine styling via `::part(...)` without breaking encapsulation.
10
-
11
- ## Theme tokens (CSS variables)
12
-
13
- The components use CSS variables in the form:
14
-
15
- - `hsl(var(--p))`: primary
16
- - `hsl(var(--a))`: accent
17
- - `hsl(var(--b1))`, `hsl(var(--b2))`, `hsl(var(--b3))`: base surfaces
18
- - `hsl(var(--bc))`: base/content text
19
- - `hsl(var(--su))`: success
20
-
21
- These align with DaisyUI’s variable scheme. If the host does not provide them, components fall back to safe defaults via `var(--token, fallback)`.
22
-
23
- ### Host responsibilities (recommended)
24
-
25
- - Load your theme (DaisyUI or any other system) and set variables on `:root` (or any ancestor of the web component).
26
- - Optionally set `data-theme="..."` if you’re using DaisyUI themes.
27
-
28
- ## `::part` hooks
29
-
30
- ### `pie-qti-order` (`orderInteraction`)
31
-
32
- Parts:
33
-
34
- - `list`: the container holding the reorderable list
35
- - `item`: a single draggable item row (button)
36
- - `index`: the item index badge
37
- - `handle`: the drag handle icon
38
- - `text`: the item label text
39
-
40
- Example:
41
-
42
- ```css
43
- pie-qti-order::part(item) {
44
- border-radius: 12px;
45
- }
46
-
47
- pie-qti-order::part(handle) {
48
- opacity: 0.9;
49
- }
50
- ```
51
-
52
- ### `pie-qti-match` (`matchInteraction`)
53
-
54
- Parts:
55
-
56
- - `grid`: overall two-column layout container
57
- - `source-column`, `source-heading`
58
- - `target-column`, `target-heading`
59
- - `source-item`: draggable source button
60
- - `source-handle`: drag handle icon inside the source item
61
- - `source-clear`: “clear match” button
62
- - `target`: drop zone/target button
63
-
64
- Example:
65
-
66
- ```css
67
- pie-qti-match::part(target) {
68
- border-style: solid;
69
- }
70
- ```
71
-
72
- ## Regression guarantee (no-host-CSS)
73
-
74
- The repo includes a Playwright regression test that renders `pie-qti-order` and `pie-qti-match` in an iframe with **no Tailwind/DaisyUI loaded** and asserts that SVG handles do not fall back to browser-default sizing.
75
-
76
- See: `packages/example/tests/playwright/no-host-css.pw.ts`
77
-
78
- ## Baseline class styling (Shadow DOM)
79
-
80
- The default web components include a small baseline stylesheet (`ShadowBaseStyles`) to provide minimal styling for common DaisyUI classnames (e.g. `btn`, `alert`, `badge`, `card`, `select`) **inside Shadow DOM** when the host does not load DaisyUI/Tailwind CSS.
81
-
82
- File: `src/shared/components/ShadowBaseStyles.svelte`
83
-
84
- ### `pie-qti-hotspot` (`hotspotInteraction`)
85
-
86
- Parts:
87
-
88
- - `prompt`: prompt text
89
- - `stage`: container holding the image + overlay
90
- - `image`: the rendered image/SVG container
91
- - `overlay`: SVG overlay that contains the hotspot shapes (positioned absolutely)
92
- - `selected`: “Selected: …” message container
93
-
94
- Notes:
95
-
96
- - The interactive hotspot shapes are SVG elements inside `overlay`. The component includes a real CSS `:hover` fallback so hover feedback works even when Tailwind `hover:` utilities are not present.
97
-
98
- ### `pie-qti-graphic-gap-match` (`graphicGapMatchInteraction`)
99
-
100
- Parts:
101
-
102
- - `prompt`: prompt text
103
- - `region`: container for labels + stage
104
- - `labels`: labels palette container
105
- - `label-remove`: remove button next to a matched label
106
- - `stage`: container holding the image + overlay
107
- - `overlay`: SVG overlay for hotspots
108
-
109
- ### `pie-qti-graphic-order` (`graphicOrderInteraction`)
110
-
111
- Parts:
112
-
113
- - `prompt`
114
- - `layout`
115
- - `image-area`
116
- - `stage`
117
- - `panel`
118
- - `panel-title`
119
- - `list`
120
- - `item`
121
- - `handle-icon`
122
- - `confirm`
123
- - `confirmed-icon`
124
-
125
- ### `pie-qti-position-object` (`positionObjectInteraction`)
126
-
127
- Parts:
128
-
129
- - `prompt`
130
- - `layout`
131
- - `canvas-area`
132
- - `canvas`
133
- - `placed`
134
- - `remove`
135
- - `palette`
136
- - `palette-item`
137
- - `drag-icon`
138
-
139
- ### `pie-qti-graphic-associate` (`graphicAssociateInteraction`)
140
-
141
- Parts:
142
-
143
- - `prompt`
144
- - `layout`
145
- - `image-area`
146
- - `stage`
147
- - `overlay`
148
- - `hotspot`
149
- - `panel`
150
-
151
- ### `pie-qti-choice` (`choiceInteraction`)
152
-
153
- Parts:
154
-
155
- - `root`
156
- - `option`
157
- - `label`
158
- - `input`
159
- - `text`
160
-
161
- ### `pie-qti-slider` (`sliderInteraction`)
162
-
163
- Parts:
164
-
165
- - `root`
166
- - `prompt`
167
- - `track`
168
- - `min`
169
- - `input`
170
- - `max`
171
- - `value`
172
- - `value-number`
173
-
174
- ### `pie-qti-gap-match` (`gapMatchInteraction`)
175
-
176
- Parts:
177
-
178
- - `root`
179
- - `prompt`
180
- - `palette`
181
- - `word`
182
- - `text`
183
- - `gap`
184
-
185
- ### `pie-qti-hottext` (`hottextInteraction`)
186
-
187
- Parts:
188
-
189
- - `root`
190
- - `prompt`
191
- - `content`
192
- - `footer`
193
-
194
- ### `pie-qti-associate` (`associateInteraction`)
195
-
196
- Parts:
197
-
198
- - `root`
199
- - `prompt`
200
- - `choices`
201
- - `choice`
202
- - `pairs-title`
203
- - `pairs`
204
- - `pair`
205
- - `pair-remove`
206
- - `helper`
207
-
208
- ### `pie-qti-custom` (`customInteraction`)
209
-
210
- Parts:
211
-
212
- - `root` (on the `pie-qti-custom` wrapper)
213
- - `root`, `warning`, `manual`, `manual-label`, `manual-input`, `toggle`, `details`, `details-title`, `attributes`, `xml` (from `CustomInteractionFallback`)
214
-
215
- ### `pie-qti-extended-text` (`extendedTextInteraction`)
216
-
217
- Parts:
218
-
219
- - `root`
220
- - `editor`
221
-
222
- The rich text editor component also exposes parts:
223
-
224
- - `root`, `toolbar`, `toolbar-button`, `toolbar-divider`, `editor`
225
-
226
-
package/svelte.config.js DELETED
@@ -1,9 +0,0 @@
1
- /**
2
- * Svelte config for default-components
3
- * Enables custom element compilation for web components
4
- */
5
- export default {
6
- compilerOptions: {
7
- customElement: true,
8
- },
9
- };
@@ -1,8 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
-
3
- describe('default-components', () => {
4
- it('should export registerDefaultComponents', () => {
5
- const { registerDefaultComponents } = require('../src/index');
6
- expect(typeof registerDefaultComponents).toBe('function');
7
- });
8
- });
package/tsconfig.json DELETED
@@ -1,20 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "ESNext",
5
- "lib": ["ES2020", "DOM"],
6
- "declaration": true,
7
- "declarationMap": true,
8
- "outDir": "./dist",
9
- "rootDir": "./src",
10
- "strict": true,
11
- "esModuleInterop": true,
12
- "skipLibCheck": true,
13
- "forceConsistentCasingInFileNames": true,
14
- "moduleResolution": "bundler",
15
- "resolveJsonModule": true,
16
- "allowSyntheticDefaultImports": true
17
- },
18
- "include": ["src/**/*.ts", "src/**/*.d.ts"],
19
- "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts", "**/*.svelte"]
20
- }