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,34 @@
|
||||
<script lang="ts">
|
||||
import Root from './alert.svelte';
|
||||
import Title from './alert-title.svelte';
|
||||
import Description from './alert-description.svelte';
|
||||
import type { AlertVariant } from './alert.svelte';
|
||||
import InfoIcon from '@lucide/svelte/icons/info';
|
||||
import AlertCircleIcon from '@lucide/svelte/icons/alert-circle';
|
||||
import AlertTriangleIcon from '@lucide/svelte/icons/alert-triangle';
|
||||
import { cn } from '../../tools';
|
||||
|
||||
const variantIcons = {
|
||||
default: InfoIcon,
|
||||
destructive: AlertCircleIcon,
|
||||
warning: AlertTriangleIcon,
|
||||
information: InfoIcon
|
||||
} as const;
|
||||
|
||||
type Props = {
|
||||
variant?: AlertVariant;
|
||||
title: string;
|
||||
description: string;
|
||||
class?: string;
|
||||
};
|
||||
|
||||
let { variant = 'default', title, description, class: className }: Props = $props();
|
||||
|
||||
const IconComponent = $derived(variantIcons[variant]);
|
||||
</script>
|
||||
|
||||
<Root {variant} class={cn(className)}>
|
||||
<IconComponent />
|
||||
<Title>{title}</Title>
|
||||
<Description>{description}</Description>
|
||||
</Root>
|
||||
@@ -0,0 +1,23 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from 'svelte/elements';
|
||||
import { cn, type WithElementRef } from '../../tools';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
</script>
|
||||
|
||||
<div
|
||||
bind:this={ref}
|
||||
data-slot="alert-description"
|
||||
class={cn(
|
||||
'ui:text-muted-foreground ui:col-start-2 ui:grid ui:justify-items-start ui:gap-1 ui:text-sm ui:[&_p]:leading-relaxed',
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</div>
|
||||
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from 'svelte/elements';
|
||||
import { cn, type WithElementRef } from '../../tools';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
</script>
|
||||
|
||||
<div
|
||||
bind:this={ref}
|
||||
data-slot="alert-title"
|
||||
class={cn('ui:col-start-2 ui:min-h-4 ui:font-medium ui:tracking-tight line-clamp-1', className)}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</div>
|
||||
@@ -0,0 +1,42 @@
|
||||
<script lang="ts" module>
|
||||
import { type VariantProps, tv } from 'tailwind-variants';
|
||||
|
||||
export const alertVariants = tv({
|
||||
base: 'ui:relative ui:grid ui:w-full ui:grid-cols-[0_1fr] ui:items-start ui:gap-y-0.5 ui:rounded-lg ui:border ui:px-4 ui:py-3 ui:text-sm ui:has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] ui:has-[>svg]:gap-x-3 ui:[&>svg]:size-4 ui:[&>svg]:translate-y-0.5 ui:[&>svg]:text-current',
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'ui:bg-card ui:text-card-foreground',
|
||||
destructive:
|
||||
'ui:text-destructive ui:bg-card *:data-[slot=alert-description]:text-destructive/90 ui:[&>svg]:text-current',
|
||||
warning:
|
||||
'ui:border-amber-200 ui:bg-amber-50 ui:text-amber-900 ui:dark:border-amber-900 ui:dark:bg-amber-950 ui:dark:text-amber-50 ui:[&>svg]:text-current',
|
||||
information:
|
||||
'ui:border-sky-200 ui:bg-sky-50 ui:text-sky-900 ui:dark:border-sky-900 ui:dark:bg-sky-950 ui:dark:text-sky-50 ui:[&>svg]:text-current'
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default'
|
||||
}
|
||||
});
|
||||
|
||||
export type AlertVariant = VariantProps<typeof alertVariants>['variant'];
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import type { HTMLAttributes } from 'svelte/elements';
|
||||
import { cn, type WithElementRef } from '../../tools';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
variant = 'default',
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
|
||||
variant?: AlertVariant;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<div bind:this={ref} data-slot="alert" role="alert" class={cn(alertVariants({ variant }), className)} {...restProps}>
|
||||
{@render children?.()}
|
||||
</div>
|
||||
@@ -0,0 +1,16 @@
|
||||
import Root from './alert.svelte';
|
||||
import Description from './alert-description.svelte';
|
||||
import Title from './alert-title.svelte';
|
||||
import Callout from './alert-callout.svelte';
|
||||
export { alertVariants, type AlertVariant } from './alert.svelte';
|
||||
|
||||
export {
|
||||
Root,
|
||||
Description,
|
||||
Title,
|
||||
Callout,
|
||||
//
|
||||
Root as Alert,
|
||||
Description as AlertDescription,
|
||||
Title as AlertTitle
|
||||
};
|
||||
@@ -9,6 +9,10 @@
|
||||
secondary: 'ui:bg-secondary ui:text-secondary-foreground ui:[a&]:hover:bg-secondary/90 ui:border-transparent',
|
||||
destructive:
|
||||
'ui:bg-destructive ui:[a&]:hover:bg-destructive/90 ui:focus-visible:ring-destructive/20 ui:dark:focus-visible:ring-destructive/40 ui:dark:bg-destructive/70 ui:border-transparent ui:text-white',
|
||||
warning:
|
||||
'ui:bg-amber-600 ui:text-white ui:[a&]:hover:bg-amber-600/90 ui:border-transparent ui:dark:bg-amber-500 ui:dark:text-amber-950',
|
||||
success:
|
||||
'ui:bg-emerald-600 ui:text-white ui:[a&]:hover:bg-emerald-600/90 ui:border-transparent ui:dark:bg-emerald-500 ui:dark:text-emerald-950',
|
||||
outline: 'ui:text-foreground ui:[a&]:hover:bg-accent ui:[a&]:hover:text-accent-foreground'
|
||||
}
|
||||
},
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
const mergedProps = $derived({
|
||||
...restProps,
|
||||
class: cn(
|
||||
"ui:bg-muted ui:shadow-xs ui:flex ui:items-center ui:gap-2 ui:rounded-md ui:border ui:px-4 ui:text-sm ui:font-medium ui:[&_svg:not([class*='size-'])]:size-4 ui:[&_svg]:pointer-events-none",
|
||||
"ui:bg-muted ui:shadow-xs ui:flex ui:items-center ui:gap-2 ui:rounded-md ui:border ui:px-4 ui:text-sm ui:font-medium ui:[&_svg:not([class*='ui:size-'])]:size-4 ui:[&_svg]:pointer-events-none",
|
||||
className
|
||||
)
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { tv, type VariantProps } from 'tailwind-variants';
|
||||
|
||||
export const buttonGroupVariants = tv({
|
||||
base: "ui:flex ui:w-fit ui:items-stretch ui:has-[>[data-slot=button-group]]:gap-2 ui:[&>*]:focus-visible:relative ui:[&>*]:focus-visible:z-10 ui:has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-e-md ui:[&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit ui:[&>input]:flex-1",
|
||||
base: "ui:flex ui:w-fit ui:items-stretch ui:has-[>[data-slot=button-group]]:gap-2 ui:[&>*]:focus-visible:relative ui:[&>*]:focus-visible:z-10 ui:has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-e-md ui:[&>[data-slot=select-trigger]:not([class*='ui:w-'])]:w-fit ui:[&>input]:flex-1",
|
||||
variants: {
|
||||
orientation: {
|
||||
horizontal:
|
||||
|
||||
@@ -4,16 +4,21 @@
|
||||
import { type VariantProps, tv } from 'tailwind-variants';
|
||||
|
||||
export const buttonVariants = tv({
|
||||
base: "ui:aria-invalid:ring-destructive/20 ui:dark:aria-invalid:ring-destructive/40 ui:aria-invalid:border-destructive ui:focus-visible:border-ring ui:focus-visible:ring-ring/50 ui:relative ui:inline-flex ui:shrink-0 ui:items-center ui:justify-center ui:gap-2 ui:overflow-hidden ui:rounded-md ui:text-sm ui:font-medium ui:whitespace-nowrap ui:outline-hidden ui:transition-all ui:select-none ui:focus-visible:ring-[3px] ui:disabled:pointer-events-none ui:disabled:opacity-50 ui:[&_svg]:pointer-events-none ui:[&_svg]:shrink-0 ui:[&_svg:not([class*='size-'])]:size-4 ui:cursor-pointer",
|
||||
base: "ui:aria-invalid:ring-destructive/20 ui:dark:aria-invalid:ring-destructive/40 ui:aria-invalid:border-destructive ui:focus-visible:border-ring ui:focus-visible:ring-ring/50 ui:relative ui:inline-flex ui:shrink-0 ui:items-center ui:justify-center ui:gap-2 ui:overflow-hidden ui:rounded-md ui:text-sm ui:font-medium ui:whitespace-nowrap ui:outline-hidden ui:transition-all ui:select-none ui:focus-visible:ring-[3px] ui:disabled:pointer-events-none ui:disabled:cursor-not-allowed ui:disabled:opacity-50 ui:[&_svg]:pointer-events-none ui:[&_svg]:shrink-0 ui:[&_svg:not([class*='ui:size-'])]:size-4 ui:cursor-pointer",
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'ui:bg-primary ui:text-primary-foreground ui:[a&]:hover:bg-primary/90 ui:shadow-2xs',
|
||||
'light-default': 'ui:bg-primary/20 ui:text-primary ui:[a&]:hover:bg-primary/30 ui:shadow-2xs',
|
||||
destructive:
|
||||
'ui:bg-destructive ui:[a&]:hover:bg-destructive/90 ui:focus-visible:ring-destructive/20 ui:dark:bg-destructive/60 ui:dark:focus-visible:ring-destructive/40 ui:text-white ui:shadow-2xs',
|
||||
outline:
|
||||
'ui:bg-background ui:[a&]:hover:bg-accent ui:[a&]:hover:text-accent-foreground ui:dark:border-input ui:dark:bg-input/30 ui:dark:hover:bg-input/50 ui:border ui:shadow-2xs',
|
||||
secondary: 'ui:bg-secondary ui:text-secondary-foreground ui:[a&]:hover:bg-secondary/80 ui:shadow-2xs',
|
||||
ghost: 'ui:[a&]:hover:bg-accent ui:[a&]:hover:text-accent-foreground ui:dark:[a&]:hover:bg-accent/50',
|
||||
'ghost-default':
|
||||
'ui:text-primary ui:[a&]:hover:bg-accent ui:[a&]:hover:text-primary ui:dark:[a&]:hover:bg-accent/50',
|
||||
'ghost-outline':
|
||||
'ui:bg-background ui:[a&]:hover:bg-accent ui:[a&]:hover:text-accent-foreground ui:dark:hover:border-input ui:dark:bg-input/30 ui:dark:hover:bg-input/50 ui:hover:border ui:hover:shadow-2xs',
|
||||
link: 'ui:text-primary ui:underline-offset-4 ui:[a&]:hover:underline'
|
||||
},
|
||||
size: {
|
||||
@@ -21,6 +26,8 @@
|
||||
sm: 'ui:h-8 ui:gap-1.5 ui:rounded-md ui:px-3 ui:has-[>svg]:px-2.5',
|
||||
lg: 'ui:h-10 ui:rounded-md ui:px-6 ui:has-[>svg]:px-4',
|
||||
icon: 'ui:size-9',
|
||||
'icon-2xs': 'ui:size-4',
|
||||
'icon-xs': `ui:size-6`,
|
||||
'icon-sm': 'ui:size-8',
|
||||
'icon-lg': 'ui:size-10'
|
||||
}
|
||||
@@ -65,7 +72,7 @@
|
||||
|
||||
<script lang="ts">
|
||||
import { cn } from '../../tools';
|
||||
import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle';
|
||||
import { Spinner } from '../spinner';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
@@ -116,11 +123,16 @@
|
||||
>
|
||||
{#if type !== undefined && loading}
|
||||
<div class="ui:absolute ui:flex ui:size-full ui:place-items-center ui:justify-center ui:bg-inherit">
|
||||
<div class="ui:flex ui:animate-spin ui:place-items-center ui:justify-center">
|
||||
<LoaderCircleIcon class="custom ui:size-4" />
|
||||
<div class="ui:flex ui:place-items-center ui:justify-center">
|
||||
<Spinner class="custom ui:size-4" />
|
||||
</div>
|
||||
</div>
|
||||
<span class="ui:sr-only">Loading</span>
|
||||
{/if}
|
||||
{@render children?.()}
|
||||
|
||||
{#if loading && size.includes('icon')}
|
||||
<span class="ui:sr-only">Loading</span>
|
||||
{:else}
|
||||
{@render children?.()}
|
||||
{/if}
|
||||
</svelte:element>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
bind:this={ref}
|
||||
data-slot="card-header"
|
||||
class={cn(
|
||||
'@container/card-header ui:has-data-[slot=card-action]:grid-cols-[1fr_auto] ui:[.border-b]:pb-6 ui:grid ui:auto-rows-min ui:grid-rows-[auto_auto] ui:items-start ui:gap-1.5 ui:px-6',
|
||||
'ui:has-data-[slot=card-action]:grid-cols-[1fr_auto] ui:[.border-b]:pb-6 ui:grid ui:auto-rows-min ui:grid-rows-[auto_auto] ui:items-start ui:gap-1.5 ui:px-6 @container/card-header',
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { cn, type WithElementRef } from '../../tools';
|
||||
import type { HTMLAttributes } from 'svelte/elements';
|
||||
import ChartStyle from './chart-style.svelte';
|
||||
import { setChartContext, type ChartConfig } from './chart-utils.js';
|
||||
import { setChartContext, type ChartConfig } from './chart-utils';
|
||||
|
||||
const uid = $props.id();
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
|
||||
// by default, when you hover a point on a stacked series chart, it will drop the opacity
|
||||
// of the other series, this overrides that
|
||||
'[&_.lc-area-path]:opacity-100 [&_.lc-highlight-line]:opacity-100 [&_.lc-highlight-point]:opacity-100 [&_.lc-spline-path]:opacity-100 [&_.lc-text-svg]:overflow-visible [&_.lc-text]:text-xs',
|
||||
'[&_.lc-area-path]:opacity-100 [&_.lc-highlight-line]:opacity-100 [&_.lc-highlight-point]:opacity-100 [&_.lc-spline-path]:opacity-100 [&_.lc-text]:text-xs [&_.lc-text-svg]:overflow-visible',
|
||||
|
||||
// We don't want the little tick lines between the axis labels and the chart, so we remove
|
||||
// the stroke. The alternative is to manually disable `tickMarks` on the x/y axis of every
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<script lang="ts">
|
||||
import type { ChartLegendItem } from './chart-utils';
|
||||
|
||||
let { items, showValue = true }: { items: ChartLegendItem[]; showValue?: boolean } = $props();
|
||||
</script>
|
||||
|
||||
{#if items.length > 0}
|
||||
<div class="ui:flex ui:flex-wrap ui:items-center ui:justify-center ui:gap-x-6 ui:gap-y-2 ui:mt-4">
|
||||
{#each items as item (item.label)}
|
||||
<div class="ui:flex ui:items-center ui:gap-2">
|
||||
<span
|
||||
class="ui:size-3 ui:shrink-0 ui:rounded-[2px] ui:ring-1 ui:ring-inset ui:ring-border/50"
|
||||
style="background-color: {item.color}"
|
||||
aria-hidden="true"
|
||||
></span>
|
||||
<span class="ui:text-muted-foreground ui:text-xs">
|
||||
{item.label}
|
||||
{#if showValue && item.value !== undefined}
|
||||
<span class="ui:font-medium ui:text-foreground">({item.value})</span>
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { THEMES, type ChartConfig } from './chart-utils.js';
|
||||
import { THEMES, type ChartConfig } from './chart-utils';
|
||||
|
||||
let { id, config }: { id: string; config: ChartConfig } = $props();
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { cn, type WithElementRef, type WithoutChildren } from '../../tools';
|
||||
import type { HTMLAttributes } from 'svelte/elements';
|
||||
import { getPayloadConfigFromPayload, useChart, type TooltipPayload } from './chart-utils.js';
|
||||
import { getPayloadConfigFromPayload, useChart, type TooltipPayload } from './chart-utils';
|
||||
import { getTooltipContext, Tooltip as TooltipPrimitive } from 'layerchart';
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
|
||||
@@ -3,6 +3,12 @@ import { getContext, setContext, type Component, type ComponentProps, type Snipp
|
||||
|
||||
export const THEMES = { light: '', dark: '.dark' } as const;
|
||||
|
||||
export type ChartLegendItem = {
|
||||
label: string;
|
||||
color: string;
|
||||
value?: number;
|
||||
};
|
||||
|
||||
export type ChartConfig = {
|
||||
[k in string]: {
|
||||
label?: string;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import ChartContainer from './chart-container.svelte';
|
||||
import ChartLegend from './chart-legend.svelte';
|
||||
import ChartTooltip from './chart-tooltip.svelte';
|
||||
|
||||
export { getPayloadConfigFromPayload, type ChartConfig } from './chart-utils.js';
|
||||
export { getPayloadConfigFromPayload, type ChartConfig } from './chart-utils';
|
||||
|
||||
export { ChartContainer, ChartTooltip, ChartContainer as Container, ChartTooltip as Tooltip };
|
||||
export { ChartContainer, ChartLegend, ChartTooltip, ChartContainer as Container, ChartTooltip as Tooltip };
|
||||
export type { ChartLegendItem } from './chart-utils';
|
||||
|
||||
export { BarChart, LineChart, AreaChart, PieChart } from 'layerchart';
|
||||
export { scaleBand } from 'd3-scale';
|
||||
|
||||
@@ -27,9 +27,9 @@
|
||||
{#snippet children({ checked, indeterminate })}
|
||||
<div data-slot="checkbox-indicator" class="ui:text-current ui:transition-none">
|
||||
{#if checked}
|
||||
<CheckIcon class="ui:size-3.5" />
|
||||
<CheckIcon class="ui:size-3.5 custom" />
|
||||
{:else if indeterminate}
|
||||
<MinusIcon class="ui:size-3.5" />
|
||||
<MinusIcon class="ui:size-3.5 custom" />
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
</Dialog.Header>
|
||||
<Dialog.Content class="ui:overflow-hidden ui:p-0" {portalProps}>
|
||||
<Command
|
||||
class="**:data-[slot=command-input-wrapper]:h-12 ui:[&_[data-command-group]:not([hidden])_~[data-command-group]]:pt-0 ui:**:data-command-group:px-2 ui:[&_[data-command-input-wrapper]_svg]:h-5 ui:[&_[data-command-input-wrapper]_svg]:w-5 ui:**:data-command-input:h-12 ui:**:data-command-item:px-2 ui:**:data-command-item:py-3 ui:[&_[data-command-item]_svg]:h-5 ui:[&_[data-command-item]_svg]:w-5"
|
||||
class="ui:[&_[data-command-group]:not([hidden])_~[data-command-group]]:pt-0 ui:**:data-command-group:px-2 ui:[&_[data-command-input-wrapper]_svg]:h-5 ui:[&_[data-command-input-wrapper]_svg]:w-5 ui:**:data-command-input:h-12 ui:**:data-command-item:px-2 ui:**:data-command-item:py-3 ui:[&_[data-command-item]_svg]:h-5 ui:[&_[data-command-item]_svg]:w-5 **:data-[slot=command-input-wrapper]:h-12"
|
||||
{...restProps}
|
||||
bind:value
|
||||
bind:ref
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
<!--
|
||||
Installed from @ieedan/shadcn-svelte-extras
|
||||
-->
|
||||
|
||||
<script lang="ts">
|
||||
import { Button } from '../button';
|
||||
import { UseClipboard } from '../../hooks/use-clipboard.svelte';
|
||||
import { cn } from '../../tools';
|
||||
import { UseClipboard } from '../../use-clipboard.svelte';
|
||||
import { cn } from '../../utils.js';
|
||||
import CheckIcon from '@lucide/svelte/icons/check';
|
||||
import CopyIcon from '@lucide/svelte/icons/copy';
|
||||
import XIcon from '@lucide/svelte/icons/x';
|
||||
@@ -44,7 +40,6 @@
|
||||
type="button"
|
||||
name="copy"
|
||||
onclick={async () => {
|
||||
// text prop is reactive, so it will use the latest value when clicked
|
||||
const status = await clipboard.copy(text);
|
||||
|
||||
onCopy?.(status);
|
||||
@@ -53,7 +48,7 @@
|
||||
{#if clipboard.status === 'success'}
|
||||
<div in:scale={{ duration: animationDuration, start: 0.85 }}>
|
||||
<CheckIcon tabindex={-1} />
|
||||
<span class="ui:sr-only">Copied</span>
|
||||
<span class="sr-only">Copied</span>
|
||||
</div>
|
||||
{:else if clipboard.status === 'failure'}
|
||||
<div in:scale={{ duration: animationDuration, start: 0.85 }}>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { Dialog as DialogPrimitive } from 'bits-ui';
|
||||
import XIcon from '@lucide/svelte/icons/x';
|
||||
import type { Snippet } from 'svelte';
|
||||
import * as Dialog from './index.js';
|
||||
import { cn, type WithoutChildrenOrChild } from '../../tools';
|
||||
import CrossIcon from '@lucide/svelte/icons/x';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
@@ -25,7 +25,7 @@
|
||||
bind:ref
|
||||
data-slot="dialog-content"
|
||||
class={cn(
|
||||
'ui:bg-background ui:data-[state=open]:animate-in ui:data-[state=closed]:animate-out ui:data-[state=closed]:fade-out-0 ui:data-[state=open]:fade-in-0 ui:data-[state=closed]:zoom-out-95 ui:data-[state=open]:zoom-in-95 ui:fixed ui:left-[50%] ui:top-[50%] ui:z-50 ui:grid ui:w-full ui:max-w-[calc(100%-2rem)] ui:translate-x-[-50%] ui:translate-y-[-50%] ui:gap-4 ui:rounded-lg ui:border ui:p-6 ui:shadow-lg ui:duration-200 ui:sm:max-w-lg',
|
||||
'ui:bg-background ui:data-[state=open]:animate-in ui:data-[state=closed]:animate-out ui:data-[state=closed]:fade-out-0 ui:data-[state=open]:fade-in-0 ui:data-[state=closed]:zoom-out-95 ui:data-[state=open]:zoom-in-95 ui:fixed ui:left-[50%] ui:top-[50%] ui:z-200 ui:grid ui:w-full ui:max-w-[calc(100%-2rem)] ui:translate-x-[-50%] ui:translate-y-[-50%] ui:gap-4 ui:rounded-lg ui:p-6 ui:shadow-lg ui:duration-200 ui:sm:max-w-lg',
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
@@ -35,7 +35,7 @@
|
||||
<DialogPrimitive.Close
|
||||
class="ui:ring-offset-background ui:focus:ring-ring ui:rounded-xs ui:focus:outline-hidden ui:absolute ui:top-4 ui:opacity-70 ui:transition-opacity ui:hover:opacity-100 ui:focus:ring-2 ui:focus:ring-offset-2 ui:disabled:pointer-events-none ui:[&_svg:not([class*='size-'])]:size-4 ui:[&_svg]:pointer-events-none ui:[&_svg]:shrink-0 ui:end-4 ui:cursor-pointer"
|
||||
>
|
||||
<XIcon />
|
||||
<CrossIcon class="custom" />
|
||||
<span class="ui:sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
{/if}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
bind:ref
|
||||
data-slot="dialog-overlay"
|
||||
class={cn(
|
||||
'ui:data-[state=open]:animate-in ui:data-[state=closed]:animate-out ui:data-[state=closed]:fade-out-0 ui:data-[state=open]:fade-in-0 ui:fixed ui:inset-0 ui:z-50 ui:bg-black/50',
|
||||
'ui:data-[state=open]:animate-in ui:data-[state=closed]:animate-out ui:data-[state=closed]:fade-out-0 ui:data-[state=open]:fade-in-0 ui:fixed ui:inset-0 ui:z-200 ui:bg-black/50',
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'ui:bg-transparent',
|
||||
icon: "ui:bg-muted ui:text-foreground ui:flex ui:size-10 ui:shrink-0 ui:items-center ui:justify-center ui:rounded-lg ui:[&_svg:not([class*='size-'])]:size-6"
|
||||
icon: "ui:bg-muted ui:text-foreground ui:flex ui:size-10 ui:shrink-0 ui:items-center ui:justify-center ui:rounded-lg ui:[&_svg:not([class*='ui:size-'])]:size-6"
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
vertical: 'ui:flex-col ui:*:w-full ui:*.sr-only:w-auto',
|
||||
horizontal: [
|
||||
'ui:flex-row ui:items-center',
|
||||
'[&>[data-slot=field-label]]:flex-auto',
|
||||
'ui:[&>[data-slot=field-label]]:flex-auto',
|
||||
'ui:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px ui:has-[>[data-slot=field-content]]:items-start'
|
||||
],
|
||||
responsive: [
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { tv, type VariantProps } from 'tailwind-variants';
|
||||
|
||||
export const inputGroupAddonVariants = tv({
|
||||
base: "ui:text-muted-foreground ui:flex ui:h-auto ui:cursor-text ui:select-none ui:items-center ui:justify-center ui:gap-2 ui:py-1.5 ui:text-sm ui:font-medium ui:group-data-[disabled=true]/input-group:opacity-50 ui:[&>kbd]:rounded-[calc(var(--radius)-5px)] ui:[&>svg:not([class*='size-'])]:size-4",
|
||||
base: "ui:text-muted-foreground ui:flex ui:h-auto ui:cursor-text ui:select-none ui:items-center ui:justify-center ui:gap-2 ui:py-1.5 ui:text-sm ui:font-medium ui:group-data-[disabled=true]/input-group:opacity-50 ui:[&>kbd]:rounded-[calc(var(--radius)-5px)] ui:[&>svg:not([class*='ui:size-'])]:size-4",
|
||||
variants: {
|
||||
align: {
|
||||
'inline-start': 'ui:order-first ui:ps-3 ui:has-[>button]:ms-[-0.45rem] ui:has-[>kbd]:ms-[-0.35rem]',
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
base: 'ui:flex ui:items-center ui:gap-2 ui:text-sm ui:shadow-none',
|
||||
variants: {
|
||||
size: {
|
||||
xs: "ui:h-6 ui:gap-1 ui:rounded-[calc(var(--radius)-5px)] ui:px-2 ui:has-[>svg]:px-2 ui:[&>svg:not([class*='size-'])]:size-3.5",
|
||||
xs: "ui:h-6 ui:gap-1 ui:rounded-[calc(var(--radius)-5px)] ui:px-2 ui:has-[>svg]:px-2 ui:[&>svg:not([class*='ui:size-'])]:size-3.5",
|
||||
sm: 'ui:h-8 ui:gap-1.5 ui:rounded-md ui:px-2.5 ui:has-[>svg]:px-2.5',
|
||||
'icon-xs': 'ui:size-6 ui:rounded-[calc(var(--radius)-5px)] ui:p-0 ui:has-[>svg]:p-0',
|
||||
'icon-sm': 'ui:size-8 ui:p-0 ui:has-[>svg]:p-0'
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Root from './input.svelte';
|
||||
import type { InputProps } from './input.svelte';
|
||||
|
||||
export {
|
||||
Root,
|
||||
//
|
||||
Root as Input
|
||||
Root as Input,
|
||||
type InputProps
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
type InputType = Exclude<HTMLInputTypeAttribute, 'file'>;
|
||||
|
||||
type Props = WithElementRef<
|
||||
export type InputProps = WithElementRef<
|
||||
Omit<HTMLInputAttributes, 'type'> & ({ type: 'file'; files?: FileList } | { type?: InputType; files?: undefined })
|
||||
>;
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
class: className,
|
||||
'data-slot': dataSlot = 'input',
|
||||
...restProps
|
||||
}: Props = $props();
|
||||
}: InputProps = $props();
|
||||
</script>
|
||||
|
||||
{#if type === 'file'}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import Root from './item.svelte';
|
||||
import Group from './item-group.svelte';
|
||||
import Separator from './item-separator.svelte';
|
||||
import Header from './item-header.svelte';
|
||||
import Footer from './item-footer.svelte';
|
||||
import Content from './item-content.svelte';
|
||||
import Title from './item-title.svelte';
|
||||
import Description from './item-description.svelte';
|
||||
import Actions from './item-actions.svelte';
|
||||
import Content from './item-content.svelte';
|
||||
import Description from './item-description.svelte';
|
||||
import Footer from './item-footer.svelte';
|
||||
import Group from './item-group.svelte';
|
||||
import Header from './item-header.svelte';
|
||||
import Media from './item-media.svelte';
|
||||
import Root from './item.svelte';
|
||||
import Separator from './item-separator.svelte';
|
||||
import SubDescription from './item-sub-description.svelte';
|
||||
import Title from './item-title.svelte';
|
||||
|
||||
export {
|
||||
Root,
|
||||
@@ -18,6 +19,7 @@ export {
|
||||
Content,
|
||||
Title,
|
||||
Description,
|
||||
SubDescription,
|
||||
Actions,
|
||||
Media,
|
||||
//
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'ui:bg-transparent',
|
||||
icon: "ui:bg-muted ui:size-8 ui:rounded-sm ui:border ui:[&_svg:not([class*='size-'])]:size-4",
|
||||
icon: "ui:bg-muted ui:size-8 ui:rounded-sm ui:border ui:[&_svg:not([class*='ui:size-'])]:size-4",
|
||||
image: 'ui:size-10 ui:overflow-hidden ui:rounded-sm ui:[&_img]:size-full ui:[&_img]:object-cover'
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<script lang="ts">
|
||||
import { cn, type WithElementRef } from '../../tools';
|
||||
import type { HTMLAttributes } from 'svelte/elements';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLSpanElement>> = $props();
|
||||
</script>
|
||||
|
||||
<span
|
||||
bind:this={ref}
|
||||
data-slot="item-sub-description"
|
||||
class={cn(
|
||||
'ui:text-muted-foreground ui:line-clamp-1 ui:text-balance ui:text-xs ui:font-normal ui:leading-normal',
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
</span>
|
||||
@@ -9,7 +9,7 @@
|
||||
bind:ref
|
||||
data-slot="navigation-menu-content"
|
||||
class={cn(
|
||||
'ui:data-[motion^=from-]:animate-in ui:data-[motion^=to-]:animate-out ui:data-[motion^=from-]:fade-in ui:data-[motion^=to-]:fade-out ui:data-[motion=from-end]:slide-in-from-end-52 ui:data-[motion=from-start]:slide-in-from-start-52 ui:data-[motion=to-end]:slide-out-to-end-52 ui:data-[motion=to-start]:slide-out-to-start-52 ui:start-0 ui:top-0 ui:w-full md:ui:absolute md:ui:w-auto',
|
||||
'ui:data-[motion^=from-]:animate-in ui:data-[motion^=to-]:animate-out ui:data-[motion^=from-]:fade-in ui:data-[motion^=to-]:fade-out ui:data-[motion=from-end]:slide-in-from-end-52 ui:data-[motion=from-start]:slide-in-from-start-52 ui:data-[motion=to-end]:slide-out-to-end-52 ui:data-[motion=to-start]:slide-out-to-start-52 ui:start-0 ui:top-0 ui:w-full ui:md:ui:absolute ui:md:ui:w-auto',
|
||||
'ui:group-data-[viewport=false]/navigation-menu:bg-popover ui:group-data-[viewport=false]/navigation-menu:text-popover-foreground ui:group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in ui:group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out ui:group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 ui:group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 ui:group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 ui:group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 ui:**:data-[slot=navigation-menu-link]:focus:ring-0 ui:**:data-[slot=navigation-menu-link]:focus:outline-none ui:group-data-[viewport=false]/navigation-menu:top-full ui:group-data-[viewport=false]/navigation-menu:mt-1.5 ui:group-data-[viewport=false]/navigation-menu:overflow-hidden ui:group-data-[viewport=false]/navigation-menu:rounded-md ui:group-data-[viewport=false]/navigation-menu:border ui:group-data-[viewport=false]/navigation-menu:shadow ui:group-data-[viewport=false]/navigation-menu:duration-200',
|
||||
className
|
||||
)}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
bind:ref
|
||||
data-slot="navigation-menu-indicator"
|
||||
class={cn(
|
||||
'ui:data-[state=visible]:animate-in ui:data-[state=hidden]:animate-out ui:data-[state=hidden]:fade-out ui:data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden',
|
||||
'ui:data-[state=visible]:animate-in ui:data-[state=hidden]:animate-out ui:data-[state=hidden]:fade-out ui:data-[state=visible]:fade-in ui:top-full ui:z-[1] ui:flex ui:h-1.5 ui:items-end ui:justify-center ui:overflow-hidden',
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
bind:ref
|
||||
data-slot="navigation-menu-viewport"
|
||||
class={cn(
|
||||
'ui:origin-top-center ui:bg-popover ui:text-popover-foreground ui:data-[state=open]:animate-in ui:data-[state=closed]:animate-out ui:data-[state=closed]:zoom-out-95 ui:data-[state=open]:zoom-in-90 ui:relative ui:mt-1.5 ui:h-(--bits-navigation-menu-viewport-height) ui:w-full ui:overflow-hidden ui:rounded-md ui:border ui:shadow md:ui:w-[var(--bits-navigation-menu-viewport-width)]',
|
||||
'ui:origin-top-center ui:bg-popover ui:text-popover-foreground ui:data-[state=open]:animate-in ui:data-[state=closed]:animate-out ui:data-[state=closed]:zoom-out-95 ui:data-[state=open]:zoom-in-90 ui:relative ui:mt-1.5 ui:h-(--bits-navigation-menu-viewport-height) ui:w-full ui:overflow-hidden ui:rounded-md ui:border ui:shadow ui:md:ui:w-[var(--bits-navigation-menu-viewport-width)]',
|
||||
className
|
||||
)}
|
||||
{...restProps}
|
||||
|
||||
@@ -5,12 +5,20 @@
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
isSticky = false,
|
||||
children,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
|
||||
isSticky?: boolean;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<div bind:this={ref} data-slot="page-header" class={cn('ui:flex ui:my-4 ui:flex-col', className)} {...restProps}>
|
||||
<div
|
||||
bind:this={ref}
|
||||
data-slot="page-header"
|
||||
class={cn('ui:flex ui:my-4 ui:py-2 ui:flex-col', isSticky && 'ui:sticky ui:top-13 ui:z-10 ui:bg-white', className)}
|
||||
{...restProps}
|
||||
>
|
||||
<div class="ui:flex ui:items-start ui:justify-between ui:gap-4">
|
||||
{@render children?.()}
|
||||
</div>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
const mergedProps = $derived(mergeProps(rest, state.props));
|
||||
</script>
|
||||
|
||||
<div class="relative">
|
||||
<div class="ui:relative">
|
||||
<Input
|
||||
{...mergedProps}
|
||||
bind:value
|
||||
|
||||
@@ -14,6 +14,6 @@
|
||||
bind:ref
|
||||
bind:value
|
||||
data-slot="radio-group"
|
||||
class={cn('ui:grid ui:gap-3', className)}
|
||||
class={cn('ui:grid ui:gap-2', className)}
|
||||
{...restProps}
|
||||
/>
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
side: 'right'
|
||||
side: 'ui:right'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
<script lang="ts">
|
||||
import { Dialog as SheetPrimitive } from 'bits-ui';
|
||||
import XIcon from '@lucide/svelte/icons/x';
|
||||
import { CloseIcon, HoverableItem } from '../../custom/moving-icons';
|
||||
import type { Snippet } from 'svelte';
|
||||
import SheetOverlay from './sheet-overlay.svelte';
|
||||
import { cn, type WithoutChildrenOrChild } from '../../../src/tools';
|
||||
@@ -50,11 +50,15 @@
|
||||
{...restProps}
|
||||
>
|
||||
{@render children?.()}
|
||||
<SheetPrimitive.Close
|
||||
class="ui:ring-offset-background ui:focus-visible:ring-ring ui:rounded-xs ui:focus-visible:outline-hidden ui:absolute ui:right-4 ui:top-4 ui:opacity-70 ui:transition-opacity ui:hover:opacity-100 ui:focus-visible:ring-2 ui:focus-visible:ring-offset-2 ui:disabled:pointer-events-none"
|
||||
>
|
||||
<XIcon class="ui:size-4" />
|
||||
<span class="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
<HoverableItem>
|
||||
{#snippet children(isHovered)}
|
||||
<SheetPrimitive.Close
|
||||
class="ui:ring-offset-background ui:focus-visible:ring-ring ui:rounded-xs ui:focus-visible:outline-hidden ui:absolute ui:right-4 ui:top-4 ui:opacity-70 ui:transition-opacity ui:hover:opacity-100 ui:focus-visible:ring-2 ui:focus-visible:ring-offset-2 ui:disabled:pointer-events-none"
|
||||
>
|
||||
<CloseIcon {isHovered} />
|
||||
<span class="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
{/snippet}
|
||||
</HoverableItem>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPrimitive.Portal>
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
'ui:peer-data-[size=lg]/menu-button:top-2.5',
|
||||
'ui:group-data-[collapsible=icon]:hidden',
|
||||
showOnHover &&
|
||||
'ui:peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 ui:data-[state=open]:opacity-100 ui:md:opacity-0',
|
||||
'ui:peer-data-[active=true]/menu-button:text-sidebar-accent-foreground ui:group-focus-within/menu-item:opacity-100 ui:group-hover/menu-item:opacity-100 ui:data-[state=open]:opacity-100 ui:md:opacity-0',
|
||||
className
|
||||
),
|
||||
'data-slot': 'sidebar-menu-action',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { tv, type VariantProps } from 'tailwind-variants';
|
||||
|
||||
export const sidebarMenuButtonVariants = tv({
|
||||
base: 'ui:peer/menu-button ui:cursor-pointer ui:outline-hidden ui:ring-sidebar-ring ui:hover:bg-sidebar-accent ui:hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground ui:group-has-data-[sidebar=menu-action]/menu-item:pr-8 ui:data-[active=true]:bg-sidebar-accent ui:data-[active=true]:text-sidebar-accent-foreground ui:data-[state=open]:hover:bg-sidebar-accent ui:data-[state=open]:hover:text-sidebar-accent-foreground ui:group-data-[collapsible=icon]:size-8! ui:group-data-[collapsible=icon]:p-2! ui:flex ui:w-full ui:items-center ui:gap-2 ui:overflow-hidden ui:rounded-md ui:p-2 ui:text-left ui:text-sm ui:transition-[width,height,padding] ui:focus-visible:ring-2 ui:disabled:pointer-events-none ui:disabled:opacity-50 ui:aria-disabled:pointer-events-none ui:aria-disabled:opacity-50 ui:data-[active=true]:font-medium ui:[&>span:last-child]:truncate ui:[&>svg]:size-4 ui:[&>svg]:shrink-0',
|
||||
base: 'ui:peer/menu-button ui:cursor-pointer ui:outline-hidden ui:text-foreground/70 ui:ring-sidebar-ring ui:hover:bg-sidebar-accent ui:hover:text-sidebar-accent-foreground ui:active:bg-sidebar-accent ui:active:text-sidebar-accent-foreground ui:group-has-data-[sidebar=menu-action]/menu-item:pr-8 ui:data-[active=true]:bg-sidebar-accent ui:data-[active=true]:text-sidebar-accent-foreground ui:data-[state=open]:hover:bg-sidebar-accent ui:data-[state=open]:hover:text-sidebar-accent-foreground ui:group-data-[collapsible=icon]:size-8! ui:group-data-[collapsible=icon]:p-2! ui:flex ui:w-full ui:items-center ui:gap-2 ui:overflow-hidden ui:rounded-md ui:p-2 ui:text-left ui:text-sm ui:transition-[width,height,padding] ui:focus-visible:ring-2 ui:disabled:pointer-events-none ui:disabled:opacity-50 ui:aria-disabled:pointer-events-none ui:aria-disabled:opacity-50 ui:data-[active=true]:font-medium ui:[&>span:last-child]:truncate ui:[&>svg]:size-4 ui:[&>svg]:shrink-0',
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'ui:hover:bg-sidebar-accent ui:hover:text-sidebar-accent-foreground',
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
const mergedProps = $derived({
|
||||
class: cn(
|
||||
'ui:text-sidebar-foreground ui:ring-sidebar-ring ui:hover:bg-sidebar-accent ui:hover:text-sidebar-accent-foreground ui:active:bg-sidebar-accent ui:active:text-sidebar-accent-foreground ui:[&>svg]:text-sidebar-accent-foreground ui:outline-hidden ui:flex ui:h-7 ui:min-w-0 ui:-translate-x-px ui:items-center ui:gap-2 ui:overflow-hidden ui:rounded-md ui:px-2 ui:focus-visible:ring-2 ui:disabled:pointer-events-none ui:disabled:opacity-50 ui:aria-disabled:pointer-events-none ui:aria-disabled:opacity-50 ui:[&>span:last-child]:truncate ui:[&>svg]:size-4 ui:[&>svg]:shrink-0',
|
||||
'ui:text-sidebar-foreground ui:ring-sidebar-ring ui:text-foreground/70 ui:hover:bg-sidebar-accent ui:hover:text-sidebar-accent-foreground ui:active:bg-sidebar-accent ui:active:text-sidebar-accent-foreground ui:[&>svg]:text-sidebar-accent-foreground ui:outline-hidden ui:flex ui:h-7 ui:min-w-0 ui:-translate-x-px ui:items-center ui:gap-2 ui:overflow-hidden ui:rounded-md ui:px-2 ui:focus-visible:ring-2 ui:cursor-pointer ui:disabled:pointer-events-none ui:disabled:opacity-50 ui:aria-disabled:pointer-events-none ui:aria-disabled:opacity-50 ui:[&>span:last-child]:truncate ui:[&>svg]:size-4 ui:[&>svg]:shrink-0',
|
||||
'ui:data-[active=true]:bg-sidebar-accent ui:data-[active=true]:text-sidebar-accent-foreground',
|
||||
size === 'sm' && 'ui:text-xs',
|
||||
size === 'md' && 'ui:text-sm',
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
class={cn(
|
||||
'ui:border-sidebar-border ui:mx-3.5 ui:flex ui:min-w-0 ui:translate-x-px ui:flex-col ui:gap-1 ui:border-l ui:px-2.5 ui:py-0.5',
|
||||
'ui:border-sidebar-border ui:ml-2.5 ui:flex ui:min-w-0 ui:translate-x-px ui:flex-col ui:gap-1 ui:border-l ui:pl-2 ui:py-0.5',
|
||||
'ui:group-data-[collapsible=icon]:hidden',
|
||||
className
|
||||
)}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { cn } from '../../tools';
|
||||
import Loader2Icon from '@lucide/svelte/icons/loader-2';
|
||||
// import Loader2Icon from '@lucide/svelte/icons/loader-2';
|
||||
import LoaderIcon from '@lucide/svelte/icons/loader';
|
||||
import type { ComponentProps } from 'svelte';
|
||||
|
||||
let { class: className, ...restProps }: ComponentProps<typeof Loader2Icon> = $props();
|
||||
let { class: className, ...restProps }: ComponentProps<typeof LoaderIcon> = $props();
|
||||
</script>
|
||||
|
||||
<Loader2Icon role="status" aria-label="Loading" class={cn('ui:size-4 ui:animate-spin', className)} {...restProps} />
|
||||
<LoaderIcon role="status" aria-label="Loading" class={cn('ui:size-4 ui:animate-spin', className)} {...restProps} />
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import Root from './toggle-group.svelte';
|
||||
import Item from './toggle-group-item.svelte';
|
||||
export { type ToggleGroupSpacing } from './toggle-group.svelte';
|
||||
export {
|
||||
toggleGroupItemVariants,
|
||||
type ToggleGroupItemSize,
|
||||
type ToggleGroupItemVariant,
|
||||
type ToggleGroupItemVariants
|
||||
} from './toggle-group-item.svelte';
|
||||
|
||||
export {
|
||||
Root,
|
||||
Item,
|
||||
//
|
||||
Root as ToggleGroup,
|
||||
Item as ToggleGroupItem
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { ToggleGroupItemSize, ToggleGroupItemVariant } from './toggle-group-item.svelte';
|
||||
|
||||
export interface ToggleGroupContextValue {
|
||||
getVariant: () => ToggleGroupItemVariant;
|
||||
getSize: () => ToggleGroupItemSize;
|
||||
}
|
||||
|
||||
export const TOGGLE_GROUP_CONTEXT = Symbol('toggle-group-context');
|
||||
@@ -0,0 +1,59 @@
|
||||
<script lang="ts" module>
|
||||
import { type VariantProps, tv } from 'tailwind-variants';
|
||||
|
||||
export const toggleGroupItemVariants = tv({
|
||||
base: "ui:hover:bg-muted ui:hover:text-muted-foreground ui:data-[state=on]:bg-accent ui:data-[state=on]:text-accent-foreground ui:focus-visible:border-ring ui:focus-visible:ring-ring/50 ui:aria-invalid:ring-destructive/20 ui:dark:aria-invalid:ring-destructive/40 ui:aria-invalid:border-destructive ui:inline-flex ui:items-center ui:justify-center ui:gap-2 ui:rounded-md ui:text-sm ui:font-medium ui:whitespace-nowrap ui:transition-[color,box-shadow] ui:outline-none ui:focus-visible:ring-[3px] ui:disabled:pointer-events-none ui:disabled:opacity-50 ui:[&_svg]:pointer-events-none ui:[&_svg]:shrink-0 ui:[&_svg:not([class*='ui:size-'])]:size-4",
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'ui:bg-transparent',
|
||||
outline:
|
||||
'ui:border-input ui:hover:bg-accent ui:hover:text-accent-foreground ui:border ui:bg-transparent ui:shadow-xs'
|
||||
},
|
||||
size: {
|
||||
default: 'ui:h-9 ui:min-w-9 ui:px-2',
|
||||
sm: 'ui:h-8 ui:min-w-8 ui:px-1.5',
|
||||
lg: 'ui:h-10 ui:min-w-10 ui:px-2.5'
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default'
|
||||
}
|
||||
});
|
||||
|
||||
export type ToggleGroupItemVariant = VariantProps<typeof toggleGroupItemVariants>['variant'];
|
||||
export type ToggleGroupItemSize = VariantProps<typeof toggleGroupItemVariants>['size'];
|
||||
export type ToggleGroupItemVariants = VariantProps<typeof toggleGroupItemVariants>;
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { getContext } from 'svelte';
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from 'bits-ui';
|
||||
import { cn } from '../../tools';
|
||||
import { TOGGLE_GROUP_CONTEXT, type ToggleGroupContextValue } from './toggle-group-context';
|
||||
|
||||
const toggleGroupContext = getContext<ToggleGroupContextValue | undefined>(TOGGLE_GROUP_CONTEXT);
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
variant = undefined,
|
||||
size = undefined,
|
||||
...restProps
|
||||
}: ToggleGroupPrimitive.ItemProps & {
|
||||
variant?: ToggleGroupItemVariant;
|
||||
size?: ToggleGroupItemSize;
|
||||
} = $props();
|
||||
|
||||
const resolvedVariant = $derived(
|
||||
(variant ?? toggleGroupContext?.getVariant() ?? 'default') as ToggleGroupItemVariant
|
||||
);
|
||||
const resolvedSize = $derived((size ?? toggleGroupContext?.getSize() ?? 'default') as ToggleGroupItemSize);
|
||||
</script>
|
||||
|
||||
<ToggleGroupPrimitive.Item
|
||||
bind:ref
|
||||
data-slot="toggle-group-item"
|
||||
class={cn(toggleGroupItemVariants({ variant: resolvedVariant, size: resolvedSize }), className)}
|
||||
{...restProps}
|
||||
/>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script lang="ts" module>
|
||||
export type ToggleGroupSpacing = 0 | 1 | 2 | 3 | 4;
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { setContext } from 'svelte';
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from 'bits-ui';
|
||||
import { cn } from '../../tools';
|
||||
import { TOGGLE_GROUP_CONTEXT, type ToggleGroupContextValue } from './toggle-group-context';
|
||||
import type { ToggleGroupItemSize, ToggleGroupItemVariant } from './toggle-group-item.svelte';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
value = $bindable(),
|
||||
class: className,
|
||||
variant = 'default',
|
||||
size = 'default',
|
||||
spacing = 1,
|
||||
...restProps
|
||||
}: ToggleGroupPrimitive.RootProps<'single' | 'multiple'> & {
|
||||
variant?: ToggleGroupItemVariant;
|
||||
size?: ToggleGroupItemSize;
|
||||
spacing?: ToggleGroupSpacing;
|
||||
} = $props();
|
||||
|
||||
setContext<ToggleGroupContextValue>(TOGGLE_GROUP_CONTEXT, {
|
||||
getVariant: () => variant,
|
||||
getSize: () => size
|
||||
});
|
||||
|
||||
const spacingClassName = $derived.by(() => {
|
||||
switch (spacing) {
|
||||
case 0:
|
||||
return 'ui:gap-0';
|
||||
case 2:
|
||||
return 'ui:gap-2';
|
||||
case 3:
|
||||
return 'ui:gap-3';
|
||||
case 4:
|
||||
return 'ui:gap-4';
|
||||
case 1:
|
||||
default:
|
||||
return 'ui:gap-1';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<ToggleGroupPrimitive.Root
|
||||
bind:ref
|
||||
bind:value
|
||||
data-slot="toggle-group"
|
||||
class={cn('ui:flex ui:w-fit ui:items-center ui:justify-center', spacingClassName, className)}
|
||||
{...restProps}
|
||||
/>
|
||||
@@ -2,7 +2,7 @@
|
||||
import { type VariantProps, tv } from 'tailwind-variants';
|
||||
|
||||
export const toggleVariants = tv({
|
||||
base: "ui:hover:bg-muted ui:hover:text-muted-foreground ui:data-[state=on]:bg-accent ui:data-[state=on]:text-accent-foreground ui:focus-visible:border-ring ui:focus-visible:ring-ring/50 ui:aria-invalid:ring-destructive/20 ui:dark:aria-invalid:ring-destructive/40 ui:aria-invalid:border-destructive ui:inline-flex ui:items-center ui:justify-center ui:gap-2 ui:rounded-md ui:text-sm ui:font-medium ui:whitespace-nowrap ui:transition-[color,box-shadow] ui:outline-none ui:focus-visible:ring-[3px] ui:disabled:pointer-events-none ui:disabled:opacity-50 ui:[&_svg]:pointer-events-none ui:[&_svg]:shrink-0 ui:[&_svg:not([class*='size-'])]:size-4",
|
||||
base: "ui:hover:bg-muted ui:hover:text-muted-foreground ui:data-[state=on]:bg-accent ui:data-[state=on]:text-accent-foreground ui:focus-visible:border-ring ui:focus-visible:ring-ring/50 ui:aria-invalid:ring-destructive/20 ui:dark:aria-invalid:ring-destructive/40 ui:aria-invalid:border-destructive ui:inline-flex ui:items-center ui:justify-center ui:gap-2 ui:rounded-md ui:text-sm ui:font-medium ui:whitespace-nowrap ui:transition-[color,box-shadow] ui:outline-none ui:focus-visible:ring-[3px] ui:disabled:pointer-events-none ui:disabled:opacity-50 ui:[&_svg]:pointer-events-none ui:[&_svg]:shrink-0 ui:[&_svg:not([class*='ui:size-'])]:size-4",
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'ui:bg-transparent',
|
||||
|
||||
@@ -28,14 +28,20 @@
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class={cn('group inline-flex w-full items-center', disabled ? 'cursor-not-allowed' : 'cursor-pointer', className)}>
|
||||
<div
|
||||
class={cn(
|
||||
'group ui:inline-flex ui:w-full ui:items-center',
|
||||
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Checkbox {name} {value} disabled={disabled || isEditable} bind:checked />
|
||||
{#if isEditable}
|
||||
<div class="w-2/4">
|
||||
<InputField bind:value={label} placeholder="Your option" className="ml-1" type="text" {onchange} />
|
||||
<div class="ui:w-2/4">
|
||||
<InputField bind:value={label} placeholder="Your option" className="ui:ml-1" type="text" {onchange} />
|
||||
</div>
|
||||
{:else}
|
||||
<span class="ml-2 dark:text-white">{label}</span>
|
||||
<span class="ui:ml-2 ui:dark:text-white">{label}</span>
|
||||
{/if}
|
||||
|
||||
{@render children?.()}
|
||||
|
||||
@@ -10,6 +10,6 @@
|
||||
let { value = 0, className = '' }: Props = $props();
|
||||
</script>
|
||||
|
||||
<Badge class={cn('h-5 min-w-5 rounded-full px-1 font-mono tabular-nums', className)} variant="outline">
|
||||
<Badge class={cn('ui:h-5 ui:min-w-5 ui:rounded-full ui:px-1 ui:font-mono tabular-nums', className)} variant="outline">
|
||||
{value}
|
||||
</Badge>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<script lang="ts">
|
||||
import { cn } from '../../tools';
|
||||
import Root from './code.svelte';
|
||||
import FileName from './code-file-header.svelte';
|
||||
import { langFromFilename } from './lang-from-filename';
|
||||
import type { SupportedLanguage } from './shiki';
|
||||
import type { CodeRootProps } from './types';
|
||||
|
||||
type Props = {
|
||||
filename: string;
|
||||
code: string;
|
||||
/** Language for syntax highlighting. Default: derived from filename. */
|
||||
lang?: SupportedLanguage;
|
||||
/** Props forwarded to Code.Root (variant, hideLines, highlight, class, etc.). */
|
||||
rootProps?: Omit<CodeRootProps, 'code' | 'lang'>;
|
||||
/** Class for the outer wrapper. */
|
||||
class?: string;
|
||||
};
|
||||
|
||||
let { filename, code, lang, rootProps = {}, class: className }: Props = $props();
|
||||
|
||||
const resolvedLang = $derived(lang ?? langFromFilename(filename));
|
||||
const mergedRootClass = $derived(cn('ui:w-full ui:border-none', rootProps.class));
|
||||
const restRoot = $derived.by(() => {
|
||||
const { class: _c, ...rest } = rootProps;
|
||||
return rest;
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class={cn('ui:rounded-lg ui:border ui:border-border', className)}>
|
||||
<FileName {filename} />
|
||||
<Root {code} lang={resolvedLang} class={mergedRootClass} {...restRoot} />
|
||||
</div>
|
||||
@@ -0,0 +1,24 @@
|
||||
<script lang="ts">
|
||||
import { CopyButton } from '../../base/copy-button';
|
||||
import { cn } from '../../tools';
|
||||
import { useCodeCopyButton } from './code-utils.svelte';
|
||||
import type { CodeCopyButtonProps } from './types';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
variant = 'secondary',
|
||||
size = 'icon-sm',
|
||||
class: className,
|
||||
...rest
|
||||
}: CodeCopyButtonProps = $props();
|
||||
|
||||
const copyButton = useCodeCopyButton();
|
||||
</script>
|
||||
|
||||
<CopyButton
|
||||
class={cn('ui:absolute ui:top-2 ui:right-2', className)}
|
||||
text={copyButton.code}
|
||||
{variant}
|
||||
{size}
|
||||
{...rest}
|
||||
/>
|
||||
@@ -0,0 +1,43 @@
|
||||
<script lang="ts">
|
||||
import { cn } from '../../tools';
|
||||
import FileCodeIcon from '@lucide/svelte/icons/file-code';
|
||||
import FileBracesIcon from '@lucide/svelte/icons/file-braces';
|
||||
import FileTextIcon from '@lucide/svelte/icons/file-text';
|
||||
|
||||
type Props = {
|
||||
filename: string;
|
||||
class?: string;
|
||||
/** Optional: override the icon (e.g. a custom Svelte component). Default: derived from extension. */
|
||||
icon?: import('svelte').Component;
|
||||
};
|
||||
|
||||
let { filename, class: className, icon: IconSlot }: Props = $props();
|
||||
|
||||
const iconMap: Record<string, import('svelte').Component> = {
|
||||
'.json': FileBracesIcon,
|
||||
'.ts': FileCodeIcon,
|
||||
'.tsx': FileCodeIcon,
|
||||
'.js': FileCodeIcon,
|
||||
'.jsx': FileCodeIcon,
|
||||
'.mjs': FileCodeIcon,
|
||||
'.cjs': FileCodeIcon,
|
||||
'.svelte': FileCodeIcon,
|
||||
'.bash': FileCodeIcon,
|
||||
'.sh': FileCodeIcon,
|
||||
'.diff': FileCodeIcon
|
||||
};
|
||||
|
||||
const ext = $derived(filename.includes('.') ? filename.slice(filename.lastIndexOf('.')) : '');
|
||||
const Icon = $derived(IconSlot ?? iconMap[ext] ?? FileTextIcon);
|
||||
</script>
|
||||
|
||||
<div
|
||||
id="file-name"
|
||||
class={cn('ui:flex ui:h-9 ui:items-center ui:justify-between ui:border-b ui:border-border ui:px-6', className)}
|
||||
role="presentation"
|
||||
>
|
||||
<div class="ui:flex ui:items-center ui:gap-2">
|
||||
<Icon class="ui:size-4" />
|
||||
<span class="ui:text-sm ui:font-medium">{filename}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,40 @@
|
||||
<script lang="ts">
|
||||
import Button from '../../base/button/button.svelte';
|
||||
import { useCodeOverflow } from './code-utils.svelte';
|
||||
import { box } from 'svelte-toolbelt';
|
||||
import type { CodeOverflowProps } from './types';
|
||||
import { cn } from '../../tools';
|
||||
|
||||
let { collapsed = $bindable(true), class: className, children, ...props }: CodeOverflowProps = $props();
|
||||
|
||||
const state = useCodeOverflow({
|
||||
collapsed: box.with(
|
||||
() => collapsed,
|
||||
(v) => (collapsed = v)
|
||||
)
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
{...props}
|
||||
data-code-overflow
|
||||
data-collapsed={collapsed}
|
||||
class={cn('ui:relative ui:overflow-y-hidden ui:data-[collapsed=true]:ui:max-h-[300px]', className)}
|
||||
>
|
||||
{@render children?.()}
|
||||
{#if collapsed}
|
||||
<div
|
||||
class="ui:from-background ui:absolute ui:bottom-0 ui:left-0 ui:z-10 ui:h-full ui:w-full ui:bg-linear-to-t ui:to-transparent"
|
||||
></div>
|
||||
{/if}
|
||||
{#if collapsed}
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
class="ui:absolute ui:bottom-2 ui:left-1/2 ui:z-20 ui:w-fit ui:-translate-x-1/2"
|
||||
onclick={state.toggleCollapsed}
|
||||
>
|
||||
Expand
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,125 @@
|
||||
import { Context } from 'runed';
|
||||
import type { ReadableBoxedValues, WritableBoxedValues } from 'svelte-toolbelt';
|
||||
import type { CodeRootProps } from './types';
|
||||
import { highlighter } from './shiki';
|
||||
import DOMPurify from 'isomorphic-dompurify';
|
||||
import type { HighlighterCore } from 'shiki';
|
||||
|
||||
type CodeOverflowStateProps = WritableBoxedValues<{
|
||||
collapsed: boolean;
|
||||
}>;
|
||||
|
||||
class CodeOverflowState {
|
||||
constructor(readonly opts: CodeOverflowStateProps) {
|
||||
this.toggleCollapsed = this.toggleCollapsed.bind(this);
|
||||
}
|
||||
|
||||
toggleCollapsed() {
|
||||
this.opts.collapsed.current = !this.opts.collapsed.current;
|
||||
}
|
||||
|
||||
get collapsed() {
|
||||
return this.opts.collapsed.current;
|
||||
}
|
||||
}
|
||||
|
||||
type CodeRootStateProps = ReadableBoxedValues<{
|
||||
code: string;
|
||||
lang: NonNullable<CodeRootProps['lang']>;
|
||||
hideLines: boolean;
|
||||
highlight: CodeRootProps['highlight'];
|
||||
}>;
|
||||
|
||||
class CodeRootState {
|
||||
highlighter: HighlighterCore | null = $state(null);
|
||||
|
||||
constructor(
|
||||
readonly opts: CodeRootStateProps,
|
||||
readonly overflow?: CodeOverflowState
|
||||
) {
|
||||
highlighter.then((hl) => (this.highlighter = hl));
|
||||
}
|
||||
|
||||
highlight(code: string) {
|
||||
return this.highlighter?.codeToHtml(code, {
|
||||
lang: this.opts.lang.current,
|
||||
themes: {
|
||||
light: 'github-light-default',
|
||||
dark: 'github-dark-default'
|
||||
},
|
||||
transformers: [
|
||||
{
|
||||
pre: (el) => {
|
||||
el.properties.style = '';
|
||||
|
||||
if (!this.opts.hideLines.current) {
|
||||
el.properties.class += ' line-numbers';
|
||||
}
|
||||
|
||||
return el;
|
||||
},
|
||||
line: (node, line) => {
|
||||
if (within(line, this.opts.highlight.current)) {
|
||||
node.properties.class = node.properties.class + ' line--highlighted';
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
get code() {
|
||||
return this.opts.code.current;
|
||||
}
|
||||
|
||||
highlighted = $derived(DOMPurify.sanitize(this.highlight(this.code) ?? ''));
|
||||
}
|
||||
|
||||
function within(num: number, range: CodeRootProps['highlight']) {
|
||||
if (!range) return false;
|
||||
|
||||
let within = false;
|
||||
|
||||
for (const r of range) {
|
||||
if (typeof r === 'number') {
|
||||
if (num === r) {
|
||||
within = true;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (r[0] <= num && num <= r[1]) {
|
||||
within = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return within;
|
||||
}
|
||||
|
||||
class CodeCopyButtonState {
|
||||
constructor(readonly root: CodeRootState) {}
|
||||
|
||||
get code() {
|
||||
return this.root.opts.code.current;
|
||||
}
|
||||
}
|
||||
|
||||
const overflowCtx = new Context<CodeOverflowState>('code-overflow-state');
|
||||
|
||||
const ctx = new Context<CodeRootState>('code-root-state');
|
||||
|
||||
export function useCodeOverflow(props: CodeOverflowStateProps) {
|
||||
return overflowCtx.set(new CodeOverflowState(props));
|
||||
}
|
||||
|
||||
export function useCode(props: CodeRootStateProps) {
|
||||
return ctx.set(new CodeRootState(props, overflowCtx.getOr(undefined)));
|
||||
}
|
||||
|
||||
export function useCodeCopyButton() {
|
||||
return new CodeCopyButtonState(ctx.get());
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<script lang="ts">
|
||||
import { cn } from '../../tools';
|
||||
import { codeVariants } from './';
|
||||
import type { CodeRootProps } from './types';
|
||||
import { useCode } from './code-utils.svelte';
|
||||
import { box } from 'svelte-toolbelt';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
variant = 'default',
|
||||
lang = 'typescript',
|
||||
code,
|
||||
class: className,
|
||||
hideLines = false,
|
||||
highlight = [],
|
||||
children,
|
||||
...rest
|
||||
}: CodeRootProps = $props();
|
||||
|
||||
const codeState = useCode({
|
||||
code: box.with(() => code),
|
||||
hideLines: box.with(() => hideLines),
|
||||
highlight: box.with(() => highlight),
|
||||
lang: box.with(() => lang)
|
||||
});
|
||||
</script>
|
||||
|
||||
<div {...rest} bind:this={ref} class={cn(codeVariants({ variant }), className)}>
|
||||
{@html codeState.highlighted}
|
||||
{@render children?.()}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../index.css";
|
||||
|
||||
:global(.dark .shiki),
|
||||
:global(.dark .shiki span) {
|
||||
color: var(--shiki-dark) !important;
|
||||
font-style: var(--shiki-dark-font-style) !important;
|
||||
font-weight: var(--shiki-dark-font-weight) !important;
|
||||
text-decoration: var(--shiki-dark-text-decoration) !important;
|
||||
}
|
||||
|
||||
/* Shiki see: https://shiki.matsu.io/guide/dual-themes#class-based-dark-mode */
|
||||
:global(html.dark .shiki, html.dark .shiki span) {
|
||||
color: var(--shiki-dark) !important;
|
||||
font-style: var(--shiki-dark-font-style) !important;
|
||||
font-weight: var(--shiki-dark-font-weight) !important;
|
||||
text-decoration: var(--shiki-dark-text-decoration) !important;
|
||||
}
|
||||
|
||||
:global(pre.shiki) {
|
||||
@apply ui:overflow-x-auto ui:rounded-lg ui:bg-inherit ui:py-4 ui:text-sm;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
:global(pre.shiki:not([data-code-overflow] *):not([data-code-overflow])) {
|
||||
@apply ui:overflow-y-auto;
|
||||
max-height: min(100%, 650px);
|
||||
}
|
||||
|
||||
:global(pre.shiki code) {
|
||||
@apply ui:grid ui:min-w-full ui:rounded-none ui:border-0 ui:bg-transparent ui:p-0 ui:break-words;
|
||||
counter-reset: line;
|
||||
box-decoration-break: clone;
|
||||
}
|
||||
|
||||
:global(pre.line-numbers) {
|
||||
counter-reset: step;
|
||||
counter-increment: step 0;
|
||||
}
|
||||
|
||||
:global(pre.line-numbers .line::before) {
|
||||
content: counter(step);
|
||||
counter-increment: step;
|
||||
display: inline-block;
|
||||
width: 1.8rem;
|
||||
margin-right: 1.4rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
:global(pre.line-numbers .line::before) {
|
||||
@apply ui:text-muted-foreground;
|
||||
}
|
||||
|
||||
:global(pre .line.line--highlighted) {
|
||||
@apply ui:bg-secondary;
|
||||
}
|
||||
|
||||
:global(pre .line.line--highlighted span) {
|
||||
@apply ui:relative;
|
||||
}
|
||||
|
||||
:global(pre .line) {
|
||||
@apply ui:inline-block ui:min-h-4 ui:w-full ui:px-4 ui:py-0.5;
|
||||
}
|
||||
|
||||
:global(pre.line-numbers .line) {
|
||||
@apply ui:px-2;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
import { tv, type VariantProps } from 'tailwind-variants';
|
||||
import Root from './code.svelte';
|
||||
import Overflow from './code-overflow.svelte';
|
||||
import CopyButton from './code-copy-button.svelte';
|
||||
import FileName from './code-file-header.svelte';
|
||||
import Block from './code-block.svelte';
|
||||
import type { CodeCopyButtonProps, CodeOverflowProps, CodeRootProps } from './types';
|
||||
|
||||
export { langFromFilename } from './lang-from-filename';
|
||||
|
||||
export const codeVariants = tv({
|
||||
base: 'ui:not-prose ui:relative ui:h-full ui:overflow-auto ui:rounded-lg ui:border',
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'ui:border-border ui:bg-card',
|
||||
secondary: 'ui:bg-secondary/50 ui:border-transparent'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export type CodeVariant = VariantProps<typeof codeVariants>['variant'];
|
||||
|
||||
export {
|
||||
Root,
|
||||
CopyButton,
|
||||
Overflow,
|
||||
FileName,
|
||||
Block,
|
||||
type CodeRootProps as RootProps,
|
||||
type CodeCopyButtonProps as CopyButtonProps,
|
||||
type CodeOverflowProps as OverflowProps
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { SupportedLanguage } from './shiki';
|
||||
|
||||
const extToLang: Record<string, SupportedLanguage> = {
|
||||
'.ts': 'typescript',
|
||||
'.tsx': 'typescript',
|
||||
'.js': 'javascript',
|
||||
'.jsx': 'javascript',
|
||||
'.mjs': 'javascript',
|
||||
'.cjs': 'javascript',
|
||||
'.svelte': 'svelte',
|
||||
'.json': 'json',
|
||||
'.bash': 'bash',
|
||||
'.sh': 'bash',
|
||||
'.diff': 'diff'
|
||||
};
|
||||
|
||||
/** Derive Shiki/Code language from a filename. Defaults to `typescript` if unknown. */
|
||||
export function langFromFilename(filename: string): SupportedLanguage {
|
||||
const ext = filename.includes('.') ? filename.slice(filename.lastIndexOf('.')) : '';
|
||||
return extToLang[ext] ?? 'typescript';
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Follows the best practices established in https://shiki.matsu.io/guide/best-performance
|
||||
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
|
||||
import { createHighlighterCore } from 'shiki/core';
|
||||
|
||||
const bundledLanguages = {
|
||||
bash: () => import('@shikijs/langs/bash'),
|
||||
diff: () => import('@shikijs/langs/diff'),
|
||||
javascript: () => import('@shikijs/langs/javascript'),
|
||||
json: () => import('@shikijs/langs/json'),
|
||||
svelte: () => import('@shikijs/langs/svelte'),
|
||||
typescript: () => import('@shikijs/langs/typescript')
|
||||
};
|
||||
|
||||
/** The languages configured for the highlighter */
|
||||
export type SupportedLanguage = keyof typeof bundledLanguages;
|
||||
|
||||
/** A preloaded highlighter instance. */
|
||||
export const highlighter = createHighlighterCore({
|
||||
themes: [import('@shikijs/themes/github-light-default'), import('@shikijs/themes/github-dark-default')],
|
||||
langs: Object.entries(bundledLanguages).map(([_, lang]) => lang),
|
||||
engine: createJavaScriptRegexEngine()
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { WithChildren, WithoutChildren } from 'bits-ui';
|
||||
import type { CodeVariant } from './';
|
||||
import type { SupportedLanguage } from './shiki';
|
||||
import type { HTMLAttributes } from 'svelte/elements';
|
||||
import type { CopyButtonPropsWithoutHTML } from '../../base/copy-button/types';
|
||||
|
||||
export type CodeRootPropsWithoutHTML = WithChildren<{
|
||||
ref?: HTMLDivElement | null;
|
||||
variant?: CodeVariant;
|
||||
lang?: SupportedLanguage;
|
||||
code: string;
|
||||
class?: string;
|
||||
hideLines?: boolean;
|
||||
highlight?: (number | [number, number])[];
|
||||
}>;
|
||||
|
||||
export type CodeRootProps = CodeRootPropsWithoutHTML & WithoutChildren<HTMLAttributes<HTMLDivElement>>;
|
||||
|
||||
export type CodeCopyButtonPropsWithoutHTML = Omit<CopyButtonPropsWithoutHTML, 'text'>;
|
||||
|
||||
export type CodeCopyButtonProps = CodeCopyButtonPropsWithoutHTML & WithoutChildren<HTMLAttributes<HTMLButtonElement>>;
|
||||
|
||||
export type CodeOverflowPropsWithoutHTML = WithChildren<{
|
||||
collapsed?: boolean;
|
||||
}>;
|
||||
|
||||
export type CodeOverflowProps = CodeOverflowPropsWithoutHTML & WithoutChildren<HTMLAttributes<HTMLDivElement>>;
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
import * as Item from '../../base/item';
|
||||
import FileTextIcon from '@lucide/svelte/icons/file-text';
|
||||
import DownloadIcon from '@lucide/svelte/icons/download';
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
interface Props {
|
||||
/** Document/file title (e.g. filename) */
|
||||
title: string;
|
||||
/** Optional subtitle (e.g. file type and size) */
|
||||
subtitle?: string;
|
||||
/** Optional presigned URL for View/Download links. When provided, renders View and Download links unless `actions` slot is used. */
|
||||
fileUrl?: string | null;
|
||||
/** Label for the View link. Default: "View" */
|
||||
viewLabel?: string;
|
||||
/** Label for the Download link. Default: "Download" */
|
||||
downloadLabel?: string;
|
||||
/** Optional slot for custom actions (e.g. lesson document buttons). When provided, replaces the default View/Download links. */
|
||||
actions?: Snippet;
|
||||
/** Optional content to render before the actions (e.g. edit mode dropdown) */
|
||||
header?: Snippet;
|
||||
class?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
title,
|
||||
subtitle = '',
|
||||
fileUrl = null,
|
||||
viewLabel = 'View',
|
||||
downloadLabel = 'Download',
|
||||
actions,
|
||||
header,
|
||||
class: className = ''
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<Item.Root variant="outline" class="ui:w-fit! ui:min-w-0 ui:cursor-default! ui:p-3! {className}">
|
||||
<div class="ui:flex ui:w-full ui:min-w-0 ui:flex-col">
|
||||
{#if header}
|
||||
{@render header()}
|
||||
{/if}
|
||||
|
||||
<Item.Header>
|
||||
<Item.Media variant="icon" class="ui:size-14! ui:[&_svg]:size-8!" aria-label={title}>
|
||||
<FileTextIcon class="ui:text-muted-foreground" />
|
||||
</Item.Media>
|
||||
</Item.Header>
|
||||
|
||||
<Item.Content class="ui:w-full! ui:min-w-0">
|
||||
<Item.Title class="ui:line-clamp-2 ui:min-h-[44px] ui:text-base!" {title}>
|
||||
<span class="ui:max-w-[200px] ui:truncate ui:break-all">{title}</span>
|
||||
</Item.Title>
|
||||
{#if subtitle}
|
||||
<p class="ui:text-muted-foreground ui:mt-1 ui:text-xs">{subtitle}</p>
|
||||
{/if}
|
||||
|
||||
{#if actions || fileUrl}
|
||||
<div class="ui:mt-3 ui:flex ui:w-full ui:min-w-0 ui:gap-2">
|
||||
{#if actions}
|
||||
{@render actions()}
|
||||
{:else if fileUrl}
|
||||
<a
|
||||
href={fileUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="ui:border-input ui:bg-background ui:text-foreground hover:ui:bg-accent hover:ui:text-accent-foreground ui:shrink ui:inline-flex ui:items-center ui:gap-1.5 ui:rounded-md ui:border ui:px-3 ui:py-1.5 ui:text-sm ui:font-medium"
|
||||
>
|
||||
{viewLabel}
|
||||
</a>
|
||||
<a
|
||||
href={fileUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
download={title}
|
||||
class="ui:border-input ui:bg-background ui:text-foreground hover:ui:bg-accent hover:ui:text-accent-foreground ui:shrink ui:inline-flex ui:items-center ui:gap-1.5 ui:rounded-md ui:border ui:px-3 ui:py-1.5 ui:text-sm ui:font-medium"
|
||||
>
|
||||
<DownloadIcon class="ui:size-4" />
|
||||
{downloadLabel}
|
||||
</a>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</Item.Content>
|
||||
</div>
|
||||
</Item.Root>
|
||||
@@ -0,0 +1 @@
|
||||
export { default as DocumentCard } from './document-card.svelte';
|
||||
@@ -23,7 +23,7 @@
|
||||
}: Props & Omit<ComponentProps<typeof InputGroup.Root>, 'class' | 'children'> = $props();
|
||||
</script>
|
||||
|
||||
<InputGroup.Root class={cn('w-full', className)} data-slot="domain-input">
|
||||
<InputGroup.Root class={cn('ui:w-full', className)} data-slot="domain-input">
|
||||
<InputGroup.Addon>
|
||||
<InputGroup.Text>{prefix}</InputGroup.Text>
|
||||
</InputGroup.Addon>
|
||||
|
||||
@@ -6,14 +6,18 @@
|
||||
|
||||
/* For Placeholder */
|
||||
|
||||
.tiptap .is-empty:not(blockquote.is-empty)::before {
|
||||
.tiptap > p.is-empty:only-child::before {
|
||||
pointer-events: none;
|
||||
float: left;
|
||||
height: 0;
|
||||
color: var(--color-muted-foreground);
|
||||
color: var(--muted-foreground);
|
||||
content: attr(data-placeholder);
|
||||
}
|
||||
|
||||
.tiptap.ProseMirror {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* Heading Styles */
|
||||
.tiptap h1,
|
||||
.tiptap h2,
|
||||
@@ -456,38 +460,38 @@ input[type='checkbox'] {
|
||||
|
||||
/* Mathematics extension styles */
|
||||
.tiptap .tiptap-mathematics-render {
|
||||
padding: 0 0.25rem;
|
||||
border-radius: 0.25rem;
|
||||
padding: 0 0.25rem;
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
|
||||
/* Editable math block */
|
||||
.tiptap .tiptap-mathematics-render--editable {
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.tiptap .tiptap-mathematics-render--editable:hover {
|
||||
background: var(--code-bg);
|
||||
background: var(--code-bg);
|
||||
}
|
||||
|
||||
/* Inline math */
|
||||
.tiptap .tiptap-mathematics-render[data-type='inline-math'] {
|
||||
display: inline-block;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
/* Block math */
|
||||
.tiptap .tiptap-mathematics-render[data-type='block-math'] {
|
||||
display: block;
|
||||
margin: 1rem 0;
|
||||
padding: 0.5rem;
|
||||
text-align: center;
|
||||
font-size: 1.25rem;
|
||||
display: block;
|
||||
margin: 1rem 0;
|
||||
padding: 0.5rem;
|
||||
text-align: center;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
/* Error styles */
|
||||
.tiptap .tiptap-mathematics-render.inline-math-error,
|
||||
.tiptap .tiptap-mathematics-render.block-math-error {
|
||||
background: var(--code-bg);
|
||||
color: var(--color-destructive);
|
||||
border: 1px solid darkred;
|
||||
background: var(--code-bg);
|
||||
color: var(--color-destructive);
|
||||
border: 1px solid darkred;
|
||||
}
|
||||
|
||||
@@ -41,8 +41,7 @@
|
||||
editorClass = '',
|
||||
placeholder,
|
||||
onContentChange,
|
||||
onEditorReady,
|
||||
onEditorDestroy
|
||||
onEditorReady
|
||||
}: Props = $props();
|
||||
|
||||
let editor = $state<Editor>();
|
||||
@@ -86,9 +85,11 @@
|
||||
}
|
||||
});
|
||||
|
||||
let isEditorReady = $state(false);
|
||||
// Handle editor ready
|
||||
$effect(() => {
|
||||
if (editor) {
|
||||
if (editor && !isEditorReady) {
|
||||
isEditorReady = true;
|
||||
onEditorReady?.(editor);
|
||||
}
|
||||
});
|
||||
@@ -105,7 +106,7 @@
|
||||
{#if browser}
|
||||
<div
|
||||
class={cn(
|
||||
'ui:bg-background ui:z-50 ui:flex ui:size-full ui:w-full ui:flex-col ui:rounded-md ui:border ui:border-dashed',
|
||||
'ui:relative ui:bg-background ui:z-50 ui:flex ui:size-full ui:w-full ui:flex-col ui:rounded-md ui:border ui:border-dashed',
|
||||
className
|
||||
)}
|
||||
>
|
||||
@@ -120,10 +121,12 @@
|
||||
{/if}
|
||||
<EdraBubbleMenu {editor} />
|
||||
|
||||
<EdraDragHandleExtended {editor} />
|
||||
{#if editable}
|
||||
<EdraDragHandleExtended {editor} />
|
||||
{/if}
|
||||
{/if}
|
||||
<EdraEditor
|
||||
class={cn('ui:h-128 ui:overflow-auto ui:p-4', editorClass)}
|
||||
class={cn('ui:relative ui:h-128 ui:overflow-auto ui:p-4', editorClass)}
|
||||
bind:editor
|
||||
{editable}
|
||||
{content}
|
||||
|
||||
@@ -90,12 +90,7 @@ export default (
|
||||
onClick: (node, pos) => {
|
||||
const newCalculation = prompt('Enter new calculation:', node.attrs.latex);
|
||||
if (newCalculation) {
|
||||
editor
|
||||
.chain()
|
||||
.setNodeSelection(pos)
|
||||
.updateBlockMath({ latex: newCalculation })
|
||||
.focus()
|
||||
.run();
|
||||
editor.chain().setNodeSelection(pos).updateBlockMath({ latex: newCalculation }).focus().run();
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -103,12 +98,7 @@ export default (
|
||||
onClick: (node, pos) => {
|
||||
const newCalculation = prompt('Enter new calculation:', node.attrs.latex);
|
||||
if (newCalculation) {
|
||||
editor
|
||||
.chain()
|
||||
.setNodeSelection(pos)
|
||||
.updateInlineMath({ latex: newCalculation })
|
||||
.focus()
|
||||
.run();
|
||||
editor.chain().setNodeSelection(pos).updateInlineMath({ latex: newCalculation }).focus().run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,20 +2,20 @@ import { textInputRule } from '@tiptap/core';
|
||||
import { InlineMath } from '@tiptap/extension-mathematics';
|
||||
|
||||
export const InlineMathReplacer = InlineMath.extend({
|
||||
name: 'inlineMathReplacer',
|
||||
addInputRules() {
|
||||
return [
|
||||
textInputRule({
|
||||
find: /\$\$([^$]+)\$\$/,
|
||||
replace: ({ match, commands }) => {
|
||||
const latex = match[1];
|
||||
// Insert the inline math node with the LaTeX content
|
||||
commands.insertInlineMath({
|
||||
latex
|
||||
});
|
||||
return '';
|
||||
}
|
||||
})
|
||||
];
|
||||
}
|
||||
name: 'inlineMathReplacer',
|
||||
addInputRules() {
|
||||
return [
|
||||
textInputRule({
|
||||
find: /\$\$([^$]+)\$\$/,
|
||||
replace: ({ match, commands }) => {
|
||||
const latex = match[1];
|
||||
// Insert the inline math node with the LaTeX content
|
||||
commands.insertInlineMath({
|
||||
latex
|
||||
});
|
||||
return '';
|
||||
}
|
||||
})
|
||||
];
|
||||
}
|
||||
});
|
||||
|
||||
@@ -43,7 +43,7 @@ function absoluteRect(node: Element) {
|
||||
const data = node.getBoundingClientRect();
|
||||
const modal = node.closest('[role="dialog"]');
|
||||
|
||||
if (modal && window.getComputedStyle(modal).transform !== 'none') {
|
||||
if (modal) {
|
||||
const modalRect = modal.getBoundingClientRect();
|
||||
|
||||
return {
|
||||
|
||||
@@ -12,14 +12,17 @@
|
||||
|
||||
let isCopying = $state(false);
|
||||
|
||||
const languages: string[] = extension.options.lowlight.listLanguages().sort();
|
||||
const languages = $derived.by(() => extension.options.lowlight.listLanguages().sort());
|
||||
|
||||
let defaultLanguage = $state(node.attrs.language);
|
||||
let defaultLanguage = $derived<string>(node.attrs.language);
|
||||
|
||||
function copyCode() {
|
||||
if (!preRef) return;
|
||||
|
||||
isCopying = true;
|
||||
|
||||
navigator.clipboard.writeText(preRef.innerText);
|
||||
|
||||
setTimeout(() => {
|
||||
isCopying = false;
|
||||
}, 1000);
|
||||
|
||||
@@ -167,7 +167,7 @@
|
||||
}}
|
||||
>
|
||||
<div
|
||||
class="ui:bg-muted ui:z-20 ui:h-[70px] ui:w-1 ui:rounded-xl ui:border ui:opacity-0 ui:transition-all group-hover:opacity-100"
|
||||
class="ui:bg-muted ui:z-20 ui:h-[70px] ui:w-1 ui:rounded-xl ui:border ui:opacity-0 ui:transition-all ui:group-hover:opacity-100"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
@@ -185,7 +185,7 @@
|
||||
}}
|
||||
>
|
||||
<div
|
||||
class="ui:bg-muted ui:z-20 ui:h-[70px] ui:w-1 ui:rounded-xl ui:border ui:opacity-0 ui:transition-all group-hover:opacity-100"
|
||||
class="ui:bg-muted ui:z-20 ui:h-[70px] ui:w-1 ui:rounded-xl ui:border ui:opacity-0 ui:transition-all ui:group-hover:opacity-100"
|
||||
></div>
|
||||
</div>
|
||||
<div
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
const plugin = DragHandlePlugin({
|
||||
pluginKey: pluginKey,
|
||||
dragHandleWidth: 20,
|
||||
scrollTreshold: 100,
|
||||
scrollTreshold: 1000,
|
||||
dragHandleSelector: '.drag-handle',
|
||||
excludedTags: ['pre', 'code', 'table p'],
|
||||
customNodes: [],
|
||||
@@ -82,8 +82,7 @@
|
||||
if (currentNodePos === -1) return;
|
||||
const currentNodeSize = currentNode?.nodeSize || 0;
|
||||
const insertPos = currentNodePos + currentNodeSize;
|
||||
const currentNodeIsEmptyParagraph =
|
||||
currentNode?.type.name === 'paragraph' && currentNode?.content?.size === 0;
|
||||
const currentNodeIsEmptyParagraph = currentNode?.type.name === 'paragraph' && currentNode?.content?.size === 0;
|
||||
const focusPos = currentNodeIsEmptyParagraph ? currentNodePos + 2 : insertPos + 2;
|
||||
editor
|
||||
.chain()
|
||||
@@ -92,10 +91,7 @@
|
||||
if (currentNodeIsEmptyParagraph) {
|
||||
tr.insertText('/', currentNodePos, currentNodePos + 1);
|
||||
} else {
|
||||
tr.insert(
|
||||
insertPos,
|
||||
state.schema.nodes.paragraph.create(null, [state.schema.text('/')])
|
||||
);
|
||||
tr.insert(insertPos, state.schema.nodes.paragraph.create(null, [state.schema.text('/')]));
|
||||
}
|
||||
|
||||
return dispatch(tr);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from 'svelte';
|
||||
import { onDestroy, onMount, untrack } from 'svelte';
|
||||
import type { EdraEditorProps } from '../types';
|
||||
import initEditor from '../editor';
|
||||
import { focusEditor } from '../utils';
|
||||
@@ -71,17 +71,15 @@
|
||||
AudioExtended(AudioExtendedComp),
|
||||
IFramePlaceholder(IFramePlaceHolderComp),
|
||||
IFrameExtended(IFrameExtendedComp),
|
||||
slashcommand(SlashCommandList),
|
||||
Placeholder.configure({
|
||||
placeholder
|
||||
})
|
||||
slashcommand(SlashCommandList)
|
||||
],
|
||||
{
|
||||
onUpdate,
|
||||
onTransaction(props) {
|
||||
editor = undefined;
|
||||
editor = props.editor;
|
||||
},
|
||||
// onTransaction(props) {
|
||||
// console.log('on transaction', props);
|
||||
// editor = undefined;
|
||||
// editor = props.editor;
|
||||
// },
|
||||
editable,
|
||||
autofocus
|
||||
},
|
||||
|
||||
@@ -22,17 +22,28 @@
|
||||
|
||||
let isDragging = $state(false);
|
||||
|
||||
editor.view.dom.addEventListener('dragstart', () => {
|
||||
const handleDragStart = () => {
|
||||
isDragging = true;
|
||||
});
|
||||
|
||||
editor.view.dom.addEventListener('drop', () => {
|
||||
};
|
||||
const handleDrop = () => {
|
||||
isDragging = true;
|
||||
|
||||
// Allow some time for the drop action to complete before re-enabling
|
||||
setTimeout(() => {
|
||||
isDragging = false;
|
||||
}, 100); // Adjust delay if needed
|
||||
};
|
||||
|
||||
$effect(() => {
|
||||
const editorInstance = editor;
|
||||
|
||||
editorInstance.view.dom.addEventListener('dragstart', handleDragStart);
|
||||
editorInstance.view.dom.addEventListener('drop', handleDrop);
|
||||
|
||||
return () => {
|
||||
editorInstance.view.dom.removeEventListener('dragstart', handleDragStart);
|
||||
editorInstance.view.dom.removeEventListener('drop', handleDrop);
|
||||
};
|
||||
});
|
||||
|
||||
function shouldShow(props: ShouldShowProps) {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
variants: {
|
||||
variant: {
|
||||
default: '',
|
||||
page: 'ui:h-full ui:border ui:border-dashed ui:max-w-3xl ui:mx-auto'
|
||||
page: 'ui:h-full ui:border ui:border-dashed ui:max-w-3xl ui:mx-auto'
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -22,6 +22,7 @@
|
||||
title?: string;
|
||||
description?: string;
|
||||
icon?: Component<any, any, any>;
|
||||
iconClass?: string;
|
||||
class?: string;
|
||||
children?: Snippet;
|
||||
variant?: EmptyVariant;
|
||||
@@ -33,6 +34,7 @@
|
||||
title,
|
||||
description,
|
||||
icon: IconComponent,
|
||||
iconClass = '',
|
||||
class: className = '',
|
||||
children,
|
||||
variant = 'default',
|
||||
@@ -55,7 +57,7 @@
|
||||
{#if IconComponent}
|
||||
<EmptyBase.Media variant="icon">
|
||||
{@const Icon = IconComponent}
|
||||
<Icon />
|
||||
<Icon class={iconClass} />
|
||||
</EmptyBase.Media>
|
||||
{/if}
|
||||
{#if title}
|
||||
|
||||
@@ -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>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user