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:
prosolis
2026-06-26 15:50:25 -07:00
parent 20442d1356
commit 8aa437ec82
23 changed files with 1614 additions and 58 deletions

View File

@@ -9,6 +9,7 @@ import { EditorCore, type EditorChange } from './components/Editor/EditorCore'
import { ToneSelect } from './components/Editor/ToneSelect'
import { ExportMenu } from './components/Export/ExportMenu'
import { HistoryPanel } from './components/History/HistoryPanel'
import { GardenPanel } from './components/Garden/GardenPanel'
import { StatusBar } from './components/StatusBar/StatusBar'
import { PetalCompanion } from './components/Companion/PetalCompanion'
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
// only on mount).
const [historyOpen, setHistoryOpen] = useState(false)
const [gardenOpen, setGardenOpen] = useState(false)
const [editorEpoch, setEditorEpoch] = useState(0)
// Live mirrors of the current doc's editable fields so the "discard blank
@@ -70,9 +72,11 @@ export default function App() {
suggestions,
checking,
voicing,
collocating,
llmDown,
schedule: scheduleCheckpoint,
runVoice,
runCollocation,
removeSuggestion,
} = useCheckpoint(currentDoc?.id ?? null)
// Browser-side spell checker — loads the en-US dictionary once per session.
@@ -395,6 +399,23 @@ export default function App() {
</button>
<span className="text-xl">🌸</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>
<div className="relative flex min-h-0 flex-1">
@@ -471,6 +492,8 @@ export default function App() {
onDismiss={handleDismiss}
onVoiceCheck={runVoice}
voicing={voicing}
onCollocationCheck={runCollocation}
collocating={collocating}
onFocusMode={() => setFocusMode(true)}
spellChecker={spellChecker}
onAddWord={addWord}
@@ -484,6 +507,7 @@ export default function App() {
saveStatus={status}
checking={checking}
voicing={voicing}
collocating={collocating}
llmDown={llmDown}
/>
</div>
@@ -507,6 +531,16 @@ export default function App() {
/>
)}
{gardenOpen && (
<GardenPanel
onClose={() => setGardenOpen(false)}
onOpenDoc={(id) => {
setGardenOpen(false)
void openDoc(id)
}}
/>
)}
{updateAvailable && <UpdateBanner />}
<div className="petal-no-print">

View File

@@ -76,7 +76,29 @@ export interface Gloss {
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
// 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
// unified pending set too. Rate-limited per document server-side.
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.
listSuggestions: (id: string) => req<Suggestion[]>(`/docs/${id}/suggestions`),
acceptSuggestion: (id: string) =>
@@ -221,6 +247,23 @@ export const api = {
unassignTag: (docId: string, tagId: string) =>
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
// app polls this to offer a refresh. Bypasses any cache so the answer is live.
version: () => req<{ version: string }>('/version', { cache: 'no-store' }),

View File

@@ -53,6 +53,10 @@ interface Props {
// it runs (drives the toolbar button's loading state).
onVoiceCheck: () => void
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.
onFocusMode?: () => void
// Browser-side spell checker (null until the dictionary loads). Adding a word
@@ -81,6 +85,33 @@ interface WordInfoState {
left: number
loading: boolean
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
@@ -185,6 +216,8 @@ export function EditorCore({
onDismiss,
onVoiceCheck,
voicing,
onCollocationCheck,
collocating,
onFocusMode,
spellChecker,
onAddWord,
@@ -630,13 +663,33 @@ export function EditorCore({
closeCard()
setMisspell(null)
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
.lookupWord(range.word)
.then((info) => {
if (token === wordReqRef.current) {
setWordInfo((w) => (w ? { ...w, loading: false, info } : null))
}
if (token !== wordReqRef.current) return
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) => {
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
// to the native menu (so copy/paste-by-menu still works — see the Selection fix).
const handleContextMenu = useCallback(
@@ -926,7 +1001,13 @@ export function EditorCore({
return (
<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
ref={wrapperRef}
className="relative flex-1"
@@ -969,6 +1050,8 @@ export function EditorCore({
word={wordInfo.word}
info={wordInfo.info}
loading={wordInfo.loading}
saved={wordInfo.saved}
onToggleSave={toggleSaveWord}
style={{ top: wordInfo.top, left: wordInfo.left }}
onReplace={replaceWord}
/>

View File

@@ -11,11 +11,15 @@ interface Props {
word: string
info: WordInfo | null
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
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 synonyms = info?.synonyms ?? []
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)' }}>
{word}
</span>
{speechSupported() && (
<button
type="button"
onClick={() => speak(word)}
aria-label={`Pronounce ${word}`}
title="朗读 · Read aloud"
className="ml-auto 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 className="ml-auto flex items-center gap-1.5">
{!empty && !loading && (
<button
type="button"
onClick={onToggleSave}
aria-label={saved ? 'Remove from vocabulary garden' : 'Save to vocabulary garden'}
aria-pressed={saved}
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={{
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>
{/* How to say it — the pronunciation aid for an English learner, paired

View File

@@ -9,4 +9,5 @@ export const TYPE_META: Record<SuggestionType, { color: string; label: string }>
idiom: { color: 'var(--color-lavender)', label: 'Idiom' },
clarity: { color: 'var(--color-sky)', label: 'Clarity' },
voice: { color: 'var(--color-honey)', label: 'Voice' },
collocation: { color: 'var(--color-blossom)', label: 'Word pairing' },
}

View 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)' }}>
Couldnt 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 itll 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>
)
}

View File

@@ -12,6 +12,8 @@ interface Props {
checking: boolean
// True while a whole-document voice pass runs — shows a breathing honey dot.
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
// (the writing still saves locally, so this is awareness, not an error).
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
// 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).
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]
// The expanded stats panel toggles open when the word count is clicked.
const [statsOpen, setStatsOpen] = useState(false)
@@ -90,7 +92,19 @@ export function StatusBar({ wordCount, text, saveStatus, checking, voicing, llmD
</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

View File

@@ -8,6 +8,9 @@ interface Props {
// Runs the whole-document voice-consistency pass; `voicing` shows its progress.
onVoiceCheck: () => void
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
@@ -165,7 +168,7 @@ function Swatch({
// Toolbar renders inline formatting controls bound to the live Tiptap editor.
// useEditorState subscribes to just the flags it reads, so the buttons reflect
// 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.
const [menu, setMenu] = useState<'color' | 'highlight' | 'size' | 'link' | 'table' | 'outline' | null>(null)
const [linkUrl, setLinkUrl] = useState('')
@@ -594,6 +597,28 @@ export function Toolbar({ editor, onVoiceCheck, voicing }: Props) {
/>
{voicing ? 'Reading…' : 'Check my voice 🍯'}
</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>
)
}

View File

@@ -13,6 +13,8 @@ export function useCheckpoint(docId: string | null) {
const [checking, setChecking] = useState(false)
// True while a whole-document voice pass is in flight (explicit user action).
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
// 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
@@ -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.
const schedule = useCallback(() => {
clearTimeout(debounceRef.current)
@@ -105,6 +130,7 @@ export function useCheckpoint(docId: string | null) {
setSuggestions([])
setChecking(false)
setVoicing(false)
setCollocating(false)
setLlmDown(false)
if (!docId) return
let cancelled = false
@@ -134,5 +160,5 @@ export function useCheckpoint(docId: string | null) {
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 }
}

View File

@@ -20,6 +20,7 @@
--color-lavender: #C5B4E8; /* idiom */
--color-sky: #A8CCE8; /* clarity */
--color-honey: #CE9B4F; /* voice */
--color-blossom: #E59ABF; /* collocation — warm blossom pink */
--color-success: #8FCFA8; /* saved / accepted */
/* Typography */
@@ -232,6 +233,7 @@ button, a, input {
.petal-suggestion-idiom { border-bottom-color: var(--color-lavender); }
.petal-suggestion-clarity { border-bottom-color: var(--color-sky); }
.petal-suggestion-voice { border-bottom-color: var(--color-honey); }
.petal-suggestion-collocation { border-bottom-color: var(--color-blossom); }
@keyframes petal-suggestion-in {
from { opacity: 0; transform: translateY(4px); }