Restore study gestures and shuffle progress; harden note autosave and record V1 comparison
This commit is contained in:
parent
4bf121728b
commit
d7e19db468
8 changed files with 236 additions and 37 deletions
|
|
@ -99,6 +99,7 @@ export function FlipCard({
|
|||
footer,
|
||||
leaving,
|
||||
burst,
|
||||
onSwipe,
|
||||
}: {
|
||||
front: string;
|
||||
back: string;
|
||||
|
|
@ -113,15 +114,19 @@ export function FlipCard({
|
|||
/** Plays the swipe-away animation used when a card is graded. */
|
||||
leaving?: 'left' | 'right' | null;
|
||||
burst?: { streak: number; tier: StreakTier; id: number } | null;
|
||||
/** Horizontal touch gestures grade an answer without interfering with vertical scrolling. */
|
||||
onSwipe?: (known: boolean) => void;
|
||||
}) {
|
||||
const [showHint, setShowHint] = useState(false);
|
||||
const touch = useRef<{ x: number; y: number } | null>(null);
|
||||
const suppressClick = useRef(false);
|
||||
useEffect(() => setShowHint(false), [cardKey]);
|
||||
const face = 'flip-face flex min-h-[max(320px,min(60vh,680px))] flex-col rounded-[24px] border border-line bg-surface shadow-2';
|
||||
// Short answers read best large and centred; long ones as normal text.
|
||||
const size = (text: string) =>
|
||||
text.length < 60 ? 'text-[30px] sm:text-[38px] lg:text-[46px] leading-tight text-center' : text.length < 220 ? 'text-[22px] sm:text-[26px] lg:text-[30px] leading-snug text-center' : 'text-[17px] sm:text-[19px] lg:text-[21px]';
|
||||
return (
|
||||
<div key={cardKey} className={cx('flip-scene relative w-full animate-in', leaving === 'left' && 'swipe-left', leaving === 'right' && 'swipe-right')}>
|
||||
<div key={cardKey} className={cx('flip-scene relative w-full', !leaving && 'animate-in', leaving === 'left' && 'swipe-left', leaving === 'right' && 'swipe-right')}>
|
||||
{/* The whole card is the flip target, on both sides. Space, Enter and the arrow keys do the same. */}
|
||||
<div
|
||||
className="flip-card rounded-[24px] outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-4 focus-visible:ring-offset-paper"
|
||||
|
|
@ -129,7 +134,31 @@ export function FlipCard({
|
|||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={flipped ? 'Flashcard, answer side. Activate to show the question.' : 'Flashcard, question side. Activate to show the answer.'}
|
||||
onClick={onFlip}
|
||||
style={{ touchAction: onSwipe ? 'pan-y' : undefined }}
|
||||
onTouchStart={(e) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (!onSwipe || target.closest('button,a,input,textarea,select')) return;
|
||||
const p = e.touches[0];
|
||||
touch.current = { x: p.clientX, y: p.clientY };
|
||||
suppressClick.current = false;
|
||||
}}
|
||||
onTouchCancel={() => { touch.current = null; }}
|
||||
onTouchEnd={(e) => {
|
||||
const start = touch.current;
|
||||
touch.current = null;
|
||||
if (!start || !onSwipe) return;
|
||||
const p = e.changedTouches[0];
|
||||
const dx = p.clientX - start.x;
|
||||
const dy = p.clientY - start.y;
|
||||
if (Math.abs(dx) >= 80 && Math.abs(dx) > Math.abs(dy) * 1.5) {
|
||||
suppressClick.current = true;
|
||||
onSwipe(dx > 0);
|
||||
}
|
||||
}}
|
||||
onClick={() => {
|
||||
if (suppressClick.current) { suppressClick.current = false; return; }
|
||||
onFlip();
|
||||
}}
|
||||
>
|
||||
<div className={cx(face, 'flip-front')} inert={flipped ? true : undefined}>
|
||||
<div className="flex items-center justify-between px-6 pt-5">
|
||||
|
|
@ -324,6 +353,14 @@ export function CramSession({
|
|||
reset();
|
||||
onState(freshCramState(cards, shuffled));
|
||||
};
|
||||
const shuffleRemaining = () => {
|
||||
if (busy) return;
|
||||
const remaining = state.order.slice(state.index);
|
||||
const ordered = state.shuffled
|
||||
? cards.filter((c) => remaining.includes(c.id)).map((c) => c.id)
|
||||
: shuffle(remaining);
|
||||
onState({ ...state, shuffled: !state.shuffled, order: [...state.order.slice(0, state.index), ...ordered] });
|
||||
};
|
||||
const studyUnknown = () => {
|
||||
reset();
|
||||
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1));
|
||||
|
|
@ -357,7 +394,7 @@ export function CramSession({
|
|||
<span className="num text-[13px] font-medium text-ink-2">
|
||||
{Math.min(state.index + 1, total)}/{total}
|
||||
</span>
|
||||
<IconButton label={state.shuffled ? 'Shuffled. Restart in order' : 'Shuffle and restart'} active={state.shuffled} onClick={() => restart(!state.shuffled)}>
|
||||
<IconButton label={state.shuffled ? 'Put remaining cards in order' : 'Shuffle remaining cards'} active={state.shuffled} disabled={busy || done} onClick={shuffleRemaining}>
|
||||
<Shuffle />
|
||||
</IconButton>
|
||||
</>
|
||||
|
|
@ -390,7 +427,7 @@ export function CramSession({
|
|||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<FlipCard cardKey={`${state.round}:${state.index}:${card.id}`} front={card.front} back={card.back} hint={card.hint} flipped={flipped} onFlip={flip} leaving={leaving} burst={burst} footer={renderExtra?.(card)} label={state.known.includes(card.id) ? 'Question · marked known' : state.unknown.includes(card.id) ? 'Question · still learning' : undefined} />
|
||||
<FlipCard cardKey={`${state.round}:${state.index}:${card.id}`} front={card.front} back={card.back} hint={card.hint} flipped={flipped} onFlip={flip} onSwipe={seenAnswer && !busy ? grade : undefined} leaving={leaving} burst={burst} footer={renderExtra?.(card)} label={state.known.includes(card.id) ? 'Question · marked known' : state.unknown.includes(card.id) ? 'Question · still learning' : undefined} />
|
||||
)}
|
||||
</main>
|
||||
{!done && card && (
|
||||
|
|
|
|||
|
|
@ -110,6 +110,11 @@ function NotFound() {
|
|||
|
||||
const page = (el: ReactNode) => <Suspense fallback={<PageLoading />}>{el}</Suspense>;
|
||||
|
||||
function ScopedReview() {
|
||||
const { search } = useLocation();
|
||||
return <ReviewPage key={search} />;
|
||||
}
|
||||
|
||||
const router = createBrowserRouter([
|
||||
// Public share links: no login, no app chrome.
|
||||
{ path: '/s/:token', element: page(<SharedPage />), errorElement: <RouteError /> },
|
||||
|
|
@ -129,7 +134,7 @@ const router = createBrowserRouter([
|
|||
{ path: '/quizzes/:quizId', element: page(<QuizPage />) },
|
||||
{ path: '/decks/:deckId', element: page(<DeckPage />) },
|
||||
// Flashcard study keeps the sidebar on desktop and takes the whole screen on phones.
|
||||
{ path: '/review', element: page(<ReviewPage />) },
|
||||
{ path: '/review', element: page(<ScopedReview />) },
|
||||
{ path: '/decks/:deckId/cram', element: page(<CramPage />) },
|
||||
{ path: '/documents/:docId', element: page(<DocumentPage />) },
|
||||
{ path: '/notes/:noteId', element: page(<NotePage />) },
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { BookOpen, Check, ChevronRight, Download, Eye, FolderInput, Layers, MoreHorizontal, Pencil, Printer, Share2, Sparkles, Trash2 } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link, useBlocker, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import { toast } from 'sonner';
|
||||
import { MoveDialog, ShareDialog } from '@/features/dialogs';
|
||||
import { MarkdownArea } from '@/features/editors';
|
||||
|
|
@ -36,6 +36,14 @@ export default function NotePage() {
|
|||
const loaded = useRef('');
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const latest = useRef({ title: '', content: '' });
|
||||
const revision = useRef(0);
|
||||
const savedRevision = useRef(0);
|
||||
const saves = useRef<Promise<boolean>>(Promise.resolve(true));
|
||||
const deleting = useRef(false);
|
||||
const savingNavigation = useRef(false);
|
||||
const blocker = useBlocker(({ currentLocation, nextLocation }) =>
|
||||
!deleting.current && revision.current > savedRevision.current && currentLocation.pathname !== nextLocation.pathname,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (note && loaded.current !== note.id) {
|
||||
|
|
@ -43,39 +51,68 @@ export default function NotePage() {
|
|||
setTitle(note.title);
|
||||
setContent(note.content);
|
||||
latest.current = { title: note.title, content: note.content };
|
||||
revision.current = 0;
|
||||
savedRevision.current = 0;
|
||||
setEditing(Boolean(params.get('edit')) || note.content.trim() === '');
|
||||
if (params.get('edit')) setParams({}, { replace: true });
|
||||
}
|
||||
}, [note, params, setParams]);
|
||||
|
||||
const saveNow = async () => {
|
||||
const saveNow = useCallback(() => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
setStatus('saving');
|
||||
try {
|
||||
await api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content });
|
||||
setStatus('saved');
|
||||
} catch {
|
||||
setStatus('error');
|
||||
}
|
||||
};
|
||||
const version = revision.current;
|
||||
const payload = { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content };
|
||||
// Save in order: a slower, older request must never overwrite a newer edit.
|
||||
saves.current = saves.current.then(async () => {
|
||||
if (savedRevision.current >= version) return true;
|
||||
setStatus('saving');
|
||||
try {
|
||||
await api.patch(`/api/notes/${noteId}`, payload);
|
||||
savedRevision.current = version;
|
||||
setStatus(version === revision.current ? 'saved' : 'dirty');
|
||||
return true;
|
||||
} catch {
|
||||
setStatus('error');
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return saves.current;
|
||||
}, [noteId]);
|
||||
const change = (patch: Partial<{ title: string; content: string }>) => {
|
||||
latest.current = { ...latest.current, ...patch };
|
||||
revision.current += 1;
|
||||
if (patch.title !== undefined) setTitle(patch.title);
|
||||
if (patch.content !== undefined) setContent(patch.content);
|
||||
setStatus('dirty');
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => void saveNow(), 900);
|
||||
};
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) {
|
||||
clearTimeout(timer.current);
|
||||
void api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }).catch(() => undefined);
|
||||
useEffect(() => {
|
||||
if (blocker.state !== 'blocked' || savingNavigation.current) return;
|
||||
savingNavigation.current = true;
|
||||
void saveNow().then((ok) => {
|
||||
savingNavigation.current = false;
|
||||
if (ok && savedRevision.current >= revision.current) blocker.proceed?.();
|
||||
else {
|
||||
blocker.reset?.();
|
||||
toast.error('Your note could not be saved. Stay here and retry when connected.');
|
||||
}
|
||||
},
|
||||
[noteId],
|
||||
);
|
||||
});
|
||||
}, [blocker, saveNow]);
|
||||
useEffect(() => {
|
||||
const warn = (e: BeforeUnloadEvent) => {
|
||||
if (revision.current > savedRevision.current && !deleting.current) {
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', warn);
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', warn);
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (q.isError) return <ErrorState title="Note not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||
if (!q.data || !note) {
|
||||
|
|
@ -94,6 +131,7 @@ export default function NotePage() {
|
|||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
await api.del(`/api/notes/${note.id}`);
|
||||
deleting.current = true;
|
||||
await refresh();
|
||||
navigate(`/classes/${note.classId}`);
|
||||
} catch (e) {
|
||||
|
|
@ -134,6 +172,9 @@ export default function NotePage() {
|
|||
)}
|
||||
</span>
|
||||
)}
|
||||
{editing && status === 'error' && (
|
||||
<button type="button" className="font-medium text-accent underline underline-offset-2" onClick={() => void saveNow()}>Retry save</button>
|
||||
)}
|
||||
{q.data.share?.enabled && (
|
||||
<Badge tone="accent">
|
||||
<Share2 /> Shared
|
||||
|
|
@ -145,8 +186,12 @@ export default function NotePage() {
|
|||
<Segmented
|
||||
label="Mode"
|
||||
value={editing ? 'edit' : 'read'}
|
||||
onChange={(v) => {
|
||||
if (v === 'read' && status !== 'saved') void saveNow().then(() => void refresh(qk.note(noteId)));
|
||||
onChange={async (v) => {
|
||||
if (v === 'read' && status !== 'saved') {
|
||||
const ok = await saveNow();
|
||||
if (!ok || savedRevision.current < revision.current) return;
|
||||
void refresh(qk.note(noteId));
|
||||
}
|
||||
setEditing(v === 'edit');
|
||||
}}
|
||||
options={[
|
||||
|
|
|
|||
|
|
@ -274,6 +274,7 @@ export default function ReviewPage() {
|
|||
hint={current.card.hint}
|
||||
flipped={flipped}
|
||||
onFlip={flip}
|
||||
onSwipe={seenAnswer && !busy ? (known) => void rate(known ? 3 : 1) : undefined}
|
||||
leaving={leaving}
|
||||
burst={burst}
|
||||
footer={ai.data?.ready ? <Explain body={{ kind: 'card', front: current.card.front, back: current.card.back }} /> : undefined}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue