new flashcards
All checks were successful
Mindforge API Build and Deploy / Build Mindforge API Image (push) Successful in 4m4s
Mindforge Web Build and Deploy (internal) / Build Mindforge Web Image (push) Successful in 5m29s
Mindforge Web Build and Deploy (internal) / Deploy Mindforge Web (internal) (push) Successful in 9s
Mindforge API Build and Deploy / Deploy Mindforge API (internal) (push) Successful in 8s

This commit is contained in:
2026-05-30 11:59:19 -03:00
parent b9736293d3
commit b80d28f671
27 changed files with 1735 additions and 290 deletions

View File

@@ -4,9 +4,10 @@ import { Header } from './components/Header';
import { Sidebar } from './components/Sidebar';
import { VerificadorComponent } from './components/VerificadorComponent';
import { FlashcardComponent } from './components/FlashcardComponent';
import { FlashcardReviewComponent } from './components/FlashcardReviewComponent';
export function App() {
const [activeModule, setActiveModule] = useState<'home' | 'verificador' | 'flashcards'>('home');
const [activeModule, setActiveModule] = useState<'home' | 'verificador' | 'flashcards' | 'revisao-flashcards'>('home');
return (
<>
@@ -17,8 +18,8 @@ export function App() {
<div style={{ display: activeModule === 'home' || !activeModule ? 'block' : 'none' }}>
<div class="home-hero">
<img src="/assets/mindforge-banner.png" alt="Mindforge Banner" style={{ maxWidth: '100%', height: 'auto', marginBottom: '2rem', borderRadius: '12px', boxShadow: '0 4px 15px rgba(0,0,0,0.5)', zIndex: -10 }} />
<h1 class="hero-title">Mindforge! - STAY HARD!</h1>
<p class="hero-subtitle">Sua ferramenta de forja mental e estudos.</p>
<h1 class="hero-title">Mindforge - Forja Mental</h1>
<p class="hero-subtitle">Sua ferramenta de estudos para concursos.</p>
</div>
</div>
<div style={{ display: activeModule === 'verificador' ? 'block' : 'none', height: '100%', width: '100%' }}>
@@ -27,6 +28,9 @@ export function App() {
<div style={{ display: activeModule === 'flashcards' ? 'block' : 'none', height: '100%', width: '100%' }}>
<FlashcardComponent />
</div>
<div style={{ display: activeModule === 'revisao-flashcards' ? 'block' : 'none', height: '100%', width: '100%' }}>
<FlashcardReviewComponent />
</div>
</main>
</div>
</>

View File

@@ -64,7 +64,7 @@
}
.tree-file-label input[type="checkbox"] {
accent-color: #7c6fcd;
accent-color: var(--color-accent);
width: 14px;
height: 14px;
cursor: pointer;

View File

@@ -1,6 +1,6 @@
.flashcard-container {
width: 100%;
max-width: 800px;
max-width: 900px;
margin: 0 auto;
animation: slideUp 0.5s ease-out;
display: flex;
@@ -8,14 +8,21 @@
gap: 1.5rem;
}
.flashcard-title {
font-size: 2.5rem;
}
.flashcard-form {
display: flex;
flex-direction: column;
gap: 1.2rem;
background: rgba(255, 255, 255, 0.05);
background: rgba(255, 255, 255, 0.06);
padding: 2rem;
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.14);
box-shadow: 0 14px 36px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.input-group {
@@ -30,47 +37,10 @@
color: var(--color-text-creamy);
}
.text-area {
width: 100%;
min-height: 200px;
background: rgba(0, 0, 0, 0.2);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 8px;
padding: 1rem;
color: var(--color-text-creamy);
font-family: inherit;
font-size: 1rem;
resize: vertical;
}
.text-area:focus {
outline: none;
border-color: var(--color-accent);
}
.file-input-wrapper {
display: flex;
align-items: center;
gap: 1rem;
}
.file-input {
display: none;
}
.file-input-label {
background: var(--color-sidebar);
color: var(--color-text-creamy);
padding: 0.6rem 1.2rem;
border-radius: 6px;
cursor: pointer;
border: 1px solid rgba(255, 255, 255, 0.2);
transition: all 0.2s ease;
}
.file-input-label:hover {
background: rgba(255, 255, 255, 0.1);
border-color: var(--color-accent);
.selection-meta {
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.55);
margin-top: 0.4rem;
}
.slider-wrapper {
@@ -86,72 +56,42 @@
width: 100%;
height: 8px;
background: rgba(0, 0, 0, 0.3);
border-radius: 4px;
border-radius: 999px;
outline: none;
}
.slider-input::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
width: 22px;
height: 22px;
border-radius: 50%;
background: var(--color-accent);
background: #f4f5f5;
border: 2px solid rgba(var(--color-accent-rgb), 0.9);
box-shadow: 0 6px 16px rgba(var(--color-accent-rgb), 0.35);
cursor: pointer;
transition: transform 0.1s;
}
.slider-input::-webkit-slider-thumb:hover {
transform: scale(1.2);
}
.amount-display {
font-weight: 700;
color: var(--color-accent);
min-width: 40px;
min-width: 44px;
text-align: right;
font-size: 1.1rem;
}
/* Spinner */
.spinner-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 3rem 0;
gap: 1rem;
}
.spinner {
width: 50px;
height: 50px;
border: 4px solid rgba(255, 255, 255, 0.1);
border-left-color: var(--color-accent);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.success-message {
color: #7ee787;
text-align: center;
font-weight: 700;
.flashcard-error {
color: #ff9c96;
margin-top: 1rem;
animation: fadeIn 0.5s ease-out;
}
.radio-group {
display: flex;
flex-wrap: wrap;
background: rgba(0, 0, 0, 0.3);
background: rgba(0, 0, 0, 0.28);
padding: 4px;
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.12);
width: fit-content;
overflow: hidden;
gap: 4px;
@@ -159,8 +99,7 @@
.radio-item {
position: relative;
flex: 1;
min-width: 100px;
min-width: 120px;
}
.radio-item input[type="radio"] {
@@ -178,30 +117,104 @@
cursor: pointer;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 600;
color: rgba(255, 255, 255, 0.6);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-weight: 700;
color: rgba(255, 255, 255, 0.65);
transition: all 0.25s ease;
white-space: nowrap;
}
.radio-item input[type="radio"]:checked + .radio-label {
background: var(--color-accent);
color: #000;
box-shadow: 0 4px 12px rgba(var(--color-accent-rgb), 0.3);
color: #012f3b;
box-shadow: 0 4px 12px rgba(var(--color-accent-rgb), 0.35);
}
.radio-item:hover .radio-label:not(.radio-item input[type="radio"]:checked + .radio-label) {
background: rgba(255, 255, 255, 0.05);
color: #fff;
.radio-item:hover .radio-label {
color: rgba(255, 255, 255, 0.92);
}
/* Animations for selection */
.radio-item input[type="radio"]:checked + .radio-label {
animation: selectBounce 0.3s ease-out;
.spinner-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem 0;
gap: 1rem;
}
@keyframes selectBounce {
0% { transform: scale(0.95); }
50% { transform: scale(1.02); }
100% { transform: scale(1); }
.spinner {
width: 50px;
height: 50px;
border: 4px solid rgba(255, 255, 255, 0.12);
border-left-color: var(--color-accent);
border-radius: 50%;
animation: spin 1s linear infinite;
}
.flashcard-result-panel {
background: rgba(255, 255, 255, 0.06);
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.14);
padding: 1.5rem;
text-align: left;
}
.flashcard-result-panel h3 {
margin: 0 0 1rem 0;
font-size: 1.1rem;
color: rgba(255, 255, 255, 0.94);
}
.flashcard-result-list {
display: grid;
grid-template-columns: 1fr;
gap: 0.85rem;
}
.flashcard-result-item {
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(0, 0, 0, 0.2);
border-radius: 10px;
padding: 0.85rem 1rem;
}
.flashcard-result-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
font-size: 0.95rem;
}
.flashcard-result-header span {
color: rgba(255, 255, 255, 0.72);
}
.flashcard-result-meta {
margin-top: 0.45rem;
display: flex;
flex-wrap: wrap;
gap: 0.85rem;
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.65);
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@media (max-width: 720px) {
.flashcard-form {
padding: 1.2rem;
}
.flashcard-result-header {
flex-direction: column;
align-items: flex-start;
}
}

View File

@@ -1,181 +1,147 @@
import { useState } from 'preact/hooks';
import { MindforgeApiService, type FlashcardMode } from '../services/MindforgeApiService';
import {
MindforgeApiService,
type FlashcardDifficulty,
type FlashcardLibraryDetails,
} from '../services/MindforgeApiService';
import { FileTreeComponent } from './FileTreeComponent';
import { Button } from './Button';
import './FlashcardComponent.css';
// Mapping of flashcard mode to its maximum allowed amount
const modeMax: Record<FlashcardMode, number> = {
Basic: 25,
Simple: 30,
Detailed: 70,
Hyper: 130,
};
const minAmount = 10;
const maxAmount = 30;
function utf8ToBase64(str: string): string {
const bytes = new TextEncoder().encode(str);
const binary = Array.from(bytes, byte => String.fromCharCode(byte)).join('');
return window.btoa(binary);
function difficultyLabel(difficulty: string) {
return difficulty === 'Hard' ? 'Dificil' : 'Facil';
}
export function FlashcardComponent() {
const [selectedPaths, setSelectedPaths] = useState<string[]>([]);
const [amount, setAmount] = useState<number>(20);
const [mode, setMode] = useState<FlashcardMode>('Simple');
const [difficulty, setDifficulty] = useState<FlashcardDifficulty>('Easy');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<boolean>(false);
const handleModeChange = (newMode: FlashcardMode) => {
setMode(newMode);
setAmount(20);
};
const [generatedLibraries, setGeneratedLibraries] = useState<FlashcardLibraryDetails[]>([]);
const handleGenerate = async () => {
if (selectedPaths.length === 0) {
setError('Selecione pelo menos um arquivo do repositório para gerar os flashcards.');
setError('Selecione pelo menos um arquivo do repositorio para gerar os flashcards.');
return;
}
setLoading(true);
setError(null);
setSuccess(false);
try {
// Fetch all selected files and merge their content
const fileContents = await Promise.all(
selectedPaths.map(path => MindforgeApiService.getFileContent(path))
);
const mergedContent = fileContents.map(f => f.content).join('\n\n---\n\n');
const mergedFileName = selectedPaths.length === 1
? (selectedPaths[0].split('/').pop() ?? 'merged.md')
: 'merged.md';
const base64Content = utf8ToBase64(mergedContent);
const res = await MindforgeApiService.generateFlashcards({
fileContent: base64Content,
fileName: mergedFileName,
const response = await MindforgeApiService.generateFlashcards({
filePaths: selectedPaths,
amount,
mode,
difficulty,
});
downloadCSV(res.result);
setSuccess(true);
setGeneratedLibraries(response.libraries);
} catch (err: any) {
setError(err.message || 'Ocorreu um erro ao gerar os flashcards.');
setError(err?.message || 'Ocorreu um erro ao gerar os flashcards.');
} finally {
setLoading(false);
}
};
const downloadCSV = (content: string) => {
const bom = new Uint8Array([0xEF, 0xBB, 0xBF]);
const blob = new Blob([bom, content], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `flashcards_${Date.now()}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
return (
<div className="flashcard-container">
<h2 className="title" style={{ fontSize: '2.5rem' }}>Gerador de Flashcards</h2>
<p className="subtitle">Selecione os arquivos do repositório para gerar flashcards. Múltiplos arquivos serão combinados.</p>
<h2 className="title flashcard-title">Gerador de Flashcards</h2>
<p className="subtitle">Selecione os arquivos do repositorio para gerar bibliotecas de flashcards.</p>
<div className="flashcard-form">
<div className="input-group">
<label>Arquivos do Repositório</label>
<label>Arquivos do Repositorio</label>
<FileTreeComponent selectedPaths={selectedPaths} onSelectionChange={setSelectedPaths} />
{selectedPaths.length > 0 && (
<div style={{ fontSize: '0.85rem', color: 'rgba(255,255,255,0.5)', marginTop: '0.4rem' }}>
{selectedPaths.length} arquivo{selectedPaths.length !== 1 ? 's' : ''} selecionado{selectedPaths.length !== 1 ? 's' : ''}
{selectedPaths.length > 1 ? ' — conteúdo será combinado' : ''}
<div className="selection-meta">
{selectedPaths.length} arquivo{selectedPaths.length !== 1 ? 's' : ''} selecionado
{selectedPaths.length !== 1 ? 's' : ''}
</div>
)}
</div>
<div className="input-group">
<label>Quantidade Estimada de Flashcards (10 - {modeMax[mode]})</label>
<label>Quantidade por Arquivo ({minAmount} - {maxAmount})</label>
<div className="slider-wrapper">
<input
type="range"
className="slider-input"
min="10"
max={modeMax[mode]}
min={minAmount}
max={maxAmount}
value={amount}
onInput={(e) => setAmount(parseInt((e.target as HTMLInputElement).value))}
onInput={(e) => setAmount(parseInt((e.target as HTMLInputElement).value, 10))}
/>
<span className="amount-display">{amount}</span>
</div>
</div>
<div className="input-group">
<label>Modo de Geração</label>
<label>Dificuldade</label>
<div className="radio-group">
<div className="radio-item">
<input
type="radio"
id="mode-basic"
name="mode"
value="Basic"
checked={mode === 'Basic'}
onChange={(e) => handleModeChange((e.target as HTMLInputElement).value as FlashcardMode)}
id="difficulty-easy"
name="difficulty"
value="Easy"
checked={difficulty === 'Easy'}
onChange={() => setDifficulty('Easy')}
/>
<label htmlFor="mode-basic" className="radio-label" title="Modo básico, rápido e simples. Geralmente conteúdos simples e repetíveis">Básico</label>
<label htmlFor="difficulty-easy" className="radio-label" title="Perguntas mais diretas e objetivas">
Facil
</label>
</div>
<div className="radio-item">
<input
type="radio"
id="mode-simple"
name="mode"
value="Simple"
checked={mode === 'Simple'}
onChange={(e) => handleModeChange((e.target as HTMLInputElement).value as FlashcardMode)}
id="difficulty-hard"
name="difficulty"
value="Hard"
checked={difficulty === 'Hard'}
onChange={() => setDifficulty('Hard')}
/>
<label htmlFor="mode-simple" className="radio-label" title="Modo rápido e simples, possui uma melhor compreensão">Simples</label>
</div>
<div className="radio-item">
<input
type="radio"
id="mode-detailed"
name="mode"
value="Detailed"
checked={mode === 'Detailed'}
onChange={(e) => handleModeChange((e.target as HTMLInputElement).value as FlashcardMode)}
/>
<label htmlFor="mode-detailed" className="radio-label" title="Modelo avançado, maior gama de detalhes">Detalhado</label>
</div>
<div className="radio-item">
<input
type="radio"
id="mode-hyper"
name="mode"
value="Hyper"
checked={mode === 'Hyper'}
onChange={(e) => handleModeChange((e.target as HTMLInputElement).value as FlashcardMode)}
/>
<label htmlFor="mode-hyper" className="radio-label" title="Modelo Pro, complexo e com perguntas adicionais">Hiper</label>
<label htmlFor="difficulty-hard" className="radio-label" title="Perguntas mais desafiadoras">
Dificil
</label>
</div>
</div>
</div>
<Button variant="primary" onClick={handleGenerate} disabled={loading} style={{ marginTop: '1rem' }}>
{loading ? 'Gerando...' : 'Gerar Flashcards e Baixar (CSV)'}
{loading ? 'Gerando...' : 'Gerar Bibliotecas de Flashcards'}
</Button>
{error && <div style={{ color: '#ff7b72', marginTop: '1rem' }}>{error}</div>}
{success && <div className="success-message">Flashcards gerados com sucesso! O download deve ter começado.</div>}
{error && <div className="flashcard-error">{error}</div>}
</div>
{loading && (
<div className="spinner-container">
<div className="spinner"></div>
<p>Extraindo os melhores conceitos para os seus flashcards. Aguarde...</p>
<p>Gerando os flashcards com IA e salvando no banco. Aguarde...</p>
</div>
)}
{generatedLibraries.length > 0 && (
<div className="flashcard-result-panel">
<h3>Bibliotecas Geradas</h3>
<div className="flashcard-result-list">
{generatedLibraries.map((library) => (
<article key={library.id} className="flashcard-result-item">
<div className="flashcard-result-header">
<strong>{library.fileName}</strong>
<span>{library.cardCount} cards</span>
</div>
<div className="flashcard-result-meta">
<span>Materia: {library.subject}</span>
<span>Dificuldade: {difficultyLabel(library.difficulty)}</span>
</div>
</article>
))}
</div>
</div>
)}
</div>

View File

@@ -0,0 +1,171 @@
.review-container {
width: 100%;
max-width: 900px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 1.2rem;
animation: slideUp 0.45s ease-out;
}
.review-title {
font-size: 2.35rem;
}
.review-error {
color: #ff9c96;
text-align: left;
background: rgba(255, 69, 58, 0.12);
border: 1px solid rgba(255, 69, 58, 0.4);
border-radius: 10px;
padding: 0.8rem 1rem;
}
.review-select-panel,
.review-session-panel {
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 12px;
padding: 1.25rem;
text-align: left;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
box-shadow: 0 14px 36px rgba(0, 0, 0, 0.18);
}
.review-state {
color: rgba(255, 255, 255, 0.72);
font-size: 0.95rem;
}
.review-subjects {
display: grid;
gap: 1rem;
}
.review-subject-section {
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(0, 0, 0, 0.18);
border-radius: 10px;
padding: 0.9rem;
}
.review-subject-section h3 {
margin: 0 0 0.8rem;
font-size: 1rem;
color: rgba(255, 255, 255, 0.95);
}
.review-library-list {
display: grid;
gap: 0.6rem;
}
.review-library-item {
display: flex;
align-items: flex-start;
gap: 0.7rem;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
padding: 0.6rem 0.7rem;
cursor: pointer;
background: rgba(255, 255, 255, 0.03);
}
.review-library-item input[type="checkbox"] {
margin-top: 0.15rem;
width: 16px;
height: 16px;
accent-color: var(--color-accent);
}
.review-library-texts {
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.review-library-texts strong {
font-size: 0.95rem;
}
.review-library-texts span {
color: rgba(255, 255, 255, 0.68);
font-size: 0.84rem;
}
.review-actions {
margin-top: 1rem;
display: flex;
justify-content: flex-end;
}
.review-progress {
display: flex;
align-items: center;
gap: 0.9rem;
margin-bottom: 0.8rem;
}
.review-progress span {
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.8);
min-width: 60px;
}
.review-progress-bar {
width: 100%;
height: 8px;
border-radius: 999px;
background: rgba(0, 0, 0, 0.25);
overflow: hidden;
}
.review-progress-fill {
height: 100%;
background: linear-gradient(90deg, rgba(var(--color-accent-rgb), 0.8), rgba(var(--color-accent-rgb), 1));
border-radius: 999px;
transition: width 0.25s ease;
}
.review-card {
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 10px;
padding: 1rem;
background: rgba(0, 0, 0, 0.2);
min-height: 250px;
}
.review-card header {
margin-bottom: 0.8rem;
}
.review-card small {
color: rgba(255, 255, 255, 0.62);
}
.review-card h3 {
margin: 0 0 0.4rem;
font-size: 0.98rem;
color: rgba(255, 255, 255, 0.9);
}
.review-card p {
margin: 0 0 1rem;
font-size: 1rem;
line-height: 1.55;
}
.review-session-actions {
margin-top: 1rem;
display: flex;
gap: 0.65rem;
flex-wrap: wrap;
}
@media (max-width: 740px) {
.review-session-actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}

View File

@@ -0,0 +1,233 @@
import { useEffect, useMemo, useState } from 'preact/hooks';
import {
MindforgeApiService,
type FlashcardCard,
type FlashcardLibrarySummary,
} from '../services/MindforgeApiService';
import { Button } from './Button';
import './FlashcardReviewComponent.css';
function groupLibrariesBySubject(libraries: FlashcardLibrarySummary[]) {
const grouped: Record<string, FlashcardLibrarySummary[]> = {};
libraries.forEach((library) => {
const subject = library.subject || 'Geral';
if (!grouped[subject]) {
grouped[subject] = [];
}
grouped[subject].push(library);
});
return Object.entries(grouped).sort(([a], [b]) => a.localeCompare(b));
}
function difficultyLabel(difficulty: string) {
return difficulty === 'Hard' ? 'Dificil' : 'Facil';
}
export function FlashcardReviewComponent() {
const [libraries, setLibraries] = useState<FlashcardLibrarySummary[]>([]);
const [selectedLibraryIds, setSelectedLibraryIds] = useState<number[]>([]);
const [loadingLibraries, setLoadingLibraries] = useState(true);
const [loadingSession, setLoadingSession] = useState(false);
const [error, setError] = useState<string | null>(null);
const [sessionCards, setSessionCards] = useState<FlashcardCard[]>([]);
const [currentIndex, setCurrentIndex] = useState(0);
const [showAnswer, setShowAnswer] = useState(false);
useEffect(() => {
let cancelled = false;
async function loadLibraries() {
setLoadingLibraries(true);
setError(null);
try {
const result = await MindforgeApiService.getFlashcardLibraries();
if (!cancelled) {
setLibraries(result);
}
} catch (err: any) {
if (!cancelled) {
setError(err?.message || 'Falha ao carregar bibliotecas de flashcards.');
}
} finally {
if (!cancelled) {
setLoadingLibraries(false);
}
}
}
loadLibraries();
return () => {
cancelled = true;
};
}, []);
const groupedLibraries = useMemo(() => groupLibrariesBySubject(libraries), [libraries]);
const libraryById = useMemo(() => {
return new Map(libraries.map((library) => [library.id, library]));
}, [libraries]);
const currentCard = sessionCards[currentIndex];
const progressPercent = sessionCards.length > 0
? ((currentIndex + 1) / sessionCards.length) * 100
: 0;
const toggleLibrary = (libraryId: number) => {
if (selectedLibraryIds.includes(libraryId)) {
setSelectedLibraryIds(selectedLibraryIds.filter((id) => id !== libraryId));
return;
}
setSelectedLibraryIds([...selectedLibraryIds, libraryId]);
};
const startReviewSession = async () => {
if (selectedLibraryIds.length === 0) {
setError('Selecione ao menos uma biblioteca para iniciar a revisao.');
return;
}
setLoadingSession(true);
setError(null);
try {
const response = await MindforgeApiService.createFlashcardReviewSession({
libraryIds: selectedLibraryIds,
});
setSessionCards(response.cards);
setCurrentIndex(0);
setShowAnswer(false);
} catch (err: any) {
setError(err?.message || 'Falha ao iniciar sessao de revisao.');
} finally {
setLoadingSession(false);
}
};
const endSession = () => {
setSessionCards([]);
setCurrentIndex(0);
setShowAnswer(false);
};
const goToPrevious = () => {
if (currentIndex === 0) {
return;
}
setCurrentIndex(currentIndex - 1);
setShowAnswer(false);
};
const goToNext = () => {
if (currentIndex >= sessionCards.length - 1) {
return;
}
setCurrentIndex(currentIndex + 1);
setShowAnswer(false);
};
return (
<div className="review-container">
<h2 className="title review-title">Revisao Flashcards</h2>
<p className="subtitle">Escolha as bibliotecas para estudar e inicie uma sessao de revisao.</p>
{error && <div className="review-error">{error}</div>}
{sessionCards.length === 0 && (
<div className="review-select-panel">
{loadingLibraries && <p className="review-state">Carregando bibliotecas...</p>}
{!loadingLibraries && libraries.length === 0 && (
<p className="review-state">Nenhuma biblioteca encontrada. Gere flashcards para comecar.</p>
)}
{!loadingLibraries && libraries.length > 0 && (
<div className="review-subjects">
{groupedLibraries.map(([subject, subjectLibraries]) => (
<section key={subject} className="review-subject-section">
<h3>{subject}</h3>
<div className="review-library-list">
{subjectLibraries.map((library) => (
<label key={library.id} className="review-library-item">
<input
type="checkbox"
checked={selectedLibraryIds.includes(library.id)}
onChange={() => toggleLibrary(library.id)}
/>
<div className="review-library-texts">
<strong>{library.fileName}</strong>
<span>
{library.cardCount} cards - {difficultyLabel(library.difficulty)}
</span>
</div>
</label>
))}
</div>
</section>
))}
</div>
)}
<div className="review-actions">
<Button variant="primary" onClick={startReviewSession} disabled={loadingSession || selectedLibraryIds.length === 0}>
{loadingSession ? 'Iniciando...' : 'Iniciar Revisao'}
</Button>
</div>
</div>
)}
{sessionCards.length > 0 && currentCard && (
<div className="review-session-panel">
<div className="review-progress">
<span>{currentIndex + 1} / {sessionCards.length}</span>
<div className="review-progress-bar">
<div className="review-progress-fill" style={{ width: `${progressPercent}%` }} />
</div>
</div>
<article className="review-card">
<header>
<small>
{libraryById.get(currentCard.libraryId)?.fileName || 'Arquivo'} -
{' '}
{libraryById.get(currentCard.libraryId)?.subject || 'Geral'}
</small>
</header>
<h3>Frente</h3>
<p>{currentCard.front}</p>
{showAnswer && (
<>
<h3>Verso</h3>
<p>{currentCard.back}</p>
</>
)}
</article>
<div className="review-session-actions">
<Button variant="secondary" onClick={goToPrevious} disabled={currentIndex === 0}>
Anterior
</Button>
{!showAnswer && (
<Button variant="primary" onClick={() => setShowAnswer(true)}>
Revelar Resposta
</Button>
)}
{showAnswer && (
<Button variant="primary" onClick={goToNext} disabled={currentIndex >= sessionCards.length - 1}>
Proximo
</Button>
)}
<Button variant="secondary" onClick={endSession}>
Encerrar Sessao
</Button>
</div>
</div>
)}
</div>
);
}

View File

@@ -2,15 +2,15 @@ import { Button } from './Button';
import './Sidebar.css';
interface SidebarProps {
onModuleChange: (module: 'home' | 'verificador' | 'flashcards') => void;
activeModule: 'home' | 'verificador' | 'flashcards';
onModuleChange: (module: 'home' | 'verificador' | 'flashcards' | 'revisao-flashcards') => void;
activeModule: 'home' | 'verificador' | 'flashcards' | 'revisao-flashcards';
}
export function Sidebar({ onModuleChange, activeModule }: SidebarProps) {
return (
<aside class="sidebar">
<div class="sidebar-header">
<h2 class="sidebar-title">Módulos</h2>
<h2 class="sidebar-title">Modulos</h2>
</div>
<div class="sidebar-nav">
<Button
@@ -27,6 +27,13 @@ export function Sidebar({ onModuleChange, activeModule }: SidebarProps) {
>
Flashcards
</Button>
<Button
variant={activeModule === 'revisao-flashcards' ? 'primary' : 'secondary'}
onClick={() => onModuleChange('revisao-flashcards')}
className="sidebar-btn"
>
Revisao Flashcards
</Button>
</div>
</aside>
);

View File

@@ -26,17 +26,66 @@ export interface CheckFileResponse {
result: string;
}
export type FlashcardDifficulty = 'Easy' | 'Hard';
export interface GenerateFlashcardsRequest {
fileContent: string;
fileName: string;
filePaths: string[];
amount: number;
mode: FlashcardMode;
difficulty: FlashcardDifficulty;
}
export type FlashcardMode = 'Basic' | 'Simple' | 'Detailed' | 'Hyper';
export interface FlashcardCard {
id: number;
libraryId: number;
front: string;
back: string;
position: number;
createdAt: string;
}
export interface FlashcardLibrarySummary {
id: number;
filePath: string;
fileName: string;
subject: string;
difficulty: string;
cardCount: number;
createdAt: string;
updatedAt: string;
}
export interface FlashcardLibraryDetails extends FlashcardLibrarySummary {
cards: FlashcardCard[];
}
export interface GenerateFlashcardsResponse {
result: string;
libraries: FlashcardLibraryDetails[];
}
export interface FlashcardReviewSessionRequest {
libraryIds: number[];
}
export interface FlashcardReviewSessionResponse {
cards: FlashcardCard[];
}
async function throwIfNotOk(response: Response, fallback: string) {
if (response.ok) {
return;
}
let apiMessage = '';
try {
const body = await response.json();
if (typeof body?.error === 'string' && body.error.length > 0) {
apiMessage = body.error;
}
} catch {
// Ignore parse failures and throw fallback below.
}
throw new Error(apiMessage || fallback);
}
export const MindforgeApiService = {
@@ -49,9 +98,7 @@ export const MindforgeApiService = {
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`Error checking file: ${response.statusText}`);
}
await throwIfNotOk(response, `Erro ao validar arquivo: ${response.statusText}`);
return response.json();
},
@@ -64,27 +111,50 @@ export const MindforgeApiService = {
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`Error generating flashcards: ${response.statusText}`);
}
await throwIfNotOk(response, `Erro ao gerar flashcards: ${response.statusText}`);
return response.json();
},
async getFlashcardLibraries(): Promise<FlashcardLibrarySummary[]> {
const response = await fetch(`${BASE_URL}/api/v1/flashcard/libraries`);
await throwIfNotOk(response, `Erro ao buscar bibliotecas de flashcards: ${response.statusText}`);
return response.json();
},
async getFlashcardLibrary(id: number): Promise<FlashcardLibraryDetails> {
const response = await fetch(`${BASE_URL}/api/v1/flashcard/libraries/${id}`);
await throwIfNotOk(response, `Erro ao buscar biblioteca ${id}: ${response.statusText}`);
return response.json();
},
async createFlashcardReviewSession(data: FlashcardReviewSessionRequest): Promise<FlashcardReviewSessionResponse> {
const response = await fetch(`${BASE_URL}/api/v1/flashcard/review-session`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
await throwIfNotOk(response, `Erro ao iniciar revisao: ${response.statusText}`);
return response.json();
},
async getRepositoryInfo(): Promise<RepositoryInfo> {
const response = await fetch(`${BASE_URL}/api/v1/repository/info`);
if (!response.ok) throw new Error(`Error fetching repository info: ${response.statusText}`);
await throwIfNotOk(response, `Erro ao buscar info do repositorio: ${response.statusText}`);
return response.json();
},
async getRepositoryTree(): Promise<FileTreeNode[]> {
const response = await fetch(`${BASE_URL}/api/v1/repository/tree`);
if (!response.ok) throw new Error(`Error fetching repository tree: ${response.statusText}`);
await throwIfNotOk(response, `Erro ao buscar arvore do repositorio: ${response.statusText}`);
return response.json();
},
async getFileContent(path: string): Promise<FileContentResponse> {
const response = await fetch(`${BASE_URL}/api/v1/repository/file?path=${encodeURIComponent(path)}`);
if (!response.ok) throw new Error(`Error fetching file ${path}: ${response.statusText}`);
await throwIfNotOk(response, `Erro ao buscar arquivo ${path}: ${response.statusText}`);
return response.json();
},
};