Phase 12 + 13: collocation coach + vocabulary garden
Phase 12 — collocation coach: a third suggestion family for gentle
"natives usually say…" hints on non-native word pairings, reusing the
existing runPass/pendingScope/rail machinery.
- llm/collocation.go (RunCollocation, 25s floor, reuses ParseCheckpoint)
+ collocationSystemPrompt/CollocationMessages (warm, Mandarin gloss,
defers grammar/spelling to the grammar family)
- migration 0005 rebuilds the suggestions table to extend the type CHECK
(SQLite can't ALTER a CHECK)
- collocationScope + CollocationLimit + POST /{id}/collocation
- fix: grammarScope was `type != 'voice'` and would wipe the new
collocation flags; now `type NOT IN ('voice','collocation')`
- frontend: --color-blossom, "Make it sound natural 🌸" pill,
collocating/runCollocation in useCheckpoint, StatusBar dot
Phase 13 — vocabulary garden: capture looked-up words and surface them
for gentle spaced repetition.
- new internal/vocab package: migration 0006 (vocab_words, SM-2-lite
columns, doc_id ON DELETE SET NULL, UNIQUE(user_id,word)),
scheduler.go (Leitner ladder 1/3/7/16/35 then geometric; gentle
"again", no streak-shaming), handlers (capture-upsert/list/due/
review/delete, owner-scoped, SQLite-side datetime math)
- auto-capture on word lookup (dictionary-known words only, captures
the surrounding sentence + doc_id) + 🤍/💚 toggle on WordCard
- GardenPanel: blossom grid (bloom by reps), flashcard review (sentence
blanked, flip, again/good/easy, recognition↔production), sleepy-kitten
footer; opened from a global 🌷 header button
Tests: TestCollocationPassCoexists, vocab scheduler + handlers, db CHECK
extended. go build/vet/test + tsc + vite + vitest (51/51) clean;
migration verified against a copy of the live DB; live backend smoke
walked the full vocab lifecycle + the warm-502 collocation path.
Claude-Session: https://claude.ai/code/session_016Yr6jELuRc7hyzYLccQKZd
This commit is contained in:
@@ -105,25 +105,25 @@ Multi-session build. **Source of truth for what's done and what's next.** Update
|
|||||||
- [x] **English phonetic (pivot from pinyin)** — for a native-Mandarin English learner the useful pronunciation aid is the English IPA, not pinyin (she reads Chinese fluently). `scripts/build_phonetic.py` extracts ECDICT's `phonetic` column (same source/freq-gate as the gloss); `phonetic.json.gz` embedded + lazily loaded; `Result.Phonetic` resolved via the same de-inflecting candidate walk; shown as `/ˈrɪvər/` in the WordCard. **Full dataset built from ECDICT: 46,579 words (361KB gz)**, in line with the other lexicon assets. The script also has a `--seed` mode (71 curated common words) that ships as a fallback / works without the csv. Curated seed entries (clean IPA) override the ECDICT form where both exist.
|
- [x] **English phonetic (pivot from pinyin)** — for a native-Mandarin English learner the useful pronunciation aid is the English IPA, not pinyin (she reads Chinese fluently). `scripts/build_phonetic.py` extracts ECDICT's `phonetic` column (same source/freq-gate as the gloss); `phonetic.json.gz` embedded + lazily loaded; `Result.Phonetic` resolved via the same de-inflecting candidate walk; shown as `/ˈrɪvər/` in the WordCard. **Full dataset built from ECDICT: 46,579 words (361KB gz)**, in line with the other lexicon assets. The script also has a `--seed` mode (71 curated common words) that ships as a fallback / works without the csv. Curated seed entries (clean IPA) override the ECDICT form where both exist.
|
||||||
- Verified: go build/vet/test (incl. new `TestExportAll`), tsc, vite build all clean; live smoke vs throwaway binaries — `/word/river|running|serendipity|rivers` all return phonetic (`rivers`→`river` de-inflected), export-all returns a valid 2-entry zip with de-duped CJK filenames + dated name, route doesn't collide with `/{id}`.
|
- Verified: go build/vet/test (incl. new `TestExportAll`), tsc, vite build all clean; live smoke vs throwaway binaries — `/word/river|running|serendipity|rivers` all return phonetic (`rivers`→`river` de-inflected), export-all returns a valid 2-entry zip with de-duped CJK filenames + dated name, route doesn't collide with `/{id}`.
|
||||||
|
|
||||||
### Phase 12 — Collocation coach 🔜 (planned 2026-06-26)
|
### Phase 12 — Collocation coach ✅ (2026-06-26)
|
||||||
**Why:** ESL writers nail grammar but miss *which words go together* — "do a decision" → "make a decision", "strong rain" → "heavy rain". These aren't *wrong*, so the grammar pass won't flag them; they're just non-native. Gentle "natives usually say…" hints are the single highest-leverage upgrade for making her writing sound native. **Build this first** — it's small and de-risks the migration-rebuild pattern Phase 13 also needs.
|
**Why:** ESL writers nail grammar but miss *which words go together* — "do a decision" → "make a decision", "strong rain" → "heavy rain". These aren't *wrong*, so the grammar pass won't flag them; they're just non-native. Gentle "natives usually say…" hints are the single highest-leverage upgrade for making her writing sound native. **Build this first** — it's small and de-risks the migration-rebuild pattern Phase 13 also needs.
|
||||||
|
|
||||||
**Key insight:** the suggestion pipeline is already generic over a `pass` + a `pendingScope` "family" (`runPass` in `internal/suggestions/handlers.go`; grammar + voice already prove it). Collocation drops in as a **third family** and reuses the entire accept/dismiss/re-anchoring/rail/Mandarin-explanation machinery — no new frontend rendering layer.
|
**Key insight:** the suggestion pipeline is already generic over a `pass` + a `pendingScope` "family" (`runPass` in `internal/suggestions/handlers.go`; grammar + voice already prove it). Collocation drops in as a **third family** and reuses the entire accept/dismiss/re-anchoring/rail/Mandarin-explanation machinery — no new frontend rendering layer.
|
||||||
- [ ] `internal/llm/collocation.go` — `CollocationInterval` (~25s) + `RunCollocation(...)`, reusing the existing `ParseCheckpoint` parser (same as `RunVoice`). No new parsing.
|
- [x] `internal/llm/collocation.go` — `CollocationInterval` (25s) + `RunCollocation(...)`, reusing the existing `ParseCheckpoint` parser (same as `RunVoice`). Whole-document (no `TruncateDoc`), tone passed through.
|
||||||
- [ ] `internal/llm/prompts.go` — `CollocationMessages(contentText, tone)`. **This prompt is the whole feature**: flag only non-wrong-but-non-native word pairings; explicitly defer real grammar errors to the grammar family; phrase every explanation as warm "natives usually say…" with a Mandarin gloss — never "error/wrong".
|
- [x] `internal/llm/prompts.go` — `CollocationMessages(contentText, tone)` + `collocationSystemPrompt`. The prompt flags only non-wrong-but-non-native word pairings ("do a decision" → "make a decision"), explicitly defers grammar/spelling to the grammar family, and frames every explanation as warm "Natives usually say…" with a Mandarin gloss — never "error/wrong/mistake".
|
||||||
- [ ] `internal/db/models.go` + migration `0005` — new suggestion type `collocation`. ⚠️ The `type` column has a `CHECK(...)` and **SQLite can't `ALTER` a CHECK** → migration must **rebuild** the `suggestions` table (create new w/ extended CHECK, copy rows, drop, rename, recreate `idx_suggestions_doc_id`). Not a one-line ALTER.
|
- [x] `internal/db/models.go` (`SuggestionTypeCollocation`) + migration `0005_collocation_suggestion_type` — **rebuilds** the `suggestions` table (new table w/ extended CHECK, copy rows, drop, rename, recreate `idx_suggestions_doc_id`), since SQLite can't `ALTER` a CHECK. Verified against a copy of the live DB (5 migrations apply cleanly, collocation insert accepted, rows preserved).
|
||||||
- [ ] `internal/suggestions/handlers.go` — add `collocationScope` (`deleteWhere: "type = 'collocation'"`, `forceType: collocation`), a `CollocationLimit` on `Handler` (+ wire in `New`), register `POST /{id}/collocation`. Mirrors `voice`, ~15 lines. Also extend `normalizeType` to accept the new type.
|
- [x] `internal/suggestions/handlers.go` — `collocationScope` (`deleteWhere: "type = 'collocation'"`, `forceType: collocation`), `CollocationLimit` on `Handler` (+ wired in `New`), `POST /{id}/collocation`, `normalizeType` extended. **Also fixed `grammarScope`** from `type != 'voice'` → `type NOT IN ('voice','collocation')` so a grammar checkpoint no longer wipes the collocation pending flags (the third family must survive like voice does).
|
||||||
- [ ] Frontend: `suggestionMeta.ts` collocation entry (💡 icon + its own warm color so cards read as friendly tips); `client.ts` `collocation(docId)`; a gentle trigger like the existing "Check my voice" pill — **"Make it sound natural 🌸"** — rendering straight into `SuggestionRail`/`SuggestionCard`.
|
- [x] Frontend: `suggestionMeta.ts` collocation entry (`--color-blossom` warm pink, "Word pairing" label); `client.ts` `collocationDoc(docId)` + `SuggestionType` extended; `index.css` token + `.petal-suggestion-collocation` decoration; `useCheckpoint` `collocating`/`runCollocation` (mirrors `runVoice`, shares the run-token guard); `Toolbar` blossom **"Make it sound natural 🌸"** pill (→ "Reading…"); `StatusBar` breathing blossom dot "Finding natural phrasing…"; threaded through `EditorCore`/`App`. Renders straight into the existing `SuggestionRail`/`SuggestionCard` (Accept applies the native pairing).
|
||||||
- [ ] Verify via the millenia UI-test harness (real-browser editor check) + go/tsc/vite clean. **Est. ~½ day** (mostly the new prompt + the table-rebuild migration).
|
- [x] Verified: go build/vet/test (`TestCollocationPassCoexists` — three families coexist, grammar checkpoint doesn't wipe voice/collocation), tsc, vite build, vitest 51/51 all clean; live smoke vs the binary (dead LLM) → collocation route returns the warm 502 like check/voice.
|
||||||
|
|
||||||
### Phase 13 — Vocabulary garden (spaced repetition) 🔜 (planned 2026-06-26)
|
### Phase 13 — Vocabulary garden (spaced repetition) ✅ (2026-06-26)
|
||||||
**Why:** the lexicon (`internal/lexicon`) is a stateless static-dataset lookup — **nothing records which words she's looked up.** Capturing them turns passive lookups into real vocabulary, and the review surface ties straight into the "petal garden" delight idea (words become blossoms; the sleeping kitten naps among them). Build **after** Phase 12.
|
**Why:** the lexicon (`internal/lexicon`) is a stateless static-dataset lookup — **nothing records which words she's looked up.** Capturing them turns passive lookups into real vocabulary, and the review surface ties straight into the "petal garden" delight idea (words become blossoms; the sleeping kitten naps among them). Build **after** Phase 12.
|
||||||
- [ ] New `internal/vocab` package + migration `0005`/`0006` — `vocab_words` table: `word, gloss, phonetic, example` (sentence captured at lookup for context), `doc_id`, + SM-2-lite scheduling: `due_at, interval_days, ease, reps, lapses, last_reviewed`; `UNIQUE(user_id, word)`.
|
- [x] New `internal/vocab` package + migration `0006_vocab_garden` (0005 was taken by collocation) — `vocab_words` table: `word, gloss, phonetic, example` (sentence captured at lookup), `doc_id` (`ON DELETE SET NULL` so a word outlives its source doc), + SM-2-lite scheduling: `due_at, interval_days, ease, reps, lapses, last_reviewed`; `UNIQUE(user_id, word)` + `idx_vocab_due`.
|
||||||
- [ ] Auto-capture: when `WordCard` calls `lookupWord`, also fire `POST /api/vocab` (upsert; new word → `due_at = now + 1 day`). Looking words up *is* the data source — zero extra effort from her.
|
- [x] Auto-capture: `EditorCore.openWordLookup` fires `POST /api/vocab` after a successful lookup — **only for words the dictionary actually knows** (a real gloss or definition), so typos/proper-noun lookups don't clutter the garden. Captures the surrounding sentence (`sentenceAround`) + `doc_id`. Idempotent upsert: re-looking-up a word refreshes its gloss/phonetic/example but never resets its schedule.
|
||||||
- [ ] Endpoints: `POST /api/vocab` (record/upsert), `GET /api/vocab/due` (cards due now), `POST /api/vocab/{id}/review` (grade again/good/easy → reschedule), `GET /api/vocab` (full garden), `DELETE /api/vocab/{id}`.
|
- [x] Endpoints (`internal/vocab/handlers.go`): `POST /api/vocab` (upsert; new word → `due_at = datetime('now','+1 day')`), `GET /api/vocab/due` (due now, server-side `datetime('now')` comparison — avoids JS local-vs-UTC parsing bugs), `POST /api/vocab/{id}/review` (grade → reschedule via `datetime('now','+N days')`), `GET /api/vocab` (full garden), `DELETE /api/vocab/{id}`. All owner-scoped.
|
||||||
- [ ] SR scheduler: gentle SM-2-lite / Leitner intervals (1d → 3d → 7d → 16d → 35d). No streak-shaming. This is the only genuinely new logic.
|
- [x] SR scheduler (`internal/vocab/scheduler.go`): gentle SM-2-lite / Leitner ladder (1d → 3d → 7d → 16d → 35d, then geometric by ease). "again" steps back to 1d + counts a lapse + nudges ease down (floored at 1.3) — no harsh wipe; "good" climbs one rung; "easy" climbs a rung and a bit more + raises ease. No streaks to break.
|
||||||
- [ ] Frontend Garden panel (sibling to `HistoryPanel`/`DocList`): each learned word a blossom, more reps → more bloomed; the `PetalCompanion` kitten naps among them. Flashcard review: captured sentence with the word blanked → recall → EN↔中文 flip → again/good/easy (direction flips for recognition *and* production). A 🤍 "save to garden" on `WordCard` for explicit saves alongside auto-capture.
|
- [x] Frontend `GardenPanel` (slide-over drawer, sibling to `HistoryPanel`): each word a blossom that opens further with reps (🌱→🌿→🌷→🌸→🌺); a "复习 N 个词 · Review N due" button; per-word detail (phonetic/example/source-doc/remove); footer "🐱💤 N 朵花在花园里" — the sleepy kitten napping among the blossoms. **Flashcard review**: due queue, the example sentence with the word blanked (`blankOut`), flip to reveal word+phonetic+gloss+sentence, again/good/easy grades; **direction alternates** by cursor parity for recognition (EN→中文) *and* production (中文→EN). A 🤍/💚 "save to garden" toggle on `WordCard` alongside the silent auto-capture. Opened from a global 🌷 词汇花园 button in the app header. All copy bilingual zh-first.
|
||||||
- [ ] Verify via the millenia UI-test harness + go/tsc/vite clean. **Est. ~1½–2 days** (new package + table + panel/review UI; reuses existing panel/companion patterns).
|
- [x] Verified: go build/vet/test (`scheduler_test.go` — ladder/again-gentle/easy-further; `handlers_test.go` — capture/upsert/due/review/delete lifecycle + empty-word 400 + doc-delete SET NULL), tsc, vite build, vitest 51/51 all clean; live smoke vs the binary (throwaway DB) — full capture→list→due→review→delete flow + 400 on bad grade verified end-to-end.
|
||||||
|
|
||||||
### Phase 14 — Companion warmth + bedtime nag + night mode ✅
|
### Phase 14 — Companion warmth + bedtime nag + night mode ✅
|
||||||
**Why:** the companion kitten is the heart of Petal's "built for her" feel. Three additions: (1) a wider, fresher pool of **encouraging phrases** so cheers don't repeat as quickly; (2) when she's still writing **late at night (≥11pm)**, the kitten gently nags her to go to bed; (3) at the same hour the whole app drifts into a calm **night mode** — dark moonlit theme + the falling petals become **falling stars**. Caring, never scolding — the sleepy-cat gag makes "you should be sleeping too 🐱💤" land perfectly. Self-contained, frontend-only.
|
**Why:** the companion kitten is the heart of Petal's "built for her" feel. Three additions: (1) a wider, fresher pool of **encouraging phrases** so cheers don't repeat as quickly; (2) when she's still writing **late at night (≥11pm)**, the kitten gently nags her to go to bed; (3) at the same hour the whole app drifts into a calm **night mode** — dark moonlit theme + the falling petals become **falling stars**. Caring, never scolding — the sleepy-cat gag makes "you should be sleeping too 🐱💤" land perfectly. Self-contained, frontend-only.
|
||||||
@@ -142,11 +142,12 @@ Multi-session build. **Source of truth for what's done and what's next.** Update
|
|||||||
### Next-up (post-v1 product, agreed with user 2026-06-26)
|
### Next-up (post-v1 product, agreed with user 2026-06-26)
|
||||||
- [x] **Phase 9 — ESL superpowers**: inline Chinese gloss on hover/select; "say it more naturally" / tone-rewrite. ✅ (see Phase 9 above)
|
- [x] **Phase 9 — ESL superpowers**: inline Chinese gloss on hover/select; "say it more naturally" / tone-rewrite. ✅ (see Phase 9 above)
|
||||||
- [x] **Phase 10 — organization & polish**: cross-doc search, tags, tablet/touch polish, warm LLM-down failure states. ✅ (see Phase 10 above; "tags only" chosen over folders, FTS5 over LIKE)
|
- [x] **Phase 10 — organization & polish**: cross-doc search, tags, tablet/touch polish, warm LLM-down failure states. ✅ (see Phase 10 above; "tags only" chosen over folders, FTS5 over LIKE)
|
||||||
- [ ] **Phase 12 — collocation coach**: gentle "natives usually say…" hints for non-native word pairings, as a third suggestion family. 🔜 (see Phase 12 above; build first)
|
- [x] **Phase 12 — collocation coach**: gentle "natives usually say…" hints for non-native word pairings, as a third suggestion family. ✅ (see Phase 12 above)
|
||||||
- [ ] **Phase 13 — vocabulary garden**: spaced-repetition review built from looked-up words, surfaced as a blooming garden. 🔜 (see Phase 13 above)
|
- [x] **Phase 13 — vocabulary garden**: spaced-repetition review built from looked-up words, surfaced as a blooming garden. ✅ (see Phase 13 above)
|
||||||
- [x] **Phase 14 — companion warmth + bedtime nag + night mode**: more encouraging phrases, a gentle "go to bed" nudge after 11pm, and a calm dark theme + falling stars at night. ✅ (see Phase 14 above)
|
- [x] **Phase 14 — companion warmth + bedtime nag + night mode**: more encouraging phrases, a gentle "go to bed" nudge after 11pm, and a calm dark theme + falling stars at night. ✅ (see Phase 14 above)
|
||||||
|
|
||||||
## Session log
|
## Session log
|
||||||
|
- 2026-06-26: **Phases 12 + 13 complete** (collocation coach + vocabulary garden — "finish the rest of the build plan except Authentik/Traefik"). **Phase 12**: collocation drops in as a third suggestion family reusing the whole `runPass`/`pendingScope` machinery — `llm/collocation.go` (`RunCollocation`, 25s floor, reuses `ParseCheckpoint`), `collocationSystemPrompt`/`CollocationMessages` (warm "Natives usually say…" + Mandarin gloss, defers grammar elsewhere), migration `0005` **rebuilds** the suggestions table to extend the `type` CHECK (SQLite can't ALTER a CHECK), `collocationScope` + `CollocationLimit` + `POST /{id}/collocation`. **Caught a latent bug**: `grammarScope` was `type != 'voice'` → would wipe collocation flags; fixed to `type NOT IN ('voice','collocation')`. Frontend: `--color-blossom` pink, "Make it sound natural 🌸" toolbar pill, `collocating`/`runCollocation` in `useCheckpoint`, StatusBar dot — all into the existing rail/card. **Phase 13**: new `internal/vocab` package — migration `0006_vocab_garden` (`vocab_words`, SM-2-lite columns, doc_id `ON DELETE SET NULL`, `UNIQUE(user_id,word)`), `scheduler.go` (Leitner ladder 1/3/7/16/35 → geometric; gentle "again", no streak-shaming), `handlers.go` (capture-upsert/list/due/review/delete, all owner-scoped, time math via SQLite `datetime()` so stored values stay canonical-UTC). Auto-capture wired into `EditorCore.openWordLookup` (only dictionary-known words, captures the surrounding sentence + doc_id) + a 🤍/💚 toggle on `WordCard`. `GardenPanel` slide-over: blossom grid (bloom stage by reps), flashcard review (sentence blanked, flip, again/good/easy, direction alternates recognition↔production), sleepy-kitten footer; opened from a global 🌷 header button. Tests: `TestCollocationPassCoexists`, vocab `scheduler_test.go` + `handlers_test.go`, db CHECK test extended. go build/vet/test + tsc + vite + vitest (51/51) all clean; migration verified against a copy of the live DB; live backend smoke (throwaway DB) walked the full vocab lifecycle + the warm-502 collocation path. **Remaining: only the deferred infra bucket** — Authentik auth, Copyleaks Tier-2 (needs a public webhook), Docker/Traefik/deploy — all on hold per the user's "except Authentik/Traefik".
|
||||||
- 2026-06-26: **Phase 14 complete** (companion warmth + bedtime nag + night mode). `tips.ts`: `ENCOURAGEMENTS` 5→10 lines; new `BEDTIME` array (4 lines, user-supplied English wit + gentle Mandarin leads). `useCompanion.ts`: bedtime branch in the 10s heartbeat (after idle-return + break, before the generic tip); only nudges while actively writing; own `lastBedtime` ref + 30min `BEDTIME_GAP`, respects `PROACTIVE_GAP`; new `'bedtime'` `BubbleTone` lingers ~4s longer. **Night mode** (added same session, user request): `lib/night.ts` centralizes `isBedtime()` + window (now shared by the nag too); `hooks/useNightMode.ts` toggles `petal-night` on `<html>` (60s re-check); `index.css` `html.petal-night` re-points only the palette tokens → whole UI flips via `var()` (no component edits), 600ms dusk fade, print stays white; `PetalFall` gains a `night` prop → chunky cartoon power stars (`makeCartoonStar`, Mario/Kirby-style, 5 candy colors) mixed ~70/30 with small twinkle sparkles, gentle spin + shallow shimmer, effect re-inits on flip; App: `useNightMode()` → `<PetalFall night={night}/>`. tsc + vite clean, companion vitest 45/45; verified with real-browser Playwright screenshots (clock mocked to 23:30) — day petals/cream vs night stars/dark-plum, both pretty. Bedtime window is `BEDTIME_FROM`/`BEDTIME_TO` (local clock) for easy retune.
|
- 2026-06-26: **Phase 14 complete** (companion warmth + bedtime nag + night mode). `tips.ts`: `ENCOURAGEMENTS` 5→10 lines; new `BEDTIME` array (4 lines, user-supplied English wit + gentle Mandarin leads). `useCompanion.ts`: bedtime branch in the 10s heartbeat (after idle-return + break, before the generic tip); only nudges while actively writing; own `lastBedtime` ref + 30min `BEDTIME_GAP`, respects `PROACTIVE_GAP`; new `'bedtime'` `BubbleTone` lingers ~4s longer. **Night mode** (added same session, user request): `lib/night.ts` centralizes `isBedtime()` + window (now shared by the nag too); `hooks/useNightMode.ts` toggles `petal-night` on `<html>` (60s re-check); `index.css` `html.petal-night` re-points only the palette tokens → whole UI flips via `var()` (no component edits), 600ms dusk fade, print stays white; `PetalFall` gains a `night` prop → chunky cartoon power stars (`makeCartoonStar`, Mario/Kirby-style, 5 candy colors) mixed ~70/30 with small twinkle sparkles, gentle spin + shallow shimmer, effect re-inits on flip; App: `useNightMode()` → `<PetalFall night={night}/>`. tsc + vite clean, companion vitest 45/45; verified with real-browser Playwright screenshots (clock mocked to 23:30) — day petals/cream vs night stars/dark-plum, both pretty. Bedtime window is `BEDTIME_FROM`/`BEDTIME_TO` (local clock) for easy retune.
|
||||||
- 2026-06-26: **Phase 11 complete** (writer power-ups, batch requested as "do it all"). Seven features: (1) in-doc **Find & Replace** — `SearchHighlight` decoration extension + `FindReplace` bar (Ctrl/Cmd+F, match-case, replace-all back-to-front, DOM scroll that doesn't trigger the selection bubble); (2) **read-aloud** Web Speech util + 🔊 in WordCard & selection bubble; (3) **keyboard/touch access** — Ctrl/Cmd+D caret lookup, Ctrl/Cmd+J rewrite, touch long-press (refactored `handleContextMenu` → shared `openWordLookup(pos)`); (4) **export-all** backup zip (`GET /api/docs/export-all`, `TestExportAll`, sidebar download links); (5) **smart typography** input-rules extension (curly quotes/em-dash/ellipsis, ASCII-only so CJK untouched); (6) **duplicate doc + sidebar sort + outline popover**; (7) **English phonetic** (pivoted from pinyin — IPA is what an English learner needs; pinyin annotates Chinese she already reads) via `scripts/build_phonetic.py` + embedded `phonetic.json.gz` + `Result.Phonetic` + WordCard `/ˈrɪvər/` line — **full 46,579-word dataset built from ECDICT** (the csv re-download worked; `--seed` mode kept as a csv-free fallback). Also folded in this session: the **selection-bubble vs copy/paste fix** (bubble deferred to pointer-up + container `pointer-events:none` so it never sits where you click). go build/vet/test + tsc + vite all clean; live smoke verified word-phonetic (incl. de-inflection) + export-all zip (de-duped CJK names, route priority). Next: deferred bucket (auth/Copyleaks/deploy), still on hold per user.
|
- 2026-06-26: **Phase 11 complete** (writer power-ups, batch requested as "do it all"). Seven features: (1) in-doc **Find & Replace** — `SearchHighlight` decoration extension + `FindReplace` bar (Ctrl/Cmd+F, match-case, replace-all back-to-front, DOM scroll that doesn't trigger the selection bubble); (2) **read-aloud** Web Speech util + 🔊 in WordCard & selection bubble; (3) **keyboard/touch access** — Ctrl/Cmd+D caret lookup, Ctrl/Cmd+J rewrite, touch long-press (refactored `handleContextMenu` → shared `openWordLookup(pos)`); (4) **export-all** backup zip (`GET /api/docs/export-all`, `TestExportAll`, sidebar download links); (5) **smart typography** input-rules extension (curly quotes/em-dash/ellipsis, ASCII-only so CJK untouched); (6) **duplicate doc + sidebar sort + outline popover**; (7) **English phonetic** (pivoted from pinyin — IPA is what an English learner needs; pinyin annotates Chinese she already reads) via `scripts/build_phonetic.py` + embedded `phonetic.json.gz` + `Result.Phonetic` + WordCard `/ˈrɪvər/` line — **full 46,579-word dataset built from ECDICT** (the csv re-download worked; `--seed` mode kept as a csv-free fallback). Also folded in this session: the **selection-bubble vs copy/paste fix** (bubble deferred to pointer-up + container `pointer-events:none` so it never sits where you click). go build/vet/test + tsc + vite all clean; live smoke verified word-phonetic (incl. de-inflection) + export-all zip (de-duped CJK names, route priority). Next: deferred bucket (auth/Copyleaks/deploy), still on hold per user.
|
||||||
- 2026-06-26: **Phase 10 complete** (organization & polish). Scope confirmed with user: all four areas, **tags** (not folders), **FTS5** search. Backend: migration `0004_tags_and_search` (tags + document_tags + `documents_fts` trigram virtual table with sync triggers + back-fill); `db.Tag` model + color constants; `internal/docs/tags.go` (tag CRUD + idempotent assignment + `tagsByDoc` helper, doc list now carries tags); `internal/docs/search.go` (`GET /api/search`, FTS for ≥3 runes + LIKE fallback for 1-2, Go-built sentinel-highlighted rune-aware snippets, owner-scoped). Mounted `/api/tags` + `/api/search` in main.go. Frontend: `useTags`, `TagChip`/`TagPicker`/`SearchBox`, rewritten `DocList`/`DocListItem` (chips + filter bar + search), `api.search`/tag methods + `splitSnippet`/`tagColorVar`; responsive sidebar drawer (hamburger + scrim, <768px) + `pointer:coarse` tap-target/affordance CSS; tap-to-open + outside-pointerdown-close for suggestion cards (touch); `useCheckpoint` `llmDown` flag → warm bilingual "小助手在休息" StatusBar note. Tests: `tags_test.go`, `search_test.go` (incl. update-trigger re-index). All builds/tests/vet/tsc/vite clean; live smoke vs binary on :8061 (dead LLM host) verified search EN/CJK/2-char, full tag lifecycle, check→502 warm path, bundle contents; FTS backfill of pre-existing docs verified. **All v1 phases (0–7) + post-v1 product (8–10) done.** Remaining: deferred bucket (auth/Copyleaks/deploy), on hold per user.
|
- 2026-06-26: **Phase 10 complete** (organization & polish). Scope confirmed with user: all four areas, **tags** (not folders), **FTS5** search. Backend: migration `0004_tags_and_search` (tags + document_tags + `documents_fts` trigram virtual table with sync triggers + back-fill); `db.Tag` model + color constants; `internal/docs/tags.go` (tag CRUD + idempotent assignment + `tagsByDoc` helper, doc list now carries tags); `internal/docs/search.go` (`GET /api/search`, FTS for ≥3 runes + LIKE fallback for 1-2, Go-built sentinel-highlighted rune-aware snippets, owner-scoped). Mounted `/api/tags` + `/api/search` in main.go. Frontend: `useTags`, `TagChip`/`TagPicker`/`SearchBox`, rewritten `DocList`/`DocListItem` (chips + filter bar + search), `api.search`/tag methods + `splitSnippet`/`tagColorVar`; responsive sidebar drawer (hamburger + scrim, <768px) + `pointer:coarse` tap-target/affordance CSS; tap-to-open + outside-pointerdown-close for suggestion cards (touch); `useCheckpoint` `llmDown` flag → warm bilingual "小助手在休息" StatusBar note. Tests: `tags_test.go`, `search_test.go` (incl. update-trigger re-index). All builds/tests/vet/tsc/vite clean; live smoke vs binary on :8061 (dead LLM host) verified search EN/CJK/2-char, full tag lifecycle, check→502 warm path, bundle contents; FTS backfill of pre-existing docs verified. **All v1 phases (0–7) + post-v1 product (8–10) done.** Remaining: deferred bucket (auth/Copyleaks/deploy), on hold per user.
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import (
|
|||||||
"gitea.parodia.dev/drwily/petal/internal/llm"
|
"gitea.parodia.dev/drwily/petal/internal/llm"
|
||||||
"gitea.parodia.dev/drwily/petal/internal/suggestions"
|
"gitea.parodia.dev/drwily/petal/internal/suggestions"
|
||||||
"gitea.parodia.dev/drwily/petal/internal/tts"
|
"gitea.parodia.dev/drwily/petal/internal/tts"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/vocab"
|
||||||
"gitea.parodia.dev/drwily/petal/web"
|
"gitea.parodia.dev/drwily/petal/web"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -83,6 +84,10 @@ func main() {
|
|||||||
api.Mount("/word", lex.Routes())
|
api.Mount("/word", lex.Routes())
|
||||||
api.Mount("/gloss", lex.GlossRoutes())
|
api.Mount("/gloss", lex.GlossRoutes())
|
||||||
|
|
||||||
|
// Vocabulary garden: words the writer looks up are captured here and
|
||||||
|
// surfaced for gentle spaced-repetition review.
|
||||||
|
api.Mount("/vocab", vocab.New(database).Routes())
|
||||||
|
|
||||||
// Editor image uploads, stored on disk and served back by content hash.
|
// Editor image uploads, stored on disk and served back by content hash.
|
||||||
imgHandler, err := images.New(cfg.ImageDir)
|
imgHandler, err := images.New(cfg.ImageDir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -260,6 +260,71 @@ END;
|
|||||||
|
|
||||||
INSERT INTO documents_fts (doc_id, title, content_text)
|
INSERT INTO documents_fts (doc_id, title, content_text)
|
||||||
SELECT id, title, content_text FROM documents;
|
SELECT id, title, content_text FROM documents;
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Collocation coach (Phase 12). Adds a third suggestion family,
|
||||||
|
// 'collocation', for gentle "natives usually say…" hints on
|
||||||
|
// non-native word pairings. The `type` column carries a CHECK
|
||||||
|
// constraint and SQLite cannot ALTER one in place, so we rebuild the
|
||||||
|
// suggestions table with the extended CHECK, copy every row across,
|
||||||
|
// and recreate its index. Nothing references suggestions, so dropping
|
||||||
|
// the old table is safe; the new table keeps the same ON DELETE
|
||||||
|
// CASCADE to documents.
|
||||||
|
name: "0005_collocation_suggestion_type",
|
||||||
|
stmt: `
|
||||||
|
CREATE TABLE suggestions_new (
|
||||||
|
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
|
||||||
|
doc_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
||||||
|
from_pos INTEGER NOT NULL,
|
||||||
|
to_pos INTEGER NOT NULL,
|
||||||
|
original TEXT NOT NULL,
|
||||||
|
replacement TEXT NOT NULL,
|
||||||
|
explanation TEXT NOT NULL,
|
||||||
|
type TEXT NOT NULL CHECK(type IN ('grammar','phrasing','idiom','clarity','voice','collocation')),
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','accepted','rejected')),
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO suggestions_new (id, doc_id, from_pos, to_pos, original, replacement, explanation, type, status, created_at)
|
||||||
|
SELECT id, doc_id, from_pos, to_pos, original, replacement, explanation, type, status, created_at FROM suggestions;
|
||||||
|
|
||||||
|
DROP TABLE suggestions;
|
||||||
|
ALTER TABLE suggestions_new RENAME TO suggestions;
|
||||||
|
CREATE INDEX idx_suggestions_doc_id ON suggestions(doc_id);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Vocabulary garden (Phase 13). Every word the writer looks up is
|
||||||
|
// captured here and put on a gentle spaced-repetition schedule, turning
|
||||||
|
// passive lookups into real vocabulary. `example` holds the sentence the
|
||||||
|
// word appeared in (captured at lookup) for context during review;
|
||||||
|
// `doc_id` links back to where she met the word (nulled if that doc is
|
||||||
|
// deleted — the word stays in the garden). The SM-2-lite scheduling
|
||||||
|
// columns (due_at/interval_days/ease/reps/lapses/last_reviewed) drive a
|
||||||
|
// Leitner-style ladder (see internal/vocab/scheduler.go). UNIQUE on
|
||||||
|
// (user_id, word) makes capture an idempotent upsert.
|
||||||
|
name: "0006_vocab_garden",
|
||||||
|
stmt: `
|
||||||
|
CREATE TABLE vocab_words (
|
||||||
|
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id),
|
||||||
|
word TEXT NOT NULL,
|
||||||
|
gloss TEXT NOT NULL DEFAULT '',
|
||||||
|
phonetic TEXT NOT NULL DEFAULT '',
|
||||||
|
example TEXT NOT NULL DEFAULT '',
|
||||||
|
doc_id TEXT REFERENCES documents(id) ON DELETE SET NULL,
|
||||||
|
due_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
interval_days INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ease REAL NOT NULL DEFAULT 2.5,
|
||||||
|
reps INTEGER NOT NULL DEFAULT 0,
|
||||||
|
lapses INTEGER NOT NULL DEFAULT 0,
|
||||||
|
last_reviewed DATETIME,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(user_id, word)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_vocab_due ON vocab_words(user_id, due_at);
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,14 @@ func TestOpenMigratesAndSeeds(t *testing.T) {
|
|||||||
t.Fatalf("insert voice suggestion: %v", err)
|
t.Fatalf("insert voice suggestion: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The collocation type (added by migration 0005's table rebuild) is permitted.
|
||||||
|
if _, err := d.Exec(
|
||||||
|
`INSERT INTO suggestions (doc_id, from_pos, to_pos, original, replacement, explanation, type)
|
||||||
|
VALUES ('d1', 0, 9, 'do a decision', 'make a decision', 'natives usually say…', 'collocation')`,
|
||||||
|
); err != nil {
|
||||||
|
t.Fatalf("insert collocation suggestion: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
// An invalid type is rejected.
|
// An invalid type is rejected.
|
||||||
if _, err := d.Exec(
|
if _, err := d.Exec(
|
||||||
`INSERT INTO suggestions (doc_id, from_pos, to_pos, original, replacement, explanation, type)
|
`INSERT INTO suggestions (doc_id, from_pos, to_pos, original, replacement, explanation, type)
|
||||||
|
|||||||
@@ -88,18 +88,19 @@ type Suggestion struct {
|
|||||||
Original string `json:"original"`
|
Original string `json:"original"`
|
||||||
Replacement string `json:"replacement"`
|
Replacement string `json:"replacement"`
|
||||||
Explanation string `json:"explanation"`
|
Explanation string `json:"explanation"`
|
||||||
Type string `json:"type"` // grammar | phrasing | idiom | clarity | voice
|
Type string `json:"type"` // grammar | phrasing | idiom | clarity | voice | collocation
|
||||||
Status string `json:"status"` // pending | accepted | rejected
|
Status string `json:"status"` // pending | accepted | rejected
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Suggestion type and status values, mirrored from the schema CHECK constraints.
|
// Suggestion type and status values, mirrored from the schema CHECK constraints.
|
||||||
const (
|
const (
|
||||||
SuggestionTypeGrammar = "grammar"
|
SuggestionTypeGrammar = "grammar"
|
||||||
SuggestionTypePhrasing = "phrasing"
|
SuggestionTypePhrasing = "phrasing"
|
||||||
SuggestionTypeIdiom = "idiom"
|
SuggestionTypeIdiom = "idiom"
|
||||||
SuggestionTypeClarity = "clarity"
|
SuggestionTypeClarity = "clarity"
|
||||||
SuggestionTypeVoice = "voice"
|
SuggestionTypeVoice = "voice"
|
||||||
|
SuggestionTypeCollocation = "collocation"
|
||||||
|
|
||||||
SuggestionStatusPending = "pending"
|
SuggestionStatusPending = "pending"
|
||||||
SuggestionStatusAccepted = "accepted"
|
SuggestionStatusAccepted = "accepted"
|
||||||
|
|||||||
35
internal/llm/collocation.go
Normal file
35
internal/llm/collocation.go
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
package llm
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CollocationInterval is the minimum gap between collocation passes for one
|
||||||
|
// document. Like the voice pass it runs on an explicit user action ("Make it
|
||||||
|
// sound natural") rather than a typing cadence, so this floor only guards the
|
||||||
|
// inference endpoint against the button being mashed.
|
||||||
|
const CollocationInterval = 25 * time.Second
|
||||||
|
|
||||||
|
// RunCollocation sends the WHOLE document for a collocation pass — gentle
|
||||||
|
// "natives usually say…" hints on non-native word pairings — and parses the JSON
|
||||||
|
// result with the checkpoint's tolerant parser. It is deliberately NOT
|
||||||
|
// TruncateDoc'd: like the voice pass it reads the whole document so the hints
|
||||||
|
// reflect the full piece. Each flag carries a native replacement to apply.
|
||||||
|
//
|
||||||
|
// The tone argument is accepted for a uniform pass signature and passed through
|
||||||
|
// to the prompt so a hint can prefer a register-appropriate pairing.
|
||||||
|
func RunCollocation(ctx context.Context, client LLMClient, contentText, tone string) ([]RawSuggestion, error) {
|
||||||
|
raw, err := client.Complete(ctx, CompletionRequest{
|
||||||
|
Messages: CollocationMessages(contentText, tone),
|
||||||
|
MaxTokens: 2048,
|
||||||
|
Temperature: 0.3,
|
||||||
|
RepetitionPenalty: 1.15,
|
||||||
|
TopP: 0.9,
|
||||||
|
Stop: []string{"```", "\n\n\n\n"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ParseCheckpoint(raw)
|
||||||
|
}
|
||||||
@@ -92,6 +92,54 @@ func VoiceMessages(contentText string) []Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// collocationSystemPrompt drives the collocation coach — the single most
|
||||||
|
// valuable polish for an ESL writer. It flags word PAIRINGS that are not wrong,
|
||||||
|
// just non-native ("do a decision" → "make a decision", "strong rain" → "heavy
|
||||||
|
// rain"), and explicitly DEFERS real grammar/spelling errors to the grammar
|
||||||
|
// checkpoint so the two families don't overlap. Every explanation is framed as a
|
||||||
|
// warm "natives usually say…" note with a short Mandarin gloss — never
|
||||||
|
// "error/wrong" — because these are stylistic, not mistakes. It is a distinct
|
||||||
|
// pass from the grammar checkpoint (do not bundle them). `replacement` carries
|
||||||
|
// the natural pairing the writer can accept in one tap.
|
||||||
|
const collocationSystemPrompt = `You are a warm, encouraging writing assistant helping someone who speaks English as a second language. ` +
|
||||||
|
`You are reviewing a COMPLETE document for COLLOCATIONS only — the natural word pairings native speakers use.
|
||||||
|
|
||||||
|
A collocation is a pair or short group of words that native speakers habitually say together. ESL writers ` +
|
||||||
|
`often choose words that are grammatically correct but sound non-native: "do a decision" instead of "make a decision", ` +
|
||||||
|
`"strong rain" instead of "heavy rain", "say a joke" instead of "tell a joke". These are NOT grammar mistakes — they ` +
|
||||||
|
`are just not what a native speaker would naturally say.
|
||||||
|
|
||||||
|
Identify up to 5 such non-native word pairings. For each, give the natural pairing a native speaker would use. ` +
|
||||||
|
`Be gentle and specific. Do NOT flag grammar errors, spelling mistakes, or unclear sentences — those are handled ` +
|
||||||
|
`elsewhere. Only flag word pairings that are correct but sound non-native.%s
|
||||||
|
|
||||||
|
Phrase every explanation warmly as "Natives usually say…" and include a brief Simplified Chinese gloss in parentheses. ` +
|
||||||
|
`Never use the words "error", "wrong", or "mistake" — these are friendly polish, not corrections.
|
||||||
|
|
||||||
|
Respond ONLY with valid JSON. No preamble, no markdown fences. Format:
|
||||||
|
{
|
||||||
|
"suggestions": [
|
||||||
|
{
|
||||||
|
"original": "exact word pairing from the document",
|
||||||
|
"replacement": "the natural native pairing",
|
||||||
|
"explanation": "friendly note, e.g. 'Natives usually say \"make a decision\" rather than \"do a decision\" (native usage / 地道说法).'",
|
||||||
|
"type": "collocation"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
If every pairing already sounds natural, return: {"suggestions": []}`
|
||||||
|
|
||||||
|
// CollocationMessages builds the message array for a collocation pass over the
|
||||||
|
// WHOLE document (no truncation), gently steered toward the document's tone so a
|
||||||
|
// hint can prefer a register-appropriate pairing.
|
||||||
|
func CollocationMessages(contentText, tone string) []Message {
|
||||||
|
return []Message{
|
||||||
|
{Role: "system", Content: fmt.Sprintf(collocationSystemPrompt, toneGuidance(tone))},
|
||||||
|
{Role: "user", Content: contentText},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// askPetalSystemTemplate is the Ask Petal tutor prompt. The suggestion context
|
// askPetalSystemTemplate is the Ask Petal tutor prompt. The suggestion context
|
||||||
// is interpolated in; the user's own messages are appended after this system
|
// is interpolated in; the user's own messages are appended after this system
|
||||||
// turn by the caller.
|
// turn by the caller.
|
||||||
|
|||||||
@@ -23,19 +23,22 @@ import (
|
|||||||
// grammar checkpoint and the voice pass each get their own per-document rate
|
// grammar checkpoint and the voice pass each get their own per-document rate
|
||||||
// limiter — they are independent passes with different cadences.
|
// limiter — they are independent passes with different cadences.
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
DB *db.DB
|
DB *db.DB
|
||||||
Client llm.LLMClient
|
Client llm.LLMClient
|
||||||
Limit *llm.RateLimiter // grammar checkpoint floor
|
Limit *llm.RateLimiter // grammar checkpoint floor
|
||||||
VoiceLimit *llm.RateLimiter // voice-consistency floor
|
VoiceLimit *llm.RateLimiter // voice-consistency floor
|
||||||
|
CollocationLimit *llm.RateLimiter // collocation-coach floor
|
||||||
}
|
}
|
||||||
|
|
||||||
// New constructs a Handler with per-document checkpoint and voice rate limiters.
|
// New constructs a Handler with per-document checkpoint, voice, and collocation
|
||||||
|
// rate limiters.
|
||||||
func New(database *db.DB, client llm.LLMClient) *Handler {
|
func New(database *db.DB, client llm.LLMClient) *Handler {
|
||||||
return &Handler{
|
return &Handler{
|
||||||
DB: database,
|
DB: database,
|
||||||
Client: client,
|
Client: client,
|
||||||
Limit: llm.NewRateLimiter(llm.CheckpointInterval),
|
Limit: llm.NewRateLimiter(llm.CheckpointInterval),
|
||||||
VoiceLimit: llm.NewRateLimiter(llm.VoiceInterval),
|
VoiceLimit: llm.NewRateLimiter(llm.VoiceInterval),
|
||||||
|
CollocationLimit: llm.NewRateLimiter(llm.CollocationInterval),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,6 +47,7 @@ func New(database *db.DB, client llm.LLMClient) *Handler {
|
|||||||
func (h *Handler) RegisterDocRoutes(r chi.Router) {
|
func (h *Handler) RegisterDocRoutes(r chi.Router) {
|
||||||
r.Post("/{id}/check", h.check)
|
r.Post("/{id}/check", h.check)
|
||||||
r.Post("/{id}/voice", h.voice)
|
r.Post("/{id}/voice", h.voice)
|
||||||
|
r.Post("/{id}/collocation", h.collocation)
|
||||||
r.Post("/{id}/rewrite", h.rewrite)
|
r.Post("/{id}/rewrite", h.rewrite)
|
||||||
r.Get("/{id}/suggestions", h.listForDoc)
|
r.Get("/{id}/suggestions", h.listForDoc)
|
||||||
}
|
}
|
||||||
@@ -70,6 +74,13 @@ func (h *Handler) voice(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.runPass(w, r, h.VoiceLimit, llm.RunVoice, voiceScope)
|
h.runPass(w, r, h.VoiceLimit, llm.RunVoice, voiceScope)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// collocation runs the collocation coach over the whole document, flagging
|
||||||
|
// non-native word pairings. Explicit-action pass; replaces only the pending
|
||||||
|
// collocation flags.
|
||||||
|
func (h *Handler) collocation(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h.runPass(w, r, h.CollocationLimit, llm.RunCollocation, collocationScope)
|
||||||
|
}
|
||||||
|
|
||||||
// pass is the signature shared by the grammar checkpoint and the voice pass:
|
// pass is the signature shared by the grammar checkpoint and the voice pass:
|
||||||
// given the document text and the document's tone it returns the model's raw
|
// given the document text and the document's tone it returns the model's raw
|
||||||
// suggestions. The voice pass ignores tone (see llm.RunVoice).
|
// suggestions. The voice pass ignores tone (see llm.RunVoice).
|
||||||
@@ -151,10 +162,14 @@ type pendingScope struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// grammarScope owns the grammar/phrasing/idiom/clarity flags (everything but voice).
|
// grammarScope owns the grammar/phrasing/idiom/clarity flags — everything but
|
||||||
grammarScope = pendingScope{deleteWhere: "type != 'voice'", forceType: ""}
|
// the explicit-action families (voice, collocation), which run on their own
|
||||||
|
// cadence and must survive a grammar checkpoint.
|
||||||
|
grammarScope = pendingScope{deleteWhere: "type NOT IN ('voice','collocation')", forceType: ""}
|
||||||
// voiceScope owns the voice flags only.
|
// voiceScope owns the voice flags only.
|
||||||
voiceScope = pendingScope{deleteWhere: "type = 'voice'", forceType: db.SuggestionTypeVoice}
|
voiceScope = pendingScope{deleteWhere: "type = 'voice'", forceType: db.SuggestionTypeVoice}
|
||||||
|
// collocationScope owns the collocation flags only.
|
||||||
|
collocationScope = pendingScope{deleteWhere: "type = 'collocation'", forceType: db.SuggestionTypeCollocation}
|
||||||
)
|
)
|
||||||
|
|
||||||
// replacePending swaps a document's pending suggestions within one family for a
|
// replacePending swaps a document's pending suggestions within one family for a
|
||||||
@@ -320,7 +335,7 @@ func locate(contentText, original string) (int, int) {
|
|||||||
// defaulting unknown values to grammar so a stray label never trips the CHECK.
|
// defaulting unknown values to grammar so a stray label never trips the CHECK.
|
||||||
func normalizeType(t string) string {
|
func normalizeType(t string) string {
|
||||||
switch strings.ToLower(strings.TrimSpace(t)) {
|
switch strings.ToLower(strings.TrimSpace(t)) {
|
||||||
case db.SuggestionTypeGrammar, db.SuggestionTypePhrasing, db.SuggestionTypeIdiom, db.SuggestionTypeClarity:
|
case db.SuggestionTypeGrammar, db.SuggestionTypePhrasing, db.SuggestionTypeIdiom, db.SuggestionTypeClarity, db.SuggestionTypeCollocation:
|
||||||
return strings.ToLower(strings.TrimSpace(t))
|
return strings.ToLower(strings.TrimSpace(t))
|
||||||
default:
|
default:
|
||||||
return db.SuggestionTypeGrammar
|
return db.SuggestionTypeGrammar
|
||||||
|
|||||||
@@ -227,6 +227,65 @@ func TestVoicePassCoexists(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestCollocationPassCoexists proves the collocation coach is a third
|
||||||
|
// independent family: it never wipes grammar or voice pending flags, a grammar
|
||||||
|
// checkpoint never wipes its flags, and each endpoint returns the unified set.
|
||||||
|
func TestCollocationPassCoexists(t *testing.T) {
|
||||||
|
client := &switchClient{}
|
||||||
|
srv, docID, h := newTestServer(t, client)
|
||||||
|
// Zero the floors so the test can re-run passes without waiting them out.
|
||||||
|
h.Limit = llm.NewRateLimiter(0)
|
||||||
|
h.VoiceLimit = llm.NewRateLimiter(0)
|
||||||
|
h.CollocationLimit = llm.NewRateLimiter(0)
|
||||||
|
|
||||||
|
// Grammar + voice first, so all three families are exercised.
|
||||||
|
client.response = `{"suggestions":[{"original":"I has","replacement":"I have","explanation":"agreement","type":"grammar"}]}`
|
||||||
|
if rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/check", ""); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("check: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
client.response = `{"suggestions":[{"original":"two apple","replacement":null,"explanation":"sounds formal","type":"voice"}]}`
|
||||||
|
if rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/voice", ""); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("voice: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collocation pass → a third flag (with a replacement). It must keep the
|
||||||
|
// grammar and voice flags; the response is the unified set of all three.
|
||||||
|
client.response = `{"suggestions":[{"original":"two apple","replacement":"two apples","explanation":"Natives usually say…","type":"collocation"}]}`
|
||||||
|
rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/collocation", "")
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("collocation: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
var got []db.Suggestion
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
byType := map[string]bool{}
|
||||||
|
for _, s := range got {
|
||||||
|
byType[s.Type] = true
|
||||||
|
}
|
||||||
|
if !byType[db.SuggestionTypeGrammar] || !byType[db.SuggestionTypeVoice] || !byType[db.SuggestionTypeCollocation] {
|
||||||
|
t.Fatalf("collocation response should carry all three families, got %+v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A grammar checkpoint must NOT wipe the voice or collocation flags.
|
||||||
|
client.response = `{"suggestions":[]}`
|
||||||
|
rec = do(t, srv, http.MethodPost, "/docs/"+docID+"/check", "")
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("second check: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &got)
|
||||||
|
byType = map[string]bool{}
|
||||||
|
for _, s := range got {
|
||||||
|
byType[s.Type] = true
|
||||||
|
}
|
||||||
|
if byType[db.SuggestionTypeGrammar] {
|
||||||
|
t.Fatalf("grammar flag should have cleared, got %+v", got)
|
||||||
|
}
|
||||||
|
if !byType[db.SuggestionTypeVoice] || !byType[db.SuggestionTypeCollocation] {
|
||||||
|
t.Fatalf("grammar checkpoint wiped a sibling family, got %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// switchClient returns a response that can be swapped between calls.
|
// switchClient returns a response that can be swapped between calls.
|
||||||
type switchClient struct {
|
type switchClient struct {
|
||||||
response string
|
response string
|
||||||
|
|||||||
245
internal/vocab/handlers.go
Normal file
245
internal/vocab/handlers.go
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
package vocab
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Word is one entry in the vocabulary garden: the looked-up word with its gloss,
|
||||||
|
// phonetic, and the sentence it was met in, plus its spaced-repetition state.
|
||||||
|
type Word struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Word string `json:"word"`
|
||||||
|
Gloss string `json:"gloss"`
|
||||||
|
Phonetic string `json:"phonetic"`
|
||||||
|
Example string `json:"example"`
|
||||||
|
DocID *string `json:"doc_id"`
|
||||||
|
DueAt time.Time `json:"due_at"`
|
||||||
|
IntervalDays int `json:"interval_days"`
|
||||||
|
Ease float64 `json:"ease"`
|
||||||
|
Reps int `json:"reps"`
|
||||||
|
Lapses int `json:"lapses"`
|
||||||
|
LastReviewed *time.Time `json:"last_reviewed"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handler owns the vocabulary-garden routes. Everything is scoped to the local
|
||||||
|
// user while auth is deferred.
|
||||||
|
type Handler struct {
|
||||||
|
DB *db.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(database *db.DB) *Handler { return &Handler{DB: database} }
|
||||||
|
|
||||||
|
// Routes mounts the garden endpoints under /api/vocab.
|
||||||
|
func (h *Handler) Routes() chi.Router {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Get("/", h.list) // the whole garden
|
||||||
|
r.Get("/due", h.due) // only the cards due for review now
|
||||||
|
r.Post("/", h.capture) // record/upsert a looked-up word
|
||||||
|
r.Post("/{id}/review", h.review)
|
||||||
|
r.Delete("/{id}", h.remove)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
const vocabColumns = `id, word, gloss, phonetic, example, doc_id,
|
||||||
|
due_at, interval_days, ease, reps, lapses, last_reviewed, created_at`
|
||||||
|
|
||||||
|
func scanWord(s interface {
|
||||||
|
Scan(dest ...any) error
|
||||||
|
}) (Word, error) {
|
||||||
|
var w Word
|
||||||
|
err := s.Scan(
|
||||||
|
&w.ID, &w.Word, &w.Gloss, &w.Phonetic, &w.Example, &w.DocID,
|
||||||
|
&w.DueAt, &w.IntervalDays, &w.Ease, &w.Reps, &w.Lapses, &w.LastReviewed, &w.CreatedAt,
|
||||||
|
)
|
||||||
|
return w, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// list returns the full garden, newest blossoms first.
|
||||||
|
func (h *Handler) list(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
h.queryList(w, `SELECT `+vocabColumns+` FROM vocab_words
|
||||||
|
WHERE user_id = ? ORDER BY created_at DESC`, db.LocalUserID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// due returns only the cards whose review time has arrived, soonest first.
|
||||||
|
func (h *Handler) due(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
h.queryList(w, `SELECT `+vocabColumns+` FROM vocab_words
|
||||||
|
WHERE user_id = ? AND due_at <= datetime('now') ORDER BY due_at ASC`, db.LocalUserID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) queryList(w http.ResponseWriter, query string, args ...any) {
|
||||||
|
rows, err := h.DB.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []Word{}
|
||||||
|
for rows.Next() {
|
||||||
|
word, err := scanWord(rows)
|
||||||
|
if err != nil {
|
||||||
|
serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out = append(out, word)
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
type captureRequest struct {
|
||||||
|
Word string `json:"word"`
|
||||||
|
Gloss string `json:"gloss"`
|
||||||
|
Phonetic string `json:"phonetic"`
|
||||||
|
Example string `json:"example"`
|
||||||
|
DocID *string `json:"doc_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// capture records a looked-up word. It's an idempotent upsert keyed on the word:
|
||||||
|
// a new word lands due tomorrow (interval 1 day); an existing word keeps its
|
||||||
|
// schedule untouched but refreshes its gloss/phonetic/example/doc_id so the most
|
||||||
|
// recent context wins. Looking words up IS the data source — no extra effort.
|
||||||
|
func (h *Handler) capture(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req captureRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
errorJSON(w, http.StatusBadRequest, "invalid body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
word := strings.TrimSpace(req.Word)
|
||||||
|
if word == "" {
|
||||||
|
errorJSON(w, http.StatusBadRequest, "word is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// New rows start due tomorrow; ON CONFLICT refreshes context but leaves the
|
||||||
|
// schedule (due_at/reps/interval/ease) alone so re-looking-up a word never
|
||||||
|
// resets its progress.
|
||||||
|
_, err := h.DB.Exec(
|
||||||
|
`INSERT INTO vocab_words (user_id, word, gloss, phonetic, example, doc_id, due_at, interval_days)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, datetime('now', '+1 day'), 1)
|
||||||
|
ON CONFLICT(user_id, word) DO UPDATE SET
|
||||||
|
gloss = excluded.gloss,
|
||||||
|
phonetic = excluded.phonetic,
|
||||||
|
example = CASE WHEN excluded.example != '' THEN excluded.example ELSE vocab_words.example END,
|
||||||
|
doc_id = COALESCE(excluded.doc_id, vocab_words.doc_id)`,
|
||||||
|
db.LocalUserID, word, req.Gloss, req.Phonetic, req.Example, req.DocID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := h.fetch(word)
|
||||||
|
if err != nil {
|
||||||
|
serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetch loads one word row by its (user, word) key.
|
||||||
|
func (h *Handler) fetch(word string) (Word, error) {
|
||||||
|
return scanWord(h.DB.QueryRow(
|
||||||
|
`SELECT `+vocabColumns+` FROM vocab_words WHERE user_id = ? AND word = ?`,
|
||||||
|
db.LocalUserID, word,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
type reviewRequest struct {
|
||||||
|
Grade Grade `json:"grade"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// review grades one card and reschedules it. The grade drives the SM-2-lite
|
||||||
|
// scheduler; the new interval is applied as `due_at = now + interval days`.
|
||||||
|
func (h *Handler) review(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id := chi.URLParam(r, "id")
|
||||||
|
var req reviewRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
errorJSON(w, http.StatusBadRequest, "invalid body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Grade != GradeAgain && req.Grade != GradeGood && req.Grade != GradeEasy {
|
||||||
|
errorJSON(w, http.StatusBadRequest, "grade must be again, good, or easy")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var cur State
|
||||||
|
err := h.DB.QueryRow(
|
||||||
|
`SELECT reps, interval_days, ease, lapses FROM vocab_words WHERE id = ? AND user_id = ?`,
|
||||||
|
id, db.LocalUserID,
|
||||||
|
).Scan(&cur.Reps, &cur.Interval, &cur.Ease, &cur.Lapses)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
errorJSON(w, http.StatusNotFound, "word not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
nxt := cur.next(req.Grade)
|
||||||
|
// `datetime('now', '+N days')` keeps the stored value in SQLite's canonical
|
||||||
|
// text format, matching CURRENT_TIMESTAMP and the due query's comparison.
|
||||||
|
offset := "+" + strconv.Itoa(nxt.Interval) + " days"
|
||||||
|
if _, err := h.DB.Exec(
|
||||||
|
`UPDATE vocab_words SET
|
||||||
|
reps = ?, interval_days = ?, ease = ?, lapses = ?,
|
||||||
|
last_reviewed = datetime('now'), due_at = datetime('now', ?)
|
||||||
|
WHERE id = ? AND user_id = ?`,
|
||||||
|
nxt.Reps, nxt.Interval, nxt.Ease, nxt.Lapses, offset, id, db.LocalUserID,
|
||||||
|
); err != nil {
|
||||||
|
serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := scanWord(h.DB.QueryRow(
|
||||||
|
`SELECT `+vocabColumns+` FROM vocab_words WHERE id = ? AND user_id = ?`, id, db.LocalUserID,
|
||||||
|
))
|
||||||
|
if err != nil {
|
||||||
|
serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove deletes a word from the garden (e.g. the writer already knows it).
|
||||||
|
func (h *Handler) remove(w http.ResponseWriter, r *http.Request) {
|
||||||
|
res, err := h.DB.Exec(
|
||||||
|
`DELETE FROM vocab_words WHERE id = ? AND user_id = ?`,
|
||||||
|
chi.URLParam(r, "id"), db.LocalUserID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
|
errorJSON(w, http.StatusNotFound, "word not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- response helpers -------------------------------------------------------
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func errorJSON(w http.ResponseWriter, status int, msg string) {
|
||||||
|
writeJSON(w, status, map[string]string{"error": msg})
|
||||||
|
}
|
||||||
|
|
||||||
|
func serverError(w http.ResponseWriter, err error) {
|
||||||
|
errorJSON(w, http.StatusInternalServerError, err.Error())
|
||||||
|
}
|
||||||
170
internal/vocab/handlers_test.go
Normal file
170
internal/vocab/handlers_test.go
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
package vocab
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newTestServer(t *testing.T) (http.Handler, *db.DB) {
|
||||||
|
t.Helper()
|
||||||
|
database, err := db.Open(filepath.Join(t.TempDir(), "test.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open db: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { database.Close() })
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Mount("/vocab", New(database).Routes())
|
||||||
|
return r, database
|
||||||
|
}
|
||||||
|
|
||||||
|
func do(t *testing.T, srv http.Handler, method, path, body string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
var r *http.Request
|
||||||
|
if body != "" {
|
||||||
|
r = httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||||
|
} else {
|
||||||
|
r = httptest.NewRequest(method, path, nil)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
srv.ServeHTTP(rec, r)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCaptureUpsertAndReview walks the garden lifecycle: capture a word (lands
|
||||||
|
// in the future, not yet due), re-capture refreshes context without resetting
|
||||||
|
// schedule, a forced-due word shows up in /due, a review reschedules it, and
|
||||||
|
// delete removes it.
|
||||||
|
func TestCaptureUpsertAndReview(t *testing.T) {
|
||||||
|
srv, database := newTestServer(t)
|
||||||
|
|
||||||
|
// Capture a new word → 201, due tomorrow (interval 1), not in /due yet.
|
||||||
|
rec := do(t, srv, http.MethodPost, "/vocab",
|
||||||
|
`{"word":"serendipity","gloss":"机缘巧合","phonetic":"/ˌserənˈdɪpəti/","example":"What a serendipity."}`)
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("capture: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
var w Word
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &w)
|
||||||
|
if w.ID == "" || w.Word != "serendipity" || w.Gloss != "机缘巧合" {
|
||||||
|
t.Fatalf("captured word wrong: %+v", w)
|
||||||
|
}
|
||||||
|
if w.IntervalDays != 1 || w.Reps != 0 {
|
||||||
|
t.Fatalf("new word should start at interval 1, reps 0: %+v", w)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not due yet (due tomorrow).
|
||||||
|
rec = do(t, srv, http.MethodGet, "/vocab/due", "")
|
||||||
|
var due []Word
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &due)
|
||||||
|
if len(due) != 0 {
|
||||||
|
t.Fatalf("freshly-captured word should not be due yet, got %d", len(due))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-capture with a new gloss → still one row (idempotent upsert), refreshed.
|
||||||
|
rec = do(t, srv, http.MethodPost, "/vocab",
|
||||||
|
`{"word":"serendipity","gloss":"意外的好运","phonetic":"/x/","example":""}`)
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("re-capture: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
rec = do(t, srv, http.MethodGet, "/vocab", "")
|
||||||
|
var all []Word
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &all)
|
||||||
|
if len(all) != 1 {
|
||||||
|
t.Fatalf("re-capture should not add a row, got %d", len(all))
|
||||||
|
}
|
||||||
|
if all[0].Gloss != "意外的好运" {
|
||||||
|
t.Fatalf("gloss should refresh on re-capture, got %q", all[0].Gloss)
|
||||||
|
}
|
||||||
|
if all[0].Example != "What a serendipity." {
|
||||||
|
t.Fatalf("empty example should not clobber the prior one, got %q", all[0].Example)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Force it due now, then it appears in /due.
|
||||||
|
if _, err := database.Exec(`UPDATE vocab_words SET due_at = datetime('now','-1 hour')`); err != nil {
|
||||||
|
t.Fatalf("force due: %v", err)
|
||||||
|
}
|
||||||
|
rec = do(t, srv, http.MethodGet, "/vocab/due", "")
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &due)
|
||||||
|
if len(due) != 1 {
|
||||||
|
t.Fatalf("forced-due word should be in /due, got %d", len(due))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Review "good" → reschedules forward (interval 3 = second ladder rung, since
|
||||||
|
// reps was 0 and a capture set interval 1 but reps 0; first good → rung 1 = 1).
|
||||||
|
rec = do(t, srv, http.MethodPost, "/vocab/"+w.ID+"/review", `{"grade":"good"}`)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("review: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
var reviewed Word
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &reviewed)
|
||||||
|
if reviewed.Reps != 1 || reviewed.IntervalDays != 1 {
|
||||||
|
t.Fatalf("first good review should be reps 1, interval 1: %+v", reviewed)
|
||||||
|
}
|
||||||
|
if reviewed.LastReviewed == nil {
|
||||||
|
t.Fatalf("review should stamp last_reviewed")
|
||||||
|
}
|
||||||
|
|
||||||
|
// After a forward review it's no longer due.
|
||||||
|
rec = do(t, srv, http.MethodGet, "/vocab/due", "")
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &due)
|
||||||
|
if len(due) != 0 {
|
||||||
|
t.Fatalf("reviewed word should leave /due, got %d", len(due))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bad grade → 400.
|
||||||
|
if rec = do(t, srv, http.MethodPost, "/vocab/"+w.ID+"/review", `{"grade":"nope"}`); rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("bad grade: want 400, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete → 204, garden empty.
|
||||||
|
if rec = do(t, srv, http.MethodDelete, "/vocab/"+w.ID, ""); rec.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("delete: code=%d", rec.Code)
|
||||||
|
}
|
||||||
|
if rec = do(t, srv, http.MethodDelete, "/vocab/"+w.ID, ""); rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("re-delete: want 404, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCaptureValidation rejects an empty word.
|
||||||
|
func TestCaptureValidation(t *testing.T) {
|
||||||
|
srv, _ := newTestServer(t)
|
||||||
|
if rec := do(t, srv, http.MethodPost, "/vocab", `{"word":" "}`); rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("empty word: want 400, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDocLinkSurvivesDocDelete proves the ON DELETE SET NULL keeps a word in the
|
||||||
|
// garden when its source document is removed.
|
||||||
|
func TestDocLinkSurvivesDocDelete(t *testing.T) {
|
||||||
|
srv, database := newTestServer(t)
|
||||||
|
var docID string
|
||||||
|
if err := database.QueryRow(
|
||||||
|
`INSERT INTO documents (user_id, content_text) VALUES (?, 'hi') RETURNING id`, db.LocalUserID,
|
||||||
|
).Scan(&docID); err != nil {
|
||||||
|
t.Fatalf("seed doc: %v", err)
|
||||||
|
}
|
||||||
|
rec := do(t, srv, http.MethodPost, "/vocab", `{"word":"ephemeral","gloss":"短暂的","doc_id":"`+docID+`"}`)
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("capture: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
if _, err := database.Exec(`DELETE FROM documents WHERE id = ?`, docID); err != nil {
|
||||||
|
t.Fatalf("delete doc: %v", err)
|
||||||
|
}
|
||||||
|
rec = do(t, srv, http.MethodGet, "/vocab", "")
|
||||||
|
var all []Word
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &all)
|
||||||
|
if len(all) != 1 {
|
||||||
|
t.Fatalf("word should survive doc deletion, got %d", len(all))
|
||||||
|
}
|
||||||
|
if all[0].DocID != nil {
|
||||||
|
t.Fatalf("doc_id should be nulled after doc delete, got %v", *all[0].DocID)
|
||||||
|
}
|
||||||
|
}
|
||||||
97
internal/vocab/scheduler.go
Normal file
97
internal/vocab/scheduler.go
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
// Package vocab implements the vocabulary garden: it captures words the writer
|
||||||
|
// looks up and schedules them for gentle spaced-repetition review. The scheduler
|
||||||
|
// is a deliberately forgiving SM-2-lite / Leitner hybrid — no streaks to break,
|
||||||
|
// no harsh resets beyond a single step back — because this is a confidence
|
||||||
|
// builder, not a drill sergeant.
|
||||||
|
package vocab
|
||||||
|
|
||||||
|
import "math"
|
||||||
|
|
||||||
|
// Grade is the writer's self-assessment after seeing a flashcard's answer.
|
||||||
|
type Grade string
|
||||||
|
|
||||||
|
const (
|
||||||
|
GradeAgain Grade = "again" // didn't recall it — show again soon
|
||||||
|
GradeGood Grade = "good" // recalled it — advance one rung
|
||||||
|
GradeEasy Grade = "easy" // knew it instantly — advance a little further
|
||||||
|
)
|
||||||
|
|
||||||
|
// ladder is the Leitner interval ladder in days for the first several successful
|
||||||
|
// reviews: 1 → 3 → 7 → 16 → 35. Beyond the ladder, intervals grow by the card's
|
||||||
|
// ease factor so well-known words drift far into the future.
|
||||||
|
var ladder = []int{1, 3, 7, 16, 35}
|
||||||
|
|
||||||
|
const (
|
||||||
|
minEase = 1.3
|
||||||
|
startEase = 2.5
|
||||||
|
easyBonus = 1.3 // multiplier applied on top of a "good" step for "easy"
|
||||||
|
easeAgainDelta = -0.20 // ease nudged down on a lapse (still floored at minEase)
|
||||||
|
easeEasyDelta = 0.15 // ease nudged up when a card feels easy
|
||||||
|
)
|
||||||
|
|
||||||
|
// State is the spaced-repetition state of one card. It mirrors the scheduling
|
||||||
|
// columns on vocab_words so a review is "load State → next(grade) → persist".
|
||||||
|
type State struct {
|
||||||
|
Reps int
|
||||||
|
Interval int // days until the next review
|
||||||
|
Ease float64
|
||||||
|
Lapses int
|
||||||
|
}
|
||||||
|
|
||||||
|
// next returns the card's state after a review with the given grade. It never
|
||||||
|
// mutates the receiver. "again" steps the card back to a 1-day interval and
|
||||||
|
// counts a lapse (but only nudges ease down, never wipes progress harshly);
|
||||||
|
// "good" advances one rung of the ladder; "easy" advances a rung and a bit more.
|
||||||
|
func (s State) next(grade Grade) State {
|
||||||
|
ease := s.Ease
|
||||||
|
if ease == 0 {
|
||||||
|
ease = startEase
|
||||||
|
}
|
||||||
|
|
||||||
|
switch grade {
|
||||||
|
case GradeAgain:
|
||||||
|
return State{
|
||||||
|
Reps: 0,
|
||||||
|
Interval: 1,
|
||||||
|
Ease: clampEase(ease + easeAgainDelta),
|
||||||
|
Lapses: s.Lapses + 1,
|
||||||
|
}
|
||||||
|
case GradeEasy:
|
||||||
|
ease = clampEase(ease + easeEasyDelta)
|
||||||
|
reps := s.Reps + 1
|
||||||
|
return State{
|
||||||
|
Reps: reps,
|
||||||
|
Interval: int(math.Round(float64(goodInterval(reps, s.Interval, ease)) * easyBonus)),
|
||||||
|
Ease: ease,
|
||||||
|
Lapses: s.Lapses,
|
||||||
|
}
|
||||||
|
default: // GradeGood
|
||||||
|
reps := s.Reps + 1
|
||||||
|
return State{
|
||||||
|
Reps: reps,
|
||||||
|
Interval: goodInterval(reps, s.Interval, ease),
|
||||||
|
Ease: ease,
|
||||||
|
Lapses: s.Lapses,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// goodInterval returns the day-interval for a successful review: the explicit
|
||||||
|
// ladder while it lasts, then geometric growth by ease once past it.
|
||||||
|
func goodInterval(reps, prevInterval int, ease float64) int {
|
||||||
|
if reps >= 1 && reps <= len(ladder) {
|
||||||
|
return ladder[reps-1]
|
||||||
|
}
|
||||||
|
prev := prevInterval
|
||||||
|
if prev < ladder[len(ladder)-1] {
|
||||||
|
prev = ladder[len(ladder)-1]
|
||||||
|
}
|
||||||
|
return int(math.Round(float64(prev) * ease))
|
||||||
|
}
|
||||||
|
|
||||||
|
func clampEase(e float64) float64 {
|
||||||
|
if e < minEase {
|
||||||
|
return minEase
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
66
internal/vocab/scheduler_test.go
Normal file
66
internal/vocab/scheduler_test.go
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
package vocab
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// TestLadderProgression walks a card up the Leitner ladder on repeated "good"
|
||||||
|
// reviews: 1 → 3 → 7 → 16 → 35 days, then geometric growth by ease.
|
||||||
|
func TestLadderProgression(t *testing.T) {
|
||||||
|
s := State{Ease: startEase}
|
||||||
|
want := []int{1, 3, 7, 16, 35}
|
||||||
|
for i, w := range want {
|
||||||
|
s = s.next(GradeGood)
|
||||||
|
if s.Interval != w {
|
||||||
|
t.Fatalf("rung %d: interval=%d, want %d", i, s.Interval, w)
|
||||||
|
}
|
||||||
|
if s.Reps != i+1 {
|
||||||
|
t.Fatalf("rung %d: reps=%d, want %d", i, s.Reps, i+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Past the ladder it grows by ease (35 * 2.5 = 87.5 → 88).
|
||||||
|
s = s.next(GradeGood)
|
||||||
|
if s.Interval != 88 {
|
||||||
|
t.Fatalf("post-ladder interval=%d, want 88", s.Interval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAgainStepsBackGently proves a lapse resets to a 1-day interval and counts
|
||||||
|
// a lapse, but only nudges ease down (never below the floor) — no harsh wipe.
|
||||||
|
func TestAgainStepsBackGently(t *testing.T) {
|
||||||
|
s := State{Reps: 4, Interval: 35, Ease: startEase}
|
||||||
|
s = s.next(GradeAgain)
|
||||||
|
if s.Interval != 1 {
|
||||||
|
t.Fatalf("again interval=%d, want 1", s.Interval)
|
||||||
|
}
|
||||||
|
if s.Reps != 0 {
|
||||||
|
t.Fatalf("again reps=%d, want 0", s.Reps)
|
||||||
|
}
|
||||||
|
if s.Lapses != 1 {
|
||||||
|
t.Fatalf("again lapses=%d, want 1", s.Lapses)
|
||||||
|
}
|
||||||
|
if s.Ease != startEase+easeAgainDelta {
|
||||||
|
t.Fatalf("again ease=%v, want %v", s.Ease, startEase+easeAgainDelta)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ease never drops below the floor no matter how many lapses.
|
||||||
|
low := State{Ease: minEase}
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
low = low.next(GradeAgain)
|
||||||
|
}
|
||||||
|
if low.Ease < minEase {
|
||||||
|
t.Fatalf("ease fell below floor: %v", low.Ease)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEasyAdvancesFurther proves "easy" both bumps ease and lands a longer
|
||||||
|
// interval than a plain "good" at the same rung.
|
||||||
|
func TestEasyAdvancesFurther(t *testing.T) {
|
||||||
|
base := State{Reps: 2, Interval: 7, Ease: startEase}
|
||||||
|
good := base.next(GradeGood)
|
||||||
|
easy := base.next(GradeEasy)
|
||||||
|
if easy.Interval <= good.Interval {
|
||||||
|
t.Fatalf("easy interval %d should exceed good interval %d", easy.Interval, good.Interval)
|
||||||
|
}
|
||||||
|
if easy.Ease <= startEase {
|
||||||
|
t.Fatalf("easy should raise ease, got %v", easy.Ease)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import { EditorCore, type EditorChange } from './components/Editor/EditorCore'
|
|||||||
import { ToneSelect } from './components/Editor/ToneSelect'
|
import { ToneSelect } from './components/Editor/ToneSelect'
|
||||||
import { ExportMenu } from './components/Export/ExportMenu'
|
import { ExportMenu } from './components/Export/ExportMenu'
|
||||||
import { HistoryPanel } from './components/History/HistoryPanel'
|
import { HistoryPanel } from './components/History/HistoryPanel'
|
||||||
|
import { GardenPanel } from './components/Garden/GardenPanel'
|
||||||
import { StatusBar } from './components/StatusBar/StatusBar'
|
import { StatusBar } from './components/StatusBar/StatusBar'
|
||||||
import { PetalCompanion } from './components/Companion/PetalCompanion'
|
import { PetalCompanion } from './components/Companion/PetalCompanion'
|
||||||
import { UpdateBanner } from './components/UpdateBanner/UpdateBanner'
|
import { UpdateBanner } from './components/UpdateBanner/UpdateBanner'
|
||||||
@@ -46,6 +47,7 @@ export default function App() {
|
|||||||
// editor to remount with the restored content (its initialContent is read
|
// editor to remount with the restored content (its initialContent is read
|
||||||
// only on mount).
|
// only on mount).
|
||||||
const [historyOpen, setHistoryOpen] = useState(false)
|
const [historyOpen, setHistoryOpen] = useState(false)
|
||||||
|
const [gardenOpen, setGardenOpen] = useState(false)
|
||||||
const [editorEpoch, setEditorEpoch] = useState(0)
|
const [editorEpoch, setEditorEpoch] = useState(0)
|
||||||
|
|
||||||
// Live mirrors of the current doc's editable fields so the "discard blank
|
// Live mirrors of the current doc's editable fields so the "discard blank
|
||||||
@@ -70,9 +72,11 @@ export default function App() {
|
|||||||
suggestions,
|
suggestions,
|
||||||
checking,
|
checking,
|
||||||
voicing,
|
voicing,
|
||||||
|
collocating,
|
||||||
llmDown,
|
llmDown,
|
||||||
schedule: scheduleCheckpoint,
|
schedule: scheduleCheckpoint,
|
||||||
runVoice,
|
runVoice,
|
||||||
|
runCollocation,
|
||||||
removeSuggestion,
|
removeSuggestion,
|
||||||
} = useCheckpoint(currentDoc?.id ?? null)
|
} = useCheckpoint(currentDoc?.id ?? null)
|
||||||
// Browser-side spell checker — loads the en-US dictionary once per session.
|
// Browser-side spell checker — loads the en-US dictionary once per session.
|
||||||
@@ -395,6 +399,23 @@ export default function App() {
|
|||||||
</button>
|
</button>
|
||||||
<span className="text-xl">🌸</span>
|
<span className="text-xl">🌸</span>
|
||||||
<span className="text-lg font-extrabold text-plum">Petal</span>
|
<span className="text-lg font-extrabold text-plum">Petal</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setGardenOpen(true)}
|
||||||
|
aria-label="Vocabulary garden"
|
||||||
|
title="Words you've looked up, blooming for review"
|
||||||
|
className="petal-tap-sm ml-auto inline-flex h-9 items-center gap-1.5 whitespace-nowrap px-3 text-sm font-bold"
|
||||||
|
style={{
|
||||||
|
borderRadius: 'var(--radius-pill)',
|
||||||
|
background: 'var(--color-surface)',
|
||||||
|
color: 'var(--color-plum)',
|
||||||
|
boxShadow: 'var(--shadow-soft)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span aria-hidden>🌷</span>
|
||||||
|
<span>词汇花园</span>
|
||||||
|
<span style={{ color: 'var(--color-muted)' }}>· Garden</span>
|
||||||
|
</button>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div className="relative flex min-h-0 flex-1">
|
<div className="relative flex min-h-0 flex-1">
|
||||||
@@ -471,6 +492,8 @@ export default function App() {
|
|||||||
onDismiss={handleDismiss}
|
onDismiss={handleDismiss}
|
||||||
onVoiceCheck={runVoice}
|
onVoiceCheck={runVoice}
|
||||||
voicing={voicing}
|
voicing={voicing}
|
||||||
|
onCollocationCheck={runCollocation}
|
||||||
|
collocating={collocating}
|
||||||
onFocusMode={() => setFocusMode(true)}
|
onFocusMode={() => setFocusMode(true)}
|
||||||
spellChecker={spellChecker}
|
spellChecker={spellChecker}
|
||||||
onAddWord={addWord}
|
onAddWord={addWord}
|
||||||
@@ -484,6 +507,7 @@ export default function App() {
|
|||||||
saveStatus={status}
|
saveStatus={status}
|
||||||
checking={checking}
|
checking={checking}
|
||||||
voicing={voicing}
|
voicing={voicing}
|
||||||
|
collocating={collocating}
|
||||||
llmDown={llmDown}
|
llmDown={llmDown}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -507,6 +531,16 @@ export default function App() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{gardenOpen && (
|
||||||
|
<GardenPanel
|
||||||
|
onClose={() => setGardenOpen(false)}
|
||||||
|
onOpenDoc={(id) => {
|
||||||
|
setGardenOpen(false)
|
||||||
|
void openDoc(id)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{updateAvailable && <UpdateBanner />}
|
{updateAvailable && <UpdateBanner />}
|
||||||
|
|
||||||
<div className="petal-no-print">
|
<div className="petal-no-print">
|
||||||
|
|||||||
@@ -76,7 +76,29 @@ export interface Gloss {
|
|||||||
gloss: string
|
gloss: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SuggestionType = 'grammar' | 'phrasing' | 'idiom' | 'clarity' | 'voice'
|
export type SuggestionType = 'grammar' | 'phrasing' | 'idiom' | 'clarity' | 'voice' | 'collocation'
|
||||||
|
|
||||||
|
// One word in the vocabulary garden: a looked-up word with its gloss/phonetic,
|
||||||
|
// the sentence it was met in, and its spaced-repetition state. `reps` drives how
|
||||||
|
// "bloomed" its blossom looks; `due_at` decides when it next surfaces for review.
|
||||||
|
export interface VocabWord {
|
||||||
|
id: string
|
||||||
|
word: string
|
||||||
|
gloss: string
|
||||||
|
phonetic: string
|
||||||
|
example: string
|
||||||
|
doc_id: string | null
|
||||||
|
due_at: string
|
||||||
|
interval_days: number
|
||||||
|
ease: number
|
||||||
|
reps: number
|
||||||
|
lapses: number
|
||||||
|
last_reviewed: string | null
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// The self-assessment grades a flashcard review can record.
|
||||||
|
export type VocabGrade = 'again' | 'good' | 'easy'
|
||||||
|
|
||||||
// A point-in-time snapshot of a document. List responses omit the heavy
|
// A point-in-time snapshot of a document. List responses omit the heavy
|
||||||
// content/content_text fields; they arrive only on getVersion (preview/restore).
|
// content/content_text fields; they arrive only on getVersion (preview/restore).
|
||||||
@@ -141,6 +163,10 @@ export const api = {
|
|||||||
// Voice-consistency pass: whole-document, explicit-action, slower. Returns the
|
// Voice-consistency pass: whole-document, explicit-action, slower. Returns the
|
||||||
// unified pending set too. Rate-limited per document server-side.
|
// unified pending set too. Rate-limited per document server-side.
|
||||||
voiceDoc: (id: string) => req<Suggestion[]>(`/docs/${id}/voice`, { method: 'POST' }),
|
voiceDoc: (id: string) => req<Suggestion[]>(`/docs/${id}/voice`, { method: 'POST' }),
|
||||||
|
// Collocation coach: whole-document, explicit-action pass flagging non-native
|
||||||
|
// word pairings ("do a decision" → "make a decision"). Returns the unified
|
||||||
|
// pending set too. Rate-limited per document server-side.
|
||||||
|
collocationDoc: (id: string) => req<Suggestion[]>(`/docs/${id}/collocation`, { method: 'POST' }),
|
||||||
// Pending suggestions for a doc, loaded when the editor opens it.
|
// Pending suggestions for a doc, loaded when the editor opens it.
|
||||||
listSuggestions: (id: string) => req<Suggestion[]>(`/docs/${id}/suggestions`),
|
listSuggestions: (id: string) => req<Suggestion[]>(`/docs/${id}/suggestions`),
|
||||||
acceptSuggestion: (id: string) =>
|
acceptSuggestion: (id: string) =>
|
||||||
@@ -221,6 +247,23 @@ export const api = {
|
|||||||
unassignTag: (docId: string, tagId: string) =>
|
unassignTag: (docId: string, tagId: string) =>
|
||||||
req<void>(`/docs/${docId}/tags/${tagId}`, { method: 'DELETE' }),
|
req<void>(`/docs/${docId}/tags/${tagId}`, { method: 'DELETE' }),
|
||||||
|
|
||||||
|
// Vocabulary garden. recordVocab captures (or refreshes) a looked-up word —
|
||||||
|
// idempotent per word, fired automatically on lookup. listVocab is the whole
|
||||||
|
// garden; dueVocab is just the cards ready for review; reviewVocab grades one
|
||||||
|
// card and returns its rescheduled state; deleteVocab removes a word.
|
||||||
|
recordVocab: (body: {
|
||||||
|
word: string
|
||||||
|
gloss?: string
|
||||||
|
phonetic?: string
|
||||||
|
example?: string
|
||||||
|
doc_id?: string | null
|
||||||
|
}) => req<VocabWord>('/vocab', { method: 'POST', body: JSON.stringify(body) }),
|
||||||
|
listVocab: () => req<VocabWord[]>('/vocab'),
|
||||||
|
dueVocab: () => req<VocabWord[]>('/vocab/due'),
|
||||||
|
reviewVocab: (id: string, grade: VocabGrade) =>
|
||||||
|
req<VocabWord>(`/vocab/${id}/review`, { method: 'POST', body: JSON.stringify({ grade }) }),
|
||||||
|
deleteVocab: (id: string) => req<void>(`/vocab/${id}`, { method: 'DELETE' }),
|
||||||
|
|
||||||
// Current deployed build id — changes whenever a new frontend ships. The
|
// Current deployed build id — changes whenever a new frontend ships. The
|
||||||
// app polls this to offer a refresh. Bypasses any cache so the answer is live.
|
// app polls this to offer a refresh. Bypasses any cache so the answer is live.
|
||||||
version: () => req<{ version: string }>('/version', { cache: 'no-store' }),
|
version: () => req<{ version: string }>('/version', { cache: 'no-store' }),
|
||||||
|
|||||||
@@ -53,6 +53,10 @@ interface Props {
|
|||||||
// it runs (drives the toolbar button's loading state).
|
// it runs (drives the toolbar button's loading state).
|
||||||
onVoiceCheck: () => void
|
onVoiceCheck: () => void
|
||||||
voicing: boolean
|
voicing: boolean
|
||||||
|
// Triggers the whole-document collocation coach; `collocating` is true while it
|
||||||
|
// runs (drives the toolbar button's loading state).
|
||||||
|
onCollocationCheck: () => void
|
||||||
|
collocating: boolean
|
||||||
// Fired when the editor gains focus, so the app can enter distraction-free mode.
|
// Fired when the editor gains focus, so the app can enter distraction-free mode.
|
||||||
onFocusMode?: () => void
|
onFocusMode?: () => void
|
||||||
// Browser-side spell checker (null until the dictionary loads). Adding a word
|
// Browser-side spell checker (null until the dictionary loads). Adding a word
|
||||||
@@ -81,6 +85,33 @@ interface WordInfoState {
|
|||||||
left: number
|
left: number
|
||||||
loading: boolean
|
loading: boolean
|
||||||
info: WordInfo | null
|
info: WordInfo | null
|
||||||
|
// Garden state: the captured word's id (null until the auto-capture returns or
|
||||||
|
// after it's removed) and whether it's currently in the garden.
|
||||||
|
vocabId: string | null
|
||||||
|
saved: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// sentenceAround pulls the sentence containing `word` out of a block of text, so
|
||||||
|
// a captured vocab word carries the context it was met in. Falls back to the
|
||||||
|
// whole (trimmed, length-capped) text when no sentence boundary is found.
|
||||||
|
function sentenceAround(text: string, wordStart: number): string {
|
||||||
|
const stops = /[.!?。!?\n]/
|
||||||
|
let start = 0
|
||||||
|
for (let i = wordStart - 1; i >= 0; i--) {
|
||||||
|
if (stops.test(text[i])) {
|
||||||
|
start = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let end = text.length
|
||||||
|
for (let i = wordStart; i < text.length; i++) {
|
||||||
|
if (stops.test(text[i])) {
|
||||||
|
end = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const s = text.slice(start, end).trim()
|
||||||
|
return s.length > 240 ? s.slice(0, 240).trim() + '…' : s
|
||||||
}
|
}
|
||||||
|
|
||||||
// A tiny CSS-only confetti burst played at an accept. Four palette-colored dots
|
// A tiny CSS-only confetti burst played at an accept. Four palette-colored dots
|
||||||
@@ -185,6 +216,8 @@ export function EditorCore({
|
|||||||
onDismiss,
|
onDismiss,
|
||||||
onVoiceCheck,
|
onVoiceCheck,
|
||||||
voicing,
|
voicing,
|
||||||
|
onCollocationCheck,
|
||||||
|
collocating,
|
||||||
onFocusMode,
|
onFocusMode,
|
||||||
spellChecker,
|
spellChecker,
|
||||||
onAddWord,
|
onAddWord,
|
||||||
@@ -630,13 +663,33 @@ export function EditorCore({
|
|||||||
closeCard()
|
closeCard()
|
||||||
setMisspell(null)
|
setMisspell(null)
|
||||||
const token = ++wordReqRef.current
|
const token = ++wordReqRef.current
|
||||||
setWordInfo({ word: range.word, from: range.from, to: range.to, top, left, loading: true, info: null })
|
setWordInfo({ word: range.word, from: range.from, to: range.to, top, left, loading: true, info: null, vocabId: null, saved: false })
|
||||||
|
// The sentence the word sits in, for review context in the garden.
|
||||||
|
const block = editor.state.doc.resolve(range.from).parent.textContent
|
||||||
|
const example = sentenceAround(block, Math.max(0, range.from - editor.state.doc.resolve(range.from).start()))
|
||||||
api
|
api
|
||||||
.lookupWord(range.word)
|
.lookupWord(range.word)
|
||||||
.then((info) => {
|
.then((info) => {
|
||||||
if (token === wordReqRef.current) {
|
if (token !== wordReqRef.current) return
|
||||||
setWordInfo((w) => (w ? { ...w, loading: false, info } : null))
|
setWordInfo((w) => (w ? { ...w, loading: false, info } : null))
|
||||||
}
|
// Auto-capture into the vocabulary garden — only words the dictionary
|
||||||
|
// actually knows (a real gloss or definition), so accidental lookups of
|
||||||
|
// typos or proper nouns don't clutter the garden. Looking words up IS
|
||||||
|
// the data source; this costs the writer nothing.
|
||||||
|
const known = !!info.gloss || info.definitions.length > 0
|
||||||
|
if (!known) return
|
||||||
|
api
|
||||||
|
.recordVocab({
|
||||||
|
word: range.word,
|
||||||
|
gloss: info.gloss,
|
||||||
|
phonetic: info.phonetic,
|
||||||
|
example,
|
||||||
|
doc_id: docId,
|
||||||
|
})
|
||||||
|
.then((row) => {
|
||||||
|
setWordInfo((w) => (w && w.word === range.word ? { ...w, vocabId: row.id, saved: true } : w))
|
||||||
|
})
|
||||||
|
.catch((err) => console.error('vocab capture failed', err))
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.error('word lookup failed', err)
|
console.error('word lookup failed', err)
|
||||||
@@ -645,9 +698,31 @@ export function EditorCore({
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
[editor, closeCard],
|
[editor, closeCard, docId],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Toggle a looked-up word in/out of the vocabulary garden from the WordCard
|
||||||
|
// heart. Auto-capture saves it on lookup; this lets the writer remove a word
|
||||||
|
// she already knows (or re-add one she removed by mistake).
|
||||||
|
const toggleSaveWord = useCallback(() => {
|
||||||
|
setWordInfo((w) => {
|
||||||
|
if (!w || !w.info) return w
|
||||||
|
if (w.saved && w.vocabId) {
|
||||||
|
const id = w.vocabId
|
||||||
|
api.deleteVocab(id).catch((err) => console.error('vocab remove failed', err))
|
||||||
|
return { ...w, saved: false, vocabId: null }
|
||||||
|
}
|
||||||
|
const word = w.word
|
||||||
|
const block = editor?.state.doc.resolve(w.from)
|
||||||
|
const example = block ? sentenceAround(block.parent.textContent, Math.max(0, w.from - block.start())) : ''
|
||||||
|
api
|
||||||
|
.recordVocab({ word, gloss: w.info.gloss, phonetic: w.info.phonetic, example, doc_id: docId })
|
||||||
|
.then((row) => setWordInfo((cur) => (cur && cur.word === word ? { ...cur, vocabId: row.id, saved: true } : cur)))
|
||||||
|
.catch((err) => console.error('vocab save failed', err))
|
||||||
|
return { ...w, saved: true }
|
||||||
|
})
|
||||||
|
}, [editor, docId])
|
||||||
|
|
||||||
// Right-click a word to look it up. Right-clicking off any word falls through
|
// Right-click a word to look it up. Right-clicking off any word falls through
|
||||||
// to the native menu (so copy/paste-by-menu still works — see the Selection fix).
|
// to the native menu (so copy/paste-by-menu still works — see the Selection fix).
|
||||||
const handleContextMenu = useCallback(
|
const handleContextMenu = useCallback(
|
||||||
@@ -926,7 +1001,13 @@ export function EditorCore({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-1 flex-col">
|
<div className="flex flex-1 flex-col">
|
||||||
<Toolbar editor={editor} onVoiceCheck={onVoiceCheck} voicing={voicing} />
|
<Toolbar
|
||||||
|
editor={editor}
|
||||||
|
onVoiceCheck={onVoiceCheck}
|
||||||
|
voicing={voicing}
|
||||||
|
onCollocationCheck={onCollocationCheck}
|
||||||
|
collocating={collocating}
|
||||||
|
/>
|
||||||
<div
|
<div
|
||||||
ref={wrapperRef}
|
ref={wrapperRef}
|
||||||
className="relative flex-1"
|
className="relative flex-1"
|
||||||
@@ -969,6 +1050,8 @@ export function EditorCore({
|
|||||||
word={wordInfo.word}
|
word={wordInfo.word}
|
||||||
info={wordInfo.info}
|
info={wordInfo.info}
|
||||||
loading={wordInfo.loading}
|
loading={wordInfo.loading}
|
||||||
|
saved={wordInfo.saved}
|
||||||
|
onToggleSave={toggleSaveWord}
|
||||||
style={{ top: wordInfo.top, left: wordInfo.left }}
|
style={{ top: wordInfo.top, left: wordInfo.left }}
|
||||||
onReplace={replaceWord}
|
onReplace={replaceWord}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -11,11 +11,15 @@ interface Props {
|
|||||||
word: string
|
word: string
|
||||||
info: WordInfo | null
|
info: WordInfo | null
|
||||||
loading: boolean
|
loading: boolean
|
||||||
|
// Whether the word is in the vocabulary garden (auto-saved on lookup). The
|
||||||
|
// heart toggles it; `onToggleSave` removes/re-adds it.
|
||||||
|
saved: boolean
|
||||||
|
onToggleSave: () => void
|
||||||
style: React.CSSProperties
|
style: React.CSSProperties
|
||||||
onReplace: (synonym: string) => void
|
onReplace: (synonym: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export function WordCard({ word, info, loading, style, onReplace }: Props) {
|
export function WordCard({ word, info, loading, saved, onToggleSave, style, onReplace }: Props) {
|
||||||
const definitions = info?.definitions ?? []
|
const definitions = info?.definitions ?? []
|
||||||
const synonyms = info?.synonyms ?? []
|
const synonyms = info?.synonyms ?? []
|
||||||
const gloss = info?.gloss ?? ''
|
const gloss = info?.gloss ?? ''
|
||||||
@@ -48,18 +52,35 @@ export function WordCard({ word, info, loading, style, onReplace }: Props) {
|
|||||||
<span className="font-bold" style={{ color: 'var(--color-plum)' }}>
|
<span className="font-bold" style={{ color: 'var(--color-plum)' }}>
|
||||||
{word}
|
{word}
|
||||||
</span>
|
</span>
|
||||||
{speechSupported() && (
|
<div className="ml-auto flex items-center gap-1.5">
|
||||||
<button
|
{!empty && !loading && (
|
||||||
type="button"
|
<button
|
||||||
onClick={() => speak(word)}
|
type="button"
|
||||||
aria-label={`Pronounce ${word}`}
|
onClick={onToggleSave}
|
||||||
title="朗读 · Read aloud"
|
aria-label={saved ? 'Remove from vocabulary garden' : 'Save to vocabulary garden'}
|
||||||
className="ml-auto flex h-7 w-7 items-center justify-center rounded-full text-sm"
|
aria-pressed={saved}
|
||||||
style={{ background: 'var(--color-surface-alt)', color: 'var(--color-plum)' }}
|
title={saved ? '已在词汇花园 · In your garden (tap to remove)' : '加入词汇花园 · Save to garden'}
|
||||||
>
|
className="flex h-7 w-7 items-center justify-center rounded-full text-sm transition-transform"
|
||||||
🔊
|
style={{
|
||||||
</button>
|
background: saved ? 'var(--color-accent)' : 'var(--color-surface-alt)',
|
||||||
)}
|
}}
|
||||||
|
>
|
||||||
|
{saved ? '💚' : '🤍'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{speechSupported() && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => speak(word)}
|
||||||
|
aria-label={`Pronounce ${word}`}
|
||||||
|
title="朗读 · Read aloud"
|
||||||
|
className="flex h-7 w-7 items-center justify-center rounded-full text-sm"
|
||||||
|
style={{ background: 'var(--color-surface-alt)', color: 'var(--color-plum)' }}
|
||||||
|
>
|
||||||
|
🔊
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* How to say it — the pronunciation aid for an English learner, paired
|
{/* How to say it — the pronunciation aid for an English learner, paired
|
||||||
|
|||||||
@@ -9,4 +9,5 @@ export const TYPE_META: Record<SuggestionType, { color: string; label: string }>
|
|||||||
idiom: { color: 'var(--color-lavender)', label: 'Idiom' },
|
idiom: { color: 'var(--color-lavender)', label: 'Idiom' },
|
||||||
clarity: { color: 'var(--color-sky)', label: 'Clarity' },
|
clarity: { color: 'var(--color-sky)', label: 'Clarity' },
|
||||||
voice: { color: 'var(--color-honey)', label: 'Voice' },
|
voice: { color: 'var(--color-honey)', label: 'Voice' },
|
||||||
|
collocation: { color: 'var(--color-blossom)', label: 'Word pairing' },
|
||||||
}
|
}
|
||||||
|
|||||||
492
web/src/components/Garden/GardenPanel.tsx
Normal file
492
web/src/components/Garden/GardenPanel.tsx
Normal file
@@ -0,0 +1,492 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { api, type VocabGrade, type VocabWord } from '../../api/client'
|
||||||
|
import { speak, speechSupported } from '../../audio/speech'
|
||||||
|
|
||||||
|
// GardenPanel is the vocabulary garden: every word the writer has looked up,
|
||||||
|
// grown into a blossom that opens further the more she remembers it, plus a
|
||||||
|
// gentle spaced-repetition review. Words are captured automatically on lookup
|
||||||
|
// (zero effort), so the garden fills itself as she writes. The sleepy kitten
|
||||||
|
// naps among the blossoms — the same companion gag, at rest in her little
|
||||||
|
// meadow. Bilingual, zh-first, to match Petal's chrome.
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
onClose: () => void
|
||||||
|
// Open the document a word was met in (so "where did I see this?" is one tap).
|
||||||
|
onOpenDoc?: (docId: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
// blossom maps a word's successful-review count to how bloomed its flower looks:
|
||||||
|
// a fresh seedling opens into a full blossom as it's remembered. No wilting — a
|
||||||
|
// forgotten word just stops climbing, never shames.
|
||||||
|
function blossom(reps: number): string {
|
||||||
|
if (reps <= 0) return '🌱'
|
||||||
|
if (reps <= 2) return '🌿'
|
||||||
|
if (reps <= 4) return '🌷'
|
||||||
|
if (reps <= 6) return '🌸'
|
||||||
|
return '🌺'
|
||||||
|
}
|
||||||
|
|
||||||
|
// blankOut hides the target word in its example sentence with a soft blank, so a
|
||||||
|
// flashcard can quiz recall in context. Whole-word, case-insensitive.
|
||||||
|
function blankOut(sentence: string, word: string): string {
|
||||||
|
if (!sentence) return ''
|
||||||
|
try {
|
||||||
|
const re = new RegExp(`\\b${word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'gi')
|
||||||
|
return sentence.replace(re, '____')
|
||||||
|
} catch {
|
||||||
|
return sentence
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GardenPanel({ onClose, onOpenDoc }: Props) {
|
||||||
|
const [words, setWords] = useState<VocabWord[] | null>(null)
|
||||||
|
const [due, setDue] = useState<VocabWord[]>([])
|
||||||
|
const [error, setError] = useState(false)
|
||||||
|
// Review session state: the queue (snapshot of due at start), a cursor, and
|
||||||
|
// whether the current card's answer is revealed.
|
||||||
|
const [queue, setQueue] = useState<VocabWord[] | null>(null)
|
||||||
|
const [cursor, setCursor] = useState(0)
|
||||||
|
const [revealed, setRevealed] = useState(false)
|
||||||
|
const [expanded, setExpanded] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setError(false)
|
||||||
|
try {
|
||||||
|
const [all, dueNow] = await Promise.all([api.listVocab(), api.dueVocab()])
|
||||||
|
setWords(all)
|
||||||
|
setDue(dueNow)
|
||||||
|
} catch {
|
||||||
|
setError(true)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
// Escape closes the panel (or ends a review session back to the garden).
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
if (queue) setQueue(null)
|
||||||
|
else onClose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', onKey)
|
||||||
|
return () => window.removeEventListener('keydown', onKey)
|
||||||
|
}, [onClose, queue])
|
||||||
|
|
||||||
|
const startReview = useCallback(() => {
|
||||||
|
if (due.length === 0) return
|
||||||
|
setQueue(due)
|
||||||
|
setCursor(0)
|
||||||
|
setRevealed(false)
|
||||||
|
}, [due])
|
||||||
|
|
||||||
|
const grade = useCallback(
|
||||||
|
async (g: VocabGrade) => {
|
||||||
|
if (!queue) return
|
||||||
|
const card = queue[cursor]
|
||||||
|
if (card) {
|
||||||
|
try {
|
||||||
|
await api.reviewVocab(card.id, g)
|
||||||
|
} catch {
|
||||||
|
/* keep going — a failed grade just won't reschedule */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const nextCursor = cursor + 1
|
||||||
|
if (nextCursor >= queue.length) {
|
||||||
|
// Session done — refresh the garden and drop back to it.
|
||||||
|
setQueue(null)
|
||||||
|
void load()
|
||||||
|
} else {
|
||||||
|
setCursor(nextCursor)
|
||||||
|
setRevealed(false)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[queue, cursor, load],
|
||||||
|
)
|
||||||
|
|
||||||
|
const removeWord = useCallback(async (id: string) => {
|
||||||
|
setWords((prev) => (prev ? prev.filter((w) => w.id !== id) : prev))
|
||||||
|
setDue((prev) => prev.filter((w) => w.id !== id))
|
||||||
|
try {
|
||||||
|
await api.deleteVocab(id)
|
||||||
|
} catch {
|
||||||
|
void load()
|
||||||
|
}
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="petal-no-print fixed inset-0 z-40 flex justify-end">
|
||||||
|
<div className="absolute inset-0" style={{ background: 'rgba(61, 46, 57, 0.18)' }} onClick={onClose} />
|
||||||
|
|
||||||
|
<aside
|
||||||
|
className="relative flex h-full w-full max-w-[420px] flex-col"
|
||||||
|
style={{
|
||||||
|
background: 'var(--color-surface)',
|
||||||
|
borderLeft: '1px solid var(--color-border)',
|
||||||
|
boxShadow: 'var(--shadow-soft)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<header
|
||||||
|
className="flex items-center justify-between px-5 py-4"
|
||||||
|
style={{ borderBottom: '1px solid var(--color-border)' }}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div className="text-base font-extrabold text-plum">🌷 词汇花园 · Vocabulary Garden</div>
|
||||||
|
<div className="text-xs" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
{queue ? '复习中 · Reviewing — recall, then grade yourself' : 'Words you looked up, blooming as you learn them'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Close garden"
|
||||||
|
onClick={onClose}
|
||||||
|
className="flex h-8 w-8 items-center justify-center rounded-full text-lg"
|
||||||
|
style={{ color: 'var(--color-muted)' }}
|
||||||
|
onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--color-surface-alt)')}
|
||||||
|
onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{queue ? (
|
||||||
|
<ReviewSession
|
||||||
|
queue={queue}
|
||||||
|
cursor={cursor}
|
||||||
|
revealed={revealed}
|
||||||
|
onReveal={() => setRevealed(true)}
|
||||||
|
onGrade={grade}
|
||||||
|
onQuit={() => setQueue(null)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<GardenView
|
||||||
|
words={words}
|
||||||
|
due={due}
|
||||||
|
error={error}
|
||||||
|
expanded={expanded}
|
||||||
|
onToggleExpand={(id) => setExpanded((cur) => (cur === id ? null : id))}
|
||||||
|
onStartReview={startReview}
|
||||||
|
onRemove={removeWord}
|
||||||
|
onOpenDoc={onOpenDoc}
|
||||||
|
onRetry={load}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- garden grid ------------------------------------------------------------
|
||||||
|
|
||||||
|
function GardenView({
|
||||||
|
words,
|
||||||
|
due,
|
||||||
|
error,
|
||||||
|
expanded,
|
||||||
|
onToggleExpand,
|
||||||
|
onStartReview,
|
||||||
|
onRemove,
|
||||||
|
onOpenDoc,
|
||||||
|
onRetry,
|
||||||
|
}: {
|
||||||
|
words: VocabWord[] | null
|
||||||
|
due: VocabWord[]
|
||||||
|
error: boolean
|
||||||
|
expanded: string | null
|
||||||
|
onToggleExpand: (id: string) => void
|
||||||
|
onStartReview: () => void
|
||||||
|
onRemove: (id: string) => void
|
||||||
|
onOpenDoc?: (docId: string) => void
|
||||||
|
onRetry: () => void
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{due.length > 0 && (
|
||||||
|
<div className="px-4 pt-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onStartReview}
|
||||||
|
className="w-full rounded-full py-3 text-sm font-extrabold text-white"
|
||||||
|
style={{ background: 'var(--color-accent)' }}
|
||||||
|
onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--color-accent-hover)')}
|
||||||
|
onMouseLeave={(e) => (e.currentTarget.style.background = 'var(--color-accent)')}
|
||||||
|
>
|
||||||
|
复习 {due.length} 个词 · Review {due.length} due 🌸
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
|
||||||
|
{error ? (
|
||||||
|
<div className="px-2 py-6 text-center text-sm" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
Couldn’t load your garden just now.
|
||||||
|
<button onClick={onRetry} className="ml-1 font-bold text-plum underline">
|
||||||
|
Try again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : words === null ? (
|
||||||
|
<div className="px-2 py-6 text-center text-sm" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
Loading…
|
||||||
|
</div>
|
||||||
|
) : words.length === 0 ? (
|
||||||
|
<div className="px-3 py-10 text-center" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
<div className="mb-2 text-4xl">🌱🐱💤</div>
|
||||||
|
<p className="text-sm leading-relaxed">
|
||||||
|
你的花园还空着。<br />
|
||||||
|
右键点一个英文单词查它的意思——它就会在这里发芽。
|
||||||
|
</p>
|
||||||
|
<p className="mt-2 text-xs">
|
||||||
|
Your garden is empty. Look up an English word (right-click it) and it’ll sprout here.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="flex flex-col gap-1.5">
|
||||||
|
{words.map((w) => {
|
||||||
|
const open = expanded === w.id
|
||||||
|
const isDue = due.some((d) => d.id === w.id)
|
||||||
|
return (
|
||||||
|
<li key={w.id}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onToggleExpand(w.id)}
|
||||||
|
className="flex w-full items-center gap-2.5 rounded-2xl px-3 py-2.5 text-left"
|
||||||
|
style={{
|
||||||
|
background: open ? 'var(--color-surface-alt)' : 'transparent',
|
||||||
|
border: `1px solid ${open ? 'var(--color-border)' : 'transparent'}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="text-xl" aria-hidden>
|
||||||
|
{blossom(w.reps)}
|
||||||
|
</span>
|
||||||
|
<span className="flex min-w-0 flex-1 flex-col">
|
||||||
|
<span className="truncate text-sm font-bold text-plum">{w.word}</span>
|
||||||
|
{w.gloss && (
|
||||||
|
<span
|
||||||
|
className="truncate text-xs"
|
||||||
|
style={{
|
||||||
|
color: 'var(--color-muted)',
|
||||||
|
fontFamily: "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{w.gloss}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
{isDue && (
|
||||||
|
<span
|
||||||
|
className="shrink-0 rounded-full px-2 py-0.5 text-[10px] font-bold"
|
||||||
|
style={{ background: 'var(--color-accent)', color: '#fff' }}
|
||||||
|
>
|
||||||
|
待复习 · due
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<div className="mb-1 ml-9 mr-2 mt-1 flex flex-col gap-2 text-xs" style={{ color: 'var(--color-plum)' }}>
|
||||||
|
{w.phonetic && <span style={{ color: 'var(--color-muted)' }}>/{w.phonetic}/</span>}
|
||||||
|
{w.example && (
|
||||||
|
<p className="italic leading-snug" style={{ fontFamily: 'var(--font-body)' }}>
|
||||||
|
“{w.example}”
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="text-[11px]" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
复习 {w.reps} 次 · seen {w.reps}× · 间隔 {w.interval_days}d
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{speechSupported() && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => speak(w.word)}
|
||||||
|
className="rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||||
|
style={{ background: 'var(--color-surface-alt)' }}
|
||||||
|
>
|
||||||
|
🔊 朗读
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{w.doc_id && onOpenDoc && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onOpenDoc(w.doc_id as string)}
|
||||||
|
className="rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||||
|
style={{ background: 'var(--color-surface-alt)' }}
|
||||||
|
>
|
||||||
|
📄 出处 · Source
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onRemove(w.id)}
|
||||||
|
className="ml-auto rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||||
|
style={{ color: 'var(--color-muted)' }}
|
||||||
|
>
|
||||||
|
🗑 移除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{words && words.length > 0 && (
|
||||||
|
<div
|
||||||
|
className="shrink-0 px-4 py-2.5 text-center text-[11px]"
|
||||||
|
style={{ borderTop: '1px solid var(--color-border)', color: 'var(--color-muted)' }}
|
||||||
|
>
|
||||||
|
🐱💤 {words.length} 朵花在花园里 · {words.length} blossom{words.length > 1 ? 's' : ''} growing
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- flashcard review -------------------------------------------------------
|
||||||
|
|
||||||
|
function ReviewSession({
|
||||||
|
queue,
|
||||||
|
cursor,
|
||||||
|
revealed,
|
||||||
|
onReveal,
|
||||||
|
onGrade,
|
||||||
|
onQuit,
|
||||||
|
}: {
|
||||||
|
queue: VocabWord[]
|
||||||
|
cursor: number
|
||||||
|
revealed: boolean
|
||||||
|
onReveal: () => void
|
||||||
|
onGrade: (g: VocabGrade) => void
|
||||||
|
onQuit: () => void
|
||||||
|
}) {
|
||||||
|
const card = queue[cursor]
|
||||||
|
// Alternate the quiz direction so she practices both recognition (see the
|
||||||
|
// English, recall the meaning) and production (see the meaning, recall the
|
||||||
|
// English word). Parity of the cursor keeps it deterministic within a session.
|
||||||
|
const production = cursor % 2 === 1 && !!card?.gloss
|
||||||
|
|
||||||
|
const prompt = useMemo(() => {
|
||||||
|
if (!card) return ''
|
||||||
|
if (production) return card.gloss
|
||||||
|
return card.example ? blankOut(card.example, card.word) : card.word
|
||||||
|
}, [card, production])
|
||||||
|
|
||||||
|
if (!card) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-0 flex-1 flex-col px-5 py-4">
|
||||||
|
<div className="mb-3 flex items-center justify-between text-xs" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
<span>
|
||||||
|
{cursor + 1} / {queue.length}
|
||||||
|
</span>
|
||||||
|
<button type="button" onClick={onQuit} className="font-semibold underline">
|
||||||
|
结束 · End
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* The card */}
|
||||||
|
<div
|
||||||
|
className="flex flex-1 flex-col items-center justify-center rounded-3xl px-5 py-8 text-center"
|
||||||
|
style={{ background: 'var(--color-surface-alt)', border: '1px solid var(--color-border)' }}
|
||||||
|
>
|
||||||
|
<div className="mb-2 text-3xl" aria-hidden>
|
||||||
|
{blossom(card.reps)}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="text-xl font-extrabold leading-snug text-plum"
|
||||||
|
style={{
|
||||||
|
fontFamily: production
|
||||||
|
? "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif"
|
||||||
|
: 'var(--font-body)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{prompt}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-xs" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
{production ? '这个中文意思的英文单词是?· Which English word?' : '这个词什么意思?· What does this mean?'}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{revealed && (
|
||||||
|
<div className="mt-5 w-full border-t pt-4" style={{ borderColor: 'var(--color-border)' }}>
|
||||||
|
<div className="flex items-center justify-center gap-2">
|
||||||
|
<span className="text-lg font-extrabold text-plum">{card.word}</span>
|
||||||
|
{speechSupported() && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => speak(card.word)}
|
||||||
|
aria-label={`Pronounce ${card.word}`}
|
||||||
|
className="flex h-6 w-6 items-center justify-center rounded-full text-xs"
|
||||||
|
style={{ background: 'var(--color-surface)' }}
|
||||||
|
>
|
||||||
|
🔊
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{card.phonetic && (
|
||||||
|
<div className="mt-0.5 text-xs" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
/{card.phonetic}/
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{card.gloss && (
|
||||||
|
<div
|
||||||
|
className="mt-1 text-sm font-semibold"
|
||||||
|
style={{
|
||||||
|
color: 'var(--color-accent-hover)',
|
||||||
|
fontFamily: "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{card.gloss}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{card.example && (
|
||||||
|
<p className="mt-2 text-xs italic leading-snug" style={{ color: 'var(--color-muted)', fontFamily: 'var(--font-body)' }}>
|
||||||
|
“{card.example}”
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Controls */}
|
||||||
|
<div className="mt-4">
|
||||||
|
{!revealed ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onReveal}
|
||||||
|
className="w-full rounded-full py-3 text-sm font-extrabold text-white"
|
||||||
|
style={{ background: 'var(--color-accent)' }}
|
||||||
|
onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--color-accent-hover)')}
|
||||||
|
onMouseLeave={(e) => (e.currentTarget.style.background = 'var(--color-accent)')}
|
||||||
|
>
|
||||||
|
翻看答案 · Show answer
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-3 gap-2">
|
||||||
|
<GradeButton color="var(--color-peach)" zh="再来" en="Again" onClick={() => onGrade('again')} />
|
||||||
|
<GradeButton color="var(--color-mint)" zh="记得" en="Good" onClick={() => onGrade('good')} />
|
||||||
|
<GradeButton color="var(--color-honey)" zh="太简单" en="Easy" onClick={() => onGrade('easy')} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function GradeButton({ color, zh, en, onClick }: { color: string; zh: string; en: string; onClick: () => void }) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClick}
|
||||||
|
className="flex flex-col items-center rounded-2xl py-2.5 text-plum"
|
||||||
|
style={{ background: color }}
|
||||||
|
>
|
||||||
|
<span className="text-sm font-extrabold">{zh}</span>
|
||||||
|
<span className="text-[11px] font-semibold opacity-80">{en}</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -12,6 +12,8 @@ interface Props {
|
|||||||
checking: boolean
|
checking: boolean
|
||||||
// True while a whole-document voice pass runs — shows a breathing honey dot.
|
// True while a whole-document voice pass runs — shows a breathing honey dot.
|
||||||
voicing: boolean
|
voicing: boolean
|
||||||
|
// True while a collocation pass runs — shows a breathing blossom dot.
|
||||||
|
collocating: boolean
|
||||||
// True when Petal can't reach its LLM helper — shows a gentle, reassuring note
|
// True when Petal can't reach its LLM helper — shows a gentle, reassuring note
|
||||||
// (the writing still saves locally, so this is awareness, not an error).
|
// (the writing still saves locally, so this is awareness, not an error).
|
||||||
llmDown: boolean
|
llmDown: boolean
|
||||||
@@ -28,7 +30,7 @@ const SAVE_LABEL: Record<SaveStatus, string> = {
|
|||||||
// StatusBar is the slim footer: word count on the left, save state and the
|
// StatusBar is the slim footer: word count on the left, save state and the
|
||||||
// grammar-checkpoint indicator on the right. The checkpoint dot is a soft rose
|
// grammar-checkpoint indicator on the right. The checkpoint dot is a soft rose
|
||||||
// circle that breathes while a check is in flight (spec → Signature animations).
|
// circle that breathes while a check is in flight (spec → Signature animations).
|
||||||
export function StatusBar({ wordCount, text, saveStatus, checking, voicing, llmDown }: Props) {
|
export function StatusBar({ wordCount, text, saveStatus, checking, voicing, collocating, llmDown }: Props) {
|
||||||
const label = SAVE_LABEL[saveStatus]
|
const label = SAVE_LABEL[saveStatus]
|
||||||
// The expanded stats panel toggles open when the word count is clicked.
|
// The expanded stats panel toggles open when the word count is clicked.
|
||||||
const [statsOpen, setStatsOpen] = useState(false)
|
const [statsOpen, setStatsOpen] = useState(false)
|
||||||
@@ -90,7 +92,19 @@ export function StatusBar({ wordCount, text, saveStatus, checking, voicing, llmD
|
|||||||
</span>
|
</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{llmDown && !checking && !voicing && (
|
{collocating && (
|
||||||
|
<>
|
||||||
|
<span aria-hidden>·</span>
|
||||||
|
<span className="inline-flex items-center gap-1.5" title="Petal is looking for more natural word pairings…">
|
||||||
|
<span
|
||||||
|
className="petal-checkpoint-dot inline-block h-2 w-2 rounded-full"
|
||||||
|
style={{ background: 'var(--color-blossom)' }}
|
||||||
|
/>
|
||||||
|
Finding natural phrasing…
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{llmDown && !checking && !voicing && !collocating && (
|
||||||
<>
|
<>
|
||||||
<span aria-hidden>·</span>
|
<span aria-hidden>·</span>
|
||||||
<span
|
<span
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ interface Props {
|
|||||||
// Runs the whole-document voice-consistency pass; `voicing` shows its progress.
|
// Runs the whole-document voice-consistency pass; `voicing` shows its progress.
|
||||||
onVoiceCheck: () => void
|
onVoiceCheck: () => void
|
||||||
voicing: boolean
|
voicing: boolean
|
||||||
|
// Runs the whole-document collocation coach; `collocating` shows its progress.
|
||||||
|
onCollocationCheck: () => void
|
||||||
|
collocating: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
// A formatting button. `active` gets the rose pill treatment so the writer can
|
// A formatting button. `active` gets the rose pill treatment so the writer can
|
||||||
@@ -165,7 +168,7 @@ function Swatch({
|
|||||||
// Toolbar renders inline formatting controls bound to the live Tiptap editor.
|
// Toolbar renders inline formatting controls bound to the live Tiptap editor.
|
||||||
// useEditorState subscribes to just the flags it reads, so the buttons reflect
|
// useEditorState subscribes to just the flags it reads, so the buttons reflect
|
||||||
// the current selection without re-rendering the whole tree on every keystroke.
|
// the current selection without re-rendering the whole tree on every keystroke.
|
||||||
export function Toolbar({ editor, onVoiceCheck, voicing }: Props) {
|
export function Toolbar({ editor, onVoiceCheck, voicing, onCollocationCheck, collocating }: Props) {
|
||||||
// Which popover (if any) is open. Only one at a time.
|
// Which popover (if any) is open. Only one at a time.
|
||||||
const [menu, setMenu] = useState<'color' | 'highlight' | 'size' | 'link' | 'table' | 'outline' | null>(null)
|
const [menu, setMenu] = useState<'color' | 'highlight' | 'size' | 'link' | 'table' | 'outline' | null>(null)
|
||||||
const [linkUrl, setLinkUrl] = useState('')
|
const [linkUrl, setLinkUrl] = useState('')
|
||||||
@@ -594,6 +597,28 @@ export function Toolbar({ editor, onVoiceCheck, voicing }: Props) {
|
|||||||
/>
|
/>
|
||||||
{voicing ? 'Reading…' : 'Check my voice 🍯'}
|
{voicing ? 'Reading…' : 'Check my voice 🍯'}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Make it sound natural"
|
||||||
|
disabled={collocating}
|
||||||
|
onMouseDown={(e) => e.preventDefault()} // keep editor selection
|
||||||
|
onClick={onCollocationCheck}
|
||||||
|
className="ml-1 inline-flex h-8 items-center gap-1.5 whitespace-nowrap px-3 text-xs font-bold transition-colors disabled:opacity-70"
|
||||||
|
style={{
|
||||||
|
borderRadius: 'var(--radius-pill)',
|
||||||
|
color: 'var(--color-plum)',
|
||||||
|
background: 'var(--color-blossom)',
|
||||||
|
}}
|
||||||
|
title="Find word pairings that natives usually say differently"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={collocating ? 'petal-checkpoint-dot inline-block h-2 w-2 rounded-full' : 'hidden'}
|
||||||
|
style={{ background: 'var(--color-plum)' }}
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
{collocating ? 'Reading…' : 'Make it sound natural 🌸'}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export function useCheckpoint(docId: string | null) {
|
|||||||
const [checking, setChecking] = useState(false)
|
const [checking, setChecking] = useState(false)
|
||||||
// True while a whole-document voice pass is in flight (explicit user action).
|
// True while a whole-document voice pass is in flight (explicit user action).
|
||||||
const [voicing, setVoicing] = useState(false)
|
const [voicing, setVoicing] = useState(false)
|
||||||
|
// True while a whole-document collocation pass is in flight (explicit action).
|
||||||
|
const [collocating, setCollocating] = useState(false)
|
||||||
// True when the last LLM pass couldn't reach the model (server 502 or network
|
// True when the last LLM pass couldn't reach the model (server 502 or network
|
||||||
// error). Drives a gentle, reassuring "helper is resting" note — the writing
|
// error). Drives a gentle, reassuring "helper is resting" note — the writing
|
||||||
// itself still saves fine, so this is awareness, not an error. Cleared on the
|
// itself still saves fine, so this is awareness, not an error. Cleared on the
|
||||||
@@ -89,6 +91,29 @@ export function useCheckpoint(docId: string | null) {
|
|||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
// Run the collocation coach now (explicit "Make it sound natural" action).
|
||||||
|
// Like runVoice it returns the unified pending set, so grammar + voice
|
||||||
|
// highlights survive. Shares the run token so a late response is discarded.
|
||||||
|
const runCollocation = useCallback(async () => {
|
||||||
|
const id = docIdRef.current
|
||||||
|
if (!id) return
|
||||||
|
clearTimeout(retryRef.current) // a collocation pass supersedes a queued grammar retry
|
||||||
|
const run = ++runRef.current
|
||||||
|
setCollocating(true)
|
||||||
|
try {
|
||||||
|
const full = await api.collocationDoc(id)
|
||||||
|
if (run === runRef.current && id === docIdRef.current) {
|
||||||
|
setSuggestions(full)
|
||||||
|
setLlmDown(false)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('collocation pass failed', err)
|
||||||
|
if (run === runRef.current) setLlmDown(true)
|
||||||
|
} finally {
|
||||||
|
if (run === runRef.current) setCollocating(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
// Call on every edit; schedules a check 4s after typing settles.
|
// Call on every edit; schedules a check 4s after typing settles.
|
||||||
const schedule = useCallback(() => {
|
const schedule = useCallback(() => {
|
||||||
clearTimeout(debounceRef.current)
|
clearTimeout(debounceRef.current)
|
||||||
@@ -105,6 +130,7 @@ export function useCheckpoint(docId: string | null) {
|
|||||||
setSuggestions([])
|
setSuggestions([])
|
||||||
setChecking(false)
|
setChecking(false)
|
||||||
setVoicing(false)
|
setVoicing(false)
|
||||||
|
setCollocating(false)
|
||||||
setLlmDown(false)
|
setLlmDown(false)
|
||||||
if (!docId) return
|
if (!docId) return
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
@@ -134,5 +160,5 @@ export function useCheckpoint(docId: string | null) {
|
|||||||
setSuggestions((prev) => prev.filter((s) => s.id !== id))
|
setSuggestions((prev) => prev.filter((s) => s.id !== id))
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
return { suggestions, checking, voicing, llmDown, schedule, runVoice, removeSuggestion }
|
return { suggestions, checking, voicing, collocating, llmDown, schedule, runVoice, runCollocation, removeSuggestion }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
--color-lavender: #C5B4E8; /* idiom */
|
--color-lavender: #C5B4E8; /* idiom */
|
||||||
--color-sky: #A8CCE8; /* clarity */
|
--color-sky: #A8CCE8; /* clarity */
|
||||||
--color-honey: #CE9B4F; /* voice */
|
--color-honey: #CE9B4F; /* voice */
|
||||||
|
--color-blossom: #E59ABF; /* collocation — warm blossom pink */
|
||||||
--color-success: #8FCFA8; /* saved / accepted */
|
--color-success: #8FCFA8; /* saved / accepted */
|
||||||
|
|
||||||
/* Typography */
|
/* Typography */
|
||||||
@@ -232,6 +233,7 @@ button, a, input {
|
|||||||
.petal-suggestion-idiom { border-bottom-color: var(--color-lavender); }
|
.petal-suggestion-idiom { border-bottom-color: var(--color-lavender); }
|
||||||
.petal-suggestion-clarity { border-bottom-color: var(--color-sky); }
|
.petal-suggestion-clarity { border-bottom-color: var(--color-sky); }
|
||||||
.petal-suggestion-voice { border-bottom-color: var(--color-honey); }
|
.petal-suggestion-voice { border-bottom-color: var(--color-honey); }
|
||||||
|
.petal-suggestion-collocation { border-bottom-color: var(--color-blossom); }
|
||||||
|
|
||||||
@keyframes petal-suggestion-in {
|
@keyframes petal-suggestion-in {
|
||||||
from { opacity: 0; transform: translateY(4px); }
|
from { opacity: 0; transform: translateY(4px); }
|
||||||
|
|||||||
Reference in New Issue
Block a user