Files
classroomio/apps/dashboard/src/routes/lms/community/[slug]/+page.svelte
T

554 lines
16 KiB
Svelte
Raw Normal View History

<script lang="ts">
2025-11-01 15:49:29 +01:00
import { untrack } from 'svelte';
import pluralize from 'pluralize';
import { goto } from '$app/navigation';
import * as Select from '@cio/ui/base/select';
import { Skeleton } from '@cio/ui/base/skeleton';
import TrashIcon from '@lucide/svelte/icons/trash';
import type { Course } from '$lib/utils/types';
import { profile } from '$lib/utils/store/user';
2024-05-22 05:49:10 +01:00
import { t } from '$lib/utils/functions/translations';
import { courses } from '$features/course/utils/store';
import { calDateDiff } from '$lib/utils/functions/date';
import { supabase } from '$lib/utils/functions/supabase';
import { snackbar } from '$features/ui/snackbar/store';
import { fetchCourses } from '$lib/utils/services/courses';
import { currentOrg, isOrgAdmin } from '$lib/utils/store/org';
import { Button } from '@cio/ui/base/button';
import { askCommunityValidation, commentInCommunityValidation } from '$lib/utils/functions/validator';
2023-08-17 14:05:01 +01:00
import { Vote } from '$features/ui';
import { IconButton } from '@cio/ui/custom/icon-button';
2025-12-02 15:27:41 +01:00
import * as Avatar from '@cio/ui/base/avatar';
import { InputField } from '@cio/ui/custom/input-field';
2025-12-02 15:27:41 +01:00
import { shortenName } from '$lib/utils/functions/string';
import { TextEditor } from '$features/ui';
import { CircleCheckIcon } from '$features/ui/icons';
import { CommunityDeleteModal } from '$features/community/components';
import { currentCommunityQuestion } from '$features/community/utils/store';
import * as Page from '@cio/ui/base/page';
2023-08-17 14:05:01 +01:00
interface Comment {
id: string;
authorId: string;
name: string;
avatar: string;
votes: number;
comment: string;
createdAt: string;
}
interface Question {
id: string;
title: string;
votes: number;
author: {
id: string;
name: string;
avatar: string;
};
body: string;
createdAt: string;
comments: Comment[];
totalComments: number;
courseId: string;
}
let { data } = $props();
const { slug } = data;
2025-11-01 15:49:29 +01:00
let question: Question | undefined = $state();
let comment = $state('');
let errors: {
title?: string;
courseId?: string;
2025-11-01 15:49:29 +01:00
} = $state({});
2023-08-17 14:05:01 +01:00
let isValidAnswer = false; // V2 allow admin mark an answer as accepted
let voted: {
question: boolean;
comment: {
[key: string]: boolean;
};
2025-11-01 15:49:29 +01:00
} = $state({ question: false, comment: {} });
let isEditMode = $state(false);
let deleteComment = $state({
2023-08-17 14:05:01 +01:00
shouldDelete: false,
commentId: '',
isDeleting: false
2025-11-01 15:49:29 +01:00
});
let deleteQuestion = $state({
shouldDelete: false,
questionId: '',
isDeleting: false
2025-11-01 15:49:29 +01:00
});
let editContent = $state({
2023-08-17 14:05:01 +01:00
title: '',
body: '',
courseId: ''
2025-11-01 15:49:29 +01:00
});
2023-08-17 14:05:01 +01:00
2025-11-01 15:49:29 +01:00
let editorInstance = $state(false);
let fetchedCourses: Course[] = $state([]);
2023-09-05 13:21:44 +00:00
function mapResToQuestion(data): Question {
2023-08-17 14:05:01 +01:00
return {
id: data.id,
title: data.title,
votes: data.votes,
author: {
id: data?.author?.id || '',
name: data?.author?.fullname || '',
avatar: data?.author?.avatar_url || ''
2023-08-17 14:05:01 +01:00
},
body: data.body,
createdAt: calDateDiff(data.created_at),
2023-08-17 14:05:01 +01:00
comments: data.comments.map((c) => ({
id: c.id,
authorId: c.author?.id || '',
name: c.author?.fullname || '',
avatar: c.author?.avatar_url || '',
2023-08-17 14:05:01 +01:00
votes: c.votes,
comment: c.body,
createdAt: calDateDiff(c.created_at)
2023-08-17 14:05:01 +01:00
})),
totalComments: 0,
courseId: data.course_id
2023-08-17 14:05:01 +01:00
};
}
async function getCourses(userId: string | null, orgId: string) {
2024-05-22 05:49:10 +01:00
if ($courses.length) {
fetchedCourses = [...$courses];
return;
}
const coursesResults = await fetchCourses(userId, orgId);
2024-05-22 05:49:10 +01:00
fetchedCourses = coursesResults?.allCourses || [];
}
async function fetchCommunityQuestion(slug: string) {
2023-08-17 14:05:01 +01:00
if (!slug) return;
const { data, error } = await supabase
.from('community_question')
.select(
`
id,
title,
body,
votes,
created_at,
course_id,
slug,
2023-08-17 14:05:01 +01:00
comments:community_answer(
id,
body,
votes,
created_at,
author:profile(id, fullname, avatar_url)
2023-08-17 14:05:01 +01:00
),
author:profile(id, fullname, avatar_url),
course!inner (
title
)
2023-08-17 14:05:01 +01:00
`
)
.eq('slug', slug)
.single();
if (error) {
console.error('[LMS] Error loading community', error);
return goto(`/lms`);
2023-08-17 14:05:01 +01:00
}
2025-11-01 15:49:29 +01:00
untrack(() => {
question = mapResToQuestion(data);
question.totalComments = question.comments.length;
// Update store for breadcrumb
currentCommunityQuestion.set({ title: question.title });
2025-11-01 15:49:29 +01:00
});
2023-08-17 14:05:01 +01:00
}
async function submitComment() {
2025-11-01 15:49:29 +01:00
if (!question) return;
2023-08-17 14:05:01 +01:00
errors = commentInCommunityValidation({ comment });
console.log('submitComment errors', errors);
if (Object.keys(errors).length) {
return;
}
const { data, error } = await supabase
.from('community_answer')
.insert({
id: undefined,
body: comment,
question_id: question.id,
author_profile_id: $profile.id,
2023-08-17 14:05:01 +01:00
votes: 0
})
.select();
if (error) {
console.error('Error: commenting', error);
2024-04-19 05:45:48 +01:00
snackbar.error('snackbar.community.error.try_again');
2023-08-17 14:05:01 +01:00
} else {
console.log('Success: commenting', data);
2024-04-19 05:45:48 +01:00
snackbar.success('snackbar.community.success.comment_submitted');
2023-08-17 14:05:01 +01:00
// Add to comment
const _c = data?.[0];
question.comments = [
...question.comments,
{
id: _c.id,
authorId: $profile.id || '',
2023-08-17 14:05:01 +01:00
name: $profile?.fullname || '',
avatar: $profile?.avatarUrl || '',
2023-08-17 14:05:01 +01:00
votes: 0,
comment: _c.body,
createdAt: calDateDiff(_c.created_at)
2023-08-17 14:05:01 +01:00
}
];
// Reset input
comment = '';
}
}
async function upvoteQuestion(type: string, commentId?: string) {
2025-11-01 15:49:29 +01:00
if (!question) return;
2023-08-17 14:05:01 +01:00
const isQuestion = type === 'question';
if (isQuestion && voted.question) return;
if (!isQuestion && commentId && voted.comment[commentId]) return;
2023-08-17 14:05:01 +01:00
const table = isQuestion ? 'community_question' : 'community_answer';
const matchId = isQuestion ? question.id : commentId;
let votes = 0;
if (isQuestion) {
question.votes = question.votes + 1;
votes = question.votes;
} else {
question.comments = question.comments.map((c) => {
if (c.id === commentId) {
c.votes = c.votes + 1;
votes = c.votes;
}
return c;
});
}
const { error } = await supabase.from(table).update({ votes }).match({ id: matchId });
if (error) {
console.error('Error: upvoteQuestion', error);
2024-04-19 05:45:48 +01:00
snackbar.error('snackbar.community.error.try_again');
2023-08-17 14:05:01 +01:00
} else {
if (isQuestion) {
voted.question = true;
} else if (commentId) {
2023-08-17 14:05:01 +01:00
voted.comment[commentId] = true;
}
}
}
async function handleQuestionEdit() {
2025-11-01 15:49:29 +01:00
if (!question) return;
2023-08-17 14:05:01 +01:00
if (isEditMode) {
errors = askCommunityValidation(editContent);
2023-08-17 14:05:01 +01:00
console.log('handleQuestionEdit errors', errors);
if (Object.keys(errors).length) {
return;
}
}
isEditMode = !isEditMode;
2023-09-05 13:21:44 +00:00
editorInstance = !editorInstance;
2023-08-17 14:05:01 +01:00
if (!isEditMode) {
errors = askCommunityValidation(editContent);
2023-08-17 14:05:01 +01:00
console.log('handleQuestionEdit errors', errors);
if (Object.keys(errors).length) {
return;
}
const { error } = await supabase
.from('community_question')
.update({
2024-04-19 05:45:48 +01:00
title: editContent.title,
body: editContent.body,
course_id: editContent.courseId
})
2023-08-17 14:05:01 +01:00
.match({ id: question.id });
if (error) {
console.error('Error: handleQuestionEdit', error);
2024-04-19 05:45:48 +01:00
snackbar.error('snackbar.community.error.try_again');
2023-08-17 14:05:01 +01:00
} else {
question.title = editContent.title;
question.body = editContent.body;
question.courseId = editContent.courseId;
2023-08-17 14:05:01 +01:00
editContent.title = '';
editContent.body = '';
editContent.courseId = '';
2023-08-17 14:05:01 +01:00
}
} else {
editContent.title = question.title;
editContent.body = question.body;
editContent.courseId = question.courseId;
2023-08-17 14:05:01 +01:00
}
}
async function handleDelete(isQuestion: boolean) {
2025-11-01 15:49:29 +01:00
if (!question) return;
if (!isQuestion) {
deleteComment.isDeleting = true;
2025-11-01 15:49:29 +01:00
const { error } = await supabase.from('community_answer').delete().match({ id: deleteComment.commentId });
deleteComment.isDeleting = false;
if (error) {
2024-04-19 05:45:48 +01:00
snackbar.error('snackbar.community.error.deleting_comments');
console.log('Error deleting comments', error);
return;
}
2024-04-19 05:45:48 +01:00
snackbar.success('snackbar.community.success.success_delete');
question.comments = question.comments.filter((c) => c.id !== deleteComment.commentId);
deleteComment.shouldDelete = false;
deleteComment.commentId = '';
// Handle only delete comment
return;
}
deleteQuestion.isDeleting = true;
const { error: commentDeleteError } = await supabase
2023-08-17 14:05:01 +01:00
.from('community_answer')
.delete()
.match({ question_id: deleteQuestion.questionId });
2023-08-17 14:05:01 +01:00
if (commentDeleteError) {
2024-04-19 05:45:48 +01:00
snackbar.error('snackbar.community.error.deleting_comments');
console.log('Error deleting comments', commentDeleteError);
deleteQuestion.isDeleting = false;
return;
2023-08-17 14:05:01 +01:00
}
const { error: questionDeleteError } = await supabase
.from('community_question')
.delete()
.match({ id: deleteQuestion.questionId });
if (questionDeleteError) {
2024-04-19 05:45:48 +01:00
snackbar.error('snackbar.community.error.deleting_question');
console.log('Error deleting question', questionDeleteError);
return;
}
2024-04-19 05:45:48 +01:00
snackbar.success('snackbar.community.success.success_delete');
goto(`/lms/community`);
deleteQuestion.isDeleting = false;
2023-08-17 14:05:01 +01:00
}
2025-11-01 15:49:29 +01:00
$effect(() => {
fetchCommunityQuestion(slug);
});
$effect(() => {
if ($profile.id && $currentOrg.id) {
getCourses($profile.id, $currentOrg.id);
}
2025-11-01 15:49:29 +01:00
});
// Clear store when component unmounts
$effect(() => {
return () => {
currentCommunityQuestion.set({ title: null });
};
});
2023-08-17 14:05:01 +01:00
</script>
<svelte:head>
<title>{question?.title || 'Question'}</title>
</svelte:head>
<CommunityDeleteModal
bind:open={deleteQuestion.shouldDelete}
2025-11-01 15:49:29 +01:00
isDeleting={deleteQuestion.isDeleting}
onCancel={() => {
deleteQuestion.shouldDelete = false;
deleteQuestion.questionId = '';
}}
onDelete={() => handleDelete(true)}
isQuestion={true}
/>
{#if !question}
<div class="mb-3 px-5 py-10">
<Skeleton class="h-4 w-[25%]" />
<Skeleton class="mb-2 h-4 w-full" />
<Skeleton class="h-80 w-full" />
</div>
{:else}
{@const currentQuestion = question}
<Page.Root class="mx-auto max-w-3xl md:mx-10 lg:mb-20">
<Page.Header>
<Page.HeaderContent>
2023-08-17 14:05:01 +01:00
{#if isEditMode}
<div class="flex w-full items-center gap-2">
<InputField bind:value={editContent.title} className="flex-1" errorMessage={errors.title} />
<Select.Root type="single" bind:value={editContent.courseId}>
<Select.Trigger class="h-full w-[25%]">
<p>
{editContent.courseId
? fetchedCourses.find((course) => course.id === editContent.courseId)?.title
: $t('community.ask.select_course')}
2023-08-17 14:05:01 +01:00
</p>
</Select.Trigger>
<Select.Content>
{#each fetchedCourses as course}
{#if course.id}
<Select.Item value={course.id}>{course.title}</Select.Item>
{/if}
{/each}
</Select.Content>
</Select.Root>
</div>
{:else}
<div class="flex items-center gap-2">
<Vote value={currentQuestion.votes} upVote={() => upvoteQuestion('question')} disabled={voted.question} />
<Page.Title>{currentQuestion.title}</Page.Title>
</div>
{/if}
</Page.HeaderContent>
{#if currentQuestion.author.id === $profile.id}
<Page.Action>
<Button variant="outline" onclick={handleQuestionEdit}>
{isEditMode ? $t('community.ask.save') : $t('community.ask.edit')}
</Button>
{#if isEditMode}
<Button variant="ghost" onclick={() => (isEditMode = !isEditMode)}>
{$t('community.ask.cancel')}
</Button>
{/if}
</Page.Action>
{/if}
</Page.Header>
<Page.Body>
{#snippet child()}
<div class="border-gray my-1 rounded-lg border px-1">
<header class="flex items-center justify-between p-2 leading-none">
<div class="flex items-center text-black no-underline hover:underline">
<Avatar.Root class="h-7 w-7">
<Avatar.Image
src={currentQuestion.author.avatar ? currentQuestion.author.avatar : '/logo-192.png'}
alt={currentQuestion.author.name ? currentQuestion.author.name : 'User'}
/>
<Avatar.Fallback>{shortenName(currentQuestion.author.name) || 'U'}</Avatar.Fallback>
</Avatar.Root>
<p class="ml-2 text-sm dark:text-white">{currentQuestion.author.name}</p>
<p class="ml-2 text-sm text-gray-500 dark:text-white">
{currentQuestion.createdAt}
</p>
</div>
{#if currentQuestion.author.id === $profile.id || $isOrgAdmin}
<IconButton
onclick={() => {
deleteQuestion.shouldDelete = true;
deleteQuestion.questionId = currentQuestion.id;
}}
>
<TrashIcon size={16} />
</IconButton>
{/if}
</header>
{#if isEditMode && editorInstance}
<div class="my-2">
<TextEditor
placeholder="Give an answer"
content={editContent.body}
onChange={(content) => (editContent.body = content)}
/>
</div>
{:else}
<section class="prose prose-sm sm:prose p-2">
{@html currentQuestion.body}
</section>
{/if}
</div>
2023-08-17 14:05:01 +01:00
<div class="my-8">
{pluralize($t('community.answers'), currentQuestion.totalComments, true)}
</div>
2023-08-17 14:05:01 +01:00
{#each currentQuestion.comments as comment}
<div class="my-5 flex items-start px-1">
<Vote
value={comment.votes}
upVote={() => upvoteQuestion('comment', comment.id)}
disabled={voted.comment[comment.id]}
/>
<div class="border-gray w-full rounded-lg border">
<header class="flex items-center justify-between p-2 leading-none">
<div class="flex items-center text-black">
<Avatar.Root class="h-7 w-7">
<Avatar.Image
src={comment.avatar ? comment.avatar : '/logo-192.png'}
alt={comment.name ? comment.name : 'User'}
/>
<Avatar.Fallback>{shortenName(comment.name) || 'U'}</Avatar.Fallback>
</Avatar.Root>
<p class="ml-2 text-sm dark:text-white">{comment.name}</p>
<p class="ml-2 text-sm text-gray-500 dark:text-white">
{comment.createdAt}
</p>
</div>
{#if isValidAnswer}
<CircleCheckIcon size={16} />
{/if}
{#if comment.authorId === $profile.id || $isOrgAdmin}
<IconButton
onclick={() => {
deleteComment.shouldDelete = true;
deleteComment.commentId = comment.id;
}}
>
<TrashIcon size={16} />
</IconButton>
{/if}
</header>
<article class="prose prose-sm sm:prose p-2">
{@html comment.comment}
</article>
</div>
</div>
{/each}
<hr />
<div class="mt-4">
{#if !editorInstance}
<TextEditor placeholder="Give an answer" content={comment} onChange={(content) => (comment = content)} />
{/if}
<div class="mt-2 flex justify-end">
<Button onclick={submitComment}>
{$t('community.ask.comment')}
</Button>
2023-08-17 14:05:01 +01:00
</div>
</div>
{/snippet}
</Page.Body>
</Page.Root>
{/if}