Files
compor-academy/pages/ProfilePage.tsx
Cauê Faleiros 50905eefd7
All checks were successful
CI / Validate frontend and API (push) Successful in 3m5s
CI / Build and publish Docker images (push) Successful in 1m42s
feat: add 2FA, secure cookies and publishing tools
2026-11-06 10:29:37 -03:00

60 lines
6.5 KiB
TypeScript

import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { ArrowSquareOutIcon, CameraIcon, CircleNotchIcon, GlobeIcon, InstagramLogoIcon, LinkedinLogoIcon, YoutubeLogoIcon } from '@phosphor-icons/react';
import { useAuth } from '../context/AuthContext';
import { Profile, ProfileInput, instructorApi, profileApi } from '../services/api';
import { CourseCoverImage } from '../components/CourseCoverImage';
import { TwoFactorSettings } from '../components/account/TwoFactorSettings';
import { Switch } from '../components/ui/Switch';
import { useToast } from '../context/ToastContext';
const emptyProfile = (user: { id: string; email: string; name: string; role: string }): Profile => ({
id: user.id, email: user.email, name: user.name,
role: user.role === 'superadmin' ? 'admin' : user.role === 'professor' ? 'instructor' : 'student',
avatarImageUrl: null, headline: '', bio: '', websiteUrl: null, linkedinUrl: null, instagramUrl: null, youtubeUrl: null, isPublic: true,
});
export const ProfilePage: React.FC = () => {
const { user, updateCurrentUser } = useAuth();
const { showToast } = useToast();
const fileInput = useRef<HTMLInputElement>(null);
const [profile, setProfile] = useState<Profile | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [isUploading, setIsUploading] = useState(false);
useEffect(() => {
if (!user) return;
profileApi.me().then((response) => setProfile(response.data)).catch(() => { setProfile(emptyProfile(user)); showToast('Não foi possível carregar todos os dados do perfil.', 'error'); }).finally(() => setIsLoading(false));
}, [showToast, user]);
if (isLoading || !profile || !user) return <main className="wrap page"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
const update = <K extends keyof Profile>(key: K, value: Profile[K]) => setProfile((current) => current ? { ...current, [key]: value } : current);
const uploadAvatar = async (file?: File) => {
if (!file) return;
if (!file.type.startsWith('image/')) { showToast('Selecione uma imagem JPG, PNG ou WebP.', 'error'); return; }
setIsUploading(true);
try { const response = await instructorApi.uploadCover(file); update('avatarImageUrl', response.data.coverImageUrl); showToast('Foto enviada. Salve o perfil para publicar a alteração.', 'success'); }
catch { showToast('Não foi possível enviar a foto.', 'error'); }
finally { setIsUploading(false); }
};
const save = async (event: React.FormEvent) => {
event.preventDefault();
const input: ProfileInput = { name: profile.name, avatarImageUrl: profile.avatarImageUrl, headline: profile.headline, bio: profile.bio, websiteUrl: profile.websiteUrl, linkedinUrl: profile.linkedinUrl, instagramUrl: profile.instagramUrl, youtubeUrl: profile.youtubeUrl, isPublic: profile.isPublic };
setIsSaving(true);
try { const response = await profileApi.update(input); setProfile(response.data); updateCurrentUser({ id: user.id, email: user.email, name: response.data.name, role: response.data.role }); showToast('Perfil salvo com sucesso.', 'success'); }
catch { showToast('Não foi possível salvar o perfil. Verifique os links informados.', 'error'); }
finally { setIsSaving(false); }
};
return <main className="wrap page enter profile-page">
<header className="ptitle"><div><h1>Conta</h1><p>Seus dados, apresentação e links.</p></div>{profile.isPublic && <Link className="btn sec" to={`/perfis/${user.id}`}><ArrowSquareOutIcon className="ph" /> Ver perfil público</Link>}</header>
<form onSubmit={save} className="profile-form">
<div className="profile-avatar"><span className="av xl">{profile.avatarImageUrl ? <CourseCoverImage source={profile.avatarImageUrl} alt={`Foto de ${profile.name}`} /> : profile.name.slice(0, 2).toUpperCase()}</span><button type="button" className="link" disabled={isUploading} onClick={() => fileInput.current?.click()}><CameraIcon className="ph" /> Trocar foto</button><input ref={fileInput} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={(event) => { void uploadAvatar(event.target.files?.[0]); event.currentTarget.value = ''; }} /></div>
<div className="profile-fields"><section className="form"><h2>Dados pessoais</h2><div className="field"><label htmlFor="profile-name">Nome</label><input id="profile-name" value={profile.name} onChange={(event) => update('name', event.target.value)} maxLength={120} required /></div><div className="field"><label htmlFor="profile-email">E-mail</label><input id="profile-email" value={user.email} disabled /></div><div className="field"><label htmlFor="profile-headline">Título profissional</label><input id="profile-headline" value={profile.headline} onChange={(event) => update('headline', event.target.value)} maxLength={180} /></div><div className="field"><label htmlFor="profile-bio">Sobre você</label><textarea id="profile-bio" value={profile.bio} onChange={(event) => update('bio', event.target.value)} maxLength={3000} /></div></section>
<section className="form"><h2>Links e visibilidade</h2><p className="muted">Use links completos, começando com https://.</p><UrlField icon={<GlobeIcon />} label="Site" value={profile.websiteUrl} onChange={(value) => update('websiteUrl', value || null)} /><UrlField icon={<LinkedinLogoIcon />} label="LinkedIn" value={profile.linkedinUrl} onChange={(value) => update('linkedinUrl', value || null)} /><UrlField icon={<InstagramLogoIcon />} label="Instagram" value={profile.instagramUrl} onChange={(value) => update('instagramUrl', value || null)} /><UrlField icon={<YoutubeLogoIcon />} label="YouTube" value={profile.youtubeUrl} onChange={(value) => update('youtubeUrl', value || null)} /><div className="toggle"><span>Perfil público<small>Permite que outras pessoas vejam sua apresentação e seus cursos.</small></span><Switch checked={profile.isPublic} onChange={(checked) => update('isPublic', checked)} label="Perfil público" /></div></section></div>
<button className="btn lg profile-save" type="submit" disabled={isSaving}>{isSaving ? 'Salvando…' : 'Salvar'}</button>
</form>
{user.role === 'superadmin' && <TwoFactorSettings />}
</main>;
};
const UrlField: React.FC<{ icon: React.ReactNode; label: string; value: string | null; onChange: (value: string) => void }> = ({ icon, label, value, onChange }) => <div className="field"><label>{icon} {label}<input type="url" value={value || ''} onChange={(event) => onChange(event.target.value)} placeholder="https://" /></label></div>;