Merge pull request #471 from learnhouse/fix/editor-issues

Fix UI glitchs, editor bugs
This commit is contained in:
Badr B. 2025-04-07 14:39:18 +02:00 committed by GitHub
commit bbe6f9e2c5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 1048 additions and 157 deletions

View file

@ -8,6 +8,7 @@ from src.db.courses.courses import Course, CourseRead
from src.db.collections import Collection, CollectionRead
from src.db.collections_courses import CollectionCourse
from src.db.organizations import Organization
from src.db.user_organizations import UserOrganization
from src.services.courses.courses import search_courses
T = TypeVar('T')
@ -60,6 +61,10 @@ async def search_across_org(
# Search users
users_query = (
select(User)
.join(UserOrganization, and_(
UserOrganization.user_id == User.id,
UserOrganization.org_id == org.id
))
.where(
or_(
text('LOWER("user".username) LIKE LOWER(:pattern) OR ' +

View file

@ -0,0 +1,434 @@
'use client';
import React, { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { searchOrgContent } from '@services/search/search';
import { useLHSession } from '@components/Contexts/LHSessionContext';
import { useOrg } from '@components/Contexts/OrgContext';
import { Book, GraduationCap, Users, Search, Filter, X } from 'lucide-react';
import Link from 'next/link';
import { getCourseThumbnailMediaDirectory, getUserAvatarMediaDirectory } from '@services/media/media';
import { getUriWithOrg } from '@services/config/config';
import { removeCoursePrefix } from '@components/Objects/Thumbnails/CourseThumbnail';
import UserAvatar from '@components/Objects/UserAvatar';
// Types from SearchBar component
interface User {
username: string;
first_name: string;
last_name: string;
email: string;
avatar_image: string;
bio: string;
details: Record<string, any>;
profile: Record<string, any>;
id: number;
user_uuid: string;
}
interface Author {
user: User;
authorship: string;
authorship_status: string;
creation_date: string;
update_date: string;
}
interface Course {
name: string;
description: string;
about: string;
learnings: string;
tags: string;
thumbnail_image: string;
public: boolean;
open_to_contributors: boolean;
id: number;
org_id: number;
authors: Author[];
course_uuid: string;
creation_date: string;
update_date: string;
}
interface Collection {
name: string;
public: boolean;
description: string;
id: number;
courses: string[];
collection_uuid: string;
creation_date: string;
update_date: string;
}
interface SearchResults {
courses: Course[];
collections: Collection[];
users: User[];
total_courses: number;
total_collections: number;
total_users: number;
}
type ContentType = 'all' | 'courses' | 'collections' | 'users';
function SearchPage() {
const router = useRouter();
const searchParams = useSearchParams();
const session = useLHSession() as any;
const org = useOrg() as any;
// Search state
const [searchResults, setSearchResults] = useState<SearchResults>({
courses: [],
collections: [],
users: [],
total_courses: 0,
total_collections: 0,
total_users: 0
});
const [isLoading, setIsLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState(searchParams.get('q') || '');
// URL parameters
const query = searchParams.get('q') || '';
const page = parseInt(searchParams.get('page') || '1');
const type = (searchParams.get('type') as ContentType) || 'all';
const perPage = 9;
// Filter state
const [selectedType, setSelectedType] = useState<ContentType>(type);
const updateSearchParams = (updates: Record<string, string>) => {
const current = new URLSearchParams(Array.from(searchParams.entries()));
Object.entries(updates).forEach(([key, value]) => {
if (value) {
current.set(key, value);
} else {
current.delete(key);
}
});
router.push(`?${current.toString()}`);
};
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
if (searchQuery.trim()) {
updateSearchParams({ q: searchQuery, page: '1' });
}
};
useEffect(() => {
setSearchQuery(query);
}, [query]);
useEffect(() => {
const fetchResults = async () => {
if (!query.trim()) {
setSearchResults({
courses: [],
collections: [],
users: [],
total_courses: 0,
total_collections: 0,
total_users: 0
});
return;
}
setIsLoading(true);
try {
const response = await searchOrgContent(
org?.slug,
query,
page,
perPage,
selectedType === 'all' ? null : selectedType,
session?.data?.tokens?.access_token
);
// Log the response to see what we're getting
console.log('Search API Response:', response);
// The response data is directly what we need
const results = response.data;
setSearchResults({
courses: results.courses || [],
collections: results.collections || [],
users: results.users || [],
total_courses: results.courses?.length || 0,
total_collections: results.collections?.length || 0,
total_users: results.users?.length || 0
});
} catch (error) {
console.error('Error searching content:', error);
setSearchResults({
courses: [],
collections: [],
users: [],
total_courses: 0,
total_collections: 0,
total_users: 0
});
}
setIsLoading(false);
};
fetchResults();
}, [query, page, selectedType, org?.slug, session?.data?.tokens?.access_token]);
const totalResults = searchResults.total_courses + searchResults.total_collections + searchResults.total_users;
const totalPages = Math.ceil(totalResults / perPage);
const FilterButton = ({ type, count, icon: Icon }: { type: ContentType; count: number; icon: any }) => (
<button
onClick={() => {
setSelectedType(type);
updateSearchParams({ type: type === 'all' ? '' : type, page: '1' });
}}
className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm transition-colors ${
selectedType === type
? 'bg-black/10 text-black/80 font-medium'
: 'hover:bg-black/5 text-black/60'
}`}
>
<Icon size={16} />
<span>{type.charAt(0).toUpperCase() + type.slice(1)}</span>
<span className="text-black/40">({count})</span>
</button>
);
const Pagination = () => {
if (totalPages <= 1) return null;
return (
<div className="flex justify-center gap-2 mt-8">
{Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNum) => (
<button
key={pageNum}
onClick={() => updateSearchParams({ page: pageNum.toString() })}
className={`w-8 h-8 rounded-lg text-sm transition-colors ${
page === pageNum
? 'bg-black/10 text-black/80 font-medium'
: 'hover:bg-black/5 text-black/60'
}`}
>
{pageNum}
</button>
))}
</div>
);
};
const LoadingState = () => (
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{[1, 2, 3, 4, 5, 6].map((i) => (
<div key={i} className="bg-white rounded-xl nice-shadow p-4 animate-pulse">
<div className="w-full h-32 bg-black/5 rounded-lg mb-4" />
<div className="space-y-2">
<div className="w-3/4 h-4 bg-black/5 rounded" />
<div className="w-1/2 h-3 bg-black/5 rounded" />
</div>
</div>
))}
</div>
);
const EmptyState = () => (
<div className="flex flex-col items-center justify-center py-16 text-center">
<div className="mb-4 p-4 bg-black/5 rounded-full">
<Search className="w-8 h-8 text-black/40" />
</div>
<h3 className="text-lg font-medium text-black/80 mb-2">No results found</h3>
<p className="text-sm text-black/50 max-w-md">
We couldn't find any matches for "{query}". Try adjusting your search terms or browse our featured content.
</p>
</div>
);
return (
<div className="min-h-screen bg-gray-50">
{/* Search Header */}
<div className="bg-white border-b border-black/5">
<div className="container mx-auto px-4 py-6">
<div className="max-w-2xl mx-auto">
<h1 className="text-2xl font-semibold text-black/80 mb-6">Search</h1>
{/* Search Input */}
<form onSubmit={handleSearch} className="relative group mb-6">
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search courses, users, collections..."
className="w-full h-12 pl-12 pr-4 rounded-xl nice-shadow bg-white
focus:outline-none focus:ring-1 focus:ring-black/5 focus:border-black/20
text-sm placeholder:text-black/40 transition-all"
/>
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
<Search className="text-black/40 group-focus-within:text-black/60 transition-colors" size={20} />
</div>
<button
type="submit"
className="absolute inset-y-0 right-0 px-4 flex items-center text-sm text-black/60 hover:text-black/80"
>
Search
</button>
</form>
{/* Filters */}
<div className="flex items-center gap-2 overflow-x-auto pb-2">
<FilterButton type="all" count={totalResults} icon={Search} />
<FilterButton type="courses" count={searchResults.total_courses} icon={GraduationCap} />
<FilterButton type="collections" count={searchResults.total_collections} icon={Book} />
<FilterButton type="users" count={searchResults.total_users} icon={Users} />
</div>
</div>
</div>
</div>
{/* Search Results */}
<div className="container mx-auto px-4 py-8">
<div className="max-w-7xl mx-auto">
{query && (
<div className="text-sm text-black/60 mb-6">
Found {totalResults} results for "{query}"
</div>
)}
{isLoading ? (
<LoadingState />
) : totalResults === 0 && query ? (
<EmptyState />
) : (
<div className="space-y-12">
{/* Courses Grid */}
{(selectedType === 'all' || selectedType === 'courses') && searchResults.courses.length > 0 && (
<div>
<h2 className="text-lg font-medium text-black/80 mb-4 flex items-center gap-2">
<GraduationCap size={20} className="text-black/60" />
Courses ({searchResults.courses.length})
</h2>
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{searchResults.courses.map((course) => (
<Link
key={course.course_uuid}
href={getUriWithOrg(org?.slug, `/course/${removeCoursePrefix(course.course_uuid)}`)}
className="bg-white rounded-xl nice-shadow hover:shadow-md transition-all overflow-hidden group"
>
<div className="relative h-48">
{course.thumbnail_image ? (
<img
src={getCourseThumbnailMediaDirectory(org?.org_uuid, course.course_uuid, course.thumbnail_image)}
alt={course.name}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
/>
) : (
<div className="w-full h-full bg-black/5 flex items-center justify-center">
<GraduationCap size={32} className="text-black/40" />
</div>
)}
</div>
<div className="p-4">
<h3 className="text-sm font-medium text-black/80 mb-1">{course.name}</h3>
<p className="text-xs text-black/50 line-clamp-2">{course.description}</p>
{course.authors && course.authors.length > 0 && (
<div className="flex items-center gap-2 mt-3">
<UserAvatar
width={20}
avatar_url={course.authors[0].user.avatar_image ? getUserAvatarMediaDirectory(course.authors[0].user.user_uuid, course.authors[0].user.avatar_image) : ''}
predefined_avatar={course.authors[0].user.avatar_image ? undefined : 'empty'}
userId={course.authors[0].user.id.toString()}
showProfilePopup={false}
rounded="rounded-full"
backgroundColor="bg-gray-100"
/>
<span className="text-xs text-black/40">
{course.authors[0].user.first_name} {course.authors[0].user.last_name}
</span>
</div>
)}
</div>
</Link>
))}
</div>
</div>
)}
{/* Collections Grid */}
{(selectedType === 'all' || selectedType === 'collections') && searchResults.collections.length > 0 && (
<div>
<h2 className="text-lg font-medium text-black/80 mb-4 flex items-center gap-2">
<Book size={20} className="text-black/60" />
Collections ({searchResults.collections.length})
</h2>
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{searchResults.collections.map((collection) => (
<Link
key={collection.collection_uuid}
href={getUriWithOrg(org?.slug, `/collection/${collection.collection_uuid.replace('collection_', '')}`)}
className="flex items-start gap-4 p-4 bg-white rounded-xl nice-shadow hover:shadow-md transition-all"
>
<div className="w-12 h-12 bg-black/5 rounded-lg flex items-center justify-center flex-shrink-0">
<Book size={24} className="text-black/40" />
</div>
<div>
<h3 className="text-sm font-medium text-black/80 mb-1">{collection.name}</h3>
<p className="text-xs text-black/50 line-clamp-2">{collection.description}</p>
</div>
</Link>
))}
</div>
</div>
)}
{/* Users Grid */}
{(selectedType === 'all' || selectedType === 'users') && searchResults.users.length > 0 && (
<div>
<h2 className="text-lg font-medium text-black/80 mb-4 flex items-center gap-2">
<Users size={20} className="text-black/60" />
Users ({searchResults.users.length})
</h2>
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{searchResults.users.map((user) => (
<Link
key={user.user_uuid}
href={getUriWithOrg(org?.slug, `/user/${user.username}`)}
className="flex items-center gap-4 p-4 bg-white rounded-xl nice-shadow hover:shadow-md transition-all"
>
<UserAvatar
width={48}
avatar_url={user.avatar_image ? getUserAvatarMediaDirectory(user.user_uuid, user.avatar_image) : ''}
predefined_avatar={user.avatar_image ? undefined : 'empty'}
userId={user.id.toString()}
showProfilePopup
rounded="rounded-full"
backgroundColor="bg-gray-100"
/>
<div>
<h3 className="text-sm font-medium text-black/80">
{user.first_name} {user.last_name}
</h3>
<p className="text-xs text-black/50">@{user.username}</p>
{user.details?.title?.text && (
<p className="text-xs text-black/40 mt-1">{user.details.title.text}</p>
)}
</div>
</Link>
))}
</div>
</div>
)}
</div>
)}
<Pagination />
</div>
</div>
</div>
);
}
export default SearchPage;

View file

@ -127,17 +127,25 @@ function ActivityElement(props: ActivitiyElementProps) {
>
{(provided, snapshot) => (
<div
className="flex flex-col sm:flex-row py-2 px-3 my-2 w-full rounded-md bg-gray-50 text-gray-500 hover:bg-gray-100 hover:scale-102 space-y-2 sm:space-y-0 sm:space-x-2 items-center shadow-md border-1 border-gray-200 nice-shadow transition-all duration-200"
className={`grid grid-cols-[auto_1fr_auto] gap-2 py-2 px-3 my-2 w-full rounded-md text-gray-500
${snapshot.isDragging
? 'nice-shadow bg-white ring-2 ring-blue-500/20 z-50 rotate-1 scale-[1.04]'
: 'nice-shadow bg-gray-50 hover:bg-gray-100 '
}
items-center border-1 border-gray-200`}
key={props.activity.id}
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
style={{
...provided.draggableProps.style
}}
>
{/* Activity Type Icon */}
<ActivityTypeIndicator activityType={props.activity.activity_type} isMobile={isMobile} />
{/* Centered Activity Name */}
<div className="grow items-center space-x-2 flex mx-auto justify-center">
<div className="flex items-center space-x-2 justify-center">
{selectedActivity === props.activity.id ? (
<div className="chapter-modification-zone text-[7px] text-gray-600 shadow-inner bg-gray-200/60 py-1 px-4 rounded-lg space-x-3">
<input
@ -179,7 +187,7 @@ function ActivityElement(props: ActivitiyElementProps) {
</div>
{/* Edit, View, Publish, and Delete Buttons */}
<div className="flex flex-wrap justify-center sm:justify-end gap-2 w-full sm:w-auto">
<div className="flex items-center gap-2 justify-end">
<ActivityElementOptions activity={props.activity} isMobile={isMobile} />
{/* Publishing */}
<button

View file

@ -72,7 +72,9 @@ function ChapterElement(props: ChapterElementProps) {
>
{(provided, snapshot) => (
<div
className="mx-2 sm:mx-4 md:mx-6 lg:mx-10 bg-white rounded-xl nice-shadow px-3 sm:px-4 md:px-6 pt-4 sm:pt-6"
className={`mx-2 sm:mx-4 md:mx-6 lg:mx-10 bg-white rounded-xl nice-shadow px-3 sm:px-4 md:px-6 pt-4 sm:pt-6 ${
snapshot.isDragging ? 'shadow-xl ring-2 ring-blue-500/20 rotate-1' : ''
}`}
key={props.chapter.chapter_uuid}
{...provided.draggableProps}
{...provided.dragHandleProps}
@ -149,24 +151,25 @@ function ChapterElement(props: ChapterElementProps) {
droppableId={props.chapter.chapter_uuid}
type="activity"
>
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
<div className="flex flex-col min-h-[60px]">
{activities.map((activity: any, index: any) => {
return (
<div key={activity.activity_uuid} className="flex items-center ">
{(provided, snapshot) => (
<div
{...provided.droppableProps}
ref={provided.innerRef}
className={`min-h-[60px] rounded-lg transition-colors duration-75 ${
snapshot.isDraggingOver ? 'bg-blue-50/50' : ''
}`}
>
{activities.map((activity: any, index: any) => (
<ActivityElement
key={activity.activity_uuid}
orgslug={props.orgslug}
course_uuid={props.course_uuid}
activityIndex={index}
activity={activity}
/>
</div>
)
})}
))}
{provided.placeholder}
</div>
</div>
)}
</Droppable>
<NewActivityButton

View file

@ -75,44 +75,36 @@ const EditCourseStructure = (props: EditCourseStructureProps) => {
destination.index === source.index
)
return
const newCourseStructure = { ...course_structure }
if (type === 'chapter') {
const newChapterOrder = Array.from(course_structure.chapters)
newChapterOrder.splice(source.index, 1)
newChapterOrder.splice(
destination.index,
0,
course_structure.chapters[source.index]
)
dispatchCourse({
type: 'setCourseStructure',
payload: { ...course_structure, chapters: newChapterOrder },
})
dispatchCourse({ type: 'setIsNotSaved' })
const newChapterOrder = Array.from(newCourseStructure.chapters)
const [movedChapter] = newChapterOrder.splice(source.index, 1)
newChapterOrder.splice(destination.index, 0, movedChapter)
newCourseStructure.chapters = newChapterOrder
}
if (type === 'activity') {
const newChapterOrder = Array.from(course_structure.chapters)
const newChapterOrder = Array.from(newCourseStructure.chapters)
const sourceChapter = newChapterOrder.find(
(chapter: any) => chapter.chapter_uuid === source.droppableId
) as any
const destinationChapter = newChapterOrder.find(
(chapter: any) => chapter.chapter_uuid === destination.droppableId
)
? newChapterOrder.find(
(chapter: any) => chapter.chapter_uuid === destination.droppableId
)
: sourceChapter
const activity = sourceChapter.activities.find(
(activity: any) => activity.activity_uuid === draggableId
)
sourceChapter.activities.splice(source.index, 1)
destinationChapter.activities.splice(destination.index, 0, activity)
) ?? sourceChapter
const [movedActivity] = sourceChapter.activities.splice(source.index, 1)
destinationChapter.activities.splice(destination.index, 0, movedActivity)
newCourseStructure.chapters = newChapterOrder
}
dispatchCourse({
type: 'setCourseStructure',
payload: { ...course_structure, chapters: newChapterOrder },
payload: newCourseStructure,
})
dispatchCourse({ type: 'setIsNotSaved' })
}
}
useEffect(() => {
setwinReady(true)
@ -125,10 +117,10 @@ const EditCourseStructure = (props: EditCourseStructureProps) => {
<div className="h-6"></div>
{winReady ? (
<DragDropContext onDragEnd={updateStructure}>
<Droppable type="chapter" droppableId="chapters">
{(provided) => (
<Droppable type="chapter" droppableId="chapters" direction="vertical">
{(provided, snapshot) => (
<div
className="space-y-4"
className={`space-y-4 ${snapshot.isDraggingOver ? 'bg-gray-50/50' : ''}`}
{...provided.droppableProps}
ref={provided.innerRef}
>

View file

@ -1,85 +1,502 @@
import { NodeViewWrapper } from '@tiptap/react'
import { Video } from 'lucide-react'
import React, { useEffect } from 'react'
import styled from 'styled-components'
import { NodeViewProps, NodeViewWrapper } from '@tiptap/react'
import { Node } from '@tiptap/core'
import {
Loader2, Video, Upload, X, HelpCircle,
Maximize2, Minimize2, ArrowLeftRight,
CheckCircle2, AlertCircle
} from 'lucide-react'
import React from 'react'
import { uploadNewVideoFile } from '../../../../../services/blocks/Video/video'
import { getActivityBlockMediaDirectory } from '@services/media/media'
import { useOrg } from '@components/Contexts/OrgContext'
import { useCourse } from '@components/Contexts/CourseContext'
import { useEditorProvider } from '@components/Contexts/Editor/EditorContext'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import { FileUploadBlock, FileUploadBlockButton, FileUploadBlockInput } from '../../FileUploadBlock'
import { constructAcceptValue } from '@/lib/constants';
import { constructAcceptValue } from '@/lib/constants'
import { cn } from '@/lib/utils'
import { motion, AnimatePresence } from 'framer-motion'
import styled from 'styled-components'
const SUPPORTED_FILES = constructAcceptValue(['webm', 'mp4'])
function VideoBlockComponents(props: any) {
const org = useOrg() as any
const course = useCourse() as any
const editorState = useEditorProvider() as any
const isEditable = editorState.isEditable
const [video, setVideo] = React.useState(null)
const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token;
const VIDEO_SIZES = {
small: { width: 480, label: 'Small' },
medium: { width: 720, label: 'Medium' },
large: { width: 960, label: 'Large' },
full: { width: '100%', label: 'Full Width' }
} as const
type VideoSize = keyof typeof VIDEO_SIZES
// Helper function to determine video size from width
const getVideoSizeFromWidth = (width: number | string | undefined): VideoSize => {
if (!width) return 'medium'
if (width === '100%') return 'full'
const numWidth = typeof width === 'string' ? parseInt(width) : width
if (numWidth <= VIDEO_SIZES.small.width) return 'small'
if (numWidth <= VIDEO_SIZES.medium.width) return 'medium'
if (numWidth <= VIDEO_SIZES.large.width) return 'large'
return 'full'
}
const VideoWrapper = styled.div`
transition: all 0.2s ease;
background-color: #f9f9f9;
border: 1px solid #eaeaea;
`
const VideoContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 100%;
`
const UploadZone = styled(motion.div)<{ isDragging: boolean }>`
border: 2px dashed ${props => props.isDragging ? '#3b82f6' : '#e5e7eb'};
background: ${props => props.isDragging ? 'rgba(59, 130, 246, 0.05)' : '#ffffff'};
transition: all 0.2s ease;
border-radius: 0.75rem;
padding: 2rem;
text-align: center;
cursor: pointer;
&:hover {
border-color: #3b82f6;
background: rgba(59, 130, 246, 0.05);
}
`
const SizeButton = styled(motion.button)<{ isActive: boolean }>`
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
border-radius: 0.375rem;
font-size: 0.875rem;
color: ${props => props.isActive ? '#ffffff' : '#4b5563'};
background: ${props => props.isActive ? '#3b82f6' : 'transparent'};
border: 1px solid ${props => props.isActive ? '#3b82f6' : '#e5e7eb'};
transition: all 0.2s ease;
&:hover {
background: ${props => props.isActive ? '#2563eb' : '#f9fafb'};
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
`
interface Organization {
org_uuid: string
}
interface Course {
courseStructure: {
course_uuid: string
}
}
interface EditorState {
isEditable: boolean
}
interface Session {
data?: {
tokens?: {
access_token?: string
}
}
}
// Legacy interface for backward compatibility
interface LegacyVideoBlockObject {
block_uuid: string
content: {
file_id: string
file_format: string
}
size?: {
width?: number | string
}
}
interface VideoBlockObject {
block_uuid: string
content: {
file_id: string
file_format: string
}
size: VideoSize
}
interface VideoBlockAttrs {
blockObject: VideoBlockObject | LegacyVideoBlockObject | null
}
interface VideoBlockExtension {
options: {
activity: {
activity_uuid: string
}
}
}
interface ExtendedNodeViewProps extends Omit<NodeViewProps, 'extension'> {
extension: Node & {
options: {
activity: {
activity_uuid: string
}
}
}
}
function VideoBlockComponent(props: ExtendedNodeViewProps) {
const { node, extension, updateAttributes } = props
const org = useOrg() as Organization | null
const course = useCourse() as Course | null
const editorState = useEditorProvider() as EditorState
const session = useLHSession() as Session
const fileInputRef = React.useRef<HTMLInputElement>(null)
const uploadZoneRef = React.useRef<HTMLDivElement>(null)
// Convert legacy block object to new format
const convertLegacyBlock = React.useCallback((block: LegacyVideoBlockObject): VideoBlockObject => {
const videoSize = getVideoSizeFromWidth(block.size?.width)
return {
...block,
size: videoSize
}
}, [])
const initialBlockObject = React.useMemo(() => {
if (!node.attrs.blockObject) return null
if ('size' in node.attrs.blockObject && typeof node.attrs.blockObject.size === 'string') {
return node.attrs.blockObject as VideoBlockObject
}
return convertLegacyBlock(node.attrs.blockObject as LegacyVideoBlockObject)
}, [node.attrs.blockObject, convertLegacyBlock])
const [video, setVideo] = React.useState<File | null>(null)
const [isLoading, setIsLoading] = React.useState(false)
const [blockObject, setblockObject] = React.useState(
props.node.attrs.blockObject
)
const fileId = blockObject
? `${blockObject.content.file_id}.${blockObject.content.file_format}`
: null
const [error, setError] = React.useState<string | null>(null)
const [isDragging, setIsDragging] = React.useState(false)
const [uploadProgress, setUploadProgress] = React.useState(0)
const [blockObject, setBlockObject] = React.useState<VideoBlockObject | null>(initialBlockObject)
const [selectedSize, setSelectedSize] = React.useState<VideoSize>(initialBlockObject?.size || 'medium')
const handleVideoChange = (event: React.ChangeEvent<any>) => {
setVideo(event.target.files[0])
// Update block object when size changes
React.useEffect(() => {
if (blockObject && blockObject.size !== selectedSize) {
const newBlockObject = {
...blockObject,
size: selectedSize
}
setBlockObject(newBlockObject)
updateAttributes({ blockObject: newBlockObject })
}
}, [selectedSize])
const isEditable = editorState?.isEditable
const access_token = session?.data?.tokens?.access_token
const fileId = blockObject ? `${blockObject.content.file_id}.${blockObject.content.file_format}` : null
const handleVideoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (file) {
setVideo(file)
setError(null)
handleUpload(file)
}
}
const handleSubmit = async (e: any) => {
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault()
setIsLoading(true)
let object = await uploadNewVideoFile(
video,
props.extension.options.activity.activity_uuid, access_token
)
setIsLoading(false)
setblockObject(object)
props.updateAttributes({
blockObject: object,
})
e.stopPropagation()
setIsDragging(true)
}
useEffect(() => { }, [course, org])
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
if (e.currentTarget === uploadZoneRef.current) {
setIsDragging(false)
}
}
console.log(blockObject)
const handleDrop = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(false)
const file = e.dataTransfer.files[0]
if (file && SUPPORTED_FILES.split(',').some(format => file.name.toLowerCase().endsWith(format.trim()))) {
setVideo(file)
setError(null)
handleUpload(file)
} else {
setError('Please upload a supported video format (MP4 or WebM)')
}
}
const handleUpload = async (file: File) => {
if (!access_token) return
try {
setIsLoading(true)
setError(null)
setUploadProgress(0)
// Simulate upload progress
const progressInterval = setInterval(() => {
setUploadProgress(prev => Math.min(prev + 10, 90))
}, 200)
const object = await uploadNewVideoFile(
file,
extension.options.activity.activity_uuid,
access_token
)
clearInterval(progressInterval)
setUploadProgress(100)
const newBlockObject = {
...object,
size: selectedSize
}
setBlockObject(newBlockObject)
updateAttributes({ blockObject: newBlockObject })
setVideo(null)
// Reset progress after a delay
setTimeout(() => {
setUploadProgress(0)
}, 1000)
} catch (err) {
setError('Failed to upload video. Please try again.')
} finally {
setIsLoading(false)
}
}
const handleRemove = () => {
setBlockObject(null)
updateAttributes({ blockObject: null })
setVideo(null)
setError(null)
setUploadProgress(0)
}
const handleSizeChange = (size: VideoSize) => {
setSelectedSize(size)
}
const videoUrl = blockObject && org?.org_uuid && course?.courseStructure.course_uuid ? getActivityBlockMediaDirectory(
org.org_uuid,
course.courseStructure.course_uuid,
extension.options.activity.activity_uuid,
blockObject.block_uuid,
fileId || '',
'videoBlock'
) : null
// If we're in preview mode and have a video, show only the video player
if (!isEditable && blockObject && videoUrl) {
const width = VIDEO_SIZES[blockObject.size].width
return (
<NodeViewWrapper className="block-video">
<FileUploadBlock isEditable={isEditable} isLoading={isLoading} isEmpty={!blockObject} Icon={Video}>
<FileUploadBlockInput onChange={handleVideoChange} accept={SUPPORTED_FILES} />
<FileUploadBlockButton onClick={handleSubmit} disabled={!video}/>
</FileUploadBlock>
{blockObject && (
<BlockVideo>
<NodeViewWrapper className="block-video w-full">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
className="w-full flex justify-center"
>
<div
style={{
maxWidth: typeof width === 'number' ? width : '100%',
width: '100%'
}}
>
<video
controls
className="rounded-lg shadow-sm h-96 w-full object-scale-down bg-black"
src={`${getActivityBlockMediaDirectory(
org?.org_uuid,
course?.courseStructure.course_uuid,
props.extension.options.activity.activity_uuid,
blockObject.block_uuid,
blockObject ? fileId : ' ',
'videoBlock'
)}`}
></video>
</BlockVideo>
)}
className="w-full aspect-video object-contain rounded-lg shadow-sm"
src={videoUrl}
/>
</div>
</motion.div>
</NodeViewWrapper>
)
}
const BlockVideo = styled.div`
display: flex;
flex-direction: column;
`
export default VideoBlockComponents
// If we're in preview mode but don't have a video, show nothing
if (!isEditable && (!blockObject || !videoUrl)) {
return null
}
// Show the full editor UI when in edit mode
return (
<NodeViewWrapper className="block-video w-full">
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<VideoWrapper className="flex flex-col space-y-4 rounded-lg py-6 px-5">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2 text-sm text-zinc-500">
<Video size={16} />
<span className="font-medium">Video Block</span>
</div>
{blockObject && (
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={handleRemove}
className="text-zinc-400 hover:text-red-500 transition-colors"
>
<X size={16} />
</motion.button>
)}
</div>
{(!blockObject || !videoUrl) && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
transition={{ duration: 0.2 }}
className="space-y-4"
>
<input
ref={fileInputRef}
type="file"
onChange={handleVideoChange}
accept={SUPPORTED_FILES}
className="hidden"
/>
<UploadZone
ref={uploadZoneRef}
isDragging={isDragging}
onDragEnter={handleDragEnter}
onDragOver={handleDragEnter}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={() => fileInputRef.current?.click()}
className="relative"
>
<AnimatePresence>
{isLoading ? (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="space-y-3"
>
<Loader2 className="w-8 h-8 animate-spin mx-auto text-blue-500" />
<div className="text-sm text-zinc-600">Uploading video... {uploadProgress}%</div>
<div className="w-48 h-1 bg-gray-200 rounded-full mx-auto overflow-hidden">
<motion.div
className="h-full bg-blue-500 rounded-full"
initial={{ width: 0 }}
animate={{ width: `${uploadProgress}%` }}
transition={{ duration: 0.2 }}
/>
</div>
</motion.div>
) : (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="space-y-3"
>
<Upload className="w-8 h-8 mx-auto text-blue-500" />
<div>
<div className="text-sm font-medium text-zinc-700">
Drop your video here or click to browse
</div>
<div className="text-xs text-zinc-500 mt-1">
Supports MP4 and WebM formats
</div>
</div>
</motion.div>
)}
</AnimatePresence>
</UploadZone>
{error && (
<div className="flex items-center gap-2 text-sm text-red-500 font-medium bg-red-50 rounded-lg p-3">
<AlertCircle size={16} />
{error}
</div>
)}
</motion.div>
)}
{blockObject && videoUrl && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
className="space-y-4"
>
<div className="flex items-center gap-2 flex-wrap">
<div className="text-sm text-zinc-500 font-medium flex items-center gap-1">
<ArrowLeftRight size={14} />
Video Size:
</div>
{(Object.keys(VIDEO_SIZES) as VideoSize[]).map((size) => (
<SizeButton
key={size}
isActive={selectedSize === size}
onClick={() => handleSizeChange(size)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
{size === selectedSize && <CheckCircle2 size={14} />}
{VIDEO_SIZES[size].label}
</SizeButton>
))}
</div>
<VideoContainer>
<div
style={{
maxWidth: typeof VIDEO_SIZES[selectedSize].width === 'number'
? VIDEO_SIZES[selectedSize].width
: '100%',
width: '100%'
}}
>
<div className="relative rounded-lg overflow-hidden bg-black/5">
{isLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-black/10 backdrop-blur-sm">
<Loader2 className="w-8 h-8 animate-spin text-white" />
</div>
)}
<video
controls
className={cn(
"w-full aspect-video object-contain bg-black/95 shadow-sm transition-all duration-200",
isLoading && "opacity-50 blur-sm"
)}
src={videoUrl}
/>
</div>
</div>
</VideoContainer>
</motion.div>
)}
</VideoWrapper>
</motion.div>
</NodeViewWrapper>
)
}
export default VideoBlockComponent

View file

@ -116,14 +116,24 @@ export const ToolbarButtons = ({ editor, props }: any) => {
<ListBulletIcon />
</ToolBtn>
<ToolSelect
onChange={(e) =>
editor
.chain()
.focus()
.toggleHeading({ level: parseInt(e.target.value) })
.run()
value={
editor.isActive('heading', { level: 1 }) ? "1" :
editor.isActive('heading', { level: 2 }) ? "2" :
editor.isActive('heading', { level: 3 }) ? "3" :
editor.isActive('heading', { level: 4 }) ? "4" :
editor.isActive('heading', { level: 5 }) ? "5" :
editor.isActive('heading', { level: 6 }) ? "6" : "0"
}
onChange={(e) => {
const value = e.target.value;
if (value === "0") {
editor.chain().focus().setParagraph().run();
} else {
editor.chain().focus().toggleHeading({ level: parseInt(value) }).run();
}
}}
>
<option value="0">Paragraph</option>
<option value="1">Heading 1</option>
<option value="2">Heading 2</option>
<option value="3">Heading 3</option>
@ -351,13 +361,31 @@ const ToolSelect = styled.select`
display: flex;
background: rgba(217, 217, 217, 0.185);
border-radius: 6px;
width: 100px;
width: 120px;
border: none;
height: 25px;
padding: 5px;
padding: 2px 5px;
font-size: 11px;
font-family: 'DM Sans';
margin-right: 5px;
cursor: pointer;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
background-repeat: no-repeat;
background-position: right 5px center;
background-size: 12px;
padding-right: 20px;
&:hover {
background-color: rgba(217, 217, 217, 0.3);
}
&:focus {
outline: none;
box-shadow: 0 0 0 2px rgba(217, 217, 217, 0.5);
}
`
const TableMenuWrapper = styled.div`

View file

@ -238,42 +238,6 @@ export const SearchBar: React.FC<SearchBarProps> = ({
<span className="font-medium">Quick Results</span>
</div>
{/* Users Section */}
{searchResults.users.length > 0 && (
<div className="mb-2">
<div className="flex items-center gap-2 px-2 py-1 text-xs text-black/40">
<Users size={12} />
<span>Users</span>
</div>
{searchResults.users.map((user) => (
<Link
key={user.user_uuid}
href={getUriWithOrg(orgslug, `/user/${user.username}`)}
className="flex items-center gap-3 p-2 hover:bg-black/[0.02] rounded-lg transition-colors"
>
<UserAvatar
width={40}
avatar_url={user.avatar_image ? getUserAvatarMediaDirectory(user.user_uuid, user.avatar_image) : ''}
predefined_avatar={user.avatar_image ? undefined : 'empty'}
userId={user.id.toString()}
showProfilePopup
rounded="rounded-full"
backgroundColor="bg-gray-100"
/>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<h3 className="text-sm font-medium text-black/80 truncate">
{user.first_name} {user.last_name}
</h3>
<span className="text-[10px] font-medium text-black/40 uppercase tracking-wide whitespace-nowrap">User</span>
</div>
<p className="text-xs text-black/50 truncate">@{user.username}</p>
</div>
</Link>
))}
</div>
)}
{/* Courses Section */}
{searchResults.courses.length > 0 && (
<div className="mb-2">
@ -342,6 +306,42 @@ export const SearchBar: React.FC<SearchBarProps> = ({
))}
</div>
)}
{/* Users Section */}
{searchResults.users.length > 0 && (
<div className="mb-2">
<div className="flex items-center gap-2 px-2 py-1 text-xs text-black/40">
<Users size={12} />
<span>Users</span>
</div>
{searchResults.users.map((user) => (
<Link
key={user.user_uuid}
href={getUriWithOrg(orgslug, `/user/${user.username}`)}
className="flex items-center gap-3 p-2 hover:bg-black/[0.02] rounded-lg transition-colors"
>
<UserAvatar
width={40}
avatar_url={user.avatar_image ? getUserAvatarMediaDirectory(user.user_uuid, user.avatar_image) : ''}
predefined_avatar={user.avatar_image ? undefined : 'empty'}
userId={user.id.toString()}
showProfilePopup
rounded="rounded-full"
backgroundColor="bg-gray-100"
/>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<h3 className="text-sm font-medium text-black/80 truncate">
{user.first_name} {user.last_name}
</h3>
<span className="text-[10px] font-medium text-black/40 uppercase tracking-wide whitespace-nowrap">User</span>
</div>
<p className="text-xs text-black/50 truncate">@{user.username}</p>
</div>
</Link>
))}
</div>
)}
</div>
);
}, [searchResults, orgslug, org?.org_uuid]);

View file

@ -113,6 +113,10 @@ layer(base);
text-decoration: none;
}
button {
@apply cursor-pointer;
}
* {
box-sizing: border-box;
}