feat: add reviews, notifications, notes and account hardening
This commit is contained in:
137
components/course/CourseReviews.tsx
Normal file
137
components/course/CourseReviews.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { StarIcon } from '@phosphor-icons/react';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
import { useToast } from '../../context/ToastContext';
|
||||
import { CourseReviewSummary, MyCourseReview, deleteMyCourseReview, getCourseReviews, getMyCourseReview, saveCourseReview } from '../../services/db';
|
||||
import { ConfirmDialog } from '../ui/ConfirmDialog';
|
||||
import { shortDate } from '../../lib/format';
|
||||
import { paths } from '../../lib/routes';
|
||||
|
||||
const Stars: React.FC<{ value: number; label?: string }> = ({ value, label }) => (
|
||||
<span className="review-stars" role="img" aria-label={label || `${value} de 5 estrelas`}>
|
||||
{[1, 2, 3, 4, 5].map((star) => <StarIcon key={star} weight={star <= Math.round(value) ? 'fill' : 'regular'} />)}
|
||||
</span>
|
||||
);
|
||||
|
||||
export const CourseReviews: React.FC<{ courseId: string }> = ({ courseId }) => {
|
||||
const { user } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const [summary, setSummary] = useState<CourseReviewSummary | null>(null);
|
||||
const [mine, setMine] = useState<MyCourseReview | null>(null);
|
||||
const [rating, setRating] = useState(0);
|
||||
const [comment, setComment] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [publicReviews, myReview] = await Promise.all([
|
||||
getCourseReviews(courseId),
|
||||
user ? getMyCourseReview(courseId).catch(() => null) : Promise.resolve(null),
|
||||
]);
|
||||
setSummary(publicReviews);
|
||||
setMine(myReview);
|
||||
setRating(myReview?.rating ?? 0);
|
||||
setComment(myReview?.comment ?? '');
|
||||
} catch {
|
||||
setSummary(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [courseId, user?.id]);
|
||||
|
||||
const submit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!rating) {
|
||||
showToast('Escolha uma nota de 1 a 5 estrelas.', 'error');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await saveCourseReview(courseId, rating, comment.trim());
|
||||
setMine(result.review);
|
||||
setSummary(result.summary);
|
||||
setRating(result.review.rating);
|
||||
setComment(result.review.comment);
|
||||
showToast('Avaliação salva.', 'success');
|
||||
} catch {
|
||||
showToast('Não foi possível salvar sua avaliação.', 'error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
setDeleteOpen(false);
|
||||
try {
|
||||
await deleteMyCourseReview(courseId);
|
||||
setMine(null);
|
||||
setRating(0);
|
||||
setComment('');
|
||||
setSummary(await getCourseReviews(courseId));
|
||||
showToast('Avaliação removida.', 'success');
|
||||
} catch {
|
||||
showToast('Não foi possível remover sua avaliação.', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const average = summary?.average ?? 0;
|
||||
const count = summary?.count ?? 0;
|
||||
|
||||
return <section className="reviews">
|
||||
<header className="reviews-header">
|
||||
<h2>Avaliações</h2>
|
||||
{count > 0 && <span className="count num">{count} {count === 1 ? 'avaliação' : 'avaliações'}</span>}
|
||||
</header>
|
||||
|
||||
{loading ? <p className="muted">Carregando avaliações…</p> : <>
|
||||
<div className="reviews-layout">
|
||||
<div className="box review-summary">
|
||||
<b className="review-average num">{count ? average.toFixed(1) : '—'}</b>
|
||||
<Stars value={average} label={count ? `Média ${average.toFixed(1)} de 5` : 'Sem avaliações'} />
|
||||
<small>{count ? `${count} ${count === 1 ? 'pessoa avaliou' : 'pessoas avaliaram'}` : 'Seja a primeira pessoa a avaliar'}</small>
|
||||
</div>
|
||||
|
||||
{user ? <form className="box review-form" onSubmit={submit}>
|
||||
<div>
|
||||
<span className="review-form-label">{mine ? 'Sua avaliação' : 'Avalie este curso'}</span>
|
||||
<div className="review-rating" role="group" aria-label="Escolha sua nota">
|
||||
{[1, 2, 3, 4, 5].map((star) => <button key={star} type="button" aria-label={`${star} ${star === 1 ? 'estrela' : 'estrelas'}`} aria-pressed={rating === star} onClick={() => setRating(star)}><StarIcon weight={star <= rating ? 'fill' : 'regular'} /></button>)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor={`review-comment-${courseId}`}>Comentário <span className="faint">(opcional)</span></label>
|
||||
<textarea id={`review-comment-${courseId}`} value={comment} onChange={(event) => setComment(event.target.value)} maxLength={2000} placeholder="Conte o que você achou do curso…" />
|
||||
</div>
|
||||
<div className="review-actions">
|
||||
<button className="btn" type="submit" disabled={saving}>{saving ? 'Salvando…' : mine ? 'Atualizar avaliação' : 'Publicar avaliação'}</button>
|
||||
{mine && <button className="link bad-text" type="button" onClick={() => setDeleteOpen(true)}>Remover minha avaliação</button>}
|
||||
</div>
|
||||
</form> : <div className="box review-signin">
|
||||
<b>Gostou do curso?</b>
|
||||
<p className="small">Entre na sua conta para avaliar e ajudar outras pessoas.</p>
|
||||
<Link className="btn sec" to={paths.signIn}>Entrar para avaliar</Link>
|
||||
</div>}
|
||||
</div>
|
||||
|
||||
{summary?.reviews.length ? <div className="review-list">
|
||||
{summary.reviews.map((review) => <article className="review-item" key={`${review.userName}-${review.updatedAt}`}>
|
||||
<header>
|
||||
<div><b>{review.userName}</b><Stars value={review.rating} /></div>
|
||||
<small>{shortDate(review.updatedAt)}</small>
|
||||
</header>
|
||||
{review.comment && <p>{review.comment}</p>}
|
||||
</article>)}
|
||||
</div> : <p className="empty">Nenhuma avaliação publicada ainda.</p>}
|
||||
</>}
|
||||
|
||||
<ConfirmDialog open={deleteOpen} title="Remover avaliação" message="Sua avaliação será removida permanentemente." confirmLabel="Remover avaliação" onCancel={() => setDeleteOpen(false)} onConfirm={() => void remove()} />
|
||||
</section>;
|
||||
};
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
MoonMockIcon, PathMockIcon, SearchMockIcon, SignOutMockIcon, SunMockIcon, TeacherMockIcon,
|
||||
TrayMockIcon, UserMockIcon, VideoMockIcon,
|
||||
} from '../ui/MockupIcons';
|
||||
import { SidebarSimpleIcon } from '@phosphor-icons/react';
|
||||
import { BellIcon, SidebarSimpleIcon } from '@phosphor-icons/react';
|
||||
import { Logo } from '../Logo';
|
||||
import { Avatar } from '../ui/Avatar';
|
||||
import { useAuth } from '../../context/AuthContext';
|
||||
@@ -15,6 +15,7 @@ import { useCatalog } from '../../context/CatalogContext';
|
||||
import { NavKey, navKeyFor } from '../../lib/navigation';
|
||||
import { paths } from '../../lib/routes';
|
||||
import { readPreference, writePreference } from '../../lib/storage';
|
||||
import { getNotifications } from '../../services/notifications';
|
||||
|
||||
const GROUPS_KEY = 'ca-groups';
|
||||
const COLLAPSED_KEY = 'ca-side';
|
||||
@@ -47,6 +48,7 @@ export const Sidebar: React.FC = () => {
|
||||
const [shut, setShut] = useState<Record<string, boolean>>(readGroups);
|
||||
const [collapsed, setCollapsed] = useState(() => readPreference(COLLAPSED_KEY) === '1');
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [unreadNotifications, setUnreadNotifications] = useState(0);
|
||||
const whoRef = useRef<HTMLButtonElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const [menuStyle, setMenuStyle] = useState<React.CSSProperties>({});
|
||||
@@ -60,6 +62,20 @@ export const Sidebar: React.FC = () => {
|
||||
|
||||
useEffect(() => setMenuOpen(false), [location.pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) { setUnreadNotifications(0); return; }
|
||||
let cancelled = false;
|
||||
const refresh = () => {
|
||||
getNotifications().then((feed) => { if (!cancelled) setUnreadNotifications(feed.unread); }).catch(() => undefined);
|
||||
};
|
||||
refresh();
|
||||
window.addEventListener('compor:notifications-updated', refresh);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener('compor:notifications-updated', refresh);
|
||||
};
|
||||
}, [user?.id, location.pathname]);
|
||||
|
||||
// The account menu lives on <body> with position: fixed, so the sidebar never clips it.
|
||||
useLayoutEffect(() => {
|
||||
if (!menuOpen || !whoRef.current) return;
|
||||
@@ -131,6 +147,10 @@ export const Sidebar: React.FC = () => {
|
||||
<button type="button" className="iconbtn" onClick={toggleCollapsed} aria-label={collapsed ? 'Expandir barra lateral' : 'Recolher barra lateral'} title={collapsed ? 'Expandir barra lateral' : 'Recolher barra lateral'}>
|
||||
<SidebarSimpleIcon className="ph" />
|
||||
</button>
|
||||
{user && <Link className="iconbtn notif" to={paths.notifications} aria-label={`Notificações${unreadNotifications ? `, ${unreadNotifications} não lidas` : ''}`} title="Notificações">
|
||||
<BellIcon className="ph" />
|
||||
{unreadNotifications > 0 && <span className="notif-badge">{unreadNotifications > 9 ? '9+' : unreadNotifications}</span>}
|
||||
</Link>}
|
||||
</div>
|
||||
<Link to={paths.explore} className="logo" aria-label="Compor Academy, início">
|
||||
<Logo width={96} />
|
||||
|
||||
31
components/ui/ErrorBoundary.tsx
Normal file
31
components/ui/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import React, { ReactNode } from 'react';
|
||||
|
||||
interface ErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends React.Component<{ children: ReactNode }, ErrorBoundaryState> {
|
||||
declare props: Readonly<{ children: ReactNode }>;
|
||||
state: ErrorBoundaryState = { hasError: false };
|
||||
|
||||
static getDerivedStateFromError(): ErrorBoundaryState {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: React.ErrorInfo) {
|
||||
console.error('Unhandled application error', error, info);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return <main className="wrap page">
|
||||
<div className="empty">
|
||||
<h1>Algo deu errado</h1>
|
||||
<p>Não foi possível exibir esta página. Recarregue para tentar novamente.</p>
|
||||
<button className="btn" type="button" onClick={() => window.location.reload()} style={{ marginTop: 20 }}>Recarregar página</button>
|
||||
</div>
|
||||
</main>;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,22 @@ interface SelectProps {
|
||||
/** Custom listbox used instead of the browser's native select. */
|
||||
export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLabel, disabled = false, variant = 'default' }) => {
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [position, setPosition] = useState<{ top: number; left: number; width: number } | null>(null);
|
||||
const selected = options.find((option) => option.value === value);
|
||||
const selectedIndex = Math.max(0, options.findIndex((option) => option.value === value));
|
||||
const [highlight, setHighlight] = useState(selectedIndex);
|
||||
|
||||
const move = (delta: number) => {
|
||||
if (!options.length) return;
|
||||
setHighlight((current) => (current + delta + options.length) % options.length);
|
||||
};
|
||||
|
||||
const closeMenu = (restoreFocus = false) => {
|
||||
setOpen(false);
|
||||
if (restoreFocus) triggerRef.current?.focus();
|
||||
};
|
||||
|
||||
const place = () => {
|
||||
const trigger = triggerRef.current;
|
||||
@@ -35,14 +48,17 @@ export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLa
|
||||
|
||||
const toggle = () => {
|
||||
if (disabled) return;
|
||||
if (!open) place();
|
||||
if (!open) {
|
||||
place();
|
||||
setHighlight(selectedIndex);
|
||||
}
|
||||
setOpen((current) => !current);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const close = () => setOpen(false);
|
||||
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') setOpen(false); };
|
||||
const close = () => closeMenu();
|
||||
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') closeMenu(true); };
|
||||
window.addEventListener('resize', close);
|
||||
window.addEventListener('scroll', close, true);
|
||||
document.addEventListener('keydown', onKey);
|
||||
@@ -53,6 +69,11 @@ export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLa
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !position) return;
|
||||
menuRef.current?.querySelectorAll<HTMLButtonElement>('button[role="option"]')[highlight]?.focus();
|
||||
}, [highlight, open, position]);
|
||||
|
||||
return <>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
@@ -63,14 +84,44 @@ export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLa
|
||||
aria-expanded={open}
|
||||
aria-label={ariaLabel}
|
||||
onClick={toggle}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
||||
event.preventDefault();
|
||||
if (!open) {
|
||||
place();
|
||||
setHighlight(selectedIndex);
|
||||
setOpen(true);
|
||||
} else {
|
||||
move(event.key === 'ArrowDown' ? 1 : -1);
|
||||
}
|
||||
}
|
||||
if (event.key === 'Escape' && open) {
|
||||
event.preventDefault();
|
||||
closeMenu();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="select-value">{selected?.label ?? ''}</span>
|
||||
<ChevronDownMockIcon className="ph" />
|
||||
</button>
|
||||
{open && position && createPortal(<>
|
||||
<button type="button" className="menu-scrim" aria-label="Fechar lista" onClick={() => setOpen(false)} />
|
||||
<div className="select-menu" role="listbox" aria-label={ariaLabel} style={{ top: position.top, left: position.left, width: position.width }}>
|
||||
{options.map((option) => <button key={option.value} type="button" role="option" aria-selected={option.value === value} onClick={() => { onChange(option.value); setOpen(false); }}><span>{option.label}</span>{option.value === value && <CheckMockIcon className="ph" />}</button>)}
|
||||
<button type="button" className="menu-scrim" aria-label="Fechar lista" onClick={() => closeMenu(true)} />
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="select-menu"
|
||||
role="listbox"
|
||||
aria-label={ariaLabel}
|
||||
style={{ top: position.top, left: position.left, width: position.width }}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'ArrowDown') { event.preventDefault(); move(1); }
|
||||
else if (event.key === 'ArrowUp') { event.preventDefault(); move(-1); }
|
||||
else if (event.key === 'Home') { event.preventDefault(); setHighlight(0); }
|
||||
else if (event.key === 'End') { event.preventDefault(); setHighlight(options.length - 1); }
|
||||
else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); }
|
||||
else if (event.key === 'Tab') { closeMenu(); }
|
||||
}}
|
||||
>
|
||||
{options.map((option, index) => <button key={option.value} type="button" role="option" aria-selected={option.value === value} tabIndex={-1} onFocus={() => setHighlight(index)} onClick={() => { onChange(option.value); closeMenu(true); }}><span>{option.label}</span>{option.value === value && <CheckMockIcon className="ph" />}</button>)}
|
||||
</div>
|
||||
</>, document.body)}
|
||||
</>;
|
||||
|
||||
Reference in New Issue
Block a user