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
28
PROGRESS.md
28
PROGRESS.md
|
|
@ -1,7 +1,8 @@
|
||||||
# Study Desk V2 — progress and resume notes
|
# Study Desk V2 — progress and resume notes
|
||||||
|
|
||||||
Updated 2026-11-11. Branch: **v2**. Original V1: **main**, preserved at `7bd0a9a`.
|
Updated 2026-11-11. Branch: **v2**. Original V1: **main**, preserved at `7bd0a9a`.
|
||||||
Work remains local; no push, repository creation or production deployment has been performed.
|
The owner authorized publishing progress and `v2` now tracks Forgejo `origin/v2`.
|
||||||
|
No production deployment has been performed.
|
||||||
|
|
||||||
## Product and architecture
|
## Product and architecture
|
||||||
|
|
||||||
|
|
@ -45,9 +46,10 @@ The earlier agent manually exercised quiz completion/results, flashcards, streak
|
||||||
mock AI generation through the assistant, editable drafts, and a 375px home page without
|
mock AI generation through the assistant, editable drafts, and a 375px home page without
|
||||||
horizontal overflow. Treat these as historical evidence; record Terra's fresh results below.
|
horizontal overflow. Treat these as historical evidence; record Terra's fresh results below.
|
||||||
|
|
||||||
Not verified: actual Docker image build/runtime, Unraid filesystem permissions and proxy,
|
Docker Desktop is now installed. Image build and a disposable non-root container passed
|
||||||
paid provider inference, real ChatGPT OAuth/eligibility. Docker is not installed here. Do not
|
login, document/card persistence across restart, full-backup ZIP, anonymous sharing and
|
||||||
claim these have been tested. The installable app caches its shell, not private study data;
|
private API denial. Still unverified: Unraid filesystem permissions/proxy, paid-provider
|
||||||
|
inference and real ChatGPT OAuth/eligibility. The installable app caches its shell, not private study data;
|
||||||
full offline administrator study is not implemented.
|
full offline administrator study is not implemented.
|
||||||
|
|
||||||
## Remaining work
|
## Remaining work
|
||||||
|
|
@ -67,9 +69,21 @@ full offline administrator study is not implemented.
|
||||||
3. `npm.cmd run check` (tests require localhost networking for their mock AI server).
|
3. `npm.cmd run check` (tests require localhost networking for their mock AI server).
|
||||||
4. `npm.cmd run dev` for Vite + API, or `npm.cmd run build` then `npm.cmd start` for the built
|
4. `npm.cmd run dev` for Vite + API, or `npm.cmd run build` then `npm.cmd start` for the built
|
||||||
app. See README and .env.example. All automated test databases are disposable copies.
|
app. See README and .env.example. All automated test databases are disposable copies.
|
||||||
5. Keep regular local commits on `v2`. Do not push until the owner explicitly changes the
|
5. Keep focused commits on `v2`. The owner has now authorized pushing progress to this branch;
|
||||||
original local-only instruction. Publishing later can use `git push -u origin v2` after
|
Git Credential Manager works. Never force push or publish/deploy to production implicitly.
|
||||||
reviewing the diff and confirming credentials; no force push is needed.
|
|
||||||
|
## V1 comparison and follow-up usability work
|
||||||
|
|
||||||
|
See `docs/V2-COMPARISON.md` for the requirement matrix, V1 differences and remaining priorities.
|
||||||
|
Fixed the flashcard entrance/exit CSS conflict; restored touch grading and shuffle-remaining;
|
||||||
|
reset review queues on scope changes; serialized note autosaves, protected navigation with
|
||||||
|
unsaved edits and added an explicit retry action. Verified a note survives immediate
|
||||||
|
navigation and reload, and shuffling keeps browse progress at 2/4 rather than restarting.
|
||||||
|
|
||||||
|
The owner's rationale check passed using a synthetic three-question quiz with per-option
|
||||||
|
explanations: correct, incorrect and partial SATA feedback all show explanations inline under
|
||||||
|
their options. Results group explanations with each question. Screenshot is ignored at
|
||||||
|
`.test-data/rationale-check/correct-inline.png`. The temporary test server is stopped after QA.
|
||||||
|
|
||||||
## Fresh UI QA findings
|
## Fresh UI QA findings
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -62,8 +62,9 @@ docker compose up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
Default V2 host port: **3727**, deliberately separate from the old application. Use a separate
|
Default V2 host port: **3727**, deliberately separate from the old application. Use a separate
|
||||||
data folder. Docker is not installed in this VM; image build/runtime checks remain to be run
|
data folder. Docker Desktop image build and disposable-container runtime checks now pass;
|
||||||
on Unraid. No production deployment has been performed.
|
Unraid-specific permissions and reverse-proxy checks remain. No production deployment has
|
||||||
|
been performed.
|
||||||
|
|
||||||
## Verification and resuming work
|
## Verification and resuming work
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -89,8 +89,11 @@ to open a newer schema.
|
||||||
|
|
||||||
## Verification still required on Unraid
|
## Verification still required on Unraid
|
||||||
|
|
||||||
Docker is unavailable in the development VM. Before production use: build the image, confirm
|
Docker Desktop is now installed in the development VM. The image builds, and a disposable
|
||||||
|
container passed non-root startup, login, class/card/document persistence across restart,
|
||||||
|
full ZIP download, anonymous deck sharing and private API denial. These checks used a new
|
||||||
|
test volume, which was removed afterward. Unraid has not been tested. Before production use: confirm
|
||||||
health status and non-root volume permissions, complete setup over HTTPS, upload a PDF and
|
health status and non-root volume permissions, complete setup over HTTPS, upload a PDF and
|
||||||
PPTX, restart and check persistence, test public links from a private browser, confirm proxy
|
PPTX, restart and check persistence, test public links from a private browser, confirm proxy
|
||||||
streaming and upload limits, and perform the restore drill above. The Dockerfile and Compose
|
streaming and upload limits, and perform the restore drill above. The Dockerfile and Compose
|
||||||
configuration are implemented, but container deployment has **not** been executed here.
|
configuration are implemented and verified locally; no production deployment has occurred.
|
||||||
|
|
|
||||||
93
docs/V2-COMPARISON.md
Normal file
93
docs/V2-COMPARISON.md
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
# V2 versus V1 and the rebuild brief
|
||||||
|
|
||||||
|
Source review on 2026-11-11, comparing `main` V1 at 7bd0a9a with local V2.
|
||||||
|
This distinguishes implementation from verification. Passing mocked AI tests does not
|
||||||
|
establish real-provider compatibility, and sampled desktop/mobile QA is not exhaustive.
|
||||||
|
|
||||||
|
## Original requirements
|
||||||
|
|
||||||
|
| Area | Current state |
|
||||||
|
| --- | --- |
|
||||||
|
| New architecture and UI | Rebuilt: React/Vite, Hono, built-in SQLite; distinct responsive light/dark design |
|
||||||
|
| Single administrator and public visitors | Implemented: secure local login, revocable links, isolated visitor progress |
|
||||||
|
| Classes and organization | Classes/folders, edit/move/search/delete, quiz/deck duplication; manual ordering and duplication are not equally exposed for every content type |
|
||||||
|
| Quizzes | MC/SATA, per-option explanations, question rationale, partial credit, practice/exam, shuffle, resume, missed review and history implemented |
|
||||||
|
| Flashcards | Decks, browse/self-assessment, persistent FSRS, reviews, undo and class/deck scoping implemented |
|
||||||
|
| Imports/templates/export | Preview/validation/editing, JSON/text bulk input, reusable templates and exports implemented |
|
||||||
|
| Documents | Required common formats, extraction/chunks/FTS search, optional provider OCR, private storage and AI generation implemented |
|
||||||
|
| AI providers and models | Five adapters, encrypted keys, discovery/manual models, routing/settings/usage; live provider verification remains |
|
||||||
|
| Integrated AI actions | Search/read content, weak-area generation, editable drafts, confirmed modifications implemented |
|
||||||
|
| ChatGPT account | No configured account OAuth. Hosted-client eligibility/approval remains unresolved; conventional API access is available |
|
||||||
|
| Docker/persistence/backups | Single-container image now builds and passes disposable runtime checks; Unraid proxy/volume validation remains |
|
||||||
|
| Accessibility and polish | Keyboard shortcuts, focus styles, reduced-motion rules, responsive layouts and state components exist; full keyboard/screen-reader audit remains |
|
||||||
|
|
||||||
|
The nursing-specific AI features are prompt-based tools using the same single/multi-choice
|
||||||
|
question engine. Dedicated interactive case-study/NGN question types and an adaptive NCLEX
|
||||||
|
exam engine are not implemented; the brief listed additional types as optional.
|
||||||
|
|
||||||
|
## V1 features that are not equivalent in V2
|
||||||
|
|
||||||
|
- **Named spaced-repetition sets:** V1 could collect selected decks into named sets with
|
||||||
|
independent schedules and new-card limits. V2 schedules each card once, with a global
|
||||||
|
daily new-card limit and deck/class/all review scopes. A practical simplification, but
|
||||||
|
it cannot reproduce separate course/exam review sets or independent per-set schedules.
|
||||||
|
- **Manual material order:** V1 supported drag/drop ordering of decks within material groups.
|
||||||
|
V2 class lists sort by recent update or title; the visible drag/drop is for file upload.
|
||||||
|
Some reorder APIs exist without matching UI. Quiz questions do have move-up/down controls.
|
||||||
|
- **Migration fidelity:** V2 imports source content, completed attempts and one selected
|
||||||
|
schedule per card. V1 interrupted StudyProgress sessions, named sets and their independent
|
||||||
|
schedules are not recreated. Historical reviewSnapshotJson is not consumed: imported
|
||||||
|
attempts reconstruct questions from current source content rather than preserving every
|
||||||
|
historical question version. Existing V1 share links are deliberately not reused.
|
||||||
|
|
||||||
|
These are not all mandatory requirements in the rebuild brief, but they matter when replacing
|
||||||
|
a V1 workflow. Extra visual effects should not obscure these functional tradeoffs.
|
||||||
|
|
||||||
|
## Issues found and addressed in this pass
|
||||||
|
|
||||||
|
- Card entrance utility overrode swipe-away CSS. Entrance and exit classes are now mutually
|
||||||
|
exclusive, restoring the intended grading transition.
|
||||||
|
- Added horizontal touch-to-grade after revealing a flashcard, while retaining vertical
|
||||||
|
scrolling. Browse uses learning/known; FSRS uses Again/Good. Desktop buttons/keys remain.
|
||||||
|
- Shuffle now rearranges only remaining cards, retaining completed cards and assessments.
|
||||||
|
Browser check confirmed the session stays at card 2/4 and 25% after shuffling.
|
||||||
|
- Review now remounts when its query scope changes, avoiding a stale deck queue when selecting
|
||||||
|
global Review from a scoped review screen.
|
||||||
|
- Note saves are serialized; navigation/read-mode waits for a successful save, and unsaved
|
||||||
|
changes trigger the browser's unload protection. Verified editing then immediately
|
||||||
|
navigating away and reopening retains the latest text.
|
||||||
|
|
||||||
|
## Rationale check requested by the owner
|
||||||
|
|
||||||
|
Created an isolated three-question quiz with a separate explanation on every option plus
|
||||||
|
each question's overall rationale. Through the actual internal browser, verified a correct
|
||||||
|
single-choice answer, an incorrect single-choice answer and partially correct SATA answer.
|
||||||
|
|
||||||
|
Practice reveals each option's explanation **under that option**, including unselected
|
||||||
|
distractors and missed correct options. The overall rationale follows that question's choices.
|
||||||
|
Results retain the same per-option/per-question grouping. Exam mode intentionally delays
|
||||||
|
feedback until submission. The stored option explanation field is `why`; a legacy import
|
||||||
|
with only a question-level rationale cannot invent separate option explanations.
|
||||||
|
|
||||||
|
Screenshot: ignored local `.test-data/rationale-check/correct-inline.png`.
|
||||||
|
|
||||||
|
## Remaining usability/feature priorities
|
||||||
|
|
||||||
|
1. Restore selected-deck named review collections if replacing that V1 workflow is important.
|
||||||
|
2. Expose consistent ordering and duplication controls across content types.
|
||||||
|
3. Make timed exams use an explicit wall-clock deadline. The current runner is an active-study
|
||||||
|
clock: it pauses when hidden, and server completion does not enforce a deadline.
|
||||||
|
4. Preserve shared quiz question snapshots if scores must remain stable across owner edits;
|
||||||
|
public saved sessions currently rebuild against the latest published quiz content.
|
||||||
|
5. Add better import reporting/preservation for V1 history and interrupted sessions.
|
||||||
|
6. Improve large scanned-document OCR: currently sent as one native vision/PDF request with
|
||||||
|
a 30 MB scanned-PDF limit and an output cap, rather than paginated OCR. Lexical retrieval
|
||||||
|
and sampled long-document generation are implemented; comprehensive textbook coverage
|
||||||
|
and semantic matching are not guaranteed.
|
||||||
|
7. Full offline private studying, rich-text WYSIWYG authoring, study-plan generation and
|
||||||
|
additional case/question types remain optional future enhancements.
|
||||||
|
|
||||||
|
No obvious missing basic flip/streak/quiz-answer feedback remains by source review. Visual
|
||||||
|
polish still needs targeted long-content/mobile/empty/error-state passes beyond the sampled
|
||||||
|
screens already checked. Prioritize those user-visible improvements over expanding a test
|
||||||
|
count for its own sake.
|
||||||
|
|
@ -99,6 +99,7 @@ export function FlipCard({
|
||||||
footer,
|
footer,
|
||||||
leaving,
|
leaving,
|
||||||
burst,
|
burst,
|
||||||
|
onSwipe,
|
||||||
}: {
|
}: {
|
||||||
front: string;
|
front: string;
|
||||||
back: string;
|
back: string;
|
||||||
|
|
@ -113,15 +114,19 @@ export function FlipCard({
|
||||||
/** Plays the swipe-away animation used when a card is graded. */
|
/** Plays the swipe-away animation used when a card is graded. */
|
||||||
leaving?: 'left' | 'right' | null;
|
leaving?: 'left' | 'right' | null;
|
||||||
burst?: { streak: number; tier: StreakTier; id: number } | 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 [showHint, setShowHint] = useState(false);
|
||||||
|
const touch = useRef<{ x: number; y: number } | null>(null);
|
||||||
|
const suppressClick = useRef(false);
|
||||||
useEffect(() => setShowHint(false), [cardKey]);
|
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';
|
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.
|
// Short answers read best large and centred; long ones as normal text.
|
||||||
const size = (text: string) =>
|
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]';
|
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 (
|
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. */}
|
{/* The whole card is the flip target, on both sides. Space, Enter and the arrow keys do the same. */}
|
||||||
<div
|
<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"
|
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"
|
role="button"
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
aria-label={flipped ? 'Flashcard, answer side. Activate to show the question.' : 'Flashcard, question side. Activate to show the answer.'}
|
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={cx(face, 'flip-front')} inert={flipped ? true : undefined}>
|
||||||
<div className="flex items-center justify-between px-6 pt-5">
|
<div className="flex items-center justify-between px-6 pt-5">
|
||||||
|
|
@ -324,6 +353,14 @@ export function CramSession({
|
||||||
reset();
|
reset();
|
||||||
onState(freshCramState(cards, shuffled));
|
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 = () => {
|
const studyUnknown = () => {
|
||||||
reset();
|
reset();
|
||||||
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1));
|
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">
|
<span className="num text-[13px] font-medium text-ink-2">
|
||||||
{Math.min(state.index + 1, total)}/{total}
|
{Math.min(state.index + 1, total)}/{total}
|
||||||
</span>
|
</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 />
|
<Shuffle />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</>
|
</>
|
||||||
|
|
@ -390,7 +427,7 @@ export function CramSession({
|
||||||
</div>
|
</div>
|
||||||
</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>
|
</main>
|
||||||
{!done && card && (
|
{!done && card && (
|
||||||
|
|
|
||||||
|
|
@ -110,6 +110,11 @@ function NotFound() {
|
||||||
|
|
||||||
const page = (el: ReactNode) => <Suspense fallback={<PageLoading />}>{el}</Suspense>;
|
const page = (el: ReactNode) => <Suspense fallback={<PageLoading />}>{el}</Suspense>;
|
||||||
|
|
||||||
|
function ScopedReview() {
|
||||||
|
const { search } = useLocation();
|
||||||
|
return <ReviewPage key={search} />;
|
||||||
|
}
|
||||||
|
|
||||||
const router = createBrowserRouter([
|
const router = createBrowserRouter([
|
||||||
// Public share links: no login, no app chrome.
|
// Public share links: no login, no app chrome.
|
||||||
{ path: '/s/:token', element: page(<SharedPage />), errorElement: <RouteError /> },
|
{ path: '/s/:token', element: page(<SharedPage />), errorElement: <RouteError /> },
|
||||||
|
|
@ -129,7 +134,7 @@ const router = createBrowserRouter([
|
||||||
{ path: '/quizzes/:quizId', element: page(<QuizPage />) },
|
{ path: '/quizzes/:quizId', element: page(<QuizPage />) },
|
||||||
{ path: '/decks/:deckId', element: page(<DeckPage />) },
|
{ path: '/decks/:deckId', element: page(<DeckPage />) },
|
||||||
// Flashcard study keeps the sidebar on desktop and takes the whole screen on phones.
|
// 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: '/decks/:deckId/cram', element: page(<CramPage />) },
|
||||||
{ path: '/documents/:docId', element: page(<DocumentPage />) },
|
{ path: '/documents/:docId', element: page(<DocumentPage />) },
|
||||||
{ path: '/notes/:noteId', element: page(<NotePage />) },
|
{ path: '/notes/:noteId', element: page(<NotePage />) },
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { BookOpen, Check, ChevronRight, Download, Eye, FolderInput, Layers, MoreHorizontal, Pencil, Printer, Share2, Sparkles, Trash2 } from 'lucide-react';
|
import { BookOpen, Check, ChevronRight, Download, Eye, FolderInput, Layers, MoreHorizontal, Pencil, Printer, Share2, Sparkles, Trash2 } from 'lucide-react';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
import { Link, useBlocker, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { MoveDialog, ShareDialog } from '@/features/dialogs';
|
import { MoveDialog, ShareDialog } from '@/features/dialogs';
|
||||||
import { MarkdownArea } from '@/features/editors';
|
import { MarkdownArea } from '@/features/editors';
|
||||||
|
|
@ -36,6 +36,14 @@ export default function NotePage() {
|
||||||
const loaded = useRef('');
|
const loaded = useRef('');
|
||||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
const latest = useRef({ title: '', content: '' });
|
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(() => {
|
useEffect(() => {
|
||||||
if (note && loaded.current !== note.id) {
|
if (note && loaded.current !== note.id) {
|
||||||
|
|
@ -43,39 +51,68 @@ export default function NotePage() {
|
||||||
setTitle(note.title);
|
setTitle(note.title);
|
||||||
setContent(note.content);
|
setContent(note.content);
|
||||||
latest.current = { title: note.title, content: note.content };
|
latest.current = { title: note.title, content: note.content };
|
||||||
|
revision.current = 0;
|
||||||
|
savedRevision.current = 0;
|
||||||
setEditing(Boolean(params.get('edit')) || note.content.trim() === '');
|
setEditing(Boolean(params.get('edit')) || note.content.trim() === '');
|
||||||
if (params.get('edit')) setParams({}, { replace: true });
|
if (params.get('edit')) setParams({}, { replace: true });
|
||||||
}
|
}
|
||||||
}, [note, params, setParams]);
|
}, [note, params, setParams]);
|
||||||
|
|
||||||
const saveNow = async () => {
|
const saveNow = useCallback(() => {
|
||||||
if (timer.current) clearTimeout(timer.current);
|
if (timer.current) clearTimeout(timer.current);
|
||||||
timer.current = null;
|
timer.current = null;
|
||||||
setStatus('saving');
|
const version = revision.current;
|
||||||
try {
|
const payload = { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content };
|
||||||
await api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content });
|
// Save in order: a slower, older request must never overwrite a newer edit.
|
||||||
setStatus('saved');
|
saves.current = saves.current.then(async () => {
|
||||||
} catch {
|
if (savedRevision.current >= version) return true;
|
||||||
setStatus('error');
|
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 }>) => {
|
const change = (patch: Partial<{ title: string; content: string }>) => {
|
||||||
latest.current = { ...latest.current, ...patch };
|
latest.current = { ...latest.current, ...patch };
|
||||||
|
revision.current += 1;
|
||||||
if (patch.title !== undefined) setTitle(patch.title);
|
if (patch.title !== undefined) setTitle(patch.title);
|
||||||
if (patch.content !== undefined) setContent(patch.content);
|
if (patch.content !== undefined) setContent(patch.content);
|
||||||
setStatus('dirty');
|
setStatus('dirty');
|
||||||
if (timer.current) clearTimeout(timer.current);
|
if (timer.current) clearTimeout(timer.current);
|
||||||
timer.current = setTimeout(() => void saveNow(), 900);
|
timer.current = setTimeout(() => void saveNow(), 900);
|
||||||
};
|
};
|
||||||
useEffect(
|
useEffect(() => {
|
||||||
() => () => {
|
if (blocker.state !== 'blocked' || savingNavigation.current) return;
|
||||||
if (timer.current) {
|
savingNavigation.current = true;
|
||||||
clearTimeout(timer.current);
|
void saveNow().then((ok) => {
|
||||||
void api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }).catch(() => undefined);
|
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.isError) return <ErrorState title="Note not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
|
||||||
if (!q.data || !note) {
|
if (!q.data || !note) {
|
||||||
|
|
@ -94,6 +131,7 @@ export default function NotePage() {
|
||||||
if (timer.current) clearTimeout(timer.current);
|
if (timer.current) clearTimeout(timer.current);
|
||||||
timer.current = null;
|
timer.current = null;
|
||||||
await api.del(`/api/notes/${note.id}`);
|
await api.del(`/api/notes/${note.id}`);
|
||||||
|
deleting.current = true;
|
||||||
await refresh();
|
await refresh();
|
||||||
navigate(`/classes/${note.classId}`);
|
navigate(`/classes/${note.classId}`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
@ -134,6 +172,9 @@ export default function NotePage() {
|
||||||
)}
|
)}
|
||||||
</span>
|
</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 && (
|
{q.data.share?.enabled && (
|
||||||
<Badge tone="accent">
|
<Badge tone="accent">
|
||||||
<Share2 /> Shared
|
<Share2 /> Shared
|
||||||
|
|
@ -145,8 +186,12 @@ export default function NotePage() {
|
||||||
<Segmented
|
<Segmented
|
||||||
label="Mode"
|
label="Mode"
|
||||||
value={editing ? 'edit' : 'read'}
|
value={editing ? 'edit' : 'read'}
|
||||||
onChange={(v) => {
|
onChange={async (v) => {
|
||||||
if (v === 'read' && status !== 'saved') void saveNow().then(() => void refresh(qk.note(noteId)));
|
if (v === 'read' && status !== 'saved') {
|
||||||
|
const ok = await saveNow();
|
||||||
|
if (!ok || savedRevision.current < revision.current) return;
|
||||||
|
void refresh(qk.note(noteId));
|
||||||
|
}
|
||||||
setEditing(v === 'edit');
|
setEditing(v === 'edit');
|
||||||
}}
|
}}
|
||||||
options={[
|
options={[
|
||||||
|
|
|
||||||
|
|
@ -274,6 +274,7 @@ export default function ReviewPage() {
|
||||||
hint={current.card.hint}
|
hint={current.card.hint}
|
||||||
flipped={flipped}
|
flipped={flipped}
|
||||||
onFlip={flip}
|
onFlip={flip}
|
||||||
|
onSwipe={seenAnswer && !busy ? (known) => void rate(known ? 3 : 1) : undefined}
|
||||||
leaving={leaving}
|
leaving={leaving}
|
||||||
burst={burst}
|
burst={burst}
|
||||||
footer={ai.data?.ready ? <Explain body={{ kind: 'card', front: current.card.front, back: current.card.back }} /> : undefined}
|
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