feat: complete rewrite of course (#622)
* theming improvements * border style improvements * refactor: migrate org routes to server-side data fetching Move client-side API calls to server-side load functions for better performance, security, and SEO. Implement permission-based course filtering * refactor: clean up course and community components This commit removes unused components and files related to courses and community features, streamlining the codebase. It also updates various routes to enhance performance and maintainability. Additionally, it introduces new types and constants for better type safety and organization. * refactor: fix video formatting on website and other styles * refactor: update course and dashboard components for improved styling and functionality * more icon improvements * refactor: streamline course and dashboard components This commit updates various course and dashboard components for improved styling and functionality. It includes the removal of unused files, updates to imports and exports, and enhancements to type safety. Additionally, it introduces new routes and optimizes existing ones for better performance and maintainability. * refactor: enhance lesson completion logic * chore: delete all emails on dashboard and move other api routes to backend. move all emails to the backend and * feat: Refactor API and database queries for courses, quizzes, and lessons, migrating Supabase functions and schema management. * get app loading * fix ui and build error of cio/api * refactor: move direct database queries to query layer - Create query functions: getCourseWithOrgData, getOrganizationByCourseId, updateCourseVersion, updateLessonsSectionId, getProfileByGroupMemberId, getQuestionTypesByIds - Refactor services to use query functions instead of direct db queries - Add transaction support to updateCourseVersion and updateLessonsSectionId - Fix getProfileByGroupMemberId to return profile directly (not nested) - Fix updateLessonsSectionId to use .returning() instead of rowCount This aligns services with architecture pattern where services orchestrate queries rather than executing them directly. * exercise saving improvements * fix and optimise exercise creation * refactor: update dialog components for improved styling and functionality - Adjusted dialog content width and maximum constraints for better responsiveness. - Changed heading font size for consistency in the new exercise modal. - Replaced CloseIcon with CrossIcon for a more modern appearance in dialog close button. * refactor: enhance course and exercise management components - Introduced new components for exercise creation, editing, and viewing, improving user experience. - Refactored existing lesson and exercise components for better organization and maintainability. - Updated routing for exercises and lessons to streamline navigation within the course structure. - Added new utility functions and constants to support content management across the application. * feat: implement course content management API and UI components - Added new API routes for updating and deleting course content, enhancing content management capabilities. - Introduced new Svelte components for displaying and managing course content, including content lists and action handlers. - Updated existing course routing to integrate new content management features. - Refactored content-related utility functions for improved organization and maintainability. * refactor: remove Supabase references and implement course section management - Removed Supabase-related environment variables and Dockerfile arguments to streamline configuration. - Introduced a new section management API with routes for creating, updating, deleting, and reordering course sections. - Updated course services to handle section operations, ensuring consistency in course content management. - Refactored existing lesson section logic to align with the new course section structure, enhancing maintainability. * chore: update .prettierignore to exclude additional file types - Added exclusions for SQL and environment files to the Prettier ignore list. - Included Dockerfile and .prettierignore itself to prevent formatting issues. * feat: enhance course content management with translation support and UI improvements - Added translation keys for user-facing text in course-related components, ensuring all UI copy is sourced from translation files. - Updated lesson and exercise creation components to utilize translation keys for success and error messages, improving localization. - Refactored course content management components to streamline the creation and editing process, enhancing user experience. - Introduced new constants for content options and stepper states to standardize component behavior and improve maintainability. - Improved styling and functionality of course content modals and steppers for better user interaction. * feat: enhance course content management and UI components - Updated .prettierignore to exclude storybook-static directory. - Improved exercise creation logic by refining option handling and adding UUID support for option values. - Enhanced navigation component with debugging output for custom links. - Introduced a new method in CourseApi to update content items locally, improving state management during navigation. - Added caching for exercise templates by tag in ExerciseTemplateApi to optimize performance. - Refactored lesson and exercise components for better organization and maintainability, including updates to modal styling and functionality. - Implemented local patching for lesson and exercise list items to ensure UI consistency after updates. * student + teacher invite (not fully tested) * refactor: streamline course team member middleware - Removed unnecessary console logging and timing for checking user permissions. - Simplified the logic for determining if a user is a course team member or organization admin. * reorder course sidebar to move content to its own page. * feat: implement unified course enrollment route and API - Introduced a new enrollment route `/course/:slug/enroll` to replace the previous invite system. - Unified enrollment logic for free and paid courses, allowing direct enrollment for free courses and invite token validation for paid courses. - Updated course landing page to redirect to the new enrollment route for free courses. - Removed obsolete invite routes and related logic, streamlining the enrollment process. - Enhanced API with a new `POST /course/:courseId/enroll` endpoint for handling enrollments. - Added rate limiting for enrollment requests to prevent abuse. - Updated UI components to reflect changes in enrollment flow and messaging. * chore: update docker stack, docs, and auth token automation * chore: make prettier check ignore unknown file types * fix: avoid using authClient on server file and keep authClient client focused * chore: always get the server on demand depending on the environment * chore: update dashboard configuration and Docker setup for environment variables - Modified the Svelte configuration to directly use the PUBLIC_SERVER_URL environment variable. - Enhanced the Docker Compose file to include health check formatting and added environment variable arguments for the dashboard build. - Updated the Dockerfile to echo environment variable values during the build process, ensuring clarity on the configuration being used. * chore: enhance Docker setup and documentation for production deployment - Added a new production Docker Compose file and example environment file for published images. - Updated README and usage documentation to include instructions for deploying with production images. - Modified Svelte configuration to standardize the use of the posthog domain. - Removed unnecessary console logs from the API client and layout server files for cleaner output. - Improved overall clarity in Docker documentation regarding self-hosting and image publishing. * chore(db): log function name in query catch blocks (console.error 'funcName error:', error) Co-authored-by: Cursor <cursoragent@cursor.com> * fix: multiple refresh issue * fix: server key not passed to api * fix: clarify usage of PRIVATE_SERVER_KEY and AUTH_BEARER_TOKEN in documentation - Updated documentation to specify that PRIVATE_SERVER_KEY is used for server-to-server API key authentication and is validated by API key middleware. - Clarified that AUTH_BEARER_TOKEN is a separate token not utilized by apiKeyMiddleware. - Adjusted examples in Docker setup and self-hosting documentation to reflect these changes. * fix migration script * fix: improve language handling and add database reset script - Updated language extraction to handle potential undefined values, defaulting to 'en' if necessary. - Added a new script for resetting the database, including functionality to truncate public tables and run setup with optional seeding. * feat: add promote ungrouped section functionality and enhance document handling in dashboard - Implemented a new API endpoint to promote synthetic "Ungrouped" content into a real persisted section, allowing for better organization of course materials. - Updated the dashboard to include a new component for displaying content count badges for lessons and exercises. - Enhanced document management features, including a new document card component with dropdown actions for viewing, downloading, and removing documents. - Improved file upload handling with a dedicated file drop zone and error handling for file type and size restrictions. - Refactored existing components for better readability and maintainability, including updates to lesson and document lists. * chore: use root env file for docker compose * docs: document docker no-build startup flow * chore: add no-build option to docker full stack script * fix(email): handle SMTP TLS mode by port * feat(auth): add configurable cookie domain env and docs * apps/dashboard/src/lib/utils/services/auth/session.ts * fix(email): make sender configurable via SMTP_SENDER * chore(i18n): regenerate locale translations and support language targeting * chore(config): switch api to PUBLIC_SERVER_URL * fix(i18n): persist selected locale across navigation * feat(assets): implement organization asset management routes and services - Added new routes for managing organization assets, including listing, creating, updating, deleting, and exporting assets. - Introduced asset-related services for handling asset operations such as creation, retrieval, and deletion. - Integrated YouTube metadata resolution and asset attachment/detachment functionalities. - Updated organization routes to include the new asset management routes. - Enhanced error handling for asset-related operations. * fix(document-list): update conditional rendering for edit mode in document list * debug self hosted layout setup * refactor(sidebar): simplify lms sidebar footer and improve navigation item rendering * feat: tags * chore: tags roadmap + translations * fix(api): add authMiddleware to exercise, invites, and content routers - exerciseRouter: apply authMiddleware before courseMemberMiddleware on all 10 routes - invitesRouter: apply authMiddleware before courseTeamMemberMiddleware on all 4 routes - contentRouter: add authMiddleware to PUT route (DELETE already had it) Both courseMemberMiddleware and courseTeamMemberMiddleware document requiring authMiddleware to be applied first. This aligns with lessonRouter pattern and ensures explicit middleware contract regardless of global session middleware. Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * fix(course): use courseTeamMemberMiddleware for PUT, DELETE, and analytics routes These routes require admin/tutor role per JSDoc but were using courseMemberMiddleware which allows any course member including students. Switch to courseTeamMemberMiddleware to restrict access to ADMIN/TUTOR group members and org admins. Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * chore: unify pricing component between dashboard and website (#630) * feat: modularize pricing card * feat: initia implementation of pricing togge * fix: minor amendment * refactor: update pricing components for improved layout and styling - Adjusted spacing in the pricing card layout for better visual consistency. - Modified button styles and sizes for enhanced usability. - Cleaned up the pricing toggle component by removing unnecessary console logs and restructuring the button rendering logic. * add handle click * chore(css): update Tailwind CSS output with new utility classes and theme variables * fix(api): enable orgMemberMiddleware for stats route This change ensures that the stats route is protected by orgMemberMiddleware, aligning access control with other routes. Additionally, removed unnecessary console log from the layout server file to clean up the code. --------- Co-authored-by: Rotimi Best <best@classroomio.com> * pass query parameter to signup from pricing page * ui updates to pricing cards * commit all PRDs * add open api spec to api prd * make blue default theme * more prds * sync option id sequence on question update * docs: more classroomio features * chore: more ui improvements * docs: new component docs * chore: CSP Configuration (#638) * feat(validation): add GitHub repository name validation - Add ZRepositoryName schema for validating GitHub repo names - Add ZRepositoryOwner for owner/username validation - Add ZRepositoryIdentifier for owner/repo format - Follow GitHub rules: A-Za-z0-9_.-, 1-100 chars, reserved names - Add translation keys for validation messages Fixes #637 Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * Revert "feat(validation): add GitHub repository name validation" This reverts commit 3436536bb17a0f05b3a9fe8dd7682cde64dd1dce. * feat(dashboard): make CSP external domains configurable via env Move hardcoded external domains from svelte.config.js to .env configuration for on-premise deployments with strict security policies, data residency constraints, or CISO-driven allowlists. - ALLOWED_EXTERNAL_DOMAINS: single list for all CSP directives - CSP_SCRIPT_SRC_DOMAINS, CSP_STYLE_SRC_DOMAINS, CSP_CONNECT_SRC_DOMAINS, CSP_FRAME_SRC_DOMAINS, CSP_FONT_SRC_DOMAINS: per-directive override - When unset, defaults retain current SaaS behavior (backward compatible) Fixes #637 Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * fix(dashboard): self-hosted CSP uses only env vars, no defaults Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * fix(dashboard): add all classroomio.com domains to CSP defaults Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat(docker): pass CSP domain env vars as build args to dashboard Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat: add SSO and token authentication routes and services - Introduced new routes for SSO and token authentication under the organization namespace. - Implemented SSO connection management including creation, update, activation, and deletion. - Added token authentication configuration with support for secret rotation and status retrieval. - Enhanced error handling for SSO and token authentication processes. - Updated existing routes and services to integrate new functionalities. - Improved gradebook service to fetch student marks and exercises. - Refactored API structure for better organization and maintainability. * update translations * fix: add PUBLIC_SERVER_URL to .env.example to prevent localhost fallback in production (#641) Co-authored-by: Cursor Agent <cursoragent@cursor.com> * feat: new exercise question types * MinIO S3 storage backend (#639) * feat(storage): add MinIO/S3-compatible object storage backend - Add OBJECT_STORAGE_* env vars for generic S3-compatible backends (MinIO, AWS S3) - Create storage config module with Cloudflare R2 fallback for backward compatibility - Refactor s3.ts to use configurable client and bucket names from config - Update media.ts to use provider-neutral public URL (OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN) - Add MinIO service and init to docker-compose (profile: minio) with videos/documents/media buckets - Add localhost:9000 to dashboard CSP for local MinIO presigned URL uploads - Update self-hosting and Cloudflare docs with MinIO option - Update .env examples and docker USAGE.md Fixes #635 Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat(media): refactor media management and integrate MinIO support - Updated media API to use a new `mediaApi` module, replacing `mediaManagerApi` references across components. - Added MinIO configuration options to the Docker setup, allowing for optional object storage exclusion. - Enhanced environment variable management for MinIO in the `.env.example` file. - Updated Content Security Policy (CSP) to allow local MinIO access in the dashboard. - Introduced new media components for asset management, including asset cards and usage dialogs. This refactor improves the modularity of the media handling system and provides better support for S3-compatible storage solutions. * feat(dashboard): enhance logging and refactor auth session handling - Added console logging for event and environment variables in hooks.server.ts to aid debugging. - Refactored auth session handling to use authServerClient instead of authClient in session.ts for improved consistency. - Updated Dockerfile to ensure the dashboard build output is present before starting the application. - Expanded self-hosting documentation to include troubleshooting steps for disk space issues in PostgreSQL and Docker. These changes improve the observability of the application and streamline the authentication process. * refactor(dashboard): remove debug logging and enhance Postgres healthcheck - Removed console logging for event and environment variables in hooks.server.ts to clean up the code. - Updated Postgres healthcheck in docker-compose.yaml to require a successful `SELECT 1` query, ensuring dependent services only start once the database is ready. - Expanded self-hosting documentation to include troubleshooting steps for database recovery issues. These changes improve code clarity and reliability in service startup sequences. --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat: add Plyr media player icons and PDF.js integration - Introduced new Plyr SVG icons for media player controls in both course and dashboard applications. - Updated Plyr player configuration to use local icon assets. - Integrated PDF.js for document viewing, replacing external CDN links with local paths for improved performance and reliability. - Enhanced PDF viewer modal z-index for better visibility. This update improves the media player experience and ensures consistent access to necessary resources. * feat: enhance account and organization services with type definitions and promise return types - Updated `getAccountData` to return a structured result type including profile and organizations. - Modified `getOrganizationsWithFilters` to specify a promise return type for better type safety. - Added new type imports for organization-related data structures to improve clarity and maintainability. These changes improve type safety and enhance the overall structure of the account and organization services. * feat: implement Redis caching for presigned URLs and refactor API interactions - Added Redis caching for presigned download URLs in the API to reduce redundant S3 calls, improving performance. - Introduced a new `PresignApi` class in the frontend to centralize presigned URL requests, enhancing code maintainability. - Updated various components to utilize the new `presignApi` methods for document and video upload/download operations. - Enhanced error handling for Redis operations to ensure graceful degradation in case of cache failures. These changes optimize the presigned URL generation process and streamline API interactions across the application. * fix: add better-auth dependency to dashboard (#645) * chore: unify exercise answer data format * feat: make selfhosting run under one org for simplicity (#647) * feat: implement self-hosting PRD + license key system Self-hosting single-org: - Add PUBLIC_IS_SELFHOSTED to API env, block org creation when org exists - Auto-add non-members as students in GET /account bootstrap - getOrgSiteInfo: root domain returns single org for self-hosted - App init: route to /lms when self-hosted + no orgs - Hide org switcher and Add Org modal when self-hosted Invite-only signup: - Add settings.signup.inviteOnly via ZUpdateOrganization - Allow public signups toggle in org auth settings - Signup page: hide form when invite-only and no invite context - Landing page nav: respect inviteOnly for signup link First signup auto-verify: - Self-hosted first signup (no orgs) auto-verifies email in createProfileHook License key system: - LICENSE_KEY, LICENSE_VERIFICATION_URL for external verification API - Feature gates: SSO, token-auth, no-tracking (PostHog/Senja) - requireLicense middleware for API routes - Dashboard: license store, gate PostHog/Senja/SSO/token-auth UI - docs/LICENSE_API_CONTRACT.md for external API spec Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat: get rid of carbon completely * chore: license verification happens only for selfhosted instance * fix: in self hosted instance, orgSite is the default * docs: how to write math in cio editor * Update packages/db/src/queries/organization/organization.ts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * Update apps/api/src/services/license.ts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * fix: translations, cursor pr reviews, simplify license fetching and check * refactor: update analytics setup for cloud and self-hosted deployments; enhance settings merge logic * refactor: update license fetching URL for development environment; optimize organization query to prevent plan row loss * more selfhosting improvements * feat: enhance signup guard for self-hosted instances by requiring organization context when no org ID is provided * pr reviews * fix: correct query parameter handling in course navigation * pr reviews --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> Co-authored-by: Abdulmuizz Hamzat <103611443+buildwithhamzat@users.noreply.github.com> Co-authored-by: Adeyemi Adetunji <tvnji01@gmail.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Rotimi Best
greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Cursor Agent
Abdulmuizz Hamzat
Adeyemi Adetunji
parent
a42565ad82
commit
1e9a82e912
@@ -0,0 +1,56 @@
|
||||
export { default as QuestionFormRoot } from './question-form-root.svelte';
|
||||
export { default as QuestionNavigation } from './question-navigation.svelte';
|
||||
export { default as QuestionRenderer } from './question-renderer.svelte';
|
||||
export { default as QuestionList } from './question-list.svelte';
|
||||
export { default as QuestionSurface } from './question-surface.svelte';
|
||||
export { default as QuestionTitle } from './question-title.svelte';
|
||||
export * from './renderer-contract';
|
||||
|
||||
export { default as TrueFalseEdit } from './renderers/true-false/edit.svelte';
|
||||
export { default as ShortAnswerEdit } from './renderers/short-answer/edit.svelte';
|
||||
export { default as NumericEdit } from './renderers/numeric/edit.svelte';
|
||||
export { default as FillBlankEdit } from './renderers/fill-blank/edit.svelte';
|
||||
export { default as FileUploadEdit } from './renderers/file-upload/edit.svelte';
|
||||
export { default as RadioEdit } from './renderers/radio/edit.svelte';
|
||||
export { default as CheckboxEdit } from './renderers/checkbox/edit.svelte';
|
||||
export { default as TextareaEdit } from './renderers/textarea/edit.svelte';
|
||||
export { default as MatchingEdit } from './renderers/matching/edit.svelte';
|
||||
export { default as OrderingEdit } from './renderers/ordering/edit.svelte';
|
||||
export { default as HotspotEdit } from './renderers/hotspot/edit.svelte';
|
||||
|
||||
export { default as TrueFalseTake } from './renderers/true-false/take.svelte';
|
||||
export { default as ShortAnswerTake } from './renderers/short-answer/take.svelte';
|
||||
export { default as NumericTake } from './renderers/numeric/take.svelte';
|
||||
export { default as FillBlankTake } from './renderers/fill-blank/take.svelte';
|
||||
export { default as FileUploadTake } from './renderers/file-upload/take.svelte';
|
||||
export { default as RadioTake } from './renderers/radio/take.svelte';
|
||||
export { default as CheckboxTake } from './renderers/checkbox/take.svelte';
|
||||
export { default as TextareaTake } from './renderers/textarea/take.svelte';
|
||||
export { default as MatchingTake } from './renderers/matching/take.svelte';
|
||||
export { default as OrderingTake } from './renderers/ordering/take.svelte';
|
||||
export { default as HotspotTake } from './renderers/hotspot/take.svelte';
|
||||
|
||||
export { default as TrueFalsePreview } from './renderers/true-false/preview.svelte';
|
||||
export { default as ShortAnswerPreview } from './renderers/short-answer/preview.svelte';
|
||||
export { default as NumericPreview } from './renderers/numeric/preview.svelte';
|
||||
export { default as FillBlankPreview } from './renderers/fill-blank/preview.svelte';
|
||||
export { default as FileUploadPreview } from './renderers/file-upload/preview.svelte';
|
||||
export { default as RadioPreview } from './renderers/radio/preview.svelte';
|
||||
export { default as CheckboxPreview } from './renderers/checkbox/preview.svelte';
|
||||
export { default as TextareaPreview } from './renderers/textarea/preview.svelte';
|
||||
export { default as MatchingPreview } from './renderers/matching/preview.svelte';
|
||||
export { default as OrderingPreview } from './renderers/ordering/preview.svelte';
|
||||
export { default as HotspotPreview } from './renderers/hotspot/preview.svelte';
|
||||
|
||||
export { default as TrueFalseSubmission } from './renderers/true-false/submission.svelte';
|
||||
export { default as ShortAnswerSubmission } from './renderers/short-answer/submission.svelte';
|
||||
export { default as NumericSubmission } from './renderers/numeric/submission.svelte';
|
||||
export { default as FillBlankSubmission } from './renderers/fill-blank/submission.svelte';
|
||||
export { default as FileUploadSubmission } from './renderers/file-upload/submission.svelte';
|
||||
export { default as RadioSubmission } from './renderers/radio/submission.svelte';
|
||||
export { default as CheckboxSubmission } from './renderers/checkbox/submission.svelte';
|
||||
export { default as TextareaSubmission } from './renderers/textarea/submission.svelte';
|
||||
export { default as MatchingSubmission } from './renderers/matching/submission.svelte';
|
||||
export { default as OrderingSubmission } from './renderers/ordering/submission.svelte';
|
||||
export { default as HotspotSubmission } from './renderers/hotspot/submission.svelte';
|
||||
export { default as LinkSubmission } from './renderers/link/submission.svelte';
|
||||
@@ -0,0 +1,26 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
description?: string;
|
||||
children?: Snippet;
|
||||
}
|
||||
|
||||
let { title = '', description = '', children }: Props = $props();
|
||||
</script>
|
||||
|
||||
<section class="ui:space-y-4">
|
||||
{#if title}
|
||||
<header class="ui:space-y-1">
|
||||
<h2 class="ui:text-lg ui:font-semibold">{title}</h2>
|
||||
{#if description}
|
||||
<p class="ui:text-muted-foreground ui:text-sm">{description}</p>
|
||||
{/if}
|
||||
</header>
|
||||
{/if}
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
{@render children?.()}
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1,43 @@
|
||||
<script lang="ts">
|
||||
import type { AnswerData, ExerciseQuestionListRenderContract, ExerciseQuestionModel } from '@cio/question-types';
|
||||
import { getExerciseQuestionContractKey } from '@cio/question-types';
|
||||
import QuestionRenderer from './question-renderer.svelte';
|
||||
|
||||
interface Props {
|
||||
contract: ExerciseQuestionListRenderContract;
|
||||
onAnswerChange?: (question: ExerciseQuestionModel, answer: AnswerData) => void;
|
||||
onQuestionChange?: (question: ExerciseQuestionModel, updatedQuestion: ExerciseQuestionModel) => void;
|
||||
itemClass?: string;
|
||||
showContainer?: boolean;
|
||||
}
|
||||
|
||||
let {
|
||||
contract,
|
||||
onAnswerChange = () => {},
|
||||
onQuestionChange = () => {},
|
||||
itemClass = '',
|
||||
showContainer = true
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
{#each contract.questions as question, index (getExerciseQuestionContractKey(question, index))}
|
||||
{@const questionKey = getExerciseQuestionContractKey(question, index)}
|
||||
<div class={itemClass}>
|
||||
<QuestionRenderer
|
||||
contract={{
|
||||
mode: contract.mode,
|
||||
question,
|
||||
answer: contract.answersByKey?.[questionKey],
|
||||
submissions: contract.submissions,
|
||||
maxSubmissionItems: contract.maxSubmissionItems,
|
||||
disabled: contract.disabled,
|
||||
labels: contract.labels,
|
||||
onImageUpload: contract.onImageUpload,
|
||||
onFileUpload: contract.onFileUpload
|
||||
}}
|
||||
onAnswerChange={(answer) => onAnswerChange(question, answer)}
|
||||
onQuestionChange={(updatedQuestion) => onQuestionChange(question, updatedQuestion)}
|
||||
{showContainer}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
@@ -0,0 +1,42 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '../../base/button';
|
||||
|
||||
interface Props {
|
||||
canGoBack?: boolean;
|
||||
canGoNext?: boolean;
|
||||
isLast?: boolean;
|
||||
isSubmitting?: boolean;
|
||||
previousLabel?: string;
|
||||
nextLabel?: string;
|
||||
finishLabel?: string;
|
||||
onPrevious?: () => void;
|
||||
onNext?: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
canGoBack = true,
|
||||
canGoNext = true,
|
||||
isLast = false,
|
||||
isSubmitting = false,
|
||||
previousLabel = '',
|
||||
nextLabel = '',
|
||||
finishLabel = '',
|
||||
onPrevious = () => {},
|
||||
onNext = () => {}
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="flex justify-end gap-3">
|
||||
<Button type="button" variant="outline" size="sm" onclick={() => onPrevious()} disabled={!canGoBack || isSubmitting}>
|
||||
{previousLabel}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onclick={() => onNext()}
|
||||
size="sm"
|
||||
disabled={!canGoNext || isSubmitting}
|
||||
loading={isLast && isSubmitting}
|
||||
>
|
||||
{isLast ? finishLabel : nextLabel}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -0,0 +1,477 @@
|
||||
<script lang="ts">
|
||||
import type {
|
||||
AnswerData,
|
||||
ExerciseQuestionModel,
|
||||
ExerciseQuestionRenderContract,
|
||||
ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import { getExerciseQuestionLabel } from '@cio/question-types';
|
||||
import PlusIcon from '@lucide/svelte/icons/plus';
|
||||
import XIcon from '@lucide/svelte/icons/x';
|
||||
import * as Dialog from '../../base/dialog';
|
||||
import * as DropdownMenu from '../../base/dropdown-menu';
|
||||
import { Input } from '../../base/input';
|
||||
import { Textarea } from '../../base/textarea';
|
||||
import { IconButton } from '../icon-button';
|
||||
import { MediaPlayer, isYoutubeUrl } from '../media-player';
|
||||
import QuestionTitle from './question-title.svelte';
|
||||
import { YoutubeLinkForm } from '../youtube-link-form';
|
||||
import QuestionSurface from './question-surface.svelte';
|
||||
import { getExerciseQuestionRenderer } from './renderer-contract';
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
interface Props {
|
||||
contract: ExerciseQuestionRenderContract;
|
||||
onAnswerChange?: (answer: AnswerData) => void;
|
||||
onQuestionChange?: (question: ExerciseQuestionRendererProps['question']) => void;
|
||||
showContainer?: boolean;
|
||||
questionTypeSelect?: Snippet;
|
||||
}
|
||||
|
||||
let {
|
||||
contract,
|
||||
onAnswerChange = () => {},
|
||||
onQuestionChange = () => {},
|
||||
showContainer = true,
|
||||
questionTypeSelect
|
||||
}: Props = $props();
|
||||
|
||||
const Renderer = $derived(getExerciseQuestionRenderer(contract.question.questionType, contract.mode));
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(contract.labels, key, fallback);
|
||||
|
||||
let imageFileInput = $state<HTMLInputElement | null>(null);
|
||||
let isImageUploading = $state(false);
|
||||
let imageUploadError = $state('');
|
||||
let isDescriptionEditorVisible = $state(false);
|
||||
let isYoutubeDialogOpen = $state(false);
|
||||
|
||||
const questionDescription = $derived(String((contract.question.settings?.description as string | undefined) ?? ''));
|
||||
const hasDescription = $derived(isDescriptionEditorVisible || questionDescription.trim().length > 0);
|
||||
const questionImageUrls = $derived.by(() => {
|
||||
const settings = contract.question.settings ?? {};
|
||||
|
||||
const explicitImageUrls = Array.isArray(settings.imageUrls)
|
||||
? settings.imageUrls.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||
: [];
|
||||
|
||||
if (explicitImageUrls.length > 0) return explicitImageUrls;
|
||||
|
||||
const legacyImageUrl = settings.imageUrl;
|
||||
if (typeof legacyImageUrl === 'string' && legacyImageUrl.trim().length > 0) return [legacyImageUrl];
|
||||
|
||||
return [] as string[];
|
||||
});
|
||||
const questionVideoUrls = $derived.by(() => {
|
||||
const settings = contract.question.settings ?? {};
|
||||
|
||||
const explicitVideoUrls = Array.isArray(settings.videoUrls)
|
||||
? settings.videoUrls.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||
: [];
|
||||
|
||||
if (explicitVideoUrls.length > 0) return explicitVideoUrls;
|
||||
|
||||
const legacyVideoUrl = settings.videoUrl;
|
||||
if (typeof legacyVideoUrl === 'string' && legacyVideoUrl.trim().length > 0) return [legacyVideoUrl];
|
||||
|
||||
return [] as string[];
|
||||
});
|
||||
const questionVideos = $derived.by(() =>
|
||||
questionVideoUrls
|
||||
.map((videoUrl, index) => {
|
||||
const sourceUrl = videoUrl.trim();
|
||||
return sourceUrl.length > 0
|
||||
? {
|
||||
key: `${sourceUrl}-${index}`,
|
||||
sourceIndex: index,
|
||||
sourceUrl
|
||||
}
|
||||
: null;
|
||||
})
|
||||
.filter((entry): entry is { key: string; sourceIndex: number; sourceUrl: string } =>
|
||||
Boolean(entry && isYoutubeUrl(entry.sourceUrl))
|
||||
)
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (questionDescription.trim().length > 0) {
|
||||
isDescriptionEditorVisible = true;
|
||||
}
|
||||
});
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...contract.question, ...partial });
|
||||
}
|
||||
|
||||
function patchSettings(next: Record<string, unknown>) {
|
||||
patchQuestion({
|
||||
settings: {
|
||||
...(contract.question.settings ?? {}),
|
||||
...next
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setQuestionDescription(nextDescription: string | null) {
|
||||
const nextSettings = { ...(contract.question.settings ?? {}) } as Record<string, unknown>;
|
||||
|
||||
if (nextDescription === null) {
|
||||
delete nextSettings.description;
|
||||
} else {
|
||||
nextSettings.description = nextDescription;
|
||||
}
|
||||
|
||||
patchQuestion({
|
||||
settings: nextSettings
|
||||
});
|
||||
}
|
||||
|
||||
function setQuestionImageUrls(nextUrls: string[]) {
|
||||
const deduped = Array.from(new Set(nextUrls.map((value) => value.trim()).filter(Boolean)));
|
||||
const nextSettings = {
|
||||
...(contract.question.settings ?? {}),
|
||||
imageUrls: deduped
|
||||
} as Record<string, unknown>;
|
||||
|
||||
delete nextSettings.imageUrl;
|
||||
|
||||
patchQuestion({
|
||||
settings: nextSettings
|
||||
});
|
||||
}
|
||||
|
||||
function setQuestionVideoUrls(nextUrls: string[]) {
|
||||
const deduped = Array.from(new Set(nextUrls.map((value) => value.trim()).filter(Boolean)));
|
||||
const nextSettings = {
|
||||
...(contract.question.settings ?? {}),
|
||||
videoUrls: deduped
|
||||
} as Record<string, unknown>;
|
||||
|
||||
delete nextSettings.videoUrl;
|
||||
|
||||
patchQuestion({
|
||||
settings: nextSettings
|
||||
});
|
||||
}
|
||||
|
||||
function openImagePicker() {
|
||||
if (contract.disabled || isImageUploading) return;
|
||||
imageFileInput?.click();
|
||||
}
|
||||
|
||||
function fileToDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = () => {
|
||||
if (!reader.result) {
|
||||
reject(new Error('Failed to read image file'));
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(String(reader.result));
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
reject(reader.error ?? new Error('Failed to read image file'));
|
||||
};
|
||||
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
async function uploadQuestionImage(file: File): Promise<string> {
|
||||
if (contract.onImageUpload) {
|
||||
return contract.onImageUpload(file);
|
||||
}
|
||||
|
||||
return fileToDataUrl(file);
|
||||
}
|
||||
|
||||
async function handleImageFileSelection(event: Event) {
|
||||
const input = event.currentTarget as HTMLInputElement;
|
||||
const selectedFiles = Array.from(input.files ?? []);
|
||||
input.value = '';
|
||||
|
||||
if (!selectedFiles.length) return;
|
||||
|
||||
const validFiles = selectedFiles.filter((file) => file.type.startsWith('image/'));
|
||||
if (!validFiles.length) {
|
||||
imageUploadError = label('question.edit.upload_error_only_images');
|
||||
return;
|
||||
}
|
||||
|
||||
imageUploadError = '';
|
||||
isImageUploading = true;
|
||||
|
||||
try {
|
||||
const uploadedUrls: string[] = [];
|
||||
|
||||
for (const file of validFiles) {
|
||||
const uploadedUrl = await uploadQuestionImage(file);
|
||||
if (!uploadedUrl) continue;
|
||||
uploadedUrls.push(uploadedUrl);
|
||||
}
|
||||
|
||||
if (uploadedUrls.length > 0) {
|
||||
setQuestionImageUrls([...questionImageUrls, ...uploadedUrls]);
|
||||
}
|
||||
|
||||
if (validFiles.length !== selectedFiles.length) {
|
||||
imageUploadError = label('question.edit.upload_error_skipped');
|
||||
}
|
||||
} catch (error) {
|
||||
imageUploadError = label('question.edit.upload_error_failed');
|
||||
console.error('Failed to upload question image:', error);
|
||||
} finally {
|
||||
isImageUploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function removeImage(imageIndex: number) {
|
||||
setQuestionImageUrls(questionImageUrls.filter((_, index) => index !== imageIndex));
|
||||
imageUploadError = '';
|
||||
}
|
||||
|
||||
function onDescriptionAction() {
|
||||
if (contract.disabled) return;
|
||||
|
||||
if (hasDescription) {
|
||||
isDescriptionEditorVisible = false;
|
||||
setQuestionDescription(null);
|
||||
return;
|
||||
}
|
||||
|
||||
isDescriptionEditorVisible = true;
|
||||
setQuestionDescription(questionDescription);
|
||||
}
|
||||
|
||||
function openYoutubeDialog() {
|
||||
if (contract.disabled) return;
|
||||
isYoutubeDialogOpen = true;
|
||||
}
|
||||
|
||||
async function addYoutubeVideos(links: string[]) {
|
||||
if (!links.length) return;
|
||||
setQuestionVideoUrls([...questionVideoUrls, ...links]);
|
||||
isYoutubeDialogOpen = false;
|
||||
}
|
||||
|
||||
function removeVideo(videoIndex: number) {
|
||||
setQuestionVideoUrls(questionVideoUrls.filter((_, index) => index !== videoIndex));
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet content()}
|
||||
{#if contract.mode === 'edit'}
|
||||
<div class="ui:space-y-3">
|
||||
<div class="ui:flex ui:items-end ui:gap-2">
|
||||
<div class="ui:space-y-1 ui:w-full">
|
||||
<p class="ui:text-sm ui:font-medium">{label('question.edit.title_label')}</p>
|
||||
<Input
|
||||
class="ui:w-full"
|
||||
value={contract.question.title}
|
||||
placeholder={label('question.edit.title_placeholder')}
|
||||
disabled={contract.disabled}
|
||||
onchange={(event) => patchQuestion({ title: event.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DropdownMenu.Root>
|
||||
<DropdownMenu.Trigger disabled={contract.disabled}>
|
||||
{#snippet child({ props })}
|
||||
<IconButton {...props} type="button" disabled={contract.disabled}>
|
||||
<PlusIcon class="ui:size-4" />
|
||||
<span class="ui:sr-only">{label('question.edit.media_menu_sr')}</span>
|
||||
</IconButton>
|
||||
{/snippet}
|
||||
</DropdownMenu.Trigger>
|
||||
<DropdownMenu.Content align="end">
|
||||
<DropdownMenu.Item disabled={contract.disabled} onclick={onDescriptionAction}>
|
||||
{hasDescription ? label('question.edit.remove_description') : label('question.edit.add_description')}
|
||||
</DropdownMenu.Item>
|
||||
<DropdownMenu.Item disabled={contract.disabled || isImageUploading} onclick={openImagePicker}>
|
||||
{label('question.edit.add_image')}
|
||||
</DropdownMenu.Item>
|
||||
<DropdownMenu.Item disabled={contract.disabled} onclick={openYoutubeDialog}>
|
||||
{label('question.edit.add_video')}
|
||||
</DropdownMenu.Item>
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Root>
|
||||
{#if questionTypeSelect}
|
||||
{@render questionTypeSelect()}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if hasDescription}
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-sm ui:font-medium">{label('question.edit.description_label')}</p>
|
||||
<Textarea
|
||||
rows={2}
|
||||
value={questionDescription}
|
||||
placeholder={label('question.edit.description_placeholder')}
|
||||
disabled={contract.disabled}
|
||||
onchange={(event) => patchSettings({ description: event.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<input
|
||||
bind:this={imageFileInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
class="ui:hidden"
|
||||
disabled={contract.disabled || isImageUploading}
|
||||
onchange={handleImageFileSelection}
|
||||
/>
|
||||
|
||||
{#if imageUploadError || questionImageUrls.length > 0}
|
||||
<div class="ui:space-y-2">
|
||||
{#if imageUploadError}
|
||||
<p class="ui:text-destructive ui:text-xs">{imageUploadError}</p>
|
||||
{/if}
|
||||
|
||||
{#if questionImageUrls.length > 0}
|
||||
<div class="ui:flex ui:flex-wrap ui:gap-3">
|
||||
{#each questionImageUrls as imageUrl, imageIndex (`${imageUrl}-${imageIndex}`)}
|
||||
<div class="ui:group ui:relative ui:h-40 ui:w-40 ui:rounded-md ui:border">
|
||||
<div class="ui:absolute ui:inset-0 ui:overflow-hidden ui:rounded-md">
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={label('question.edit.image_alt')}
|
||||
class="ui:h-full ui:w-full ui:object-cover"
|
||||
/>
|
||||
</div>
|
||||
<IconButton
|
||||
disabled={contract.disabled}
|
||||
tooltipClass="ui:absolute ui:right-[-12px] ui:top-[-12px] ui:z-10"
|
||||
class="ui:opacity-0 ui:transition-opacity ui:group-hover:opacity-100"
|
||||
tooltip={label('question.edit.remove_image_tooltip')}
|
||||
onclick={() => removeImage(imageIndex)}
|
||||
size="icon-sm"
|
||||
>
|
||||
<XIcon />
|
||||
<span class="ui:sr-only">{label('question.edit.remove_image_sr')}</span>
|
||||
</IconButton>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if questionVideos.length > 0}
|
||||
<div class="ui:space-y-3">
|
||||
{#each questionVideos as video (video.key)}
|
||||
<div class="ui:group ui:relative ui:max-w-xl ui:rounded-md ui:border">
|
||||
<MediaPlayer
|
||||
source={{
|
||||
type: 'youtube',
|
||||
url: video.sourceUrl
|
||||
}}
|
||||
options={{
|
||||
maxHeight: '320px',
|
||||
width: '100%',
|
||||
controls: true,
|
||||
playsinline: true
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
disabled={contract.disabled}
|
||||
tooltipClass="ui:absolute ui:right-[-12px] ui:top-[-12px] ui:z-10"
|
||||
class="ui:opacity-0 ui:transition-opacity ui:group-hover:opacity-100"
|
||||
tooltip={label('question.edit.remove_video_tooltip')}
|
||||
onclick={() => removeVideo(video.sourceIndex)}
|
||||
size="icon-sm"
|
||||
>
|
||||
<XIcon />
|
||||
<span class="ui:sr-only">{label('question.edit.remove_video_sr')}</span>
|
||||
</IconButton>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Dialog.Root bind:open={isYoutubeDialogOpen}>
|
||||
<Dialog.Content class="ui:max-w-xl">
|
||||
<Dialog.Header>
|
||||
<Dialog.Title>{label('question.edit.video_modal_title')}</Dialog.Title>
|
||||
</Dialog.Header>
|
||||
<YoutubeLinkForm
|
||||
inputLabel={label('question.edit.video_link_label')}
|
||||
inputPlaceholder={label('question.edit.video_link_placeholder')}
|
||||
addButtonLabel={label('question.edit.video_add_button')}
|
||||
invalidYoutubeMessage={label('question.edit.video_invalid_link')}
|
||||
disabled={contract.disabled}
|
||||
onSubmit={addYoutubeVideos}
|
||||
/>
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
{/if}
|
||||
|
||||
{#if contract.mode !== 'edit'}
|
||||
<div class="ui:mb-4 ui:space-y-3">
|
||||
{#if contract.question.title.trim().length > 0}
|
||||
<QuestionTitle title={contract.question.title} />
|
||||
{/if}
|
||||
|
||||
{#if questionDescription.trim().length > 0}
|
||||
<p class="ui:text-sm ui:text-muted-foreground">{questionDescription}</p>
|
||||
{/if}
|
||||
|
||||
{#if questionImageUrls.length > 0}
|
||||
<div class="ui:flex ui:flex-wrap ui:gap-3">
|
||||
{#each questionImageUrls as imageUrl, imageIndex (`${imageUrl}-${imageIndex}`)}
|
||||
<div class="ui:h-40 ui:w-40 ui:overflow-hidden ui:rounded-md ui:border">
|
||||
<img src={imageUrl} alt={label('question.edit.image_alt')} class="ui:h-full ui:w-full ui:object-cover" />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if questionVideos.length > 0}
|
||||
<div class="ui:space-y-3">
|
||||
{#each questionVideos as video (video.key)}
|
||||
<div class="ui:max-w-xl ui:overflow-hidden ui:rounded-md ui:border">
|
||||
<MediaPlayer
|
||||
source={{
|
||||
type: 'youtube',
|
||||
url: video.sourceUrl
|
||||
}}
|
||||
options={{
|
||||
maxHeight: '320px',
|
||||
width: '100%',
|
||||
controls: true,
|
||||
playsinline: true
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<Renderer
|
||||
question={contract.question}
|
||||
answer={contract.answer}
|
||||
submissions={contract.submissions}
|
||||
maxSubmissionItems={contract.maxSubmissionItems}
|
||||
disabled={contract.disabled}
|
||||
labels={contract.labels}
|
||||
onImageUpload={contract.onImageUpload}
|
||||
onFileUpload={contract.onFileUpload}
|
||||
{onAnswerChange}
|
||||
{onQuestionChange}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
{#if showContainer}
|
||||
<QuestionSurface>
|
||||
{@render content()}
|
||||
</QuestionSurface>
|
||||
{:else}
|
||||
{@render content()}
|
||||
{/if}
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { cn } from '../../tools';
|
||||
|
||||
interface Props {
|
||||
class?: string;
|
||||
children?: import('svelte').Snippet;
|
||||
}
|
||||
|
||||
let { class: className = '', children }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class={cn('ui:rounded-md ui:border ui:p-4', className)}>
|
||||
{@render children?.()}
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { cn } from '../../tools';
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
class?: string;
|
||||
}
|
||||
|
||||
let { title, class: className = '' }: Props = $props();
|
||||
</script>
|
||||
|
||||
<h4 class={cn('ui:font-medium', className)}>{title}</h4>
|
||||
@@ -0,0 +1,153 @@
|
||||
import {
|
||||
QUESTION_TYPE_KEY,
|
||||
getRendererForMode,
|
||||
type ExerciseRendererDefinition,
|
||||
type ExerciseRendererMode,
|
||||
type ExerciseRendererRegistry,
|
||||
type ExerciseQuestionRendererProps,
|
||||
type ExerciseQuestionTypeKey
|
||||
} from '@cio/question-types';
|
||||
import type { Component } from 'svelte';
|
||||
|
||||
import { default as CheckboxEdit } from './renderers/checkbox/edit.svelte';
|
||||
import { default as FileUploadEdit } from './renderers/file-upload/edit.svelte';
|
||||
import { default as FillBlankEdit } from './renderers/fill-blank/edit.svelte';
|
||||
import { default as HotspotEdit } from './renderers/hotspot/edit.svelte';
|
||||
import { default as MatchingEdit } from './renderers/matching/edit.svelte';
|
||||
import { default as NumericEdit } from './renderers/numeric/edit.svelte';
|
||||
import { default as OrderingEdit } from './renderers/ordering/edit.svelte';
|
||||
import { default as RadioEdit } from './renderers/radio/edit.svelte';
|
||||
import { default as LinkEdit } from './renderers/link/edit.svelte';
|
||||
import { default as ShortAnswerEdit } from './renderers/short-answer/edit.svelte';
|
||||
import { default as TextareaEdit } from './renderers/textarea/edit.svelte';
|
||||
import { default as TrueFalseEdit } from './renderers/true-false/edit.svelte';
|
||||
|
||||
import { default as CheckboxTake } from './renderers/checkbox/take.svelte';
|
||||
import { default as FileUploadTake } from './renderers/file-upload/take.svelte';
|
||||
import { default as FillBlankTake } from './renderers/fill-blank/take.svelte';
|
||||
import { default as HotspotTake } from './renderers/hotspot/take.svelte';
|
||||
import { default as MatchingTake } from './renderers/matching/take.svelte';
|
||||
import { default as NumericTake } from './renderers/numeric/take.svelte';
|
||||
import { default as OrderingTake } from './renderers/ordering/take.svelte';
|
||||
import { default as RadioTake } from './renderers/radio/take.svelte';
|
||||
import { default as LinkTake } from './renderers/link/take.svelte';
|
||||
import { default as ShortAnswerTake } from './renderers/short-answer/take.svelte';
|
||||
import { default as TextareaTake } from './renderers/textarea/take.svelte';
|
||||
import { default as TrueFalseTake } from './renderers/true-false/take.svelte';
|
||||
|
||||
import { default as CheckboxPreview } from './renderers/checkbox/preview.svelte';
|
||||
import { default as FileUploadPreview } from './renderers/file-upload/preview.svelte';
|
||||
import { default as FillBlankPreview } from './renderers/fill-blank/preview.svelte';
|
||||
import { default as HotspotPreview } from './renderers/hotspot/preview.svelte';
|
||||
import { default as MatchingPreview } from './renderers/matching/preview.svelte';
|
||||
import { default as NumericPreview } from './renderers/numeric/preview.svelte';
|
||||
import { default as OrderingPreview } from './renderers/ordering/preview.svelte';
|
||||
import { default as RadioPreview } from './renderers/radio/preview.svelte';
|
||||
import { default as LinkPreview } from './renderers/link/preview.svelte';
|
||||
import { default as ShortAnswerPreview } from './renderers/short-answer/preview.svelte';
|
||||
import { default as TextareaPreview } from './renderers/textarea/preview.svelte';
|
||||
import { default as TrueFalsePreview } from './renderers/true-false/preview.svelte';
|
||||
|
||||
import { default as CheckboxSubmission } from './renderers/checkbox/submission.svelte';
|
||||
import { default as FileUploadSubmission } from './renderers/file-upload/submission.svelte';
|
||||
import { default as FillBlankSubmission } from './renderers/fill-blank/submission.svelte';
|
||||
import { default as HotspotSubmission } from './renderers/hotspot/submission.svelte';
|
||||
import { default as MatchingSubmission } from './renderers/matching/submission.svelte';
|
||||
import { default as NumericSubmission } from './renderers/numeric/submission.svelte';
|
||||
import { default as OrderingSubmission } from './renderers/ordering/submission.svelte';
|
||||
import { default as RadioSubmission } from './renderers/radio/submission.svelte';
|
||||
import { default as LinkSubmission } from './renderers/link/submission.svelte';
|
||||
import { default as ShortAnswerSubmission } from './renderers/short-answer/submission.svelte';
|
||||
import { default as TextareaSubmission } from './renderers/textarea/submission.svelte';
|
||||
import { default as TrueFalseSubmission } from './renderers/true-false/submission.svelte';
|
||||
|
||||
type SharedRendererComponent = Component<ExerciseQuestionRendererProps>;
|
||||
|
||||
export const EXERCISE_QUESTION_RENDERER_CONTRACT: ExerciseRendererRegistry<SharedRendererComponent> = {
|
||||
[QUESTION_TYPE_KEY.RADIO]: {
|
||||
edit: RadioEdit,
|
||||
take: RadioTake,
|
||||
preview: RadioPreview,
|
||||
submission: RadioSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.CHECKBOX]: {
|
||||
edit: CheckboxEdit,
|
||||
take: CheckboxTake,
|
||||
preview: CheckboxPreview,
|
||||
submission: CheckboxSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.TEXTAREA]: {
|
||||
edit: TextareaEdit,
|
||||
take: TextareaTake,
|
||||
preview: TextareaPreview,
|
||||
submission: TextareaSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.TRUE_FALSE]: {
|
||||
edit: TrueFalseEdit,
|
||||
take: TrueFalseTake,
|
||||
preview: TrueFalsePreview,
|
||||
submission: TrueFalseSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.SHORT_ANSWER]: {
|
||||
edit: ShortAnswerEdit,
|
||||
take: ShortAnswerTake,
|
||||
preview: ShortAnswerPreview,
|
||||
submission: ShortAnswerSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.NUMERIC]: {
|
||||
edit: NumericEdit,
|
||||
take: NumericTake,
|
||||
preview: NumericPreview,
|
||||
submission: NumericSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.FILL_BLANK]: {
|
||||
edit: FillBlankEdit,
|
||||
take: FillBlankTake,
|
||||
preview: FillBlankPreview,
|
||||
submission: FillBlankSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.FILE_UPLOAD]: {
|
||||
edit: FileUploadEdit,
|
||||
take: FileUploadTake,
|
||||
preview: FileUploadPreview,
|
||||
submission: FileUploadSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.MATCHING]: {
|
||||
edit: MatchingEdit,
|
||||
take: MatchingTake,
|
||||
preview: MatchingPreview,
|
||||
submission: MatchingSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.ORDERING]: {
|
||||
edit: OrderingEdit,
|
||||
take: OrderingTake,
|
||||
preview: OrderingPreview,
|
||||
submission: OrderingSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.HOTSPOT]: {
|
||||
edit: HotspotEdit,
|
||||
take: HotspotTake,
|
||||
preview: HotspotPreview,
|
||||
submission: HotspotSubmission
|
||||
},
|
||||
[QUESTION_TYPE_KEY.LINK]: {
|
||||
edit: LinkEdit,
|
||||
take: LinkTake,
|
||||
preview: LinkPreview,
|
||||
submission: LinkSubmission
|
||||
}
|
||||
};
|
||||
|
||||
const FALLBACK_RENDERER: ExerciseRendererDefinition<SharedRendererComponent> = {
|
||||
edit: ShortAnswerEdit,
|
||||
take: ShortAnswerTake,
|
||||
preview: ShortAnswerPreview,
|
||||
submission: ShortAnswerSubmission
|
||||
};
|
||||
|
||||
export function getExerciseQuestionRenderer(
|
||||
questionTypeKey: ExerciseQuestionTypeKey,
|
||||
mode: ExerciseRendererMode
|
||||
): SharedRendererComponent {
|
||||
return getRendererForMode(EXERCISE_QUESTION_RENDERER_CONTRACT, questionTypeKey, mode, FALLBACK_RENDERER);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionOption,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import PlusIcon from '@lucide/svelte/icons/plus';
|
||||
import Trash2Icon from '@lucide/svelte/icons/trash-2';
|
||||
import CheckIcon from '@lucide/svelte/icons/check';
|
||||
import CircleIcon from '@lucide/svelte/icons/circle';
|
||||
import { Button } from '../../../../base/button';
|
||||
import { Input } from '../../../../base/input';
|
||||
import { IconButton } from '../../../icon-button';
|
||||
import OptionImage from '../option-image.svelte';
|
||||
import { fileToDataUrl, getOptionImageUrl, mergeOptionSettings, removeOptionSetting } from '../option-image-utils';
|
||||
|
||||
let {
|
||||
question,
|
||||
disabled = false,
|
||||
labels,
|
||||
onQuestionChange = () => {},
|
||||
onImageUpload
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
let optionImageInput = $state<HTMLInputElement | null>(null);
|
||||
let optionImageTargetIndex = $state<number | null>(null);
|
||||
let optionImageError = $state('');
|
||||
let isOptionImageUploading = $state(false);
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
|
||||
function updateOption(index: number, partial: Partial<ExerciseQuestionOption>) {
|
||||
const options = [...(question.options ?? [])];
|
||||
const option = options[index];
|
||||
if (!option) return;
|
||||
|
||||
options[index] = { ...option, ...partial };
|
||||
patchQuestion({ options });
|
||||
}
|
||||
|
||||
function addOption() {
|
||||
patchQuestion({
|
||||
options: [
|
||||
...(question.options ?? []),
|
||||
{
|
||||
id: `${new Date().getTime()}-option`,
|
||||
label: '',
|
||||
value: '',
|
||||
isCorrect: false,
|
||||
settings: {}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
function removeOption(index: number) {
|
||||
const options = [...(question.options ?? [])];
|
||||
options.splice(index, 1);
|
||||
patchQuestion({ options });
|
||||
}
|
||||
|
||||
function toggleCorrectOption(index: number) {
|
||||
const options = [...(question.options ?? [])];
|
||||
const option = options[index];
|
||||
if (!option) return;
|
||||
|
||||
options[index] = {
|
||||
...option,
|
||||
isCorrect: option.isCorrect !== true
|
||||
};
|
||||
|
||||
patchQuestion({ options });
|
||||
}
|
||||
|
||||
function openOptionImagePicker(index: number) {
|
||||
if (disabled || isOptionImageUploading) return;
|
||||
|
||||
optionImageTargetIndex = index;
|
||||
optionImageInput?.click();
|
||||
}
|
||||
|
||||
async function uploadOptionImage(file: File): Promise<string> {
|
||||
if (onImageUpload) {
|
||||
return onImageUpload(file);
|
||||
}
|
||||
|
||||
return fileToDataUrl(file);
|
||||
}
|
||||
|
||||
async function handleOptionImageSelection(event: Event) {
|
||||
const targetIndex = optionImageTargetIndex;
|
||||
optionImageTargetIndex = null;
|
||||
|
||||
const input = event.currentTarget as HTMLInputElement;
|
||||
const selectedFile = input.files?.[0];
|
||||
input.value = '';
|
||||
|
||||
if (targetIndex === null || targetIndex < 0 || !selectedFile) return;
|
||||
|
||||
if (!selectedFile.type.startsWith('image/')) {
|
||||
optionImageError = label('question.edit.upload_error_only_images');
|
||||
return;
|
||||
}
|
||||
|
||||
optionImageError = '';
|
||||
isOptionImageUploading = true;
|
||||
|
||||
try {
|
||||
const imageUrl = await uploadOptionImage(selectedFile);
|
||||
if (!imageUrl) return;
|
||||
|
||||
const options = [...(question.options ?? [])];
|
||||
const option = options[targetIndex];
|
||||
if (!option) return;
|
||||
|
||||
options[targetIndex] = mergeOptionSettings(option, { imageUrl });
|
||||
patchQuestion({ options });
|
||||
} catch (error) {
|
||||
optionImageError = label('question.edit.upload_error_failed');
|
||||
console.error('Failed to upload option image:', error);
|
||||
} finally {
|
||||
isOptionImageUploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function removeOptionImage(index: number) {
|
||||
const options = [...(question.options ?? [])];
|
||||
const option = options[index];
|
||||
if (!option) return;
|
||||
|
||||
options[index] = removeOptionSetting(option, 'imageUrl');
|
||||
patchQuestion({ options });
|
||||
optionImageError = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('checkbox.edit.helper')}</p>
|
||||
{#if optionImageError}
|
||||
<p class="ui:text-destructive ui:text-xs">{optionImageError}</p>
|
||||
{/if}
|
||||
|
||||
<input
|
||||
bind:this={optionImageInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
class="ui:hidden"
|
||||
disabled={disabled || isOptionImageUploading}
|
||||
onchange={handleOptionImageSelection}
|
||||
/>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
{#each question.options ?? [] as option, index}
|
||||
{@const optionImageUrl = getOptionImageUrl(option)}
|
||||
<div class="ui:flex ui:items-start ui:gap-2">
|
||||
<IconButton
|
||||
type="button"
|
||||
{disabled}
|
||||
tooltip={option.isCorrect === true
|
||||
? label('checkbox.edit.correct_selected_tooltip')
|
||||
: label('checkbox.edit.toggle_correct_tooltip')}
|
||||
class={option.isCorrect === true
|
||||
? 'ui:text-primary ui:border-primary/30 ui:bg-primary/10'
|
||||
: 'ui:text-muted-foreground'}
|
||||
onclick={() => toggleCorrectOption(index)}
|
||||
>
|
||||
{#if option.isCorrect === true}
|
||||
<CheckIcon class="ui:size-4" />
|
||||
{:else}
|
||||
<CircleIcon class="ui:size-4" />
|
||||
{/if}
|
||||
<span class="ui:sr-only">{label('checkbox.edit.toggle_correct_sr')}</span>
|
||||
</IconButton>
|
||||
|
||||
<div class="ui:flex-1 ui:space-y-2">
|
||||
<Input
|
||||
class="ui:w-full"
|
||||
placeholder={[label('common.option_prefix'), String(index + 1)].filter(Boolean).join(' ').trim()}
|
||||
value={option.label}
|
||||
{disabled}
|
||||
onchange={(event) => updateOption(index, { label: event.currentTarget.value })}
|
||||
/>
|
||||
|
||||
<div class="ui:flex ui:flex-wrap ui:items-start ui:gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
type="button"
|
||||
disabled={disabled || isOptionImageUploading}
|
||||
onclick={() => openOptionImagePicker(index)}
|
||||
>
|
||||
<PlusIcon class="ui:size-4" />
|
||||
{label('question.edit.add_image')}
|
||||
</Button>
|
||||
|
||||
{#if optionImageUrl}
|
||||
<OptionImage
|
||||
src={optionImageUrl}
|
||||
alt={label('question.edit.image_alt')}
|
||||
variant="edit"
|
||||
onRemove={() => removeOptionImage(index)}
|
||||
{disabled}
|
||||
removeTooltip={label('question.edit.remove_image_tooltip')}
|
||||
removeSr={label('question.edit.remove_image_sr')}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<IconButton
|
||||
type="button"
|
||||
{disabled}
|
||||
tooltip={label('common.remove')}
|
||||
class="ui:text-muted-foreground"
|
||||
onclick={() => removeOption(index)}
|
||||
>
|
||||
<Trash2Icon class="ui:size-4" />
|
||||
<span class="ui:sr-only">{label('common.remove')}</span>
|
||||
</IconButton>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<Button variant="outline" type="button" {disabled} onclick={addOption}>{label('common.add_option')}</Button>
|
||||
</div>
|
||||
@@ -0,0 +1,35 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import OptionImage from '../option-image.svelte';
|
||||
import { getOptionImageUrl, hasOptionImages } from '../option-image-utils';
|
||||
import { cn } from '../../../../tools';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const optionsHaveImages = $derived(hasOptionImages(question.options));
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<ul class={optionsHaveImages ? 'ui:grid ui:grid-cols-2 ui:gap-3' : 'ui:space-y-1'}>
|
||||
{#each question.options ?? [] as option, index}
|
||||
{@const optionImageUrl = getOptionImageUrl(option)}
|
||||
<li class={cn(optionsHaveImages && 'ui:space-y-2 ui:rounded-md ui:p-2', 'ui:text-sm')}>
|
||||
<OptionImage
|
||||
src={optionImageUrl}
|
||||
alt={label('question.edit.image_alt')}
|
||||
variant="preview"
|
||||
hasAnyImageInOptions={optionsHaveImages}
|
||||
/>
|
||||
|
||||
<div>
|
||||
{option.label || option.value || [label('common.option_prefix'), String(index + 1)].filter(Boolean).join(' ')}
|
||||
{#if option.isCorrect}
|
||||
<span class="ui:ml-2 ui:text-xs ui:text-green-600">{label('common.correct_badge')}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
@@ -0,0 +1,93 @@
|
||||
<script lang="ts">
|
||||
import * as Chart from '../../../../base/chart';
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import { getAnswerForQuestion, getSubmissionLabel, normalizeLabel, withChartColors } from '../submission-utils';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels'> = $props();
|
||||
|
||||
const chartConfig = $derived({
|
||||
responses: {
|
||||
label: getSubmissionLabel(labels, 'submission.chart.responses', 'Responses'),
|
||||
color: 'var(--chart-1)'
|
||||
}
|
||||
} satisfies Chart.ChartConfig);
|
||||
|
||||
const series = $derived([
|
||||
{
|
||||
key: 'responses',
|
||||
value: 'responses',
|
||||
label: chartConfig.responses.label,
|
||||
color: 'var(--color-responses)'
|
||||
}
|
||||
]);
|
||||
|
||||
const chartData = $derived.by(() => {
|
||||
const byOptionId = new Map<string, { key: string; label: string; responses: number }>();
|
||||
for (const option of question.options || []) {
|
||||
const optionId = option.id == null ? '' : String(option.id);
|
||||
if (!optionId) continue;
|
||||
|
||||
byOptionId.set(optionId, {
|
||||
key: optionId,
|
||||
label: normalizeLabel(option.label || option.value, optionId),
|
||||
responses: 0
|
||||
});
|
||||
}
|
||||
|
||||
let noAnswerCount = 0;
|
||||
|
||||
for (const submission of submissions || []) {
|
||||
const answer = getAnswerForQuestion(submission, question);
|
||||
if (!answer || answer.type !== 'CHECKBOX' || answer.optionIds.length < 1) {
|
||||
noAnswerCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let hadKnownOption = false;
|
||||
for (const optionId of answer.optionIds) {
|
||||
const option = byOptionId.get(String(optionId));
|
||||
if (!option) continue;
|
||||
hadKnownOption = true;
|
||||
option.responses += 1;
|
||||
}
|
||||
|
||||
if (!hadKnownOption) {
|
||||
noAnswerCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const rows = [...byOptionId.values()].filter((item) => item.responses > 0);
|
||||
|
||||
if (noAnswerCount > 0) {
|
||||
rows.push({
|
||||
key: 'no-answer',
|
||||
label: getSubmissionLabel(labels, 'submission.common.no_answer', 'No answer'),
|
||||
responses: noAnswerCount
|
||||
});
|
||||
}
|
||||
|
||||
return withChartColors(rows);
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if chartData.length > 0}
|
||||
<Chart.Container config={chartConfig} class="ui:h-[280px] ui:w-full">
|
||||
<Chart.BarChart
|
||||
data={chartData}
|
||||
xScale={Chart.scaleBand().padding(0.25)}
|
||||
x="label"
|
||||
axis="x"
|
||||
tooltip={false}
|
||||
{series}
|
||||
/>
|
||||
</Chart.Container>
|
||||
{:else}
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{getSubmissionLabel(labels, 'submission.chart.no_data', 'No responses yet')}
|
||||
</p>
|
||||
{/if}
|
||||
@@ -0,0 +1,94 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Checkbox } from '../../../../base/checkbox';
|
||||
import { Label } from '../../../../base/label';
|
||||
import OptionImage from '../option-image.svelte';
|
||||
import { getOptionImageUrl, hasOptionImages } from '../option-image-utils';
|
||||
import { cn } from '../../../../tools';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer = null,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
function getOptionValue(option: { id?: number | string; value?: string; label?: string }, index: number): string {
|
||||
return String(option.id ?? option.value ?? option.label ?? index);
|
||||
}
|
||||
|
||||
const selectedOptionValues = $derived.by(() => {
|
||||
const optionIds = answer?.type === 'CHECKBOX' ? answer.optionIds : [];
|
||||
return new Set(optionIds.map((id) => String(id)));
|
||||
});
|
||||
|
||||
const optionsHaveImages = $derived(hasOptionImages(question.options));
|
||||
|
||||
function isOptionSelected(option: { id?: number | string; value?: string; label?: string }, index: number): boolean {
|
||||
return selectedOptionValues.has(getOptionValue(option, index));
|
||||
}
|
||||
|
||||
function toggleOption(nextValue: string) {
|
||||
const nextSelectedValues = new Set(selectedOptionValues);
|
||||
|
||||
if (nextSelectedValues.has(nextValue)) {
|
||||
nextSelectedValues.delete(nextValue);
|
||||
} else {
|
||||
nextSelectedValues.add(nextValue);
|
||||
}
|
||||
|
||||
const options = question.options ?? [];
|
||||
const optionIds = Array.from(nextSelectedValues)
|
||||
.map((val) => {
|
||||
const matched = options.find((opt, i) => getOptionValue(opt, i) === val);
|
||||
const id = matched?.id ?? val;
|
||||
const num = Number(id);
|
||||
return Number.isNaN(num) ? undefined : num;
|
||||
})
|
||||
.filter((id): id is number => id !== undefined);
|
||||
|
||||
onAnswerChange({ type: 'CHECKBOX', optionIds });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<div class={optionsHaveImages ? 'ui:grid ui:grid-cols-2 ui:gap-3' : 'ui:space-y-2'}>
|
||||
{#each question.options ?? [] as option, index}
|
||||
{@const optionValue = getOptionValue(option, index)}
|
||||
{@const optionId = `checkbox-${question.id ?? 'question'}-${index}`}
|
||||
{@const optionImageUrl = getOptionImageUrl(option)}
|
||||
|
||||
<div
|
||||
class={cn(
|
||||
'ui:rounded-md ui:p-2 ui:border',
|
||||
optionsHaveImages ? 'ui:space-y-2' : 'ui:flex ui:items-center ui:gap-2'
|
||||
)}
|
||||
>
|
||||
<OptionImage
|
||||
src={optionImageUrl}
|
||||
alt={label('question.edit.image_alt')}
|
||||
variant="take"
|
||||
hasAnyImageInOptions={optionsHaveImages}
|
||||
/>
|
||||
|
||||
<div class="ui:flex ui:items-center ui:gap-2">
|
||||
<Checkbox
|
||||
id={optionId}
|
||||
checked={isOptionSelected(option, index)}
|
||||
{disabled}
|
||||
onCheckedChange={() => toggleOption(optionValue)}
|
||||
/>
|
||||
<Label class="ui:cursor-pointer ui:font-normal ui:w-full" for={optionId}>
|
||||
{option.label ||
|
||||
option.value ||
|
||||
[label('common.option_prefix'), String(index + 1)].filter(Boolean).join(' ')}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,115 @@
|
||||
export const FILE_UPLOAD_MAX_SIZE_MB = 2;
|
||||
|
||||
export const FILE_UPLOAD_SUPPORTED_TYPES = [
|
||||
{ value: 'application/pdf', label: 'PDF (.pdf)', aliases: ['pdf', '.pdf'] },
|
||||
{
|
||||
value: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
label: 'DOCX (.docx)',
|
||||
aliases: ['docx', '.docx']
|
||||
},
|
||||
{ value: 'application/msword', label: 'DOC (.doc)', aliases: ['doc', '.doc'] },
|
||||
{ value: 'image/jpeg', label: 'JPEG (.jpg, .jpeg)', aliases: ['jpg', '.jpg', 'jpeg', '.jpeg', 'image/jpg'] },
|
||||
{ value: 'image/png', label: 'PNG (.png)', aliases: ['png', '.png'] },
|
||||
{ value: 'image/webp', label: 'WEBP (.webp)', aliases: ['webp', '.webp'] },
|
||||
{ value: 'image/gif', label: 'GIF (.gif)', aliases: ['gif', '.gif'] },
|
||||
{ value: 'video/mp4', label: 'MP4 (.mp4)', aliases: ['mp4', '.mp4'] },
|
||||
{ value: 'video/quicktime', label: 'MOV (.mov)', aliases: ['mov', '.mov'] },
|
||||
{ value: 'video/x-msvideo', label: 'AVI (.avi)', aliases: ['avi', '.avi'] },
|
||||
{ value: 'video/x-matroska', label: 'MKV (.mkv)', aliases: ['mkv', '.mkv'] }
|
||||
] as const;
|
||||
|
||||
type SupportedType = (typeof FILE_UPLOAD_SUPPORTED_TYPES)[number];
|
||||
const SUPPORTED_TYPE_BY_VALUE = new Map<string, SupportedType>(
|
||||
FILE_UPLOAD_SUPPORTED_TYPES.map((entry) => [entry.value, entry])
|
||||
);
|
||||
|
||||
function normalizeToken(value: string): string {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function toCanonicalAcceptedType(value: string): string | null {
|
||||
const normalizedValue = normalizeToken(value);
|
||||
if (!normalizedValue) return null;
|
||||
|
||||
if (SUPPORTED_TYPE_BY_VALUE.has(normalizedValue)) {
|
||||
return normalizedValue;
|
||||
}
|
||||
|
||||
for (const fileType of FILE_UPLOAD_SUPPORTED_TYPES) {
|
||||
if (fileType.aliases.some((alias) => normalizeToken(alias) === normalizedValue)) {
|
||||
return fileType.value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function normalizeAcceptedFileTypes(value: unknown): string[] {
|
||||
const rawValues = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [];
|
||||
const seen = new Set<string>();
|
||||
const normalized: string[] = [];
|
||||
|
||||
for (const rawValue of rawValues) {
|
||||
if (typeof rawValue !== 'string') continue;
|
||||
|
||||
const canonicalValue = toCanonicalAcceptedType(rawValue);
|
||||
if (!canonicalValue || seen.has(canonicalValue)) continue;
|
||||
|
||||
seen.add(canonicalValue);
|
||||
normalized.push(canonicalValue);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function formatAcceptedFileTypes(values: string[]): string {
|
||||
return values
|
||||
.map((value) => SUPPORTED_TYPE_BY_VALUE.get(value)?.label ?? value)
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
function getFileExtension(filename: string): string | null {
|
||||
const extensionSeparatorIndex = filename.lastIndexOf('.');
|
||||
if (extensionSeparatorIndex < 0) return null;
|
||||
return normalizeToken(filename.slice(extensionSeparatorIndex));
|
||||
}
|
||||
|
||||
export function isFileTypeAllowed(file: File, acceptedTypes: string[]): boolean {
|
||||
if (acceptedTypes.length === 0) return true;
|
||||
|
||||
const fileMimeType = normalizeToken(file.type);
|
||||
const fileExtension = getFileExtension(file.name);
|
||||
const fileExtensionWithoutDot = fileExtension ? fileExtension.slice(1) : null;
|
||||
|
||||
for (const acceptedType of acceptedTypes) {
|
||||
const supportedType = SUPPORTED_TYPE_BY_VALUE.get(acceptedType);
|
||||
if (!supportedType) continue;
|
||||
|
||||
if (fileMimeType === supportedType.value) return true;
|
||||
|
||||
if (fileMimeType === 'image/jpg' && supportedType.value === 'image/jpeg') return true;
|
||||
|
||||
if (
|
||||
fileExtension &&
|
||||
supportedType.aliases.some((alias) => {
|
||||
const normalizedAlias = normalizeToken(alias);
|
||||
return normalizedAlias === fileExtension || normalizedAlias === fileExtensionWithoutDot;
|
||||
})
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const BYTES_PER_MB = 1024 * 1024;
|
||||
|
||||
export function isFileSizeAllowed(file: File, maxSizeMb: number | undefined | null): boolean {
|
||||
const effectiveMaxMb = Math.min(
|
||||
typeof maxSizeMb === 'number' && maxSizeMb > 0 ? maxSizeMb : FILE_UPLOAD_MAX_SIZE_MB,
|
||||
FILE_UPLOAD_MAX_SIZE_MB
|
||||
);
|
||||
return file.size <= effectiveMaxMb * BYTES_PER_MB;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import { Button } from '../../../../base/button';
|
||||
import { Checkbox } from '../../../../base/checkbox';
|
||||
import { Input } from '../../../../base/input';
|
||||
import * as Popover from '../../../../base/popover';
|
||||
import ChevronDownIcon from '@lucide/svelte/icons/chevron-down';
|
||||
import {
|
||||
FILE_UPLOAD_SUPPORTED_TYPES,
|
||||
formatAcceptedFileTypes,
|
||||
normalizeAcceptedFileTypes
|
||||
} from '../file-upload-types';
|
||||
|
||||
let { question, disabled = false, labels, onQuestionChange = () => {} }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
const acceptedTypes = $derived(normalizeAcceptedFileTypes(question.settings?.acceptedTypes));
|
||||
const acceptedTypesDisplay = $derived(
|
||||
acceptedTypes.length > 0
|
||||
? formatAcceptedFileTypes(acceptedTypes)
|
||||
: label('file_upload.edit.accepted_types_placeholder')
|
||||
);
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
|
||||
function patchSettings(next: Record<string, unknown>) {
|
||||
patchQuestion({ settings: { ...(question.settings ?? {}), ...next } });
|
||||
}
|
||||
|
||||
function toggleAcceptedType(typeValue: string, checked: boolean) {
|
||||
const nextAcceptedTypes = checked
|
||||
? [...acceptedTypes, typeValue]
|
||||
: acceptedTypes.filter((acceptedType) => acceptedType !== typeValue);
|
||||
|
||||
patchSettings({ acceptedTypes: nextAcceptedTypes });
|
||||
}
|
||||
|
||||
const rawMaxSize = $derived(question.settings?.maxSizeMb as number | undefined);
|
||||
const maxSizeMb = $derived(
|
||||
typeof rawMaxSize === 'number' && !Number.isNaN(rawMaxSize) && rawMaxSize >= 0
|
||||
? String(Math.min(rawMaxSize, 2))
|
||||
: ''
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
const raw = question.settings?.maxSizeMb as number | undefined;
|
||||
if (typeof raw === 'number' && raw > 2) {
|
||||
patchSettings({ maxSizeMb: 2 });
|
||||
}
|
||||
});
|
||||
|
||||
function onMaxSizeChange(value: string) {
|
||||
const num = Number(value);
|
||||
if (value === '' || Number.isNaN(num)) {
|
||||
patchSettings({ maxSizeMb: undefined });
|
||||
return;
|
||||
}
|
||||
patchSettings({ maxSizeMb: Math.min(2, Math.max(0, num)) });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<div class="ui:grid ui:gap-3 ui:md:grid-cols-2">
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-sm ui:font-medium">{label('file_upload.preview.accepted_types_label')}</p>
|
||||
<Popover.Root>
|
||||
<Popover.Trigger {disabled} class="ui:w-full">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
class="ui:w-full ui:justify-between ui:text-left ui:font-normal"
|
||||
{disabled}
|
||||
>
|
||||
<span class="ui:truncate">{acceptedTypesDisplay}</span>
|
||||
<ChevronDownIcon class="ui:ml-2 ui:size-4 ui:shrink-0 ui:opacity-50" aria-hidden="true" />
|
||||
</Button>
|
||||
</Popover.Trigger>
|
||||
<Popover.Content align="start" class="ui:max-h-72 ui:w-88 ui:p-2">
|
||||
<div class="ui:flex ui:max-h-64 ui:flex-col ui:gap-0 ui:overflow-y-auto">
|
||||
{#each FILE_UPLOAD_SUPPORTED_TYPES as fileType (fileType.value)}
|
||||
<label
|
||||
class="ui:flex ui:cursor-pointer ui:select-none ui:items-center ui:gap-2 ui:rounded-sm ui:px-2 ui:py-2 ui:text-sm hover:ui:bg-accent hover:ui:text-accent-foreground {disabled
|
||||
? 'ui:pointer-events-none ui:opacity-50'
|
||||
: ''}"
|
||||
>
|
||||
<Checkbox
|
||||
checked={acceptedTypes.includes(fileType.value)}
|
||||
{disabled}
|
||||
onCheckedChange={(checked) => toggleAcceptedType(fileType.value, checked === true)}
|
||||
/>
|
||||
<span>{fileType.label}</span>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</Popover.Content>
|
||||
</Popover.Root>
|
||||
</div>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-sm ui:font-medium">{label('file_upload.preview.max_size_label')}</p>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="2"
|
||||
step="0.1"
|
||||
placeholder={label('file_upload.edit.max_size_placeholder')}
|
||||
value={maxSizeMb}
|
||||
{disabled}
|
||||
onchange={(event) => onMaxSizeChange(event.currentTarget.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,23 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { formatAcceptedFileTypes, normalizeAcceptedFileTypes } from '../file-upload-types';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
const acceptedTypes = $derived(normalizeAcceptedFileTypes(question.settings?.acceptedTypes));
|
||||
const acceptedTypesDisplay = $derived(
|
||||
acceptedTypes.length > 0 ? formatAcceptedFileTypes(acceptedTypes) : label('common.not_set')
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{label('file_upload.preview.accepted_types_label')}:
|
||||
{acceptedTypesDisplay}
|
||||
</p>
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{label('file_upload.preview.max_size_label')}:
|
||||
{String((question.settings?.maxSizeMb as number | undefined) ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import GenericSubmission from '../submission-generic.svelte';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
</script>
|
||||
|
||||
<GenericSubmission {question} {submissions} {labels} {maxSubmissionItems} />
|
||||
@@ -0,0 +1,143 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import PlusIcon from '@lucide/svelte/icons/plus';
|
||||
import { DocumentCard } from '../../../document-card';
|
||||
import { Button } from '../../../../base/button';
|
||||
import { Spinner } from '../../../../base/spinner';
|
||||
import { isFileSizeAllowed, isFileTypeAllowed, normalizeAcceptedFileTypes } from '../file-upload-types';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer = null,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {},
|
||||
onFileUpload
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
let fileInput = $state<HTMLInputElement | null>(null);
|
||||
let isUploading = $state(false);
|
||||
let uploadError = $state<string | null>(null);
|
||||
|
||||
const acceptedTypes = $derived(normalizeAcceptedFileTypes(question.settings?.acceptedTypes));
|
||||
const acceptAttribute = $derived(acceptedTypes.join(','));
|
||||
const maxSizeMb = $derived(question.settings?.maxSizeMb as number | undefined);
|
||||
|
||||
const uploadedFile = $derived.by(
|
||||
(): {
|
||||
fileName: string;
|
||||
fileUrl: string | null;
|
||||
mimeType?: string;
|
||||
size?: number;
|
||||
} | null => {
|
||||
if (answer?.type !== 'FILE_UPLOAD') return null;
|
||||
const name = answer.fileName?.trim() ?? '';
|
||||
if (!name) return null;
|
||||
const url =
|
||||
typeof (answer as { fileUrl?: string }).fileUrl === 'string' ? (answer as { fileUrl?: string }).fileUrl : null;
|
||||
return {
|
||||
fileName: name,
|
||||
fileUrl: url ?? null,
|
||||
mimeType: answer.mimeType,
|
||||
size: answer.size
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
const fileTypeLabel = $derived.by(() => {
|
||||
const mime = uploadedFile?.mimeType ?? '';
|
||||
if (mime.includes('pdf')) return 'PDF';
|
||||
if (mime.includes('wordprocessingml') || mime.includes('docx')) return 'DOCX';
|
||||
if (mime.includes('msword') || mime.includes('doc')) return 'DOC';
|
||||
if (mime.includes('image')) return 'IMAGE';
|
||||
if (mime.includes('video')) return 'VIDEO';
|
||||
return mime.split('/')[1]?.toUpperCase() ?? 'FILE';
|
||||
});
|
||||
|
||||
const subtitle = $derived(
|
||||
uploadedFile
|
||||
? [fileTypeLabel, uploadedFile.size != null ? formatFileSize(uploadedFile.size) : null]
|
||||
.filter(Boolean)
|
||||
.join(' · ') || '–'
|
||||
: ''
|
||||
);
|
||||
|
||||
function openFilePicker() {
|
||||
if (disabled || isUploading) return;
|
||||
uploadError = null;
|
||||
fileInput?.click();
|
||||
}
|
||||
|
||||
async function onFileSelected(event: Event) {
|
||||
const input = event.currentTarget as HTMLInputElement;
|
||||
const selectedFile = input.files?.[0];
|
||||
input.value = '';
|
||||
|
||||
if (!selectedFile) return;
|
||||
if (!isFileTypeAllowed(selectedFile, acceptedTypes)) return;
|
||||
if (!isFileSizeAllowed(selectedFile, maxSizeMb)) return;
|
||||
|
||||
if (!onFileUpload) return;
|
||||
|
||||
isUploading = true;
|
||||
uploadError = null;
|
||||
try {
|
||||
const result = await onFileUpload(selectedFile);
|
||||
onAnswerChange({
|
||||
type: 'FILE_UPLOAD',
|
||||
fileKey: result.fileKey,
|
||||
fileName: result.fileName,
|
||||
mimeType: selectedFile.type,
|
||||
size: selectedFile.size
|
||||
});
|
||||
} catch (err) {
|
||||
uploadError = err instanceof Error ? err.message : label('file_upload.take.upload_error', 'Upload failed');
|
||||
} finally {
|
||||
isUploading = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<input
|
||||
bind:this={fileInput}
|
||||
type="file"
|
||||
accept={acceptAttribute || undefined}
|
||||
hidden
|
||||
class="ui:hidden"
|
||||
disabled={disabled || isUploading}
|
||||
onchange={onFileSelected}
|
||||
/>
|
||||
<Button type="button" variant="outline" disabled={disabled || isUploading} onclick={openFilePicker}>
|
||||
{#if isUploading}
|
||||
<Spinner class="ui:size-4" />
|
||||
{label('file_upload.take.upload_progress', 'Uploading...')}
|
||||
{:else}
|
||||
<PlusIcon class="ui:size-4" />
|
||||
{label('file_upload.take.upload_button')}
|
||||
{/if}
|
||||
</Button>
|
||||
{#if uploadError}
|
||||
<p class="ui:text-destructive ui:text-xs">{uploadError}</p>
|
||||
{/if}
|
||||
{#if uploadedFile}
|
||||
<DocumentCard
|
||||
title={uploadedFile.fileName}
|
||||
{subtitle}
|
||||
fileUrl={uploadedFile.fileUrl}
|
||||
viewLabel={label('file_upload.take.view', 'View')}
|
||||
downloadLabel={label('file_upload.take.download', 'Download')}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,31 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import { Textarea } from '../../../../base/textarea';
|
||||
|
||||
let { question, disabled = false, labels, onQuestionChange = () => {} }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
|
||||
function patchSettings(next: Record<string, unknown>) {
|
||||
patchQuestion({ settings: { ...(question.settings ?? {}), ...next } });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<Textarea
|
||||
class="ui:w-full"
|
||||
rows={2}
|
||||
placeholder={label('fill_blank.edit.accepted_answers_placeholder')}
|
||||
value={String((question.settings?.acceptedAnswers as string | undefined) ?? '')}
|
||||
{disabled}
|
||||
onchange={(event) => patchSettings({ acceptedAnswers: event.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{label('fill_blank.preview.accepted_answers_label')}:
|
||||
{String((question.settings?.acceptedAnswers as string | undefined) ?? label('common.not_set'))}
|
||||
</p>
|
||||
</div>
|
||||
@@ -0,0 +1,109 @@
|
||||
<script lang="ts">
|
||||
import * as Chart from '../../../../base/chart';
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import { getAnswerForQuestion, getSubmissionLabel, normalizeLabel, withChartColors } from '../submission-utils';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems = 8
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
|
||||
const chartConfig = $derived({
|
||||
responses: {
|
||||
label: getSubmissionLabel(labels, 'submission.chart.responses', 'Responses'),
|
||||
color: 'var(--chart-1)'
|
||||
}
|
||||
} satisfies Chart.ChartConfig);
|
||||
|
||||
const series = $derived([
|
||||
{
|
||||
key: 'responses',
|
||||
value: 'responses',
|
||||
label: chartConfig.responses.label,
|
||||
color: 'var(--color-responses)'
|
||||
}
|
||||
]);
|
||||
|
||||
const chartData = $derived.by(() => {
|
||||
const byValue = new Map<string, { key: string; label: string; responses: number }>();
|
||||
let noAnswerCount = 0;
|
||||
|
||||
for (const submission of submissions || []) {
|
||||
const answer = getAnswerForQuestion(submission, question);
|
||||
if (!answer || answer.type !== 'FILL_BLANK') {
|
||||
noAnswerCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const values = answer.values.map((value) => String(value || '').trim()).filter(Boolean);
|
||||
if (values.length < 1) {
|
||||
noAnswerCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const value of values) {
|
||||
const key = value.toLowerCase();
|
||||
const current = byValue.get(key);
|
||||
|
||||
if (!current) {
|
||||
byValue.set(key, {
|
||||
key,
|
||||
label: value,
|
||||
responses: 1
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
current.responses += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = [...byValue.values()].sort((a, b) => b.responses - a.responses);
|
||||
|
||||
let rows = sorted;
|
||||
|
||||
if (rows.length > maxSubmissionItems) {
|
||||
const kept = rows.slice(0, maxSubmissionItems);
|
||||
const otherCount = rows.slice(maxSubmissionItems).reduce((sum, item) => sum + item.responses, 0);
|
||||
|
||||
rows = [
|
||||
...kept,
|
||||
{
|
||||
key: 'other',
|
||||
label: getSubmissionLabel(labels, 'submission.common.other', 'Other'),
|
||||
responses: otherCount
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
if (noAnswerCount > 0) {
|
||||
rows.push({
|
||||
key: 'no-answer',
|
||||
label: getSubmissionLabel(labels, 'submission.common.no_answer', 'No answer'),
|
||||
responses: noAnswerCount
|
||||
});
|
||||
}
|
||||
|
||||
return withChartColors(rows.map((row) => ({ ...row, label: normalizeLabel(row.label, row.key) })));
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if chartData.length > 0}
|
||||
<Chart.Container config={chartConfig} class="ui:h-[280px] ui:w-full">
|
||||
<Chart.BarChart
|
||||
data={chartData}
|
||||
xScale={Chart.scaleBand().padding(0.25)}
|
||||
x="label"
|
||||
axis="x"
|
||||
tooltip={false}
|
||||
{series}
|
||||
/>
|
||||
</Chart.Container>
|
||||
{:else}
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{getSubmissionLabel(labels, 'submission.chart.no_data', 'No responses yet')}
|
||||
</p>
|
||||
{/if}
|
||||
@@ -0,0 +1,40 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Input } from '../../../../base/input';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const value = $derived.by(() => {
|
||||
const values = answer?.type === 'FILL_BLANK' ? answer.values : [];
|
||||
return values
|
||||
.map((token) => String(token).trim())
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<Input
|
||||
class="ui:w-full ui:max-w-[300px]"
|
||||
{value}
|
||||
{disabled}
|
||||
placeholder={label('fill_blank.take.placeholder')}
|
||||
onchange={(event) =>
|
||||
onAnswerChange({
|
||||
type: 'FILL_BLANK',
|
||||
values: event.currentTarget.value
|
||||
.split(',')
|
||||
.map((token) => token.trim())
|
||||
.filter(Boolean)
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
let { labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('hotspot.edit.helper')}</p>
|
||||
</div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">{label('hotspot.preview.helper')}</p>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import GenericSubmission from '../submission-generic.svelte';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
</script>
|
||||
|
||||
<GenericSubmission {question} {submissions} {labels} {maxSubmissionItems} />
|
||||
@@ -0,0 +1,50 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Textarea } from '../../../../base/textarea';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer = null,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const value = $derived.by(() => {
|
||||
if (answer?.type === 'HOTSPOT') return JSON.stringify(answer.coordinates, null, 2);
|
||||
return '';
|
||||
});
|
||||
|
||||
function parseCoordinates(raw: string): Array<{ x: number; y: number }> {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter(
|
||||
(c): c is { x: number; y: number } =>
|
||||
c &&
|
||||
typeof c === 'object' &&
|
||||
typeof (c as { x?: unknown }).x === 'number' &&
|
||||
typeof (c as { y?: unknown }).y === 'number'
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<Textarea
|
||||
class="ui:w-full"
|
||||
rows={4}
|
||||
{value}
|
||||
{disabled}
|
||||
placeholder={label('hotspot.take.placeholder')}
|
||||
onchange={(event) => {
|
||||
const coordinates = parseCoordinates(event.currentTarget.value);
|
||||
onAnswerChange({ type: 'HOTSPOT', coordinates });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,33 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import { Textarea } from '../../../../base/textarea';
|
||||
|
||||
let { question, disabled = false, labels, onQuestionChange = () => {} }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
|
||||
function patchSettings(next: Record<string, unknown>) {
|
||||
patchQuestion({ settings: { ...(question.settings ?? {}), ...next } });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<Textarea
|
||||
class="ui:w-full"
|
||||
rows={2}
|
||||
placeholder={label('link.edit.instructions_placeholder')}
|
||||
value={String((question.settings?.instructions as string | undefined) ?? '')}
|
||||
{disabled}
|
||||
onchange={(event) => patchSettings({ instructions: event.currentTarget.value })}
|
||||
/>
|
||||
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('link.edit.helper')}</p>
|
||||
</div>
|
||||
@@ -0,0 +1,55 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import ExternalLinkIcon from '@lucide/svelte/icons/external-link';
|
||||
|
||||
let { question, answer = null, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
function isValidLink(value: string): boolean {
|
||||
try {
|
||||
const parsedUrl = new URL(value);
|
||||
return parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const links = $derived.by(() => {
|
||||
if (answer?.type === 'LINK') return answer.urls.map((u) => String(u ?? '').trim()).filter(Boolean);
|
||||
return [];
|
||||
});
|
||||
|
||||
function formatLinkLabel(index: number): string {
|
||||
const template = label('link.preview.item_label');
|
||||
if (!template) return String(index + 1);
|
||||
return template.replace('{index}', String(index + 1));
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
{#if links.length === 0}
|
||||
<p class="ui:text-muted-foreground ui:text-sm">{label('link.preview.empty')}</p>
|
||||
{:else}
|
||||
<div class="ui:space-y-2">
|
||||
{#each links as link, index}
|
||||
<div class="ui:bg-background ui:rounded-md ui:border ui:p-2">
|
||||
{#if isValidLink(link)}
|
||||
<a
|
||||
href={link}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
class="ui:text-primary ui:inline-flex ui:items-center ui:gap-2 ui:text-sm ui:underline"
|
||||
>
|
||||
<span>{formatLinkLabel(index)}</span>
|
||||
<ExternalLinkIcon class="ui:size-3.5" />
|
||||
</a>
|
||||
<p class="ui:text-muted-foreground ui:mt-1 ui:text-xs">{link}</p>
|
||||
{:else}
|
||||
<p class="ui:text-sm">{link}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import GenericSubmission from '../submission-generic.svelte';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
</script>
|
||||
|
||||
<GenericSubmission {question} {submissions} {labels} {maxSubmissionItems} />
|
||||
@@ -0,0 +1,111 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import PlusIcon from '@lucide/svelte/icons/plus';
|
||||
import Trash2Icon from '@lucide/svelte/icons/trash-2';
|
||||
import { Button } from '../../../../base/button';
|
||||
import { Input } from '../../../../base/input';
|
||||
import { IconButton } from '../../../icon-button';
|
||||
|
||||
let { answer, disabled = false, labels, onAnswerChange = () => {} }: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
let links = $derived.by<string[]>(() => {
|
||||
const nextLinks = toAnswerLinks(answer);
|
||||
return nextLinks.length > 0 ? nextLinks : [''];
|
||||
});
|
||||
|
||||
function isValidLink(value: string): boolean {
|
||||
try {
|
||||
const parsedUrl = new URL(value);
|
||||
return parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function toAnswerLinks(value: ExerciseQuestionRendererProps['answer']): string[] {
|
||||
if (value?.type === 'LINK') return value.urls.map((u) => String(u ?? '').trim()).filter(Boolean);
|
||||
return [];
|
||||
}
|
||||
|
||||
function syncAnswer(nextLinks: string[]) {
|
||||
const normalizedLinks = nextLinks.map((entry) => entry.trim()).filter(Boolean);
|
||||
onAnswerChange({ type: 'LINK', urls: normalizedLinks });
|
||||
}
|
||||
|
||||
function addLinkField() {
|
||||
links = [...links, ''];
|
||||
}
|
||||
|
||||
function removeLinkField(index: number) {
|
||||
if (links.length === 1) return;
|
||||
const nextLinks = links.filter((_, linkIndex) => linkIndex !== index);
|
||||
links = nextLinks;
|
||||
syncAnswer(nextLinks);
|
||||
}
|
||||
|
||||
function updateLink(index: number, value: string) {
|
||||
const nextLinks = links.map((linkValue, linkIndex) => (linkIndex === index ? value : linkValue));
|
||||
links = nextLinks;
|
||||
syncAnswer(nextLinks);
|
||||
}
|
||||
|
||||
function formatInputPlaceholder(index: number): string {
|
||||
const template = label('link.take.placeholder');
|
||||
if (!template) return '';
|
||||
return template.replace('{index}', String(index + 1));
|
||||
}
|
||||
|
||||
const validationState = $derived.by(() =>
|
||||
links.map((linkValue) => {
|
||||
const trimmedValue = linkValue.trim();
|
||||
const isEmpty = trimmedValue.length === 0;
|
||||
|
||||
return {
|
||||
isEmpty,
|
||||
isValid: isEmpty ? true : isValidLink(trimmedValue)
|
||||
};
|
||||
})
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('link.take.helper')}</p>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
{#each links as link, index}
|
||||
<div class="ui:space-y-1">
|
||||
<div class="ui:flex ui:items-center ui:gap-2">
|
||||
<Input
|
||||
class="ui:flex-1 ui:max-w-[300px]"
|
||||
type="url"
|
||||
value={link}
|
||||
{disabled}
|
||||
placeholder={formatInputPlaceholder(index)}
|
||||
onchange={(event) => updateLink(index, event.currentTarget.value)}
|
||||
/>
|
||||
<IconButton
|
||||
type="button"
|
||||
tooltip={label('link.take.remove_tooltip')}
|
||||
disabled={disabled || links.length === 1}
|
||||
onclick={() => removeLinkField(index)}
|
||||
>
|
||||
<Trash2Icon class="ui:size-4" />
|
||||
<span class="ui:sr-only">{label('link.take.remove_sr')}</span>
|
||||
</IconButton>
|
||||
</div>
|
||||
|
||||
{#if !validationState[index]?.isEmpty && !validationState[index]?.isValid}
|
||||
<p class="ui:text-destructive ui:text-xs">{label('link.take.invalid_url_error')}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<Button variant="outline" size="sm" type="button" {disabled} onclick={addLinkField}>
|
||||
<PlusIcon class="ui:size-4" />
|
||||
{label('link.take.add_button')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
let { labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('matching.edit.helper')}</p>
|
||||
</div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">{label('matching.preview.helper')}</p>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import GenericSubmission from '../submission-generic.svelte';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
</script>
|
||||
|
||||
<GenericSubmission {question} {submissions} {labels} {maxSubmissionItems} />
|
||||
@@ -0,0 +1,50 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Textarea } from '../../../../base/textarea';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer = null,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const value = $derived.by(() => {
|
||||
if (answer?.type === 'MATCHING') return JSON.stringify(answer.pairs, null, 2);
|
||||
return '';
|
||||
});
|
||||
|
||||
function parsePairs(raw: string): Array<{ left: string; right: string }> {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter(
|
||||
(p): p is { left: string; right: string } =>
|
||||
p &&
|
||||
typeof p === 'object' &&
|
||||
typeof (p as { left?: unknown }).left === 'string' &&
|
||||
typeof (p as { right?: unknown }).right === 'string'
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<Textarea
|
||||
class="ui:w-full"
|
||||
rows={4}
|
||||
{value}
|
||||
{disabled}
|
||||
placeholder={label('matching.take.placeholder')}
|
||||
onchange={(event) => {
|
||||
const pairs = parsePairs(event.currentTarget.value);
|
||||
onAnswerChange({ type: 'MATCHING', pairs });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,60 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import CircleQuestionMarkIcon from '@lucide/svelte/icons/circle-question-mark';
|
||||
import { Input } from '../../../../base/input';
|
||||
import { IconButton } from '../../../icon-button';
|
||||
|
||||
let { question, disabled = false, labels, onQuestionChange = () => {} }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
|
||||
function patchSettings(next: Record<string, unknown>) {
|
||||
patchQuestion({ settings: { ...(question.settings ?? {}), ...next } });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<div class="ui:grid ui:gap-3 ui:md:grid-cols-2">
|
||||
<div class="ui:space-y-1">
|
||||
<div class="ui:flex ui:items-center ui:gap-1">
|
||||
<p class="ui:text-sm ui:font-medium">{label('numeric.edit.correct_value_label')}</p>
|
||||
<IconButton type="button" class="ui:h-6 ui:w-6" {disabled} tooltip={label('numeric.edit.correct_value_info')}>
|
||||
<CircleQuestionMarkIcon class="ui:size-3.5" />
|
||||
<span class="ui:sr-only">{label('numeric.edit.correct_value_info')}</span>
|
||||
</IconButton>
|
||||
</div>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder={label('numeric.edit.correct_value_placeholder')}
|
||||
value={String((question.settings?.correctValue as number | undefined) ?? '')}
|
||||
{disabled}
|
||||
onchange={(event) => patchSettings({ correctValue: Number(event.currentTarget.value) })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<div class="ui:flex ui:items-center ui:gap-1">
|
||||
<p class="ui:text-sm ui:font-medium">{label('numeric.edit.tolerance_label')}</p>
|
||||
<IconButton type="button" class="ui:h-6 ui:w-6" {disabled} tooltip={label('numeric.edit.tolerance_info')}>
|
||||
<CircleQuestionMarkIcon class="ui:size-3.5" />
|
||||
<span class="ui:sr-only">{label('numeric.edit.tolerance_info')}</span>
|
||||
</IconButton>
|
||||
</div>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder={label('numeric.edit.tolerance_placeholder')}
|
||||
value={String((question.settings?.tolerance as number | undefined) ?? '')}
|
||||
{disabled}
|
||||
onchange={(event) => patchSettings({ tolerance: Number(event.currentTarget.value) })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const correctValue = $derived(question.settings?.correctValue as number | undefined);
|
||||
const tolerance = $derived(question.settings?.tolerance as number | undefined);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{label('numeric.preview.correct_value_label')}: {correctValue ?? label('common.not_set')}
|
||||
</p>
|
||||
<p class="ui:text-muted-foreground ui:text-sm">{label('numeric.preview.tolerance_label')}: {tolerance ?? 0}</p>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import GenericSubmission from '../submission-generic.svelte';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
</script>
|
||||
|
||||
<GenericSubmission {question} {submissions} {labels} {maxSubmissionItems} />
|
||||
@@ -0,0 +1,37 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Input } from '../../../../base/input';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer = null,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const numericValue = $derived.by(() => {
|
||||
const val = answer?.type === 'NUMERIC' ? answer.value : undefined;
|
||||
if (typeof val === 'number' && Number.isFinite(val)) return String(val);
|
||||
return '';
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<Input
|
||||
class="ui:w-full ui:max-w-[300px]"
|
||||
type="number"
|
||||
value={numericValue}
|
||||
{disabled}
|
||||
placeholder={label('numeric.take.placeholder')}
|
||||
onchange={(event) => {
|
||||
const rawValue = event.currentTarget.value.trim();
|
||||
if (rawValue === '') return;
|
||||
const num = Number(rawValue);
|
||||
onAnswerChange({ type: 'NUMERIC', value: Number.isNaN(num) ? 0 : num });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { ExerciseQuestionOption } from '@cio/question-types';
|
||||
|
||||
export function getOptionImageUrl(option: ExerciseQuestionOption): string | null {
|
||||
const settings = option.settings;
|
||||
if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const imageUrl = settings.imageUrl;
|
||||
if (typeof imageUrl !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmedImageUrl = imageUrl.trim();
|
||||
return trimmedImageUrl.length > 0 ? trimmedImageUrl : null;
|
||||
}
|
||||
|
||||
export function hasOptionImages(options: ExerciseQuestionOption[] | undefined | null): boolean {
|
||||
return (options ?? []).some((opt) => getOptionImageUrl(opt) !== null);
|
||||
}
|
||||
|
||||
export function mergeOptionSettings(
|
||||
option: ExerciseQuestionOption,
|
||||
nextSettings: Record<string, unknown>
|
||||
): ExerciseQuestionOption {
|
||||
const currentSettings =
|
||||
option.settings && typeof option.settings === 'object' && !Array.isArray(option.settings) ? option.settings : {};
|
||||
|
||||
return {
|
||||
...option,
|
||||
settings: {
|
||||
...currentSettings,
|
||||
...nextSettings
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function removeOptionSetting(option: ExerciseQuestionOption, key: string): ExerciseQuestionOption {
|
||||
const currentSettings =
|
||||
option.settings && typeof option.settings === 'object' && !Array.isArray(option.settings) ? option.settings : {};
|
||||
const nextSettings = { ...currentSettings };
|
||||
delete nextSettings[key];
|
||||
|
||||
return {
|
||||
...option,
|
||||
settings: nextSettings
|
||||
};
|
||||
}
|
||||
|
||||
export function fileToDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = () => {
|
||||
if (!reader.result) {
|
||||
reject(new Error('Failed to read image file'));
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(String(reader.result));
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
reject(reader.error ?? new Error('Failed to read image file'));
|
||||
};
|
||||
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<script lang="ts">
|
||||
import XIcon from '@lucide/svelte/icons/x';
|
||||
import { IconButton } from '../../icon-button';
|
||||
|
||||
let {
|
||||
src,
|
||||
alt,
|
||||
variant = 'preview',
|
||||
onRemove,
|
||||
disabled = false,
|
||||
removeTooltip = '',
|
||||
removeSr = 'Remove image',
|
||||
hasAnyImageInOptions = false
|
||||
}: {
|
||||
src: string | null;
|
||||
alt: string;
|
||||
variant?: 'preview' | 'take' | 'edit';
|
||||
onRemove?: () => void;
|
||||
disabled?: boolean;
|
||||
removeTooltip?: string;
|
||||
removeSr?: string;
|
||||
hasAnyImageInOptions?: boolean;
|
||||
} = $props();
|
||||
|
||||
const sizeClass = $derived(variant === 'edit' ? 'ui:h-24 ui:w-24' : 'ui:h-28 ui:w-28');
|
||||
const containerClass = $derived(`${sizeClass} ui:overflow-hidden ui:rounded-md ui:border ui:border-border`);
|
||||
</script>
|
||||
|
||||
{#if variant === 'edit'}
|
||||
{#if src}
|
||||
<div class="ui:group ui:relative {sizeClass} ui:rounded-md ui:border">
|
||||
<div class="ui:absolute ui:inset-0 ui:overflow-hidden ui:rounded-md">
|
||||
<img {src} {alt} class="ui:h-full ui:w-full ui:object-cover" />
|
||||
</div>
|
||||
{#if onRemove}
|
||||
<IconButton
|
||||
{disabled}
|
||||
tooltipClass="ui:absolute ui:right-[-12px] ui:top-[-12px] ui:z-10"
|
||||
class="ui:opacity-0 ui:transition-opacity ui:group-hover:opacity-100"
|
||||
tooltip={removeTooltip}
|
||||
onclick={onRemove}
|
||||
size="icon-sm"
|
||||
>
|
||||
<XIcon />
|
||||
<span class="ui:sr-only">{removeSr}</span>
|
||||
</IconButton>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{:else if hasAnyImageInOptions}
|
||||
<div class="{containerClass} {src ? '' : 'ui:bg-muted'}">
|
||||
{#if src}
|
||||
<img {src} {alt} class="ui:h-full ui:w-full ui:object-cover" />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { ExerciseQuestionModel, ExerciseQuestionOption } from '@cio/question-types';
|
||||
import type { AnswerData } from '@cio/question-types';
|
||||
|
||||
export interface OrderingRenderItem {
|
||||
id: string;
|
||||
label: string;
|
||||
answerValue: string;
|
||||
}
|
||||
|
||||
function normalizeText(value: unknown): string {
|
||||
return String(value ?? '').trim();
|
||||
}
|
||||
|
||||
function normalizeToken(value: unknown): string {
|
||||
return normalizeText(value).toLowerCase();
|
||||
}
|
||||
|
||||
function buildFallbackLabel(index: number): string {
|
||||
return String(index + 1);
|
||||
}
|
||||
|
||||
function buildFallbackId(index: number): string {
|
||||
return `ordering-${index + 1}`;
|
||||
}
|
||||
|
||||
export function getOrderingItemsFromQuestion(question: ExerciseQuestionModel): OrderingRenderItem[] {
|
||||
const options = Array.isArray(question.options) ? question.options : [];
|
||||
if (options.length > 0) {
|
||||
return options.map((option, index) => {
|
||||
const label = normalizeText(option.label ?? option.value) || buildFallbackLabel(index);
|
||||
const id =
|
||||
normalizeText(option.id ?? option.value ?? option.label ?? buildFallbackId(index)) || buildFallbackId(index);
|
||||
const answerValue = normalizeText(option.id ?? option.value ?? option.label ?? id) || id;
|
||||
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
answerValue
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const rawItems = Array.isArray(question.settings?.items) ? question.settings.items : [];
|
||||
return rawItems.map((rawItem, index) => {
|
||||
const label = normalizeText(rawItem) || buildFallbackLabel(index);
|
||||
const id = buildFallbackId(index);
|
||||
|
||||
return {
|
||||
id,
|
||||
label,
|
||||
answerValue: label
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function toOrderingQuestionOptions(items: OrderingRenderItem[]): ExerciseQuestionOption[] {
|
||||
return items.map((item, index) => ({
|
||||
id: item.id || buildFallbackId(index),
|
||||
label: item.label,
|
||||
value: item.label,
|
||||
isCorrect: false
|
||||
}));
|
||||
}
|
||||
|
||||
export function toOrderingSettings(items: OrderingRenderItem[]): string[] {
|
||||
return items.map((item) => item.label);
|
||||
}
|
||||
|
||||
function getOrderedValues(answer: AnswerData | string[] | null | undefined): string[] {
|
||||
if (answer && typeof answer === 'object' && 'type' in answer && answer.type === 'ORDERING') {
|
||||
return Array.isArray(answer.orderedValues) ? answer.orderedValues : [];
|
||||
}
|
||||
return Array.isArray(answer) ? answer : [];
|
||||
}
|
||||
|
||||
export function applyOrderingAnswer(
|
||||
items: OrderingRenderItem[],
|
||||
answer: AnswerData | string[] | null | undefined
|
||||
): OrderingRenderItem[] {
|
||||
const orderedValues = getOrderedValues(answer);
|
||||
if (orderedValues.length === 0) {
|
||||
return items;
|
||||
}
|
||||
|
||||
const answerTokens = orderedValues.map((entry) => normalizeToken(entry)).filter(Boolean);
|
||||
if (answerTokens.length === 0) {
|
||||
return items;
|
||||
}
|
||||
|
||||
const usedItemIds = new Set<string>();
|
||||
const orderedItems: OrderingRenderItem[] = [];
|
||||
|
||||
answerTokens.forEach((token) => {
|
||||
const matchingItem = items.find((item) => {
|
||||
if (usedItemIds.has(item.id)) return false;
|
||||
const candidates = [item.id, item.answerValue, item.label].map((candidate) => normalizeToken(candidate));
|
||||
return candidates.includes(token);
|
||||
});
|
||||
|
||||
if (!matchingItem) return;
|
||||
usedItemIds.add(matchingItem.id);
|
||||
orderedItems.push(matchingItem);
|
||||
});
|
||||
|
||||
const remainingItems = items.filter((item) => !usedItemIds.has(item.id));
|
||||
return [...orderedItems, ...remainingItems];
|
||||
}
|
||||
|
||||
export function areSameOrdering(left: OrderingRenderItem[], right: OrderingRenderItem[]): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
|
||||
return left.every((item, index) => {
|
||||
const other = right[index];
|
||||
return other ? item.answerValue === other.answerValue : false;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import { dndzone } from 'svelte-dnd-action';
|
||||
import { flip } from 'svelte/animate';
|
||||
import GripVerticalIcon from '@lucide/svelte/icons/grip-vertical';
|
||||
import PlusIcon from '@lucide/svelte/icons/plus';
|
||||
import Trash2Icon from '@lucide/svelte/icons/trash-2';
|
||||
import { Button } from '../../../../base/button';
|
||||
import { Input } from '../../../../base/input';
|
||||
import { IconButton } from '../../../icon-button';
|
||||
import {
|
||||
getOrderingItemsFromQuestion,
|
||||
toOrderingQuestionOptions,
|
||||
toOrderingSettings,
|
||||
type OrderingRenderItem
|
||||
} from '../ordering-utils';
|
||||
|
||||
const flipDurationMs = 150;
|
||||
|
||||
let { question, disabled = false, labels, onQuestionChange = () => {} }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
let items = $state<OrderingRenderItem[]>([]);
|
||||
let lastSyncedSignature = $state('');
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
|
||||
function createItemId() {
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}-ordering-item`;
|
||||
}
|
||||
|
||||
function normalizeItemIds(nextItems: OrderingRenderItem[]): OrderingRenderItem[] {
|
||||
return nextItems.map((item) => {
|
||||
const normalizedId = item.id || createItemId();
|
||||
return {
|
||||
...item,
|
||||
id: normalizedId,
|
||||
answerValue: item.answerValue || normalizedId
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function syncQuestionWithItems(nextItems: OrderingRenderItem[]) {
|
||||
const normalizedItems = normalizeItemIds(nextItems);
|
||||
items = normalizedItems;
|
||||
lastSyncedSignature = getItemsSignature(normalizedItems);
|
||||
|
||||
patchQuestion({
|
||||
options: toOrderingQuestionOptions(normalizedItems),
|
||||
settings: {
|
||||
...(question.settings ?? {}),
|
||||
items: toOrderingSettings(normalizedItems)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getItemsSignature(nextItems: OrderingRenderItem[]): string {
|
||||
return JSON.stringify(nextItems.map((item) => ({ id: item.id, label: item.label, answerValue: item.answerValue })));
|
||||
}
|
||||
|
||||
function hydrateFromQuestion() {
|
||||
const nextItems = getOrderingItemsFromQuestion(question);
|
||||
const signature = getItemsSignature(nextItems);
|
||||
if (signature === lastSyncedSignature) return;
|
||||
|
||||
items = nextItems;
|
||||
lastSyncedSignature = signature;
|
||||
}
|
||||
|
||||
function handleDndConsider(event: CustomEvent<{ items: OrderingRenderItem[] }>) {
|
||||
items = event.detail.items;
|
||||
}
|
||||
|
||||
function handleDndFinalize(event: CustomEvent<{ items: OrderingRenderItem[] }>) {
|
||||
syncQuestionWithItems(event.detail.items);
|
||||
}
|
||||
|
||||
function updateItemLabel(id: string, label: string) {
|
||||
const nextItems = items.map((item) =>
|
||||
item.id === id ? { ...item, label, answerValue: item.answerValue || item.id } : item
|
||||
);
|
||||
syncQuestionWithItems(nextItems);
|
||||
}
|
||||
|
||||
function addItem() {
|
||||
const nextId = createItemId();
|
||||
syncQuestionWithItems([
|
||||
...items,
|
||||
{
|
||||
id: nextId,
|
||||
label: '',
|
||||
answerValue: nextId
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
function removeItem(id: string) {
|
||||
syncQuestionWithItems(items.filter((item) => item.id !== id));
|
||||
}
|
||||
|
||||
function formatStepPlaceholder(index: number): string {
|
||||
const template = label('ordering.edit.step_placeholder');
|
||||
if (!template) return String(index + 1);
|
||||
return template.replace('{index}', String(index + 1));
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
hydrateFromQuestion();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<div class="ui:flex ui:items-center ui:justify-between">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('ordering.edit.helper')}</p>
|
||||
<Button variant="outline" size="sm" type="button" {disabled} onclick={addItem}>
|
||||
<PlusIcon class="ui:size-4" />
|
||||
{label('ordering.edit.add_step')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<section
|
||||
class="ui:space-y-2"
|
||||
use:dndzone={{
|
||||
items,
|
||||
flipDurationMs,
|
||||
dragDisabled: disabled,
|
||||
dropTargetStyle: {
|
||||
border: '2px #1d4ed8 solid',
|
||||
'border-style': 'dashed',
|
||||
'border-radius': '0.5rem'
|
||||
}
|
||||
}}
|
||||
onconsider={handleDndConsider}
|
||||
onfinalize={handleDndFinalize}
|
||||
>
|
||||
{#if items.length === 0}
|
||||
<div class="ui:text-muted-foreground ui:rounded-md ui:border ui:border-dashed ui:p-4 ui:text-sm">
|
||||
{label('ordering.edit.empty')}
|
||||
</div>
|
||||
{:else}
|
||||
{#each items as item, index (item.id)}
|
||||
<div
|
||||
animate:flip={{ duration: flipDurationMs }}
|
||||
class="ui:bg-background ui:flex ui:items-center ui:gap-2 ui:rounded-md ui:border ui:p-2"
|
||||
>
|
||||
<div class="ui:text-muted-foreground ui:flex ui:cursor-grab ui:items-center">
|
||||
<GripVerticalIcon class="ui:size-4" />
|
||||
</div>
|
||||
<span
|
||||
class="ui:bg-muted ui:text-muted-foreground ui:flex ui:h-6 ui:w-6 ui:items-center ui:justify-center ui:rounded-full ui:text-xs"
|
||||
>
|
||||
{index + 1}
|
||||
</span>
|
||||
<Input
|
||||
class="ui:flex-1"
|
||||
value={item.label}
|
||||
{disabled}
|
||||
placeholder={formatStepPlaceholder(index)}
|
||||
onchange={(event) => updateItemLabel(item.id, event.currentTarget.value)}
|
||||
/>
|
||||
<IconButton
|
||||
type="button"
|
||||
{disabled}
|
||||
tooltip={label('ordering.edit.remove_step_tooltip')}
|
||||
class="ui:text-muted-foreground"
|
||||
onclick={() => removeItem(item.id)}
|
||||
>
|
||||
<Trash2Icon class="ui:size-4" />
|
||||
</IconButton>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
@@ -0,0 +1,53 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { applyOrderingAnswer, areSameOrdering, getOrderingItemsFromQuestion } from '../ordering-utils';
|
||||
|
||||
let { question, answer = null, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const expectedOrder = $derived.by(() => getOrderingItemsFromQuestion(question));
|
||||
const submittedOrder = $derived.by(() => applyOrderingAnswer(expectedOrder, answer));
|
||||
const hasSubmittedAnswer = $derived(answer?.type === 'ORDERING' ? answer.orderedValues.length > 0 : false);
|
||||
const isSubmittedOrderCorrect = $derived(areSameOrdering(expectedOrder, submittedOrder));
|
||||
|
||||
function getRowClass(index: number): string {
|
||||
if (!hasSubmittedAnswer) return 'ui:border-muted';
|
||||
|
||||
const expected = expectedOrder[index];
|
||||
const submitted = submittedOrder[index];
|
||||
const isMatch = expected && submitted ? expected.answerValue === submitted.answerValue : false;
|
||||
|
||||
return isMatch ? 'ui:border-emerald-400 ui:bg-emerald-50/30' : 'ui:border-amber-400 ui:bg-amber-50/30';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
{#if hasSubmittedAnswer}
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('ordering.preview.submitted_label')}</p>
|
||||
{#each submittedOrder as item, index (item.id)}
|
||||
<div class={`ui:flex ui:items-center ui:gap-3 ui:rounded-md ui:border ui:p-2 ${getRowClass(index)}`}>
|
||||
<span class="ui:bg-muted ui:text-muted-foreground ui:rounded-full ui:px-2 ui:py-1 ui:text-xs"
|
||||
>{index + 1}</span
|
||||
>
|
||||
<span class="ui:text-sm">{item.label}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<p class={`ui:text-xs ${isSubmittedOrderCorrect ? 'ui:text-emerald-600' : 'ui:text-amber-600'}`}>
|
||||
{isSubmittedOrderCorrect ? label('ordering.preview.matches') : label('ordering.preview.differs')}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('ordering.preview.expected_label')}</p>
|
||||
{#each expectedOrder as item, index (item.id)}
|
||||
<div class="ui:bg-background ui:flex ui:items-center ui:gap-3 ui:rounded-md ui:border ui:p-2">
|
||||
<span class="ui:bg-muted ui:text-muted-foreground ui:rounded-full ui:px-2 ui:py-1 ui:text-xs">{index + 1}</span>
|
||||
<span class="ui:text-sm">{item.label}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import GenericSubmission from '../submission-generic.svelte';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
</script>
|
||||
|
||||
<GenericSubmission {question} {submissions} {labels} {maxSubmissionItems} />
|
||||
@@ -0,0 +1,95 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import GripVerticalIcon from '@lucide/svelte/icons/grip-vertical';
|
||||
import { dndzone } from 'svelte-dnd-action';
|
||||
import { flip } from 'svelte/animate';
|
||||
import { applyOrderingAnswer, getOrderingItemsFromQuestion, type OrderingRenderItem } from '../ordering-utils';
|
||||
|
||||
const flipDurationMs = 150;
|
||||
|
||||
let {
|
||||
question,
|
||||
answer,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
let items = $state<OrderingRenderItem[]>([]);
|
||||
let signature = $state('');
|
||||
|
||||
function toSignature(nextItems: OrderingRenderItem[]): string {
|
||||
return JSON.stringify(nextItems.map((item) => ({ id: item.id, label: item.label, answerValue: item.answerValue })));
|
||||
}
|
||||
|
||||
function hydrateFromQuestionAndAnswer() {
|
||||
const sourceItems = getOrderingItemsFromQuestion(question);
|
||||
const sortedItems = applyOrderingAnswer(sourceItems, answer);
|
||||
const nextSignature = toSignature(sortedItems);
|
||||
|
||||
if (nextSignature === signature) return;
|
||||
|
||||
items = sortedItems;
|
||||
signature = nextSignature;
|
||||
}
|
||||
|
||||
function syncAnswer(nextItems: OrderingRenderItem[]) {
|
||||
items = nextItems;
|
||||
signature = toSignature(nextItems);
|
||||
onAnswerChange({ type: 'ORDERING', orderedValues: nextItems.map((item) => item.answerValue) });
|
||||
}
|
||||
|
||||
function handleDndConsider(event: CustomEvent<{ items: OrderingRenderItem[] }>) {
|
||||
items = event.detail.items;
|
||||
}
|
||||
|
||||
function handleDndFinalize(event: CustomEvent<{ items: OrderingRenderItem[] }>) {
|
||||
syncAnswer(event.detail.items);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
hydrateFromQuestionAndAnswer();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('ordering.take.helper')}</p>
|
||||
|
||||
<section
|
||||
class="ui:space-y-2"
|
||||
use:dndzone={{
|
||||
items,
|
||||
flipDurationMs,
|
||||
dragDisabled: disabled,
|
||||
dropTargetStyle: {
|
||||
border: '2px #1d4ed8 solid',
|
||||
'border-style': 'dashed',
|
||||
'border-radius': '0.5rem'
|
||||
}
|
||||
}}
|
||||
onconsider={handleDndConsider}
|
||||
onfinalize={handleDndFinalize}
|
||||
>
|
||||
{#if items.length === 0}
|
||||
<div class="ui:text-muted-foreground ui:rounded-md ui:border ui:border-dashed ui:p-4 ui:text-sm">
|
||||
{label('ordering.take.empty')}
|
||||
</div>
|
||||
{:else}
|
||||
{#each items as item, index (item.id)}
|
||||
<div
|
||||
animate:flip={{ duration: flipDurationMs }}
|
||||
class="ui:bg-background ui:flex ui:items-center ui:gap-3 ui:rounded-md ui:border ui:p-3"
|
||||
>
|
||||
<GripVerticalIcon class="ui:text-muted-foreground ui:size-4" />
|
||||
<span class="ui:bg-muted ui:text-muted-foreground ui:rounded-full ui:px-2 ui:py-1 ui:text-xs"
|
||||
>{index + 1}</span
|
||||
>
|
||||
<p class="ui:text-sm">{item.label}</p>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
@@ -0,0 +1,225 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionOption,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import PlusIcon from '@lucide/svelte/icons/plus';
|
||||
import Trash2Icon from '@lucide/svelte/icons/trash-2';
|
||||
import CheckIcon from '@lucide/svelte/icons/check';
|
||||
import CircleIcon from '@lucide/svelte/icons/circle';
|
||||
import { Button } from '../../../../base/button';
|
||||
import { Input } from '../../../../base/input';
|
||||
import { IconButton } from '../../../icon-button';
|
||||
import OptionImage from '../option-image.svelte';
|
||||
import { fileToDataUrl, getOptionImageUrl, mergeOptionSettings, removeOptionSetting } from '../option-image-utils';
|
||||
|
||||
let {
|
||||
question,
|
||||
disabled = false,
|
||||
labels,
|
||||
onQuestionChange = () => {},
|
||||
onImageUpload
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
let optionImageInput = $state<HTMLInputElement | null>(null);
|
||||
let optionImageTargetIndex = $state<number | null>(null);
|
||||
let optionImageError = $state('');
|
||||
let isOptionImageUploading = $state(false);
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
|
||||
function updateOption(index: number, partial: Partial<ExerciseQuestionOption>) {
|
||||
const options = [...(question.options ?? [])];
|
||||
const option = options[index];
|
||||
if (!option) return;
|
||||
|
||||
options[index] = { ...option, ...partial };
|
||||
patchQuestion({ options });
|
||||
}
|
||||
|
||||
function setCorrectOption(index: number) {
|
||||
const options = [...(question.options ?? [])].map((option, optionIndex) => ({
|
||||
...option,
|
||||
isCorrect: optionIndex === index
|
||||
}));
|
||||
patchQuestion({ options });
|
||||
}
|
||||
|
||||
function addOption() {
|
||||
patchQuestion({
|
||||
options: [
|
||||
...(question.options ?? []),
|
||||
{
|
||||
id: `${new Date().getTime()}-option`,
|
||||
label: '',
|
||||
value: '',
|
||||
isCorrect: false,
|
||||
settings: {}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
function removeOption(index: number) {
|
||||
const options = [...(question.options ?? [])];
|
||||
options.splice(index, 1);
|
||||
patchQuestion({ options });
|
||||
}
|
||||
|
||||
function openOptionImagePicker(index: number) {
|
||||
if (disabled || isOptionImageUploading) return;
|
||||
|
||||
optionImageTargetIndex = index;
|
||||
optionImageInput?.click();
|
||||
}
|
||||
|
||||
async function uploadOptionImage(file: File): Promise<string> {
|
||||
if (onImageUpload) {
|
||||
return onImageUpload(file);
|
||||
}
|
||||
|
||||
return fileToDataUrl(file);
|
||||
}
|
||||
|
||||
async function handleOptionImageSelection(event: Event) {
|
||||
const targetIndex = optionImageTargetIndex;
|
||||
optionImageTargetIndex = null;
|
||||
|
||||
const input = event.currentTarget as HTMLInputElement;
|
||||
const selectedFile = input.files?.[0];
|
||||
input.value = '';
|
||||
|
||||
if (targetIndex === null || targetIndex < 0 || !selectedFile) return;
|
||||
|
||||
if (!selectedFile.type.startsWith('image/')) {
|
||||
optionImageError = label('question.edit.upload_error_only_images');
|
||||
return;
|
||||
}
|
||||
|
||||
optionImageError = '';
|
||||
isOptionImageUploading = true;
|
||||
|
||||
try {
|
||||
const imageUrl = await uploadOptionImage(selectedFile);
|
||||
if (!imageUrl) return;
|
||||
|
||||
const options = [...(question.options ?? [])];
|
||||
const option = options[targetIndex];
|
||||
if (!option) return;
|
||||
|
||||
options[targetIndex] = mergeOptionSettings(option, { imageUrl });
|
||||
patchQuestion({ options });
|
||||
} catch (error) {
|
||||
optionImageError = label('question.edit.upload_error_failed');
|
||||
console.error('Failed to upload option image:', error);
|
||||
} finally {
|
||||
isOptionImageUploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function removeOptionImage(index: number) {
|
||||
const options = [...(question.options ?? [])];
|
||||
const option = options[index];
|
||||
if (!option) return;
|
||||
|
||||
options[index] = removeOptionSetting(option, 'imageUrl');
|
||||
patchQuestion({ options });
|
||||
optionImageError = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<p class="ui:text-muted-foreground ui:text-xs">{label('radio.edit.helper')}</p>
|
||||
{#if optionImageError}
|
||||
<p class="ui:text-destructive ui:text-xs">{optionImageError}</p>
|
||||
{/if}
|
||||
|
||||
<input
|
||||
bind:this={optionImageInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
class="ui:hidden"
|
||||
disabled={disabled || isOptionImageUploading}
|
||||
onchange={handleOptionImageSelection}
|
||||
/>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
{#each question.options ?? [] as option, index}
|
||||
{@const optionImageUrl = getOptionImageUrl(option)}
|
||||
<div class="ui:flex ui:items-start ui:gap-2">
|
||||
<IconButton
|
||||
type="button"
|
||||
{disabled}
|
||||
tooltip={option.isCorrect === true
|
||||
? label('radio.edit.correct_selected_tooltip')
|
||||
: label('radio.edit.mark_correct_tooltip')}
|
||||
class={option.isCorrect === true
|
||||
? 'ui:text-primary ui:border-primary/30 ui:bg-primary/10'
|
||||
: 'ui:text-muted-foreground'}
|
||||
onclick={() => setCorrectOption(index)}
|
||||
>
|
||||
{#if option.isCorrect === true}
|
||||
<CheckIcon class="ui:size-4" />
|
||||
{:else}
|
||||
<CircleIcon class="ui:size-4" />
|
||||
{/if}
|
||||
<span class="ui:sr-only">{label('radio.edit.mark_correct_sr')}</span>
|
||||
</IconButton>
|
||||
|
||||
<div class="ui:flex-1 ui:space-y-2">
|
||||
<Input
|
||||
class="ui:w-full"
|
||||
placeholder={[label('common.option_prefix'), String(index + 1)].filter(Boolean).join(' ').trim()}
|
||||
value={option.label}
|
||||
{disabled}
|
||||
onchange={(event) => updateOption(index, { label: event.currentTarget.value })}
|
||||
/>
|
||||
|
||||
<div class="ui:flex ui:flex-wrap ui:items-start ui:gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
type="button"
|
||||
disabled={disabled || isOptionImageUploading}
|
||||
onclick={() => openOptionImagePicker(index)}
|
||||
>
|
||||
<PlusIcon class="ui:size-4" />
|
||||
{label('question.edit.add_image')}
|
||||
</Button>
|
||||
|
||||
{#if optionImageUrl}
|
||||
<OptionImage
|
||||
src={optionImageUrl}
|
||||
alt={label('question.edit.image_alt')}
|
||||
variant="edit"
|
||||
onRemove={() => removeOptionImage(index)}
|
||||
{disabled}
|
||||
removeTooltip={label('question.edit.remove_image_tooltip')}
|
||||
removeSr={label('question.edit.remove_image_sr')}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<IconButton
|
||||
type="button"
|
||||
{disabled}
|
||||
tooltip={label('common.remove')}
|
||||
class="ui:text-muted-foreground"
|
||||
onclick={() => removeOption(index)}
|
||||
>
|
||||
<Trash2Icon class="ui:size-4" />
|
||||
<span class="ui:sr-only">{label('common.remove')}</span>
|
||||
</IconButton>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<Button variant="outline" type="button" {disabled} onclick={addOption}>{label('common.add_option')}</Button>
|
||||
</div>
|
||||
@@ -0,0 +1,35 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import OptionImage from '../option-image.svelte';
|
||||
import { getOptionImageUrl, hasOptionImages } from '../option-image-utils';
|
||||
import { cn } from '../../../../tools';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const optionsHaveImages = $derived(hasOptionImages(question.options));
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<ul class={optionsHaveImages ? 'ui:grid ui:grid-cols-2 ui:gap-3' : 'ui:space-y-1'}>
|
||||
{#each question.options ?? [] as option, index}
|
||||
{@const optionImageUrl = getOptionImageUrl(option)}
|
||||
<li class={cn(optionsHaveImages && 'ui:space-y-2 ui:rounded-md ui:p-2', 'ui:text-sm')}>
|
||||
<OptionImage
|
||||
src={optionImageUrl}
|
||||
alt={label('question.edit.image_alt')}
|
||||
variant="preview"
|
||||
hasAnyImageInOptions={optionsHaveImages}
|
||||
/>
|
||||
|
||||
<div>
|
||||
{option.label || option.value || [label('common.option_prefix'), String(index + 1)].filter(Boolean).join(' ')}
|
||||
{#if option.isCorrect}
|
||||
<span class="ui:ml-2 ui:text-xs ui:text-green-600">{label('common.correct_badge')}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
@@ -0,0 +1,74 @@
|
||||
<script lang="ts">
|
||||
import * as Chart from '../../../../base/chart';
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import { getAnswerForQuestion, getSubmissionLabel, normalizeLabel, withChartColors } from '../submission-utils';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels'> = $props();
|
||||
|
||||
const chartConfig = $derived({
|
||||
responses: {
|
||||
label: getSubmissionLabel(labels, 'submission.chart.responses', 'Responses'),
|
||||
color: 'var(--chart-1)'
|
||||
}
|
||||
} satisfies Chart.ChartConfig);
|
||||
|
||||
const chartData = $derived.by(() => {
|
||||
const byOptionId = new Map<string, { key: string; label: string; responses: number }>();
|
||||
for (const option of question.options || []) {
|
||||
const optionId = option.id == null ? '' : String(option.id);
|
||||
if (!optionId) continue;
|
||||
|
||||
byOptionId.set(optionId, {
|
||||
key: optionId,
|
||||
label: normalizeLabel(option.label || option.value, optionId),
|
||||
responses: 0
|
||||
});
|
||||
}
|
||||
|
||||
let noAnswerCount = 0;
|
||||
|
||||
for (const submission of submissions || []) {
|
||||
const answer = getAnswerForQuestion(submission, question);
|
||||
if (!answer || answer.type !== 'RADIO') {
|
||||
noAnswerCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const option = byOptionId.get(String(answer.optionId));
|
||||
if (!option) {
|
||||
noAnswerCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
option.responses += 1;
|
||||
}
|
||||
|
||||
const rows = [...byOptionId.values()].filter((item) => item.responses > 0);
|
||||
|
||||
if (noAnswerCount > 0) {
|
||||
rows.push({
|
||||
key: 'no-answer',
|
||||
label: getSubmissionLabel(labels, 'submission.common.no_answer', 'No answer'),
|
||||
responses: noAnswerCount
|
||||
});
|
||||
}
|
||||
|
||||
return withChartColors(rows);
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if chartData.length > 0}
|
||||
<Chart.Container config={chartConfig} class="ui:h-[280px] ui:w-full ui:flex-col ui:items-center">
|
||||
<Chart.PieChart data={chartData} key="key" label="label" value="responses" c="color" />
|
||||
<Chart.ChartLegend items={chartData.map((d) => ({ label: d.label, color: d.color, value: d.responses }))} />
|
||||
</Chart.Container>
|
||||
{:else}
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{getSubmissionLabel(labels, 'submission.chart.no_data', 'No responses yet')}
|
||||
</p>
|
||||
{/if}
|
||||
@@ -0,0 +1,80 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import * as RadioGroup from '../../../../base/radio-group';
|
||||
import { Label } from '../../../../base/label';
|
||||
import OptionImage from '../option-image.svelte';
|
||||
import { getOptionImageUrl, hasOptionImages } from '../option-image-utils';
|
||||
import { cn } from '../../../../tools';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer = null,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
function getOptionValue(option: { id?: number | string; value?: string; label?: string }, index: number): string {
|
||||
return String(option.id ?? option.value ?? option.label ?? index);
|
||||
}
|
||||
|
||||
const selectedOptionValue = $derived.by(() => {
|
||||
const optionId = answer?.type === 'RADIO' ? answer.optionId : null;
|
||||
if (optionId === undefined || optionId === null) return '';
|
||||
return String(optionId);
|
||||
});
|
||||
|
||||
const optionsHaveImages = $derived(hasOptionImages(question.options));
|
||||
|
||||
function handleOptionChange(value: string) {
|
||||
const nextValue = String(value ?? '').trim();
|
||||
if (!nextValue) return;
|
||||
|
||||
const matchedOption = (question.options ?? []).find((option, index) => getOptionValue(option, index) === nextValue);
|
||||
|
||||
if (matchedOption?.id !== undefined && matchedOption.id !== null) {
|
||||
const optionId = Number(matchedOption.id);
|
||||
onAnswerChange({ type: 'RADIO', optionId: Number.isNaN(optionId) ? Number(nextValue) : optionId });
|
||||
return;
|
||||
}
|
||||
onAnswerChange({ type: 'RADIO', optionId: Number(nextValue) });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<RadioGroup.Root value={selectedOptionValue} {disabled} onValueChange={handleOptionChange}>
|
||||
<div class={optionsHaveImages ? 'ui:grid ui:grid-cols-2 ui:gap-3' : 'ui:space-y-2'}>
|
||||
{#each question.options ?? [] as option, index}
|
||||
{@const optionValue = getOptionValue(option, index)}
|
||||
{@const optionId = `radio-${question.id ?? 'question'}-${index}`}
|
||||
{@const optionImageUrl = getOptionImageUrl(option)}
|
||||
|
||||
<div
|
||||
class={cn(
|
||||
'ui:rounded-md ui:p-2 ui:border',
|
||||
optionsHaveImages ? 'ui:space-y-2' : 'ui:flex ui:items-center ui:gap-2'
|
||||
)}
|
||||
>
|
||||
<OptionImage
|
||||
src={optionImageUrl}
|
||||
alt={label('question.edit.image_alt')}
|
||||
variant="take"
|
||||
hasAnyImageInOptions={optionsHaveImages}
|
||||
/>
|
||||
|
||||
<div class="ui:flex ui:items-center ui:gap-2">
|
||||
<RadioGroup.Item id={optionId} value={optionValue} />
|
||||
<Label class="ui:cursor-pointer ui:font-normal ui:w-full" for={optionId}>
|
||||
{option.label ||
|
||||
option.value ||
|
||||
[label('common.option_prefix'), String(index + 1)].filter(Boolean).join(' ')}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</RadioGroup.Root>
|
||||
</div>
|
||||
@@ -0,0 +1,28 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import { Textarea } from '../../../../base/textarea';
|
||||
|
||||
let { question, disabled = false, labels, onQuestionChange = () => {} }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<Textarea
|
||||
class="ui:w-full"
|
||||
rows={2}
|
||||
placeholder={label('short_answer.edit.instructions_placeholder')}
|
||||
value={String((question.settings?.instructions as string | undefined) ?? '')}
|
||||
{disabled}
|
||||
onchange={(event) =>
|
||||
patchQuestion({ settings: { ...(question.settings ?? {}), instructions: event.currentTarget.value } })}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">{label('short_answer.preview.helper')}</p>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import GenericSubmission from '../submission-generic.svelte';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
</script>
|
||||
|
||||
<GenericSubmission {question} {submissions} {labels} {maxSubmissionItems} />
|
||||
@@ -0,0 +1,25 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Input } from '../../../../base/input';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<Input
|
||||
class="ui:w-full ui:max-w-[300px]"
|
||||
value={answer?.type === 'SHORT_ANSWER' ? answer.text : String(answer ?? '')}
|
||||
{disabled}
|
||||
placeholder={label('short_answer.take.placeholder')}
|
||||
onchange={(event) => onAnswerChange({ type: 'SHORT_ANSWER', text: event.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,92 @@
|
||||
<script lang="ts">
|
||||
import { extractAnswerDisplayValues, type AnswerData, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import { getAnswerForQuestion, getSubmissionLabel, normalizeLabel } from './submission-utils';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
|
||||
function summarizeAnswer(answer: AnswerData): string[] {
|
||||
switch (answer.type) {
|
||||
case 'TEXTAREA':
|
||||
case 'SHORT_ANSWER':
|
||||
return [answer.text];
|
||||
case 'NUMERIC':
|
||||
return [String(answer.value)];
|
||||
case 'LINK':
|
||||
return answer.urls;
|
||||
case 'FILE_UPLOAD':
|
||||
return [answer.fileName || answer.fileKey];
|
||||
case 'MATCHING':
|
||||
return [`${answer.pairs.length} pair(s)`];
|
||||
case 'ORDERING':
|
||||
return [answer.orderedValues.join(' -> ')];
|
||||
case 'HOTSPOT':
|
||||
return [`${answer.coordinates.length} point(s)`];
|
||||
default: {
|
||||
const display = extractAnswerDisplayValues(answer);
|
||||
if (typeof display.text === 'string' && display.text.trim().length > 0) {
|
||||
return [display.text];
|
||||
}
|
||||
|
||||
return display.selectedValues.map((value) => String(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const responseRows = $derived.by(() => {
|
||||
const bySummary = new Map<string, number>();
|
||||
|
||||
for (const submission of submissions || []) {
|
||||
const answer = getAnswerForQuestion(submission, question);
|
||||
if (!answer) continue;
|
||||
|
||||
const values = summarizeAnswer(answer)
|
||||
.map((item) => normalizeLabel(item, ''))
|
||||
.filter(Boolean);
|
||||
if (values.length < 1) continue;
|
||||
|
||||
for (const value of values) {
|
||||
bySummary.set(value, (bySummary.get(value) || 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const rows = [...bySummary.entries()]
|
||||
.map(([label, responses]) => ({ label, responses }))
|
||||
.sort((a, b) => b.responses - a.responses);
|
||||
|
||||
if (typeof maxSubmissionItems === 'number' && maxSubmissionItems > 0) {
|
||||
return rows.slice(0, maxSubmissionItems);
|
||||
}
|
||||
|
||||
return rows;
|
||||
});
|
||||
|
||||
const totalResponses = $derived(responseRows.reduce((sum, row) => sum + row.responses, 0));
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{totalResponses}
|
||||
{getSubmissionLabel(labels, 'submission.list.responses', 'Responses')}
|
||||
</p>
|
||||
|
||||
{#if responseRows.length > 0}
|
||||
<div class="ui:max-h-80 ui:space-y-2 ui:overflow-y-auto ui:pr-1">
|
||||
{#each responseRows as row (`${row.label}-${row.responses}`)}
|
||||
<div class="ui:flex ui:items-center ui:justify-between ui:gap-3 ui:rounded-md ui:border ui:px-3 ui:py-2">
|
||||
<p class="ui:text-sm">{row.label}</p>
|
||||
<span class="ui:text-muted-foreground ui:text-xs">{row.responses}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{getSubmissionLabel(labels, 'submission.list.no_responses', 'No responses yet')}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,72 @@
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type AnswerData,
|
||||
type ExerciseQuestionLabels,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseSubmissionModel
|
||||
} from '@cio/question-types';
|
||||
|
||||
export const CHART_COLORS = [
|
||||
'var(--chart-1)',
|
||||
'var(--chart-2)',
|
||||
'var(--chart-3)',
|
||||
'var(--chart-4)',
|
||||
'var(--chart-5)'
|
||||
] as const;
|
||||
|
||||
export type SubmissionChartDatum = {
|
||||
key: string;
|
||||
label: string;
|
||||
responses: number;
|
||||
color: string;
|
||||
};
|
||||
|
||||
export function getSubmissionLabel(
|
||||
labels: ExerciseQuestionLabels | undefined,
|
||||
key:
|
||||
| 'submission.common.no_answer'
|
||||
| 'submission.common.other'
|
||||
| 'submission.chart.responses'
|
||||
| 'submission.chart.no_data'
|
||||
| 'submission.list.responses'
|
||||
| 'submission.list.no_responses',
|
||||
fallback = ''
|
||||
): string {
|
||||
return getExerciseQuestionLabel(labels, key, fallback);
|
||||
}
|
||||
|
||||
function getQuestionKey(question: ExerciseQuestionModel): string | null {
|
||||
if (question.id !== undefined && question.id !== null) return String(question.id);
|
||||
if (question.key) return String(question.key);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function normalizeLabel(value: string | null | undefined, fallback: string): string {
|
||||
const label = String(value || '').trim();
|
||||
return label.length > 0 ? label : fallback;
|
||||
}
|
||||
|
||||
export function getAnswerForQuestion(
|
||||
submission: ExerciseSubmissionModel,
|
||||
question: ExerciseQuestionModel
|
||||
): AnswerData | undefined {
|
||||
const questionKey = getQuestionKey(question);
|
||||
if (!questionKey) return undefined;
|
||||
|
||||
const answer = submission.answers.find((item) => String(item.questionId) === questionKey);
|
||||
|
||||
if (!answer?.answerData || typeof answer.answerData !== 'object' || !('type' in answer.answerData)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return answer.answerData;
|
||||
}
|
||||
|
||||
export function withChartColors(
|
||||
items: Array<{ key: string; label: string; responses: number }>
|
||||
): SubmissionChartDatum[] {
|
||||
return items.map((item, index) => ({
|
||||
...item,
|
||||
color: CHART_COLORS[index % CHART_COLORS.length]
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Textarea } from '../../../../base/textarea';
|
||||
|
||||
let { labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<Textarea class="ui:w-full" rows={4} disabled={true} placeholder={label('textarea.edit.placeholder')} />
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Editor } from '../../../editor';
|
||||
|
||||
let { question, answer = null }: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const content = $derived(answer?.type === 'TEXTAREA' ? answer.text : '');
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<Editor {content} editable={false} showToolBar={false} editorClass="ui:h-40" />
|
||||
</div>
|
||||
@@ -0,0 +1,66 @@
|
||||
<script lang="ts">
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { sanitizeHtml } from '../../../../tools/sanitize';
|
||||
|
||||
import { getAnswerForQuestion, getSubmissionLabel } from '../submission-utils';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels,
|
||||
maxSubmissionItems
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels' | 'maxSubmissionItems'> = $props();
|
||||
|
||||
const responseRows = $derived.by(() => {
|
||||
const byHtml = new Map<string, number>();
|
||||
|
||||
for (const submission of submissions || []) {
|
||||
const answer = getAnswerForQuestion(submission, question);
|
||||
if (!answer || answer.type !== 'TEXTAREA') continue;
|
||||
|
||||
const rawHtml = String(answer.text || '').trim();
|
||||
if (rawHtml.length < 1) continue;
|
||||
|
||||
const safeHtml = sanitizeHtml(rawHtml).trim();
|
||||
if (safeHtml.length < 1) continue;
|
||||
|
||||
byHtml.set(safeHtml, (byHtml.get(safeHtml) || 0) + 1);
|
||||
}
|
||||
|
||||
const rows = [...byHtml.entries()]
|
||||
.map(([html, responses]) => ({ html, responses }))
|
||||
.sort((a, b) => b.responses - a.responses);
|
||||
|
||||
if (typeof maxSubmissionItems === 'number' && maxSubmissionItems > 0) {
|
||||
return rows.slice(0, maxSubmissionItems);
|
||||
}
|
||||
|
||||
return rows;
|
||||
});
|
||||
|
||||
const totalResponses = $derived(responseRows.reduce((sum, row) => sum + row.responses, 0));
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{totalResponses}
|
||||
{getSubmissionLabel(labels, 'submission.list.responses', 'Responses')}
|
||||
</p>
|
||||
|
||||
{#if responseRows.length > 0}
|
||||
<div class="ui:max-h-80 ui:space-y-2 ui:overflow-y-auto ui:pr-1">
|
||||
{#each responseRows as row, index (`${index}-${row.responses}`)}
|
||||
<div class="ui:flex ui:items-start ui:justify-between ui:gap-3 ui:rounded-md ui:border ui:px-3 ui:py-2">
|
||||
<div class="ui:min-w-0 ui:flex-1 ui:break-words ui:text-sm">
|
||||
{@html row.html}
|
||||
</div>
|
||||
<span class="ui:text-muted-foreground ui:mt-0.5 ui:shrink-0 ui:text-xs">{row.responses}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{getSubmissionLabel(labels, 'submission.list.no_responses', 'No responses yet')}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,42 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import type { Editor } from '@tiptap/core';
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import { Editor as EditorComponent } from '../../../editor';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const content = $derived(answer?.type === 'TEXTAREA' ? answer.text : String(answer ?? ''));
|
||||
|
||||
function handleEditorReady(editor: Editor) {
|
||||
if (!editor?.view?.dom || disabled) return;
|
||||
const blurHandler = () => {
|
||||
if (!editor.isDestroyed) onAnswerChange({ type: 'TEXTAREA', text: String(editor.getHTML() ?? '') });
|
||||
};
|
||||
editor.view.dom.addEventListener('blur', blurHandler);
|
||||
onDestroy(() => {
|
||||
if (editor?.view?.dom) editor.view.dom.removeEventListener('blur', blurHandler);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<EditorComponent
|
||||
{content}
|
||||
editable={!disabled}
|
||||
showToolBar={!disabled}
|
||||
placeholder={label('textarea.take.placeholder')}
|
||||
editorClass="ui:h-40"
|
||||
onContentChange={(nextContent) => onAnswerChange({ type: 'TEXTAREA', text: String(nextContent ?? '') })}
|
||||
onEditorReady={handleEditorReady}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,68 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getExerciseQuestionLabel,
|
||||
type ExerciseQuestionModel,
|
||||
type ExerciseQuestionRendererProps
|
||||
} from '@cio/question-types';
|
||||
import * as ToggleGroup from '../../../../base/toggle-group';
|
||||
|
||||
let { question, disabled = false, labels, onQuestionChange = () => {} }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
function patchQuestion(partial: Partial<ExerciseQuestionModel>) {
|
||||
onQuestionChange({ ...question, ...partial });
|
||||
}
|
||||
|
||||
function handleCorrectValueChange(value: string) {
|
||||
if (value !== 'true' && value !== 'false') return;
|
||||
|
||||
const correctValue = value === 'true';
|
||||
const opts = question.options ?? [];
|
||||
const options = opts.map((opt) => {
|
||||
const v = String(opt.value ?? opt.label ?? '').toLowerCase();
|
||||
const isTrue = v === 'true' || v === '1';
|
||||
const isFalse = v === 'false' || v === '0';
|
||||
const isCorrect = (isTrue && correctValue) || (isFalse && !correctValue);
|
||||
return isTrue || isFalse ? { ...opt, isCorrect } : opt;
|
||||
});
|
||||
|
||||
patchQuestion({
|
||||
settings: { ...(question.settings ?? {}), correctValue },
|
||||
options:
|
||||
options.length >= 2
|
||||
? options
|
||||
: [
|
||||
{ id: `${Date.now()}-true`, label: 'True', value: 'true', isCorrect: correctValue },
|
||||
{ id: `${Date.now()}-false`, label: 'False', value: 'false', isCorrect: !correctValue }
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
const selectedValue = $derived.by(() => {
|
||||
const correctOpt = (question.options ?? []).find((o) => o.isCorrect);
|
||||
if (correctOpt) {
|
||||
const v = String(correctOpt.value ?? correctOpt.label).toLowerCase();
|
||||
return v === 'false' || v === '0' ? 'false' : 'true';
|
||||
}
|
||||
const fromSettings = question.settings?.correctValue as boolean | undefined;
|
||||
return typeof fromSettings === 'boolean' ? String(fromSettings) : 'true';
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-3">
|
||||
<div class="ui:space-y-2">
|
||||
<p class="ui:text-sm ui:font-medium">{label('true_false.edit.correct_answer_label')}</p>
|
||||
<ToggleGroup.Root
|
||||
type="single"
|
||||
value={selectedValue}
|
||||
{disabled}
|
||||
variant="outline"
|
||||
onValueChange={handleCorrectValueChange}
|
||||
class="ui:w-fit"
|
||||
>
|
||||
<ToggleGroup.Item value="true">{label('true_false.true_label')}</ToggleGroup.Item>
|
||||
<ToggleGroup.Item value="false">{label('true_false.false_label')}</ToggleGroup.Item>
|
||||
</ToggleGroup.Root>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
let { question, labels }: ExerciseQuestionRendererProps = $props();
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const correctValue = $derived(
|
||||
(question.settings?.correctValue as boolean | undefined) === false
|
||||
? label('true_false.false_label')
|
||||
: label('true_false.true_label')
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-1">
|
||||
<p class="ui:text-muted-foreground ui:text-sm">{label('true_false.preview.correct_value_label')}: {correctValue}</p>
|
||||
</div>
|
||||
@@ -0,0 +1,93 @@
|
||||
<script lang="ts">
|
||||
import * as Chart from '../../../../base/chart';
|
||||
import type { ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
|
||||
import { getAnswerForQuestion, getSubmissionLabel, normalizeLabel, withChartColors } from '../submission-utils';
|
||||
|
||||
let {
|
||||
question,
|
||||
submissions = [],
|
||||
labels
|
||||
}: Pick<ExerciseQuestionRendererProps, 'question' | 'submissions' | 'labels'> = $props();
|
||||
|
||||
function resolveBooleanOptionLabel(value: boolean): string {
|
||||
const wanted = String(value);
|
||||
|
||||
const option = (question.options || []).find((item) => {
|
||||
const optionValue = String(item.value || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return optionValue === wanted;
|
||||
});
|
||||
|
||||
if (!option) return value ? 'True' : 'False';
|
||||
|
||||
return normalizeLabel(option.label || option.value, value ? 'True' : 'False');
|
||||
}
|
||||
|
||||
const chartConfig = $derived({
|
||||
responses: {
|
||||
label: getSubmissionLabel(labels, 'submission.chart.responses', 'Responses'),
|
||||
color: 'var(--chart-1)'
|
||||
}
|
||||
} satisfies Chart.ChartConfig);
|
||||
|
||||
const chartData = $derived.by(() => {
|
||||
let trueCount = 0;
|
||||
let falseCount = 0;
|
||||
let noAnswerCount = 0;
|
||||
|
||||
for (const submission of submissions || []) {
|
||||
const answer = getAnswerForQuestion(submission, question);
|
||||
if (!answer || answer.type !== 'TRUE_FALSE') {
|
||||
noAnswerCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (answer.value) {
|
||||
trueCount += 1;
|
||||
} else {
|
||||
falseCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const rows: Array<{ key: string; label: string; responses: number }> = [];
|
||||
|
||||
if (trueCount > 0) {
|
||||
rows.push({
|
||||
key: 'true',
|
||||
label: resolveBooleanOptionLabel(true),
|
||||
responses: trueCount
|
||||
});
|
||||
}
|
||||
|
||||
if (falseCount > 0) {
|
||||
rows.push({
|
||||
key: 'false',
|
||||
label: resolveBooleanOptionLabel(false),
|
||||
responses: falseCount
|
||||
});
|
||||
}
|
||||
|
||||
if (noAnswerCount > 0) {
|
||||
rows.push({
|
||||
key: 'no-answer',
|
||||
label: getSubmissionLabel(labels, 'submission.common.no_answer', 'No answer'),
|
||||
responses: noAnswerCount
|
||||
});
|
||||
}
|
||||
|
||||
return withChartColors(rows);
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if chartData.length > 0}
|
||||
<Chart.Container config={chartConfig} class="ui:h-[280px] ui:w-full ui:flex-col ui:items-center">
|
||||
<Chart.PieChart data={chartData} key="key" label="label" value="responses" c="color" />
|
||||
<Chart.ChartLegend items={chartData.map((d) => ({ label: d.label, color: d.color, value: d.responses }))} />
|
||||
</Chart.Container>
|
||||
{:else}
|
||||
<p class="ui:text-muted-foreground ui:text-sm">
|
||||
{getSubmissionLabel(labels, 'submission.chart.no_data', 'No responses yet')}
|
||||
</p>
|
||||
{/if}
|
||||
@@ -0,0 +1,33 @@
|
||||
<script lang="ts">
|
||||
import { getExerciseQuestionLabel, type ExerciseQuestionRendererProps } from '@cio/question-types';
|
||||
import * as ToggleGroup from '../../../../base/toggle-group';
|
||||
|
||||
let {
|
||||
question,
|
||||
answer = null,
|
||||
disabled = false,
|
||||
labels,
|
||||
onAnswerChange = () => {}
|
||||
}: ExerciseQuestionRendererProps = $props();
|
||||
|
||||
const label = (key: Parameters<typeof getExerciseQuestionLabel>[1], fallback = '') =>
|
||||
getExerciseQuestionLabel(labels, key, fallback);
|
||||
|
||||
const selected = $derived.by(() => {
|
||||
const val = answer?.type === 'TRUE_FALSE' ? answer.value : undefined;
|
||||
if (typeof val === 'boolean') return val ? 'true' : 'false';
|
||||
return '';
|
||||
});
|
||||
|
||||
function update(value: string) {
|
||||
if (value !== 'true' && value !== 'false') return;
|
||||
onAnswerChange({ type: 'TRUE_FALSE', value: value === 'true' });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="ui:space-y-2">
|
||||
<ToggleGroup.Root type="single" value={selected} {disabled} variant="outline" onValueChange={update}>
|
||||
<ToggleGroup.Item value="true">{label('true_false.true_label')}</ToggleGroup.Item>
|
||||
<ToggleGroup.Item value="false">{label('true_false.false_label')}</ToggleGroup.Item>
|
||||
</ToggleGroup.Root>
|
||||
</div>
|
||||
Reference in New Issue
Block a user