Compare commits
36 Commits
feat/petal
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49e84278d5 | ||
|
|
9d2501a625 | ||
|
|
08b801e752 | ||
|
|
dd1dd7879b | ||
|
|
cb8f132d43 | ||
|
|
cea25a3ebc | ||
|
|
96f68a91ee | ||
|
|
3867cca2fa | ||
|
|
8be852ddf2 | ||
|
|
4d544f29b5 | ||
|
|
8c6bc1604b | ||
|
|
4161830da6 | ||
|
|
8aa437ec82 | ||
|
|
20442d1356 | ||
|
|
375e0dde4c | ||
|
|
7824b68ea1 | ||
|
|
631279bd3a | ||
|
|
9576340391 | ||
|
|
aebdc2679a | ||
|
|
8bd2509bc2 | ||
|
|
0f2f753efa | ||
|
|
46db0a3e16 | ||
|
|
1bd38b20e8 | ||
|
|
82e2bcc777 | ||
|
|
035dcf5d25 | ||
|
|
5120b1e5a2 | ||
|
|
adc0cdff1c | ||
|
|
9d6698dcc6 | ||
|
|
6783ce7a51 | ||
|
|
3ac6382696 | ||
|
|
db737fa612 | ||
|
|
6e6e4edce7 | ||
|
|
58c326d0cf | ||
|
|
045ec19b92 | ||
|
|
f6fa73b17b | ||
|
|
8cf78130bf |
17
.env.example
17
.env.example
@@ -7,6 +7,9 @@ BASE_URL=http://localhost:8080
|
|||||||
# Database (SQLite, pure-Go modernc — no cgo)
|
# Database (SQLite, pure-Go modernc — no cgo)
|
||||||
DATABASE_PATH=./data/petal.db
|
DATABASE_PATH=./data/petal.db
|
||||||
|
|
||||||
|
# On-disk store for images pasted/dropped/inserted in the editor
|
||||||
|
IMAGE_DIR=./data/images
|
||||||
|
|
||||||
# LLM
|
# LLM
|
||||||
LLM_BACKEND=vllm # vllm | ollama
|
LLM_BACKEND=vllm # vllm | ollama
|
||||||
LLM_ENDPOINT=http://localhost:8000 # vLLM :8000, Ollama :11434
|
LLM_ENDPOINT=http://localhost:8000 # vLLM :8000, Ollama :11434
|
||||||
@@ -14,6 +17,20 @@ LLM_MODEL= # checkpoint model (small/fast). Never hardcod
|
|||||||
LLM_CHAT_MODEL= # Ask Petal model (Mandarin-native). Falls back to LLM_MODEL if empty.
|
LLM_CHAT_MODEL= # Ask Petal model (Mandarin-native). Falls back to LLM_MODEL if empty.
|
||||||
LLM_TIMEOUT=30s
|
LLM_TIMEOUT=30s
|
||||||
|
|
||||||
|
# Read-aloud (TTS). Off unless TTS_ENDPOINT is set — when empty, the /api/tts route
|
||||||
|
# is not mounted and the frontend falls back to the browser's Web Speech API.
|
||||||
|
# Backed by a local Piper HTTP server (python3 -m piper.http_server).
|
||||||
|
# Each Piper HTTP server loads ONE voice, so English and Chinese need separate
|
||||||
|
# instances (different ports). zh is only routed when both TTS_ENDPOINT_ZH and
|
||||||
|
# TTS_VOICE_ZH are set; otherwise Chinese falls back to Web Speech.
|
||||||
|
TTS_ENDPOINT= # e.g. http://127.0.0.1:5005 — empty disables server TTS
|
||||||
|
TTS_ENDPOINT_ZH= # e.g. http://127.0.0.1:5006 — Chinese Piper instance
|
||||||
|
TTS_VOICE_EN=en_US-amy-medium # Piper voice id for English
|
||||||
|
TTS_VOICE_ZH=zh_CN-huayan-medium # Piper voice id for Chinese
|
||||||
|
TTS_CACHE_DIR=./data/tts # on-disk store for synthesized clips (content-addressed)
|
||||||
|
TTS_TIMEOUT=15s
|
||||||
|
TTS_AUDIO_FORMAT=mp3 # mp3 | opus | wav — mp3/opus transcode Piper's WAV via ffmpeg
|
||||||
|
|
||||||
# --- Deferred (not wired in the local-dev build) ---
|
# --- Deferred (not wired in the local-dev build) ---
|
||||||
|
|
||||||
# Auth (Authentik OIDC) — deferred; single hardcoded local user for now
|
# Auth (Authentik OIDC) — deferred; single hardcoded local user for now
|
||||||
|
|||||||
@@ -95,6 +95,45 @@ Multi-session build. **Source of truth for what's done and what's next.** Update
|
|||||||
- Tests: `tags_test.go` (full lifecycle — create/idempotent/color-coerce/rename-recolor/assign/unassign/doc-list inclusion/roster counts/delete-cascade/404s), `search_test.go` (EN FTS, CJK FTS, 2-char CJK LIKE fallback, title-only, case-insensitive, empty/no-match, **edit re-indexes via the update trigger**). go build/vet/test clean, tsc clean, vite build OK. Live smoke vs the binary on a throwaway DB (port 8061, LLM pointed at a dead host): search EN/CJK/2-char all highlighted, tag create+assign+roster-counts+doc-list-tags+delete-cascade, check→502 (warm path), new CSS classes (`petal-tag-chip`/`petal-scrim`/`petal-drawer-open`/`pointer:coarse`) and the 小助手在休息 string present in the served bundle. FTS backfill of pre-existing docs verified separately.
|
- Tests: `tags_test.go` (full lifecycle — create/idempotent/color-coerce/rename-recolor/assign/unassign/doc-list inclusion/roster counts/delete-cascade/404s), `search_test.go` (EN FTS, CJK FTS, 2-char CJK LIKE fallback, title-only, case-insensitive, empty/no-match, **edit re-indexes via the update trigger**). go build/vet/test clean, tsc clean, vite build OK. Live smoke vs the binary on a throwaway DB (port 8061, LLM pointed at a dead host): search EN/CJK/2-char all highlighted, tag create+assign+roster-counts+doc-list-tags+delete-cascade, check→502 (warm path), new CSS classes (`petal-tag-chip`/`petal-scrim`/`petal-drawer-open`/`pointer:coarse`) and the 小助手在休息 string present in the served bundle. FTS backfill of pre-existing docs verified separately.
|
||||||
- **Known limitations**: trigram FTS snippets/ranking treat the query as a contiguous phrase (multi-term relevance is substring, not BM25-per-term) — fine for a personal corpus. Search is title+body only (not tag names). Hover gloss and right-click word lookup remain pointer-oriented (long-press contextmenu on touch is browser-dependent); the spelling/suggestion cards and rewrite bubble are fully touch-reachable.
|
- **Known limitations**: trigram FTS snippets/ranking treat the query as a contiguous phrase (multi-term relevance is substring, not BM25-per-term) — fine for a personal corpus. Search is title+body only (not tag names). Hover gloss and right-click word lookup remain pointer-oriented (long-press contextmenu on touch is browser-dependent); the spelling/suggestion cards and rewrite bubble are fully touch-reachable.
|
||||||
|
|
||||||
|
### Phase 11 — Writer power-ups ✅
|
||||||
|
- [x] **In-document Find & Replace (Ctrl/Cmd+F)** — `SearchHighlight` ProseMirror extension (decorations, not marks — same anchoring discipline as the suggestion/spell layers; matches recomputed per-textblock on every edit, never stranded). `FindReplace` bar (bilingual zh-first): live match highlighting, ↑/↓ step-through with no-selection DOM scroll-into-view (so it never pops the rewrite bubble), match-case toggle, replace / replace-all (replace-all applies back-to-front so earlier edits don't shift later positions). Honey wash on all matches, rose ring on the active one.
|
||||||
|
- [x] **Read-aloud / TTS** (`web/src/audio/speech.ts`) — Web Speech API, offline, feature-detected. 🔊 in the `WordCard` (pronounce the word) and the selection bubble (read the selection). Pairs with the phonetic line.
|
||||||
|
- [x] **Keyboard + touch access to the ESL helpers** — refactored the right-click word-lookup into a position-based `openWordLookup(pos)`; now also driven by **Ctrl/Cmd+D** (look up the word at the caret) and a **touch long-press** (~500ms, the touch equivalent of right-click). **Ctrl/Cmd+J** rewrites the selection more naturally. (Closes the "pointer-only" limitation noted in Phase 10.)
|
||||||
|
- [x] **Whole-corpus backup** — `GET /api/docs/export-all?format=md|docx|…` zips every doc (reuses the per-doc renderers; de-duplicates same-titled filenames; dated `petal-backup-YYYY-MM-DD.zip`). Static route takes priority over `/{id}` in chi — covered by `TestExportAll`. Sidebar footer "备份 · Back up all: Word / Markdown" download links.
|
||||||
|
- [x] **Smart typography** (`Typography.ts`) — dependency-free input rules: curly quotes, em-dash (`--`), ellipsis (`...`). ASCII-only triggers so CJK fullwidth punctuation is untouched; every rule is plain-Undo-able.
|
||||||
|
- [x] **Org niceties** — duplicate-a-document (App `handleDuplicate` → "… (副本)", copies body/tone, not tags), sidebar **sort** (Recent / Title / Longest), and a **document outline** popover in the toolbar (headings → click to scroll, indented by level).
|
||||||
|
- [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}`.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
**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.
|
||||||
|
- [x] `internal/llm/collocation.go` — `CollocationInterval` (25s) + `RunCollocation(...)`, reusing the existing `ParseCheckpoint` parser (same as `RunVoice`). Whole-document (no `TruncateDoc`), tone passed through.
|
||||||
|
- [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".
|
||||||
|
- [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).
|
||||||
|
- [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).
|
||||||
|
- [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).
|
||||||
|
- [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) ✅ (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.
|
||||||
|
- [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`.
|
||||||
|
- [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.
|
||||||
|
- [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.
|
||||||
|
- [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.
|
||||||
|
- [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.
|
||||||
|
- [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 ✅
|
||||||
|
**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.
|
||||||
|
- [x] `web/src/components/Companion/tips.ts` — `ENCOURAGEMENTS` grown from 5→10 bilingual zh-first lines so cheers rotate fresher. New `BEDTIME: Line[]` array — four warm/playful lines (user-supplied English wit: "I bet your bed is missing you right now", "A tired writer is a bad writer", "Sleep is a wondrous enabler", "Hear that? No… everyone is sleeping and you should be too") with gentle Mandarin leads.
|
||||||
|
- [x] `web/src/components/Companion/useCompanion.ts` — bedtime check folded into the existing 10s heartbeat (after the idle-return + break check, before the generic tip): `isBedtime()` = local hour ≥ 23 or < 4 (`new Date().getHours()`, the writer's machine clock). Only fires while actively writing (idle branch returns first). Own `lastBedtime` ref + `BEDTIME_GAP` 30min cooldown; respects `PROACTIVE_GAP`. New `BubbleTone` `'bedtime'` paces `readBubbleMs` (BUBBLE_MS + 4s lingers a touch longer for a wind-down read). Window knobs `BEDTIME_FROM`/`BEDTIME_TO` so the 11pm–4am range is one edit to retune.
|
||||||
|
- [x] No tone-based bubble styling exists, so no CSS needed; the tone is metadata for pacing only. Sound stays the rotating pop.
|
||||||
|
- [x] **Night mode** — `web/src/lib/night.ts` centralizes `isBedtime()` + the `BEDTIME_FROM`/`BEDTIME_TO` window (shared with the companion nag so they always agree). `web/src/hooks/useNightMode.ts` re-checks every 60s and toggles a `petal-night` class on `<html>`. `index.css` adds an `html.petal-night` block that **only re-points the palette tokens** (`--color-bg/surface/border/plum/muted/accent…`) to a dark moonlit set — every Tailwind color utility reads them via `var()`, so the whole UI flips with zero component changes (verified: `.text-plum{color:var(--color-plum)}`). Accent/type colors kept (they pop on dark); 600ms bg/color fade for a gentle dusk transition; print stays white (the `#fff` override is inside `@media print`).
|
||||||
|
- [x] **Falling stars** — `PetalFall` gains a `night` prop. Particles are **chunky cartoon power stars** (`makeCartoonStar`, Mario/Kirby-style: fat 5-point shape, glossy radial fill, puffy round-join colored outline, corner shine + soft glow halo so they pop off the dark sky) in 5 candy colors (`CARTOON_COLORS`), mixed ~70/30 with small four-point twinkle sparkles (`makeStarSprite`/`STAR_PALETTE`) for depth. Every star clearly **spins** (random direction, ~0.5–2.2 rad/s so the quick ones really whirl while slow ones drift for contrast; guaranteed min speed since a 5-point star is symmetric every 72°), **falls straight down** (no sway — that's a petal thing), and shimmers via a shallow alpha pulse (not blink). Effect re-inits on the day↔night flip. App wires `const night = useNightMode()` → `<PetalFall night={night} />`. All sprites are canvas-drawn (offline, no asset files) — `sprites[]` is an image array, so a real PNG/SVG star could drop in later without restructuring.
|
||||||
|
- [x] Verified: tsc clean, vite build OK, companion vitest 45/45. **Real-browser screenshots** (local Playwright + Chromium, clock mocked to 23:30): day = warm cream + pink sakura petals; night = dark plum-indigo + twinkling stars + glowing sleepy kitten. Both pretty (acceptance criterion).
|
||||||
|
|
||||||
### Deferred (post-v1-local)
|
### Deferred (post-v1-local)
|
||||||
- [ ] Authentik OIDC auth + session middleware ← **on hold: user doing foundational work first**
|
- [ ] Authentik OIDC auth + session middleware ← **on hold: user doing foundational work first**
|
||||||
- [ ] Copyleaks Tier-2 + webhook HMAC
|
- [ ] Copyleaks Tier-2 + webhook HMAC
|
||||||
@@ -103,8 +142,14 @@ 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)
|
||||||
|
- [x] **Phase 12 — collocation coach**: gentle "natives usually say…" hints for non-native word pairings, as a third suggestion family. ✅ (see Phase 12 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)
|
||||||
|
|
||||||
## 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 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.
|
||||||
- 2026-06-26: **Phase 9 complete** (ESL superpowers: inline Chinese gloss + tone-rewrite). Decisions confirmed with user: gloss is an **offline EC dictionary** (instant, LLM-down-proof, fits the embedded-lexicon ethos), rewrite is a **selection bubble**. Data: `scripts/build_gloss.py` builds `internal/lexicon/data/gloss.json.gz` from ECDICT (66MB csv → 1.3MB gz, 57k freq-≤50k words, cleaned/trimmed). Backend: `lexicon` gloss map + `Gloss()`/`Result.Gloss` + `GET /api/gloss/{word}`; `llm.RunRewrite` + rewrite prompt/`styleGuidance`; `internal/suggestions/rewrite.go` (`POST /api/docs/:id/rewrite`, stateless, owner-scoped). Frontend: `GlossTip` hover tooltip (350ms delay, reuses `wordAt`, CJK-safe) + gloss line in `WordCard`; `SelectionBubble` + `RewritePreview` wired through `EditorCore` (onMouseMove/onSelectionUpdate, request-token guards, clears on edit/doc-switch); `api.glossWord`/`api.rewriteSelection`; CSS for the three new surfaces (+ print-hidden). Tests added in `lexicon` and `suggestions`. All builds/tests/vet/tsc/vite clean; live smoke vs fake vLLM on :8055 verified gloss + rewrite + 400/404/502 paths. Next: **Phase 10 (organization & polish).**
|
- 2026-06-26: **Phase 9 complete** (ESL superpowers: inline Chinese gloss + tone-rewrite). Decisions confirmed with user: gloss is an **offline EC dictionary** (instant, LLM-down-proof, fits the embedded-lexicon ethos), rewrite is a **selection bubble**. Data: `scripts/build_gloss.py` builds `internal/lexicon/data/gloss.json.gz` from ECDICT (66MB csv → 1.3MB gz, 57k freq-≤50k words, cleaned/trimmed). Backend: `lexicon` gloss map + `Gloss()`/`Result.Gloss` + `GET /api/gloss/{word}`; `llm.RunRewrite` + rewrite prompt/`styleGuidance`; `internal/suggestions/rewrite.go` (`POST /api/docs/:id/rewrite`, stateless, owner-scoped). Frontend: `GlossTip` hover tooltip (350ms delay, reuses `wordAt`, CJK-safe) + gloss line in `WordCard`; `SelectionBubble` + `RewritePreview` wired through `EditorCore` (onMouseMove/onSelectionUpdate, request-token guards, clears on edit/doc-switch); `api.glossWord`/`api.rewriteSelection`; CSS for the three new surfaces (+ print-hidden). Tests added in `lexicon` and `suggestions`. All builds/tests/vet/tsc/vite clean; live smoke vs fake vLLM on :8055 verified gloss + rewrite + 400/404/502 paths. Next: **Phase 10 (organization & polish).**
|
||||||
- 2026-06-26: **Phase 8 complete** (Trust foundation: version history + export) + empty-doc fix. Backend: migration `0003_document_versions`; `internal/docs/versions.go` (throttled auto-snapshot wired into `update`, manual snapshot, restore-with-pre_restore, prune to 40 auto, owner-scoped via join) and `internal/docs/export.go` (pure-Go Tiptap-JSON → md/html/txt/docx, no deps, CJK-safe filenames via RFC 5987). `DocumentVersion` model + kind constants. Tests: `versions_test.go`, `export_test.go` (incl. valid-zip docx assertion). Frontend: `api.client` version/export methods; `ExportMenu` + `HistoryPanel` components wired into the title row; `@media print` stylesheet + `.petal-no-print` for the browser PDF path; `editorEpoch` remount on restore. Empty-doc fix in `App.tsx` (blank drafts reuse-on-create + discard-on-leave via refs to dodge stale closures); deleted 2 orphan empties from the live :8099 DB. Multi-session plan agreed: this session = Phase 8; **Phase 9 (ESL gloss + tone-rewrite)** next, then **Phase 10 (search/folders/polish)**; **auth/deploy (was Phase 11) shelved** until user's foundational work lands. All builds/tests/vet clean; live smoke verified the full version+export+restore flow end-to-end. Next: **Phase 9.**
|
- 2026-06-26: **Phase 8 complete** (Trust foundation: version history + export) + empty-doc fix. Backend: migration `0003_document_versions`; `internal/docs/versions.go` (throttled auto-snapshot wired into `update`, manual snapshot, restore-with-pre_restore, prune to 40 auto, owner-scoped via join) and `internal/docs/export.go` (pure-Go Tiptap-JSON → md/html/txt/docx, no deps, CJK-safe filenames via RFC 5987). `DocumentVersion` model + kind constants. Tests: `versions_test.go`, `export_test.go` (incl. valid-zip docx assertion). Frontend: `api.client` version/export methods; `ExportMenu` + `HistoryPanel` components wired into the title row; `@media print` stylesheet + `.petal-no-print` for the browser PDF path; `editorEpoch` remount on restore. Empty-doc fix in `App.tsx` (blank drafts reuse-on-create + discard-on-leave via refs to dodge stale closures); deleted 2 orphan empties from the live :8099 DB. Multi-session plan agreed: this session = Phase 8; **Phase 9 (ESL gloss + tone-rewrite)** next, then **Phase 10 (search/folders/polish)**; **auth/deploy (was Phase 11) shelved** until user's foundational work lands. All builds/tests/vet clean; live smoke verified the full version+export+restore flow end-to-end. Next: **Phase 9.**
|
||||||
|
|||||||
@@ -15,9 +15,12 @@ import (
|
|||||||
"gitea.parodia.dev/drwily/petal/internal/config"
|
"gitea.parodia.dev/drwily/petal/internal/config"
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
"gitea.parodia.dev/drwily/petal/internal/docs"
|
"gitea.parodia.dev/drwily/petal/internal/docs"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/images"
|
||||||
"gitea.parodia.dev/drwily/petal/internal/lexicon"
|
"gitea.parodia.dev/drwily/petal/internal/lexicon"
|
||||||
"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/vocab"
|
||||||
"gitea.parodia.dev/drwily/petal/web"
|
"gitea.parodia.dev/drwily/petal/web"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -45,6 +48,11 @@ func main() {
|
|||||||
log.Printf("frontend build version %s", version)
|
log.Printf("frontend build version %s", version)
|
||||||
|
|
||||||
r.Route("/api", func(api chi.Router) {
|
r.Route("/api", func(api chi.Router) {
|
||||||
|
// Cap request bodies so a runaway or hostile client can't stream an
|
||||||
|
// unbounded payload into a JSON decoder. Image uploads carry their own
|
||||||
|
// (larger) limit inside the images handler, so they're exempt here.
|
||||||
|
api.Use(limitBody(maxAPIBodyBytes, "/api/images"))
|
||||||
|
|
||||||
api.Get("/health", func(w http.ResponseWriter, _ *http.Request) {
|
api.Get("/health", func(w http.ResponseWriter, _ *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
_, _ = w.Write([]byte(`{"status":"ok"}`))
|
_, _ = w.Write([]byte(`{"status":"ok"}`))
|
||||||
@@ -80,6 +88,25 @@ func main() {
|
|||||||
lex := lexicon.NewHandler()
|
lex := lexicon.NewHandler()
|
||||||
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.
|
||||||
|
imgHandler, err := images.New(cfg.ImageDir)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("image store: %v", err)
|
||||||
|
}
|
||||||
|
api.Mount("/images", imgHandler.Routes())
|
||||||
|
|
||||||
|
// Read-aloud: proxy short passages to a local Piper TTS server. Only
|
||||||
|
// mounted when TTS_ENDPOINT is configured; otherwise the frontend falls
|
||||||
|
// back to the browser's Web Speech API on its own.
|
||||||
|
if ttsHandler, ok := tts.New(cfg); ok {
|
||||||
|
api.Mount("/tts", ttsHandler.Routes())
|
||||||
|
log.Printf("read-aloud enabled (TTS endpoint=%s)", cfg.TTSEndpoint)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// Everything else: serve the embedded SPA (with index.html fallback for client routing).
|
// Everything else: serve the embedded SPA (with index.html fallback for client routing).
|
||||||
@@ -92,6 +119,32 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// maxAPIBodyBytes caps a JSON API request body at 2 MiB. That's far above any
|
||||||
|
// real document save (the body is text plus lightweight marks; images upload
|
||||||
|
// separately by reference) while still bounding abuse. Exceeding it makes the
|
||||||
|
// handler's json.Decode fail, which surfaces as a 400.
|
||||||
|
const maxAPIBodyBytes = 2 << 20
|
||||||
|
|
||||||
|
// limitBody wraps each request body in an http.MaxBytesReader so handlers can't
|
||||||
|
// be made to read an unbounded payload. Paths under any of exemptPrefixes are
|
||||||
|
// left alone (e.g. image uploads, which set their own, larger limit).
|
||||||
|
func limitBody(max int64, exemptPrefixes ...string) func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
for _, p := range exemptPrefixes {
|
||||||
|
if strings.HasPrefix(r.URL.Path, p) {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r.Body != nil {
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, max)
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// buildVersion derives a short, stable identifier for the currently embedded
|
// buildVersion derives a short, stable identifier for the currently embedded
|
||||||
// frontend by hashing dist/index.html. Vite stamps content-hashed asset names
|
// frontend by hashing dist/index.html. Vite stamps content-hashed asset names
|
||||||
// into that file each build, so the digest is a reliable "did the deploy
|
// into that file each build, so the digest is a reliable "did the deploy
|
||||||
|
|||||||
65
deploy/README.md
Normal file
65
deploy/README.md
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# Deploying read-aloud (Piper TTS) to millenia
|
||||||
|
|
||||||
|
Petal's read-aloud generates audio with a local **Piper** neural-TTS server and
|
||||||
|
transcodes it to mp3 with **ffmpeg**. Both run on millenia (192.168.1.212);
|
||||||
|
nothing leaves the box. If Piper is down or `TTS_ENDPOINT` is unset, the frontend
|
||||||
|
falls back to the browser's Web Speech API automatically.
|
||||||
|
|
||||||
|
## 1. Piper as a systemd service (one-time)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# from this repo, on your workstation:
|
||||||
|
scp deploy/piper.service deploy/setup-piper.sh 192.168.1.212:/tmp/
|
||||||
|
ssh 192.168.1.212 'cd /tmp && sudo ./setup-piper.sh'
|
||||||
|
```
|
||||||
|
|
||||||
|
`setup-piper.sh` creates `~/piper/venv`, installs `piper-tts[http]`, downloads the
|
||||||
|
`en_US-amy-medium` voice into `~/piper/voices`, installs+enables `piper.service`
|
||||||
|
(loopback :5005), and smoke-tests it. Idempotent.
|
||||||
|
|
||||||
|
Check it any time: `systemctl status piper`, `journalctl -u piper -f`.
|
||||||
|
|
||||||
|
## 2. Point petal at Piper + redeploy the binary
|
||||||
|
|
||||||
|
Add to petal's environment (its `.env` or launch env):
|
||||||
|
|
||||||
|
```
|
||||||
|
TTS_ENDPOINT=http://127.0.0.1:5005
|
||||||
|
TTS_VOICE_EN=en_US-amy-medium
|
||||||
|
TTS_AUDIO_FORMAT=mp3
|
||||||
|
```
|
||||||
|
|
||||||
|
Then ship the rebuilt binary (`go build -o petal ./cmd/server` already done) and
|
||||||
|
restart the petal `:8088` session. Confirm the log line:
|
||||||
|
`read-aloud enabled (TTS endpoint=http://127.0.0.1:5005)`.
|
||||||
|
|
||||||
|
## 3. Verify
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# on millenia — end-to-end through petal, including ffmpeg transcode:
|
||||||
|
curl -sf -X POST localhost:8088/api/tts \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"text":"hello there","lang":"en-US"}' -o /tmp/petal-tts.mp3 \
|
||||||
|
&& file /tmp/petal-tts.mp3 # expect: Audio file ... MPEG ... layer III
|
||||||
|
```
|
||||||
|
|
||||||
|
- Second identical call is served from the cache (`~/petal/.../data/tts/*.mp3`).
|
||||||
|
- A language with no configured instance returns 404 → client uses Web Speech.
|
||||||
|
- Browser check via the uitest harness (`~/petal/uitest`): tap a word in the
|
||||||
|
WordCard / select a sentence and hit speak — expect the natural Piper voice.
|
||||||
|
|
||||||
|
## Chinese voice (live)
|
||||||
|
|
||||||
|
Each Piper HTTP server loads ONE model, so Chinese runs as a **second instance**:
|
||||||
|
`piper-zh.service` on :5006 with `zh_CN-huayan-medium`. Deployed via:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
scp deploy/piper-zh.service 192.168.1.212:~/.config/systemd/user/
|
||||||
|
ssh 192.168.1.212 'export XDG_RUNTIME_DIR=/run/user/$(id -u)
|
||||||
|
~/piper/venv/bin/python -m piper.download_voices zh_CN-huayan-medium --data-dir ~/piper/voices
|
||||||
|
systemctl --user daemon-reload && systemctl --user enable --now piper-zh.service'
|
||||||
|
```
|
||||||
|
|
||||||
|
Then in petal's `start.sh`: `TTS_ENDPOINT_ZH=http://127.0.0.1:5006` and
|
||||||
|
`TTS_VOICE_ZH=zh_CN-huayan-medium`. The handler maps language → instance from config,
|
||||||
|
so adding more languages is just another instance + env pair (no code change).
|
||||||
17
deploy/piper-zh.service
Normal file
17
deploy/piper-zh.service
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Piper TTS HTTP server — Chinese voice (read-aloud backend for petal)
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
# Bound to loopback only — petal proxies to it; never exposed off-box.
|
||||||
|
ExecStart=%h/piper/venv/bin/python -m piper.http_server \
|
||||||
|
-m zh_CN-huayan-medium \
|
||||||
|
--data-dir %h/piper/voices \
|
||||||
|
--host 127.0.0.1 --port 5006
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
17
deploy/piper.service
Normal file
17
deploy/piper.service
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Piper TTS HTTP server (read-aloud backend for petal)
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
# Bound to loopback only — petal proxies to it; never exposed off-box.
|
||||||
|
ExecStart=%h/piper/venv/bin/python -m piper.http_server \
|
||||||
|
-m en_US-amy-medium \
|
||||||
|
--data-dir %h/piper/voices \
|
||||||
|
--host 127.0.0.1 --port 5005
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
43
deploy/setup-piper.sh
Executable file
43
deploy/setup-piper.sh
Executable file
@@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# One-time Piper TTS setup on millenia as a *user* systemd service (no sudo).
|
||||||
|
# Idempotent — safe to re-run. Run on the box:
|
||||||
|
# bash setup-piper.sh
|
||||||
|
# To survive logout/reboot, also (once, needs root):
|
||||||
|
# sudo loginctl enable-linger "$USER"
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PIPER_HOME="$HOME/piper"
|
||||||
|
VENV="$PIPER_HOME/venv"
|
||||||
|
VOICES="$PIPER_HOME/voices"
|
||||||
|
VOICE=en_US-amy-medium
|
||||||
|
UNIT_DIR="$HOME/.config/systemd/user"
|
||||||
|
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
|
||||||
|
|
||||||
|
echo ">> ffmpeg check (petal transcodes Piper WAV -> mp3 with it):"
|
||||||
|
command -v ffmpeg >/dev/null || { echo "ffmpeg not found on PATH"; exit 1; }
|
||||||
|
|
||||||
|
echo ">> venv + piper-tts[http]"
|
||||||
|
[ -d "$VENV" ] || python3 -m venv "$VENV"
|
||||||
|
"$VENV/bin/pip" install --upgrade pip >/dev/null
|
||||||
|
"$VENV/bin/pip" install "piper-tts[http]"
|
||||||
|
|
||||||
|
echo ">> download voice $VOICE"
|
||||||
|
mkdir -p "$VOICES"
|
||||||
|
"$VENV/bin/python" -m piper.download_voices "$VOICE" --data-dir "$VOICES"
|
||||||
|
|
||||||
|
echo ">> install user service"
|
||||||
|
mkdir -p "$UNIT_DIR"
|
||||||
|
install -m 0644 "$(dirname "$0")/piper.service" "$UNIT_DIR/piper.service"
|
||||||
|
systemctl --user daemon-reload
|
||||||
|
systemctl --user enable --now piper.service
|
||||||
|
|
||||||
|
echo ">> wait + status"
|
||||||
|
sleep 2
|
||||||
|
systemctl --user --no-pager --full status piper.service | head -n 6 || true
|
||||||
|
|
||||||
|
echo ">> smoke test"
|
||||||
|
curl -sf -X POST localhost:5005/ \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d "{\"text\":\"hello there\",\"voice\":\"$VOICE\"}" -o /tmp/piper-test.wav \
|
||||||
|
&& echo "OK: /tmp/piper-test.wav ($(stat -c%s /tmp/piper-test.wav) bytes)" \
|
||||||
|
|| { echo "smoke test FAILED"; journalctl --user -u piper.service --no-pager | tail -n 20; exit 1; }
|
||||||
@@ -11,6 +11,7 @@ type Config struct {
|
|||||||
Port string
|
Port string
|
||||||
BaseURL string
|
BaseURL string
|
||||||
DatabasePath string
|
DatabasePath string
|
||||||
|
ImageDir string // on-disk store for editor image uploads
|
||||||
|
|
||||||
// LLM
|
// LLM
|
||||||
LLMBackend string // "vllm" | "ollama"
|
LLMBackend string // "vllm" | "ollama"
|
||||||
@@ -19,6 +20,17 @@ type Config struct {
|
|||||||
LLMChatModel string // Ask Petal model; falls back to LLMModel if empty
|
LLMChatModel string // Ask Petal model; falls back to LLMModel if empty
|
||||||
LLMTimeout time.Duration
|
LLMTimeout time.Duration
|
||||||
|
|
||||||
|
// TTS (read-aloud). Off unless TTSEndpoint is set — when empty, the /api/tts
|
||||||
|
// route isn't mounted and the frontend falls back to the browser's Web Speech
|
||||||
|
// API. Endpoint points at a local Piper HTTP server.
|
||||||
|
TTSEndpoint string // Piper instance serving the English voice
|
||||||
|
TTSEndpointZH string // Piper instance serving the Chinese voice; empty = zh falls back to Web Speech
|
||||||
|
TTSVoiceEN string // Piper voice id for English (e.g. en_US-amy-medium)
|
||||||
|
TTSVoiceZH string // Piper voice id for Chinese (e.g. zh_CN-huayan-medium)
|
||||||
|
TTSCacheDir string // on-disk store for synthesized clips (content-addressed)
|
||||||
|
TTSTimeout time.Duration
|
||||||
|
TTSFormat string // mp3 | opus | wav — mp3/opus transcode Piper's WAV via ffmpeg
|
||||||
|
|
||||||
// Auth (deferred — not wired in the local-dev build, kept for later)
|
// Auth (deferred — not wired in the local-dev build, kept for later)
|
||||||
AuthentikURL string
|
AuthentikURL string
|
||||||
AuthentikClientID string
|
AuthentikClientID string
|
||||||
@@ -32,6 +44,7 @@ func Load() *Config {
|
|||||||
Port: env("PORT", "8080"),
|
Port: env("PORT", "8080"),
|
||||||
BaseURL: env("BASE_URL", "http://localhost:8080"),
|
BaseURL: env("BASE_URL", "http://localhost:8080"),
|
||||||
DatabasePath: env("DATABASE_PATH", "./data/petal.db"),
|
DatabasePath: env("DATABASE_PATH", "./data/petal.db"),
|
||||||
|
ImageDir: env("IMAGE_DIR", "./data/images"),
|
||||||
|
|
||||||
LLMBackend: env("LLM_BACKEND", "vllm"),
|
LLMBackend: env("LLM_BACKEND", "vllm"),
|
||||||
LLMEndpoint: env("LLM_ENDPOINT", "http://localhost:8000"),
|
LLMEndpoint: env("LLM_ENDPOINT", "http://localhost:8000"),
|
||||||
@@ -39,6 +52,14 @@ func Load() *Config {
|
|||||||
LLMChatModel: env("LLM_CHAT_MODEL", ""),
|
LLMChatModel: env("LLM_CHAT_MODEL", ""),
|
||||||
LLMTimeout: envDuration("LLM_TIMEOUT", 30*time.Second),
|
LLMTimeout: envDuration("LLM_TIMEOUT", 30*time.Second),
|
||||||
|
|
||||||
|
TTSEndpoint: env("TTS_ENDPOINT", ""),
|
||||||
|
TTSEndpointZH: env("TTS_ENDPOINT_ZH", ""),
|
||||||
|
TTSVoiceEN: env("TTS_VOICE_EN", "en_US-amy-medium"),
|
||||||
|
TTSVoiceZH: env("TTS_VOICE_ZH", "zh_CN-huayan-medium"),
|
||||||
|
TTSCacheDir: env("TTS_CACHE_DIR", "./data/tts"),
|
||||||
|
TTSTimeout: envDuration("TTS_TIMEOUT", 15*time.Second),
|
||||||
|
TTSFormat: env("TTS_AUDIO_FORMAT", "mp3"),
|
||||||
|
|
||||||
AuthentikURL: env("AUTHENTIK_URL", ""),
|
AuthentikURL: env("AUTHENTIK_URL", ""),
|
||||||
AuthentikClientID: env("AUTHENTIK_CLIENT_ID", ""),
|
AuthentikClientID: env("AUTHENTIK_CLIENT_ID", ""),
|
||||||
AuthentikClientSecret: env("AUTHENTIK_CLIENT_SECRET", ""),
|
AuthentikClientSecret: env("AUTHENTIK_CLIENT_SECRET", ""),
|
||||||
|
|||||||
@@ -260,6 +260,111 @@ 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);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Vocabulary garden, follow-up. Some looked-up words have an English
|
||||||
|
// definition but no Chinese gloss; those produced an unanswerable review
|
||||||
|
// card (review reveals only the gloss). `definition` stores a short
|
||||||
|
// English sense captured at lookup as a fallback "meaning" so such words
|
||||||
|
// are still reviewable.
|
||||||
|
name: "0007_vocab_definition",
|
||||||
|
stmt: `
|
||||||
|
ALTER TABLE vocab_words ADD COLUMN definition TEXT NOT NULL DEFAULT '';
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Deterministic mechanics pass. Adds a 'mechanics' suggestion family for
|
||||||
|
// rule-based fixes (doubled words, spacing/punctuation, lowercase "i",
|
||||||
|
// curated confusables) detected in pure Go — no LLM. As with 0005, the
|
||||||
|
// `type` CHECK can't be ALTERed in place, so rebuild the table with the
|
||||||
|
// extended constraint, copy every row across, and recreate the index.
|
||||||
|
name: "0008_mechanics_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','mechanics')),
|
||||||
|
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);
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,20 @@ 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"
|
||||||
|
SuggestionTypeMechanics = "mechanics" // deterministic rule-based pass (no LLM)
|
||||||
|
|
||||||
SuggestionStatusPending = "pending"
|
SuggestionStatusPending = "pending"
|
||||||
SuggestionStatusAccepted = "accepted"
|
SuggestionStatusAccepted = "accepted"
|
||||||
|
|||||||
@@ -9,15 +9,102 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// exportRoutes registers the download endpoint: GET /api/docs/{id}/export?format=md|html|txt|docx
|
// exportRoutes registers the download endpoints: one document
|
||||||
|
// (GET /api/docs/{id}/export?format=…) and a whole-corpus backup zip
|
||||||
|
// (GET /api/docs/export-all?format=…). The static "export-all" segment takes
|
||||||
|
// priority over the {id} param in chi's router, so the two don't collide.
|
||||||
func (h *Handler) exportRoutes(r chi.Router) {
|
func (h *Handler) exportRoutes(r chi.Router) {
|
||||||
r.Get("/{id}/export", h.export)
|
r.Get("/{id}/export", h.export)
|
||||||
|
r.Get("/export-all", h.exportAll)
|
||||||
|
}
|
||||||
|
|
||||||
|
// exportAll streams every document the user owns, each rendered in the requested
|
||||||
|
// format, bundled into a single zip — a one-click "download all my writing"
|
||||||
|
// backup. Per-doc version history guards against bad edits; this guards against
|
||||||
|
// a lost disk. Reuses the same renderers as the single-document export.
|
||||||
|
func (h *Handler) exportAll(w http.ResponseWriter, r *http.Request) {
|
||||||
|
formatKey := r.URL.Query().Get("format")
|
||||||
|
if formatKey == "" {
|
||||||
|
formatKey = "md"
|
||||||
|
}
|
||||||
|
format, ok := exportFormats[formatKey]
|
||||||
|
if !ok {
|
||||||
|
badRequest(w, "unsupported export format")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := h.DB.Query(
|
||||||
|
`SELECT id, user_id, title, content, content_text, tone, word_count, created_at, updated_at
|
||||||
|
FROM documents
|
||||||
|
WHERE user_id = ?
|
||||||
|
ORDER BY updated_at DESC`,
|
||||||
|
db.LocalUserID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
zw := zip.NewWriter(&buf)
|
||||||
|
seen := map[string]int{} // de-duplicate filenames from same-titled docs
|
||||||
|
for rows.Next() {
|
||||||
|
var doc db.Document
|
||||||
|
if err := rows.Scan(
|
||||||
|
&doc.ID, &doc.UserID, &doc.Title, &doc.Content, &doc.ContentText,
|
||||||
|
&doc.Tone, &doc.WordCount, &doc.CreatedAt, &doc.UpdatedAt,
|
||||||
|
); err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, err := format.render(doc)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
base := sanitizeFilename(doc.Title)
|
||||||
|
if base == "" {
|
||||||
|
base = "untitled"
|
||||||
|
}
|
||||||
|
key := base + "." + format.ext
|
||||||
|
name := key
|
||||||
|
if c := seen[key]; c > 0 {
|
||||||
|
name = fmt.Sprintf("%s (%d).%s", base, c, format.ext)
|
||||||
|
}
|
||||||
|
seen[key]++
|
||||||
|
f, err := zw.Create(name)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := f.Write(body); err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := zw.Close(); err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
filename := "petal-backup-" + time.Now().Format("2006-01-02") + ".zip"
|
||||||
|
w.Header().Set("Content-Type", "application/zip")
|
||||||
|
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename*=UTF-8''%s", urlEscapeFilename(filename)))
|
||||||
|
w.Header().Set("Content-Length", fmt.Sprintf("%d", buf.Len()))
|
||||||
|
_, _ = w.Write(buf.Bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
// exportFormat describes one downloadable format: how to render it and how to
|
// exportFormat describes one downloadable format: how to render it and how to
|
||||||
@@ -62,13 +149,13 @@ func (h *Handler) export(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
body, err := format.render(doc)
|
body, err := format.render(doc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +179,8 @@ type pmNode struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type pmMark struct {
|
type pmMark struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
|
Attrs map[string]any `json:"attrs"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseDoc decodes Document.Content into a node tree. On empty or malformed JSON
|
// parseDoc decodes Document.Content into a node tree. On empty or malformed JSON
|
||||||
@@ -131,6 +219,29 @@ func (n pmNode) hasMark(t string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// attrStr returns a string-valued attribute (e.g. an image src), or "".
|
||||||
|
func (n pmNode) attrStr(key string) string {
|
||||||
|
if n.Attrs == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if s, ok := n.Attrs[key].(string); ok {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// markAttr returns a string attribute from the named mark (e.g. a link href).
|
||||||
|
func (n pmNode) markAttr(markType, key string) string {
|
||||||
|
for _, m := range n.Marks {
|
||||||
|
if m.Type == markType && m.Attrs != nil {
|
||||||
|
if s, ok := m.Attrs[key].(string); ok {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func (n pmNode) level() int {
|
func (n pmNode) level() int {
|
||||||
if n.Attrs == nil {
|
if n.Attrs == nil {
|
||||||
return 1
|
return 1
|
||||||
@@ -173,6 +284,11 @@ func mdBlock(n pmNode, depth int) string {
|
|||||||
return "```\n" + textContent(n) + "\n```"
|
return "```\n" + textContent(n) + "\n```"
|
||||||
case "horizontalRule":
|
case "horizontalRule":
|
||||||
return "---"
|
return "---"
|
||||||
|
case "image":
|
||||||
|
alt := n.attrStr("alt")
|
||||||
|
return fmt.Sprintf("", alt, n.attrStr("src"))
|
||||||
|
case "table":
|
||||||
|
return mdTable(n)
|
||||||
case "bulletList", "orderedList":
|
case "bulletList", "orderedList":
|
||||||
var items []string
|
var items []string
|
||||||
for i, item := range n.Content {
|
for i, item := range n.Content {
|
||||||
@@ -213,6 +329,55 @@ func mdInline(nodes []pmNode) string {
|
|||||||
return b.String()
|
return b.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mdTable renders a table node as a GitHub-flavored Markdown table. The first
|
||||||
|
// row is used as the header (Markdown tables require one); a separator row is
|
||||||
|
// inserted after it. Cell text is flattened to inline Markdown.
|
||||||
|
func mdTable(n pmNode) string {
|
||||||
|
var rows [][]string
|
||||||
|
for _, row := range n.Content {
|
||||||
|
if row.Type != "tableRow" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var cells []string
|
||||||
|
for _, cell := range row.Content {
|
||||||
|
// A cell holds block children (usually one paragraph); flatten them.
|
||||||
|
var parts []string
|
||||||
|
for _, c := range cell.Content {
|
||||||
|
parts = append(parts, mdInline(c.Content))
|
||||||
|
}
|
||||||
|
// Escape pipes so cell content doesn't break the column layout.
|
||||||
|
cells = append(cells, strings.ReplaceAll(strings.TrimSpace(strings.Join(parts, " ")), "|", "\\|"))
|
||||||
|
}
|
||||||
|
rows = append(rows, cells)
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
cols := 0
|
||||||
|
for _, r := range rows {
|
||||||
|
if len(r) > cols {
|
||||||
|
cols = len(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pad := func(r []string) string {
|
||||||
|
for len(r) < cols {
|
||||||
|
r = append(r, "")
|
||||||
|
}
|
||||||
|
return "| " + strings.Join(r, " | ") + " |"
|
||||||
|
}
|
||||||
|
var lines []string
|
||||||
|
lines = append(lines, pad(rows[0]))
|
||||||
|
sep := make([]string, cols)
|
||||||
|
for i := range sep {
|
||||||
|
sep[i] = "---"
|
||||||
|
}
|
||||||
|
lines = append(lines, "| "+strings.Join(sep, " | ")+" |")
|
||||||
|
for _, r := range rows[1:] {
|
||||||
|
lines = append(lines, pad(r))
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
func applyMdMarks(n pmNode) string {
|
func applyMdMarks(n pmNode) string {
|
||||||
t := n.Text
|
t := n.Text
|
||||||
if n.hasMark("code") {
|
if n.hasMark("code") {
|
||||||
@@ -230,6 +395,9 @@ func applyMdMarks(n pmNode) string {
|
|||||||
if n.hasMark("underline") {
|
if n.hasMark("underline") {
|
||||||
t = "<u>" + t + "</u>"
|
t = "<u>" + t + "</u>"
|
||||||
}
|
}
|
||||||
|
if href := n.markAttr("link", "href"); href != "" {
|
||||||
|
t = "[" + t + "](" + href + ")"
|
||||||
|
}
|
||||||
return t
|
return t
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,6 +515,11 @@ func htmlBlock(n pmNode) string {
|
|||||||
return "<pre><code>" + htmlEscape(textContent(n)) + "</code></pre>\n"
|
return "<pre><code>" + htmlEscape(textContent(n)) + "</code></pre>\n"
|
||||||
case "horizontalRule":
|
case "horizontalRule":
|
||||||
return "<hr>\n"
|
return "<hr>\n"
|
||||||
|
case "image":
|
||||||
|
alt := htmlEscape(n.attrStr("alt"))
|
||||||
|
return fmt.Sprintf("<p><img src=\"%s\" alt=\"%s\"></p>\n", htmlEscape(n.attrStr("src")), alt)
|
||||||
|
case "table":
|
||||||
|
return htmlTable(n)
|
||||||
case "bulletList", "orderedList":
|
case "bulletList", "orderedList":
|
||||||
tag := "ul"
|
tag := "ul"
|
||||||
if n.Type == "orderedList" {
|
if n.Type == "orderedList" {
|
||||||
@@ -376,6 +549,38 @@ func htmlBlock(n pmNode) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// htmlTable renders a table node as an HTML <table>. tableHeader cells become
|
||||||
|
// <th>, tableCell cells become <td>; each cell's block children are flattened
|
||||||
|
// to inline HTML.
|
||||||
|
func htmlTable(n pmNode) string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("<table>\n")
|
||||||
|
for _, row := range n.Content {
|
||||||
|
if row.Type != "tableRow" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b.WriteString("<tr>")
|
||||||
|
for _, cell := range row.Content {
|
||||||
|
tag := "td"
|
||||||
|
if cell.Type == "tableHeader" {
|
||||||
|
tag = "th"
|
||||||
|
}
|
||||||
|
var inner strings.Builder
|
||||||
|
for _, c := range cell.Content {
|
||||||
|
if c.Type == "paragraph" {
|
||||||
|
inner.WriteString(htmlInline(c.Content))
|
||||||
|
} else {
|
||||||
|
inner.WriteString(htmlBlock(c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteString("<" + tag + ">" + inner.String() + "</" + tag + ">")
|
||||||
|
}
|
||||||
|
b.WriteString("</tr>\n")
|
||||||
|
}
|
||||||
|
b.WriteString("</table>\n")
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
func htmlInline(nodes []pmNode) string {
|
func htmlInline(nodes []pmNode) string {
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
for _, n := range nodes {
|
for _, n := range nodes {
|
||||||
@@ -408,6 +613,12 @@ func applyHTMLMarks(n pmNode) string {
|
|||||||
if n.hasMark("strike") {
|
if n.hasMark("strike") {
|
||||||
t = "<s>" + t + "</s>"
|
t = "<s>" + t + "</s>"
|
||||||
}
|
}
|
||||||
|
if n.hasMark("highlight") {
|
||||||
|
t = "<mark>" + t + "</mark>"
|
||||||
|
}
|
||||||
|
if href := n.markAttr("link", "href"); href != "" {
|
||||||
|
t = fmt.Sprintf("<a href=\"%s\">%s</a>", htmlEscape(href), t)
|
||||||
|
}
|
||||||
return t
|
return t
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -500,6 +711,16 @@ func docxBlock(n pmNode) string {
|
|||||||
return b.String()
|
return b.String()
|
||||||
case "horizontalRule":
|
case "horizontalRule":
|
||||||
return `<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="auto"/></w:pBdr></w:pPr></w:p>`
|
return `<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="auto"/></w:pBdr></w:pPr></w:p>`
|
||||||
|
case "image":
|
||||||
|
// Image bytes aren't embedded (that needs media parts); leave a labeled
|
||||||
|
// placeholder so the reader knows an image belonged here.
|
||||||
|
label := n.attrStr("alt")
|
||||||
|
if label == "" {
|
||||||
|
label = "image"
|
||||||
|
}
|
||||||
|
return docxPara(pmNode{Content: []pmNode{{Type: "text", Text: "[" + label + "]", Marks: []pmMark{{Type: "italic"}}}}}, "")
|
||||||
|
case "table":
|
||||||
|
return docxTable(n)
|
||||||
case "bulletList", "orderedList":
|
case "bulletList", "orderedList":
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
for i, item := range n.Content {
|
for i, item := range n.Content {
|
||||||
@@ -520,6 +741,48 @@ func docxBlock(n pmNode) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// docxTable renders a table node as a Word table (w:tbl) with single-line
|
||||||
|
// borders. Header cells get a shaded background; every cell's block children are
|
||||||
|
// rendered as paragraphs inside the cell.
|
||||||
|
func docxTable(n pmNode) string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(`<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/>` +
|
||||||
|
`<w:tblBorders>` +
|
||||||
|
`<w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||||
|
`<w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||||
|
`<w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||||
|
`<w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||||
|
`<w:insideH w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||||
|
`<w:insideV w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||||
|
`</w:tblBorders></w:tblPr>`)
|
||||||
|
for _, row := range n.Content {
|
||||||
|
if row.Type != "tableRow" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b.WriteString("<w:tr>")
|
||||||
|
for _, cell := range row.Content {
|
||||||
|
b.WriteString("<w:tc><w:tcPr>")
|
||||||
|
if cell.Type == "tableHeader" {
|
||||||
|
b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="FFF0F5"/>`)
|
||||||
|
}
|
||||||
|
b.WriteString("</w:tcPr>")
|
||||||
|
// A cell must contain at least one paragraph to be valid.
|
||||||
|
if len(cell.Content) == 0 {
|
||||||
|
b.WriteString("<w:p/>")
|
||||||
|
}
|
||||||
|
for _, c := range cell.Content {
|
||||||
|
b.WriteString(docxBlock(c))
|
||||||
|
}
|
||||||
|
b.WriteString("</w:tc>")
|
||||||
|
}
|
||||||
|
b.WriteString("</w:tr>")
|
||||||
|
}
|
||||||
|
b.WriteString("</w:tbl>")
|
||||||
|
// Word needs a paragraph after a table; otherwise consecutive tables merge.
|
||||||
|
b.WriteString("<w:p/>")
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
// docxPara renders a block's inline children as a Word paragraph. An optional
|
// docxPara renders a block's inline children as a Word paragraph. An optional
|
||||||
// style name (e.g. "Quote") and an optional literal text prefix (for list
|
// style name (e.g. "Quote") and an optional literal text prefix (for list
|
||||||
// markers) may be supplied.
|
// markers) may be supplied.
|
||||||
@@ -571,6 +834,15 @@ func docxRun(n pmNode) string {
|
|||||||
if n.hasMark("strike") {
|
if n.hasMark("strike") {
|
||||||
props.WriteString("<w:strike/>")
|
props.WriteString("<w:strike/>")
|
||||||
}
|
}
|
||||||
|
if n.hasMark("highlight") {
|
||||||
|
// Word's text highlight only supports a fixed palette of named colors.
|
||||||
|
props.WriteString(`<w:highlight w:val="yellow"/>`)
|
||||||
|
}
|
||||||
|
if n.markAttr("link", "href") != "" {
|
||||||
|
// Without hyperlink relationships, style links as blue underlined text so
|
||||||
|
// they at least read as links (the URL itself is preserved in md/html).
|
||||||
|
props.WriteString(`<w:color w:val="2563EB"/><w:u w:val="single"/>`)
|
||||||
|
}
|
||||||
rpr := ""
|
rpr := ""
|
||||||
if props.Len() > 0 {
|
if props.Len() > 0 {
|
||||||
rpr = "<w:rPr>" + props.String() + "</w:rPr>"
|
rpr = "<w:rPr>" + props.String() + "</w:rPr>"
|
||||||
|
|||||||
@@ -61,6 +61,45 @@ func TestExportMarkdown(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExportAll(t *testing.T) {
|
||||||
|
srv := newTestServer(t)
|
||||||
|
// Two docs, one with a duplicate title to exercise filename de-duplication.
|
||||||
|
seedRichDoc(t, srv)
|
||||||
|
id2 := newDoc(t, srv)
|
||||||
|
if rec := do(t, srv, http.MethodPut, "/"+id2, `{"title":"日记 Diary","content":`+jsonString(richDocJSON)+`,"content_text":"x","word_count":1}`); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("seed second doc: %d %s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec := do(t, srv, http.MethodGet, "/export-all?format=md", "")
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("export-all: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
if ct := rec.Header().Get("Content-Type"); ct != "application/zip" {
|
||||||
|
t.Fatalf("unexpected content-type: %q", ct)
|
||||||
|
}
|
||||||
|
zr, err := zip.NewReader(bytes.NewReader(rec.Body.Bytes()), int64(rec.Body.Len()))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("zip open: %v", err)
|
||||||
|
}
|
||||||
|
if len(zr.File) != 2 {
|
||||||
|
t.Fatalf("expected 2 files in backup, got %d", len(zr.File))
|
||||||
|
}
|
||||||
|
names := map[string]bool{}
|
||||||
|
for _, f := range zr.File {
|
||||||
|
names[f.Name] = true
|
||||||
|
rc, _ := f.Open()
|
||||||
|
b, _ := io.ReadAll(rc)
|
||||||
|
rc.Close()
|
||||||
|
if !strings.Contains(string(b), "你好") {
|
||||||
|
t.Fatalf("backup entry %q missing CJK body", f.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The duplicate title must have been disambiguated, not overwritten.
|
||||||
|
if !names["日记 Diary.md"] || !names["日记 Diary (1).md"] {
|
||||||
|
t.Fatalf("expected de-duplicated filenames, got %v", names)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestExportHTML(t *testing.T) {
|
func TestExportHTML(t *testing.T) {
|
||||||
srv := newTestServer(t)
|
srv := newTestServer(t)
|
||||||
id := seedRichDoc(t, srv)
|
id := seedRichDoc(t, srv)
|
||||||
@@ -126,6 +165,77 @@ func TestExportDocx(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// richDocJSON2 exercises the newer node/mark types: links, highlight, an image,
|
||||||
|
// and a table (with a header row). Each export format should carry them through.
|
||||||
|
const richDocJSON2 = `{"type":"doc","content":[` +
|
||||||
|
`{"type":"paragraph","content":[` +
|
||||||
|
`{"type":"text","marks":[{"type":"link","attrs":{"href":"https://petal.test"}}],"text":"site"},` +
|
||||||
|
`{"type":"text","text":" and "},` +
|
||||||
|
`{"type":"text","marks":[{"type":"highlight","attrs":{"color":"#FFF1A8"}}],"text":"lit"}` +
|
||||||
|
`]},` +
|
||||||
|
`{"type":"image","attrs":{"src":"/api/images/abc123.png","alt":"a cat"}},` +
|
||||||
|
`{"type":"table","content":[` +
|
||||||
|
`{"type":"tableRow","content":[` +
|
||||||
|
`{"type":"tableHeader","content":[{"type":"paragraph","content":[{"type":"text","text":"Name"}]}]},` +
|
||||||
|
`{"type":"tableHeader","content":[{"type":"paragraph","content":[{"type":"text","text":"年龄"}]}]}` +
|
||||||
|
`]},` +
|
||||||
|
`{"type":"tableRow","content":[` +
|
||||||
|
`{"type":"tableCell","content":[{"type":"paragraph","content":[{"type":"text","text":"Mei"}]}]},` +
|
||||||
|
`{"type":"tableCell","content":[{"type":"paragraph","content":[{"type":"text","text":"30"}]}]}` +
|
||||||
|
`]}` +
|
||||||
|
`]}` +
|
||||||
|
`]}`
|
||||||
|
|
||||||
|
func seedRichDoc2(t *testing.T, srv http.Handler) string {
|
||||||
|
t.Helper()
|
||||||
|
id := newDoc(t, srv)
|
||||||
|
body := `{"title":"Rich2","content":` + jsonString(richDocJSON2) + `,"content_text":"site and lit\nName 年龄 Mei 30","word_count":6}`
|
||||||
|
if rec := do(t, srv, http.MethodPut, "/"+id, body); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("seed rich doc 2: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExportLinksImagesTables(t *testing.T) {
|
||||||
|
srv := newTestServer(t)
|
||||||
|
id := seedRichDoc2(t, srv)
|
||||||
|
|
||||||
|
md := do(t, srv, http.MethodGet, "/"+id+"/export?format=md", "").Body.String()
|
||||||
|
for _, want := range []string{"[site](https://petal.test)", "", "| Name | 年龄 |", "| --- | --- |", "| Mei | 30 |"} {
|
||||||
|
if !strings.Contains(md, want) {
|
||||||
|
t.Fatalf("markdown missing %q in:\n%s", want, md)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
html := do(t, srv, http.MethodGet, "/"+id+"/export?format=html", "").Body.String()
|
||||||
|
for _, want := range []string{`<a href="https://petal.test">site</a>`, "<mark>lit</mark>", `<img src="/api/images/abc123.png" alt="a cat">`, "<th>Name</th>", "<td>Mei</td>"} {
|
||||||
|
if !strings.Contains(html, want) {
|
||||||
|
t.Fatalf("html missing %q in:\n%s", want, html)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
docx := do(t, srv, http.MethodGet, "/"+id+"/export?format=docx", "")
|
||||||
|
raw := docx.Body.Bytes()
|
||||||
|
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("docx not a zip: %v", err)
|
||||||
|
}
|
||||||
|
var docXML string
|
||||||
|
for _, f := range zr.File {
|
||||||
|
if f.Name == "word/document.xml" {
|
||||||
|
rc, _ := f.Open()
|
||||||
|
b, _ := io.ReadAll(rc)
|
||||||
|
rc.Close()
|
||||||
|
docXML = string(b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, want := range []string{"<w:tbl>", "Name", "年龄", "[a cat]", "<w:highlight"} {
|
||||||
|
if !strings.Contains(docXML, want) {
|
||||||
|
t.Fatalf("docx document.xml missing %q", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestExportUnsupportedFormat(t *testing.T) {
|
func TestExportUnsupportedFormat(t *testing.T) {
|
||||||
srv := newTestServer(t)
|
srv := newTestServer(t)
|
||||||
id := newDoc(t, srv)
|
id := newDoc(t, srv)
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Handler holds the dependencies shared by every document route.
|
// Handler holds the dependencies shared by every document route.
|
||||||
@@ -62,7 +63,7 @@ func (h *Handler) list(w http.ResponseWriter, r *http.Request) {
|
|||||||
db.LocalUserID,
|
db.LocalUserID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
@@ -72,20 +73,20 @@ func (h *Handler) list(w http.ResponseWriter, r *http.Request) {
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var d docSummary
|
var d docSummary
|
||||||
if err := rows.Scan(&d.ID, &d.Title, &d.WordCount, &d.UpdatedAt); err != nil {
|
if err := rows.Scan(&d.ID, &d.Title, &d.WordCount, &d.UpdatedAt); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
out = append(out, d)
|
out = append(out, d)
|
||||||
ids = append(ids, d.ID)
|
ids = append(ids, d.ID)
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
if err := rows.Err(); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
byDoc, err := h.tagsByDoc(ids)
|
byDoc, err := h.tagsByDoc(ids)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
for i := range out {
|
for i := range out {
|
||||||
@@ -94,7 +95,7 @@ func (h *Handler) list(w http.ResponseWriter, r *http.Request) {
|
|||||||
out[i].Tags = []db.Tag{}
|
out[i].Tags = []db.Tag{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, out)
|
httputil.WriteJSON(w, http.StatusOK, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
// create inserts a fresh blank document and returns it in full.
|
// create inserts a fresh blank document and returns it in full.
|
||||||
@@ -109,10 +110,10 @@ func (h *Handler) create(w http.ResponseWriter, r *http.Request) {
|
|||||||
&doc.Tone, &doc.WordCount, &doc.CreatedAt, &doc.UpdatedAt,
|
&doc.Tone, &doc.WordCount, &doc.CreatedAt, &doc.UpdatedAt,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, doc)
|
httputil.WriteJSON(w, http.StatusCreated, doc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// get returns a single full document by id.
|
// get returns a single full document by id.
|
||||||
@@ -123,10 +124,10 @@ func (h *Handler) get(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, doc)
|
httputil.WriteJSON(w, http.StatusOK, doc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// updateRequest is the auto-save payload. Every field is optional (a pointer) so
|
// updateRequest is the auto-save payload. Every field is optional (a pointer) so
|
||||||
@@ -163,7 +164,7 @@ func (h *Handler) update(w http.ResponseWriter, r *http.Request) {
|
|||||||
req.Title, req.Content, req.ContentText, req.Tone, req.WordCount, id, db.LocalUserID,
|
req.Title, req.Content, req.ContentText, req.Tone, req.WordCount, id, db.LocalUserID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if n, _ := res.RowsAffected(); n == 0 {
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
@@ -173,7 +174,7 @@ func (h *Handler) update(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
doc, err := h.fetch(id)
|
doc, err := h.fetch(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,7 +187,7 @@ func (h *Handler) update(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
writeJSON(w, http.StatusOK, doc)
|
httputil.WriteJSON(w, http.StatusOK, doc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// delete removes a document (suggestions cascade via the FK).
|
// delete removes a document (suggestions cascade via the FK).
|
||||||
@@ -196,7 +197,7 @@ func (h *Handler) delete(w http.ResponseWriter, r *http.Request) {
|
|||||||
chi.URLParam(r, "id"), db.LocalUserID,
|
chi.URLParam(r, "id"), db.LocalUserID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if n, _ := res.RowsAffected(); n == 0 {
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
@@ -222,21 +223,12 @@ func (h *Handler) fetch(id string) (db.Document, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- small response helpers -------------------------------------------------
|
// --- small response helpers -------------------------------------------------
|
||||||
|
//
|
||||||
|
// The generic JSON/error helpers live in internal/httputil; these are the
|
||||||
|
// document-specific shorthands that carry domain wording.
|
||||||
|
|
||||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
func badRequest(w http.ResponseWriter, msg string) { httputil.BadRequest(w, msg) }
|
||||||
w.Header().Set("Content-Type", "application/json")
|
func notFound(w http.ResponseWriter) {
|
||||||
w.WriteHeader(status)
|
httputil.ErrorJSON(w, http.StatusNotFound, "document not found")
|
||||||
_ = json.NewEncoder(w).Encode(v)
|
|
||||||
}
|
}
|
||||||
|
func notFoundMsg(w http.ResponseWriter, msg string) { httputil.ErrorJSON(w, http.StatusNotFound, msg) }
|
||||||
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())
|
|
||||||
}
|
|
||||||
|
|
||||||
func badRequest(w http.ResponseWriter, msg string) { errorJSON(w, http.StatusBadRequest, msg) }
|
|
||||||
func notFound(w http.ResponseWriter) { errorJSON(w, http.StatusNotFound, "document not found") }
|
|
||||||
func notFoundMsg(w http.ResponseWriter, msg string) { errorJSON(w, http.StatusNotFound, msg) }
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Search snippet shaping.
|
// Search snippet shaping.
|
||||||
@@ -57,7 +58,7 @@ func (h *Handler) SearchRoutes() chi.Router {
|
|||||||
func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
|
||||||
q := strings.TrimSpace(r.URL.Query().Get("q"))
|
q := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||||
if q == "" {
|
if q == "" {
|
||||||
writeJSON(w, http.StatusOK, []searchResult{})
|
httputil.WriteJSON(w, http.StatusOK, []searchResult{})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,20 +83,20 @@ func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
|
|||||||
phrase, db.LocalUserID, maxSearchResults,
|
phrase, db.LocalUserID, maxSearchResults,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer sqlRows.Close()
|
defer sqlRows.Close()
|
||||||
for sqlRows.Next() {
|
for sqlRows.Next() {
|
||||||
var rw row
|
var rw row
|
||||||
if err := sqlRows.Scan(&rw.id, &rw.title, &rw.contentText, &rw.wordCount, &rw.updatedAt); err != nil {
|
if err := sqlRows.Scan(&rw.id, &rw.title, &rw.contentText, &rw.wordCount, &rw.updatedAt); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
rows = append(rows, rw)
|
rows = append(rows, rw)
|
||||||
}
|
}
|
||||||
if err := sqlRows.Err(); err != nil {
|
if err := sqlRows.Err(); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -112,20 +113,20 @@ func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
|
|||||||
db.LocalUserID, like, like, maxSearchResults,
|
db.LocalUserID, like, like, maxSearchResults,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer sqlRows.Close()
|
defer sqlRows.Close()
|
||||||
for sqlRows.Next() {
|
for sqlRows.Next() {
|
||||||
var rw row
|
var rw row
|
||||||
if err := sqlRows.Scan(&rw.id, &rw.title, &rw.contentText, &rw.wordCount, &rw.updatedAt); err != nil {
|
if err := sqlRows.Scan(&rw.id, &rw.title, &rw.contentText, &rw.wordCount, &rw.updatedAt); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
rows = append(rows, rw)
|
rows = append(rows, rw)
|
||||||
}
|
}
|
||||||
if err := sqlRows.Err(); err != nil {
|
if err := sqlRows.Err(); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,7 +146,7 @@ func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
byDoc, err := h.tagsByDoc(ids)
|
byDoc, err := h.tagsByDoc(ids)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
for i := range out {
|
for i := range out {
|
||||||
@@ -154,7 +155,7 @@ func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
|
|||||||
out[i].Tags = []db.Tag{}
|
out[i].Tags = []db.Tag{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, out)
|
httputil.WriteJSON(w, http.StatusOK, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
// escapeLike escapes the LIKE metacharacters (% and _) and the escape character
|
// escapeLike escapes the LIKE metacharacters (% and _) and the escape character
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// validTagColors is the palette a tag may use, mirrored from the design tokens.
|
// validTagColors is the palette a tag may use, mirrored from the design tokens.
|
||||||
@@ -57,7 +58,7 @@ func (h *Handler) listTags(w http.ResponseWriter, r *http.Request) {
|
|||||||
db.LocalUserID,
|
db.LocalUserID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
@@ -66,16 +67,16 @@ func (h *Handler) listTags(w http.ResponseWriter, r *http.Request) {
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var t db.Tag
|
var t db.Tag
|
||||||
if err := rows.Scan(&t.ID, &t.Name, &t.Color, &t.DocCount); err != nil {
|
if err := rows.Scan(&t.ID, &t.Name, &t.Color, &t.DocCount); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
out = append(out, t)
|
out = append(out, t)
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
if err := rows.Err(); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, out)
|
httputil.WriteJSON(w, http.StatusOK, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
type tagRequest struct {
|
type tagRequest struct {
|
||||||
@@ -106,10 +107,10 @@ func (h *Handler) createTag(w http.ResponseWriter, r *http.Request) {
|
|||||||
db.LocalUserID, name, normalizeColor(req.Color),
|
db.LocalUserID, name, normalizeColor(req.Color),
|
||||||
).Scan(&t.ID, &t.Name, &t.Color)
|
).Scan(&t.ID, &t.Name, &t.Color)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, t)
|
httputil.WriteJSON(w, http.StatusCreated, t)
|
||||||
}
|
}
|
||||||
|
|
||||||
// updateTag renames and/or recolors a tag. Both fields optional via pointers so
|
// updateTag renames and/or recolors a tag. Both fields optional via pointers so
|
||||||
@@ -147,7 +148,7 @@ func (h *Handler) updateTag(w http.ResponseWriter, r *http.Request) {
|
|||||||
namePtr, colorPtr, id, db.LocalUserID,
|
namePtr, colorPtr, id, db.LocalUserID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if n, _ := res.RowsAffected(); n == 0 {
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
@@ -160,10 +161,10 @@ func (h *Handler) updateTag(w http.ResponseWriter, r *http.Request) {
|
|||||||
`SELECT id, name, color FROM tags WHERE id = ? AND user_id = ?`,
|
`SELECT id, name, color FROM tags WHERE id = ? AND user_id = ?`,
|
||||||
id, db.LocalUserID,
|
id, db.LocalUserID,
|
||||||
).Scan(&t.ID, &t.Name, &t.Color); err != nil {
|
).Scan(&t.ID, &t.Name, &t.Color); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, t)
|
httputil.WriteJSON(w, http.StatusOK, t)
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteTag removes a tag; its document assignments cascade away via the FK.
|
// deleteTag removes a tag; its document assignments cascade away via the FK.
|
||||||
@@ -173,7 +174,7 @@ func (h *Handler) deleteTag(w http.ResponseWriter, r *http.Request) {
|
|||||||
chi.URLParam(r, "id"), db.LocalUserID,
|
chi.URLParam(r, "id"), db.LocalUserID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if n, _ := res.RowsAffected(); n == 0 {
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
@@ -216,7 +217,7 @@ func (h *Handler) assignTag(w http.ResponseWriter, r *http.Request) {
|
|||||||
ON CONFLICT(doc_id, tag_id) DO NOTHING`,
|
ON CONFLICT(doc_id, tag_id) DO NOTHING`,
|
||||||
docID, req.TagID,
|
docID, req.TagID,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
@@ -235,7 +236,7 @@ func (h *Handler) unassignTag(w http.ResponseWriter, r *http.Request) {
|
|||||||
`DELETE FROM document_tags WHERE doc_id = ? AND tag_id = ?`,
|
`DELETE FROM document_tags WHERE doc_id = ? AND tag_id = ?`,
|
||||||
docID, tagID,
|
docID, tagID,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Version-history tuning.
|
// Version-history tuning.
|
||||||
@@ -29,8 +30,8 @@ const (
|
|||||||
// resolve to /api/docs/{id}/versions...
|
// resolve to /api/docs/{id}/versions...
|
||||||
func (h *Handler) versionRoutes(r chi.Router) {
|
func (h *Handler) versionRoutes(r chi.Router) {
|
||||||
r.Get("/{id}/versions", h.listVersions)
|
r.Get("/{id}/versions", h.listVersions)
|
||||||
r.Post("/{id}/versions", h.createVersion) // explicit "save a restore point"
|
r.Post("/{id}/versions", h.createVersion) // explicit "save a restore point"
|
||||||
r.Get("/{id}/versions/{vid}", h.getVersion) // full body for preview
|
r.Get("/{id}/versions/{vid}", h.getVersion) // full body for preview
|
||||||
r.Post("/{id}/versions/{vid}/restore", h.restoreVersion)
|
r.Post("/{id}/versions/{vid}/restore", h.restoreVersion)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,7 +51,7 @@ func (h *Handler) listVersions(w http.ResponseWriter, r *http.Request) {
|
|||||||
docID, db.LocalUserID,
|
docID, db.LocalUserID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
@@ -59,16 +60,16 @@ func (h *Handler) listVersions(w http.ResponseWriter, r *http.Request) {
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var v db.DocumentVersion
|
var v db.DocumentVersion
|
||||||
if err := rows.Scan(&v.ID, &v.DocID, &v.Title, &v.WordCount, &v.Kind, &v.CreatedAt); err != nil {
|
if err := rows.Scan(&v.ID, &v.DocID, &v.Title, &v.WordCount, &v.Kind, &v.CreatedAt); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
out = append(out, v)
|
out = append(out, v)
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
if err := rows.Err(); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, out)
|
httputil.WriteJSON(w, http.StatusOK, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
// getVersion returns one snapshot in full (including content) for preview.
|
// getVersion returns one snapshot in full (including content) for preview.
|
||||||
@@ -79,10 +80,10 @@ func (h *Handler) getVersion(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, v)
|
httputil.WriteJSON(w, http.StatusOK, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
// createVersion takes an explicit, user-requested ('manual') restore point from
|
// createVersion takes an explicit, user-requested ('manual') restore point from
|
||||||
@@ -96,16 +97,16 @@ func (h *Handler) createVersion(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
v, err := h.insertVersion(doc, db.VersionKindManual)
|
v, err := h.insertVersion(doc, db.VersionKindManual)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusCreated, v)
|
httputil.WriteJSON(w, http.StatusCreated, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
// restoreVersion copies a snapshot back onto the live document. Before
|
// restoreVersion copies a snapshot back onto the live document. Before
|
||||||
@@ -121,17 +122,17 @@ func (h *Handler) restoreVersion(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
current, err := h.fetch(docID)
|
current, err := h.fetch(docID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, err := h.insertVersion(current, db.VersionKindPreRestore); err != nil {
|
if _, err := h.insertVersion(current, db.VersionKindPreRestore); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +144,7 @@ func (h *Handler) restoreVersion(w http.ResponseWriter, r *http.Request) {
|
|||||||
v.Title, v.Content, v.ContentText, v.WordCount, docID, db.LocalUserID,
|
v.Title, v.Content, v.ContentText, v.WordCount, docID, db.LocalUserID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if n, _ := res.RowsAffected(); n == 0 {
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
@@ -153,10 +154,10 @@ func (h *Handler) restoreVersion(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
doc, err := h.fetch(docID)
|
doc, err := h.fetch(docID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, doc)
|
httputil.WriteJSON(w, http.StatusOK, doc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// maybeAutoSnapshot records a throttled background snapshot of the just-saved
|
// maybeAutoSnapshot records a throttled background snapshot of the just-saved
|
||||||
|
|||||||
37
internal/httputil/json.go
Normal file
37
internal/httputil/json.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
// Package httputil holds the small HTTP response helpers shared by every API
|
||||||
|
// handler package (docs, suggestions, vocab, …). Keeping them in one place means
|
||||||
|
// JSON encoding and — crucially — error handling behave identically everywhere:
|
||||||
|
// internal errors are logged in full but never leaked to the client.
|
||||||
|
package httputil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WriteJSON encodes v as the response body with the given status code.
|
||||||
|
func WriteJSON(w http.ResponseWriter, status int, v any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrorJSON sends a {"error": msg} body with the given status. The message is
|
||||||
|
// caller-chosen and safe to show the client.
|
||||||
|
func ErrorJSON(w http.ResponseWriter, status int, msg string) {
|
||||||
|
WriteJSON(w, status, map[string]string{"error": msg})
|
||||||
|
}
|
||||||
|
|
||||||
|
// BadRequest is the common 400 shorthand.
|
||||||
|
func BadRequest(w http.ResponseWriter, msg string) {
|
||||||
|
ErrorJSON(w, http.StatusBadRequest, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServerError logs the real error (with full detail, for the operator) and
|
||||||
|
// returns a generic 500 to the client — raw database/internal errors must never
|
||||||
|
// reach the browser, where they leak schema and implementation details.
|
||||||
|
func ServerError(w http.ResponseWriter, err error) {
|
||||||
|
log.Printf("internal error: %v", err)
|
||||||
|
ErrorJSON(w, http.StatusInternalServerError, "something went wrong")
|
||||||
|
}
|
||||||
132
internal/images/handler.go
Normal file
132
internal/images/handler.go
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
// Package images implements a tiny content-addressed image store: writers upload
|
||||||
|
// images from the editor, they're saved to disk under the configured directory,
|
||||||
|
// and served back by hashed filename. Content addressing means the same image
|
||||||
|
// pasted twice is stored once, and URLs are stable and cacheable forever.
|
||||||
|
package images
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxUploadBytes caps a single image at 10 MiB — generous for a writing tool,
|
||||||
|
// small enough to keep a careless paste from filling the disk.
|
||||||
|
const maxUploadBytes = 10 << 20
|
||||||
|
|
||||||
|
// extByContentType maps the image types we accept to a canonical extension. The
|
||||||
|
// allowlist doubles as validation: anything not here is rejected.
|
||||||
|
var extByContentType = map[string]string{
|
||||||
|
"image/png": ".png",
|
||||||
|
"image/jpeg": ".jpg",
|
||||||
|
"image/gif": ".gif",
|
||||||
|
"image/webp": ".webp",
|
||||||
|
"image/svg+xml": ".svg",
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handler serves the upload + fetch endpoints, backed by a directory on disk.
|
||||||
|
type Handler struct {
|
||||||
|
dir string
|
||||||
|
}
|
||||||
|
|
||||||
|
// New constructs a Handler, ensuring the storage directory exists.
|
||||||
|
func New(dir string) (*Handler, error) {
|
||||||
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Handler{dir: dir}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Routes mounts the image endpoints. Mount under "/images" so the full paths are
|
||||||
|
// POST /api/images (upload) and GET /api/images/{name} (fetch).
|
||||||
|
func (h *Handler) Routes() chi.Router {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Post("/", h.upload)
|
||||||
|
r.Get("/{name}", h.serve)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// upload accepts a single multipart "image" field, sniffs and validates its
|
||||||
|
// type, and writes it under a content hash so identical images dedupe. Responds
|
||||||
|
// with the served URL the editor inserts.
|
||||||
|
func (h *Handler) upload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, maxUploadBytes)
|
||||||
|
file, _, err := r.FormFile("image")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "expected an 'image' file field", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
data, err := io.ReadAll(file)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "could not read upload", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trust a sniff over the client-declared type. SVG isn't reliably sniffable
|
||||||
|
// (DetectContentType returns text/plain or text/xml), so fall back to a
|
||||||
|
// lightweight tag check for it.
|
||||||
|
ct := http.DetectContentType(data)
|
||||||
|
ext, ok := extByContentType[ct]
|
||||||
|
if !ok {
|
||||||
|
if looksLikeSVG(data) {
|
||||||
|
ext, ok = ".svg", true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "unsupported image type", http.StatusUnsupportedMediaType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sum := sha256.Sum256(data)
|
||||||
|
name := hex.EncodeToString(sum[:])[:32] + ext
|
||||||
|
path := filepath.Join(h.dir, name)
|
||||||
|
|
||||||
|
// Skip the write if this exact content is already stored.
|
||||||
|
if _, statErr := os.Stat(path); errors.Is(statErr, os.ErrNotExist) {
|
||||||
|
if err := os.WriteFile(path, data, 0o644); err != nil {
|
||||||
|
http.Error(w, "could not store image", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]string{"url": "/api/images/" + name})
|
||||||
|
}
|
||||||
|
|
||||||
|
// serve returns a stored image by its hashed filename. The filename is validated
|
||||||
|
// to be a bare name (no path separators) so it can't escape the storage dir, and
|
||||||
|
// served with a long-lived cache header since content-addressed URLs never change.
|
||||||
|
func (h *Handler) serve(w http.ResponseWriter, r *http.Request) {
|
||||||
|
name := chi.URLParam(r, "name")
|
||||||
|
if name == "" || name != filepath.Base(name) || strings.ContainsAny(name, `/\`) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
path := filepath.Join(h.dir, filepath.Base(name))
|
||||||
|
if _, err := os.Stat(path); err != nil {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
|
http.ServeFile(w, r, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// looksLikeSVG does a cheap check for an <svg root tag near the start of the
|
||||||
|
// file, since DetectContentType doesn't recognize SVG.
|
||||||
|
func looksLikeSVG(data []byte) bool {
|
||||||
|
head := data
|
||||||
|
if len(head) > 512 {
|
||||||
|
head = head[:512]
|
||||||
|
}
|
||||||
|
return strings.Contains(strings.ToLower(string(head)), "<svg")
|
||||||
|
}
|
||||||
97
internal/images/handler_test.go
Normal file
97
internal/images/handler_test.go
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
package images
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// a 1x1 transparent PNG.
|
||||||
|
var pngBytes = []byte{
|
||||||
|
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
|
||||||
|
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
|
||||||
|
0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x62, 0x00, 0x01, 0x00, 0x00,
|
||||||
|
0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
|
||||||
|
0x42, 0x60, 0x82,
|
||||||
|
}
|
||||||
|
|
||||||
|
func uploadReq(t *testing.T, field string, data []byte) *http.Request {
|
||||||
|
t.Helper()
|
||||||
|
var buf bytes.Buffer
|
||||||
|
mw := multipart.NewWriter(&buf)
|
||||||
|
fw, err := mw.CreateFormFile(field, "x.png")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fw.Write(data)
|
||||||
|
mw.Close()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/", &buf)
|
||||||
|
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||||
|
return req
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadAndServe(t *testing.T) {
|
||||||
|
h, err := New(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := h.Routes()
|
||||||
|
|
||||||
|
// Upload a PNG → expect a JSON url under /api/images/.
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, uploadReq(t, "image", pngBytes))
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("upload code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
var resp struct{ URL string }
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(resp.URL, "/api/images/") || !strings.HasSuffix(resp.URL, ".png") {
|
||||||
|
t.Fatalf("unexpected url %q", resp.URL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same content uploaded again dedupes to the same URL.
|
||||||
|
rec2 := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec2, uploadReq(t, "image", pngBytes))
|
||||||
|
var resp2 struct{ URL string }
|
||||||
|
json.Unmarshal(rec2.Body.Bytes(), &resp2)
|
||||||
|
if resp2.URL != resp.URL {
|
||||||
|
t.Fatalf("expected dedup to same url, got %q vs %q", resp2.URL, resp.URL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch it back.
|
||||||
|
name := strings.TrimPrefix(resp.URL, "/api/images/")
|
||||||
|
rec3 := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec3, httptest.NewRequest(http.MethodGet, "/"+name, nil))
|
||||||
|
if rec3.Code != http.StatusOK {
|
||||||
|
t.Fatalf("serve code=%d", rec3.Code)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(rec3.Body.Bytes(), pngBytes) {
|
||||||
|
t.Fatal("served bytes differ from uploaded")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadRejectsNonImage(t *testing.T) {
|
||||||
|
h, _ := New(t.TempDir())
|
||||||
|
r := h.Routes()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, uploadReq(t, "image", []byte("this is plainly not an image at all")))
|
||||||
|
if rec.Code != http.StatusUnsupportedMediaType {
|
||||||
|
t.Fatalf("expected 415, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServeMissing(t *testing.T) {
|
||||||
|
h, _ := New(t.TempDir())
|
||||||
|
r := h.Routes()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/deadbeef.png", nil))
|
||||||
|
if rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("expected 404, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,3 +27,12 @@ var synonymsGz []byte
|
|||||||
//
|
//
|
||||||
//go:embed data/gloss.json.gz
|
//go:embed data/gloss.json.gz
|
||||||
var glossGz []byte
|
var glossGz []byte
|
||||||
|
|
||||||
|
// phoneticGz is the gzipped English-phonetic map: word → IPA, lowercase keys.
|
||||||
|
// Built from ECDICT's phonetic column (scripts/build_phonetic.py). Shown beside
|
||||||
|
// the read-aloud button so the writer — a Mandarin speaker learning English —
|
||||||
|
// can see how to say the word. Ships with a small common-word seed; a full build
|
||||||
|
// broadens coverage.
|
||||||
|
//
|
||||||
|
//go:embed data/phonetic.json.gz
|
||||||
|
var phoneticGz []byte
|
||||||
|
|||||||
BIN
internal/lexicon/data/phonetic.json.gz
Normal file
BIN
internal/lexicon/data/phonetic.json.gz
Normal file
Binary file not shown.
@@ -26,6 +26,7 @@ type Meaning struct {
|
|||||||
type Result struct {
|
type Result struct {
|
||||||
Word string `json:"word"`
|
Word string `json:"word"`
|
||||||
Gloss string `json:"gloss"`
|
Gloss string `json:"gloss"`
|
||||||
|
Phonetic string `json:"phonetic"` // IPA for the English word; "" when absent
|
||||||
Definitions []Meaning `json:"definitions"`
|
Definitions []Meaning `json:"definitions"`
|
||||||
Synonyms []string `json:"synonyms"`
|
Synonyms []string `json:"synonyms"`
|
||||||
}
|
}
|
||||||
@@ -56,6 +57,7 @@ type Lexicon struct {
|
|||||||
defs map[string][][]string // word → [[pos, def, example], …]
|
defs map[string][][]string // word → [[pos, def, example], …]
|
||||||
synonyms map[string][]string // word → [synonym, …]
|
synonyms map[string][]string // word → [synonym, …]
|
||||||
gloss map[string]string // word → Chinese gloss
|
gloss map[string]string // word → Chinese gloss
|
||||||
|
phonetic map[string]string // word → IPA
|
||||||
}
|
}
|
||||||
|
|
||||||
// New returns a Lexicon. The datasets aren't read until the first Lookup.
|
// New returns a Lexicon. The datasets aren't read until the first Lookup.
|
||||||
@@ -75,6 +77,10 @@ func (l *Lexicon) load() {
|
|||||||
l.loadErr = fmt.Errorf("load gloss: %w", err)
|
l.loadErr = fmt.Errorf("load gloss: %w", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if err := gunzipJSON(phoneticGz, &l.phonetic); err != nil {
|
||||||
|
l.loadErr = fmt.Errorf("load phonetic: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,6 +101,9 @@ func (l *Lexicon) Lookup(word string) (Result, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
res.Gloss = lookupGloss(l.gloss, norm)
|
res.Gloss = lookupGloss(l.gloss, norm)
|
||||||
|
// Phonetic is a word→string map like the gloss, so the same de-inflecting
|
||||||
|
// candidate walk resolves "running" → "run", etc.
|
||||||
|
res.Phonetic = lookupGloss(l.phonetic, norm)
|
||||||
|
|
||||||
if raw := lookupDefs(l.defs, norm); raw != nil {
|
if raw := lookupDefs(l.defs, norm); raw != nil {
|
||||||
for _, m := range raw {
|
for _, m := range raw {
|
||||||
|
|||||||
@@ -14,6 +14,16 @@ import (
|
|||||||
// that protects the inference endpoint from rapid repeat checks.
|
// that protects the inference endpoint from rapid repeat checks.
|
||||||
const CheckpointInterval = 30 * time.Second
|
const CheckpointInterval = 30 * time.Second
|
||||||
|
|
||||||
|
// checkpointMaxTokens caps the checkpoint's generated output. Each suggestion
|
||||||
|
// echoes its original sentence, a replacement, and a friendly explanation, so
|
||||||
|
// the full JSON for the prompt's "up to 5 issues" runs ~2,000 tokens on a long
|
||||||
|
// document (measured ~2,007 for a 380-word doc). The old 1,024 cap truncated
|
||||||
|
// the JSON mid-array — done_reason "length" — leaving an object that never
|
||||||
|
// closed, so ParseCheckpoint found no parseable JSON and the pass 502'd on
|
||||||
|
// every long doc. This is a ceiling, not a target: the model stops at its JSON
|
||||||
|
// close well before it, so the headroom costs nothing on shorter docs.
|
||||||
|
const checkpointMaxTokens = 4096
|
||||||
|
|
||||||
// RawSuggestion is one item as the model emits it. Positions are resolved
|
// RawSuggestion is one item as the model emits it. Positions are resolved
|
||||||
// server-side from Original; the frontend re-anchors by string at render time.
|
// server-side from Original; the frontend re-anchors by string at render time.
|
||||||
type RawSuggestion struct {
|
type RawSuggestion struct {
|
||||||
@@ -34,7 +44,7 @@ type checkpointResponse struct {
|
|||||||
func RunCheckpoint(ctx context.Context, client LLMClient, contentText, tone string) ([]RawSuggestion, error) {
|
func RunCheckpoint(ctx context.Context, client LLMClient, contentText, tone string) ([]RawSuggestion, error) {
|
||||||
raw, err := client.Complete(ctx, CompletionRequest{
|
raw, err := client.Complete(ctx, CompletionRequest{
|
||||||
Messages: CheckpointMessages(TruncateDoc(contentText), tone),
|
Messages: CheckpointMessages(TruncateDoc(contentText), tone),
|
||||||
MaxTokens: 1024,
|
MaxTokens: checkpointMaxTokens,
|
||||||
Temperature: 0.3,
|
Temperature: 0.3,
|
||||||
RepetitionPenalty: 1.15,
|
RepetitionPenalty: 1.15,
|
||||||
TopP: 0.9,
|
TopP: 0.9,
|
||||||
@@ -48,36 +58,99 @@ func RunCheckpoint(ctx context.Context, client LLMClient, contentText, tone stri
|
|||||||
|
|
||||||
// ParseCheckpoint extracts the suggestions array from a model response. Smaller
|
// ParseCheckpoint extracts the suggestions array from a model response. Smaller
|
||||||
// models sometimes wrap JSON in prose or markdown fences despite instructions,
|
// models sometimes wrap JSON in prose or markdown fences despite instructions,
|
||||||
// so we salvage the outermost {...} object before decoding.
|
// so we salvage the outermost {...} object before decoding. When the model
|
||||||
|
// truncates mid-array (it ran out of output budget) the outer object never
|
||||||
|
// closes and won't parse — we then recover the suggestion objects that *did*
|
||||||
|
// complete, so a long document still gets feedback instead of a hard failure.
|
||||||
func ParseCheckpoint(raw string) ([]RawSuggestion, error) {
|
func ParseCheckpoint(raw string) ([]RawSuggestion, error) {
|
||||||
jsonText := extractJSONObject(raw)
|
var suggestions []RawSuggestion
|
||||||
if jsonText == "" {
|
parsed := false
|
||||||
return nil, fmt.Errorf("checkpoint: no JSON object in model output: %q", truncateForError(raw))
|
if jsonText := extractJSONObject(raw); jsonText != "" {
|
||||||
|
var resp checkpointResponse
|
||||||
|
if err := json.Unmarshal([]byte(jsonText), &resp); err == nil {
|
||||||
|
suggestions = resp.Suggestions
|
||||||
|
parsed = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
var parsed checkpointResponse
|
if !parsed {
|
||||||
if err := json.Unmarshal([]byte(jsonText), &parsed); err != nil {
|
// No closeable object, or it failed to decode (most often a truncated
|
||||||
return nil, fmt.Errorf("checkpoint: parse JSON: %w (got %q)", err, truncateForError(jsonText))
|
// array). Salvage the individual suggestion objects that completed.
|
||||||
|
suggestions = salvageSuggestions(raw)
|
||||||
|
if suggestions == nil {
|
||||||
|
return nil, fmt.Errorf("checkpoint: no JSON object in model output: %q", truncateForError(raw))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Drop items the model returned with an empty original — they can't be
|
// Drop items the model returned with an empty original — they can't be
|
||||||
// anchored — and normalize whitespace the model may have echoed.
|
// anchored — and normalize whitespace the model may have echoed.
|
||||||
out := parsed.Suggestions[:0]
|
out := suggestions[:0]
|
||||||
for _, s := range parsed.Suggestions {
|
for _, s := range suggestions {
|
||||||
s.Original = strings.TrimSpace(s.Original)
|
s.Original = strings.TrimSpace(s.Original)
|
||||||
s.Replacement = strings.TrimSpace(s.Replacement)
|
s.Replacement = strings.TrimSpace(s.Replacement)
|
||||||
if s.Original == "" {
|
if s.Original == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// Drop no-ops: the model sometimes "flags" a correct sentence and echoes
|
||||||
|
// it verbatim as the replacement, producing a card whose before/after are
|
||||||
|
// identical and whose explanation says it's already fine — a suggestion
|
||||||
|
// that suggests nothing. Awareness-only families (voice) carry an empty
|
||||||
|
// replacement, so this only ever fires on the edit families.
|
||||||
|
if s.Replacement != "" && s.Original == s.Replacement {
|
||||||
|
continue
|
||||||
|
}
|
||||||
out = append(out, s)
|
out = append(out, s)
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// salvageSuggestions recovers as many complete suggestion objects as it can from
|
||||||
|
// a response whose top-level JSON didn't parse — typically one truncated mid
|
||||||
|
// "suggestions" array. It scans the array region for brace-balanced {...}
|
||||||
|
// objects and keeps each that decodes into a RawSuggestion with a non-empty
|
||||||
|
// original; the final, cut-off object simply never balances and is dropped.
|
||||||
|
// Returns nil when there is no salvageable array (so the caller can error).
|
||||||
|
func salvageSuggestions(raw string) []RawSuggestion {
|
||||||
|
key := strings.Index(raw, `"suggestions"`)
|
||||||
|
if key < 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
lb := strings.IndexByte(raw[key:], '[')
|
||||||
|
if lb < 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
rest := raw[key+lb+1:]
|
||||||
|
out := []RawSuggestion{}
|
||||||
|
for {
|
||||||
|
obj, end := firstBalancedObject(rest)
|
||||||
|
if end < 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
var s RawSuggestion
|
||||||
|
if err := json.Unmarshal([]byte(obj), &s); err == nil && strings.TrimSpace(s.Original) != "" {
|
||||||
|
out = append(out, s)
|
||||||
|
}
|
||||||
|
rest = rest[end:]
|
||||||
|
}
|
||||||
|
if len(out) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// extractJSONObject returns the substring from the first '{' to its matching
|
// extractJSONObject returns the substring from the first '{' to its matching
|
||||||
// closing '}', or "" if none. Tolerates fences/preamble around the object.
|
// closing '}', or "" if none. Tolerates fences/preamble around the object.
|
||||||
func extractJSONObject(s string) string {
|
func extractJSONObject(s string) string {
|
||||||
|
obj, _ := firstBalancedObject(s)
|
||||||
|
return obj
|
||||||
|
}
|
||||||
|
|
||||||
|
// firstBalancedObject returns the first brace-balanced {...} substring in s and
|
||||||
|
// the index in s just past its closing brace, or ("", -1) if no object closes
|
||||||
|
// (none present, or the only one is truncated). String contents — including
|
||||||
|
// braces inside quoted values — are skipped so they can't unbalance the count.
|
||||||
|
func firstBalancedObject(s string) (string, int) {
|
||||||
start := strings.IndexByte(s, '{')
|
start := strings.IndexByte(s, '{')
|
||||||
if start < 0 {
|
if start < 0 {
|
||||||
return ""
|
return "", -1
|
||||||
}
|
}
|
||||||
depth := 0
|
depth := 0
|
||||||
inString := false
|
inString := false
|
||||||
@@ -98,11 +171,11 @@ func extractJSONObject(s string) string {
|
|||||||
case c == '}':
|
case c == '}':
|
||||||
depth--
|
depth--
|
||||||
if depth == 0 {
|
if depth == 0 {
|
||||||
return s[start : i+1]
|
return s[start : i+1], i + 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return ""
|
return "", -1
|
||||||
}
|
}
|
||||||
|
|
||||||
func truncateForError(s string) string {
|
func truncateForError(s string) string {
|
||||||
@@ -127,17 +200,33 @@ func NewRateLimiter(interval time.Duration) *RateLimiter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Allow reports whether a checkpoint may run for docID now. When allowed it
|
// Allow reports whether a checkpoint may run for docID now. When allowed it
|
||||||
// records the time and returns (true, 0); when throttled it returns
|
// records the time and returns (true, 0, recordedAt); when throttled it returns
|
||||||
// (false, retryAfter) where retryAfter is the wait until the next allowed run.
|
// (false, retryAfter, zero) where retryAfter is the wait until the next allowed
|
||||||
func (rl *RateLimiter) Allow(docID string) (bool, time.Duration) {
|
// run. recordedAt lets a caller whose pass fails hand the exact timestamp to
|
||||||
|
// Release so it rolls back only its own slot.
|
||||||
|
func (rl *RateLimiter) Allow(docID string) (bool, time.Duration, time.Time) {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
defer rl.mu.Unlock()
|
defer rl.mu.Unlock()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
if last, ok := rl.last[docID]; ok {
|
if last, ok := rl.last[docID]; ok {
|
||||||
if elapsed := now.Sub(last); elapsed < rl.interval {
|
if elapsed := now.Sub(last); elapsed < rl.interval {
|
||||||
return false, rl.interval - elapsed
|
return false, rl.interval - elapsed, time.Time{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
rl.last[docID] = now
|
rl.last[docID] = now
|
||||||
return true, 0
|
return true, 0, now
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release rolls back the slot a prior Allow recorded for docID, but only if no
|
||||||
|
// newer Allow has since claimed it. Called when an LLM pass fails: Allow runs
|
||||||
|
// before the model call, so without this a failed checkpoint would hold the
|
||||||
|
// per-document slot for the full interval and a retry (or the frontend's
|
||||||
|
// auto-retry) would hit the throttle path and get the stale/empty set back
|
||||||
|
// instead of re-running. `at` is the time the failed Allow returned.
|
||||||
|
func (rl *RateLimiter) Release(docID string, at time.Time) {
|
||||||
|
rl.mu.Lock()
|
||||||
|
defer rl.mu.Unlock()
|
||||||
|
if last, ok := rl.last[docID]; ok && last.Equal(at) {
|
||||||
|
delete(rl.last, docID)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,11 +37,45 @@ func TestParseCheckpoint(t *testing.T) {
|
|||||||
raw: "I could not find any issues!",
|
raw: "I could not find any issues!",
|
||||||
wantErr: true,
|
wantErr: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// A correct sentence echoed verbatim as its own replacement is a card
|
||||||
|
// that suggests nothing — dropped. The second item is a real edit.
|
||||||
|
name: "drops no-op where replacement equals original",
|
||||||
|
raw: `{"suggestions":[{"original":"It wasn't the most graceful morning.","replacement":"It wasn't the most graceful morning.","explanation":"used correctly here","type":"idiom"},{"original":"teh","replacement":"the","explanation":"typo","type":"grammar"}]}`,
|
||||||
|
want: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Whitespace-only difference is still a no-op once both are trimmed.
|
||||||
|
name: "drops no-op after whitespace trim",
|
||||||
|
raw: `{"suggestions":[{"original":"the cat sat","replacement":" the cat sat ","explanation":"already fine","type":"grammar"}]}`,
|
||||||
|
want: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Awareness-only voice flags carry an empty replacement and must survive.
|
||||||
|
name: "keeps awareness-only flag with empty replacement",
|
||||||
|
raw: `{"suggestions":[{"original":"a long run-on passage","replacement":"","explanation":"this drifts from your voice","type":"voice"}]}`,
|
||||||
|
want: 1,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "braces inside string values",
|
name: "braces inside string values",
|
||||||
raw: `{"suggestions":[{"original":"use {x}","replacement":"use x","explanation":"drop the braces","type":"clarity"}]}`,
|
raw: `{"suggestions":[{"original":"use {x}","replacement":"use x","explanation":"drop the braces","type":"clarity"}]}`,
|
||||||
want: 1,
|
want: 1,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// The bug that 502'd every long doc: the model hit num_predict and the
|
||||||
|
// JSON never closed. Two suggestions completed; the third is cut off.
|
||||||
|
// Salvage keeps the two that completed instead of failing outright.
|
||||||
|
name: "truncated mid-array salvages completed objects",
|
||||||
|
raw: `{"suggestions":[{"original":"I has","replacement":"I have","explanation":"subject-verb agreement","type":"grammar"},{"original":"a apple","replacement":"an apple","explanation":"use an before a vowel","type":"grammar"},{"original":"she relised","replacement":"she real`,
|
||||||
|
want: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// A truncated array where even the first object is incomplete has
|
||||||
|
// nothing to salvage → still an error (the caller releases + retries).
|
||||||
|
name: "truncated before any object closes",
|
||||||
|
raw: `{"suggestions":[{"original":"It was a thursdy morning when Clara`,
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
@@ -65,16 +99,31 @@ func TestParseCheckpoint(t *testing.T) {
|
|||||||
func TestRateLimiter(t *testing.T) {
|
func TestRateLimiter(t *testing.T) {
|
||||||
rl := NewRateLimiter(30 * time.Second)
|
rl := NewRateLimiter(30 * time.Second)
|
||||||
|
|
||||||
if ok, _ := rl.Allow("doc1"); !ok {
|
ok, _, at := rl.Allow("doc1")
|
||||||
|
if !ok {
|
||||||
t.Fatal("first call should be allowed")
|
t.Fatal("first call should be allowed")
|
||||||
}
|
}
|
||||||
if ok, retry := rl.Allow("doc1"); ok || retry <= 0 {
|
if ok, retry, _ := rl.Allow("doc1"); ok || retry <= 0 {
|
||||||
t.Fatalf("immediate second call should be throttled, got ok=%v retry=%v", ok, retry)
|
t.Fatalf("immediate second call should be throttled, got ok=%v retry=%v", ok, retry)
|
||||||
}
|
}
|
||||||
// A different document is independent.
|
// A different document is independent.
|
||||||
if ok, _ := rl.Allow("doc2"); !ok {
|
if ok, _, _ := rl.Allow("doc2"); !ok {
|
||||||
t.Fatal("different doc should be allowed")
|
t.Fatal("different doc should be allowed")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Releasing doc1's slot (as a failed pass does) lets the next check re-run
|
||||||
|
// immediately instead of waiting out the interval.
|
||||||
|
rl.Release("doc1", at)
|
||||||
|
if ok, _, _ := rl.Allow("doc1"); !ok {
|
||||||
|
t.Fatal("after Release the next call should be allowed again")
|
||||||
|
}
|
||||||
|
// Release only rolls back its own slot: a stale timestamp must not evict the
|
||||||
|
// slot a newer Allow holds (so a late failure can't cancel a fresh in-flight
|
||||||
|
// check). doc2 still holds its slot from above; a zero-time Release is a no-op.
|
||||||
|
rl.Release("doc2", time.Time{})
|
||||||
|
if ok, _, _ := rl.Allow("doc2"); ok {
|
||||||
|
t.Fatal("stale Release must not free doc2's current slot")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTruncateDoc(t *testing.T) {
|
func TestTruncateDoc(t *testing.T) {
|
||||||
|
|||||||
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.
|
||||||
@@ -165,3 +213,24 @@ func RewriteMessages(text, style string) []Message {
|
|||||||
{Role: "user", Content: text},
|
{Role: "user", Content: text},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// translateSystemPrompt drives the explanation translator: it renders a
|
||||||
|
// suggestion's English explanation into Simplified Chinese so an ESL reader sees
|
||||||
|
// the "why" in her first language. Strict about returning ONLY the translation
|
||||||
|
// (no quotes, no pinyin, no English echo) so it can drop straight into the chat
|
||||||
|
// bubble. Kept warm and plain — these are short, friendly one-liners.
|
||||||
|
const translateSystemPrompt = `You are Petal, a warm writing assistant. Translate the English text the user ` +
|
||||||
|
`sends into natural, friendly Simplified Chinese (Mandarin). It is a short explanation of a writing ` +
|
||||||
|
`suggestion, written for a native Chinese speaker learning English.
|
||||||
|
|
||||||
|
Respond with ONLY the Simplified Chinese translation. No quotation marks, no pinyin, no English, no preamble — ` +
|
||||||
|
`just the translated sentence.`
|
||||||
|
|
||||||
|
// TranslateMessages builds the message array for translating one short English
|
||||||
|
// explanation into Simplified Chinese.
|
||||||
|
func TranslateMessages(text string) []Message {
|
||||||
|
return []Message{
|
||||||
|
{Role: "system", Content: translateSystemPrompt},
|
||||||
|
{Role: "user", Content: text},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
23
internal/llm/translate.go
Normal file
23
internal/llm/translate.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package llm
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RunTranslate renders a short English explanation into Simplified Chinese. It
|
||||||
|
// is a one-shot Complete (the result seeds the Ask Petal bubble), kept at a low
|
||||||
|
// temperature so the translation is faithful rather than creative. Output is
|
||||||
|
// trimmed of any stray surrounding quotes the model may add.
|
||||||
|
func RunTranslate(ctx context.Context, client LLMClient, text string) (string, error) {
|
||||||
|
out, err := client.Complete(ctx, CompletionRequest{
|
||||||
|
Messages: TranslateMessages(text),
|
||||||
|
MaxTokens: 512,
|
||||||
|
Temperature: 0.2,
|
||||||
|
TopP: 0.9,
|
||||||
|
RepetitionPenalty: 1.1,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return cleanRewrite(out), nil
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
"gitea.parodia.dev/drwily/petal/internal/llm"
|
"gitea.parodia.dev/drwily/petal/internal/llm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -29,7 +30,7 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var body chatRequest
|
var body chatRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
errorJSON(w, http.StatusBadRequest, "invalid request body")
|
httputil.ErrorJSON(w, http.StatusBadRequest, "invalid request body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,8 +38,8 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
|
|||||||
// scoped to the local user so a stray id can't read another user's doc.
|
// scoped to the local user so a stray id can't read another user's doc.
|
||||||
var (
|
var (
|
||||||
original, replacement, explanation, typ string
|
original, replacement, explanation, typ string
|
||||||
fromPos int
|
fromPos int
|
||||||
contentText string
|
contentText string
|
||||||
)
|
)
|
||||||
err := h.DB.QueryRow(
|
err := h.DB.QueryRow(
|
||||||
`SELECT s.original, s.replacement, s.explanation, s.type, s.from_pos, d.content_text
|
`SELECT s.original, s.replacement, s.explanation, s.type, s.from_pos, d.content_text
|
||||||
@@ -48,11 +49,11 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
|
|||||||
sugID, db.LocalUserID,
|
sugID, db.LocalUserID,
|
||||||
).Scan(&original, &replacement, &explanation, &typ, &fromPos, &contentText)
|
).Scan(&original, &replacement, &explanation, &typ, &fromPos, &contentText)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
errorJSON(w, http.StatusNotFound, "suggestion not found")
|
httputil.ErrorJSON(w, http.StatusNotFound, "suggestion not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,7 +64,7 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
|
|||||||
// Flush through; bail with a plain error if somehow they don't.
|
// Flush through; bail with a plain error if somehow they don't.
|
||||||
flusher, ok := w.(http.Flusher)
|
flusher, ok := w.(http.Flusher)
|
||||||
if !ok {
|
if !ok {
|
||||||
serverError(w, errors.New("streaming unsupported"))
|
httputil.ServerError(w, errors.New("streaming unsupported"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,7 +72,7 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
// The stream never opened (e.g. LLM unreachable) — a normal JSON error is
|
// The stream never opened (e.g. LLM unreachable) — a normal JSON error is
|
||||||
// still appropriate since we haven't written SSE headers yet.
|
// still appropriate since we haven't written SSE headers yet.
|
||||||
errorJSON(w, http.StatusBadGateway, "chat failed: "+err.Error())
|
httputil.ErrorJSON(w, http.StatusBadGateway, "chat failed: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,12 +10,14 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
"gitea.parodia.dev/drwily/petal/internal/llm"
|
"gitea.parodia.dev/drwily/petal/internal/llm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -23,19 +25,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),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,7 +48,9 @@ func New(database *db.DB, client llm.LLMClient) *Handler {
|
|||||||
// the existing /api/docs router so they share its base path.
|
// the existing /api/docs router so they share its base path.
|
||||||
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}/mechanics", h.mechanics)
|
||||||
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)
|
||||||
}
|
}
|
||||||
@@ -55,20 +62,136 @@ func (h *Handler) Routes() chi.Router {
|
|||||||
r.Post("/{id}/accept", h.accept)
|
r.Post("/{id}/accept", h.accept)
|
||||||
r.Post("/{id}/dismiss", h.dismiss)
|
r.Post("/{id}/dismiss", h.dismiss)
|
||||||
r.Post("/{id}/chat", h.chat)
|
r.Post("/{id}/chat", h.chat)
|
||||||
|
r.Post("/{id}/translate", h.translate)
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
// check runs a grammar checkpoint over the document. Fast, typing-cadence pass.
|
// check runs a grammar checkpoint over the document. Fast, typing-cadence pass.
|
||||||
|
// The deterministic mechanics family is owned by a separate pass (see mechanics),
|
||||||
|
// detected client-side; a grammar checkpoint leaves those flags untouched.
|
||||||
func (h *Handler) check(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) check(w http.ResponseWriter, r *http.Request) {
|
||||||
h.runPass(w, r, h.Limit, llm.RunCheckpoint, grammarScope)
|
h.runPass(w, r, h.Limit, llm.RunCheckpoint, grammarScope)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mechanicsFinding is one deterministic, rule-based fix detected client-side (see
|
||||||
|
// web Companion/prose.ts). Detection lives in the frontend — the same rules that
|
||||||
|
// power the companion's prose notes — so the server only persists these; it does
|
||||||
|
// not compute them. Offsets are exact plaintext spans from the detector.
|
||||||
|
type mechanicsFinding struct {
|
||||||
|
From int `json:"from"`
|
||||||
|
To int `json:"to"`
|
||||||
|
Original string `json:"original"`
|
||||||
|
Replacement string `json:"replacement"`
|
||||||
|
Explanation string `json:"explanation"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxMechanicsFindings caps a single submission so a runaway client can't flood
|
||||||
|
// the table; far above any realistic count for one document.
|
||||||
|
const maxMechanicsFindings = 500
|
||||||
|
|
||||||
|
// mechanics persists the client-detected deterministic fixes as the 'mechanics'
|
||||||
|
// family and returns the document's unified pending set. Free and not rate-
|
||||||
|
// limited — it runs alongside the grammar checkpoint. It mirrors a single LLM
|
||||||
|
// family: it replaces only the pending mechanics rows, honours actioned-
|
||||||
|
// suppression, and (unlike the LLM passes) keeps the detector's exact offsets
|
||||||
|
// rather than re-locating by string, which matters when the same word repeats.
|
||||||
|
func (h *Handler) mechanics(w http.ResponseWriter, r *http.Request) {
|
||||||
|
docID := chi.URLParam(r, "id")
|
||||||
|
|
||||||
|
// Confirm the document exists (and is the local user's) for clean 404s.
|
||||||
|
var exists bool
|
||||||
|
err := h.DB.QueryRow(
|
||||||
|
`SELECT EXISTS(SELECT 1 FROM documents WHERE id = ? AND user_id = ?)`,
|
||||||
|
docID, db.LocalUserID,
|
||||||
|
).Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
httputil.ErrorJSON(w, http.StatusNotFound, "document not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
Findings []mechanicsFinding `json:"findings"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
|
||||||
|
httputil.BadRequest(w, "invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(body.Findings) > maxMechanicsFindings {
|
||||||
|
body.Findings = body.Findings[:maxMechanicsFindings]
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.replaceMechanics(docID, body.Findings); err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := h.fetchPending(docID)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
httputil.WriteJSON(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// replaceMechanics swaps the document's pending mechanics rows for the supplied
|
||||||
|
// findings in one transaction, leaving the LLM families and actioned rows
|
||||||
|
// untouched. Findings the user already accepted or dismissed are suppressed (the
|
||||||
|
// detector has no memory between runs), and malformed spans are skipped.
|
||||||
|
func (h *Handler) replaceMechanics(docID string, findings []mechanicsFinding) error {
|
||||||
|
tx, err := h.DB.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
if _, err := tx.Exec(
|
||||||
|
`DELETE FROM suggestions WHERE doc_id = ? AND status = ? AND type = ?`,
|
||||||
|
docID, db.SuggestionStatusPending, db.SuggestionTypeMechanics,
|
||||||
|
); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
sup, err := buildSuppressor(tx, docID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, f := range findings {
|
||||||
|
if f.From < 0 || f.To <= f.From || strings.TrimSpace(f.Original) == "" {
|
||||||
|
continue // malformed span — the client re-anchors by string anyway
|
||||||
|
}
|
||||||
|
if sup.suppressed(f.Original, f.Replacement) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(
|
||||||
|
`INSERT INTO suggestions (doc_id, from_pos, to_pos, original, replacement, explanation, type)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
docID, f.From, f.To, f.Original, f.Replacement, f.Explanation, db.SuggestionTypeMechanics,
|
||||||
|
); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
// voice runs a Tier-1 voice-consistency pass over the whole document. Slow,
|
// voice runs a Tier-1 voice-consistency pass over the whole document. Slow,
|
||||||
// explicit-action pass; replaces only the pending voice flags.
|
// explicit-action pass; replaces only the pending voice flags.
|
||||||
func (h *Handler) voice(w http.ResponseWriter, r *http.Request) {
|
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).
|
||||||
@@ -87,40 +210,45 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R
|
|||||||
docID, db.LocalUserID,
|
docID, db.LocalUserID,
|
||||||
).Scan(&contentText, &tone)
|
).Scan(&contentText, &tone)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
errorJSON(w, http.StatusNotFound, "document not found")
|
httputil.ErrorJSON(w, http.StatusNotFound, "document not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Nothing to analyze on an empty document — skip the LLM round-trip.
|
// Nothing to analyze on an empty document — skip the LLM round-trip.
|
||||||
if strings.TrimSpace(contentText) == "" {
|
if strings.TrimSpace(contentText) == "" {
|
||||||
writeJSON(w, http.StatusOK, []db.Suggestion{})
|
httputil.WriteJSON(w, http.StatusOK, []db.Suggestion{})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if ok, _ := limiter.Allow(docID); !ok {
|
ok, _, slotAt := limiter.Allow(docID)
|
||||||
|
if !ok {
|
||||||
// Throttled: return the existing pending set unchanged rather than an
|
// Throttled: return the existing pending set unchanged rather than an
|
||||||
// error, so the frontend keeps showing current suggestions.
|
// error, so the frontend keeps showing current suggestions.
|
||||||
existing, err := h.fetchPending(docID)
|
existing, err := h.fetchPending(docID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, existing)
|
httputil.WriteJSON(w, http.StatusOK, existing)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
raw, err := run(r.Context(), h.Client, contentText, tone)
|
raw, err := run(r.Context(), h.Client, contentText, tone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errorJSON(w, http.StatusBadGateway, "llm pass failed: "+err.Error())
|
// Allow ran before the model call, so a failed pass would otherwise hold
|
||||||
|
// the per-document slot for the full interval — stranding the frontend's
|
||||||
|
// auto-retry on the throttle path. Release it so a retry can re-run.
|
||||||
|
limiter.Release(docID, slotAt)
|
||||||
|
httputil.ErrorJSON(w, http.StatusBadGateway, "llm pass failed: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.replacePending(docID, contentText, raw, scope); err != nil {
|
if err := h.replacePending(docID, contentText, raw, scope); err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,10 +257,10 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R
|
|||||||
// throttle path above stays consistent with the success path.
|
// throttle path above stays consistent with the success path.
|
||||||
out, err := h.fetchPending(docID)
|
out, err := h.fetchPending(docID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, out)
|
httputil.WriteJSON(w, http.StatusOK, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
// pendingScope describes how one LLM pass touches the shared suggestions table:
|
// pendingScope describes how one LLM pass touches the shared suggestions table:
|
||||||
@@ -145,15 +273,28 @@ 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 other self-owned families (voice, collocation, mechanics), which run on
|
||||||
|
// their own cadence/pass and must survive a grammar checkpoint. Notably the
|
||||||
|
// deterministic mechanics pass writes its rows in the same /check request just
|
||||||
|
// before this DELETE runs, so excluding it here is what keeps them alive.
|
||||||
|
grammarScope = pendingScope{deleteWhere: "type NOT IN ('voice','collocation','mechanics')", 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
|
||||||
// fresh batch in a single transaction. Accepted/rejected suggestions and the
|
// fresh batch in a single transaction. Accepted/rejected suggestions and the
|
||||||
// other family's pending rows are left untouched.
|
// other family's pending rows are left untouched.
|
||||||
|
//
|
||||||
|
// Suggestions touching a sentence the user already settled are suppressed from
|
||||||
|
// the fresh batch (see suppressor): not just the identical edit re-proposed, but
|
||||||
|
// reversals and re-polishing of the model's own just-accepted output — the
|
||||||
|
// "fickle, keeps going back and forth on a few sentences" behavior. The model has
|
||||||
|
// no memory between passes, so without this it re-opens resolved sentences every
|
||||||
|
// checkpoint.
|
||||||
func (h *Handler) replacePending(docID, contentText string, raw []llm.RawSuggestion, scope pendingScope) error {
|
func (h *Handler) replacePending(docID, contentText string, raw []llm.RawSuggestion, scope pendingScope) error {
|
||||||
tx, err := h.DB.Begin()
|
tx, err := h.DB.Begin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -168,7 +309,15 @@ func (h *Handler) replacePending(docID, contentText string, raw []llm.RawSuggest
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sup, err := buildSuppressor(tx, docID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
for _, s := range raw {
|
for _, s := range raw {
|
||||||
|
if sup.suppressed(s.Original, s.Replacement) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
typ := scope.forceType
|
typ := scope.forceType
|
||||||
if typ == "" {
|
if typ == "" {
|
||||||
typ = normalizeType(s.Type)
|
typ = normalizeType(s.Type)
|
||||||
@@ -186,15 +335,142 @@ func (h *Handler) replacePending(docID, contentText string, raw []llm.RawSuggest
|
|||||||
return tx.Commit()
|
return tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dedupQuoteReplacer folds every straight/curly single- and double-quote variant
|
||||||
|
// (and backtick/acute accent) onto one canonical character. The editor and the
|
||||||
|
// model both rewrite quotes between passes — a sentence accepted with "…" comes
|
||||||
|
// back flagged with '…' — so without folding, byte-identical text reads as a
|
||||||
|
// different edit and the suppression below misses it. (This normalization is for
|
||||||
|
// dedup ONLY; the frontend still anchors on the verbatim `original`.)
|
||||||
|
var dedupQuoteReplacer = strings.NewReplacer(
|
||||||
|
"‘", "'", "’", "'", "‚", "'", "‛", "'", // single curly
|
||||||
|
"“", "'", "”", "'", "„", "'", "″", "'", // double curly
|
||||||
|
"\"", "'", "`", "'", "´", "'", // straight double, backtick, acute
|
||||||
|
)
|
||||||
|
|
||||||
|
// normalizeForDedup canonicalizes a string for suppression comparisons: quotes
|
||||||
|
// folded (above) and runs of whitespace collapsed to single spaces (so a reflowed
|
||||||
|
// paragraph still matches). Used only to decide what to suppress, never to alter
|
||||||
|
// stored or rendered text.
|
||||||
|
func normalizeForDedup(s string) string {
|
||||||
|
return strings.Join(strings.Fields(dedupQuoteReplacer.Replace(s)), " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// suppressor decides which fresh suggestions to drop because the user has already
|
||||||
|
// settled the sentence they touch. The model has no memory between passes, so on
|
||||||
|
// every checkpoint it re-examines the current text and proposes edits — including
|
||||||
|
// ones that re-open a sentence the user already resolved. Three families of those
|
||||||
|
// are suppressed (all compared under normalizeForDedup):
|
||||||
|
//
|
||||||
|
// - pairs: the identical edit, re-proposed verbatim (the original "accept it,
|
||||||
|
// then it nags again" case; also covers a silent no-op accept that left the
|
||||||
|
// text unchanged).
|
||||||
|
// - actionedOrig: any edit whose original is a span the user already accepted or
|
||||||
|
// dismissed an edit on — "you already decided about this exact sentence."
|
||||||
|
// - acceptedRepl: any edit whose original is text the user accepted AS a
|
||||||
|
// replacement — i.e. the model re-touching its own just-accepted output, which
|
||||||
|
// is how the reversals and endless re-polishing arise (accept "due to the
|
||||||
|
// rain", next pass proposes changing "due to the rain" back). Guarded to
|
||||||
|
// multi-word spans so word-level fixes aren't swept up as collateral.
|
||||||
|
// - acceptedReplList holds the same accepted replacements for a containment
|
||||||
|
// check: the model evades the exact acceptedRepl match by re-flagging a
|
||||||
|
// *sub-clause* of an accepted sentence (flag "she was…due to the rain" instead
|
||||||
|
// of the whole sentence). When one of the new original / an accepted
|
||||||
|
// replacement contains the other and the shorter side is substantial
|
||||||
|
// (>= minContainWords words), it's the same settled span and is dropped.
|
||||||
|
type suppressor struct {
|
||||||
|
pairs map[string]struct{}
|
||||||
|
actionedOrig map[string]struct{}
|
||||||
|
acceptedRepl map[string]struct{}
|
||||||
|
acceptedReplList []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// minContainWords is the floor for the containment check: the shorter of the two
|
||||||
|
// spans must be at least this many words before a substring relationship counts
|
||||||
|
// as "the same settled text." High enough that an incidental common phrase ("the
|
||||||
|
// rain") can't suppress an unrelated sentence, low enough to catch a re-flagged
|
||||||
|
// clause.
|
||||||
|
const minContainWords = 4
|
||||||
|
|
||||||
|
// suppressed reports whether a fresh suggestion should be dropped as already
|
||||||
|
// settled. An empty original is never suppressed here (it can't anchor anyway and
|
||||||
|
// is dropped upstream).
|
||||||
|
func (s suppressor) suppressed(original, replacement string) bool {
|
||||||
|
o := normalizeForDedup(original)
|
||||||
|
if o == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if _, ok := s.pairs[o+"\x00"+normalizeForDedup(replacement)]; ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if _, ok := s.actionedOrig[o]; ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if strings.ContainsRune(o, ' ') {
|
||||||
|
if _, ok := s.acceptedRepl[o]; ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Containment: the model re-flagged a sub-clause of (or a window around) an
|
||||||
|
// accepted span. Suppress when one contains the other and the shorter side is
|
||||||
|
// a substantial multi-word run.
|
||||||
|
for _, r := range s.acceptedReplList {
|
||||||
|
shorter, longer := o, r
|
||||||
|
if len(r) < len(o) {
|
||||||
|
shorter, longer = r, o
|
||||||
|
}
|
||||||
|
if len(strings.Fields(shorter)) >= minContainWords && strings.Contains(longer, shorter) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildSuppressor loads the document's accepted/rejected edits and indexes them
|
||||||
|
// into the three suppression families described on suppressor.
|
||||||
|
func buildSuppressor(tx *sql.Tx, docID string) (suppressor, error) {
|
||||||
|
rows, err := tx.Query(
|
||||||
|
`SELECT original, replacement, status FROM suggestions
|
||||||
|
WHERE doc_id = ? AND status IN (?, ?)`,
|
||||||
|
docID, db.SuggestionStatusAccepted, db.SuggestionStatusRejected,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return suppressor{}, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
s := suppressor{
|
||||||
|
pairs: make(map[string]struct{}),
|
||||||
|
actionedOrig: make(map[string]struct{}),
|
||||||
|
acceptedRepl: make(map[string]struct{}),
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
var original, replacement, status string
|
||||||
|
if err := rows.Scan(&original, &replacement, &status); err != nil {
|
||||||
|
return suppressor{}, err
|
||||||
|
}
|
||||||
|
o := normalizeForDedup(original)
|
||||||
|
r := normalizeForDedup(replacement)
|
||||||
|
s.pairs[o+"\x00"+r] = struct{}{}
|
||||||
|
if o != "" {
|
||||||
|
s.actionedOrig[o] = struct{}{}
|
||||||
|
}
|
||||||
|
if status == db.SuggestionStatusAccepted && r != "" {
|
||||||
|
s.acceptedRepl[r] = struct{}{}
|
||||||
|
s.acceptedReplList = append(s.acceptedReplList, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
// listForDoc returns the document's current pending suggestions (used when the
|
// listForDoc returns the document's current pending suggestions (used when the
|
||||||
// editor loads a document, before any new checkpoint fires).
|
// editor loads a document, before any new checkpoint fires).
|
||||||
func (h *Handler) listForDoc(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) listForDoc(w http.ResponseWriter, r *http.Request) {
|
||||||
out, err := h.fetchPending(chi.URLParam(r, "id"))
|
out, err := h.fetchPending(chi.URLParam(r, "id"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, out)
|
httputil.WriteJSON(w, http.StatusOK, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) fetchPending(docID string) ([]db.Suggestion, error) {
|
func (h *Handler) fetchPending(docID string) ([]db.Suggestion, error) {
|
||||||
@@ -221,7 +497,51 @@ func (h *Handler) fetchPending(docID string) ([]db.Suggestion, error) {
|
|||||||
}
|
}
|
||||||
out = append(out, s)
|
out = append(out, s)
|
||||||
}
|
}
|
||||||
return out, rows.Err()
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return dedupeSpans(out), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// dedupeSpans resolves collisions between the deterministic mechanics family and
|
||||||
|
// the LLM families: when a mechanics finding and an LLM suggestion fight over the
|
||||||
|
// same characters, mechanics wins and the LLM card is dropped. Its span is exact
|
||||||
|
// (the detector matched it), whereas the LLM positions are only advisory
|
||||||
|
// (re-anchored by string at render), so the precise fix should own the span.
|
||||||
|
//
|
||||||
|
// This deliberately does NOT dedupe LLM-vs-LLM overlaps: voice (awareness-only,
|
||||||
|
// no replacement) and collocation legitimately co-occupy the same span, and that
|
||||||
|
// is intended. Suggestions that never anchored (from_pos < 0) occupy no real span
|
||||||
|
// and are always kept.
|
||||||
|
func dedupeSpans(in []db.Suggestion) []db.Suggestion {
|
||||||
|
type span struct{ from, to int }
|
||||||
|
var claimed []span
|
||||||
|
for _, s := range in {
|
||||||
|
if s.Type == db.SuggestionTypeMechanics && s.FromPos >= 0 {
|
||||||
|
claimed = append(claimed, span{s.FromPos, s.ToPos})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(claimed) == 0 {
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
|
||||||
|
out := make([]db.Suggestion, 0, len(in))
|
||||||
|
for _, s := range in {
|
||||||
|
if s.Type != db.SuggestionTypeMechanics && s.FromPos >= 0 {
|
||||||
|
overlaps := false
|
||||||
|
for _, sp := range claimed {
|
||||||
|
if s.FromPos < sp.to && sp.from < s.ToPos {
|
||||||
|
overlaps = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if overlaps {
|
||||||
|
continue // an exact mechanics fix owns these characters
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, s)
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// accept marks a suggestion accepted (the client applies the replacement text).
|
// accept marks a suggestion accepted (the client applies the replacement text).
|
||||||
@@ -240,11 +560,11 @@ func (h *Handler) setStatus(w http.ResponseWriter, r *http.Request, status strin
|
|||||||
status, chi.URLParam(r, "id"), db.SuggestionStatusPending,
|
status, chi.URLParam(r, "id"), db.SuggestionStatusPending,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if n, _ := res.RowsAffected(); n == 0 {
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
errorJSON(w, http.StatusNotFound, "pending suggestion not found")
|
httputil.ErrorJSON(w, http.StatusNotFound, "pending suggestion not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
@@ -265,25 +585,9 @@ 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 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())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -127,6 +127,86 @@ func TestCheckpointFlow(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestResolvedSuggestionsNotReproposed proves a checkpoint won't re-nag a
|
||||||
|
// sentence the user already accepted or dismissed: the model returns the same
|
||||||
|
// raw batch on the next pass (it has no memory), but the resolved edits are
|
||||||
|
// suppressed. This is the "accept it, then it nags again moments later" bug.
|
||||||
|
func TestResolvedSuggestionsNotReproposed(t *testing.T) {
|
||||||
|
client := &stubClient{response: `{"suggestions":[
|
||||||
|
{"original":"I has","replacement":"I have","explanation":"subject-verb agreement","type":"grammar"},
|
||||||
|
{"original":"two apple","replacement":"two apples","explanation":"plural noun","type":"grammar"}
|
||||||
|
]}`}
|
||||||
|
srv, docID, h := newTestServer(t, client)
|
||||||
|
// Zero the checkpoint floor so the second pass runs instead of being throttled.
|
||||||
|
h.Limit = llm.NewRateLimiter(0)
|
||||||
|
|
||||||
|
rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/check", "")
|
||||||
|
var got []db.Suggestion
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &got)
|
||||||
|
if len(got) != 2 {
|
||||||
|
t.Fatalf("first pass: want 2, got %d", len(got))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accept one, dismiss the other.
|
||||||
|
do(t, srv, http.MethodPost, "/suggestions/"+got[0].ID+"/accept", "")
|
||||||
|
do(t, srv, http.MethodPost, "/suggestions/"+got[1].ID+"/dismiss", "")
|
||||||
|
|
||||||
|
// Second checkpoint returns the identical raw batch — both must be suppressed.
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
var again []db.Suggestion
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &again); err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
if len(again) != 0 {
|
||||||
|
t.Fatalf("resolved suggestions should not be re-proposed, got %d: %+v", len(again), again)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFickleEditsSuppressed proves the suppressor kills the "keeps going back and
|
||||||
|
// forth on a few sentences" behavior seen live on the Missing Key doc: a later
|
||||||
|
// pass that (a) reverses an edit the user just accepted — even with the editor's
|
||||||
|
// double→single quote churn that defeats a byte-exact match — or (b) re-polishes
|
||||||
|
// the model's own accepted output. A genuinely new edit on a fresh sentence still
|
||||||
|
// survives.
|
||||||
|
func TestFickleEditsSuppressed(t *testing.T) {
|
||||||
|
client := &stubClient{response: `{"suggestions":[
|
||||||
|
{"original":"He left \"early,\" because of the rain.","replacement":"He left \"early,\" due to the rain.","explanation":"smoother","type":"phrasing"},
|
||||||
|
{"original":"The cat always have a calm face.","replacement":"The cat always has a calm face.","explanation":"agreement","type":"grammar"}
|
||||||
|
]}`}
|
||||||
|
srv, docID, h := newTestServer(t, client)
|
||||||
|
h.Limit = llm.NewRateLimiter(0)
|
||||||
|
|
||||||
|
rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/check", "")
|
||||||
|
var got []db.Suggestion
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &got)
|
||||||
|
if len(got) != 2 {
|
||||||
|
t.Fatalf("first pass: want 2, got %d", len(got))
|
||||||
|
}
|
||||||
|
for _, s := range got {
|
||||||
|
do(t, srv, http.MethodPost, "/suggestions/"+s.ID+"/accept", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reversal of the first accept (note the " → ' quote churn) and a re-polish of
|
||||||
|
// the second accept must both be dropped; only the unrelated edit survives.
|
||||||
|
client.response = `{"suggestions":[
|
||||||
|
{"original":"He left 'early,' due to the rain.","replacement":"He left 'early,' because of the rain.","explanation":"reverts the accepted edit","type":"phrasing"},
|
||||||
|
{"original":"The cat always has a calm face.","replacement":"The cat always seems to have a calm face.","explanation":"re-polishes accepted output","type":"phrasing"},
|
||||||
|
{"original":"due to the rain","replacement":"because of the rain","explanation":"sub-clause reversal of the accepted span","type":"phrasing"},
|
||||||
|
{"original":"She drived home.","replacement":"She drove home.","explanation":"past tense","type":"grammar"}
|
||||||
|
]}`
|
||||||
|
rec = do(t, srv, http.MethodPost, "/docs/"+docID+"/check", "")
|
||||||
|
var again []db.Suggestion
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &again); err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
if len(again) != 1 || again[0].Original != "She drived home." {
|
||||||
|
t.Fatalf("want only the new edit to survive, got %d: %+v", len(again), again)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestVoicePassCoexists proves the voice pass and the grammar checkpoint own
|
// TestVoicePassCoexists proves the voice pass and the grammar checkpoint own
|
||||||
// disjoint pending families: running one never wipes the other's flags, and
|
// disjoint pending families: running one never wipes the other's flags, and
|
||||||
// each endpoint returns the unified pending set.
|
// each endpoint returns the unified pending set.
|
||||||
@@ -189,6 +269,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
|
||||||
@@ -219,3 +358,116 @@ func TestCheckpointRateLimit(t *testing.T) {
|
|||||||
t.Fatalf("rate limit should suppress the second model call, got %d calls", client.calls)
|
t.Fatalf("rate limit should suppress the second model call, got %d calls", client.calls)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// postMechanics submits a deterministic-findings batch (as the client's prose
|
||||||
|
// detector would) and returns the unified pending set.
|
||||||
|
func postMechanics(t *testing.T, srv http.Handler, docID, findingsJSON string) []db.Suggestion {
|
||||||
|
t.Helper()
|
||||||
|
rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/mechanics", `{"findings":`+findingsJSON+`}`)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("mechanics: 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)
|
||||||
|
}
|
||||||
|
return got
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMechanicsPersistsFindings proves the endpoint persists client-detected
|
||||||
|
// findings as a 'mechanics' family with the exact offsets the client supplied,
|
||||||
|
// and that a later grammar checkpoint leaves them untouched (own family).
|
||||||
|
func TestMechanicsPersistsFindings(t *testing.T) {
|
||||||
|
client := &stubClient{response: `{"suggestions":[]}`}
|
||||||
|
srv, docID, _ := newTestServer(t, client)
|
||||||
|
|
||||||
|
got := postMechanics(t, srv, docID, `[
|
||||||
|
{"from":0,"to":1,"original":"i","replacement":"I","explanation":"capitalize I"},
|
||||||
|
{"from":6,"to":13,"original":"the the","replacement":"the","explanation":"doubled word"}
|
||||||
|
]`)
|
||||||
|
var mech []db.Suggestion
|
||||||
|
for _, s := range got {
|
||||||
|
if s.Type == db.SuggestionTypeMechanics {
|
||||||
|
mech = append(mech, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(mech) != 2 {
|
||||||
|
t.Fatalf("want 2 mechanics findings, got %d: %+v", len(mech), got)
|
||||||
|
}
|
||||||
|
// The client's exact offsets are preserved verbatim.
|
||||||
|
for _, s := range mech {
|
||||||
|
if s.Original == "the the" && (s.FromPos != 6 || s.ToPos != 13) {
|
||||||
|
t.Errorf("offsets not preserved: %+v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A grammar checkpoint must not wipe the mechanics family.
|
||||||
|
rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/check", "")
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("check: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
var after []db.Suggestion
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &after)
|
||||||
|
count := 0
|
||||||
|
for _, s := range after {
|
||||||
|
if s.Type == db.SuggestionTypeMechanics {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count != 2 {
|
||||||
|
t.Fatalf("grammar checkpoint disturbed the mechanics family: got %d, want 2", count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMechanicsWinsSpanCollision proves that when a mechanics finding and an LLM
|
||||||
|
// grammar suggestion claim overlapping characters, the LLM card is dropped from
|
||||||
|
// the response and the exact mechanics fix owns the span.
|
||||||
|
func TestMechanicsWinsSpanCollision(t *testing.T) {
|
||||||
|
// LLM grammar suggestion covers "the the cat", overlapping the mechanics
|
||||||
|
// "the the" finding at [0,7].
|
||||||
|
client := &stubClient{response: `{"suggestions":[
|
||||||
|
{"original":"the the cat","replacement":"the cat","explanation":"wordy","type":"grammar"}
|
||||||
|
]}`}
|
||||||
|
srv, docID, h := newTestServer(t, client)
|
||||||
|
if _, err := h.DB.Exec(`UPDATE documents SET content_text = ? WHERE id = ?`, "the the cat sat", docID); err != nil {
|
||||||
|
t.Fatalf("set content: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist the mechanics finding, then run the grammar pass.
|
||||||
|
postMechanics(t, srv, docID, `[{"from":0,"to":7,"original":"the the","replacement":"the","explanation":"doubled word"}]`)
|
||||||
|
rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/check", "")
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("check: 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)
|
||||||
|
}
|
||||||
|
for _, s := range got {
|
||||||
|
if s.Type == db.SuggestionTypeGrammar {
|
||||||
|
t.Fatalf("overlapping grammar card should have been dropped in favor of mechanics, got %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(got) != 1 || got[0].Type != db.SuggestionTypeMechanics {
|
||||||
|
t.Fatalf("want sole mechanics finding, got %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMechanicsActionedSuppression proves a dismissed mechanics fix is not
|
||||||
|
// re-proposed on the next submission of the same finding.
|
||||||
|
func TestMechanicsActionedSuppression(t *testing.T) {
|
||||||
|
client := &stubClient{response: `{"suggestions":[]}`}
|
||||||
|
srv, docID, _ := newTestServer(t, client)
|
||||||
|
|
||||||
|
findings := `[{"from":6,"to":13,"original":"the the","replacement":"the","explanation":"doubled word"}]`
|
||||||
|
got := postMechanics(t, srv, docID, findings)
|
||||||
|
if len(got) != 1 {
|
||||||
|
t.Fatalf("want 1 finding, got %+v", got)
|
||||||
|
}
|
||||||
|
// Dismiss it, then resubmit the same finding — it must stay suppressed.
|
||||||
|
do(t, srv, http.MethodPost, "/suggestions/"+got[0].ID+"/dismiss", "")
|
||||||
|
again := postMechanics(t, srv, docID, findings)
|
||||||
|
if len(again) != 0 {
|
||||||
|
t.Fatalf("dismissed mechanics fix should not reappear, got %+v", again)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"gitea.parodia.dev/drwily/petal/internal/db"
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
"gitea.parodia.dev/drwily/petal/internal/llm"
|
"gitea.parodia.dev/drwily/petal/internal/llm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -36,17 +37,17 @@ func (h *Handler) rewrite(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var body rewriteRequest
|
var body rewriteRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
errorJSON(w, http.StatusBadRequest, "invalid request body")
|
httputil.ErrorJSON(w, http.StatusBadRequest, "invalid request body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
text := strings.TrimSpace(body.Text)
|
text := strings.TrimSpace(body.Text)
|
||||||
if text == "" {
|
if text == "" {
|
||||||
errorJSON(w, http.StatusBadRequest, "no text to rewrite")
|
httputil.ErrorJSON(w, http.StatusBadRequest, "no text to rewrite")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if len([]rune(text)) > llm.RewriteMaxRunes {
|
if len([]rune(text)) > llm.RewriteMaxRunes {
|
||||||
errorJSON(w, http.StatusBadRequest, "selection too long to rewrite")
|
httputil.ErrorJSON(w, http.StatusBadRequest, "selection too long to rewrite")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,19 +59,19 @@ func (h *Handler) rewrite(w http.ResponseWriter, r *http.Request) {
|
|||||||
docID, db.LocalUserID,
|
docID, db.LocalUserID,
|
||||||
).Scan(&exists)
|
).Scan(&exists)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
errorJSON(w, http.StatusNotFound, "document not found")
|
httputil.ErrorJSON(w, http.StatusNotFound, "document not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
serverError(w, err)
|
httputil.ServerError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
out, err := llm.RunRewrite(r.Context(), h.Client, text, body.Style)
|
out, err := llm.RunRewrite(r.Context(), h.Client, text, body.Style)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errorJSON(w, http.StatusBadGateway, "rewrite failed: "+err.Error())
|
httputil.ErrorJSON(w, http.StatusBadGateway, "rewrite failed: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
writeJSON(w, http.StatusOK, rewriteResponse{Rewrite: out})
|
httputil.WriteJSON(w, http.StatusOK, rewriteResponse{Rewrite: out})
|
||||||
}
|
}
|
||||||
|
|||||||
58
internal/suggestions/translate.go
Normal file
58
internal/suggestions/translate.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package suggestions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/db"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/llm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type translateResponse struct {
|
||||||
|
Translation string `json:"translation"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// translate renders a suggestion's English explanation into Simplified Chinese
|
||||||
|
// for the Ask Petal bubble, so the ESL reader sees the "why" in her first
|
||||||
|
// language instead of a second copy of the same English text. The explanation is
|
||||||
|
// loaded server-side from the suggestion id (scoped to the local user) and never
|
||||||
|
// trusted from the client, mirroring chat (spec Note #10).
|
||||||
|
func (h *Handler) translate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sugID := chi.URLParam(r, "id")
|
||||||
|
|
||||||
|
var explanation string
|
||||||
|
err := h.DB.QueryRow(
|
||||||
|
`SELECT s.explanation
|
||||||
|
FROM suggestions s
|
||||||
|
JOIN documents d ON d.id = s.doc_id
|
||||||
|
WHERE s.id = ? AND d.user_id = ?`,
|
||||||
|
sugID, db.LocalUserID,
|
||||||
|
).Scan(&explanation)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
httputil.ErrorJSON(w, http.StatusNotFound, "suggestion not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
explanation = strings.TrimSpace(explanation)
|
||||||
|
if explanation == "" {
|
||||||
|
httputil.WriteJSON(w, http.StatusOK, translateResponse{Translation: ""})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := llm.RunTranslate(r.Context(), h.Client, explanation)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ErrorJSON(w, http.StatusBadGateway, "translate failed: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
httputil.WriteJSON(w, http.StatusOK, translateResponse{Translation: out})
|
||||||
|
}
|
||||||
264
internal/tts/handler.go
Normal file
264
internal/tts/handler.go
Normal file
@@ -0,0 +1,264 @@
|
|||||||
|
// Package tts implements read-aloud: it proxies short passages to a local Piper
|
||||||
|
// HTTP server (a fast, offline neural TTS), optionally transcodes Piper's WAV to
|
||||||
|
// mp3/opus with ffmpeg, and serves the audio back to the editor. Synthesized
|
||||||
|
// clips are content-addressed on disk so tapping the same word twice is instant
|
||||||
|
// and never re-synthesizes. The feature is entirely optional: when TTS_ENDPOINT
|
||||||
|
// is unset the route isn't mounted and the frontend falls back to the browser's
|
||||||
|
// Web Speech API.
|
||||||
|
package tts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxTextBytes bounds a single synthesis request. Read-aloud is for a word or a
|
||||||
|
// sentence or two, not whole documents; this keeps one tap from pinning Piper.
|
||||||
|
const maxTextBytes = 4000
|
||||||
|
|
||||||
|
// lengthScale slows Piper slightly below natural pace — a learner following along
|
||||||
|
// with the words, mirroring the old utterance.rate = 0.95. Higher = slower.
|
||||||
|
const lengthScale = 1.1
|
||||||
|
|
||||||
|
// audioFormat describes one output encoding: the cache-file extension, the
|
||||||
|
// response Content-Type, and the ffmpeg args that turn Piper's WAV (on stdin)
|
||||||
|
// into this format (on stdout). A nil ffmpegArgs means "serve the WAV as-is".
|
||||||
|
type audioFormat struct {
|
||||||
|
ext string
|
||||||
|
contentType string
|
||||||
|
ffmpegArgs []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// formats maps the configured TTS_AUDIO_FORMAT to its encoding. mp3 is the safe
|
||||||
|
// default (every browser plays it); opus is ~half the size for speech but has
|
||||||
|
// patchier Safari support; wav skips ffmpeg entirely.
|
||||||
|
var formats = map[string]audioFormat{
|
||||||
|
"wav": {ext: ".wav", contentType: "audio/wav"},
|
||||||
|
"mp3": {ext: ".mp3", contentType: "audio/mpeg",
|
||||||
|
ffmpegArgs: []string{"-f", "mp3", "-c:a", "libmp3lame", "-b:a", "64k", "-ac", "1"}},
|
||||||
|
"opus": {ext: ".opus", contentType: "audio/ogg",
|
||||||
|
ffmpegArgs: []string{"-f", "ogg", "-c:a", "libopus", "-b:a", "32k", "-ac", "1"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
// route is the Piper instance and voice id serving one language. Each Piper
|
||||||
|
// HTTP server loads exactly one model, so distinct languages mean distinct
|
||||||
|
// endpoints (e.g. English on :5005, Chinese on :5006).
|
||||||
|
type route struct {
|
||||||
|
endpoint string // Piper HTTP base URL (no trailing slash)
|
||||||
|
voice string // Piper voice id (sent in the request; also part of the cache key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handler proxies synthesis to Piper and caches the result on disk.
|
||||||
|
type Handler struct {
|
||||||
|
routes map[string]route // base language (e.g. "en", "zh") -> Piper instance
|
||||||
|
cacheDir string
|
||||||
|
format audioFormat
|
||||||
|
client *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
// New builds a Handler from config. It returns (nil, false) when TTS_ENDPOINT is
|
||||||
|
// unset, signalling main to skip mounting the route. An unknown TTS_AUDIO_FORMAT
|
||||||
|
// falls back to mp3 rather than failing the whole server.
|
||||||
|
func New(cfg *config.Config) (*Handler, bool) {
|
||||||
|
if strings.TrimSpace(cfg.TTSEndpoint) == "" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
format, ok := formats[strings.ToLower(strings.TrimSpace(cfg.TTSFormat))]
|
||||||
|
if !ok {
|
||||||
|
format = formats["mp3"]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map by base language so en-US, en-GB, etc. all resolve to the English
|
||||||
|
// instance (the client sends BCP-47 tags like the old Web Speech path did).
|
||||||
|
// A language is only routable when both its endpoint and voice are set;
|
||||||
|
// otherwise the client falls back to Web Speech for that language.
|
||||||
|
routes := map[string]route{}
|
||||||
|
if cfg.TTSVoiceEN != "" {
|
||||||
|
routes["en"] = route{strings.TrimRight(cfg.TTSEndpoint, "/"), cfg.TTSVoiceEN}
|
||||||
|
}
|
||||||
|
if cfg.TTSEndpointZH != "" && cfg.TTSVoiceZH != "" {
|
||||||
|
routes["zh"] = route{strings.TrimRight(cfg.TTSEndpointZH, "/"), cfg.TTSVoiceZH}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.MkdirAll(cfg.TTSCacheDir, 0o755); err != nil {
|
||||||
|
// A missing cache dir isn't fatal — synthesis still works, it just won't
|
||||||
|
// cache. Disable the feature only on endpoint absence, not this.
|
||||||
|
fmt.Fprintf(os.Stderr, "tts: cache dir %q: %v\n", cfg.TTSCacheDir, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Handler{
|
||||||
|
routes: routes,
|
||||||
|
cacheDir: cfg.TTSCacheDir,
|
||||||
|
format: format,
|
||||||
|
client: &http.Client{Timeout: cfg.TTSTimeout},
|
||||||
|
}, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Routes mounts the synthesis endpoint. Mount under "/tts" so the full path is
|
||||||
|
// POST /api/tts.
|
||||||
|
func (h *Handler) Routes() chi.Router {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Post("/", h.synth)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// synthRequest is the body the editor posts: a passage and the BCP-47 language
|
||||||
|
// tag it's written in (e.g. "en-US", "zh-CN").
|
||||||
|
type synthRequest struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
Lang string `json:"lang"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// synth resolves a voice for the requested language, returns cached audio when
|
||||||
|
// present, and otherwise asks Piper to synthesize, transcodes if configured,
|
||||||
|
// caches, and serves. An unconfigured language yields 404 so the client can fall
|
||||||
|
// back to Web Speech without treating it as an error.
|
||||||
|
func (h *Handler) synth(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req synthRequest
|
||||||
|
// Cap the raw body generously above maxTextBytes to leave room for JSON
|
||||||
|
// framing and the lang field; the text itself is truncated after decoding.
|
||||||
|
if err := json.NewDecoder(io.LimitReader(r.Body, maxTextBytes+1024)).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
text := strings.TrimSpace(req.Text)
|
||||||
|
if text == "" {
|
||||||
|
http.Error(w, "empty text", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(text) > maxTextBytes {
|
||||||
|
// Trim back to the last valid rune boundary so we never hand Piper a
|
||||||
|
// half-encoded multibyte character (common with Chinese, 3 bytes/char).
|
||||||
|
text = text[:maxTextBytes]
|
||||||
|
for len(text) > 0 && !utf8.ValidString(text) {
|
||||||
|
text = text[:len(text)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rt, ok := h.routes[baseLang(req.Lang)]
|
||||||
|
if !ok {
|
||||||
|
// No voice for this language — let the client fall back to Web Speech.
|
||||||
|
http.Error(w, "no voice for language", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Content-addressed: identical (voice, text) → identical clip. The format
|
||||||
|
// extension keeps encodings from colliding in the same dir.
|
||||||
|
sum := sha256.Sum256([]byte(rt.voice + "\n" + text))
|
||||||
|
name := hex.EncodeToString(sum[:])[:32] + h.format.ext
|
||||||
|
path := filepath.Join(h.cacheDir, name)
|
||||||
|
|
||||||
|
if _, err := os.Stat(path); err == nil {
|
||||||
|
h.serve(w, r, path)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
audio, err := h.synthesize(r.Context(), rt, text)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "synthesis failed", http.StatusBadGateway)
|
||||||
|
fmt.Fprintf(os.Stderr, "tts: synthesize: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Best-effort cache write via a temp file + rename so a concurrent reader
|
||||||
|
// never sees a half-written clip. A failed write just means no caching.
|
||||||
|
if h.cacheDir != "" {
|
||||||
|
tmp := path + ".tmp"
|
||||||
|
if err := os.WriteFile(tmp, audio, 0o644); err == nil {
|
||||||
|
_ = os.Rename(tmp, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", h.format.contentType)
|
||||||
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
|
_, _ = w.Write(audio)
|
||||||
|
}
|
||||||
|
|
||||||
|
// serve streams a cached clip with a long-lived immutable cache header (the URL
|
||||||
|
// is content-addressed, so the bytes never change for a given request).
|
||||||
|
func (h *Handler) serve(w http.ResponseWriter, r *http.Request, path string) {
|
||||||
|
w.Header().Set("Content-Type", h.format.contentType)
|
||||||
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
|
http.ServeFile(w, r, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// synthesize POSTs to the route's Piper instance, then transcodes the returned
|
||||||
|
// WAV when the configured format calls for it.
|
||||||
|
func (h *Handler) synthesize(ctx context.Context, rt route, text string) ([]byte, error) {
|
||||||
|
body, _ := json.Marshal(map[string]any{
|
||||||
|
"text": text,
|
||||||
|
"voice": rt.voice,
|
||||||
|
"length_scale": lengthScale,
|
||||||
|
})
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, rt.endpoint+"/", bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
httpReq.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
resp, err := h.client.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
|
||||||
|
return nil, fmt.Errorf("piper %d: %s", resp.StatusCode, strings.TrimSpace(string(snippet)))
|
||||||
|
}
|
||||||
|
wav, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if h.format.ffmpegArgs == nil {
|
||||||
|
return wav, nil
|
||||||
|
}
|
||||||
|
return transcode(ctx, wav, h.format.ffmpegArgs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// transcode pipes WAV bytes through ffmpeg (stdin → stdout) into the target
|
||||||
|
// encoding. ffmpeg is assumed on PATH; an error here surfaces as a 502.
|
||||||
|
func transcode(ctx context.Context, wav []byte, args []string) ([]byte, error) {
|
||||||
|
// Guard ffmpeg against a hang independent of the HTTP client timeout.
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
full := append([]string{"-hide_banner", "-loglevel", "error", "-i", "pipe:0"}, args...)
|
||||||
|
full = append(full, "pipe:1")
|
||||||
|
cmd := exec.CommandContext(ctx, "ffmpeg", full...)
|
||||||
|
cmd.Stdin = bytes.NewReader(wav)
|
||||||
|
var out, errBuf bytes.Buffer
|
||||||
|
cmd.Stdout = &out
|
||||||
|
cmd.Stderr = &errBuf
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
return nil, fmt.Errorf("ffmpeg: %v: %s", err, strings.TrimSpace(errBuf.String()))
|
||||||
|
}
|
||||||
|
return out.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// baseLang reduces a BCP-47 tag to its primary subtag, lowercased: "en-US" → "en",
|
||||||
|
// "zh-CN" → "zh", "" → "". Mirrors the client's pickVoice base-language matching.
|
||||||
|
func baseLang(tag string) string {
|
||||||
|
tag = strings.ToLower(strings.TrimSpace(tag))
|
||||||
|
if i := strings.IndexAny(tag, "-_"); i >= 0 {
|
||||||
|
return tag[:i]
|
||||||
|
}
|
||||||
|
return tag
|
||||||
|
}
|
||||||
170
internal/tts/handler_test.go
Normal file
170
internal/tts/handler_test.go
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
package tts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newStubPiper returns a fake Piper server that echoes a fixed WAV body and
|
||||||
|
// records how many times it was called and the last request payload.
|
||||||
|
func newStubPiper(t *testing.T, body []byte) (*httptest.Server, *int32, *synthEcho) {
|
||||||
|
t.Helper()
|
||||||
|
var calls int32
|
||||||
|
last := &synthEcho{}
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
atomic.AddInt32(&calls, 1)
|
||||||
|
var req map[string]any
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||||
|
last.voice, _ = req["voice"].(string)
|
||||||
|
last.text, _ = req["text"].(string)
|
||||||
|
w.Header().Set("Content-Type", "audio/wav")
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}))
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
return srv, &calls, last
|
||||||
|
}
|
||||||
|
|
||||||
|
type synthEcho struct{ voice, text string }
|
||||||
|
|
||||||
|
// newHandler builds a wav-format handler (no ffmpeg) pointed at a stub server.
|
||||||
|
func newHandler(t *testing.T, endpoint string) *Handler {
|
||||||
|
t.Helper()
|
||||||
|
return &Handler{
|
||||||
|
routes: map[string]route{"en": {strings.TrimRight(endpoint, "/"), "en_US-amy-medium"}},
|
||||||
|
cacheDir: t.TempDir(),
|
||||||
|
format: formats["wav"],
|
||||||
|
client: http.DefaultClient,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func post(t *testing.T, h *Handler, text, lang string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
b, _ := json.Marshal(synthRequest{Text: text, Lang: lang})
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(b))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
h.synth(rr, req)
|
||||||
|
return rr
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSynthSuccessAndVoiceSelection(t *testing.T) {
|
||||||
|
wav := []byte("RIFF....fake-wav")
|
||||||
|
srv, calls, last := newStubPiper(t, wav)
|
||||||
|
h := newHandler(t, srv.URL)
|
||||||
|
|
||||||
|
rr := post(t, h, "hello there", "en-US")
|
||||||
|
if rr.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want 200", rr.Code)
|
||||||
|
}
|
||||||
|
if got := rr.Body.Bytes(); !bytes.Equal(got, wav) {
|
||||||
|
t.Fatalf("body = %q, want the piper wav", got)
|
||||||
|
}
|
||||||
|
if ct := rr.Header().Get("Content-Type"); ct != "audio/wav" {
|
||||||
|
t.Fatalf("content-type = %q, want audio/wav", ct)
|
||||||
|
}
|
||||||
|
if last.voice != "en_US-amy-medium" {
|
||||||
|
t.Fatalf("piper voice = %q, want en_US-amy-medium", last.voice)
|
||||||
|
}
|
||||||
|
if *calls != 1 {
|
||||||
|
t.Fatalf("piper calls = %d, want 1", *calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRoutesByLanguageToSeparateInstances(t *testing.T) {
|
||||||
|
enSrv, enCalls, _ := newStubPiper(t, []byte("EN-wav"))
|
||||||
|
zhSrv, zhCalls, zhLast := newStubPiper(t, []byte("ZH-wav"))
|
||||||
|
h := &Handler{
|
||||||
|
routes: map[string]route{
|
||||||
|
"en": {strings.TrimRight(enSrv.URL, "/"), "en_US-amy-medium"},
|
||||||
|
"zh": {strings.TrimRight(zhSrv.URL, "/"), "zh_CN-huayan-medium"},
|
||||||
|
},
|
||||||
|
cacheDir: t.TempDir(),
|
||||||
|
format: formats["wav"],
|
||||||
|
client: http.DefaultClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
if rr := post(t, h, "你好世界", "zh-CN"); rr.Code != http.StatusOK {
|
||||||
|
t.Fatalf("zh status = %d, want 200", rr.Code)
|
||||||
|
}
|
||||||
|
if *zhCalls != 1 || *enCalls != 0 {
|
||||||
|
t.Fatalf("calls en=%d zh=%d, want en=0 zh=1 (zh routed to zh instance)", *enCalls, *zhCalls)
|
||||||
|
}
|
||||||
|
if zhLast.voice != "zh_CN-huayan-medium" {
|
||||||
|
t.Fatalf("zh voice = %q, want zh_CN-huayan-medium", zhLast.voice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnknownLanguageReturns404(t *testing.T) {
|
||||||
|
srv, calls, _ := newStubPiper(t, []byte("x"))
|
||||||
|
h := newHandler(t, srv.URL)
|
||||||
|
|
||||||
|
rr := post(t, h, "你好", "zh-CN") // only "en" is configured
|
||||||
|
if rr.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("status = %d, want 404", rr.Code)
|
||||||
|
}
|
||||||
|
if *calls != 0 {
|
||||||
|
t.Fatalf("piper calls = %d, want 0 (should not synthesize)", *calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCacheHitSkipsPiper(t *testing.T) {
|
||||||
|
srv, calls, _ := newStubPiper(t, []byte("RIFF....fake-wav"))
|
||||||
|
h := newHandler(t, srv.URL)
|
||||||
|
|
||||||
|
if rr := post(t, h, "same words", "en-US"); rr.Code != http.StatusOK {
|
||||||
|
t.Fatalf("first status = %d, want 200", rr.Code)
|
||||||
|
}
|
||||||
|
if rr := post(t, h, "same words", "en-US"); rr.Code != http.StatusOK {
|
||||||
|
t.Fatalf("second status = %d, want 200", rr.Code)
|
||||||
|
}
|
||||||
|
if *calls != 1 {
|
||||||
|
t.Fatalf("piper calls = %d, want 1 (second served from cache)", *calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmptyTextReturns400(t *testing.T) {
|
||||||
|
srv, _, _ := newStubPiper(t, []byte("x"))
|
||||||
|
h := newHandler(t, srv.URL)
|
||||||
|
|
||||||
|
if rr := post(t, h, " ", "en-US"); rr.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("status = %d, want 400", rr.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTextIsCapped(t *testing.T) {
|
||||||
|
srv, _, last := newStubPiper(t, []byte("x"))
|
||||||
|
h := newHandler(t, srv.URL)
|
||||||
|
|
||||||
|
long := strings.Repeat("a", maxTextBytes+500)
|
||||||
|
if rr := post(t, h, long, "en-US"); rr.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want 200", rr.Code)
|
||||||
|
}
|
||||||
|
if len(last.text) != maxTextBytes {
|
||||||
|
t.Fatalf("piper received %d chars, want capped to %d", len(last.text), maxTextBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBaseLang(t *testing.T) {
|
||||||
|
cases := map[string]string{"en-US": "en", "EN_gb": "en", "zh-CN": "zh", "en": "en", "": ""}
|
||||||
|
for in, want := range cases {
|
||||||
|
if got := baseLang(in); got != want {
|
||||||
|
t.Errorf("baseLang(%q) = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensure the stub's body is fully consumable (guards against the LimitReader cap
|
||||||
|
// accidentally truncating a normal request body in synth()).
|
||||||
|
func TestRequestBodyNotTruncated(t *testing.T) {
|
||||||
|
srv, _, last := newStubPiper(t, []byte("x"))
|
||||||
|
h := newHandler(t, srv.URL)
|
||||||
|
text := strings.Repeat("word ", 200) // ~1000 bytes, under the cap
|
||||||
|
post(t, h, text, "en-US")
|
||||||
|
if last.text != strings.TrimSpace(text) {
|
||||||
|
t.Fatalf("piper text length = %d, want %d", len(last.text), len(strings.TrimSpace(text)))
|
||||||
|
}
|
||||||
|
}
|
||||||
307
internal/vocab/handlers.go
Normal file
307
internal/vocab/handlers.go
Normal file
@@ -0,0 +1,307 @@
|
|||||||
|
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"
|
||||||
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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"`
|
||||||
|
Definition string `json:"definition"` // English fallback meaning when there's no Chinese 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, definition, 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.Definition, &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 {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []Word{}
|
||||||
|
for rows.Next() {
|
||||||
|
word, err := scanWord(rows)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out = append(out, word)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
httputil.WriteJSON(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
type captureRequest struct {
|
||||||
|
Word string `json:"word"`
|
||||||
|
Gloss string `json:"gloss"`
|
||||||
|
Definition string `json:"definition"`
|
||||||
|
Phonetic string `json:"phonetic"`
|
||||||
|
Example string `json:"example"`
|
||||||
|
DocID *string `json:"doc_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Field-length caps. The captured fields come from the offline lexicon and the
|
||||||
|
// editor selection, not free-typed prose, so we clamp rather than reject — a
|
||||||
|
// lookup should never fail because a definition ran long. Counts are runes so a
|
||||||
|
// Chinese gloss isn't cut mid-character. The word is the upsert key, so an absurd
|
||||||
|
// "word" is bounded too.
|
||||||
|
const (
|
||||||
|
maxWordLen = 128
|
||||||
|
maxGlossLen = 512
|
||||||
|
maxDefinitionLen = 4096
|
||||||
|
maxPhoneticLen = 256
|
||||||
|
maxExampleLen = 4096
|
||||||
|
)
|
||||||
|
|
||||||
|
// clamp trims s to at most max runes (rune-safe so multibyte glosses survive).
|
||||||
|
func clamp(s string, max int) string {
|
||||||
|
r := []rune(s)
|
||||||
|
if len(r) <= max {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return string(r[:max])
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
httputil.ErrorJSON(w, http.StatusBadRequest, "invalid body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Normalize the same way the lexicon does (internal/lexicon: lower+trim) so
|
||||||
|
// the UNIQUE(user_id, word) upsert is genuinely idempotent — otherwise
|
||||||
|
// "Apple" at a sentence start and "apple" mid-line would create two separate
|
||||||
|
// cards on independent schedules.
|
||||||
|
word := clamp(strings.ToLower(strings.TrimSpace(req.Word)), maxWordLen)
|
||||||
|
if word == "" {
|
||||||
|
httputil.ErrorJSON(w, http.StatusBadRequest, "word is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Gloss = clamp(req.Gloss, maxGlossLen)
|
||||||
|
req.Definition = clamp(req.Definition, maxDefinitionLen)
|
||||||
|
req.Phonetic = clamp(req.Phonetic, maxPhoneticLen)
|
||||||
|
req.Example = clamp(req.Example, maxExampleLen)
|
||||||
|
|
||||||
|
// A blank doc_id is the same as none; otherwise the word must belong to a
|
||||||
|
// document the user actually owns. Without this check a stale or forged id
|
||||||
|
// would hit the foreign key and leak a raw "FOREIGN KEY constraint" 500
|
||||||
|
// instead of a clean 400 (and, once auth lands, would let a word be attached
|
||||||
|
// to another user's document).
|
||||||
|
if req.DocID != nil {
|
||||||
|
if strings.TrimSpace(*req.DocID) == "" {
|
||||||
|
req.DocID = nil
|
||||||
|
} else {
|
||||||
|
var ok int
|
||||||
|
err := h.DB.QueryRow(
|
||||||
|
`SELECT 1 FROM documents WHERE id = ? AND user_id = ?`,
|
||||||
|
*req.DocID, db.LocalUserID,
|
||||||
|
).Scan(&ok)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
httputil.ErrorJSON(w, http.StatusBadRequest, "unknown doc_id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
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, definition, 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,
|
||||||
|
definition = excluded.definition,
|
||||||
|
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.Definition, req.Phonetic, req.Example, req.DocID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := h.fetch(word)
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
httputil.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 {
|
||||||
|
httputil.ErrorJSON(w, http.StatusBadRequest, "invalid body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Grade != GradeAgain && req.Grade != GradeGood && req.Grade != GradeEasy {
|
||||||
|
httputil.ErrorJSON(w, http.StatusBadRequest, "grade must be again, good, or easy")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// The grade is computed in Go (the SM-2-lite scheduler), so the read and the
|
||||||
|
// write must be one atomic unit: a bare SELECT-then-UPDATE could interleave
|
||||||
|
// with a concurrent review of the same card and lose an update. Wrap both in a
|
||||||
|
// transaction.
|
||||||
|
tx, err := h.DB.Begin()
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer tx.Rollback() // no-op once committed
|
||||||
|
|
||||||
|
var cur State
|
||||||
|
err = tx.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) {
|
||||||
|
httputil.ErrorJSON(w, http.StatusNotFound, "word not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
httputil.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 := tx.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 {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := scanWord(tx.QueryRow(
|
||||||
|
`SELECT `+vocabColumns+` FROM vocab_words WHERE id = ? AND user_id = ?`, id, db.LocalUserID,
|
||||||
|
))
|
||||||
|
if err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
httputil.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 {
|
||||||
|
httputil.ServerError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
|
httputil.ErrorJSON(w, http.StatusNotFound, "word not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
249
internal/vocab/handlers_test.go
Normal file
249
internal/vocab/handlers_test.go
Normal file
@@ -0,0 +1,249 @@
|
|||||||
|
package vocab
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCaptureStoresDefinitionFallback proves a word with an English definition
|
||||||
|
// but no Chinese gloss still round-trips its definition, so review has a meaning
|
||||||
|
// to reveal instead of a blank card.
|
||||||
|
func TestCaptureStoresDefinitionFallback(t *testing.T) {
|
||||||
|
srv, _ := newTestServer(t)
|
||||||
|
rec := do(t, srv, http.MethodPost, "/vocab",
|
||||||
|
`{"word":"ineffable","definition":"too great to be expressed in words"}`)
|
||||||
|
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.Gloss != "" {
|
||||||
|
t.Fatalf("expected no gloss, got %q", w.Gloss)
|
||||||
|
}
|
||||||
|
if w.Definition != "too great to be expressed in words" {
|
||||||
|
t.Fatalf("definition not stored, got %q", w.Definition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCaptureCaseInsensitive proves "Apple" (sentence start) and "apple"
|
||||||
|
// (mid-line) land in the SAME garden card — capture normalizes to lower+trim
|
||||||
|
// like the lexicon, so the idempotent upsert isn't defeated by casing.
|
||||||
|
func TestCaptureCaseInsensitive(t *testing.T) {
|
||||||
|
srv, _ := newTestServer(t)
|
||||||
|
if rec := do(t, srv, http.MethodPost, "/vocab", `{"word":"Apple","gloss":"苹果"}`); rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("capture Apple: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
if rec := do(t, srv, http.MethodPost, "/vocab", `{"word":" apple ","gloss":"苹果"}`); rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("capture apple: 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("Apple/apple should be one card, got %d", len(all))
|
||||||
|
}
|
||||||
|
if all[0].Word != "apple" {
|
||||||
|
t.Fatalf("word should be normalized to lowercase, got %q", all[0].Word)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCaptureUnknownDocID rejects an unowned/stale doc_id with a clean 400
|
||||||
|
// rather than letting it hit the foreign key and leak a raw 500.
|
||||||
|
func TestCaptureUnknownDocID(t *testing.T) {
|
||||||
|
srv, _ := newTestServer(t)
|
||||||
|
rec := do(t, srv, http.MethodPost, "/vocab",
|
||||||
|
`{"word":"quixotic","gloss":"不切实际的","doc_id":"does-not-exist"}`)
|
||||||
|
if rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("unknown doc_id: want 400, got %d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
// A blank doc_id is treated as none, not an error.
|
||||||
|
if rec := do(t, srv, http.MethodPost, "/vocab", `{"word":"limpid","gloss":"清澈的","doc_id":""}`); rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("blank doc_id should be accepted as none: code=%d body=%s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCaptureClampsLongFields proves over-long fields are clamped (not rejected)
|
||||||
|
// so a lookup never fails on length, and the word key stays bounded.
|
||||||
|
func TestCaptureClampsLongFields(t *testing.T) {
|
||||||
|
srv, _ := newTestServer(t)
|
||||||
|
longWord := strings.Repeat("a", maxWordLen+50)
|
||||||
|
longDef := strings.Repeat("x", maxDefinitionLen+50)
|
||||||
|
rec := do(t, srv, http.MethodPost, "/vocab",
|
||||||
|
`{"word":"`+longWord+`","definition":"`+longDef+`"}`)
|
||||||
|
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 len([]rune(w.Word)) != maxWordLen {
|
||||||
|
t.Fatalf("word should clamp to %d runes, got %d", maxWordLen, len([]rune(w.Word)))
|
||||||
|
}
|
||||||
|
if len([]rune(w.Definition)) != maxDefinitionLen {
|
||||||
|
t.Fatalf("definition should clamp to %d runes, got %d", maxDefinitionLen, len([]rune(w.Definition)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
114
internal/vocab/scheduler.go
Normal file
114
internal/vocab/scheduler.go
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
// 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
|
||||||
|
maxEase = 3.0 // ease ceiling — keeps "easy" from compounding growth without bound
|
||||||
|
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
|
||||||
|
|
||||||
|
// maxInterval caps how far a card can drift into the future. Even a word
|
||||||
|
// graded "easy" many times resurfaces about once a year, so nothing silently
|
||||||
|
// leaves the garden forever (the whole point is to keep words in gentle
|
||||||
|
// rotation, not to retire them).
|
||||||
|
maxInterval = 365
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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: clampInterval(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: clampInterval(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
|
||||||
|
}
|
||||||
|
if e > maxEase {
|
||||||
|
return maxEase
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
func clampInterval(d int) int {
|
||||||
|
if d > maxInterval {
|
||||||
|
return maxInterval
|
||||||
|
}
|
||||||
|
return d
|
||||||
|
}
|
||||||
88
internal/vocab/scheduler_test.go
Normal file
88
internal/vocab/scheduler_test.go
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCapsBoundGrowth proves runaway "easy" grading can't push ease or the
|
||||||
|
// interval past their ceilings, so a word always resurfaces within a year.
|
||||||
|
func TestCapsBoundGrowth(t *testing.T) {
|
||||||
|
s := State{Ease: startEase}
|
||||||
|
for i := 0; i < 40; i++ {
|
||||||
|
s = s.next(GradeEasy)
|
||||||
|
if s.Ease > maxEase {
|
||||||
|
t.Fatalf("step %d: ease %v exceeded cap %v", i, s.Ease, maxEase)
|
||||||
|
}
|
||||||
|
if s.Interval > maxInterval {
|
||||||
|
t.Fatalf("step %d: interval %d exceeded cap %d", i, s.Interval, maxInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// After enough "easy" reviews it should be pinned at the ceilings.
|
||||||
|
if s.Interval != maxInterval {
|
||||||
|
t.Fatalf("interval should saturate at %d, got %d", maxInterval, s.Interval)
|
||||||
|
}
|
||||||
|
if s.Ease != maxEase {
|
||||||
|
t.Fatalf("ease should saturate at %v, got %v", maxEase, s.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)
|
||||||
|
}
|
||||||
|
}
|
||||||
101
scripts/build_phonetic.py
Normal file
101
scripts/build_phonetic.py
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Build the embedded English-phonetic dataset.
|
||||||
|
|
||||||
|
Petal's writer is a native Mandarin speaker learning English, so the useful
|
||||||
|
pronunciation aid is *how to say the English word* — shown in the word popover
|
||||||
|
beside the 🔊 read-aloud button. (Pinyin would annotate Chinese she already
|
||||||
|
reads fluently, so it isn't built.) The phonetic spelling comes from the same
|
||||||
|
ECDICT source as the Chinese gloss, which already carries a `phonetic` column.
|
||||||
|
|
||||||
|
Two modes:
|
||||||
|
|
||||||
|
# Full build from ECDICT (same CSV used by build_gloss.py):
|
||||||
|
curl -sL https://raw.githubusercontent.com/skywind3000/ECDICT/master/ecdict.csv -o ecdict.csv
|
||||||
|
python3 scripts/build_phonetic.py ecdict.csv internal/lexicon/data/phonetic.json.gz
|
||||||
|
|
||||||
|
# Write just the built-in common-word seed (no CSV needed — what ships in-repo
|
||||||
|
# so the feature works out of the box until a full build is run):
|
||||||
|
python3 scripts/build_phonetic.py --seed internal/lexicon/data/phonetic.json.gz
|
||||||
|
"""
|
||||||
|
import csv
|
||||||
|
import gzip
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# Same frequency gate as the gloss build, so coverage matches the words an ESL
|
||||||
|
# writer actually meets and the asset stays small.
|
||||||
|
MAX_RANK = 50000
|
||||||
|
|
||||||
|
# Single English word (letters with internal apostrophe/hyphen).
|
||||||
|
WORD_RE = re.compile(r"^[a-z][a-z'\-]*[a-z]$|^[a-z]$")
|
||||||
|
|
||||||
|
# A small, hand-checked seed of common words → IPA. This ships in the repo so the
|
||||||
|
# phonetic line is live immediately; a full ECDICT build overwrites it with broad
|
||||||
|
# coverage. Kept deliberately short and correct rather than large and shaky.
|
||||||
|
SEED = {
|
||||||
|
"hello": "həˈloʊ", "world": "wɜːrld", "people": "ˈpiːpl", "water": "ˈwɔːtər",
|
||||||
|
"river": "ˈrɪvər", "house": "haʊs", "school": "skuːl", "friend": "frɛnd",
|
||||||
|
"family": "ˈfæməli", "mother": "ˈmʌðər", "father": "ˈfɑːðər", "woman": "ˈwʊmən",
|
||||||
|
"language": "ˈlæŋɡwɪdʒ", "english": "ˈɪŋɡlɪʃ", "write": "raɪt", "writing": "ˈraɪtɪŋ",
|
||||||
|
"read": "riːd", "word": "wɜːrd", "sentence": "ˈsɛntəns", "beautiful": "ˈbjuːtɪfl",
|
||||||
|
"happy": "ˈhæpi", "love": "lʌv", "thought": "θɔːt", "through": "θruː",
|
||||||
|
"though": "ðoʊ", "enough": "ɪˈnʌf", "question": "ˈkwɛstʃən", "answer": "ˈænsər",
|
||||||
|
"because": "bɪˈkɔːz", "people's": "ˈpiːplz", "important": "ɪmˈpɔːrtnt",
|
||||||
|
"different": "ˈdɪfərənt", "remember": "rɪˈmɛmbər", "together": "təˈɡɛðər",
|
||||||
|
"morning": "ˈmɔːrnɪŋ", "tonight": "təˈnaɪt", "yesterday": "ˈjɛstərdeɪ",
|
||||||
|
"tomorrow": "təˈmɒroʊ", "weather": "ˈwɛðər", "color": "ˈkʌlər", "colour": "ˈkʌlər",
|
||||||
|
"favourite": "ˈfeɪvərɪt", "favorite": "ˈfeɪvərɪt", "comfortable": "ˈkʌmftəbl",
|
||||||
|
"vegetable": "ˈvɛdʒtəbl", "interesting": "ˈɪntrəstɪŋ", "necessary": "ˈnɛsəsɛri",
|
||||||
|
"february": "ˈfɛbruɛri", "wednesday": "ˈwɛnzdeɪ",
|
||||||
|
"island": "ˈaɪlənd", "knife": "naɪf", "know": "noʊ", "knee": "niː",
|
||||||
|
"hour": "ˈaʊər", "honest": "ˈɒnɪst", "listen": "ˈlɪsn", "castle": "ˈkæsl",
|
||||||
|
"thank": "θæŋk", "think": "θɪŋk", "thing": "θɪŋ", "three": "θriː",
|
||||||
|
"voice": "vɔɪs", "choice": "tʃɔɪs", "nature": "ˈneɪtʃər", "picture": "ˈpɪktʃər",
|
||||||
|
"future": "ˈfjuːtʃər", "culture": "ˈkʌltʃər", "measure": "ˈmɛʒər",
|
||||||
|
"usually": "ˈjuːʒuəli", "decision": "dɪˈsɪʒn", "delicious": "dɪˈlɪʃəs",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def clean_phonetic(p: str) -> str:
|
||||||
|
"""Normalize an ECDICT phonetic field: trim, strip wrapping slashes/brackets."""
|
||||||
|
p = p.strip().strip("/[]").strip()
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def build_from_csv(src: str) -> dict:
|
||||||
|
out = {}
|
||||||
|
with open(src, newline="", encoding="utf-8") as fh:
|
||||||
|
for row in csv.DictReader(fh):
|
||||||
|
word = (row.get("word") or "").strip().lower()
|
||||||
|
phon = clean_phonetic(row.get("phonetic") or "")
|
||||||
|
if not word or not phon or not WORD_RE.match(word):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
rank = int(row.get("frq") or 0) or int(row.get("bnc") or 0)
|
||||||
|
except ValueError:
|
||||||
|
rank = 0
|
||||||
|
if rank <= 0 or rank > MAX_RANK:
|
||||||
|
continue
|
||||||
|
out[word] = phon
|
||||||
|
# Make sure the curated seed is always present (and authoritative).
|
||||||
|
out.update(SEED)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
args = sys.argv[1:]
|
||||||
|
if not args:
|
||||||
|
sys.exit(__doc__)
|
||||||
|
if args[0] == "--seed":
|
||||||
|
data, dest = dict(SEED), args[1]
|
||||||
|
else:
|
||||||
|
src, dest = args[0], args[1]
|
||||||
|
data = build_from_csv(src)
|
||||||
|
with gzip.open(dest, "wt", encoding="utf-8") as fh:
|
||||||
|
json.dump(data, fh, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
print(f"wrote {len(data)} phonetic entries to {dest}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
124
web/package-lock.json
generated
124
web/package-lock.json
generated
@@ -9,7 +9,15 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tiptap/extension-character-count": "^2.11.5",
|
"@tiptap/extension-character-count": "^2.11.5",
|
||||||
|
"@tiptap/extension-color": "^2.27.2",
|
||||||
|
"@tiptap/extension-highlight": "^2.27.2",
|
||||||
|
"@tiptap/extension-image": "^2.27.2",
|
||||||
|
"@tiptap/extension-link": "^2.27.2",
|
||||||
"@tiptap/extension-placeholder": "^2.11.5",
|
"@tiptap/extension-placeholder": "^2.11.5",
|
||||||
|
"@tiptap/extension-table": "^2.27.2",
|
||||||
|
"@tiptap/extension-table-cell": "^2.27.2",
|
||||||
|
"@tiptap/extension-table-header": "^2.27.2",
|
||||||
|
"@tiptap/extension-table-row": "^2.27.2",
|
||||||
"@tiptap/extension-text-align": "^2.11.5",
|
"@tiptap/extension-text-align": "^2.11.5",
|
||||||
"@tiptap/extension-underline": "^2.11.5",
|
"@tiptap/extension-underline": "^2.11.5",
|
||||||
"@tiptap/pm": "^2.11.5",
|
"@tiptap/pm": "^2.11.5",
|
||||||
@@ -1568,6 +1576,20 @@
|
|||||||
"@tiptap/pm": "^2.7.0"
|
"@tiptap/pm": "^2.7.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tiptap/extension-color": {
|
||||||
|
"version": "2.27.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-color/-/extension-color-2.27.2.tgz",
|
||||||
|
"integrity": "sha512-sOKCP8/2V3sRM3FdWgMe1lFE5ewsWNCRafiVoujS1+TTHGCj4jw6W+LiumBUk7cRI8kXW/rqGWVC4RVdknYUCA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/core": "^2.7.0",
|
||||||
|
"@tiptap/extension-text-style": "^2.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tiptap/extension-document": {
|
"node_modules/@tiptap/extension-document": {
|
||||||
"version": "2.27.2",
|
"version": "2.27.2",
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-2.27.2.tgz",
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-2.27.2.tgz",
|
||||||
@@ -1652,6 +1674,19 @@
|
|||||||
"@tiptap/core": "^2.7.0"
|
"@tiptap/core": "^2.7.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tiptap/extension-highlight": {
|
||||||
|
"version": "2.27.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-highlight/-/extension-highlight-2.27.2.tgz",
|
||||||
|
"integrity": "sha512-ZjlktDdMjruMJFAVz0TbQf0v92Jqkc7Ri1iZJqBXuLid+r+GxUzl2CVAV7qq5yagkGQgvAG+WGsMk880HgR3MA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/core": "^2.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tiptap/extension-history": {
|
"node_modules/@tiptap/extension-history": {
|
||||||
"version": "2.27.2",
|
"version": "2.27.2",
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-history/-/extension-history-2.27.2.tgz",
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-history/-/extension-history-2.27.2.tgz",
|
||||||
@@ -1680,6 +1715,19 @@
|
|||||||
"@tiptap/pm": "^2.7.0"
|
"@tiptap/pm": "^2.7.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tiptap/extension-image": {
|
||||||
|
"version": "2.27.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-image/-/extension-image-2.27.2.tgz",
|
||||||
|
"integrity": "sha512-5zL/BY41FIt72azVrCrv3n+2YJ/JyO8wxCcA4Dk1eXIobcgVyIdo4rG39gCqIOiqziAsqnqoj12QHTBtHsJ6mQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/core": "^2.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tiptap/extension-italic": {
|
"node_modules/@tiptap/extension-italic": {
|
||||||
"version": "2.27.2",
|
"version": "2.27.2",
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-2.27.2.tgz",
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-2.27.2.tgz",
|
||||||
@@ -1693,6 +1741,23 @@
|
|||||||
"@tiptap/core": "^2.7.0"
|
"@tiptap/core": "^2.7.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tiptap/extension-link": {
|
||||||
|
"version": "2.27.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-2.27.2.tgz",
|
||||||
|
"integrity": "sha512-bnP61qkr0Kj9Cgnop1hxn2zbOCBzNtmawxr92bVTOE31fJv6FhtCnQiD6tuPQVGMYhcmAj7eihtvuEMFfqEPcQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"linkifyjs": "^4.3.2"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/core": "^2.7.0",
|
||||||
|
"@tiptap/pm": "^2.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tiptap/extension-list-item": {
|
"node_modules/@tiptap/extension-list-item": {
|
||||||
"version": "2.27.2",
|
"version": "2.27.2",
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-list-item/-/extension-list-item-2.27.2.tgz",
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-list-item/-/extension-list-item-2.27.2.tgz",
|
||||||
@@ -1759,6 +1824,59 @@
|
|||||||
"@tiptap/core": "^2.7.0"
|
"@tiptap/core": "^2.7.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tiptap/extension-table": {
|
||||||
|
"version": "2.27.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-table/-/extension-table-2.27.2.tgz",
|
||||||
|
"integrity": "sha512-pDbhOpT5phZkcsyPjGBQlXv0+0hmdrvqHJ+dJjkGcCtlfy2pHiEIhmIItOFagc7wXy8G9iUFZ9Jie4zvDf+brg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/core": "^2.7.0",
|
||||||
|
"@tiptap/pm": "^2.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tiptap/extension-table-cell": {
|
||||||
|
"version": "2.27.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-table-cell/-/extension-table-cell-2.27.2.tgz",
|
||||||
|
"integrity": "sha512-9Lk46MjZMFzVZfOj9Kd7VgC6Odt6vmEhlCYVumErShUY7EkFqCw3b2IYoUtQkntfOEx/Afnhff/okNQwPsJeUA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/core": "^2.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tiptap/extension-table-header": {
|
||||||
|
"version": "2.27.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-table-header/-/extension-table-header-2.27.2.tgz",
|
||||||
|
"integrity": "sha512-ZEb6lbG0NbbodWLV0b4BS/QrDIPlUbCcuOsUxzqVvlMUY1Vg6Fj6fKwLaBcsIUDHi8sxZDBEgYEDw3BR/zcO6A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/core": "^2.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tiptap/extension-table-row": {
|
||||||
|
"version": "2.27.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-table-row/-/extension-table-row-2.27.2.tgz",
|
||||||
|
"integrity": "sha512-Nw9+tA56Y5HtLVP01NGCZSUuTQhJPtfK9OfmDgGgcxynn2cRVdEtj+9FNZqRhQ1iRVaAI+Rd4xRvX9qYePMOxw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ueberdosis"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tiptap/core": "^2.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tiptap/extension-text": {
|
"node_modules/@tiptap/extension-text": {
|
||||||
"version": "2.27.2",
|
"version": "2.27.2",
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-2.27.2.tgz",
|
"resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-2.27.2.tgz",
|
||||||
@@ -2828,6 +2946,12 @@
|
|||||||
"uc.micro": "^2.0.0"
|
"uc.micro": "^2.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/linkifyjs": {
|
||||||
|
"version": "4.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.3.tgz",
|
||||||
|
"integrity": "sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/lottie-web": {
|
"node_modules/lottie-web": {
|
||||||
"version": "5.13.0",
|
"version": "5.13.0",
|
||||||
"resolved": "https://registry.npmjs.org/lottie-web/-/lottie-web-5.13.0.tgz",
|
"resolved": "https://registry.npmjs.org/lottie-web/-/lottie-web-5.13.0.tgz",
|
||||||
|
|||||||
@@ -12,7 +12,15 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tiptap/extension-character-count": "^2.11.5",
|
"@tiptap/extension-character-count": "^2.11.5",
|
||||||
|
"@tiptap/extension-color": "^2.27.2",
|
||||||
|
"@tiptap/extension-highlight": "^2.27.2",
|
||||||
|
"@tiptap/extension-image": "^2.27.2",
|
||||||
|
"@tiptap/extension-link": "^2.27.2",
|
||||||
"@tiptap/extension-placeholder": "^2.11.5",
|
"@tiptap/extension-placeholder": "^2.11.5",
|
||||||
|
"@tiptap/extension-table": "^2.27.2",
|
||||||
|
"@tiptap/extension-table-cell": "^2.27.2",
|
||||||
|
"@tiptap/extension-table-header": "^2.27.2",
|
||||||
|
"@tiptap/extension-table-row": "^2.27.2",
|
||||||
"@tiptap/extension-text-align": "^2.11.5",
|
"@tiptap/extension-text-align": "^2.11.5",
|
||||||
"@tiptap/extension-underline": "^2.11.5",
|
"@tiptap/extension-underline": "^2.11.5",
|
||||||
"@tiptap/pm": "^2.11.5",
|
"@tiptap/pm": "^2.11.5",
|
||||||
|
|||||||
@@ -9,15 +9,21 @@ 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'
|
||||||
import { useVersionWatch } from './hooks/useVersionWatch'
|
import { useVersionWatch } from './hooks/useVersionWatch'
|
||||||
import { PetalFall } from './effects/PetalFall'
|
import { PetalFall } from './effects/PetalFall'
|
||||||
|
import { useNightMode } from './hooks/useNightMode'
|
||||||
import { playSuggestionSound } from './audio/sounds'
|
import { playSuggestionSound } from './audio/sounds'
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const updateAvailable = useVersionWatch()
|
const updateAvailable = useVersionWatch()
|
||||||
|
// Late-night calm mode: dark theme + falling stars instead of petals. The hook
|
||||||
|
// toggles the `petal-night` class on <html>; we pass the flag to the ambient
|
||||||
|
// layer so the petals become stars.
|
||||||
|
const night = useNightMode()
|
||||||
const [docs, setDocs] = useState<DocSummary[]>([])
|
const [docs, setDocs] = useState<DocSummary[]>([])
|
||||||
const [currentDoc, setCurrentDoc] = useState<Document | null>(null)
|
const [currentDoc, setCurrentDoc] = useState<Document | null>(null)
|
||||||
const [title, setTitle] = useState('')
|
const [title, setTitle] = useState('')
|
||||||
@@ -41,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
|
||||||
@@ -65,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.
|
||||||
@@ -192,6 +201,38 @@ export default function App() {
|
|||||||
setDocText('')
|
setDocText('')
|
||||||
}, [saveNow, isBlankDraft])
|
}, [saveNow, isBlankDraft])
|
||||||
|
|
||||||
|
// Duplicate a document: copy its body/tone into a fresh doc titled "… (副本)",
|
||||||
|
// then open the copy. Tags aren't carried over (a fresh start for the copy).
|
||||||
|
const handleDuplicate = useCallback(
|
||||||
|
async (id: string) => {
|
||||||
|
try {
|
||||||
|
await saveNow() // flush in case we're duplicating the open doc
|
||||||
|
const src = await api.getDoc(id)
|
||||||
|
const fresh = await api.createDoc()
|
||||||
|
const dupTitle = `${src.title?.trim() || 'Untitled'} (副本)`
|
||||||
|
const updated = await api.updateDoc(fresh.id, {
|
||||||
|
title: dupTitle,
|
||||||
|
content: src.content,
|
||||||
|
content_text: src.content_text,
|
||||||
|
tone: src.tone,
|
||||||
|
word_count: src.word_count,
|
||||||
|
})
|
||||||
|
setDocs((prev) => [
|
||||||
|
{ id: updated.id, title: updated.title, word_count: updated.word_count, updated_at: updated.updated_at, tags: [] },
|
||||||
|
...prev,
|
||||||
|
])
|
||||||
|
setCurrentDoc(updated)
|
||||||
|
setTitle(updated.title)
|
||||||
|
setWordCount(updated.word_count)
|
||||||
|
setTone(updated.tone || 'general')
|
||||||
|
setDocText(updated.content_text)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('duplicate failed', err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[saveNow],
|
||||||
|
)
|
||||||
|
|
||||||
const handleDelete = useCallback(
|
const handleDelete = useCallback(
|
||||||
async (id: string) => {
|
async (id: string) => {
|
||||||
await api.deleteDoc(id)
|
await api.deleteDoc(id)
|
||||||
@@ -233,7 +274,7 @@ export default function App() {
|
|||||||
if (currentDoc) {
|
if (currentDoc) {
|
||||||
patchSummary(currentDoc.id, { word_count: change.word_count })
|
patchSummary(currentDoc.id, { word_count: change.word_count })
|
||||||
schedule(change)
|
schedule(change)
|
||||||
scheduleCheckpoint()
|
scheduleCheckpoint(change.content_text)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[currentDoc, patchSummary, schedule, scheduleCheckpoint],
|
[currentDoc, patchSummary, schedule, scheduleCheckpoint],
|
||||||
@@ -338,7 +379,7 @@ export default function App() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full flex-col">
|
<div className="flex h-full flex-col">
|
||||||
<PetalFall />
|
<PetalFall night={night} />
|
||||||
<header
|
<header
|
||||||
onMouseDown={handleChromeDown}
|
onMouseDown={handleChromeDown}
|
||||||
className="petal-no-print flex h-12 shrink-0 items-center gap-2 px-5"
|
className="petal-no-print flex h-12 shrink-0 items-center gap-2 px-5"
|
||||||
@@ -358,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">
|
||||||
@@ -371,6 +429,7 @@ export default function App() {
|
|||||||
onSelect={openDoc}
|
onSelect={openDoc}
|
||||||
onCreate={handleCreate}
|
onCreate={handleCreate}
|
||||||
onDelete={handleDelete}
|
onDelete={handleDelete}
|
||||||
|
onDuplicate={handleDuplicate}
|
||||||
onToggleTag={handleToggleTag}
|
onToggleTag={handleToggleTag}
|
||||||
onCreateTag={handleCreateTag}
|
onCreateTag={handleCreateTag}
|
||||||
/>
|
/>
|
||||||
@@ -433,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}
|
||||||
@@ -446,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>
|
||||||
@@ -469,12 +531,23 @@ 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">
|
||||||
<PetalCompanion
|
<PetalCompanion
|
||||||
wordCount={wordCount}
|
wordCount={wordCount}
|
||||||
saveStatus={status}
|
saveStatus={status}
|
||||||
|
llmDown={llmDown}
|
||||||
editTick={editTick}
|
editTick={editTick}
|
||||||
acceptTick={acceptTick}
|
acceptTick={acceptTick}
|
||||||
text={docText}
|
text={docText}
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ export interface WordMeaning {
|
|||||||
export interface WordInfo {
|
export interface WordInfo {
|
||||||
word: string
|
word: string
|
||||||
gloss: string // Chinese translation; '' when the word isn't in the gloss set
|
gloss: string // Chinese translation; '' when the word isn't in the gloss set
|
||||||
|
phonetic: string // IPA for the English word; '' when absent
|
||||||
definitions: WordMeaning[]
|
definitions: WordMeaning[]
|
||||||
synonyms: string[]
|
synonyms: string[]
|
||||||
}
|
}
|
||||||
@@ -75,7 +76,30 @@ export interface Gloss {
|
|||||||
gloss: string
|
gloss: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SuggestionType = 'grammar' | 'phrasing' | 'idiom' | 'clarity' | 'voice'
|
export type SuggestionType = 'grammar' | 'phrasing' | 'idiom' | 'clarity' | 'voice' | 'collocation' | 'mechanics'
|
||||||
|
|
||||||
|
// 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
|
||||||
|
definition: string // English fallback meaning shown in review when there's no gloss
|
||||||
|
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).
|
||||||
@@ -111,6 +135,17 @@ export interface Suggestion {
|
|||||||
created_at: string
|
created_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A deterministic, rule-based fix detected client-side (see Companion/prose.ts).
|
||||||
|
// The frontend owns mechanics detection; the backend only persists these as the
|
||||||
|
// 'mechanics' suggestion family. Spans are exact plaintext offsets.
|
||||||
|
export interface MechanicsFinding {
|
||||||
|
from: number
|
||||||
|
to: number
|
||||||
|
original: string
|
||||||
|
replacement: string
|
||||||
|
explanation: string
|
||||||
|
}
|
||||||
|
|
||||||
async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
const res = await fetch(`/api${path}`, {
|
const res = await fetch(`/api${path}`, {
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
@@ -140,12 +175,28 @@ 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' }),
|
||||||
|
// Mechanics pass: persist the client-detected deterministic fixes as the
|
||||||
|
// 'mechanics' family and return the unified pending set. Not rate-limited (it's
|
||||||
|
// free, local detection); runs alongside the grammar checkpoint.
|
||||||
|
submitMechanics: (id: string, findings: MechanicsFinding[]) =>
|
||||||
|
req<Suggestion[]>(`/docs/${id}/mechanics`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ findings }),
|
||||||
|
}),
|
||||||
// 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) =>
|
||||||
req<void>(`/suggestions/${id}/accept`, { method: 'POST' }),
|
req<void>(`/suggestions/${id}/accept`, { method: 'POST' }),
|
||||||
dismissSuggestion: (id: string) =>
|
dismissSuggestion: (id: string) =>
|
||||||
req<void>(`/suggestions/${id}/dismiss`, { method: 'POST' }),
|
req<void>(`/suggestions/${id}/dismiss`, { method: 'POST' }),
|
||||||
|
// Simplified-Chinese rendering of a suggestion's explanation, for the Ask Petal
|
||||||
|
// opening bubble (the explanation itself stays English in the card body).
|
||||||
|
translateSuggestion: (id: string) =>
|
||||||
|
req<{ translation: string }>(`/suggestions/${id}/translate`, { method: 'POST' }),
|
||||||
|
|
||||||
// Version history. listVersions returns metadata only (no bodies); getVersion
|
// Version history. listVersions returns metadata only (no bodies); getVersion
|
||||||
// loads one full snapshot for preview; snapshotDoc takes an explicit restore
|
// loads one full snapshot for preview; snapshotDoc takes an explicit restore
|
||||||
@@ -164,6 +215,10 @@ export const api = {
|
|||||||
exportUrl: (id: string, format: ExportFormat) =>
|
exportUrl: (id: string, format: ExportFormat) =>
|
||||||
`/api/docs/${id}/export?format=${format}`,
|
`/api/docs/${id}/export?format=${format}`,
|
||||||
|
|
||||||
|
// Download URL for a whole-corpus backup: a zip of every document rendered in
|
||||||
|
// the given format. A one-click "download all my writing" safety net.
|
||||||
|
exportAllUrl: (format: ExportFormat) => `/api/docs/export-all?format=${format}`,
|
||||||
|
|
||||||
// Offline word lookup (gloss + definition + synonyms) for the right-click popover.
|
// Offline word lookup (gloss + definition + synonyms) for the right-click popover.
|
||||||
lookupWord: (word: string) => req<WordInfo>(`/word/${encodeURIComponent(word)}`),
|
lookupWord: (word: string) => req<WordInfo>(`/word/${encodeURIComponent(word)}`),
|
||||||
// Lightweight Chinese-only gloss for the inline hover/select tooltip — instant
|
// Lightweight Chinese-only gloss for the inline hover/select tooltip — instant
|
||||||
@@ -182,6 +237,21 @@ export const api = {
|
|||||||
// highlighted snippet. Empty query returns []. Encodes the term for the URL.
|
// highlighted snippet. Empty query returns []. Encodes the term for the URL.
|
||||||
search: (q: string) => req<SearchResult[]>(`/search?q=${encodeURIComponent(q)}`),
|
search: (q: string) => req<SearchResult[]>(`/search?q=${encodeURIComponent(q)}`),
|
||||||
|
|
||||||
|
// Image upload: posts a single image file as multipart form data and returns
|
||||||
|
// its served URL (e.g. /api/images/<hash>.png). Stored on disk by the binary,
|
||||||
|
// so the document JSON keeps a small URL reference instead of inlined base64.
|
||||||
|
// Doesn't go through req() because the body is FormData, not JSON.
|
||||||
|
uploadImage: async (file: File): Promise<{ url: string }> => {
|
||||||
|
const form = new FormData()
|
||||||
|
form.append('image', file)
|
||||||
|
const res = await fetch('/api/images', { method: 'POST', body: form })
|
||||||
|
if (!res.ok) {
|
||||||
|
const detail = await res.text().catch(() => '')
|
||||||
|
throw new Error(`${res.status} ${res.statusText}${detail ? `: ${detail}` : ''}`)
|
||||||
|
}
|
||||||
|
return res.json() as Promise<{ url: string }>
|
||||||
|
},
|
||||||
|
|
||||||
// Tags. listTags returns the roster with per-tag document counts; createTag is
|
// Tags. listTags returns the roster with per-tag document counts; createTag is
|
||||||
// idempotent on name (returns the existing tag if it already exists);
|
// idempotent on name (returns the existing tag if it already exists);
|
||||||
// updateTag recolors/renames; deleteTag removes it (assignments cascade).
|
// updateTag recolors/renames; deleteTag removes it (assignments cascade).
|
||||||
@@ -197,6 +267,24 @@ 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
|
||||||
|
definition?: 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' }),
|
||||||
|
|||||||
BIN
web/src/assets/sounds/baoding.mp3
Normal file
BIN
web/src/assets/sounds/baoding.mp3
Normal file
Binary file not shown.
BIN
web/src/assets/sounds/block.mp3
Normal file
BIN
web/src/assets/sounds/block.mp3
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
web/src/assets/sounds/error.mp3
Normal file
BIN
web/src/assets/sounds/error.mp3
Normal file
Binary file not shown.
BIN
web/src/assets/sounds/milestone.mp3
Normal file
BIN
web/src/assets/sounds/milestone.mp3
Normal file
Binary file not shown.
Binary file not shown.
BIN
web/src/assets/sounds/pop1.mp3
Normal file
BIN
web/src/assets/sounds/pop1.mp3
Normal file
Binary file not shown.
BIN
web/src/assets/sounds/pop2.mp3
Normal file
BIN
web/src/assets/sounds/pop2.mp3
Normal file
Binary file not shown.
Binary file not shown.
BIN
web/src/assets/sounds/tok.mp3
Normal file
BIN
web/src/assets/sounds/tok.mp3
Normal file
Binary file not shown.
@@ -1,16 +1,18 @@
|
|||||||
// Petal's cute sound palette. The actual tones live as tiny WAV assets in
|
// Petal's cute sound palette. These are hand-picked mp3 effects (warm bubble
|
||||||
// ./assets (generated by scripts/gen_sounds.py — warm bubble pops, water drops,
|
// pops, a wooden "tok", rolling baoding balls, a Chinese fanfare for milestones,
|
||||||
// and soft bells tuned to match the app's gentle look). Vite fingerprints and
|
// and a playful "haiya" for errors) living as assets in ./assets/sounds. Vite
|
||||||
// bundles them into dist, so they ride along inside the single Go binary; here
|
// fingerprints and bundles them into dist, so they ride along inside the single
|
||||||
// we just fetch + decode them once and play them through a Web Audio bus with a
|
// Go binary; here we just fetch + decode them once and play them through a Web
|
||||||
// soft master volume. The whole thing is opt-out-able and the mute choice
|
// Audio bus with a soft master volume. The whole thing is opt-out-able and the
|
||||||
// persists in localStorage so it survives reloads.
|
// mute choice persists in localStorage so it survives reloads.
|
||||||
|
|
||||||
import popUrl from '../assets/sounds/pop.wav'
|
import pop1Url from '../assets/sounds/pop1.mp3'
|
||||||
import dropletUrl from '../assets/sounds/droplet.wav'
|
import pop2Url from '../assets/sounds/pop2.mp3'
|
||||||
import chimeUrl from '../assets/sounds/chime.wav'
|
import tokUrl from '../assets/sounds/tok.mp3'
|
||||||
import shimmerUrl from '../assets/sounds/shimmer.wav'
|
import blockUrl from '../assets/sounds/block.mp3'
|
||||||
import cheerUrl from '../assets/sounds/cheer.wav'
|
import baodingUrl from '../assets/sounds/baoding.mp3'
|
||||||
|
import milestoneUrl from '../assets/sounds/milestone.mp3'
|
||||||
|
import errorUrl from '../assets/sounds/error.mp3'
|
||||||
|
|
||||||
const STORAGE_KEY = 'petal.sound'
|
const STORAGE_KEY = 'petal.sound'
|
||||||
|
|
||||||
@@ -18,20 +20,32 @@ const STORAGE_KEY = 'petal.sound'
|
|||||||
const MASTER_GAIN = 0.5
|
const MASTER_GAIN = 0.5
|
||||||
|
|
||||||
export type SoundName =
|
export type SoundName =
|
||||||
| 'pop' // a soft bubble pop — the signature "something arrived"
|
| 'pop1' // a soft bubble pop
|
||||||
| 'droplet' // a single rounded water-drop ping
|
| 'pop2' // a second bubble pop, slightly different
|
||||||
| 'chime' // a gentle two-note bell
|
| 'tok' // a light wooden "tok"
|
||||||
| 'shimmer' // three quick ascending sparkles
|
| 'block' // a quick Chinese wood-block tap
|
||||||
| 'cheer' // a happy little major arpeggio (accepts, milestones)
|
| 'baoding' // rolling baoding-ball shimmer
|
||||||
|
| 'milestone' // a happy Chinese fanfare (word-count milestones)
|
||||||
|
| 'error' // a playful "haiya" — something went wrong
|
||||||
|
|
||||||
const SOURCES: Record<SoundName, string> = {
|
const SOURCES: Record<SoundName, string> = {
|
||||||
pop: popUrl,
|
pop1: pop1Url,
|
||||||
droplet: dropletUrl,
|
pop2: pop2Url,
|
||||||
chime: chimeUrl,
|
tok: tokUrl,
|
||||||
shimmer: shimmerUrl,
|
block: blockUrl,
|
||||||
cheer: cheerUrl,
|
baoding: baodingUrl,
|
||||||
|
milestone: milestoneUrl,
|
||||||
|
error: errorUrl,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The pool of light "something happened" notification sounds. We rotate through
|
||||||
|
// these (skipping the one just played) so the same blip never repeats back to
|
||||||
|
// back — a batch of suggestions or a run of tips stays lively instead of
|
||||||
|
// hammering one note. milestone/error are deliberately NOT in the pool: they're
|
||||||
|
// reserved for their specific moments.
|
||||||
|
const POP_POOL: SoundName[] = ['pop1', 'pop2', 'tok', 'block', 'baoding']
|
||||||
|
let lastPop = -1
|
||||||
|
|
||||||
let ctx: AudioContext | null = null
|
let ctx: AudioContext | null = null
|
||||||
let master: GainNode | null = null
|
let master: GainNode | null = null
|
||||||
const buffers = new Map<SoundName, AudioBuffer>()
|
const buffers = new Map<SoundName, AudioBuffer>()
|
||||||
@@ -147,18 +161,24 @@ export function playSound(name: SoundName): void {
|
|||||||
})()
|
})()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Map an editor suggestion type to its sound, so each kind of help has its own
|
// Play the next notification pop from the pool, never repeating the last one, so
|
||||||
// little voice (grammar pops like a bubble, idioms chime, etc.).
|
// consecutive blips always sound different. This is the everyday "something
|
||||||
const SUGGESTION_SOUND: Record<string, SoundName> = {
|
// arrived" voice for suggestions, tips, and gentle cheers.
|
||||||
grammar: 'pop',
|
export function playPop(): void {
|
||||||
phrasing: 'droplet',
|
let i = lastPop
|
||||||
idiom: 'chime',
|
// Tiny pool, so a short scan to pick anything but the last is plenty.
|
||||||
clarity: 'shimmer',
|
for (let tries = 0; tries < POP_POOL.length && i === lastPop; tries++) {
|
||||||
voice: 'droplet',
|
i = Math.floor(Math.random() * POP_POOL.length)
|
||||||
|
}
|
||||||
|
lastPop = i
|
||||||
|
playSound(POP_POOL[i])
|
||||||
}
|
}
|
||||||
|
|
||||||
export function playSuggestionSound(type: string): void {
|
// Each freshly-surfaced suggestion just gets a rotating pop — the variety comes
|
||||||
playSound(SUGGESTION_SOUND[type] ?? 'pop')
|
// from the pool, not from the suggestion type, so a batch of same-type fixes
|
||||||
|
// still sounds lively.
|
||||||
|
export function playSuggestionSound(_type: string): void {
|
||||||
|
playPop()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unlock + warm audio on the first user gesture so the very first sound isn't
|
// Unlock + warm audio on the first user gesture so the very first sound isn't
|
||||||
|
|||||||
120
web/src/audio/speech.ts
Normal file
120
web/src/audio/speech.ts
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
// Read-aloud for an ESL writer: hear how an English word or passage sounds.
|
||||||
|
//
|
||||||
|
// Primary path is server-side neural TTS (Piper, proxied at /api/tts) — natural,
|
||||||
|
// consistent across devices, and far better than the browser's built-in voices
|
||||||
|
// (which fall back to robotic espeak on Chromium). If the server route is absent
|
||||||
|
// (TTS disabled) or unreachable, we fall back to the browser's Web Speech API so
|
||||||
|
// the buttons still do something. No model or network is strictly required.
|
||||||
|
|
||||||
|
// speechSupported reports whether read-aloud can do anything at all. Audio
|
||||||
|
// playback is universal, so as long as we can construct an Audio element OR the
|
||||||
|
// Web Speech API exists, the buttons should show. The server path is tried at
|
||||||
|
// call time and degrades on its own.
|
||||||
|
export function speechSupported(): boolean {
|
||||||
|
if (typeof window === 'undefined') return false
|
||||||
|
return typeof window.Audio === 'function' || 'speechSynthesis' in window
|
||||||
|
}
|
||||||
|
|
||||||
|
// webSpeechSupported gates the fallback path specifically.
|
||||||
|
function webSpeechSupported(): boolean {
|
||||||
|
return typeof window !== 'undefined' && 'speechSynthesis' in window && 'SpeechSynthesisUtterance' in window
|
||||||
|
}
|
||||||
|
|
||||||
|
// current holds the in-flight server-audio element and its object URL so a rapid
|
||||||
|
// re-tap can stop and replace it (mirroring speechSynthesis.cancel()).
|
||||||
|
let current: { audio: HTMLAudioElement; url: string } | null = null
|
||||||
|
|
||||||
|
// requestSeq increments on every speak() call so a slow fetch that resolves after
|
||||||
|
// a newer tap can detect it's stale and bow out instead of double-playing.
|
||||||
|
let requestSeq = 0
|
||||||
|
|
||||||
|
// stopSpeech halts any read-aloud in flight — both the server-audio element and
|
||||||
|
// the Web Speech fallback — and bumps requestSeq so a fetch still in flight bows
|
||||||
|
// out instead of playing late. Exported so a panel can cancel audio on unmount,
|
||||||
|
// keeping a word's pronunciation from outliving the panel that started it.
|
||||||
|
export function stopSpeech(): void {
|
||||||
|
requestSeq++
|
||||||
|
if (current) {
|
||||||
|
current.audio.pause()
|
||||||
|
URL.revokeObjectURL(current.url)
|
||||||
|
current = null
|
||||||
|
}
|
||||||
|
if (webSpeechSupported()) window.speechSynthesis.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
// pickVoice prefers an exact locale match (e.g. en-US), then any voice in the
|
||||||
|
// same language family (en-*). Returns undefined to let the engine default.
|
||||||
|
function pickVoice(lang: string): SpeechSynthesisVoice | undefined {
|
||||||
|
const voices = window.speechSynthesis.getVoices()
|
||||||
|
const base = lang.split('-')[0]
|
||||||
|
return voices.find((v) => v.lang === lang) || voices.find((v) => v.lang?.startsWith(base))
|
||||||
|
}
|
||||||
|
|
||||||
|
// speakWebSpeech is the fallback: the browser's built-in synthesizer. A touch
|
||||||
|
// slower than default so learners can follow along.
|
||||||
|
function speakWebSpeech(text: string, lang: string): void {
|
||||||
|
if (!webSpeechSupported()) return
|
||||||
|
const synth = window.speechSynthesis
|
||||||
|
synth.cancel()
|
||||||
|
const utterance = new SpeechSynthesisUtterance(text)
|
||||||
|
utterance.lang = lang
|
||||||
|
const voice = pickVoice(lang)
|
||||||
|
if (voice) utterance.voice = voice
|
||||||
|
utterance.rate = 0.95
|
||||||
|
synth.speak(utterance)
|
||||||
|
}
|
||||||
|
|
||||||
|
// detectLang guesses a BCP-47 locale from the text so the right Piper voice is
|
||||||
|
// chosen. Any Han/kana character routes to Chinese (zh-CN) — a selection is
|
||||||
|
// essentially never mixed at the level that matters, and reading a Chinese
|
||||||
|
// passage with the English voice spells each character out ("Chinese letter…").
|
||||||
|
// Everything else defaults to US English, the language she's learning.
|
||||||
|
const CJK = /[-ヿ㐀-䶿一-鿿豈-ヲ-゚]/
|
||||||
|
export function detectLang(text: string): string {
|
||||||
|
return CJK.test(text) ? 'zh-CN' : 'en-US'
|
||||||
|
}
|
||||||
|
|
||||||
|
// speak reads `text` aloud, cancelling anything already in flight so rapid taps
|
||||||
|
// don't queue up. `lang` defaults to a guess from the text (Chinese vs English)
|
||||||
|
// so callers can just pass the selection; pass an explicit locale to override.
|
||||||
|
// It tries the server's neural voice first and silently falls back to the browser
|
||||||
|
// voice if that's unavailable (route off, network error, or a 404 for a language
|
||||||
|
// with no configured voice).
|
||||||
|
export function speak(text: string, lang = detectLang(text)): void {
|
||||||
|
if (!text.trim()) return
|
||||||
|
stopSpeech()
|
||||||
|
const seq = ++requestSeq
|
||||||
|
|
||||||
|
fetch('/api/tts', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ text, lang }),
|
||||||
|
})
|
||||||
|
.then((res) => {
|
||||||
|
if (!res.ok) throw new Error(`tts ${res.status}`)
|
||||||
|
return res.blob()
|
||||||
|
})
|
||||||
|
.then((blob) => {
|
||||||
|
// A newer tap superseded this one while the fetch was in flight — drop it.
|
||||||
|
if (seq !== requestSeq) return
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const audio = new Audio(url)
|
||||||
|
current = { audio, url }
|
||||||
|
// Release the blob once playback finishes (or errors) to avoid leaking.
|
||||||
|
const cleanup = () => {
|
||||||
|
if (current?.audio === audio) {
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
current = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
audio.addEventListener('ended', cleanup)
|
||||||
|
audio.addEventListener('error', cleanup)
|
||||||
|
return audio.play()
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
// Server TTS unavailable for this request — use the browser voice instead,
|
||||||
|
// unless a newer tap has already superseded this one.
|
||||||
|
if (seq !== requestSeq) return
|
||||||
|
speakWebSpeech(text, lang)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -11,6 +11,8 @@ interface Props {
|
|||||||
animationData?: object
|
animationData?: object
|
||||||
loop?: boolean
|
loop?: boolean
|
||||||
className?: string
|
className?: string
|
||||||
|
// Mirror the animation left↔right (for assets drawn facing the wrong way).
|
||||||
|
flip?: boolean
|
||||||
fallback: React.ReactNode
|
fallback: React.ReactNode
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +50,7 @@ function fitToContent(anim: AnimationItem, svg: SVGSVGElement) {
|
|||||||
// A thin wrapper over lottie-web (framework-agnostic, no React peer deps, fully
|
// A thin wrapper over lottie-web (framework-agnostic, no React peer deps, fully
|
||||||
// offline). Reloads the animation whenever the data changes — moods swap by
|
// offline). Reloads the animation whenever the data changes — moods swap by
|
||||||
// passing a different `animationData`.
|
// passing a different `animationData`.
|
||||||
export function LottiePlayer({ animationData, loop = true, className, fallback }: Props) {
|
export function LottiePlayer({ animationData, loop = true, className, flip, fallback }: Props) {
|
||||||
const ref = useRef<HTMLDivElement>(null)
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
const anim = useRef<AnimationItem | null>(null)
|
const anim = useRef<AnimationItem | null>(null)
|
||||||
|
|
||||||
@@ -74,5 +76,12 @@ export function LottiePlayer({ animationData, loop = true, className, fallback }
|
|||||||
}, [animationData, loop])
|
}, [animationData, loop])
|
||||||
|
|
||||||
if (!animationData) return <>{fallback}</>
|
if (!animationData) return <>{fallback}</>
|
||||||
return <div ref={ref} className={className} aria-hidden />
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={className}
|
||||||
|
style={flip ? { transform: 'scaleX(-1)' } : undefined}
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { COMPANIONS, DEFAULT_COMPANION } from './companions'
|
|||||||
interface Props {
|
interface Props {
|
||||||
wordCount: number
|
wordCount: number
|
||||||
saveStatus: SaveStatus
|
saveStatus: SaveStatus
|
||||||
|
llmDown: boolean
|
||||||
editTick: number
|
editTick: number
|
||||||
acceptTick: number
|
acceptTick: number
|
||||||
text: string
|
text: string
|
||||||
@@ -27,10 +28,11 @@ const STORAGE_KEY = 'petal.companion'
|
|||||||
// useCompanion and shows a Mandarin-first speech bubble for cheers, tips, and
|
// useCompanion and shows a Mandarin-first speech bubble for cheers, tips, and
|
||||||
// break reminders. Clicking the mascot opens a picker to switch companions
|
// break reminders. Clicking the mascot opens a picker to switch companions
|
||||||
// (the choice persists in localStorage).
|
// (the choice persists in localStorage).
|
||||||
export function PetalCompanion({ wordCount, saveStatus, editTick, acceptTick, text }: Props) {
|
export function PetalCompanion({ wordCount, saveStatus, llmDown, editTick, acceptTick, text }: Props) {
|
||||||
const { mood, bubble, dismiss, holdBubble, releaseBubble } = useCompanion({
|
const { mood, bubble, dismiss, holdBubble, releaseBubble } = useCompanion({
|
||||||
wordCount,
|
wordCount,
|
||||||
saveStatus,
|
saveStatus,
|
||||||
|
llmDown,
|
||||||
editTick,
|
editTick,
|
||||||
acceptTick,
|
acceptTick,
|
||||||
text,
|
text,
|
||||||
@@ -145,7 +147,7 @@ export function PetalCompanion({ wordCount, saveStatus, editTick, acceptTick, te
|
|||||||
onClick={dismiss}
|
onClick={dismiss}
|
||||||
onMouseEnter={holdBubble}
|
onMouseEnter={holdBubble}
|
||||||
onMouseLeave={releaseBubble}
|
onMouseLeave={releaseBubble}
|
||||||
className="petal-bubble pointer-events-auto max-w-[260px] cursor-pointer p-3 pr-3.5"
|
className="petal-bubble pointer-events-auto max-w-[420px] cursor-pointer p-4 pr-5"
|
||||||
style={{
|
style={{
|
||||||
background: 'var(--color-surface)',
|
background: 'var(--color-surface)',
|
||||||
border: '1px solid var(--color-border)',
|
border: '1px solid var(--color-border)',
|
||||||
@@ -156,10 +158,16 @@ export function PetalCompanion({ wordCount, saveStatus, editTick, acceptTick, te
|
|||||||
}}
|
}}
|
||||||
title="Click to dismiss"
|
title="Click to dismiss"
|
||||||
>
|
>
|
||||||
<p className="text-sm font-bold leading-snug" style={{ color: 'var(--color-plum)' }}>
|
<p
|
||||||
|
className="font-bold leading-snug"
|
||||||
|
style={{ color: 'var(--color-plum)', fontSize: '1.4rem' }}
|
||||||
|
>
|
||||||
{bubble.zh}
|
{bubble.zh}
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-0.5 text-xs leading-snug" style={{ color: 'var(--color-muted)' }}>
|
<p
|
||||||
|
className="mt-0.5 leading-snug"
|
||||||
|
style={{ color: 'var(--color-muted)', fontSize: '1.15rem' }}
|
||||||
|
>
|
||||||
{bubble.en}
|
{bubble.en}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -172,8 +180,9 @@ export function PetalCompanion({ wordCount, saveStatus, editTick, acceptTick, te
|
|||||||
aria-label="Choose a companion"
|
aria-label="Choose a companion"
|
||||||
className={`petal-companion pointer-events-auto select-none ${napping ? 'petal-companion-sleep' : ''}`}
|
className={`petal-companion pointer-events-auto select-none ${napping ? 'petal-companion-sleep' : ''}`}
|
||||||
style={{
|
style={{
|
||||||
width: 144,
|
// Size scales with the viewport — see --petal-companion-size in index.css.
|
||||||
height: 144,
|
width: 'var(--petal-companion-size)',
|
||||||
|
height: 'var(--petal-companion-size)',
|
||||||
padding: 0,
|
padding: 0,
|
||||||
borderRadius: 'var(--radius-pill)',
|
borderRadius: 'var(--radius-pill)',
|
||||||
background: 'var(--color-surface-alt)',
|
background: 'var(--color-surface-alt)',
|
||||||
@@ -187,8 +196,13 @@ export function PetalCompanion({ wordCount, saveStatus, editTick, acceptTick, te
|
|||||||
<LottiePlayer
|
<LottiePlayer
|
||||||
key={companion.id}
|
key={companion.id}
|
||||||
animationData={animationData}
|
animationData={animationData}
|
||||||
className="h-32 w-32"
|
flip={companion.flip}
|
||||||
fallback={<span style={{ fontSize: 72, lineHeight: 1 }}>{MOOD_EMOJI[renderMood]}</span>}
|
className="petal-companion-art"
|
||||||
|
fallback={
|
||||||
|
<span style={{ fontSize: 'calc(var(--petal-companion-size) * 0.5)', lineHeight: 1 }}>
|
||||||
|
{MOOD_EMOJI[renderMood]}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
{napping && (
|
{napping && (
|
||||||
<span className="petal-zzz absolute" aria-hidden style={{ color: 'var(--color-muted)' }}>
|
<span className="petal-zzz absolute" aria-hidden style={{ color: 'var(--color-muted)' }}>
|
||||||
|
|||||||
1
web/src/components/Companion/animations/butterfly.json
Normal file
1
web/src/components/Companion/animations/butterfly.json
Normal file
File diff suppressed because one or more lines are too long
1
web/src/components/Companion/animations/parrot.json
Normal file
1
web/src/components/Companion/animations/parrot.json
Normal file
File diff suppressed because one or more lines are too long
1
web/src/components/Companion/animations/wiggle-dog.json
Normal file
1
web/src/components/Companion/animations/wiggle-dog.json
Normal file
File diff suppressed because one or more lines are too long
@@ -1,6 +1,9 @@
|
|||||||
import type { Mood } from './useCompanion'
|
import type { Mood } from './useCompanion'
|
||||||
import sleepingCat from './animations/sleeping-cat.json'
|
import sleepingCat from './animations/sleeping-cat.json'
|
||||||
import happyDog from './animations/happy-dog.json'
|
import happyDog from './animations/happy-dog.json'
|
||||||
|
import wiggleDog from './animations/wiggle-dog.json'
|
||||||
|
import butterfly from './animations/butterfly.json'
|
||||||
|
import parrot from './animations/parrot.json'
|
||||||
|
|
||||||
export interface Companion {
|
export interface Companion {
|
||||||
id: string
|
id: string
|
||||||
@@ -12,6 +15,9 @@ export interface Companion {
|
|||||||
// When true the mascot keeps its calm sway + drifting zzz regardless of mood
|
// When true the mascot keeps its calm sway + drifting zzz regardless of mood
|
||||||
// (e.g. a cat that's always asleep but still talks in its sleep).
|
// (e.g. a cat that's always asleep but still talks in its sleep).
|
||||||
alwaysAsleep?: boolean
|
alwaysAsleep?: boolean
|
||||||
|
// When true the rendered animation is mirrored left↔right — for assets drawn
|
||||||
|
// facing the "wrong" way for our bottom-right corner (e.g. the parrot).
|
||||||
|
flip?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
// The roster. Add a companion by dropping a pure-vector Lottie JSON into
|
// The roster. Add a companion by dropping a pure-vector Lottie JSON into
|
||||||
@@ -44,6 +50,43 @@ export const COMPANIONS: Companion[] = [
|
|||||||
// no sleeping clip → stays in its idle pose instead of visibly napping
|
// no sleeping clip → stays in its idle pose instead of visibly napping
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'wiggle-dog',
|
||||||
|
name: 'Wiggle Dog',
|
||||||
|
zh: '摇尾狗',
|
||||||
|
emoji: '🐕',
|
||||||
|
animations: {
|
||||||
|
idle: wiggleDog,
|
||||||
|
happy: wiggleDog,
|
||||||
|
talking: wiggleDog,
|
||||||
|
celebrate: wiggleDog,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'butterfly',
|
||||||
|
name: 'Butterfly',
|
||||||
|
zh: '蝴蝶',
|
||||||
|
emoji: '🦋',
|
||||||
|
animations: {
|
||||||
|
idle: butterfly,
|
||||||
|
happy: butterfly,
|
||||||
|
talking: butterfly,
|
||||||
|
celebrate: butterfly,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'parrot',
|
||||||
|
name: 'Parrot',
|
||||||
|
zh: '鹦鹉',
|
||||||
|
emoji: '🦜',
|
||||||
|
flip: true, // asset faces left; mirror it to face into the page
|
||||||
|
animations: {
|
||||||
|
idle: parrot,
|
||||||
|
happy: parrot,
|
||||||
|
talking: parrot,
|
||||||
|
celebrate: parrot,
|
||||||
|
},
|
||||||
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
export const DEFAULT_COMPANION = 'cat'
|
export const DEFAULT_COMPANION = 'cat'
|
||||||
|
|||||||
@@ -248,3 +248,119 @@ describe('capitalization basics', () => {
|
|||||||
expectRule('The sun set slowly. it was a beautiful evening down by the river.', 'cap-sentence')
|
expectRule('The sun set slowly. it was a beautiful evening down by the river.', 'cap-sentence')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
import { mechanicsFindings } from './prose'
|
||||||
|
|
||||||
|
// mechanicsFindings is the applyable subset feeding the suggestion cards. Each
|
||||||
|
// finding must carry an EXACT span (text.slice(from,to) === original) and a
|
||||||
|
// replacement that actually changes the text — these become one-click edits.
|
||||||
|
describe('mechanicsFindings — applyable fixes', () => {
|
||||||
|
// Every finding's span must be exact, regardless of which rule produced it.
|
||||||
|
function expectExactSpans(text: string) {
|
||||||
|
const found = mechanicsFindings(text)
|
||||||
|
for (const f of found) {
|
||||||
|
expect(text.slice(f.from, f.to), `span for ${JSON.stringify(f)}`).toBe(f.original)
|
||||||
|
expect(f.replacement).not.toBe(f.original)
|
||||||
|
}
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
const one = (text: string, rulePred: (f: ReturnType<typeof mechanicsFindings>[number]) => boolean) =>
|
||||||
|
expectExactSpans(text).find(rulePred)
|
||||||
|
|
||||||
|
it('doubled word → single word, exact span', () => {
|
||||||
|
const f = one('I saw the the cat in the garden today.', (f) => f.original === 'the the')
|
||||||
|
expect(f?.replacement).toBe('the')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('finds BOTH doublings with distinct spans', () => {
|
||||||
|
const found = mechanicsFindings('the the dog and the the cat ran around the yard.')
|
||||||
|
.filter((f) => f.original === 'the the')
|
||||||
|
expect(found).toHaveLength(2)
|
||||||
|
expect(found[0].from).not.toBe(found[1].from)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Spans are widened to a distinctive phrase so they re-anchor by string in the
|
||||||
|
// editor (a bare "a"/"i"/" is" would match the wrong spot). The replacement
|
||||||
|
// carries the whole corrected phrase.
|
||||||
|
|
||||||
|
it('lowercase standalone i is awareness-only (no card)', () => {
|
||||||
|
// It still flags as a companion bubble (see analyzeProse), but a single
|
||||||
|
// character can't be anchored, so it must NOT become a card.
|
||||||
|
expect(mechanicsFindings('Yesterday i walked to the store and came home.').length).toBe(0)
|
||||||
|
expect(rulesFor('Yesterday i walked to the store and came home.')).toContain('cap-i')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a → an: spans the whole "a <noun>" phrase', () => {
|
||||||
|
const f = one('She found a umbrella under the old wooden table.', (f) => f.original === 'a umbrella')
|
||||||
|
expect(f?.replacement).toBe('an umbrella')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uncountable plural → singular', () => {
|
||||||
|
const f = one('She gave me many informations about the new job.', (f) => f.original === 'informations')
|
||||||
|
expect(f?.replacement).toBe('information')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lowercase proper noun → capitalized', () => {
|
||||||
|
const f = one('I am learning english during my free time this year.', (f) => f.original === 'english')
|
||||||
|
expect(f?.replacement).toBe('English')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('subject-verb agreement → corrects the verb, spans subject+verb', () => {
|
||||||
|
const f = one('She have three cats and a dog at her house.', (f) => f.original === 'She have')
|
||||||
|
expect(f?.replacement).toBe('She has')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('singular noun after a number → plural, spans number+noun', () => {
|
||||||
|
const f = one('I bought five apple at the market this morning.', (f) => f.original === 'five apple')
|
||||||
|
expect(f?.replacement).toBe('five apples')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('comparative + then → than, spans the phrase', () => {
|
||||||
|
const f = one('This book is better then the one I read last week.', (f) => f.original === 'better then')
|
||||||
|
expect(f?.replacement).toBe('better than')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('space before punctuation is removed (spans the word)', () => {
|
||||||
|
const f = one('I love it , it makes me very happy indeed.', (f) => f.original === 'it ,')
|
||||||
|
expect(f?.replacement).toBe('it,')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('missing space after a comma is added (spans both words)', () => {
|
||||||
|
const f = one('I bought apples,bananas and pears at the store.', (f) => f.original === 'apples,bananas')
|
||||||
|
expect(f?.replacement).toBe('apples, bananas')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('stacked determiner drops the article', () => {
|
||||||
|
const f = one('She left the my book on the kitchen table again.', (f) => f.original === 'the my')
|
||||||
|
expect(f?.replacement).toBe('my')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('there is + plural → there are, spans the phrase', () => {
|
||||||
|
const f = one('There is many people waiting outside in the cold.', (f) => f.original === 'There is many')
|
||||||
|
expect(f?.replacement).toBe('There are many')
|
||||||
|
})
|
||||||
|
|
||||||
|
it("it's own → its own, spans the phrase", () => {
|
||||||
|
const f = one("The cat licked it's own paw very slowly today.", (f) => f.original === "it's own")
|
||||||
|
expect(f?.replacement).toBe('its own')
|
||||||
|
})
|
||||||
|
|
||||||
|
it("its a → it's a, spans the phrase", () => {
|
||||||
|
const f = one('I think its a wonderful day to go outside now.', (f) => f.original === 'its a')
|
||||||
|
expect(f?.replacement).toBe("it's a")
|
||||||
|
})
|
||||||
|
|
||||||
|
// Awareness-only rules never produce cards — they stay companion bubbles.
|
||||||
|
it('run-ons and splices produce NO card findings', () => {
|
||||||
|
const runOn = 'I went to the market and I bought some apples and then I saw my friend and we talked for a while and after that we went to the cafe and ordered coffee and cake together.'
|
||||||
|
expect(mechanicsFindings(runOn).some((f) => f.original.length > 30)).toBe(false)
|
||||||
|
const splice = 'I finished the report, I sent it to my boss right away today.'
|
||||||
|
// no card spans the comma-join; only (if any) small word-level fixes
|
||||||
|
expect(mechanicsFindings(splice).every((f) => f.to - f.from < 12)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clean prose yields no findings', () => {
|
||||||
|
expect(mechanicsFindings('The garden was quiet and the rain fell softly on the leaves.')).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -8,6 +8,14 @@
|
|||||||
// Each finding becomes a Mandarin-first bubble Line (see tips.ts), often quoting
|
// Each finding becomes a Mandarin-first bubble Line (see tips.ts), often quoting
|
||||||
// a short slice of her own sentence so the advice clearly belongs to *this*
|
// a short slice of her own sentence so the advice clearly belongs to *this*
|
||||||
// paragraph and not a generic tip jar.
|
// paragraph and not a generic tip jar.
|
||||||
|
//
|
||||||
|
// Two consumers share these rules (one source of truth, no duplication):
|
||||||
|
// • the companion bubbles — awareness notes, shown one at a time (analyzeProse)
|
||||||
|
// • the suggestion cards — applyable one-click fixes (mechanicsFindings)
|
||||||
|
// A rule is "applyable" when it can name an exact span and a single replacement;
|
||||||
|
// it attaches a `fix` and feeds the cards. Awareness-only rules (run-ons, comma
|
||||||
|
// splices, …) carry no `fix` and stay companion bubbles. The companion hides
|
||||||
|
// fix-bearing hints so the same span never appears as both a bubble and a card.
|
||||||
|
|
||||||
import type { Line } from './tips'
|
import type { Line } from './tips'
|
||||||
|
|
||||||
@@ -17,6 +25,28 @@ export interface ProseHint extends Line {
|
|||||||
id: string
|
id: string
|
||||||
// Rule family, used to vary advice (don't show the same kind twice in a row).
|
// Rule family, used to vary advice (don't show the same kind twice in a row).
|
||||||
rule: string
|
rule: string
|
||||||
|
// Present only on *applyable* findings: the exact span and the text to swap in.
|
||||||
|
// These become suggestion cards; the companion skips them (see useCompanion).
|
||||||
|
fix?: Fix
|
||||||
|
}
|
||||||
|
|
||||||
|
// An exact, one-click edit: replace text[from:to] with `replacement`.
|
||||||
|
export interface Fix {
|
||||||
|
from: number
|
||||||
|
to: number
|
||||||
|
replacement: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// A deterministic suggestion-card finding, derived from an applyable hint. Mirrors
|
||||||
|
// the backend's card shape (original/replacement/explanation + span) so the card
|
||||||
|
// pipeline can persist it as the 'mechanics' family. `explanation` is the English
|
||||||
|
// note; the card's own translate action renders Mandarin on demand.
|
||||||
|
export interface MechanicsFinding {
|
||||||
|
from: number
|
||||||
|
to: number
|
||||||
|
original: string
|
||||||
|
replacement: string
|
||||||
|
explanation: string
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── small text helpers ──────────────────────────────────────────────────────
|
// ── small text helpers ──────────────────────────────────────────────────────
|
||||||
@@ -48,11 +78,23 @@ function key(s: string): string {
|
|||||||
return s.toLowerCase().replace(/\s+/g, ' ').trim().slice(0, 48)
|
return s.toLowerCase().replace(/\s+/g, ' ').trim().slice(0, 48)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Capitalize `repl`'s first letter when `original` started uppercase, so fixing a
|
||||||
|
// sentence-initial word doesn't quietly lowercase the line.
|
||||||
|
function matchCase(original: string, repl: string): string {
|
||||||
|
if (!original || !repl) return repl
|
||||||
|
const c = original[0]
|
||||||
|
if (c >= 'A' && c <= 'Z') return repl[0].toUpperCase() + repl.slice(1)
|
||||||
|
return repl
|
||||||
|
}
|
||||||
|
|
||||||
// ── individual rules ────────────────────────────────────────────────────────
|
// ── individual rules ────────────────────────────────────────────────────────
|
||||||
// Each rule pushes at most a couple of findings; the caller shows one at a time.
|
// Each rule pushes its findings; awareness rules cap themselves to a couple so a
|
||||||
|
// single sentence can't flood the bubble, while applyable rules report every
|
||||||
|
// occurrence (each becomes its own card). Applyable rules attach a `fix`.
|
||||||
|
|
||||||
// Run-on / overly long sentences — the single most common readability problem
|
// Run-on / overly long sentences — the single most common readability problem
|
||||||
// for ESL writers, who often chain clauses that a period would serve better.
|
// for ESL writers, who often chain clauses that a period would serve better.
|
||||||
|
// Awareness-only: there is no single mechanical fix for "split this sentence".
|
||||||
function runOns(text: string, out: ProseHint[]) {
|
function runOns(text: string, out: ProseHint[]) {
|
||||||
let found = 0
|
let found = 0
|
||||||
for (const s of sentences(text)) {
|
for (const s of sentences(text)) {
|
||||||
@@ -110,6 +152,7 @@ const INTRO_LEAD = new Set([
|
|||||||
// approximate that by requiring the lead to be ≥3 words and not begin with an
|
// approximate that by requiring the lead to be ≥3 words and not begin with an
|
||||||
// introductory word — short or transition-led leads are intro phrases, not
|
// introductory word — short or transition-led leads are intro phrases, not
|
||||||
// spliced clauses. Precision over recall: a wrong nudge costs more than a miss.
|
// spliced clauses. Precision over recall: a wrong nudge costs more than a miss.
|
||||||
|
// Awareness-only: the fix is ambiguous (period vs. a joining word).
|
||||||
function commaSplices(text: string, out: ProseHint[]) {
|
function commaSplices(text: string, out: ProseHint[]) {
|
||||||
let found = 0
|
let found = 0
|
||||||
for (const s of sentences(text)) {
|
for (const s of sentences(text)) {
|
||||||
@@ -137,6 +180,7 @@ function commaSplices(text: string, out: ProseHint[]) {
|
|||||||
// Unclear antecedent — a sentence that opens with This/That/These/Those riding
|
// Unclear antecedent — a sentence that opens with This/That/These/Those riding
|
||||||
// straight into a verb, with no noun naming what it points back to. Only flag
|
// straight into a verb, with no noun naming what it points back to. Only flag
|
||||||
// when there's a prior sentence (so an antecedent is actually in question).
|
// when there's a prior sentence (so an antecedent is actually in question).
|
||||||
|
// Awareness-only: naming the referent needs the writer.
|
||||||
const ANTECEDENT_RE =
|
const ANTECEDENT_RE =
|
||||||
/^(This|That|These|Those)\s+(is|are|was|were|will|would|can|could|should|makes?|made|means?|shows?|showed|gives?|gave|causes?|caused|creates?|created|leads?|led|results?|happens?|happened|helps?|helped)\b/
|
/^(This|That|These|Those)\s+(is|are|was|were|will|would|can|could|should|makes?|made|means?|shows?|showed|gives?|gave|causes?|caused|creates?|created|leads?|led|results?|happens?|happened|helps?|helped)\b/
|
||||||
|
|
||||||
@@ -160,7 +204,8 @@ function antecedents(text: string, out: ProseHint[]) {
|
|||||||
|
|
||||||
// Oxford comma — a 3+ item list ending “… X and Y” with no comma before the
|
// Oxford comma — a 3+ item list ending “… X and Y” with no comma before the
|
||||||
// conjunction. Guarded by a clause-starter stoplist so we don't mistake a
|
// conjunction. Guarded by a clause-starter stoplist so we don't mistake a
|
||||||
// compound clause (“…, but she and I…”) for a list.
|
// compound clause (“…, but she and I…”) for a list. Awareness-only: inserting
|
||||||
|
// the serial comma is borderline-stylistic, so we nudge rather than auto-edit.
|
||||||
const OXFORD_RE = /(\w+),\s+([\w'’-]+(?:\s+[\w'’-]+){0,2})\s+(and|or)\s+[\w'’-]+/g
|
const OXFORD_RE = /(\w+),\s+([\w'’-]+(?:\s+[\w'’-]+){0,2})\s+(and|or)\s+[\w'’-]+/g
|
||||||
const CLAUSE_STARTERS = new Set([
|
const CLAUSE_STARTERS = new Set([
|
||||||
'but', 'so', 'because', 'which', 'who', 'that', 'when', 'while', 'if',
|
'but', 'so', 'because', 'which', 'who', 'that', 'when', 'while', 'if',
|
||||||
@@ -187,81 +232,32 @@ function oxford(text: string, out: ProseHint[]) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// a vs. an — chosen by the *sound* of the next word. We work only on lowercase
|
// A transition word opening a sentence with no comma after it (“However we…”).
|
||||||
// words (sidestepping proper nouns / acronyms) and keep sound-exception lists.
|
// Limited to conjunctive adverbs that strongly want the comma — sequence words
|
||||||
const A_BEFORE_VOWEL_RE = /\ba\s+([aeiou][a-z]+)\b/g
|
// like “Then/First/Finally” are left out (their comma is optional). Awareness-
|
||||||
// Vowel-spelled but consonant-sounding → “a” is correct, don't flag.
|
// only: it fires per-sentence (offsets are sentence-relative), so we nudge.
|
||||||
const CONSONANT_SOUND_RE = /^(uni|use|usu|util|euro?|eul|ewe|once|one|ubiqu|unanim)/
|
const INTRO_RE =
|
||||||
const AN_BEFORE_CONSONANT_RE = /\ban\s+([b-df-hj-np-tv-z][a-z]+)\b/g
|
/^(However|Therefore|Moreover|Furthermore|Nevertheless|Nonetheless|Meanwhile|Consequently|In addition|In conclusion|As a result|On the other hand|For example|For instance)\s+[A-Za-z]/
|
||||||
// Consonant-spelled but vowel-sounding (silent h) → “an” is correct, don't flag.
|
|
||||||
const VOWEL_SOUND_RE = /^(hour|honest|honou?r|heir|homage)/
|
|
||||||
|
|
||||||
function articles(text: string, out: ProseHint[]) {
|
function introComma(text: string, out: ProseHint[]) {
|
||||||
let m: RegExpExecArray | null
|
for (const s of sentences(text)) {
|
||||||
let found = 0
|
const m = s.match(INTRO_RE)
|
||||||
A_BEFORE_VOWEL_RE.lastIndex = 0
|
if (m) {
|
||||||
while ((m = A_BEFORE_VOWEL_RE.exec(text)) && found < 1) {
|
out.push({
|
||||||
if (CONSONANT_SOUND_RE.test(m[1])) continue
|
id: `introcomma:${m[1].toLowerCase()}`,
|
||||||
found++
|
rule: 'introcomma',
|
||||||
out.push({
|
zh: `开头的过渡词后面加个逗号:“${m[1]}, …”。`,
|
||||||
id: `article-an:${key(m[1])}`,
|
en: `Put a comma after the opening transition: “${m[1]}, …”.`,
|
||||||
rule: 'article',
|
})
|
||||||
zh: `元音开头的词前用 “an”:“an ${m[1]}”。`,
|
break
|
||||||
en: `Before a vowel sound, use “an”: “an ${m[1]}”.`,
|
}
|
||||||
})
|
|
||||||
}
|
|
||||||
AN_BEFORE_CONSONANT_RE.lastIndex = 0
|
|
||||||
while ((m = AN_BEFORE_CONSONANT_RE.exec(text)) && found < 2) {
|
|
||||||
if (VOWEL_SOUND_RE.test(m[1])) continue
|
|
||||||
found++
|
|
||||||
out.push({
|
|
||||||
id: `article-a:${key(m[1])}`,
|
|
||||||
rule: 'article',
|
|
||||||
zh: `辅音开头的词前用 “a”:“a ${m[1]}”。`,
|
|
||||||
en: `Before a consonant sound, use “a”: “a ${m[1]}”.`,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Doubled word — “the the”, “is is”. Excludes the handful of doublings that can
|
|
||||||
// be legitimate (“the fact that that happened”, “she had had enough”).
|
|
||||||
const DOUBLE_RE = /\b([A-Za-z]+)\s+\1\b/gi
|
|
||||||
const LEGIT_DOUBLES = new Set(['that', 'had'])
|
|
||||||
|
|
||||||
function doubles(text: string, out: ProseHint[]) {
|
|
||||||
let m: RegExpExecArray | null
|
|
||||||
let found = 0
|
|
||||||
DOUBLE_RE.lastIndex = 0
|
|
||||||
while ((m = DOUBLE_RE.exec(text)) && found < 1) {
|
|
||||||
const w = m[1].toLowerCase()
|
|
||||||
if (LEGIT_DOUBLES.has(w)) continue
|
|
||||||
found++
|
|
||||||
out.push({
|
|
||||||
id: `double:${key(m[0])}`,
|
|
||||||
rule: 'double',
|
|
||||||
zh: `“${m[1]}” 好像写了两遍,检查一下哦。`,
|
|
||||||
en: `“${m[1]} ${m[1]}” — looks like a word got doubled.`,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lowercase standalone “I”. Conservative: only when bounded by spaces / line
|
|
||||||
// edge, to avoid tangling with “i.e.” and the like.
|
|
||||||
const LOWER_I_RE = /(?:^|\s)i(?=\s|$)/m
|
|
||||||
|
|
||||||
function pronounI(text: string, out: ProseHint[]) {
|
|
||||||
if (LOWER_I_RE.test(text)) {
|
|
||||||
out.push({
|
|
||||||
id: 'cap-i',
|
|
||||||
rule: 'cap-i',
|
|
||||||
zh: '英文里的 “I”(我)任何时候都要大写哦。',
|
|
||||||
en: 'In English, “I” is always written as a capital letter.',
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sentence not starting with a capital. We look after a terminator, and ignore
|
// Sentence not starting with a capital. We look after a terminator, and ignore
|
||||||
// CJK sentences (she writes Mandarin too — those don't take Latin capitals).
|
// CJK sentences (she writes Mandarin too — those don't take Latin capitals).
|
||||||
|
// Awareness-only: a bare “. x” also matches abbreviations (“U.S. then”), so we
|
||||||
|
// nudge rather than auto-capitalize.
|
||||||
const LOWER_START_RE = /[.!?]\s+([a-z])/
|
const LOWER_START_RE = /[.!?]\s+([a-z])/
|
||||||
|
|
||||||
function sentenceCaps(text: string, out: ProseHint[]) {
|
function sentenceCaps(text: string, out: ProseHint[]) {
|
||||||
@@ -275,40 +271,148 @@ function sentenceCaps(text: string, out: ProseHint[]) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A stray space *before* punctuation (a common habit carried from CJK spacing).
|
// ── applyable rules (also feed the suggestion cards) ─────────────────────────
|
||||||
const SPACE_BEFORE_PUNCT_RE = /[A-Za-z] +([,;:!?]|\.(?!\.))/
|
|
||||||
|
|
||||||
function spaceBeforePunct(text: string, out: ProseHint[]) {
|
// Doubled word — “the the”, “is is”. Excludes the handful of doublings that can
|
||||||
if (SPACE_BEFORE_PUNCT_RE.test(text)) {
|
// be legitimate (“the fact that that happened”, “she had had enough”).
|
||||||
|
const DOUBLE_RE = /\b([A-Za-z]+)(\s+)\1\b/gi
|
||||||
|
const LEGIT_DOUBLES = new Set(['that', 'had'])
|
||||||
|
|
||||||
|
function doubles(text: string, out: ProseHint[]) {
|
||||||
|
let m: RegExpExecArray | null
|
||||||
|
DOUBLE_RE.lastIndex = 0
|
||||||
|
while ((m = DOUBLE_RE.exec(text))) {
|
||||||
|
const w = m[1].toLowerCase()
|
||||||
|
if (LEGIT_DOUBLES.has(w)) continue
|
||||||
|
const from = m.index
|
||||||
|
const to = from + m[0].length
|
||||||
out.push({
|
out.push({
|
||||||
id: 'space-punct',
|
id: `double:${from}:${key(m[0])}`,
|
||||||
rule: 'space-punct',
|
rule: 'double',
|
||||||
zh: '标点前面不用空格,逗号、句号紧跟在前一个词后面就好。',
|
zh: `“${m[1]}” 好像写了两遍,检查一下哦。`,
|
||||||
en: 'No space before punctuation — it tucks right against the word.',
|
en: `“${m[1]} ${m[1]}” — looks like a word got doubled.`,
|
||||||
|
fix: { from, to, replacement: m[1] },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Chinese-L1 interference rules (Tier 1) ──────────────────────────────────
|
// Lowercase standalone “I”. Conservative: only when bounded by spaces / line
|
||||||
// Mandarin lacks plural inflection, articles, and verb agreement, so these
|
// edge, to avoid tangling with “i.e.” and the like. Awareness-only: a single
|
||||||
// patterns are the predictable places that grammar "leaks" into her English.
|
// character can't be re-anchored unambiguously by string (every word holds an
|
||||||
// All are closed-list or strong-signal to keep false positives near zero.
|
// “i”), so this stays a companion nudge rather than a one-click card.
|
||||||
|
const LOWER_I_RE = /(^|[^\p{L}\p{N}_])i(?=$|[^\p{L}\p{N}_])/mu
|
||||||
|
|
||||||
|
function pronounI(text: string, out: ProseHint[]) {
|
||||||
|
const m = LOWER_I_RE.exec(text)
|
||||||
|
LOWER_I_RE.lastIndex = 0
|
||||||
|
if (!m) return
|
||||||
|
const at = m.index + m[1].length
|
||||||
|
if (text[at + 1] === '.') return // “i.e.” etc. — precision over recall
|
||||||
|
out.push({
|
||||||
|
id: 'cap-i',
|
||||||
|
rule: 'cap-i',
|
||||||
|
zh: '英文里的 “I”(我)任何时候都要大写哦。',
|
||||||
|
en: 'In English, “I” is always written as a capital letter.',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// A stray space *before* punctuation (a common habit carried from CJK spacing).
|
||||||
|
const SPACE_BEFORE_PUNCT_RE = /([A-Za-z]+) +([,;:!?]|\.(?!\.))/g
|
||||||
|
|
||||||
|
function spaceBeforePunct(text: string, out: ProseHint[]) {
|
||||||
|
let m: RegExpExecArray | null
|
||||||
|
SPACE_BEFORE_PUNCT_RE.lastIndex = 0
|
||||||
|
while ((m = SPACE_BEFORE_PUNCT_RE.exec(text))) {
|
||||||
|
const from = m.index
|
||||||
|
const to = from + m[0].length
|
||||||
|
out.push({
|
||||||
|
id: `space-punct:${from}`,
|
||||||
|
rule: 'space-punct',
|
||||||
|
zh: '标点前面不用空格,逗号、句号紧跟在前一个词后面就好。',
|
||||||
|
en: 'No space before punctuation — it tucks right against the word.',
|
||||||
|
fix: { from, to, replacement: m[1] + m[2] },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Missing space *after* a comma or sentence period (“apple,banana”, “end.Next”).
|
||||||
|
// The comma case requires letters on both sides so numbers like 1,000 are safe;
|
||||||
|
// the period case requires a real word boundary so “e.g.”/“U.S.” are skipped.
|
||||||
|
const NO_SPACE_COMMA_RE = /([A-Za-z]+,)([A-Za-z]+)/g
|
||||||
|
const NO_SPACE_PERIOD_RE = /([a-z]{2,}\.)([A-Z][a-z]+)/g
|
||||||
|
|
||||||
|
function spaceAfterPunct(text: string, out: ProseHint[]) {
|
||||||
|
for (const re of [NO_SPACE_COMMA_RE, NO_SPACE_PERIOD_RE]) {
|
||||||
|
let m: RegExpExecArray | null
|
||||||
|
re.lastIndex = 0
|
||||||
|
while ((m = re.exec(text))) {
|
||||||
|
const from = m.index
|
||||||
|
const to = from + m[0].length
|
||||||
|
out.push({
|
||||||
|
id: `space-after:${from}`,
|
||||||
|
rule: 'space-after',
|
||||||
|
zh: '逗号、句号后面要空一格,再接下一个词。',
|
||||||
|
en: 'Add a space after a comma or period before the next word.',
|
||||||
|
fix: { from, to, replacement: `${m[1]} ${m[2]}` },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a vs. an — chosen by the *sound* of the next word. We work only on lowercase
|
||||||
|
// words (sidestepping proper nouns / acronyms) and keep sound-exception lists.
|
||||||
|
const A_BEFORE_VOWEL_RE = /\b(a)\s+([aeiou][a-z]+)\b/g
|
||||||
|
// Vowel-spelled but consonant-sounding → “a” is correct, don't flag.
|
||||||
|
const CONSONANT_SOUND_RE = /^(uni|use|usu|util|euro?|eul|ewe|once|one|ubiqu|unanim)/
|
||||||
|
const AN_BEFORE_CONSONANT_RE = /\b(an)\s+([b-df-hj-np-tv-z][a-z]+)\b/g
|
||||||
|
// Consonant-spelled but vowel-sounding (silent h) → “an” is correct, don't flag.
|
||||||
|
const VOWEL_SOUND_RE = /^(hour|honest|honou?r|heir|homage)/
|
||||||
|
|
||||||
|
function articles(text: string, out: ProseHint[]) {
|
||||||
|
let m: RegExpExecArray | null
|
||||||
|
A_BEFORE_VOWEL_RE.lastIndex = 0
|
||||||
|
while ((m = A_BEFORE_VOWEL_RE.exec(text))) {
|
||||||
|
if (CONSONANT_SOUND_RE.test(m[2])) continue
|
||||||
|
// Span the whole "a <noun>" so the original is a distinctive, anchorable
|
||||||
|
// phrase (a bare "a" matches everywhere). Replacement swaps only the article.
|
||||||
|
out.push({
|
||||||
|
id: `article-an:${m.index}`,
|
||||||
|
rule: 'article',
|
||||||
|
zh: `元音开头的词前用 “an”:“an ${m[2]}”。`,
|
||||||
|
en: `Before a vowel sound, use “an”: “an ${m[2]}”.`,
|
||||||
|
fix: { from: m.index, to: m.index + m[0].length, replacement: matchCase(m[1], 'an') + m[0].slice(m[1].length) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
AN_BEFORE_CONSONANT_RE.lastIndex = 0
|
||||||
|
while ((m = AN_BEFORE_CONSONANT_RE.exec(text))) {
|
||||||
|
if (VOWEL_SOUND_RE.test(m[2])) continue
|
||||||
|
out.push({
|
||||||
|
id: `article-a:${m.index}`,
|
||||||
|
rule: 'article',
|
||||||
|
zh: `辅音开头的词前用 “a”:“a ${m[2]}”。`,
|
||||||
|
en: `Before a consonant sound, use “a”: “a ${m[2]}”.`,
|
||||||
|
fix: { from: m.index, to: m.index + m[0].length, replacement: matchCase(m[1], 'a') + m[0].slice(m[1].length) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Mass nouns that Mandarin speakers very commonly pluralize. These words are
|
// Mass nouns that Mandarin speakers very commonly pluralize. These words are
|
||||||
// essentially never valid with a trailing “s”, so the list is its own guard.
|
// essentially never valid with a trailing “s”, so the list is its own guard.
|
||||||
const UNCOUNTABLE_PLURAL_RE =
|
const UNCOUNTABLE_PLURAL_RE =
|
||||||
/\b(informations|advices|knowledges|equipments|furnitures|homeworks|softwares|hardwares|luggages|baggages|sceneries|machineries)\b/i
|
/\b(informations|advices|knowledges|equipments|furnitures|homeworks|softwares|hardwares|luggages|baggages|sceneries|machineries)\b/gi
|
||||||
|
|
||||||
function uncountables(text: string, out: ProseHint[]) {
|
function uncountables(text: string, out: ProseHint[]) {
|
||||||
const m = UNCOUNTABLE_PLURAL_RE.exec(text)
|
let m: RegExpExecArray | null
|
||||||
UNCOUNTABLE_PLURAL_RE.lastIndex = 0
|
UNCOUNTABLE_PLURAL_RE.lastIndex = 0
|
||||||
if (m) {
|
while ((m = UNCOUNTABLE_PLURAL_RE.exec(text))) {
|
||||||
const singular = m[1].replace(/s$/i, '')
|
const word = m[1]
|
||||||
|
const singular = word.replace(/s$/i, '')
|
||||||
out.push({
|
out.push({
|
||||||
id: `uncountable:${m[1].toLowerCase()}`,
|
id: `uncountable:${m.index}`,
|
||||||
rule: 'uncountable',
|
rule: 'uncountable',
|
||||||
zh: `“${m[1]}” 是不可数名词,不用加 s,写 “${singular}” 就好。`,
|
zh: `“${word}” 是不可数名词,不用加 s,写 “${singular}” 就好。`,
|
||||||
en: `“${m[1]}” is uncountable — drop the “s”: just “${singular}”.`,
|
en: `“${word}” is uncountable — drop the “s”: just “${singular}”.`,
|
||||||
|
fix: { from: m.index, to: m.index + word.length, replacement: singular },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -324,17 +428,20 @@ const PROPER_NOUNS =
|
|||||||
'italian|russian|portuguese|arabic|vietnamese|thai|american|british|canadian|' +
|
'italian|russian|portuguese|arabic|vietnamese|thai|american|british|canadian|' +
|
||||||
'australian|mexican|brazilian|european'
|
'australian|mexican|brazilian|european'
|
||||||
// Case-sensitive (lowercase-only) so already-capitalized words aren't flagged.
|
// Case-sensitive (lowercase-only) so already-capitalized words aren't flagged.
|
||||||
const PROPER_NOUN_RE = new RegExp(`\\b(${PROPER_NOUNS})\\b`)
|
const PROPER_NOUN_RE = new RegExp(`\\b(${PROPER_NOUNS})\\b`, 'g')
|
||||||
|
|
||||||
function properCaps(text: string, out: ProseHint[]) {
|
function properCaps(text: string, out: ProseHint[]) {
|
||||||
const m = PROPER_NOUN_RE.exec(text)
|
let m: RegExpExecArray | null
|
||||||
if (m) {
|
PROPER_NOUN_RE.lastIndex = 0
|
||||||
const fixed = m[1][0].toUpperCase() + m[1].slice(1)
|
while ((m = PROPER_NOUN_RE.exec(text))) {
|
||||||
|
const word = m[1]
|
||||||
|
const fixed = word[0].toUpperCase() + word.slice(1)
|
||||||
out.push({
|
out.push({
|
||||||
id: `propercap:${m[1]}`,
|
id: `propercap:${m.index}`,
|
||||||
rule: 'propercap',
|
rule: 'propercap',
|
||||||
zh: `语言、国籍、星期和月份在英文里要大写:“${fixed}”。`,
|
zh: `语言、国籍、星期和月份在英文里要大写:“${fixed}”。`,
|
||||||
en: `Languages, days, and months are capitalized in English: “${fixed}”.`,
|
en: `Languages, days, and months are capitalized in English: “${fixed}”.`,
|
||||||
|
fix: { from: m.index, to: m.index + word.length, replacement: fixed },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -367,17 +474,20 @@ const CAUSATIVE = new Set([
|
|||||||
|
|
||||||
function subjectVerbAgreement(text: string, out: ProseHint[]) {
|
function subjectVerbAgreement(text: string, out: ProseHint[]) {
|
||||||
let m: RegExpExecArray | null
|
let m: RegExpExecArray | null
|
||||||
let found = 0
|
|
||||||
SVA_RE.lastIndex = 0
|
SVA_RE.lastIndex = 0
|
||||||
while ((m = SVA_RE.exec(text)) && found < 2) {
|
while ((m = SVA_RE.exec(text))) {
|
||||||
if (m[1] && CAUSATIVE.has(m[1].toLowerCase())) continue
|
if (m[1] && CAUSATIVE.has(m[1].toLowerCase())) continue
|
||||||
found++
|
const verb = m[3]
|
||||||
const fixed = third(m[3])
|
const fixed = third(verb)
|
||||||
|
// Span the whole match (subject + verb, plus any captured lead) so the
|
||||||
|
// original anchors; the replacement corrects only the trailing verb.
|
||||||
|
const head = m[0].slice(0, m[0].length - verb.length)
|
||||||
out.push({
|
out.push({
|
||||||
id: `sva:${m[2].toLowerCase()}:${m[3].toLowerCase()}`,
|
id: `sva:${m.index}`,
|
||||||
rule: 'sva',
|
rule: 'sva',
|
||||||
zh: `主语是 he/she/it 时,动词要加 -s:“${m[2]} ${fixed}”。`,
|
zh: `主语是 he/she/it 时,动词要加 -s:“${m[2]} ${fixed}”。`,
|
||||||
en: `After he/she/it the verb takes “-s”: “${m[2]} ${fixed}”.`,
|
en: `After he/she/it the verb takes “-s”: “${m[2]} ${fixed}”.`,
|
||||||
|
fix: { from: m.index, to: m.index + m[0].length, replacement: head + matchCase(verb, fixed) },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -397,35 +507,40 @@ const NON_S_PLURAL = new Set([
|
|||||||
|
|
||||||
function pluralAfterNumber(text: string, out: ProseHint[]) {
|
function pluralAfterNumber(text: string, out: ProseHint[]) {
|
||||||
let m: RegExpExecArray | null
|
let m: RegExpExecArray | null
|
||||||
let found = 0
|
|
||||||
NUMBER_NOUN_RE.lastIndex = 0
|
NUMBER_NOUN_RE.lastIndex = 0
|
||||||
while ((m = NUMBER_NOUN_RE.exec(text)) && found < 1) {
|
while ((m = NUMBER_NOUN_RE.exec(text))) {
|
||||||
const noun = m[2].toLowerCase()
|
const noun = m[2].toLowerCase()
|
||||||
if (noun.endsWith('s') || NON_S_PLURAL.has(noun)) continue
|
if (noun.endsWith('s') || NON_S_PLURAL.has(noun)) continue
|
||||||
found++
|
// Span "<number> <noun>" so the original anchors; append “s” to the noun.
|
||||||
out.push({
|
out.push({
|
||||||
id: `plural:${key(m[0])}`,
|
id: `plural:${m.index}`,
|
||||||
rule: 'plural',
|
rule: 'plural',
|
||||||
zh: `“${m[1]}” 后面的名词要用复数:“${m[1]} ${m[2]}s”。`,
|
zh: `“${m[1]}” 后面的名词要用复数:“${m[1]} ${m[2]}s”。`,
|
||||||
en: `After “${m[1]}”, the noun is plural: “${m[1]} ${m[2]}s”.`,
|
en: `After “${m[1]}”, the noun is plural: “${m[1]} ${m[2]}s”.`,
|
||||||
|
fix: { from: m.index, to: m.index + m[0].length, replacement: `${m[0]}s` },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Two stacked determiners (“the my book”, “a the”) — Mandarin uses a bare
|
// Two stacked determiners (“the my book”, “a the”) — Mandarin uses a bare
|
||||||
// possessive, so the article often gets stacked on top. One of the two must go.
|
// possessive, so the article often gets stacked on top. The article goes.
|
||||||
const DOUBLE_DET_RE =
|
const DOUBLE_DET_RE =
|
||||||
/\b(a|an|the)\s+(a|an|the|my|your|his|her|its|our|their)\b/gi
|
/\b(a|an|the)(\s+)(a|an|the|my|your|his|her|its|our|their)\b/gi
|
||||||
|
|
||||||
function doubleDeterminer(text: string, out: ProseHint[]) {
|
function doubleDeterminer(text: string, out: ProseHint[]) {
|
||||||
const m = DOUBLE_DET_RE.exec(text)
|
let m: RegExpExecArray | null
|
||||||
DOUBLE_DET_RE.lastIndex = 0
|
DOUBLE_DET_RE.lastIndex = 0
|
||||||
if (m) {
|
while ((m = DOUBLE_DET_RE.exec(text))) {
|
||||||
|
// Two *identical* words ("the the") are a doubled word, not stacked
|
||||||
|
// determiners — leave that to the `doubles` rule so we don't double-flag.
|
||||||
|
if (m[1].toLowerCase() === m[3].toLowerCase()) continue
|
||||||
out.push({
|
out.push({
|
||||||
id: `doubledet:${key(m[0])}`,
|
id: `doubledet:${m.index}`,
|
||||||
rule: 'doubledet',
|
rule: 'doubledet',
|
||||||
zh: `“${m[1]} ${m[2]}” 用了两个限定词,留一个就好(比如去掉 “${m[1]}”)。`,
|
zh: `“${m[1]} ${m[3]}” 用了两个限定词,留一个就好(比如去掉 “${m[1]}”)。`,
|
||||||
en: `“${m[1]} ${m[2]}” stacks two determiners — keep just one.`,
|
en: `“${m[1]} ${m[3]}” stacks two determiners — keep just one.`,
|
||||||
|
// Drop the article (m[1]); keep the second determiner, casing preserved.
|
||||||
|
fix: { from: m.index, to: m.index + m[0].length, replacement: matchCase(m[1], m[3]) },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -434,46 +549,52 @@ function doubleDeterminer(text: string, out: ProseHint[]) {
|
|||||||
// on clearly-plural cues (skip “some/any”, which are fine with singular mass
|
// on clearly-plural cues (skip “some/any”, which are fine with singular mass
|
||||||
// nouns: “there is some water”).
|
// nouns: “there is some water”).
|
||||||
const THERE_IS_RE =
|
const THERE_IS_RE =
|
||||||
/\bthere(?:\s+is|'s|’s)\s+(many|several|numerous|various|few|two|three|four|five|six|seven|eight|nine|ten)\b/i
|
/\bthere(\s+is|'s|’s)\s+(many|several|numerous|various|few|two|three|four|five|six|seven|eight|nine|ten)\b/gi
|
||||||
|
|
||||||
function thereIsPlural(text: string, out: ProseHint[]) {
|
function thereIsPlural(text: string, out: ProseHint[]) {
|
||||||
const m = THERE_IS_RE.exec(text)
|
let m: RegExpExecArray | null
|
||||||
THERE_IS_RE.lastIndex = 0
|
THERE_IS_RE.lastIndex = 0
|
||||||
if (m) {
|
while ((m = THERE_IS_RE.exec(text))) {
|
||||||
|
// Span the whole "there is <plural>" phrase so it anchors; swap the verb part
|
||||||
|
// (m[1]: “ is” / “'s”) for “ are”, preserving the “there” casing and the cue.
|
||||||
|
const replacement = m[0].slice(0, 5) + ' are' + m[0].slice(5 + m[1].length)
|
||||||
out.push({
|
out.push({
|
||||||
id: `thereis:${m[1].toLowerCase()}`,
|
id: `thereis:${m.index}`,
|
||||||
rule: 'thereis',
|
rule: 'thereis',
|
||||||
zh: `后面是复数时用 “there are”:“there are ${m[1]}…”。`,
|
zh: `后面是复数时用 “there are”:“there are ${m[2]}…”。`,
|
||||||
en: `With a plural, use “there are”: “there are ${m[1]}…”.`,
|
en: `With a plural, use “there are”: “there are ${m[2]}…”.`,
|
||||||
|
fix: { from: m.index, to: m.index + m[0].length, replacement },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── confusables (Tier 2) ─────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
// its / it's — only the two unambiguous directions: “it's own” (always its own)
|
// its / it's — only the two unambiguous directions: “it's own” (always its own)
|
||||||
// and “its a/an” (the possessive can't take an article → it's a/an).
|
// and “its a/an” (the possessive can't take an article → it's a/an).
|
||||||
const ITS_OWN_RE = /\bit's\s+own\b/i
|
const ITS_OWN_RE = /\b(it's|it’s)\s+own\b/gi
|
||||||
const ITS_ARTICLE_RE = /\bits\s+(a|an)\b/i
|
const ITS_ARTICLE_RE = /\bits\s+(a|an)\b/gi
|
||||||
|
|
||||||
function itsConfusion(text: string, out: ProseHint[]) {
|
function itsConfusion(text: string, out: ProseHint[]) {
|
||||||
if (ITS_OWN_RE.test(text)) {
|
let m: RegExpExecArray | null
|
||||||
|
ITS_OWN_RE.lastIndex = 0
|
||||||
|
while ((m = ITS_OWN_RE.exec(text))) {
|
||||||
|
// Span "it's own" so it anchors; swap the leading token to the possessive.
|
||||||
out.push({
|
out.push({
|
||||||
id: 'its-own',
|
id: `its-own:${m.index}`,
|
||||||
rule: 'its',
|
rule: 'its',
|
||||||
zh: '“it’s” = “it is”;表示“它的”要用 “its”,所以是 “its own”。',
|
zh: '“it’s” = “it is”;表示“它的”要用 “its”,所以是 “its own”。',
|
||||||
en: '“it’s” means “it is” — the possessive is “its”: “its own”.',
|
en: '“it’s” means “it is” — the possessive is “its”: “its own”.',
|
||||||
|
fix: { from: m.index, to: m.index + m[0].length, replacement: matchCase(m[1], 'its') + m[0].slice(m[1].length) },
|
||||||
})
|
})
|
||||||
return
|
|
||||||
}
|
}
|
||||||
const m = ITS_ARTICLE_RE.exec(text)
|
|
||||||
ITS_ARTICLE_RE.lastIndex = 0
|
ITS_ARTICLE_RE.lastIndex = 0
|
||||||
if (m) {
|
while ((m = ITS_ARTICLE_RE.exec(text))) {
|
||||||
|
// Span "its a/an" so it anchors; swap "its" → "it's".
|
||||||
out.push({
|
out.push({
|
||||||
id: 'its-article',
|
id: `its-article:${m.index}`,
|
||||||
rule: 'its',
|
rule: 'its',
|
||||||
zh: `这里应该是 “it’s ${m[1]}”(it is),“its” 是“它的”。`,
|
zh: `这里应该是 “it’s ${m[1]}”(it is),“its” 是“它的”。`,
|
||||||
en: `Here it should be “it’s ${m[1]}” (it is); “its” means belonging to it.`,
|
en: `Here it should be “it’s ${m[1]}” (it is); “its” means belonging to it.`,
|
||||||
|
fix: { from: m.index, to: m.index + m[0].length, replacement: matchCase(m[0][0], "it's") + m[0].slice(3) },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -485,57 +606,20 @@ const COMPARATIVES =
|
|||||||
'better|more|less|rather|worse|greater|other|older|younger|bigger|smaller|' +
|
'better|more|less|rather|worse|greater|other|older|younger|bigger|smaller|' +
|
||||||
'larger|faster|slower|higher|lower|cheaper|stronger|weaker|easier|harder|' +
|
'larger|faster|slower|higher|lower|cheaper|stronger|weaker|easier|harder|' +
|
||||||
'earlier|later|sooner|longer|shorter|taller|richer|poorer|happier|safer'
|
'earlier|later|sooner|longer|shorter|taller|richer|poorer|happier|safer'
|
||||||
const THAN_THEN_RE = new RegExp(`\\b(${COMPARATIVES})\\s+then\\b`, 'i')
|
const THAN_THEN_RE = new RegExp(`\\b(${COMPARATIVES})(\\s+)then\\b`, 'gi')
|
||||||
|
|
||||||
function thanThen(text: string, out: ProseHint[]) {
|
function thanThen(text: string, out: ProseHint[]) {
|
||||||
const m = THAN_THEN_RE.exec(text)
|
let m: RegExpExecArray | null
|
||||||
if (m) {
|
THAN_THEN_RE.lastIndex = 0
|
||||||
|
while ((m = THAN_THEN_RE.exec(text))) {
|
||||||
|
// Span "<comparative> then" so it anchors; swap the trailing “then” → “than”.
|
||||||
|
const thenFrom = m.index + m[0].length - 4
|
||||||
out.push({
|
out.push({
|
||||||
id: `than:${m[1].toLowerCase()}`,
|
id: `than:${m.index}`,
|
||||||
rule: 'than',
|
rule: 'than',
|
||||||
zh: `比较的时候用 “than”,不是 “then”:“${m[1]} than”。`,
|
zh: `比较的时候用 “than”,不是 “then”:“${m[1]} than”。`,
|
||||||
en: `For comparisons use “than”, not “then”: “${m[1]} than”.`,
|
en: `For comparisons use “than”, not “then”: “${m[1]} than”.`,
|
||||||
})
|
fix: { from: m.index, to: m.index + m[0].length, replacement: m[0].slice(0, m[0].length - 4) + matchCase(text[thenFrom], 'than') },
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A transition word opening a sentence with no comma after it (“However we…”).
|
|
||||||
// Limited to conjunctive adverbs that strongly want the comma — sequence words
|
|
||||||
// like “Then/First/Finally” are left out (their comma is optional).
|
|
||||||
const INTRO_RE =
|
|
||||||
/^(However|Therefore|Moreover|Furthermore|Nevertheless|Nonetheless|Meanwhile|Consequently|In addition|In conclusion|As a result|On the other hand|For example|For instance)\s+[A-Za-z]/
|
|
||||||
|
|
||||||
function introComma(text: string, out: ProseHint[]) {
|
|
||||||
let found = false
|
|
||||||
for (const s of sentences(text)) {
|
|
||||||
const m = s.match(INTRO_RE)
|
|
||||||
if (m) {
|
|
||||||
out.push({
|
|
||||||
id: `introcomma:${m[1].toLowerCase()}`,
|
|
||||||
rule: 'introcomma',
|
|
||||||
zh: `开头的过渡词后面加个逗号:“${m[1]}, …”。`,
|
|
||||||
en: `Put a comma after the opening transition: “${m[1]}, …”.`,
|
|
||||||
})
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return found
|
|
||||||
}
|
|
||||||
|
|
||||||
// Missing space *after* a comma or sentence period (“apple,banana”, “end.Next”).
|
|
||||||
// The comma case requires letters on both sides so numbers like 1,000 are safe;
|
|
||||||
// the period case requires a real word boundary so “e.g.”/“U.S.” are skipped.
|
|
||||||
const NO_SPACE_COMMA_RE = /[A-Za-z],[A-Za-z]/
|
|
||||||
const NO_SPACE_PERIOD_RE = /[a-z]{2,}\.[A-Z][a-z]/
|
|
||||||
|
|
||||||
function spaceAfterPunct(text: string, out: ProseHint[]) {
|
|
||||||
if (NO_SPACE_COMMA_RE.test(text) || NO_SPACE_PERIOD_RE.test(text)) {
|
|
||||||
out.push({
|
|
||||||
id: 'space-after',
|
|
||||||
rule: 'space-after',
|
|
||||||
zh: '逗号、句号后面要空一格,再接下一个词。',
|
|
||||||
en: 'Add a space after a comma or period before the next word.',
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -568,6 +652,8 @@ const RULES: Array<(text: string, out: ProseHint[]) => void> = [
|
|||||||
|
|
||||||
// analyzeProse returns context-aware hints, highest-priority first. It bails on
|
// analyzeProse returns context-aware hints, highest-priority first. It bails on
|
||||||
// text too short to advise on (mid-thought drafts shouldn't get picked apart).
|
// text too short to advise on (mid-thought drafts shouldn't get picked apart).
|
||||||
|
// Hints that carry a `fix` are applyable (they also surface as suggestion cards);
|
||||||
|
// the companion filters those out so a span isn't both a bubble and a card.
|
||||||
export function analyzeProse(text: string): ProseHint[] {
|
export function analyzeProse(text: string): ProseHint[] {
|
||||||
const englishWords = text.match(ENGLISH_WORD_RE)?.length ?? 0
|
const englishWords = text.match(ENGLISH_WORD_RE)?.length ?? 0
|
||||||
if (englishWords < 8) return []
|
if (englishWords < 8) return []
|
||||||
@@ -575,3 +661,35 @@ export function analyzeProse(text: string): ProseHint[] {
|
|||||||
for (const rule of RULES) rule(text, out)
|
for (const rule of RULES) rule(text, out)
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mechanicsFindings returns every applyable deterministic fix in the text, as
|
||||||
|
// suggestion-card findings with exact spans. No word-count floor: a doubled word
|
||||||
|
// or a stray lowercase “i” is worth fixing even in a short draft, the way a
|
||||||
|
// spell-checker would. The card pipeline persists these as the 'mechanics'
|
||||||
|
// family; collisions with the LLM cards are resolved server-side (mechanics
|
||||||
|
// wins, since its span is exact).
|
||||||
|
export function mechanicsFindings(text: string): MechanicsFinding[] {
|
||||||
|
const hints: ProseHint[] = []
|
||||||
|
for (const rule of RULES) rule(text, hints)
|
||||||
|
const found: MechanicsFinding[] = []
|
||||||
|
for (const h of hints) {
|
||||||
|
if (!h.fix) continue
|
||||||
|
const { from, to, replacement } = h.fix
|
||||||
|
const original = text.slice(from, to)
|
||||||
|
if (!original || original === replacement) continue
|
||||||
|
found.push({ from, to, original, replacement, explanation: h.en })
|
||||||
|
}
|
||||||
|
// Two rules can occasionally claim overlapping spans (e.g. a doubled word that
|
||||||
|
// also reads as stacked determiners). Resolve to one card per stretch of text:
|
||||||
|
// earlier start wins, ties broken by the longer span. The backend resolves the
|
||||||
|
// separate mechanics-vs-LLM collisions; this handles mechanics-vs-mechanics.
|
||||||
|
found.sort((a, b) => (a.from !== b.from ? a.from - b.from : b.to - a.to))
|
||||||
|
const out: MechanicsFinding[] = []
|
||||||
|
let lastEnd = -1
|
||||||
|
for (const f of found) {
|
||||||
|
if (f.from < lastEnd) continue
|
||||||
|
out.push(f)
|
||||||
|
lastEnd = f.to
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ export const ENCOURAGEMENTS: Line[] = [
|
|||||||
{ zh: '我很喜欢这个改法 💕', en: 'I really like that change.' },
|
{ zh: '我很喜欢这个改法 💕', en: 'I really like that change.' },
|
||||||
{ zh: '继续保持,加油!', en: 'Keep going — you’ve got this!' },
|
{ zh: '继续保持,加油!', en: 'Keep going — you’ve got this!' },
|
||||||
{ zh: '嗯嗯,这样清楚多了 👍', en: 'Mm, that’s much clearer.' },
|
{ zh: '嗯嗯,这样清楚多了 👍', en: 'Mm, that’s much clearer.' },
|
||||||
|
{ zh: '这个词用得真好 🌷', en: 'That’s such a good word choice.' },
|
||||||
|
{ zh: '哇,这一段读起来真舒服 ☁️', en: 'Ooh, that paragraph flows so nicely.' },
|
||||||
|
{ zh: '看你越写越有信心,真好 💛', en: 'I love watching you write with more confidence.' },
|
||||||
|
{ zh: '一点点进步,都是了不起的进步 🌱', en: 'Every little bit of progress counts.' },
|
||||||
|
{ zh: '今天的你,文字闪闪发光 ✨', en: 'Your words are sparkling today.' },
|
||||||
]
|
]
|
||||||
|
|
||||||
// Gentle, generic writing/ESL tips — the fallback when the rules-based prose
|
// Gentle, generic writing/ESL tips — the fallback when the rules-based prose
|
||||||
@@ -36,6 +41,23 @@ export const BREAKS: Line[] = [
|
|||||||
{ zh: '看看远方,放松一下眼睛 🌿', en: 'Look into the distance for a moment — give your eyes a break. 🌿' },
|
{ zh: '看看远方,放松一下眼睛 🌿', en: 'Look into the distance for a moment — give your eyes a break. 🌿' },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
// Shown when she's still writing late at night (≥11pm). Caring, a little
|
||||||
|
// playful — the kitten is always asleep, so "you should be too" lands as a gag,
|
||||||
|
// never a scold. zh stays gentle; the English subtitle carries the wink.
|
||||||
|
export const BEDTIME: Line[] = [
|
||||||
|
{ zh: '你的床在想你了哦 🛏️', en: 'I bet your bed is missing you right now.' },
|
||||||
|
{ zh: '太累可写不出好文字呀,早点歇着吧 🌙', en: 'A tired writer is a bad writer — get some rest.' },
|
||||||
|
{ zh: '好好睡一觉,灵感自己会来 ✨', en: 'Sleep is a wondrous enabler.' },
|
||||||
|
{ zh: '听见了吗?没有吧——大家都睡了,你也该睡啦 😴', en: "Hear that? No… you don't, because everyone is sleeping and you should be too." },
|
||||||
|
// A few old Chinese proverbs on sleep (zh = a faithful rendering of the
|
||||||
|
// English sense — the verified classical 原文 isn't recoverable; swap in the
|
||||||
|
// exact source text if you have it). They read a touch wittier/wiser than the
|
||||||
|
// gentle lines above, which suits a late-night nudge.
|
||||||
|
{ zh: '一夜不眠,十日不安。', en: "The loss of one night's sleep is followed by ten days of inconvenience." },
|
||||||
|
{ zh: '前半夜醒着想自己的过错,后半夜睡着才想别人的不是。', en: 'Think of your own faults the first part of the night when you are awake, and of the faults of others the latter part of the night when you are asleep.' },
|
||||||
|
{ zh: '黄昏与人相骂,夜半独自难眠。', en: 'Curse your spouse at evening, sleep alone at night.' },
|
||||||
|
]
|
||||||
|
|
||||||
// First hello when the app opens.
|
// First hello when the app opens.
|
||||||
export const GREETING: Line = {
|
export const GREETING: Line = {
|
||||||
zh: '嗨~我在这儿陪你写作哦 🐱',
|
zh: '嗨~我在这儿陪你写作哦 🐱',
|
||||||
@@ -48,8 +70,16 @@ export const WELCOME_BACK: Line = {
|
|||||||
en: 'Welcome back ✨ let’s keep going!',
|
en: 'Welcome back ✨ let’s keep going!',
|
||||||
}
|
}
|
||||||
|
|
||||||
// Word-count milestones worth a little cheer.
|
// Gentle "haiya, something went wrong" lines — paired with the error sound when
|
||||||
export const MILESTONES = [50, 100, 250, 500, 1000, 2000]
|
// the LLM is unreachable or a save fails. Never alarming, always reassuring.
|
||||||
|
export const ERRORS: Line[] = [
|
||||||
|
{ zh: '哎呀~出了点小问题,你的字都还在哦。', en: 'Oops — a little hiccup, but your words are safe.' },
|
||||||
|
{ zh: '哎呀,我这边卡了一下,马上就好。', en: 'Haiya, I got stuck for a sec — back in a moment.' },
|
||||||
|
{ zh: '别担心,等一下再试试看 🍵', en: "Don't worry — let's try again in a bit. 🍵" },
|
||||||
|
]
|
||||||
|
|
||||||
|
// Word-count milestones worth a little cheer — every 100 words, on up.
|
||||||
|
export const MILESTONES = Array.from({ length: 100 }, (_, i) => (i + 1) * 100)
|
||||||
|
|
||||||
export function milestoneLine(n: number): Line {
|
export function milestoneLine(n: number): Line {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
import type { SaveStatus } from '../../hooks/useAutoSave'
|
import type { SaveStatus } from '../../hooks/useAutoSave'
|
||||||
import {
|
import {
|
||||||
|
BEDTIME,
|
||||||
BREAKS,
|
BREAKS,
|
||||||
ENCOURAGEMENTS,
|
ENCOURAGEMENTS,
|
||||||
|
ERRORS,
|
||||||
GREETING,
|
GREETING,
|
||||||
MILESTONES,
|
MILESTONES,
|
||||||
TIPS,
|
TIPS,
|
||||||
@@ -12,13 +14,14 @@ import {
|
|||||||
type Line,
|
type Line,
|
||||||
} from './tips'
|
} from './tips'
|
||||||
import { analyzeProse } from './prose'
|
import { analyzeProse } from './prose'
|
||||||
import { playSound } from '../../audio/sounds'
|
import { playPop, playSound, type SoundName } from '../../audio/sounds'
|
||||||
|
import { isBedtime } from '../../lib/night'
|
||||||
|
|
||||||
// The kitten's expression. Maps to a Lottie animation when assets are present,
|
// The kitten's expression. Maps to a Lottie animation when assets are present,
|
||||||
// otherwise to an emoji placeholder (see PetalCompanion).
|
// otherwise to an emoji placeholder (see PetalCompanion).
|
||||||
export type Mood = 'idle' | 'happy' | 'talking' | 'sleeping' | 'celebrate'
|
export type Mood = 'idle' | 'happy' | 'talking' | 'sleeping' | 'celebrate'
|
||||||
|
|
||||||
export type BubbleTone = 'cheer' | 'tip' | 'break'
|
export type BubbleTone = 'cheer' | 'tip' | 'break' | 'error' | 'bedtime'
|
||||||
export interface Bubble extends Line {
|
export interface Bubble extends Line {
|
||||||
tone: BubbleTone
|
tone: BubbleTone
|
||||||
}
|
}
|
||||||
@@ -26,6 +29,9 @@ export interface Bubble extends Line {
|
|||||||
interface Signals {
|
interface Signals {
|
||||||
wordCount: number
|
wordCount: number
|
||||||
saveStatus: SaveStatus
|
saveStatus: SaveStatus
|
||||||
|
// True while the writing-assist LLM is unreachable (timeout / down). A
|
||||||
|
// false→true flip earns a gentle "haiya".
|
||||||
|
llmDown: boolean
|
||||||
// Monotonic counters bumped by the app on each editor change / accepted
|
// Monotonic counters bumped by the app on each editor change / accepted
|
||||||
// suggestion — lets the companion react without a full event bus.
|
// suggestion — lets the companion react without a full event bus.
|
||||||
editTick: number
|
editTick: number
|
||||||
@@ -40,13 +46,16 @@ const IDLE_MS = 75_000 // no edits → kitten naps
|
|||||||
const BREAK_MS = 25 * 60_000 // continuous writing → suggest a break
|
const BREAK_MS = 25 * 60_000 // continuous writing → suggest a break
|
||||||
const TIP_MIN_GAP = 4 * 60_000 // at most one spontaneous tip per this window
|
const TIP_MIN_GAP = 4 * 60_000 // at most one spontaneous tip per this window
|
||||||
const PROACTIVE_GAP = 40_000 // floor between any two unsolicited bubbles
|
const PROACTIVE_GAP = 40_000 // floor between any two unsolicited bubbles
|
||||||
|
const BEDTIME_GAP = 30 * 60_000 // at most one "go to bed" nudge per this window
|
||||||
|
// The late-night window itself (isBedtime) lives in ../../lib/night so the
|
||||||
|
// companion nag and the night-mode theme/starfall share one definition.
|
||||||
// How long a bubble lingers. These are *floors* — readBubbleMs extends them by
|
// How long a bubble lingers. These are *floors* — readBubbleMs extends them by
|
||||||
// how much there is to read, since she reads both the Mandarin and the English
|
// how much there is to read, since she reads both the Mandarin and the English
|
||||||
// (and tips now quote a slice of her own sentence, so they run longer).
|
// (and tips now quote a slice of her own sentence, so they run longer).
|
||||||
const BUBBLE_MS = 9_000 // baseline for a tip / break
|
const BUBBLE_MS = 14_000 // baseline for a tip / break
|
||||||
const CHEER_MS = 6_000 // a short cheer still needs a beat in two languages
|
const CHEER_MS = 9_000 // a short cheer still needs a beat in two languages
|
||||||
const READ_MS_PER_CHAR = 45 // ~22 chars/sec, generous for a bilingual read
|
const READ_MS_PER_CHAR = 55 // ~18 chars/sec, generous for a bilingual ESL read
|
||||||
const MAX_BUBBLE_MS = 20_000 // cap so a long quote can't pin the bubble forever
|
const MAX_BUBBLE_MS = 32_000 // cap so a long quote can't pin the bubble forever
|
||||||
const HOVER_GRACE_MS = 3_000 // lingers this long after she stops hovering
|
const HOVER_GRACE_MS = 3_000 // lingers this long after she stops hovering
|
||||||
const now = () => Date.now()
|
const now = () => Date.now()
|
||||||
|
|
||||||
@@ -54,7 +63,7 @@ const now = () => Date.now()
|
|||||||
// length of the Mandarin + English lines so denser advice stays up long enough
|
// length of the Mandarin + English lines so denser advice stays up long enough
|
||||||
// to actually finish reading.
|
// to actually finish reading.
|
||||||
function readBubbleMs(b: Bubble): number {
|
function readBubbleMs(b: Bubble): number {
|
||||||
const base = b.tone === 'cheer' ? CHEER_MS : BUBBLE_MS
|
const base = b.tone === 'cheer' ? CHEER_MS : b.tone === 'bedtime' ? BUBBLE_MS + 4_000 : BUBBLE_MS
|
||||||
const chars = b.zh.length + b.en.length
|
const chars = b.zh.length + b.en.length
|
||||||
return Math.min(MAX_BUBBLE_MS, base + chars * READ_MS_PER_CHAR)
|
return Math.min(MAX_BUBBLE_MS, base + chars * READ_MS_PER_CHAR)
|
||||||
}
|
}
|
||||||
@@ -62,7 +71,7 @@ function readBubbleMs(b: Bubble): number {
|
|||||||
// useCompanion is the behavior engine: it watches writing signals and decides
|
// useCompanion is the behavior engine: it watches writing signals and decides
|
||||||
// when the kitten speaks, what mood it shows, and how to pace itself so the
|
// when the kitten speaks, what mood it shows, and how to pace itself so the
|
||||||
// companion feels alive without interrupting. UI-agnostic — returns state only.
|
// companion feels alive without interrupting. UI-agnostic — returns state only.
|
||||||
export function useCompanion({ wordCount, saveStatus, editTick, acceptTick, text }: Signals) {
|
export function useCompanion({ wordCount, saveStatus, llmDown, editTick, acceptTick, text }: Signals) {
|
||||||
const [mood, setMood] = useState<Mood>('idle')
|
const [mood, setMood] = useState<Mood>('idle')
|
||||||
const [bubble, setBubble] = useState<Bubble | null>(null)
|
const [bubble, setBubble] = useState<Bubble | null>(null)
|
||||||
|
|
||||||
@@ -71,6 +80,7 @@ export function useCompanion({ wordCount, saveStatus, editTick, acceptTick, text
|
|||||||
const lastProactive = useRef(0)
|
const lastProactive = useRef(0)
|
||||||
const lastTip = useRef(0)
|
const lastTip = useRef(0)
|
||||||
const lastBreak = useRef(0)
|
const lastBreak = useRef(0)
|
||||||
|
const lastBedtime = useRef(0)
|
||||||
const nextMilestone = useRef(0) // index into MILESTONES
|
const nextMilestone = useRef(0) // index into MILESTONES
|
||||||
const sleeping = useRef(false)
|
const sleeping = useRef(false)
|
||||||
|
|
||||||
@@ -88,7 +98,8 @@ export function useCompanion({ wordCount, saveStatus, editTick, acceptTick, text
|
|||||||
|
|
||||||
// Show a bubble + talking mood, then settle back. `proactive` messages respect
|
// Show a bubble + talking mood, then settle back. `proactive` messages respect
|
||||||
// the spacing floor; user-triggered ones (cheers) always go through.
|
// the spacing floor; user-triggered ones (cheers) always go through.
|
||||||
const say = useCallback((b: Bubble, opts?: { proactive?: boolean; celebrate?: boolean }) => {
|
const say = useCallback(
|
||||||
|
(b: Bubble, opts?: { proactive?: boolean; celebrate?: boolean; sound?: SoundName }) => {
|
||||||
const t = now()
|
const t = now()
|
||||||
if (opts?.proactive) {
|
if (opts?.proactive) {
|
||||||
if (bubble) return
|
if (bubble) return
|
||||||
@@ -96,11 +107,11 @@ export function useCompanion({ wordCount, saveStatus, editTick, acceptTick, text
|
|||||||
lastProactive.current = t
|
lastProactive.current = t
|
||||||
}
|
}
|
||||||
sleeping.current = false
|
sleeping.current = false
|
||||||
// A soft sound to match the bubble's mood — celebrations cheer, gentle
|
// A sound to match the bubble: callers can name a specific one (the milestone
|
||||||
// cheers sparkle, break nudges chime, and tips give a little bubble pop.
|
// fanfare, the "haiya" on errors); everything else gets a rotating pop so the
|
||||||
playSound(
|
// same blip never repeats back to back.
|
||||||
opts?.celebrate ? 'cheer' : b.tone === 'cheer' ? 'shimmer' : b.tone === 'break' ? 'chime' : 'pop',
|
if (opts?.sound) playSound(opts.sound)
|
||||||
)
|
else playPop()
|
||||||
setBubble(b)
|
setBubble(b)
|
||||||
setMood(opts?.celebrate ? 'celebrate' : 'talking')
|
setMood(opts?.celebrate ? 'celebrate' : 'talking')
|
||||||
clearTimeout(bubbleTimer.current)
|
clearTimeout(bubbleTimer.current)
|
||||||
@@ -116,7 +127,10 @@ export function useCompanion({ wordCount, saveStatus, editTick, acceptTick, text
|
|||||||
// every finding was shown recently. Avoids repeating a finding or the same
|
// every finding was shown recently. Avoids repeating a finding or the same
|
||||||
// rule family back-to-back so the companion never feels like a broken record.
|
// rule family back-to-back so the companion never feels like a broken record.
|
||||||
const nextTip = useCallback((): Bubble => {
|
const nextTip = useCallback((): Bubble => {
|
||||||
const hints = analyzeProse(textRef.current)
|
// Applyable hints (those with a `fix`) surface as one-click suggestion cards,
|
||||||
|
// so the companion skips them — a span shouldn't be both a bubble and a card.
|
||||||
|
// What's left is the awareness notes (run-ons, splices, …) the kitten alone gives.
|
||||||
|
const hints = analyzeProse(textRef.current).filter((h) => !h.fix)
|
||||||
const fresh = hints.find(
|
const fresh = hints.find(
|
||||||
(h) => !recentHints.current.includes(h.id) && h.rule !== lastRule.current,
|
(h) => !recentHints.current.includes(h.id) && h.rule !== lastRule.current,
|
||||||
)
|
)
|
||||||
@@ -196,11 +210,39 @@ export function useCompanion({ wordCount, saveStatus, editTick, acceptTick, text
|
|||||||
const n = MILESTONES[nextMilestone.current]
|
const n = MILESTONES[nextMilestone.current]
|
||||||
nextMilestone.current += 1
|
nextMilestone.current += 1
|
||||||
// Skip silently if we're just loading a long doc (no edits yet).
|
// Skip silently if we're just loading a long doc (no edits yet).
|
||||||
if (!firstEdit.current) say({ ...milestoneLine(n), tone: 'cheer' }, { celebrate: true })
|
if (!firstEdit.current)
|
||||||
|
say({ ...milestoneLine(n), tone: 'cheer' }, { celebrate: true, sound: 'milestone' })
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [wordCount])
|
}, [wordCount])
|
||||||
|
|
||||||
|
// Trouble — a save failed or the writing-assist LLM went unreachable. Play the
|
||||||
|
// playful "haiya" and reassure her, but never spam: at most one per gap, and
|
||||||
|
// only on the *transition* into trouble (not while it lingers).
|
||||||
|
const lastError = useRef(0)
|
||||||
|
const ERROR_GAP = 20_000
|
||||||
|
const wasLlmDown = useRef(false)
|
||||||
|
const haiya = useCallback(() => {
|
||||||
|
const t = now()
|
||||||
|
if (t - lastError.current < ERROR_GAP) {
|
||||||
|
playSound('error') // still acknowledge it, just without a fresh bubble
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lastError.current = t
|
||||||
|
say({ ...pick(ERRORS), tone: 'error' }, { sound: 'error' })
|
||||||
|
}, [say])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (saveStatus === 'error') haiya()
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [saveStatus])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (llmDown && !wasLlmDown.current) haiya()
|
||||||
|
wasLlmDown.current = llmDown
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [llmDown])
|
||||||
|
|
||||||
// Occasional gentle cheer on a successful save (kept rare so it isn't noise).
|
// Occasional gentle cheer on a successful save (kept rare so it isn't noise).
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (saveStatus === 'saved' && Math.random() < 0.18) {
|
if (saveStatus === 'saved' && Math.random() < 0.18) {
|
||||||
@@ -229,6 +271,15 @@ export function useCompanion({ wordCount, saveStatus, editTick, acceptTick, text
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Burning the midnight oil? Gently suggest bed — caring, low-frequency,
|
||||||
|
// and only while she's actually still at it (the idle branch above already
|
||||||
|
// returned if she's away/napping).
|
||||||
|
if (isBedtime() && t - lastBedtime.current > BEDTIME_GAP) {
|
||||||
|
lastBedtime.current = t
|
||||||
|
say({ ...pick(BEDTIME), tone: 'bedtime' }, { proactive: true })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Otherwise an occasional tip — context-aware when her text gives us
|
// Otherwise an occasional tip — context-aware when her text gives us
|
||||||
// something concrete to gently point at, generic warmth otherwise.
|
// something concrete to gently point at, generic warmth otherwise.
|
||||||
if (t - lastTip.current > TIP_MIN_GAP) {
|
if (t - lastTip.current > TIP_MIN_GAP) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useMemo, useState } from 'react'
|
import { useMemo, useState } from 'react'
|
||||||
import type { DocSummary, Tag, TagColor } from '../../api/client'
|
import { api, type DocSummary, type Tag, type TagColor } from '../../api/client'
|
||||||
import { DocListItem } from './DocListItem'
|
import { DocListItem } from './DocListItem'
|
||||||
import { SearchBox } from './SearchBox'
|
import { SearchBox } from './SearchBox'
|
||||||
import { TagChip } from './TagChip'
|
import { TagChip } from './TagChip'
|
||||||
@@ -11,10 +11,19 @@ interface Props {
|
|||||||
onSelect: (id: string) => void
|
onSelect: (id: string) => void
|
||||||
onCreate: () => void
|
onCreate: () => void
|
||||||
onDelete: (id: string) => void
|
onDelete: (id: string) => void
|
||||||
|
onDuplicate: (id: string) => void
|
||||||
onToggleTag: (docId: string, tag: Tag) => void
|
onToggleTag: (docId: string, tag: Tag) => void
|
||||||
onCreateTag: (docId: string, name: string, color: TagColor) => void
|
onCreateTag: (docId: string, name: string, color: TagColor) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sidebar sort orders. 'recent' keeps the server's updated_at-desc ordering.
|
||||||
|
type SortMode = 'recent' | 'title' | 'longest'
|
||||||
|
const SORTS: { value: SortMode; label: string }[] = [
|
||||||
|
{ value: 'recent', label: '最近 · Recent' },
|
||||||
|
{ value: 'title', label: '标题 · Title' },
|
||||||
|
{ value: 'longest', label: '字数 · Longest' },
|
||||||
|
]
|
||||||
|
|
||||||
// DocList is the sidebar: a cross-document search box, a tag filter bar, the New
|
// DocList is the sidebar: a cross-document search box, a tag filter bar, the New
|
||||||
// button, and the document browser (each row showing its tag chips).
|
// button, and the document browser (each row showing its tag chips).
|
||||||
export function DocList({
|
export function DocList({
|
||||||
@@ -24,6 +33,7 @@ export function DocList({
|
|||||||
onSelect,
|
onSelect,
|
||||||
onCreate,
|
onCreate,
|
||||||
onDelete,
|
onDelete,
|
||||||
|
onDuplicate,
|
||||||
onToggleTag,
|
onToggleTag,
|
||||||
onCreateTag,
|
onCreateTag,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
@@ -31,11 +41,21 @@ export function DocList({
|
|||||||
// disappears from the roster.
|
// disappears from the roster.
|
||||||
const [filterId, setFilterId] = useState<string | null>(null)
|
const [filterId, setFilterId] = useState<string | null>(null)
|
||||||
const activeFilter = filterId && roster.some((t) => t.id === filterId) ? filterId : null
|
const activeFilter = filterId && roster.some((t) => t.id === filterId) ? filterId : null
|
||||||
|
const [sort, setSort] = useState<SortMode>('recent')
|
||||||
|
|
||||||
const filtered = useMemo(
|
const filtered = useMemo(() => {
|
||||||
() => (activeFilter ? docs.filter((d) => d.tags.some((t) => t.id === activeFilter)) : docs),
|
const base = activeFilter ? docs.filter((d) => d.tags.some((t) => t.id === activeFilter)) : docs
|
||||||
[docs, activeFilter],
|
if (sort === 'recent') return base // already updated_at-desc from the server
|
||||||
)
|
const arr = [...base]
|
||||||
|
if (sort === 'title') {
|
||||||
|
arr.sort((a, b) =>
|
||||||
|
(a.title || 'Untitled').localeCompare(b.title || 'Untitled', undefined, { sensitivity: 'base' }),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
arr.sort((a, b) => b.word_count - a.word_count)
|
||||||
|
}
|
||||||
|
return arr
|
||||||
|
}, [docs, activeFilter, sort])
|
||||||
|
|
||||||
// Only surface tags that are actually in use, so the filter bar stays tidy.
|
// Only surface tags that are actually in use, so the filter bar stays tidy.
|
||||||
const usedTags = useMemo(() => roster.filter((t) => (t.doc_count ?? 0) > 0), [roster])
|
const usedTags = useMemo(() => roster.filter((t) => (t.doc_count ?? 0) > 0), [roster])
|
||||||
@@ -72,6 +92,25 @@ export function DocList({
|
|||||||
<span className="text-base leading-none">+</span> New Doc
|
<span className="text-base leading-none">+</span> New Doc
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{docs.length > 1 && (
|
||||||
|
<div className="flex items-center justify-end gap-1.5 px-1 text-xs" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
<span aria-hidden>↕</span>
|
||||||
|
<select
|
||||||
|
aria-label="Sort documents"
|
||||||
|
value={sort}
|
||||||
|
onChange={(e) => setSort(e.target.value as SortMode)}
|
||||||
|
className="bg-transparent text-xs font-semibold focus:outline-none"
|
||||||
|
style={{ color: 'var(--color-plum)' }}
|
||||||
|
>
|
||||||
|
{SORTS.map((s) => (
|
||||||
|
<option key={s.value} value={s.value}>
|
||||||
|
{s.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="flex flex-1 flex-col gap-0.5 overflow-y-auto">
|
<div className="flex flex-1 flex-col gap-0.5 overflow-y-auto">
|
||||||
{filtered.length === 0 ? (
|
{filtered.length === 0 ? (
|
||||||
<p className="px-3 py-6 text-center text-xs" style={{ color: 'var(--color-muted)' }}>
|
<p className="px-3 py-6 text-center text-xs" style={{ color: 'var(--color-muted)' }}>
|
||||||
@@ -86,12 +125,30 @@ export function DocList({
|
|||||||
roster={roster}
|
roster={roster}
|
||||||
onSelect={() => onSelect(doc.id)}
|
onSelect={() => onSelect(doc.id)}
|
||||||
onDelete={() => onDelete(doc.id)}
|
onDelete={() => onDelete(doc.id)}
|
||||||
|
onDuplicate={() => onDuplicate(doc.id)}
|
||||||
onToggleTag={onToggleTag}
|
onToggleTag={onToggleTag}
|
||||||
onCreateTag={onCreateTag}
|
onCreateTag={onCreateTag}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Whole-corpus backup — "download all my writing". Plain download links so
|
||||||
|
the browser saves the zip; no extra app state needed. */}
|
||||||
|
{docs.length > 0 && (
|
||||||
|
<div
|
||||||
|
className="flex items-center gap-2 px-1 pt-1 text-xs"
|
||||||
|
style={{ color: 'var(--color-muted)', borderTop: '1px solid var(--color-border)' }}
|
||||||
|
>
|
||||||
|
<span className="font-semibold">备份 · Back up all:</span>
|
||||||
|
<a href={api.exportAllUrl('docx')} download className="font-bold hover:underline" style={{ color: 'var(--color-accent-hover)' }}>
|
||||||
|
Word
|
||||||
|
</a>
|
||||||
|
<a href={api.exportAllUrl('md')} download className="font-bold hover:underline" style={{ color: 'var(--color-accent-hover)' }}>
|
||||||
|
Markdown
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</aside>
|
</aside>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ interface Props {
|
|||||||
roster: Tag[]
|
roster: Tag[]
|
||||||
onSelect: () => void
|
onSelect: () => void
|
||||||
onDelete: () => void
|
onDelete: () => void
|
||||||
|
onDuplicate: () => void
|
||||||
onToggleTag: (docId: string, tag: Tag) => void
|
onToggleTag: (docId: string, tag: Tag) => void
|
||||||
onCreateTag: (docId: string, name: string, color: TagColor) => void
|
onCreateTag: (docId: string, name: string, color: TagColor) => void
|
||||||
}
|
}
|
||||||
@@ -21,6 +22,7 @@ export function DocListItem({
|
|||||||
roster,
|
roster,
|
||||||
onSelect,
|
onSelect,
|
||||||
onDelete,
|
onDelete,
|
||||||
|
onDuplicate,
|
||||||
onToggleTag,
|
onToggleTag,
|
||||||
onCreateTag,
|
onCreateTag,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
@@ -65,6 +67,19 @@ export function DocListItem({
|
|||||||
>
|
>
|
||||||
🏷️
|
🏷️
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Duplicate document"
|
||||||
|
title="副本 · Duplicate"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
onDuplicate()
|
||||||
|
}}
|
||||||
|
className="petal-row-action flex h-7 w-7 shrink-0 items-center justify-center text-sm"
|
||||||
|
style={{ borderRadius: 'var(--radius-pill)', color: 'var(--color-muted)' }}
|
||||||
|
>
|
||||||
|
⧉
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-label="Delete document"
|
aria-label="Delete document"
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { streamSuggestionChat, type ChatMessage } from '../../api/client'
|
import { api, streamSuggestionChat, type ChatMessage } from '../../api/client'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
suggestionId: string
|
suggestionId: string
|
||||||
// Pre-populates Petal's first bubble so the conversation opens with context.
|
// The English explanation (shown in the card body). Petal's opening bubble is
|
||||||
|
// its Simplified-Chinese translation, fetched on open — so the panel doesn't
|
||||||
|
// just repeat the same English text twice. Falls back to this on failure.
|
||||||
explanation: string
|
explanation: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17,9 +19,10 @@ const CHAT_FONT = "'Nunito', 'PingFang SC', 'Microsoft YaHei', 'Noto Sans CJK SC
|
|||||||
// the card (unmounting) clears it. Each send streams Petal's reply token-by-
|
// the card (unmounting) clears it. Each send streams Petal's reply token-by-
|
||||||
// token into the latest assistant bubble.
|
// token into the latest assistant bubble.
|
||||||
export function AskPetal({ suggestionId, explanation }: Props) {
|
export function AskPetal({ suggestionId, explanation }: Props) {
|
||||||
const [messages, setMessages] = useState<ChatMessage[]>([
|
// Opening bubble starts empty (caret-only) and fills with the Mandarin
|
||||||
{ role: 'assistant', content: explanation },
|
// translation once it lands; `seeding` drives that loading caret.
|
||||||
])
|
const [messages, setMessages] = useState<ChatMessage[]>([{ role: 'assistant', content: '' }])
|
||||||
|
const [seeding, setSeeding] = useState(true)
|
||||||
const [input, setInput] = useState('')
|
const [input, setInput] = useState('')
|
||||||
const [streaming, setStreaming] = useState(false)
|
const [streaming, setStreaming] = useState(false)
|
||||||
const scrollRef = useRef<HTMLDivElement>(null)
|
const scrollRef = useRef<HTMLDivElement>(null)
|
||||||
@@ -31,11 +34,39 @@ export function AskPetal({ suggestionId, explanation }: Props) {
|
|||||||
if (el) el.scrollTop = el.scrollHeight
|
if (el) el.scrollTop = el.scrollHeight
|
||||||
}, [messages])
|
}, [messages])
|
||||||
|
|
||||||
// Focus the input when the panel opens.
|
// Focus the input when the panel opens. preventScroll: the card is already on
|
||||||
|
// screen as an absolutely-positioned overlay, and a default focus() would make
|
||||||
|
// the browser scroll its ancestor to "reveal" the input — jumping the document
|
||||||
|
// to the top.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
inputRef.current?.focus()
|
inputRef.current?.focus({ preventScroll: true })
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
// Fetch the Chinese translation of the explanation to seed the first bubble.
|
||||||
|
// Only replaces the seed bubble if the user hasn't started chatting yet (the
|
||||||
|
// conversation always opens with this one assistant turn). Falls back to the
|
||||||
|
// English explanation if the translation can't be fetched.
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false
|
||||||
|
api
|
||||||
|
.translateSuggestion(suggestionId)
|
||||||
|
.then((res) => {
|
||||||
|
if (cancelled) return
|
||||||
|
const text = res.translation.trim() || explanation
|
||||||
|
setMessages((prev) => (prev.length === 1 ? [{ role: 'assistant', content: text }] : prev))
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (cancelled) return
|
||||||
|
setMessages((prev) => (prev.length === 1 ? [{ role: 'assistant', content: explanation }] : prev))
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!cancelled) setSeeding(false)
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}, [suggestionId, explanation])
|
||||||
|
|
||||||
async function send() {
|
async function send() {
|
||||||
const text = input.trim()
|
const text = input.trim()
|
||||||
if (!text || streaming) return
|
if (!text || streaming) return
|
||||||
@@ -67,7 +98,7 @@ export function AskPetal({ suggestionId, explanation }: Props) {
|
|||||||
console.error('Ask Petal chat failed:', err)
|
console.error('Ask Petal chat failed:', err)
|
||||||
} finally {
|
} finally {
|
||||||
setStreaming(false)
|
setStreaming(false)
|
||||||
inputRef.current?.focus()
|
inputRef.current?.focus({ preventScroll: true })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +117,12 @@ export function AskPetal({ suggestionId, explanation }: Props) {
|
|||||||
style={{ maxHeight: 220 }}
|
style={{ maxHeight: 220 }}
|
||||||
>
|
>
|
||||||
{messages.map((m, i) => (
|
{messages.map((m, i) => (
|
||||||
<Bubble key={i} role={m.role} content={m.content} streaming={streaming && i === messages.length - 1} />
|
<Bubble
|
||||||
|
key={i}
|
||||||
|
role={m.role}
|
||||||
|
content={m.content}
|
||||||
|
streaming={(streaming && i === messages.length - 1) || (seeding && i === 0)}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -4,17 +4,33 @@ import Underline from '@tiptap/extension-underline'
|
|||||||
import TextAlign from '@tiptap/extension-text-align'
|
import TextAlign from '@tiptap/extension-text-align'
|
||||||
import Placeholder from '@tiptap/extension-placeholder'
|
import Placeholder from '@tiptap/extension-placeholder'
|
||||||
import CharacterCount from '@tiptap/extension-character-count'
|
import CharacterCount from '@tiptap/extension-character-count'
|
||||||
|
import Link from '@tiptap/extension-link'
|
||||||
|
import { Color } from '@tiptap/extension-color'
|
||||||
|
import TextStyle from '@tiptap/extension-text-style'
|
||||||
|
import Highlight from '@tiptap/extension-highlight'
|
||||||
|
import Image from '@tiptap/extension-image'
|
||||||
|
import Table from '@tiptap/extension-table'
|
||||||
|
import TableRow from '@tiptap/extension-table-row'
|
||||||
|
import TableHeader from '@tiptap/extension-table-header'
|
||||||
|
import TableCell from '@tiptap/extension-table-cell'
|
||||||
|
import { FontSize } from './FontSize'
|
||||||
|
import type { EditorView } from '@tiptap/pm/view'
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
import { Toolbar } from '../Toolbar/Toolbar'
|
import { Toolbar } from '../Toolbar/Toolbar'
|
||||||
import { SuggestionCard } from './SuggestionCard'
|
import { SuggestionCard } from './SuggestionCard'
|
||||||
import { SuggestionHighlight, setSuggestions, findRange } from './SuggestionHighlight'
|
import { SuggestionRail, type RailItem } from './SuggestionRail'
|
||||||
|
import { SuggestionHighlight, setSuggestions, setActiveSuggestion, findRange } from './SuggestionHighlight'
|
||||||
import { SpellCheck, setSpellChecker, wordAt } from './SpellCheck'
|
import { SpellCheck, setSpellChecker, wordAt } from './SpellCheck'
|
||||||
import { MisspellCard } from './MisspellCard'
|
import { MisspellCard } from './MisspellCard'
|
||||||
import { WordCard } from './WordCard'
|
import { WordCard } from './WordCard'
|
||||||
import { GlossTip } from './GlossTip'
|
import { GlossTip } from './GlossTip'
|
||||||
import { SelectionBubble } from './SelectionBubble'
|
import { SelectionBubble } from './SelectionBubble'
|
||||||
|
import { SearchHighlight } from './SearchHighlight'
|
||||||
|
import { FindReplace } from './FindReplace'
|
||||||
|
import { Typography } from './Typography'
|
||||||
import { RewritePreview, type RewriteStatus } from './RewritePreview'
|
import { RewritePreview, type RewriteStatus } from './RewritePreview'
|
||||||
import { api, type Suggestion, type WordInfo } from '../../api/client'
|
import { api, type Suggestion, type WordInfo } from '../../api/client'
|
||||||
|
import { speak, speechSupported } from '../../audio/speech'
|
||||||
import type { SpellChecker } from '../../hooks/useSpellChecker'
|
import type { SpellChecker } from '../../hooks/useSpellChecker'
|
||||||
|
|
||||||
export interface EditorChange {
|
export interface EditorChange {
|
||||||
@@ -37,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
|
||||||
@@ -65,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
|
||||||
@@ -103,6 +150,21 @@ function parseDoc(raw: string): object | undefined {
|
|||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// uploadImageInto sends an image file to the store and inserts the returned URL
|
||||||
|
// as an image node — at `pos` if given (a drop point), otherwise at the current
|
||||||
|
// selection (a paste). Shared by the paste/drop handlers and the toolbar button.
|
||||||
|
export async function uploadImageInto(view: EditorView, file: File, pos?: number) {
|
||||||
|
try {
|
||||||
|
const { url } = await api.uploadImage(file)
|
||||||
|
const { schema } = view.state
|
||||||
|
const node = schema.nodes.image.create({ src: url })
|
||||||
|
const at = pos ?? view.state.selection.from
|
||||||
|
view.dispatch(view.state.tr.insert(at, node))
|
||||||
|
} catch (err) {
|
||||||
|
console.error('image upload failed', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
interface HoverState {
|
interface HoverState {
|
||||||
suggestion: Suggestion
|
suggestion: Suggestion
|
||||||
top: number
|
top: number
|
||||||
@@ -154,6 +216,8 @@ export function EditorCore({
|
|||||||
onDismiss,
|
onDismiss,
|
||||||
onVoiceCheck,
|
onVoiceCheck,
|
||||||
voicing,
|
voicing,
|
||||||
|
onCollocationCheck,
|
||||||
|
collocating,
|
||||||
onFocusMode,
|
onFocusMode,
|
||||||
spellChecker,
|
spellChecker,
|
||||||
onAddWord,
|
onAddWord,
|
||||||
@@ -181,22 +245,73 @@ export function EditorCore({
|
|||||||
// The rewrite affordances: a bubble over the current selection, and the
|
// The rewrite affordances: a bubble over the current selection, and the
|
||||||
// preview that replaces it once a style is chosen.
|
// preview that replaces it once a style is chosen.
|
||||||
const [selection, setSelection] = useState<SelectionState | null>(null)
|
const [selection, setSelection] = useState<SelectionState | null>(null)
|
||||||
|
// True while a pointer is held down (a drag-select in progress). The rewrite
|
||||||
|
// bubble stays hidden until release so it never appears — or re-anchors — under
|
||||||
|
// a still-moving cursor, which is where the user is trying to click.
|
||||||
|
const [dragging, setDragging] = useState(false)
|
||||||
const [rewrite, setRewrite] = useState<RewriteState | null>(null)
|
const [rewrite, setRewrite] = useState<RewriteState | null>(null)
|
||||||
const rewriteReqRef = useRef(0)
|
const rewriteReqRef = useRef(0)
|
||||||
|
// The in-document Find & Replace bar (Ctrl/Cmd+F).
|
||||||
|
const [findOpen, setFindOpen] = useState(false)
|
||||||
|
// The right-margin comment rail. `railItems` carries each anchored suggestion's
|
||||||
|
// vertical offset; `railEnabled` is true only when the viewport has room for the
|
||||||
|
// column beside the editor (otherwise we fall back to the inline hover cards).
|
||||||
|
// `railExpandedId` is the card showing its full explanation + Ask Petal, and
|
||||||
|
// `activeId` is the suggestion currently emphasized (hovered text or card).
|
||||||
|
const [railItems, setRailItems] = useState<RailItem[]>([])
|
||||||
|
const [railEnabled, setRailEnabled] = useState(false)
|
||||||
|
const [railExpandedId, setRailExpandedId] = useState<string | null>(null)
|
||||||
|
const [activeId, setActiveId] = useState<string | null>(null)
|
||||||
|
// A stable handle to the latest recompute so the editor's onUpdate (captured
|
||||||
|
// once at construction) can trigger a re-measure without stale closures.
|
||||||
|
const recomputeRailRef = useRef<() => void>(() => {})
|
||||||
|
|
||||||
const editor = useEditor({
|
const editor = useEditor({
|
||||||
extensions: [
|
extensions: [
|
||||||
StarterKit,
|
StarterKit,
|
||||||
Underline,
|
Underline,
|
||||||
|
TextStyle,
|
||||||
|
Color,
|
||||||
|
FontSize,
|
||||||
|
Highlight.configure({ multicolor: true }),
|
||||||
|
Link.configure({ openOnClick: false, autolink: true, HTMLAttributes: { rel: 'noopener noreferrer nofollow' } }),
|
||||||
|
Image.configure({ inline: false, HTMLAttributes: { class: 'petal-image' } }),
|
||||||
|
Table.configure({ resizable: true, HTMLAttributes: { class: 'petal-table' } }),
|
||||||
|
TableRow,
|
||||||
|
TableHeader,
|
||||||
|
TableCell,
|
||||||
TextAlign.configure({ types: ['heading', 'paragraph'] }),
|
TextAlign.configure({ types: ['heading', 'paragraph'] }),
|
||||||
Placeholder.configure({ placeholder: 'Start writing…' }),
|
Placeholder.configure({ placeholder: 'Start writing…' }),
|
||||||
CharacterCount,
|
CharacterCount,
|
||||||
SuggestionHighlight,
|
SuggestionHighlight,
|
||||||
SpellCheck,
|
SpellCheck,
|
||||||
|
SearchHighlight,
|
||||||
|
Typography,
|
||||||
],
|
],
|
||||||
content: parseDoc(initialContent),
|
content: parseDoc(initialContent),
|
||||||
editorProps: {
|
editorProps: {
|
||||||
attributes: { class: 'petal-prose focus:outline-none' },
|
attributes: { class: 'petal-prose focus:outline-none' },
|
||||||
|
// Dropping or pasting an image file uploads it and inserts it at the drop
|
||||||
|
// point (or the cursor for a paste). Returns true to consume the event so
|
||||||
|
// ProseMirror doesn't also try to handle the raw file. Non-image pastes
|
||||||
|
// fall through to the default handler.
|
||||||
|
handleDrop: (view, event) => {
|
||||||
|
const files = (event as DragEvent).dataTransfer?.files
|
||||||
|
const image = files && Array.from(files).find((f) => f.type.startsWith('image/'))
|
||||||
|
if (!image) return false
|
||||||
|
event.preventDefault()
|
||||||
|
const coords = view.posAtCoords({ left: (event as DragEvent).clientX, top: (event as DragEvent).clientY })
|
||||||
|
uploadImageInto(view, image, coords?.pos)
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
handlePaste: (view, event) => {
|
||||||
|
const files = event.clipboardData?.files
|
||||||
|
const image = files && Array.from(files).find((f) => f.type.startsWith('image/'))
|
||||||
|
if (!image) return false
|
||||||
|
event.preventDefault()
|
||||||
|
uploadImageInto(view, image)
|
||||||
|
return true
|
||||||
|
},
|
||||||
},
|
},
|
||||||
onFocus: () => onFocusMode?.(),
|
onFocus: () => onFocusMode?.(),
|
||||||
onUpdate: ({ editor }) => {
|
onUpdate: ({ editor }) => {
|
||||||
@@ -213,6 +328,8 @@ export function EditorCore({
|
|||||||
content_text: editor.getText(),
|
content_text: editor.getText(),
|
||||||
word_count: editor.storage.characterCount.words(),
|
word_count: editor.storage.characterCount.words(),
|
||||||
})
|
})
|
||||||
|
// Edits reflow the text, so the rail anchors need re-measuring.
|
||||||
|
recomputeRailRef.current()
|
||||||
},
|
},
|
||||||
onSelectionUpdate: ({ editor }) => {
|
onSelectionUpdate: ({ editor }) => {
|
||||||
// A selection supersedes the hover gloss; an empty one clears the bubble.
|
// A selection supersedes the hover gloss; an empty one clears the bubble.
|
||||||
@@ -264,8 +381,87 @@ export function EditorCore({
|
|||||||
setSuggestions(editor.state, editor.view.dispatch, suggestions)
|
setSuggestions(editor.state, editor.view.dispatch, suggestions)
|
||||||
// Close the card if its suggestion is gone.
|
// Close the card if its suggestion is gone.
|
||||||
setHover((h) => (h && suggestions.some((s) => s.id === h.suggestion.id) ? h : null))
|
setHover((h) => (h && suggestions.some((s) => s.id === h.suggestion.id) ? h : null))
|
||||||
|
// Drop any rail expand/emphasis that points at a now-removed suggestion.
|
||||||
|
setRailExpandedId((id) => (id && suggestions.some((s) => s.id === id) ? id : null))
|
||||||
|
setActiveId((id) => (id && suggestions.some((s) => s.id === id) ? id : null))
|
||||||
}, [editor, suggestions])
|
}, [editor, suggestions])
|
||||||
|
|
||||||
|
// Re-measure the margin rail: whether there's room for the column beside the
|
||||||
|
// editor, and where each suggestion's highlight sits vertically. Anchors are
|
||||||
|
// taken from the live decoration DOM (keyed by data-suggestion-id) relative to
|
||||||
|
// the wrapper — stable under scroll since text and wrapper scroll together.
|
||||||
|
// Deferred a frame so decoration DOM and reflow have settled.
|
||||||
|
const recomputeRail = useCallback(() => {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
const wrapper = wrapperRef.current
|
||||||
|
if (!wrapper) return
|
||||||
|
const wrapRect = wrapper.getBoundingClientRect()
|
||||||
|
// Need room for the 300px column + its 32px gutter (see .petal-rail), plus
|
||||||
|
// a little breathing space to the viewport edge.
|
||||||
|
setRailEnabled(window.innerWidth - wrapRect.right >= 348)
|
||||||
|
const seen = new Set<string>()
|
||||||
|
const items: RailItem[] = []
|
||||||
|
wrapper.querySelectorAll<HTMLElement>('.petal-suggestion[data-suggestion-id]').forEach((el) => {
|
||||||
|
const id = el.getAttribute('data-suggestion-id')
|
||||||
|
if (!id || seen.has(id)) return
|
||||||
|
const s = suggestions.find((x) => x.id === id)
|
||||||
|
if (!s) return
|
||||||
|
seen.add(id)
|
||||||
|
items.push({ suggestion: s, anchorTop: el.getBoundingClientRect().top - wrapRect.top })
|
||||||
|
})
|
||||||
|
setRailItems(items)
|
||||||
|
})
|
||||||
|
}, [suggestions])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
recomputeRailRef.current = recomputeRail
|
||||||
|
}, [recomputeRail])
|
||||||
|
|
||||||
|
// Re-anchor when the suggestion set changes (after the decorations repaint),
|
||||||
|
// and keep the rail in sync with viewport/editor width changes (room + reflow).
|
||||||
|
useEffect(() => {
|
||||||
|
recomputeRail()
|
||||||
|
const wrapper = wrapperRef.current
|
||||||
|
const ro = wrapper ? new ResizeObserver(() => recomputeRail()) : null
|
||||||
|
if (wrapper && ro) ro.observe(wrapper)
|
||||||
|
window.addEventListener('resize', recomputeRail)
|
||||||
|
return () => {
|
||||||
|
ro?.disconnect()
|
||||||
|
window.removeEventListener('resize', recomputeRail)
|
||||||
|
}
|
||||||
|
}, [recomputeRail])
|
||||||
|
|
||||||
|
// Emphasize the flagged text for the active suggestion, mirroring the rail
|
||||||
|
// card ↔ text link both ways. Driven through the decoration plugin (not an
|
||||||
|
// imperative DOM class) so it survives the repaints that fire on every edit.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!editor) return
|
||||||
|
setActiveSuggestion(editor.state, editor.view.dispatch, railEnabled ? activeId : null)
|
||||||
|
}, [editor, activeId, railEnabled])
|
||||||
|
|
||||||
|
// Scroll a suggestion's highlight to the middle of the viewport (clicking its
|
||||||
|
// rail card jumps the editor to the flagged text).
|
||||||
|
const scrollToSuggestion = useCallback((id: string) => {
|
||||||
|
const el = wrapperRef.current?.querySelector(
|
||||||
|
`.petal-suggestion[data-suggestion-id="${CSS.escape(id)}"]`,
|
||||||
|
)
|
||||||
|
el?.scrollIntoView({ block: 'center', behavior: 'smooth' })
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// Clicking a rail card's body jumps to the text and toggles its detail panel.
|
||||||
|
const activateRailCard = useCallback(
|
||||||
|
(id: string) => {
|
||||||
|
setActiveId(id)
|
||||||
|
scrollToSuggestion(id)
|
||||||
|
setRailExpandedId((cur) => (cur === id ? null : id))
|
||||||
|
},
|
||||||
|
[scrollToSuggestion],
|
||||||
|
)
|
||||||
|
|
||||||
|
const toggleRailExpand = useCallback((id: string) => {
|
||||||
|
setRailExpandedId((cur) => (cur === id ? null : id))
|
||||||
|
}, [])
|
||||||
|
|
||||||
const openCardFor = useCallback(
|
const openCardFor = useCallback(
|
||||||
(id: string, el: HTMLElement) => {
|
(id: string, el: HTMLElement) => {
|
||||||
const wrapper = wrapperRef.current
|
const wrapper = wrapperRef.current
|
||||||
@@ -297,10 +493,17 @@ export function EditorCore({
|
|||||||
if (!target) return
|
if (!target) return
|
||||||
const id = target.getAttribute('data-suggestion-id')
|
const id = target.getAttribute('data-suggestion-id')
|
||||||
if (!id) return
|
if (!id) return
|
||||||
|
// With the rail open the card already lives in the margin — hovering the
|
||||||
|
// text just emphasizes its card (and the highlight) rather than popping a
|
||||||
|
// second, redundant floating card.
|
||||||
|
if (railEnabled) {
|
||||||
|
setActiveId(id)
|
||||||
|
return
|
||||||
|
}
|
||||||
clearTimeout(closeTimer.current)
|
clearTimeout(closeTimer.current)
|
||||||
openCardFor(id, target)
|
openCardFor(id, target)
|
||||||
},
|
},
|
||||||
[openCardFor],
|
[openCardFor, railEnabled],
|
||||||
)
|
)
|
||||||
|
|
||||||
const scheduleClose = useCallback(() => {
|
const scheduleClose = useCallback(() => {
|
||||||
@@ -320,35 +523,53 @@ export function EditorCore({
|
|||||||
// pointer can bridge the small gap from text to card.
|
// pointer can bridge the small gap from text to card.
|
||||||
const handleMouseOut = useCallback(
|
const handleMouseOut = useCallback(
|
||||||
(e: React.MouseEvent) => {
|
(e: React.MouseEvent) => {
|
||||||
if ((e.target as HTMLElement).closest('.petal-suggestion')) scheduleClose()
|
if (!(e.target as HTMLElement).closest('.petal-suggestion')) return
|
||||||
|
if (railEnabled) {
|
||||||
|
setActiveId(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
scheduleClose()
|
||||||
},
|
},
|
||||||
[scheduleClose],
|
[scheduleClose, railEnabled],
|
||||||
)
|
)
|
||||||
|
|
||||||
const keepOpen = useCallback(() => clearTimeout(closeTimer.current), [])
|
const keepOpen = useCallback(() => clearTimeout(closeTimer.current), [])
|
||||||
|
|
||||||
// Accept applies the replacement to the document, plays a little confetti
|
// Accept applies the replacement to the document, plays a little confetti
|
||||||
// burst where the card sat, then notifies the parent.
|
// burst over the flagged text, then notifies the parent. The confetti is
|
||||||
|
// anchored to the highlight itself (captured before the replacement removes it),
|
||||||
|
// so it fires in the right spot whether the accept came from the hover card or
|
||||||
|
// the margin rail.
|
||||||
const handleAccept = useCallback(
|
const handleAccept = useCallback(
|
||||||
(s: Suggestion) => {
|
(s: Suggestion) => {
|
||||||
|
const wrapper = wrapperRef.current
|
||||||
|
const el = wrapper?.querySelector(
|
||||||
|
`.petal-suggestion[data-suggestion-id="${CSS.escape(s.id)}"]`,
|
||||||
|
) as HTMLElement | null
|
||||||
|
let burst: { top: number; left: number } | null = null
|
||||||
|
if (wrapper && el) {
|
||||||
|
const wrapRect = wrapper.getBoundingClientRect()
|
||||||
|
const elRect = el.getBoundingClientRect()
|
||||||
|
burst = { top: elRect.top - wrapRect.top, left: elRect.right - wrapRect.left }
|
||||||
|
}
|
||||||
if (editor && s.replacement.trim() !== '') {
|
if (editor && s.replacement.trim() !== '') {
|
||||||
const range = findRange(editor.state.doc, s.original)
|
const range = findRange(editor.state.doc, s.original)
|
||||||
if (range) {
|
if (range) {
|
||||||
editor.chain().focus().insertContentAt(range, s.replacement).run()
|
editor.chain().focus().insertContentAt(range, s.replacement).run()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setHover((h) => {
|
// Fall back to the hover card's position if the highlight wasn't found.
|
||||||
if (h) {
|
if (!burst && hover) burst = { top: hover.top, left: hover.left + 16 }
|
||||||
setConfetti({ top: h.top, left: h.left + 16 })
|
if (burst) {
|
||||||
clearTimeout(confettiTimer.current)
|
setConfetti(burst)
|
||||||
confettiTimer.current = setTimeout(() => setConfetti(null), 720)
|
clearTimeout(confettiTimer.current)
|
||||||
}
|
confettiTimer.current = setTimeout(() => setConfetti(null), 720)
|
||||||
return h
|
}
|
||||||
})
|
|
||||||
closeCard()
|
closeCard()
|
||||||
|
setRailExpandedId(null)
|
||||||
onAccept(s)
|
onAccept(s)
|
||||||
},
|
},
|
||||||
[editor, onAccept, closeCard],
|
[editor, onAccept, closeCard, hover],
|
||||||
)
|
)
|
||||||
|
|
||||||
const handleDismiss = useCallback(
|
const handleDismiss = useCallback(
|
||||||
@@ -359,9 +580,37 @@ export function EditorCore({
|
|||||||
[onDismiss, closeCard],
|
[onDismiss, closeCard],
|
||||||
)
|
)
|
||||||
|
|
||||||
// Click a red-underlined word to open its spelling popover, anchored under the
|
// openMisspellAt resolves the word at a document position and, if the checker
|
||||||
// word. posAtCoords→wordAt resolves the exact PM span (robust to the same
|
// flags it as misspelled, opens the spelling popover anchored under the word.
|
||||||
// misspelling appearing elsewhere); nspell supplies the corrections.
|
// Returns true if it opened a card. We resolve the word from coordinates and
|
||||||
|
// the checker rather than from the `.petal-misspelling` DOM span: clicking a
|
||||||
|
// word moves the caret into it, which fires the decoration rebuild that
|
||||||
|
// deliberately un-underlines the caret word (see SpellCheck's caret exemption),
|
||||||
|
// so by the time a click/contextmenu handler runs the span is already gone.
|
||||||
|
const openMisspellAt = useCallback(
|
||||||
|
(pos: number): boolean => {
|
||||||
|
if (!editor || !spellChecker) return false
|
||||||
|
const range = wordAt(editor.state.doc, pos)
|
||||||
|
if (!range || spellChecker.correct(range.word)) return false
|
||||||
|
const wrapper = wrapperRef.current
|
||||||
|
if (!wrapper) return false
|
||||||
|
const start = editor.view.coordsAtPos(range.from)
|
||||||
|
const end = editor.view.coordsAtPos(range.to)
|
||||||
|
const wrapRect = wrapper.getBoundingClientRect()
|
||||||
|
const cardWidth = 240
|
||||||
|
const left = Math.max(0, Math.min(start.left - wrapRect.left, wrapper.clientWidth - cardWidth))
|
||||||
|
const top = end.bottom - wrapRect.top + 6
|
||||||
|
// Opening a spelling popover supersedes any AI-suggestion or lookup card.
|
||||||
|
closeCard()
|
||||||
|
setWordInfo(null)
|
||||||
|
setMisspell({ ...range, suggestions: spellChecker.suggest(range.word), top, left })
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
[editor, spellChecker, closeCard],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Click a misspelled word to open its spelling popover, anchored under the
|
||||||
|
// word; nspell supplies the corrections.
|
||||||
//
|
//
|
||||||
// Tapping an AI-suggestion highlight also opens its card here — on touch there's
|
// Tapping an AI-suggestion highlight also opens its card here — on touch there's
|
||||||
// no hover, so the tap is the only way in (mouse users still get hover).
|
// no hover, so the tap is the only way in (mouse users still get hover).
|
||||||
@@ -370,29 +619,28 @@ export function EditorCore({
|
|||||||
const suggestionEl = (e.target as HTMLElement).closest('.petal-suggestion') as HTMLElement | null
|
const suggestionEl = (e.target as HTMLElement).closest('.petal-suggestion') as HTMLElement | null
|
||||||
if (suggestionEl) {
|
if (suggestionEl) {
|
||||||
const id = suggestionEl.getAttribute('data-suggestion-id')
|
const id = suggestionEl.getAttribute('data-suggestion-id')
|
||||||
if (id) openCardFor(id, suggestionEl)
|
if (id) {
|
||||||
|
// With the rail open, a tap emphasizes and expands its margin card
|
||||||
|
// instead of opening a floating one.
|
||||||
|
if (railEnabled) {
|
||||||
|
setActiveId(id)
|
||||||
|
setRailExpandedId(id)
|
||||||
|
} else {
|
||||||
|
openCardFor(id, suggestionEl)
|
||||||
|
}
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!editor || !spellChecker) return
|
if (!editor) return
|
||||||
const target = (e.target as HTMLElement).closest('.petal-misspelling') as HTMLElement | null
|
// Only act on clicks in the editor text itself — the floating cards/popovers
|
||||||
if (!target) return
|
// are children of this same wrapper, and a click on one shouldn't resolve a
|
||||||
const wrapper = wrapperRef.current
|
// (hidden) word behind it.
|
||||||
if (!wrapper) return
|
if (!(e.target as HTMLElement).closest('.petal-prose')) return
|
||||||
const coords = editor.view.posAtCoords({ left: e.clientX, top: e.clientY })
|
const coords = editor.view.posAtCoords({ left: e.clientX, top: e.clientY })
|
||||||
if (!coords) return
|
if (!coords) return
|
||||||
const range = wordAt(editor.state.doc, coords.pos)
|
openMisspellAt(coords.pos)
|
||||||
if (!range) return
|
|
||||||
const elRect = target.getBoundingClientRect()
|
|
||||||
const wrapRect = wrapper.getBoundingClientRect()
|
|
||||||
const cardWidth = 240
|
|
||||||
const left = Math.max(0, Math.min(elRect.left - wrapRect.left, wrapper.clientWidth - cardWidth))
|
|
||||||
const top = elRect.bottom - wrapRect.top + 6
|
|
||||||
// Opening a spelling popover supersedes any AI-suggestion hover card.
|
|
||||||
closeCard()
|
|
||||||
setWordInfo(null)
|
|
||||||
setMisspell({ ...range, suggestions: spellChecker.suggest(range.word), top, left })
|
|
||||||
},
|
},
|
||||||
[editor, spellChecker, closeCard, openCardFor],
|
[editor, openMisspellAt, openCardFor, railEnabled],
|
||||||
)
|
)
|
||||||
|
|
||||||
const replaceMisspelling = useCallback(
|
const replaceMisspelling = useCallback(
|
||||||
@@ -410,20 +658,31 @@ export function EditorCore({
|
|||||||
setMisspell(null)
|
setMisspell(null)
|
||||||
}, [misspell, onAddWord])
|
}, [misspell, onAddWord])
|
||||||
|
|
||||||
// Right-click a word to look it up: resolve the exact word span under the
|
// exampleAt pulls the sentence containing the position out of its block, for
|
||||||
// pointer, anchor a popover beneath it, and kick off the offline lookup. The
|
// review context in the garden. textBetween with a single-char leaf/break
|
||||||
// card opens immediately in a loading state and fills in when the (local)
|
// placeholder keeps the string indices aligned with ProseMirror's parentOffset
|
||||||
// lookup returns. Right-clicking off any word falls through to the native menu.
|
// (so a hard break or inline atom before the word doesn't desync the slice).
|
||||||
const handleContextMenu = useCallback(
|
const exampleAt = useCallback(
|
||||||
(e: React.MouseEvent) => {
|
(pos: number): string => {
|
||||||
|
if (!editor) return ''
|
||||||
|
const $pos = editor.state.doc.resolve(pos)
|
||||||
|
const text = $pos.parent.textBetween(0, $pos.parent.content.size, '\n', ' ')
|
||||||
|
return sentenceAround(text, Math.max(0, $pos.parentOffset))
|
||||||
|
},
|
||||||
|
[editor],
|
||||||
|
)
|
||||||
|
|
||||||
|
// openWordLookup resolves the exact word span at a document position, anchors a
|
||||||
|
// popover beneath it, and kicks off the offline lookup. The card opens
|
||||||
|
// immediately in a loading state and fills in when the (local) lookup returns.
|
||||||
|
// Shared by right-click, the keyboard shortcut (caret), and touch long-press.
|
||||||
|
const openWordLookup = useCallback(
|
||||||
|
(pos: number) => {
|
||||||
if (!editor) return
|
if (!editor) return
|
||||||
const coords = editor.view.posAtCoords({ left: e.clientX, top: e.clientY })
|
const range = wordAt(editor.state.doc, pos)
|
||||||
if (!coords) return
|
|
||||||
const range = wordAt(editor.state.doc, coords.pos)
|
|
||||||
if (!range) return
|
if (!range) return
|
||||||
const wrapper = wrapperRef.current
|
const wrapper = wrapperRef.current
|
||||||
if (!wrapper) return
|
if (!wrapper) return
|
||||||
e.preventDefault()
|
|
||||||
// Anchor under the word itself (not the click point) so the card lines up
|
// Anchor under the word itself (not the click point) so the card lines up
|
||||||
// with the text the way the spelling popover does.
|
// with the text the way the spelling popover does.
|
||||||
const start = editor.view.coordsAtPos(range.from)
|
const start = editor.view.coordsAtPos(range.from)
|
||||||
@@ -436,13 +695,40 @@ 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 example = exampleAt(range.from)
|
||||||
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))
|
// 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
|
||||||
|
// Reflect the saved state optimistically so the heart shows 💚 the
|
||||||
|
// moment a known word loads, rather than flashing 🤍 until the capture
|
||||||
|
// round-trips. vocabId is filled in when recordVocab returns.
|
||||||
|
setWordInfo((w) => (w ? { ...w, loading: false, info, saved: known } : null))
|
||||||
|
if (!known) return
|
||||||
|
api
|
||||||
|
.recordVocab({
|
||||||
|
word: range.word,
|
||||||
|
gloss: info.gloss,
|
||||||
|
definition: info.definitions[0]?.definition ?? '',
|
||||||
|
phonetic: info.phonetic,
|
||||||
|
example,
|
||||||
|
doc_id: docId,
|
||||||
|
})
|
||||||
|
.then((row) => {
|
||||||
|
// Discard a late capture if the card has since been superseded (a
|
||||||
|
// new lookup, navigation, or an explicit remove all bump the token),
|
||||||
|
// so it can't resurrect a word the writer just removed.
|
||||||
|
if (token !== wordReqRef.current) return
|
||||||
|
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)
|
||||||
@@ -451,9 +737,79 @@ 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(() => {
|
||||||
|
// Read the current card and do the network side effects OUTSIDE the state
|
||||||
|
// updater — an updater must be pure (React StrictMode double-invokes it,
|
||||||
|
// which would otherwise fire each request twice).
|
||||||
|
const w = wordInfo
|
||||||
|
if (!w || !w.info) return
|
||||||
|
if (w.vocabId) {
|
||||||
|
// Already in the garden — remove it, and invalidate any in-flight capture
|
||||||
|
// for this card so a late auto-capture can't resurrect the removed word.
|
||||||
|
const id = w.vocabId
|
||||||
|
wordReqRef.current++
|
||||||
|
setWordInfo((cur) => (cur ? { ...cur, saved: false, vocabId: null } : cur))
|
||||||
|
api.deleteVocab(id).catch((err) => console.error('vocab remove failed', err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Not in the garden yet — save it (idempotent upsert keyed on the word).
|
||||||
|
const word = w.word
|
||||||
|
const example = exampleAt(w.from)
|
||||||
|
setWordInfo((cur) => (cur ? { ...cur, saved: true } : cur))
|
||||||
|
api
|
||||||
|
.recordVocab({
|
||||||
|
word,
|
||||||
|
gloss: w.info.gloss,
|
||||||
|
definition: w.info.definitions[0]?.definition ?? '',
|
||||||
|
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))
|
||||||
|
}, [wordInfo, exampleAt, docId])
|
||||||
|
|
||||||
|
// Right-click a misspelled word for spelling corrections (the familiar "did you
|
||||||
|
// mean" gesture); right-click any other 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(
|
||||||
|
(e: React.MouseEvent) => {
|
||||||
|
if (!editor) return
|
||||||
|
const coords = editor.view.posAtCoords({ left: e.clientX, top: e.clientY })
|
||||||
|
if (!coords) return
|
||||||
|
if (!wordAt(editor.state.doc, coords.pos)) return
|
||||||
|
e.preventDefault()
|
||||||
|
// A misspelled word offers corrections first; otherwise look it up.
|
||||||
|
if (openMisspellAt(coords.pos)) return
|
||||||
|
openWordLookup(coords.pos)
|
||||||
|
},
|
||||||
|
[editor, openMisspellAt, openWordLookup],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Touch has no hover or right-click, so a long-press (~500ms without moving)
|
||||||
|
// opens the word lookup at the finger — the touch equivalent of right-click.
|
||||||
|
const longPressTimer = useRef<ReturnType<typeof setTimeout>>(undefined)
|
||||||
|
const handleTouchStart = useCallback(
|
||||||
|
(e: React.TouchEvent) => {
|
||||||
|
if (!editor || e.touches.length !== 1) return
|
||||||
|
const { clientX, clientY } = e.touches[0]
|
||||||
|
clearTimeout(longPressTimer.current)
|
||||||
|
longPressTimer.current = setTimeout(() => {
|
||||||
|
const coords = editor.view.posAtCoords({ left: clientX, top: clientY })
|
||||||
|
if (coords) openWordLookup(coords.pos)
|
||||||
|
}, 500)
|
||||||
|
},
|
||||||
|
[editor, openWordLookup],
|
||||||
|
)
|
||||||
|
const cancelLongPress = useCallback(() => clearTimeout(longPressTimer.current), [])
|
||||||
|
|
||||||
const replaceWord = useCallback(
|
const replaceWord = useCallback(
|
||||||
(synonym: string) => {
|
(synonym: string) => {
|
||||||
if (editor && wordInfo) {
|
if (editor && wordInfo) {
|
||||||
@@ -626,10 +982,52 @@ export function EditorCore({
|
|||||||
return () => document.removeEventListener('mousedown', onDown)
|
return () => document.removeEventListener('mousedown', onDown)
|
||||||
}, [misspell])
|
}, [misspell])
|
||||||
|
|
||||||
|
// A pointer-down in the editor starts a (possible) drag-select, which keeps the
|
||||||
|
// rewrite bubble hidden until release. A pointer-down on the bubble itself is
|
||||||
|
// excluded so its buttons stay clickable. Release always re-arms the bubble.
|
||||||
|
const handlePointerDown = useCallback((e: React.PointerEvent) => {
|
||||||
|
if ((e.target as HTMLElement).closest('.petal-selection-bubble')) return
|
||||||
|
setDragging(true)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onUp = () => setDragging(false)
|
||||||
|
document.addEventListener('pointerup', onUp)
|
||||||
|
return () => document.removeEventListener('pointerup', onUp)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// Editor keyboard shortcuts, so the ESL helpers aren't mouse-only:
|
||||||
|
// Ctrl/Cmd+F — Find & Replace (overrides the browser find, which can't see
|
||||||
|
// into the editor's content anyway)
|
||||||
|
// Ctrl/Cmd+D — look up the word at the caret (the keyboard "right-click")
|
||||||
|
// Ctrl/Cmd+J — rewrite the current selection more naturally (✨更自然)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!editor) return
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (!(e.ctrlKey || e.metaKey) || e.altKey) return
|
||||||
|
const k = e.key.toLowerCase()
|
||||||
|
if (k === 'f') {
|
||||||
|
e.preventDefault()
|
||||||
|
setFindOpen(true)
|
||||||
|
} else if (k === 'd') {
|
||||||
|
e.preventDefault()
|
||||||
|
openWordLookup(editor.state.selection.from)
|
||||||
|
} else if (k === 'j') {
|
||||||
|
if (!editor.state.selection.empty) {
|
||||||
|
e.preventDefault()
|
||||||
|
handleRewrite('natural')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', onKey)
|
||||||
|
return () => window.removeEventListener('keydown', onKey)
|
||||||
|
}, [editor, openWordLookup, handleRewrite])
|
||||||
|
|
||||||
useEffect(() => () => {
|
useEffect(() => () => {
|
||||||
clearTimeout(closeTimer.current)
|
clearTimeout(closeTimer.current)
|
||||||
clearTimeout(confettiTimer.current)
|
clearTimeout(confettiTimer.current)
|
||||||
clearTimeout(glossTimer.current)
|
clearTimeout(glossTimer.current)
|
||||||
|
clearTimeout(longPressTimer.current)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// While pinned (Ask Petal open), a pointer-down outside the card closes it —
|
// While pinned (Ask Petal open), a pointer-down outside the card closes it —
|
||||||
@@ -659,7 +1057,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"
|
||||||
@@ -667,16 +1071,22 @@ export function EditorCore({
|
|||||||
onMouseOut={handleMouseOut}
|
onMouseOut={handleMouseOut}
|
||||||
onMouseMove={handleMouseMove}
|
onMouseMove={handleMouseMove}
|
||||||
onMouseLeave={handleMouseLeave}
|
onMouseLeave={handleMouseLeave}
|
||||||
|
onPointerDown={handlePointerDown}
|
||||||
onClick={handleSpellClick}
|
onClick={handleSpellClick}
|
||||||
onContextMenu={handleContextMenu}
|
onContextMenu={handleContextMenu}
|
||||||
|
onTouchStart={handleTouchStart}
|
||||||
|
onTouchMove={cancelLongPress}
|
||||||
|
onTouchEnd={cancelLongPress}
|
||||||
>
|
>
|
||||||
<EditorContent editor={editor} className="h-full" />
|
<EditorContent editor={editor} className="h-full" />
|
||||||
|
{findOpen && editor && <FindReplace editor={editor} onClose={() => setFindOpen(false)} />}
|
||||||
{confetti && <Confetti top={confetti.top} left={confetti.left} />}
|
{confetti && <Confetti top={confetti.top} left={confetti.left} />}
|
||||||
{gloss && <GlossTip gloss={gloss.gloss} style={{ top: gloss.top, left: gloss.left }} />}
|
{gloss && <GlossTip gloss={gloss.gloss} style={{ top: gloss.top, left: gloss.left }} />}
|
||||||
{selection && !rewrite && (
|
{selection && !rewrite && !dragging && (
|
||||||
<SelectionBubble
|
<SelectionBubble
|
||||||
style={{ top: selection.top, left: selection.left, transform: 'translateY(calc(-100% - 8px))' }}
|
style={{ top: selection.top, left: selection.left, transform: 'translateY(calc(-100% - 8px))' }}
|
||||||
onRewrite={handleRewrite}
|
onRewrite={handleRewrite}
|
||||||
|
onSpeak={speechSupported() ? () => speak(selection.text) : null}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{rewrite && (
|
{rewrite && (
|
||||||
@@ -696,6 +1106,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}
|
||||||
/>
|
/>
|
||||||
@@ -709,7 +1121,7 @@ export function EditorCore({
|
|||||||
onAdd={addMisspellingToDict}
|
onAdd={addMisspellingToDict}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{hover && (
|
{hover && !railEnabled && (
|
||||||
<SuggestionCard
|
<SuggestionCard
|
||||||
suggestion={hover.suggestion}
|
suggestion={hover.suggestion}
|
||||||
style={{ top: hover.top, left: hover.left }}
|
style={{ top: hover.top, left: hover.left }}
|
||||||
@@ -720,6 +1132,18 @@ export function EditorCore({
|
|||||||
onExpandChange={setPinned}
|
onExpandChange={setPinned}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{railEnabled && railItems.length > 0 && (
|
||||||
|
<SuggestionRail
|
||||||
|
items={railItems}
|
||||||
|
activeId={activeId}
|
||||||
|
expandedId={railExpandedId}
|
||||||
|
onAccept={handleAccept}
|
||||||
|
onDismiss={handleDismiss}
|
||||||
|
onHover={setActiveId}
|
||||||
|
onActivate={activateRailCard}
|
||||||
|
onToggleExpand={toggleRailExpand}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
238
web/src/components/Editor/FindReplace.tsx
Normal file
238
web/src/components/Editor/FindReplace.tsx
Normal file
@@ -0,0 +1,238 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
import type { Editor } from '@tiptap/react'
|
||||||
|
import { clearSearch, getSearchState, setActive, setSearch } from './SearchHighlight'
|
||||||
|
|
||||||
|
// FindReplace is the in-document search bar (Ctrl/Cmd+F). It drives the
|
||||||
|
// SearchHighlight decoration layer: typing updates the highlighted matches, the
|
||||||
|
// arrows step through them (scrolling each into view), and replace / replace-all
|
||||||
|
// edit the document in place. Bilingual, zh-first, matching the editor chrome.
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
editor: Editor
|
||||||
|
onClose: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const CJK = "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif"
|
||||||
|
|
||||||
|
// Scroll the active match into the middle of the viewport without moving the
|
||||||
|
// selection (which would otherwise pop the rewrite bubble).
|
||||||
|
function scrollToActive(editor: Editor) {
|
||||||
|
const st = getSearchState(editor.state)
|
||||||
|
if (st.active < 0) return
|
||||||
|
const m = st.matches[st.active]
|
||||||
|
const dom = editor.view.domAtPos(m.from)
|
||||||
|
const el = dom.node.nodeType === Node.TEXT_NODE ? dom.node.parentElement : (dom.node as HTMLElement)
|
||||||
|
el?.scrollIntoView({ block: 'center', behavior: 'smooth' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FindReplace({ editor, onClose }: Props) {
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
const [replacement, setReplacement] = useState('')
|
||||||
|
const [caseSensitive, setCaseSensitive] = useState(false)
|
||||||
|
const [showReplace, setShowReplace] = useState(false)
|
||||||
|
// Mirror of the plugin's match count + active index for the "n / m" readout.
|
||||||
|
const [{ count, active }, setCounts] = useState({ count: 0, active: -1 })
|
||||||
|
const findRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
const sync = useCallback(() => {
|
||||||
|
const st = getSearchState(editor.state)
|
||||||
|
setCounts({ count: st.matches.length, active: st.active })
|
||||||
|
}, [editor])
|
||||||
|
|
||||||
|
// Push the query into the decoration layer whenever it (or case-sensitivity)
|
||||||
|
// changes, then jump to the first match.
|
||||||
|
useEffect(() => {
|
||||||
|
setSearch(editor.state, editor.view.dispatch, query, caseSensitive)
|
||||||
|
sync()
|
||||||
|
scrollToActive(editor)
|
||||||
|
}, [editor, query, caseSensitive, sync])
|
||||||
|
|
||||||
|
// Tear the highlight layer down when the bar closes.
|
||||||
|
useEffect(() => () => clearSearch(editor.state, editor.view.dispatch), [editor])
|
||||||
|
|
||||||
|
// Focus the find field on open.
|
||||||
|
useEffect(() => {
|
||||||
|
findRef.current?.focus()
|
||||||
|
findRef.current?.select()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const go = useCallback(
|
||||||
|
(delta: number) => {
|
||||||
|
const st = getSearchState(editor.state)
|
||||||
|
if (!st.matches.length) return
|
||||||
|
setActive(editor.state, editor.view.dispatch, st.active + delta)
|
||||||
|
sync()
|
||||||
|
scrollToActive(editor)
|
||||||
|
},
|
||||||
|
[editor, sync],
|
||||||
|
)
|
||||||
|
|
||||||
|
const replaceActive = useCallback(() => {
|
||||||
|
const st = getSearchState(editor.state)
|
||||||
|
if (st.active < 0) return
|
||||||
|
const m = st.matches[st.active]
|
||||||
|
const tr = editor.state.tr
|
||||||
|
if (replacement) tr.insertText(replacement, m.from, m.to)
|
||||||
|
else tr.delete(m.from, m.to)
|
||||||
|
editor.view.dispatch(tr)
|
||||||
|
sync()
|
||||||
|
scrollToActive(editor)
|
||||||
|
}, [editor, replacement, sync])
|
||||||
|
|
||||||
|
const replaceAll = useCallback(() => {
|
||||||
|
const st = getSearchState(editor.state)
|
||||||
|
if (!st.matches.length) return
|
||||||
|
const tr = editor.state.tr
|
||||||
|
// Apply back-to-front so earlier edits don't shift later match positions.
|
||||||
|
for (let i = st.matches.length - 1; i >= 0; i--) {
|
||||||
|
const m = st.matches[i]
|
||||||
|
if (replacement) tr.insertText(replacement, m.from, m.to)
|
||||||
|
else tr.delete(m.from, m.to)
|
||||||
|
}
|
||||||
|
editor.view.dispatch(tr)
|
||||||
|
sync()
|
||||||
|
}, [editor, replacement, sync])
|
||||||
|
|
||||||
|
const inputStyle: React.CSSProperties = {
|
||||||
|
borderRadius: 'var(--radius-input)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
color: 'var(--color-plum)',
|
||||||
|
fontFamily: CJK,
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="petal-no-print absolute right-2 top-2 z-40 flex flex-col gap-1.5 p-2"
|
||||||
|
role="dialog"
|
||||||
|
aria-label="Find and replace"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
e.preventDefault()
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
style={{
|
||||||
|
width: 320,
|
||||||
|
background: 'var(--color-surface)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
borderRadius: 'var(--radius-card)',
|
||||||
|
boxShadow: 'var(--shadow-soft)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowReplace((v) => !v)}
|
||||||
|
aria-label={showReplace ? 'Hide replace' : 'Show replace'}
|
||||||
|
title={showReplace ? 'Hide replace' : 'Show replace'}
|
||||||
|
className="flex h-8 w-6 items-center justify-center text-xs"
|
||||||
|
style={{ color: 'var(--color-muted)' }}
|
||||||
|
>
|
||||||
|
{showReplace ? '▾' : '▸'}
|
||||||
|
</button>
|
||||||
|
<input
|
||||||
|
ref={findRef}
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault()
|
||||||
|
go(e.shiftKey ? -1 : 1)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="查找 · Find"
|
||||||
|
className="min-w-0 flex-1 px-2 py-1.5 text-sm focus:outline-none"
|
||||||
|
style={inputStyle}
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
className="w-14 shrink-0 text-center text-xs tabular-nums"
|
||||||
|
style={{ color: 'var(--color-muted)' }}
|
||||||
|
>
|
||||||
|
{count ? `${active + 1} / ${count}` : query ? '无 · 0' : ''}
|
||||||
|
</span>
|
||||||
|
<FindBtn label="Previous match" disabled={!count} onClick={() => go(-1)}>↑</FindBtn>
|
||||||
|
<FindBtn label="Next match" disabled={!count} onClick={() => go(1)}>↓</FindBtn>
|
||||||
|
<FindBtn
|
||||||
|
label="Match case"
|
||||||
|
active={caseSensitive}
|
||||||
|
onClick={() => setCaseSensitive((v) => !v)}
|
||||||
|
title="Match case · 区分大小写"
|
||||||
|
>
|
||||||
|
Aa
|
||||||
|
</FindBtn>
|
||||||
|
<FindBtn label="Close" onClick={onClose} title="Close · 关闭">✕</FindBtn>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showReplace && (
|
||||||
|
<div className="flex items-center gap-1.5 pl-7">
|
||||||
|
<input
|
||||||
|
value={replacement}
|
||||||
|
onChange={(e) => setReplacement(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault()
|
||||||
|
replaceActive()
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="替换为 · Replace"
|
||||||
|
className="min-w-0 flex-1 px-2 py-1.5 text-sm focus:outline-none"
|
||||||
|
style={inputStyle}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={replaceActive}
|
||||||
|
disabled={!count}
|
||||||
|
className="h-8 shrink-0 whitespace-nowrap px-2.5 text-xs font-semibold disabled:opacity-40"
|
||||||
|
style={{ borderRadius: 'var(--radius-pill)', background: 'var(--color-surface-alt)', color: 'var(--color-plum)' }}
|
||||||
|
>
|
||||||
|
替换
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={replaceAll}
|
||||||
|
disabled={!count}
|
||||||
|
className="h-8 shrink-0 whitespace-nowrap px-2.5 text-xs font-bold disabled:opacity-40"
|
||||||
|
style={{ borderRadius: 'var(--radius-pill)', background: 'var(--color-accent)', color: '#fff' }}
|
||||||
|
>
|
||||||
|
全部
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FindBtn({
|
||||||
|
children,
|
||||||
|
onClick,
|
||||||
|
label,
|
||||||
|
title,
|
||||||
|
active,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode
|
||||||
|
onClick: () => void
|
||||||
|
label: string
|
||||||
|
title?: string
|
||||||
|
active?: boolean
|
||||||
|
disabled?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={label}
|
||||||
|
title={title ?? label}
|
||||||
|
aria-pressed={active}
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={onClick}
|
||||||
|
className="flex h-8 min-w-8 items-center justify-center px-1.5 text-sm font-semibold disabled:opacity-40"
|
||||||
|
style={{
|
||||||
|
borderRadius: 'var(--radius-input)',
|
||||||
|
color: active ? 'var(--color-accent-hover)' : 'var(--color-muted)',
|
||||||
|
background: active ? 'var(--color-surface-alt)' : 'transparent',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
51
web/src/components/Editor/FontSize.ts
Normal file
51
web/src/components/Editor/FontSize.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { Extension } from '@tiptap/core'
|
||||||
|
|
||||||
|
// FontSize adds a `fontSize` attribute to the textStyle mark so a writer can
|
||||||
|
// pick a size preset (Small / Normal / Large / Title) from the toolbar. It rides
|
||||||
|
// on TextStyle (already loaded) rather than introducing a new mark, so it stacks
|
||||||
|
// cleanly with color and other inline styling.
|
||||||
|
declare module '@tiptap/core' {
|
||||||
|
interface Commands<ReturnType> {
|
||||||
|
fontSize: {
|
||||||
|
setFontSize: (size: string) => ReturnType
|
||||||
|
unsetFontSize: () => ReturnType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const FontSize = Extension.create({
|
||||||
|
name: 'fontSize',
|
||||||
|
|
||||||
|
addOptions() {
|
||||||
|
return { types: ['textStyle'] }
|
||||||
|
},
|
||||||
|
|
||||||
|
addGlobalAttributes() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
types: this.options.types,
|
||||||
|
attributes: {
|
||||||
|
fontSize: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.style.fontSize || null,
|
||||||
|
renderHTML: (attributes) =>
|
||||||
|
attributes.fontSize ? { style: `font-size: ${attributes.fontSize}` } : {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
addCommands() {
|
||||||
|
return {
|
||||||
|
setFontSize:
|
||||||
|
(size) =>
|
||||||
|
({ chain }) =>
|
||||||
|
chain().setMark('textStyle', { fontSize: size }).run(),
|
||||||
|
unsetFontSize:
|
||||||
|
() =>
|
||||||
|
({ chain }) =>
|
||||||
|
chain().setMark('textStyle', { fontSize: null }).removeEmptyTextStyle().run(),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
143
web/src/components/Editor/SearchHighlight.ts
Normal file
143
web/src/components/Editor/SearchHighlight.ts
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
import { Extension } from '@tiptap/core'
|
||||||
|
import { Plugin, PluginKey } from '@tiptap/pm/state'
|
||||||
|
import type { EditorState, Transaction } from '@tiptap/pm/state'
|
||||||
|
import { Decoration, DecorationSet } from '@tiptap/pm/view'
|
||||||
|
import type { Node as PMNode } from '@tiptap/pm/model'
|
||||||
|
import { mapOffset } from './SuggestionHighlight'
|
||||||
|
|
||||||
|
// SearchHighlight powers the in-document Find & Replace bar. Like the suggestion
|
||||||
|
// layer it uses ProseMirror *decorations* (not stored marks), so matches are
|
||||||
|
// recomputed from the live document on every edit and never leave a stale
|
||||||
|
// highlight behind. Matches are found per-textblock (a query never spans a
|
||||||
|
// paragraph break), mirroring how the rest of the editor anchors text.
|
||||||
|
|
||||||
|
export interface Match {
|
||||||
|
from: number
|
||||||
|
to: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PluginState {
|
||||||
|
query: string
|
||||||
|
caseSensitive: boolean
|
||||||
|
matches: Match[]
|
||||||
|
active: number // index into matches, or -1 when there are none
|
||||||
|
decorations: DecorationSet
|
||||||
|
}
|
||||||
|
|
||||||
|
export const searchPluginKey = new PluginKey<PluginState>('petalSearch')
|
||||||
|
|
||||||
|
// findMatches collects every occurrence of `query` across the document's
|
||||||
|
// textblocks and maps each to an absolute ProseMirror range.
|
||||||
|
function findMatches(doc: PMNode, query: string, caseSensitive: boolean): Match[] {
|
||||||
|
if (!query) return []
|
||||||
|
const needle = caseSensitive ? query : query.toLowerCase()
|
||||||
|
const matches: Match[] = []
|
||||||
|
doc.descendants((node, pos) => {
|
||||||
|
if (!node.isTextblock) return true
|
||||||
|
const haystackRaw = node.textContent
|
||||||
|
const haystack = caseSensitive ? haystackRaw : haystackRaw.toLowerCase()
|
||||||
|
let idx = haystack.indexOf(needle)
|
||||||
|
while (idx >= 0) {
|
||||||
|
matches.push({
|
||||||
|
from: mapOffset(node, pos, idx),
|
||||||
|
to: mapOffset(node, pos, idx + query.length),
|
||||||
|
})
|
||||||
|
idx = haystack.indexOf(needle, idx + query.length)
|
||||||
|
}
|
||||||
|
return false // don't descend into inline children
|
||||||
|
})
|
||||||
|
return matches
|
||||||
|
}
|
||||||
|
|
||||||
|
function build(doc: PMNode, query: string, caseSensitive: boolean, preferred: number): PluginState {
|
||||||
|
const matches = findMatches(doc, query, caseSensitive)
|
||||||
|
const active = matches.length === 0 ? -1 : Math.max(0, Math.min(preferred, matches.length - 1))
|
||||||
|
const decos = matches.map((m, i) =>
|
||||||
|
Decoration.inline(m.from, m.to, {
|
||||||
|
class: i === active ? 'petal-find-match petal-find-match-active' : 'petal-find-match',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
return { query, caseSensitive, matches, active, decorations: DecorationSet.create(doc, decos) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY: PluginState = {
|
||||||
|
query: '',
|
||||||
|
caseSensitive: false,
|
||||||
|
matches: [],
|
||||||
|
active: -1,
|
||||||
|
decorations: DecorationSet.empty,
|
||||||
|
}
|
||||||
|
|
||||||
|
// setSearch updates the query / case-sensitivity and recomputes matches. Passing
|
||||||
|
// an empty query clears the layer.
|
||||||
|
export function setSearch(
|
||||||
|
state: EditorState,
|
||||||
|
dispatch: (tr: Transaction) => void,
|
||||||
|
query: string,
|
||||||
|
caseSensitive: boolean,
|
||||||
|
) {
|
||||||
|
dispatch(state.tr.setMeta(searchPluginKey, { kind: 'search', query, caseSensitive }))
|
||||||
|
}
|
||||||
|
|
||||||
|
// setActive moves the highlighted (current) match by index.
|
||||||
|
export function setActive(state: EditorState, dispatch: (tr: Transaction) => void, index: number) {
|
||||||
|
dispatch(state.tr.setMeta(searchPluginKey, { kind: 'active', index }))
|
||||||
|
}
|
||||||
|
|
||||||
|
// clearSearch tears the layer down (on close).
|
||||||
|
export function clearSearch(state: EditorState, dispatch: (tr: Transaction) => void) {
|
||||||
|
dispatch(state.tr.setMeta(searchPluginKey, { kind: 'clear' }))
|
||||||
|
}
|
||||||
|
|
||||||
|
// getSearchState reads the live plugin state (match list + active index) so the
|
||||||
|
// Find bar can render "n / m" and drive navigation/replacement.
|
||||||
|
export function getSearchState(state: EditorState): PluginState {
|
||||||
|
return searchPluginKey.getState(state) ?? EMPTY
|
||||||
|
}
|
||||||
|
|
||||||
|
type Meta =
|
||||||
|
| { kind: 'search'; query: string; caseSensitive: boolean }
|
||||||
|
| { kind: 'active'; index: number }
|
||||||
|
| { kind: 'clear' }
|
||||||
|
|
||||||
|
export const SearchHighlight = Extension.create({
|
||||||
|
name: 'searchHighlight',
|
||||||
|
|
||||||
|
addProseMirrorPlugins() {
|
||||||
|
return [
|
||||||
|
new Plugin<PluginState>({
|
||||||
|
key: searchPluginKey,
|
||||||
|
state: {
|
||||||
|
init: () => EMPTY,
|
||||||
|
apply(tr, value, _oldState, newState): PluginState {
|
||||||
|
const meta = tr.getMeta(searchPluginKey) as Meta | undefined
|
||||||
|
if (meta?.kind === 'search') {
|
||||||
|
return build(newState.doc, meta.query, meta.caseSensitive, value.active < 0 ? 0 : value.active)
|
||||||
|
}
|
||||||
|
if (meta?.kind === 'active') {
|
||||||
|
if (value.matches.length === 0) return value
|
||||||
|
const active = ((meta.index % value.matches.length) + value.matches.length) % value.matches.length
|
||||||
|
const decos = value.matches.map((m, i) =>
|
||||||
|
Decoration.inline(m.from, m.to, {
|
||||||
|
class: i === active ? 'petal-find-match petal-find-match-active' : 'petal-find-match',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
return { ...value, active, decorations: DecorationSet.create(newState.doc, decos) }
|
||||||
|
}
|
||||||
|
if (meta?.kind === 'clear') return EMPTY
|
||||||
|
// Re-anchor on any document change so highlights track edits/replaces.
|
||||||
|
if (tr.docChanged && value.query) {
|
||||||
|
return build(newState.doc, value.query, value.caseSensitive, value.active)
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
},
|
||||||
|
},
|
||||||
|
props: {
|
||||||
|
decorations(state) {
|
||||||
|
return searchPluginKey.getState(state)?.decorations
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -27,11 +27,14 @@ export const REWRITE_STYLES: RewriteStyle[] = [
|
|||||||
interface Props {
|
interface Props {
|
||||||
style: React.CSSProperties
|
style: React.CSSProperties
|
||||||
onRewrite: (style: string) => void
|
onRewrite: (style: string) => void
|
||||||
|
// Read the selected text aloud (null when speech isn't available — the button
|
||||||
|
// is then hidden).
|
||||||
|
onSpeak: (() => void) | null
|
||||||
}
|
}
|
||||||
|
|
||||||
const CJK = "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif"
|
const CJK = "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif"
|
||||||
|
|
||||||
export function SelectionBubble({ style, onRewrite }: Props) {
|
export function SelectionBubble({ style, onRewrite, onSpeak }: Props) {
|
||||||
const [natural, ...tones] = REWRITE_STYLES
|
const [natural, ...tones] = REWRITE_STYLES
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -39,21 +42,25 @@ export function SelectionBubble({ style, onRewrite }: Props) {
|
|||||||
className="petal-selection-bubble absolute z-30 flex max-w-[360px] flex-wrap items-center gap-1.5 p-2"
|
className="petal-selection-bubble absolute z-30 flex max-w-[360px] flex-wrap items-center gap-1.5 p-2"
|
||||||
role="toolbar"
|
role="toolbar"
|
||||||
aria-label="Rewrite the selection"
|
aria-label="Rewrite the selection"
|
||||||
onMouseDown={(e) => e.preventDefault()} // keep the editor selection
|
|
||||||
style={{
|
style={{
|
||||||
background: 'var(--color-surface)',
|
background: 'var(--color-surface)',
|
||||||
border: '1px solid var(--color-border)',
|
border: '1px solid var(--color-border)',
|
||||||
borderRadius: 'var(--radius-pill)',
|
borderRadius: 'var(--radius-pill)',
|
||||||
boxShadow: 'var(--shadow-soft)',
|
boxShadow: 'var(--shadow-soft)',
|
||||||
fontFamily: CJK,
|
fontFamily: CJK,
|
||||||
|
// Only the buttons capture the pointer; clicks landing on the bubble's
|
||||||
|
// padding/gaps fall through to the text underneath so it never blocks
|
||||||
|
// where the user is trying to click.
|
||||||
|
pointerEvents: 'none',
|
||||||
...style,
|
...style,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()} // keep the editor selection
|
||||||
onClick={() => onRewrite(natural.value)}
|
onClick={() => onRewrite(natural.value)}
|
||||||
className="inline-flex h-8 items-center gap-1.5 whitespace-nowrap px-3 text-sm font-bold"
|
className="inline-flex h-8 items-center gap-1.5 whitespace-nowrap px-3 text-sm font-bold"
|
||||||
style={{ borderRadius: 'var(--radius-pill)', background: 'var(--color-accent)', color: 'var(--color-plum)' }}
|
style={{ borderRadius: 'var(--radius-pill)', background: 'var(--color-accent)', color: 'var(--color-plum)', pointerEvents: 'auto' }}
|
||||||
title="Rewrite the selection to sound more natural"
|
title="Rewrite the selection to sound more natural"
|
||||||
>
|
>
|
||||||
<span aria-hidden>{natural.emoji}</span>
|
<span aria-hidden>{natural.emoji}</span>
|
||||||
@@ -63,15 +70,30 @@ export function SelectionBubble({ style, onRewrite }: Props) {
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{onSpeak && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()} // keep the editor selection
|
||||||
|
onClick={onSpeak}
|
||||||
|
className="inline-flex h-8 items-center justify-center px-2 text-sm"
|
||||||
|
style={{ borderRadius: 'var(--radius-pill)', background: 'var(--color-surface-alt)', color: 'var(--color-plum)', pointerEvents: 'auto' }}
|
||||||
|
title="朗读所选 · Read selection aloud"
|
||||||
|
aria-label="Read selection aloud"
|
||||||
|
>
|
||||||
|
🔊
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
<span className="mx-0.5 h-5 w-px shrink-0" style={{ background: 'var(--color-border)' }} />
|
<span className="mx-0.5 h-5 w-px shrink-0" style={{ background: 'var(--color-border)' }} />
|
||||||
|
|
||||||
{tones.map((t) => (
|
{tones.map((t) => (
|
||||||
<button
|
<button
|
||||||
key={t.value}
|
key={t.value}
|
||||||
type="button"
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()} // keep the editor selection
|
||||||
onClick={() => onRewrite(t.value)}
|
onClick={() => onRewrite(t.value)}
|
||||||
className="inline-flex h-8 items-center gap-1 whitespace-nowrap px-2.5 text-sm font-semibold"
|
className="inline-flex h-8 items-center gap-1 whitespace-nowrap px-2.5 text-sm font-semibold"
|
||||||
style={{ borderRadius: 'var(--radius-pill)', background: 'var(--color-surface-alt)', color: 'var(--color-plum)' }}
|
style={{ borderRadius: 'var(--radius-pill)', background: 'var(--color-surface-alt)', color: 'var(--color-plum)', pointerEvents: 'auto' }}
|
||||||
onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--color-lavender)')}
|
onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--color-lavender)')}
|
||||||
onMouseLeave={(e) => (e.currentTarget.style.background = 'var(--color-surface-alt)')}
|
onMouseLeave={(e) => (e.currentTarget.style.background = 'var(--color-surface-alt)')}
|
||||||
title={`Rewrite in a ${t.en.toLowerCase()} tone`}
|
title={`Rewrite in a ${t.en.toLowerCase()} tone`}
|
||||||
|
|||||||
@@ -1,15 +1,7 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import type { Suggestion, SuggestionType } from '../../api/client'
|
import type { Suggestion } from '../../api/client'
|
||||||
import { AskPetal } from './AskPetal'
|
import { AskPetal } from './AskPetal'
|
||||||
|
import { TYPE_META } from './suggestionMeta'
|
||||||
// Per-type accent color + human label, mirroring the design tokens.
|
|
||||||
const TYPE_META: Record<SuggestionType, { color: string; label: string }> = {
|
|
||||||
grammar: { color: 'var(--color-mint)', label: 'Grammar' },
|
|
||||||
phrasing: { color: 'var(--color-peach)', label: 'Phrasing' },
|
|
||||||
idiom: { color: 'var(--color-lavender)', label: 'Idiom' },
|
|
||||||
clarity: { color: 'var(--color-sky)', label: 'Clarity' },
|
|
||||||
voice: { color: 'var(--color-honey)', label: 'Voice' },
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
suggestion: Suggestion
|
suggestion: Suggestion
|
||||||
|
|||||||
54
web/src/components/Editor/SuggestionHighlight.test.ts
Normal file
54
web/src/components/Editor/SuggestionHighlight.test.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { foldTypography, findRange } from './SuggestionHighlight'
|
||||||
|
import { Schema, type Node as PMNode } from '@tiptap/pm/model'
|
||||||
|
|
||||||
|
// A minimal doc/paragraph/text schema, enough to exercise findRange's textblock
|
||||||
|
// walk without pulling in the full editor.
|
||||||
|
const schema = new Schema({
|
||||||
|
nodes: {
|
||||||
|
doc: { content: 'block+' },
|
||||||
|
paragraph: { group: 'block', content: 'inline*', toDOM: () => ['p', 0] },
|
||||||
|
text: { group: 'inline' },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Build a single-paragraph doc with the given plaintext.
|
||||||
|
const para = (text: string): PMNode => schema.node('doc', null, [schema.node('paragraph', null, text ? [schema.text(text)] : [])])
|
||||||
|
|
||||||
|
describe('foldTypography', () => {
|
||||||
|
it('folds curly quotes back to straight ASCII', () => {
|
||||||
|
expect(foldTypography('“He’s here,” she said').folded).toBe('"He\'s here," she said')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('folds dashes and ellipsis, keeping a source-index map across length changes', () => {
|
||||||
|
const { folded, map } = foldTypography('wait—really...')
|
||||||
|
expect(folded).toBe('wait—really…')
|
||||||
|
// The em dash is already one glyph; the `...` collapsed 3 source chars to 1,
|
||||||
|
// so the trailing sentinel still points just past the last source char.
|
||||||
|
expect(map[map.length - 1]).toBe('wait—really...'.length)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('treats `--` and `...` typed-but-unconverted as their canonical glyphs', () => {
|
||||||
|
expect(foldTypography('a--b...c').folded).toBe('a—b…c')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('findRange typographic anchoring', () => {
|
||||||
|
it('anchors a model echo with straight quotes onto curly-quote document text', () => {
|
||||||
|
const doc = para('She said “hello” to me')
|
||||||
|
const range = findRange(doc, '“hello”'.replace(/[“”]/g, '"')) // model echoed "hello"
|
||||||
|
expect(range).not.toBeNull()
|
||||||
|
// The matched span must cover the curly-quoted region in the real document.
|
||||||
|
expect(doc.textBetween(range!.from - 1, range!.to - 1)).toContain('hello')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('anchors an ASCII `--` echo onto an em-dash in the document', () => {
|
||||||
|
const doc = para('I waited—forever')
|
||||||
|
const range = findRange(doc, 'waited--forever')
|
||||||
|
expect(range).not.toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('still returns null when the text genuinely is not present', () => {
|
||||||
|
expect(findRange(para('nothing to see'), 'absent phrase')).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -16,9 +16,17 @@ export const suggestionPluginKey = new PluginKey<PluginState>('petalSuggestions'
|
|||||||
|
|
||||||
interface PluginState {
|
interface PluginState {
|
||||||
suggestions: Suggestion[]
|
suggestions: Suggestion[]
|
||||||
|
// The suggestion currently emphasized from its margin card / a hover, or null.
|
||||||
|
// Carried in plugin state (not an imperative DOM class) so it survives the
|
||||||
|
// decoration repaints that fire on every document change.
|
||||||
|
activeId: string | null
|
||||||
decorations: DecorationSet
|
decorations: DecorationSet
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Meta carried on a transaction to update the plugin: either a fresh suggestion
|
||||||
|
// list or a change to which suggestion is emphasized.
|
||||||
|
type SuggestionMeta = { suggestions: Suggestion[] } | { activeId: string | null }
|
||||||
|
|
||||||
// mapOffset converts a character offset within a textblock's flattened text into
|
// mapOffset converts a character offset within a textblock's flattened text into
|
||||||
// an absolute ProseMirror position, accounting for inline atoms (e.g. hard
|
// an absolute ProseMirror position, accounting for inline atoms (e.g. hard
|
||||||
// breaks) that occupy a position but contribute no text.
|
// breaks) that occupy a position but contribute no text.
|
||||||
@@ -42,21 +50,87 @@ export function mapOffset(block: PMNode, blockPos: number, targetOffset: number)
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// foldTypography canonicalizes the typographic variants that the editor's
|
||||||
|
// Typography input rules introduce (curly quotes, em/en dashes, single-glyph
|
||||||
|
// ellipsis) and the unicode spaces a paste can carry. The model echoes a
|
||||||
|
// suggestion's `original` from the same text but often normalizes these back to
|
||||||
|
// plain ASCII — straight quotes, `--`, `...` — so an exact match would miss and
|
||||||
|
// the suggestion could be neither highlighted nor applied.
|
||||||
|
//
|
||||||
|
// It returns the folded string plus `map`, where map[k] is the source index at
|
||||||
|
// which folded character k begins. A multi-character source run (`...`, `--`)
|
||||||
|
// folds to one glyph, so lengths differ; map projects a match in folded space
|
||||||
|
// back onto real document offsets. map has a trailing sentinel (= source length)
|
||||||
|
// so map[start + folded.length] yields the offset just past the match.
|
||||||
|
export function foldTypography(text: string): { folded: string; map: number[] } {
|
||||||
|
let folded = ''
|
||||||
|
const map: number[] = []
|
||||||
|
let i = 0
|
||||||
|
while (i < text.length) {
|
||||||
|
// Multi-character ASCII sequences the Typography rules would have replaced.
|
||||||
|
if (text.startsWith('...', i)) {
|
||||||
|
folded += '…'
|
||||||
|
map.push(i)
|
||||||
|
i += 3
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (text[i] === '-' && text[i + 1] === '-') {
|
||||||
|
folded += '—'
|
||||||
|
map.push(i)
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
folded += foldChar(text[i])
|
||||||
|
map.push(i)
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
map.push(text.length)
|
||||||
|
return { folded, map }
|
||||||
|
}
|
||||||
|
|
||||||
|
// foldChar maps a single character onto its canonical form (length-preserving).
|
||||||
|
function foldChar(c: string): string {
|
||||||
|
switch (c) {
|
||||||
|
case '‘':
|
||||||
|
case '’':
|
||||||
|
case '‚':
|
||||||
|
case '‛':
|
||||||
|
return "'"
|
||||||
|
case '“':
|
||||||
|
case '”':
|
||||||
|
case '„':
|
||||||
|
case '‟':
|
||||||
|
return '"'
|
||||||
|
case '–': // en dash → em dash, the canonical form `--` also folds to
|
||||||
|
return '—'
|
||||||
|
case ' ': // non-breaking space
|
||||||
|
case ' ': // thin space
|
||||||
|
case ' ': // narrow no-break space
|
||||||
|
return ' '
|
||||||
|
default:
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// findRange locates the first occurrence of `search` within a single textblock
|
// findRange locates the first occurrence of `search` within a single textblock
|
||||||
// and returns its ProseMirror range, or null if the string isn't present (the
|
// and returns its ProseMirror range, or null if the string isn't present (the
|
||||||
// user may have edited or removed it since the checkpoint ran). Exported so the
|
// user may have edited or removed it since the checkpoint ran). Matching is done
|
||||||
// accept flow can resolve the same span to replace.
|
// in canonical typographic space (see foldTypography) so curly-quote/dash/ellipsis
|
||||||
|
// differences between the model's echo and the live document don't strand the
|
||||||
|
// anchor. Exported so the accept flow can resolve the same span to replace.
|
||||||
export function findRange(doc: PMNode, search: string): { from: number; to: number } | null {
|
export function findRange(doc: PMNode, search: string): { from: number; to: number } | null {
|
||||||
if (!search) return null
|
const needle = foldTypography(search).folded
|
||||||
|
if (!needle) return null
|
||||||
let result: { from: number; to: number } | null = null
|
let result: { from: number; to: number } | null = null
|
||||||
doc.descendants((node, pos) => {
|
doc.descendants((node, pos) => {
|
||||||
if (result) return false
|
if (result) return false
|
||||||
if (!node.isTextblock) return true // keep descending to the textblock
|
if (!node.isTextblock) return true // keep descending to the textblock
|
||||||
const idx = node.textContent.indexOf(search)
|
const { folded, map } = foldTypography(node.textContent)
|
||||||
|
const idx = folded.indexOf(needle)
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
result = {
|
result = {
|
||||||
from: mapOffset(node, pos, idx),
|
from: mapOffset(node, pos, map[idx]),
|
||||||
to: mapOffset(node, pos, idx + search.length),
|
to: mapOffset(node, pos, map[idx + needle.length]),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false // never descend into a textblock's inline children
|
return false // never descend into a textblock's inline children
|
||||||
@@ -64,14 +138,15 @@ export function findRange(doc: PMNode, search: string): { from: number; to: numb
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildDecorations(doc: PMNode, suggestions: Suggestion[]): DecorationSet {
|
function buildDecorations(doc: PMNode, suggestions: Suggestion[], activeId: string | null): DecorationSet {
|
||||||
const decos: Decoration[] = []
|
const decos: Decoration[] = []
|
||||||
for (const s of suggestions) {
|
for (const s of suggestions) {
|
||||||
const range = findRange(doc, s.original)
|
const range = findRange(doc, s.original)
|
||||||
if (!range) continue
|
if (!range) continue
|
||||||
|
const active = s.id === activeId ? ' petal-suggestion-active' : ''
|
||||||
decos.push(
|
decos.push(
|
||||||
Decoration.inline(range.from, range.to, {
|
Decoration.inline(range.from, range.to, {
|
||||||
class: `petal-suggestion petal-suggestion-${s.type}`,
|
class: `petal-suggestion petal-suggestion-${s.type}${active}`,
|
||||||
'data-suggestion-id': s.id,
|
'data-suggestion-id': s.id,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -82,10 +157,22 @@ function buildDecorations(doc: PMNode, suggestions: Suggestion[]): DecorationSet
|
|||||||
// setSuggestions pushes a new suggestion list into the plugin. Decorations are
|
// setSuggestions pushes a new suggestion list into the plugin. Decorations are
|
||||||
// rebuilt against the current document immediately.
|
// rebuilt against the current document immediately.
|
||||||
export function setSuggestions(state: EditorState, dispatch: (tr: Transaction) => void, suggestions: Suggestion[]) {
|
export function setSuggestions(state: EditorState, dispatch: (tr: Transaction) => void, suggestions: Suggestion[]) {
|
||||||
const tr = state.tr.setMeta(suggestionPluginKey, suggestions)
|
const tr = state.tr.setMeta(suggestionPluginKey, { suggestions } satisfies SuggestionMeta)
|
||||||
dispatch(tr)
|
dispatch(tr)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// setActiveSuggestion marks one suggestion (or none) as emphasized, rebuilding
|
||||||
|
// the decorations so the flagged text gets the active wash. Driven by the margin
|
||||||
|
// rail's hover/selection so the card↔text link reads both ways.
|
||||||
|
export function setActiveSuggestion(
|
||||||
|
state: EditorState,
|
||||||
|
dispatch: (tr: Transaction) => void,
|
||||||
|
activeId: string | null,
|
||||||
|
) {
|
||||||
|
if (suggestionPluginKey.getState(state)?.activeId === activeId) return
|
||||||
|
dispatch(state.tr.setMeta(suggestionPluginKey, { activeId } satisfies SuggestionMeta))
|
||||||
|
}
|
||||||
|
|
||||||
export const SuggestionHighlight = Extension.create({
|
export const SuggestionHighlight = Extension.create({
|
||||||
name: 'suggestionHighlight',
|
name: 'suggestionHighlight',
|
||||||
|
|
||||||
@@ -94,17 +181,29 @@ export const SuggestionHighlight = Extension.create({
|
|||||||
new Plugin<PluginState>({
|
new Plugin<PluginState>({
|
||||||
key: suggestionPluginKey,
|
key: suggestionPluginKey,
|
||||||
state: {
|
state: {
|
||||||
init: () => ({ suggestions: [], decorations: DecorationSet.empty }),
|
init: () => ({ suggestions: [], activeId: null, decorations: DecorationSet.empty }),
|
||||||
apply(tr, value, _oldState, newState) {
|
apply(tr, value, _oldState, newState) {
|
||||||
const meta = tr.getMeta(suggestionPluginKey) as Suggestion[] | undefined
|
const meta = tr.getMeta(suggestionPluginKey) as SuggestionMeta | undefined
|
||||||
if (meta) {
|
if (meta && 'suggestions' in meta) {
|
||||||
return { suggestions: meta, decorations: buildDecorations(newState.doc, meta) }
|
return {
|
||||||
|
suggestions: meta.suggestions,
|
||||||
|
activeId: value.activeId,
|
||||||
|
decorations: buildDecorations(newState.doc, meta.suggestions, value.activeId),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (meta && 'activeId' in meta) {
|
||||||
|
return {
|
||||||
|
suggestions: value.suggestions,
|
||||||
|
activeId: meta.activeId,
|
||||||
|
decorations: buildDecorations(newState.doc, value.suggestions, meta.activeId),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// On any document change, re-anchor by string against the new doc.
|
// On any document change, re-anchor by string against the new doc.
|
||||||
if (tr.docChanged) {
|
if (tr.docChanged) {
|
||||||
return {
|
return {
|
||||||
suggestions: value.suggestions,
|
suggestions: value.suggestions,
|
||||||
decorations: buildDecorations(newState.doc, value.suggestions),
|
activeId: value.activeId,
|
||||||
|
decorations: buildDecorations(newState.doc, value.suggestions, value.activeId),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
|
|||||||
211
web/src/components/Editor/SuggestionRail.tsx
Normal file
211
web/src/components/Editor/SuggestionRail.tsx
Normal file
@@ -0,0 +1,211 @@
|
|||||||
|
import { forwardRef, useLayoutEffect, useRef, useState } from 'react'
|
||||||
|
import type { Suggestion } from '../../api/client'
|
||||||
|
import { AskPetal } from './AskPetal'
|
||||||
|
import { TYPE_META } from './suggestionMeta'
|
||||||
|
|
||||||
|
// Vertical breathing room kept between stacked cards when their natural anchors
|
||||||
|
// would otherwise collide.
|
||||||
|
const CARD_GAP = 12
|
||||||
|
|
||||||
|
export interface RailItem {
|
||||||
|
suggestion: Suggestion
|
||||||
|
// Vertical offset (px) of the suggestion's highlight, relative to the editor
|
||||||
|
// wrapper — the position the card wants to sit beside.
|
||||||
|
anchorTop: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
items: RailItem[]
|
||||||
|
// The suggestion currently emphasized (its highlight hovered, or this card
|
||||||
|
// hovered) — gets a lifted, ring-accented treatment so the text↔card link reads.
|
||||||
|
activeId: string | null
|
||||||
|
// The card expanded to show the full explanation + Ask Petal, or null.
|
||||||
|
expandedId: string | null
|
||||||
|
onAccept: (s: Suggestion) => void
|
||||||
|
onDismiss: (s: Suggestion) => void
|
||||||
|
// Pointer entering/leaving a card, so the matching highlight can light up.
|
||||||
|
onHover: (id: string | null) => void
|
||||||
|
// A card's body was clicked — scroll its highlight into view and toggle expand.
|
||||||
|
onActivate: (id: string) => void
|
||||||
|
onToggleExpand: (id: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
// SuggestionRail is the right-margin "comment column": every outstanding
|
||||||
|
// suggestion as a card, vertically aligned to the text it flags, so the writer
|
||||||
|
// sees the whole queue at once instead of hunting highlight by highlight. Cards
|
||||||
|
// are anchored to their highlight's vertical position and pushed down only as far
|
||||||
|
// as needed to avoid overlapping their neighbor above (a la doc-editor comments).
|
||||||
|
export function SuggestionRail({
|
||||||
|
items,
|
||||||
|
activeId,
|
||||||
|
expandedId,
|
||||||
|
onAccept,
|
||||||
|
onDismiss,
|
||||||
|
onHover,
|
||||||
|
onActivate,
|
||||||
|
onToggleExpand,
|
||||||
|
}: Props) {
|
||||||
|
// Measured resolved tops keyed by suggestion id (after collision avoidance).
|
||||||
|
const [tops, setTops] = useState<Record<string, number>>({})
|
||||||
|
const cardRefs = useRef<Map<string, HTMLDivElement>>(new Map())
|
||||||
|
// Bumped whenever a card's own height changes (Ask Petal streaming in, wrapping
|
||||||
|
// text) so the stack re-packs and cards below don't get overlapped.
|
||||||
|
const [measureTick, setMeasureTick] = useState(0)
|
||||||
|
const observerRef = useRef<ResizeObserver | null>(null)
|
||||||
|
if (!observerRef.current && typeof ResizeObserver !== 'undefined') {
|
||||||
|
observerRef.current = new ResizeObserver(() => setMeasureTick((t) => t + 1))
|
||||||
|
}
|
||||||
|
useLayoutEffect(() => () => observerRef.current?.disconnect(), [])
|
||||||
|
|
||||||
|
// Sort by anchor, then greedily stack: each card sits at its anchor unless that
|
||||||
|
// would overlap the previous card, in which case it slides down just enough.
|
||||||
|
// Re-runs whenever the anchors or the expanded card (which changes a height)
|
||||||
|
// shift. Reads live offsetHeight so variable-length explanations pack tightly.
|
||||||
|
const ordered = [...items].sort((a, b) => a.anchorTop - b.anchorTop)
|
||||||
|
const layoutKey = ordered.map((i) => `${i.suggestion.id}:${Math.round(i.anchorTop)}`).join('|')
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
let cursor = -Infinity
|
||||||
|
const next: Record<string, number> = {}
|
||||||
|
for (const { suggestion, anchorTop } of ordered) {
|
||||||
|
const h = cardRefs.current.get(suggestion.id)?.offsetHeight ?? 96
|
||||||
|
const top = Math.max(anchorTop, cursor)
|
||||||
|
next[suggestion.id] = top
|
||||||
|
cursor = top + h + CARD_GAP
|
||||||
|
}
|
||||||
|
setTops((prev) => {
|
||||||
|
const ids = Object.keys(next)
|
||||||
|
if (ids.length === Object.keys(prev).length && ids.every((id) => prev[id] === next[id])) return prev
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
// layoutKey captures anchor positions; expandedId/measureTick capture height
|
||||||
|
// changes (toggling detail, Ask Petal streaming in).
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [layoutKey, expandedId, measureTick])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="petal-rail petal-no-print" aria-label="Suggestions">
|
||||||
|
{ordered.map(({ suggestion }) => (
|
||||||
|
<RailCard
|
||||||
|
key={suggestion.id}
|
||||||
|
ref={(el) => {
|
||||||
|
const prev = cardRefs.current.get(suggestion.id)
|
||||||
|
if (prev && prev !== el) observerRef.current?.unobserve(prev)
|
||||||
|
if (el) {
|
||||||
|
cardRefs.current.set(suggestion.id, el)
|
||||||
|
observerRef.current?.observe(el)
|
||||||
|
} else {
|
||||||
|
cardRefs.current.delete(suggestion.id)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
suggestion={suggestion}
|
||||||
|
top={tops[suggestion.id] ?? 0}
|
||||||
|
active={activeId === suggestion.id}
|
||||||
|
expanded={expandedId === suggestion.id}
|
||||||
|
onAccept={onAccept}
|
||||||
|
onDismiss={onDismiss}
|
||||||
|
onHover={onHover}
|
||||||
|
onActivate={onActivate}
|
||||||
|
onToggleExpand={onToggleExpand}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CardProps {
|
||||||
|
suggestion: Suggestion
|
||||||
|
top: number
|
||||||
|
active: boolean
|
||||||
|
expanded: boolean
|
||||||
|
onAccept: (s: Suggestion) => void
|
||||||
|
onDismiss: (s: Suggestion) => void
|
||||||
|
onHover: (id: string | null) => void
|
||||||
|
onActivate: (id: string) => void
|
||||||
|
onToggleExpand: (id: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const RailCard = forwardRef<HTMLDivElement, CardProps>(function RailCard(
|
||||||
|
{ suggestion, top, active, expanded, onAccept, onDismiss, onHover, onActivate, onToggleExpand },
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
const meta = TYPE_META[suggestion.type]
|
||||||
|
const hasReplacement = suggestion.replacement.trim() !== ''
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
role="group"
|
||||||
|
aria-label={`${meta.label} suggestion`}
|
||||||
|
onMouseEnter={() => onHover(suggestion.id)}
|
||||||
|
onMouseLeave={() => onHover(null)}
|
||||||
|
className={`petal-rail-card${active ? ' petal-rail-card-active' : ''}`}
|
||||||
|
style={{ top, borderLeftColor: meta.color }}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center rounded-full px-2 py-0.5 text-[0.68rem] font-bold"
|
||||||
|
style={{ background: meta.color, color: 'var(--color-plum)' }}
|
||||||
|
>
|
||||||
|
{meta.label}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Dismiss suggestion"
|
||||||
|
onClick={() => onDismiss(suggestion)}
|
||||||
|
className="petal-rail-x"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* The body toggles the expanded explanation + Ask Petal and points the
|
||||||
|
editor at the flagged text. */}
|
||||||
|
<button type="button" onClick={() => onActivate(suggestion.id)} className="mt-2 block w-full text-left">
|
||||||
|
{hasReplacement && (
|
||||||
|
<span className="flex flex-col gap-0.5" style={{ fontFamily: 'var(--font-body)' }}>
|
||||||
|
<span className="truncate text-[0.9rem] line-through" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
{suggestion.original}
|
||||||
|
</span>
|
||||||
|
<span className="truncate text-[0.9rem] font-medium" style={{ color: 'var(--color-plum)' }}>
|
||||||
|
{suggestion.replacement}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span
|
||||||
|
className={`mt-1.5 block text-[0.82rem] leading-snug${expanded ? '' : ' line-clamp-2'}`}
|
||||||
|
style={{ color: 'var(--color-plum)' }}
|
||||||
|
>
|
||||||
|
{suggestion.explanation}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{expanded && <AskPetal suggestionId={suggestion.id} explanation={suggestion.explanation} />}
|
||||||
|
|
||||||
|
<div className="mt-2.5 flex items-center gap-2">
|
||||||
|
{hasReplacement && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onAccept(suggestion)}
|
||||||
|
className="rounded-full px-3 py-1 text-xs font-bold 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)')}
|
||||||
|
>
|
||||||
|
Accept
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onToggleExpand(suggestion.id)}
|
||||||
|
className="rounded-full px-2.5 py-1 text-xs font-bold transition-colors"
|
||||||
|
style={{
|
||||||
|
background: expanded ? 'var(--color-surface-alt)' : 'transparent',
|
||||||
|
color: 'var(--color-accent-hover)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{expanded ? 'Hide Petal' : 'Ask Petal ✨'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})
|
||||||
29
web/src/components/Editor/Typography.ts
Normal file
29
web/src/components/Editor/Typography.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { Extension, textInputRule } from '@tiptap/core'
|
||||||
|
|
||||||
|
// Typography adds the small print-shop niceties as you type: curly quotes,
|
||||||
|
// em-dashes, and a single-character ellipsis. Implemented as input rules (no
|
||||||
|
// dependency, offline-friendly — matching FontSize.ts's hand-rolled approach),
|
||||||
|
// and every one is plain Undo-able if it ever fires when you didn't want it.
|
||||||
|
//
|
||||||
|
// CJK is untouched: these rules only rewrite ASCII quotes/dashes/dots, never the
|
||||||
|
// fullwidth forms a Mandarin sentence uses.
|
||||||
|
export const Typography = Extension.create({
|
||||||
|
name: 'petalTypography',
|
||||||
|
|
||||||
|
addInputRules() {
|
||||||
|
return [
|
||||||
|
// “ opening double quote — after start, whitespace, or an opening bracket.
|
||||||
|
textInputRule({ find: /(?:^|[\s{[(<'"‘“])(")$/, replace: '“' }),
|
||||||
|
// ” closing double quote — any other time you type a ".
|
||||||
|
textInputRule({ find: /"$/, replace: '”' }),
|
||||||
|
// ‘ opening single quote.
|
||||||
|
textInputRule({ find: /(?:^|[\s{[(<'"‘“])(')$/, replace: '‘' }),
|
||||||
|
// ’ closing single quote / apostrophe.
|
||||||
|
textInputRule({ find: /'$/, replace: '’' }),
|
||||||
|
// — em dash from a double hyphen.
|
||||||
|
textInputRule({ find: /--$/, replace: '—' }),
|
||||||
|
// … ellipsis from three dots.
|
||||||
|
textInputRule({ find: /\.\.\.$/, replace: '…' }),
|
||||||
|
]
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { WordInfo } from '../../api/client'
|
import type { WordInfo } from '../../api/client'
|
||||||
|
import { speak, speechSupported } from '../../audio/speech'
|
||||||
|
|
||||||
// WordCard is the right-click popover for any word: its dictionary definition(s)
|
// WordCard is the right-click popover for any word: its dictionary definition(s)
|
||||||
// on top and tappable synonym pills below. Clicking a synonym replaces the word
|
// on top and tappable synonym pills below. Clicking a synonym replaces the word
|
||||||
@@ -10,14 +11,19 @@ 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 ?? ''
|
||||||
|
const phonetic = info?.phonetic ?? ''
|
||||||
const empty = !loading && !gloss && definitions.length === 0 && synonyms.length === 0
|
const empty = !loading && !gloss && definitions.length === 0 && synonyms.length === 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -46,8 +52,45 @@ 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>
|
||||||
|
<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>
|
</div>
|
||||||
|
|
||||||
|
{/* How to say it — the pronunciation aid for an English learner, paired
|
||||||
|
with the 🔊 button above. */}
|
||||||
|
{phonetic && (
|
||||||
|
<p className="mt-1.5 text-sm" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
/{phonetic}/
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Chinese gloss first — it's what the Mandarin-speaking writer reaches for. */}
|
{/* Chinese gloss first — it's what the Mandarin-speaking writer reaches for. */}
|
||||||
{gloss && (
|
{gloss && (
|
||||||
<p
|
<p
|
||||||
|
|||||||
14
web/src/components/Editor/suggestionMeta.ts
Normal file
14
web/src/components/Editor/suggestionMeta.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import type { SuggestionType } from '../../api/client'
|
||||||
|
|
||||||
|
// Per-type accent color + human label, mirroring the design tokens. Shared by the
|
||||||
|
// inline hover SuggestionCard and the margin SuggestionRail so a given suggestion
|
||||||
|
// type reads the same color/name wherever it surfaces.
|
||||||
|
export const TYPE_META: Record<SuggestionType, { color: string; label: string }> = {
|
||||||
|
grammar: { color: 'var(--color-mint)', label: 'Grammar' },
|
||||||
|
phrasing: { color: 'var(--color-peach)', label: 'Phrasing' },
|
||||||
|
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' },
|
||||||
|
mechanics: { color: 'var(--color-sage)', label: 'Tidy-up' },
|
||||||
|
}
|
||||||
521
web/src/components/Garden/GardenPanel.tsx
Normal file
521
web/src/components/Garden/GardenPanel.tsx
Normal file
@@ -0,0 +1,521 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { api, type VocabGrade, type VocabWord } from '../../api/client'
|
||||||
|
import { speak, speechSupported, stopSpeech } from '../../audio/speech'
|
||||||
|
import { useFocusTrap } from '../../hooks/useFocusTrap'
|
||||||
|
|
||||||
|
// 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 panelRef = useFocusTrap<HTMLElement>()
|
||||||
|
|
||||||
|
// Read-aloud is fire-and-forget, so a word she tapped could still be speaking
|
||||||
|
// when the panel closes. Cancel any in-flight audio on unmount so it can't
|
||||||
|
// outlive the garden.
|
||||||
|
useEffect(() => stopSpeech, [])
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setError(false)
|
||||||
|
// Settle the two requests independently: a failed /due shouldn't blank the
|
||||||
|
// whole garden when the word list loaded fine. Only listVocab failing is a
|
||||||
|
// true error state; a dueVocab failure just hides the review button.
|
||||||
|
const [allRes, dueRes] = await Promise.allSettled([api.listVocab(), api.dueVocab()])
|
||||||
|
if (allRes.status === 'fulfilled') setWords(allRes.value)
|
||||||
|
else setError(true)
|
||||||
|
if (dueRes.status === 'fulfilled') setDue(dueRes.value)
|
||||||
|
else setDue([])
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
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={() => (queue ? setQueue(null) : onClose())}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<aside
|
||||||
|
ref={panelRef}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label="词汇花园 · Vocabulary Garden"
|
||||||
|
tabIndex={-1}
|
||||||
|
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
|
||||||
|
}) {
|
||||||
|
// Index the due cards once so the per-word "due" check below is O(1), not a
|
||||||
|
// linear scan of `due` for every word in the garden.
|
||||||
|
const dueIds = useMemo(() => new Set(due.map((d) => d.id)), [due])
|
||||||
|
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 = dueIds.has(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 || w.definition) && (
|
||||||
|
<span
|
||||||
|
className="truncate text-xs"
|
||||||
|
style={{
|
||||||
|
color: 'var(--color-muted)',
|
||||||
|
fontFamily: w.gloss
|
||||||
|
? "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif"
|
||||||
|
: 'var(--font-body)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{w.gloss || w.definition}
|
||||||
|
</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>
|
||||||
|
|
||||||
|
{!error && 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]
|
||||||
|
// The meaning shown/asked is the Chinese gloss, or the English definition when
|
||||||
|
// a word has no gloss — so definition-only words are still reviewable.
|
||||||
|
const meaning = card?.gloss || card?.definition || ''
|
||||||
|
// 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 && !!meaning
|
||||||
|
|
||||||
|
const prompt = useMemo(() => {
|
||||||
|
if (!card) return ''
|
||||||
|
if (production) return meaning
|
||||||
|
return card.example ? blankOut(card.example, card.word) : card.word
|
||||||
|
}, [card, production, meaning])
|
||||||
|
|
||||||
|
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>
|
||||||
|
)}
|
||||||
|
{meaning && (
|
||||||
|
<div
|
||||||
|
className="mt-1 text-sm font-semibold"
|
||||||
|
style={{
|
||||||
|
color: 'var(--color-accent-hover)',
|
||||||
|
// Chinese gloss gets the CJK stack; an English definition fallback
|
||||||
|
// reads better in the body font.
|
||||||
|
fontFamily: card.gloss
|
||||||
|
? "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif"
|
||||||
|
: 'var(--font-body)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{meaning}
|
||||||
|
</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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { api, type Document, type DocumentVersion } from '../../api/client'
|
import { api, type Document, type DocumentVersion } from '../../api/client'
|
||||||
|
import { useFocusTrap } from '../../hooks/useFocusTrap'
|
||||||
|
|
||||||
// HistoryPanel is the "time machine" drawer: every snapshot Petal kept of this
|
// HistoryPanel is the "time machine" drawer: every snapshot Petal kept of this
|
||||||
// document, newest first, with a one-click preview and restore. It's the safety
|
// document, newest first, with a one-click preview and restore. It's the safety
|
||||||
@@ -41,6 +42,7 @@ export function HistoryPanel({ docId, onClose, onRestored }: Props) {
|
|||||||
const [selected, setSelected] = useState<DocumentVersion | null>(null)
|
const [selected, setSelected] = useState<DocumentVersion | null>(null)
|
||||||
const [preview, setPreview] = useState<DocumentVersion | null>(null)
|
const [preview, setPreview] = useState<DocumentVersion | null>(null)
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
|
const panelRef = useFocusTrap<HTMLElement>()
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
setError(false)
|
setError(false)
|
||||||
@@ -99,6 +101,11 @@ export function HistoryPanel({ docId, onClose, onRestored }: Props) {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<aside
|
<aside
|
||||||
|
ref={panelRef}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label="历史 · History"
|
||||||
|
tabIndex={-1}
|
||||||
className="relative flex h-full w-full max-w-[380px] flex-col"
|
className="relative flex h-full w-full max-w-[380px] flex-col"
|
||||||
style={{
|
style={{
|
||||||
background: 'var(--color-surface)',
|
background: 'var(--color-surface)',
|
||||||
|
|||||||
37
web/src/components/StatusBar/PetalsToggle.tsx
Normal file
37
web/src/components/StatusBar/PetalsToggle.tsx
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { isPetalsEnabled, onPetalsEnabledChange, setPetalsEnabled } from '../../effects/petals'
|
||||||
|
|
||||||
|
// A tiny toggle for Petal's ambient falling-blossom layer, sitting just left of
|
||||||
|
// the sound toggle in the status bar. Some people find the drifting petals
|
||||||
|
// distracting, so this turns them off entirely. Bilingual tooltip (she reads
|
||||||
|
// Mandarin first), and the choice persists across reloads.
|
||||||
|
export function PetalsToggle() {
|
||||||
|
const [on, setOn] = useState(isPetalsEnabled)
|
||||||
|
|
||||||
|
// Stay in sync if the setting is flipped elsewhere.
|
||||||
|
useEffect(() => onPetalsEnabledChange(setOn), [])
|
||||||
|
|
||||||
|
const toggle = () => {
|
||||||
|
const next = !on
|
||||||
|
setPetalsEnabled(next)
|
||||||
|
setOn(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={toggle}
|
||||||
|
aria-pressed={on}
|
||||||
|
title={on ? '花瓣开 · Petals on' : '花瓣关 · Petals off'}
|
||||||
|
aria-label={on ? 'Hide falling petals' : 'Show falling petals'}
|
||||||
|
className="flex items-center justify-center rounded-full px-2 py-1 text-xl leading-none transition-colors"
|
||||||
|
style={{ color: on ? 'var(--color-accent)' : 'var(--color-muted)', lineHeight: 1 }}
|
||||||
|
onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--color-accent-hover)')}
|
||||||
|
onMouseLeave={(e) =>
|
||||||
|
(e.currentTarget.style.color = on ? 'var(--color-accent)' : 'var(--color-muted)')
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span aria-hidden>{on ? '🌸' : '🍃'}</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { isSoundEnabled, onSoundEnabledChange, playSound, setSoundEnabled } from '../../audio/sounds'
|
import { isSoundEnabled, onSoundEnabledChange, playPop, setSoundEnabled } from '../../audio/sounds'
|
||||||
|
|
||||||
// A tiny mute toggle for Petal's cute sounds, tucked at the right of the status
|
// A tiny mute toggle for Petal's cute sounds, tucked at the right of the status
|
||||||
// bar. Bilingual tooltip (she reads Mandarin first), and a soft confirming pop
|
// bar. Bilingual tooltip (she reads Mandarin first), and a soft confirming pop
|
||||||
@@ -14,7 +14,7 @@ export function SoundToggle() {
|
|||||||
const next = !on
|
const next = !on
|
||||||
setSoundEnabled(next)
|
setSoundEnabled(next)
|
||||||
setOn(next)
|
setOn(next)
|
||||||
if (next) playSound('pop') // a little hello when re-enabled
|
if (next) playPop() // a little hello when re-enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -24,7 +24,7 @@ export function SoundToggle() {
|
|||||||
aria-pressed={on}
|
aria-pressed={on}
|
||||||
title={on ? '声音开 · Sounds on' : '声音关 · Sounds off'}
|
title={on ? '声音开 · Sounds on' : '声音关 · Sounds off'}
|
||||||
aria-label={on ? 'Mute Petal sounds' : 'Unmute Petal sounds'}
|
aria-label={on ? 'Mute Petal sounds' : 'Unmute Petal sounds'}
|
||||||
className="rounded-full px-1.5 py-0.5 transition-colors"
|
className="flex items-center justify-center rounded-full px-2 py-1 text-xl leading-none transition-colors"
|
||||||
style={{ color: on ? 'var(--color-accent)' : 'var(--color-muted)', lineHeight: 1 }}
|
style={{ color: on ? 'var(--color-accent)' : 'var(--color-muted)', lineHeight: 1 }}
|
||||||
onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--color-accent-hover)')}
|
onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--color-accent-hover)')}
|
||||||
onMouseLeave={(e) =>
|
onMouseLeave={(e) =>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { Fragment, useEffect, useRef, useState } from 'react'
|
||||||
import type { SaveStatus } from '../../hooks/useAutoSave'
|
import type { SaveStatus } from '../../hooks/useAutoSave'
|
||||||
import { StatsPanel } from './StatsPanel'
|
import { StatsPanel } from './StatsPanel'
|
||||||
|
import { PetalsToggle } from './PetalsToggle'
|
||||||
import { SoundToggle } from './SoundToggle'
|
import { SoundToggle } from './SoundToggle'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -12,6 +13,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,8 +31,40 @@ 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) {
|
// The live "Petal is working" indicators. Each is a breathing dot + label shown
|
||||||
|
// while its pass is in flight; driving them from one array keeps the markup (and
|
||||||
|
// the "nothing in flight" check below) in lockstep as passes are added.
|
||||||
|
interface Indicator {
|
||||||
|
active: boolean
|
||||||
|
color: string
|
||||||
|
title: string
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StatusBar({ wordCount, text, saveStatus, checking, voicing, collocating, llmDown }: Props) {
|
||||||
const label = SAVE_LABEL[saveStatus]
|
const label = SAVE_LABEL[saveStatus]
|
||||||
|
|
||||||
|
const indicators: Indicator[] = [
|
||||||
|
{
|
||||||
|
active: checking,
|
||||||
|
color: 'var(--color-accent)',
|
||||||
|
title: 'Petal is reading your writing…',
|
||||||
|
label: 'Checking…',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
active: voicing,
|
||||||
|
color: 'var(--color-honey)',
|
||||||
|
title: 'Petal is reading your voice…',
|
||||||
|
label: 'Reading your voice…',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
active: collocating,
|
||||||
|
color: 'var(--color-blossom)',
|
||||||
|
title: 'Petal is looking for more natural word pairings…',
|
||||||
|
label: 'Finding natural phrasing…',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const anyBusy = indicators.some((i) => i.active)
|
||||||
// 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)
|
||||||
const statsRef = useRef<HTMLDivElement>(null)
|
const statsRef = useRef<HTMLDivElement>(null)
|
||||||
@@ -45,7 +80,7 @@ export function StatusBar({ wordCount, text, saveStatus, checking, voicing, llmD
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<footer
|
<footer
|
||||||
className="flex h-9 shrink-0 items-center gap-3 px-6 text-xs"
|
className="flex h-11 shrink-0 items-center gap-3 px-6 text-sm"
|
||||||
style={{ borderTop: '1px solid var(--color-border)', color: 'var(--color-muted)' }}
|
style={{ borderTop: '1px solid var(--color-border)', color: 'var(--color-muted)' }}
|
||||||
>
|
>
|
||||||
<div className="relative" ref={statsRef}>
|
<div className="relative" ref={statsRef}>
|
||||||
@@ -54,7 +89,7 @@ export function StatusBar({ wordCount, text, saveStatus, checking, voicing, llmD
|
|||||||
onClick={() => setStatsOpen((o) => !o)}
|
onClick={() => setStatsOpen((o) => !o)}
|
||||||
aria-haspopup="dialog"
|
aria-haspopup="dialog"
|
||||||
aria-expanded={statsOpen}
|
aria-expanded={statsOpen}
|
||||||
className="rounded-full px-1.5 py-0.5 font-semibold transition-colors"
|
className="rounded-full px-2 py-0.5 text-[0.95rem] font-bold transition-colors"
|
||||||
style={{ color: statsOpen ? 'var(--color-accent-hover)' : 'inherit' }}
|
style={{ color: statsOpen ? 'var(--color-accent-hover)' : 'inherit' }}
|
||||||
onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--color-accent-hover)')}
|
onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--color-accent-hover)')}
|
||||||
onMouseLeave={(e) =>
|
onMouseLeave={(e) =>
|
||||||
@@ -66,31 +101,21 @@ export function StatusBar({ wordCount, text, saveStatus, checking, voicing, llmD
|
|||||||
</button>
|
</button>
|
||||||
{statsOpen && <StatsPanel text={text} wordCount={wordCount} />}
|
{statsOpen && <StatsPanel text={text} wordCount={wordCount} />}
|
||||||
</div>
|
</div>
|
||||||
{checking && (
|
{indicators
|
||||||
<>
|
.filter((i) => i.active)
|
||||||
<span aria-hidden>·</span>
|
.map((i) => (
|
||||||
<span className="inline-flex items-center gap-1.5" title="Petal is reading your writing…">
|
<Fragment key={i.label}>
|
||||||
<span
|
<span aria-hidden>·</span>
|
||||||
className="petal-checkpoint-dot inline-block h-2 w-2 rounded-full"
|
<span className="inline-flex items-center gap-1.5" title={i.title}>
|
||||||
style={{ background: 'var(--color-accent)' }}
|
<span
|
||||||
/>
|
className="petal-checkpoint-dot inline-block h-2 w-2 rounded-full"
|
||||||
Checking…
|
style={{ background: i.color }}
|
||||||
</span>
|
/>
|
||||||
</>
|
{i.label}
|
||||||
)}
|
</span>
|
||||||
{voicing && (
|
</Fragment>
|
||||||
<>
|
))}
|
||||||
<span aria-hidden>·</span>
|
{llmDown && !anyBusy && (
|
||||||
<span className="inline-flex items-center gap-1.5" title="Petal is reading your voice…">
|
|
||||||
<span
|
|
||||||
className="petal-checkpoint-dot inline-block h-2 w-2 rounded-full"
|
|
||||||
style={{ background: 'var(--color-honey)' }}
|
|
||||||
/>
|
|
||||||
Reading your voice…
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{llmDown && !checking && !voicing && (
|
|
||||||
<>
|
<>
|
||||||
<span aria-hidden>·</span>
|
<span aria-hidden>·</span>
|
||||||
<span
|
<span
|
||||||
@@ -121,7 +146,8 @@ export function StatusBar({ wordCount, text, saveStatus, checking, voicing, llmD
|
|||||||
</span>
|
</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<div className="ml-auto">
|
<div className="ml-auto flex items-center">
|
||||||
|
<PetalsToggle />
|
||||||
<SoundToggle />
|
<SoundToggle />
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
import type { Editor } from '@tiptap/react'
|
import type { Editor } from '@tiptap/react'
|
||||||
import { useEditorState } from '@tiptap/react'
|
import { useEditorState } from '@tiptap/react'
|
||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import { uploadImageInto } from '../Editor/EditorCore'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
editor: Editor | null
|
editor: Editor | null
|
||||||
// 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
|
||||||
@@ -15,18 +20,21 @@ function TBtn({
|
|||||||
active,
|
active,
|
||||||
disabled,
|
disabled,
|
||||||
label,
|
label,
|
||||||
|
title,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
onClick: () => void
|
onClick: () => void
|
||||||
active?: boolean
|
active?: boolean
|
||||||
disabled?: boolean
|
disabled?: boolean
|
||||||
label: string
|
label: string
|
||||||
|
title?: string
|
||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-label={label}
|
aria-label={label}
|
||||||
|
title={title ?? label}
|
||||||
aria-pressed={active}
|
aria-pressed={active}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onMouseDown={(e) => e.preventDefault()} // keep editor selection
|
onMouseDown={(e) => e.preventDefault()} // keep editor selection
|
||||||
@@ -47,10 +55,125 @@ const Divider = () => (
|
|||||||
<span className="mx-1 h-5 w-px" style={{ background: 'var(--color-border)' }} />
|
<span className="mx-1 h-5 w-px" style={{ background: 'var(--color-border)' }} />
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// A popover anchored under its trigger. The trigger + panel share a relative
|
||||||
|
// wrapper; `open`/`onClose` are owned by the toolbar so only one is open at once.
|
||||||
|
// A pointer-down outside the wrapper closes it.
|
||||||
|
function Popover({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
trigger,
|
||||||
|
children,
|
||||||
|
width = 200,
|
||||||
|
}: {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
trigger: React.ReactNode
|
||||||
|
children: React.ReactNode
|
||||||
|
width?: number
|
||||||
|
}) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
const onDown = (e: MouseEvent) => {
|
||||||
|
if (!ref.current?.contains(e.target as Node)) onClose()
|
||||||
|
}
|
||||||
|
document.addEventListener('mousedown', onDown)
|
||||||
|
return () => document.removeEventListener('mousedown', onDown)
|
||||||
|
}, [open, onClose])
|
||||||
|
return (
|
||||||
|
<div ref={ref} className="relative flex items-center">
|
||||||
|
{trigger}
|
||||||
|
{open && (
|
||||||
|
<div
|
||||||
|
className="absolute left-0 top-full z-40 mt-1.5 p-2"
|
||||||
|
style={{
|
||||||
|
width,
|
||||||
|
borderRadius: 'var(--radius-card)',
|
||||||
|
background: 'var(--color-surface)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
boxShadow: 'var(--shadow-soft)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text-color swatches. `null` clears the color back to the theme default.
|
||||||
|
const TEXT_COLORS: { label: string; value: string | null }[] = [
|
||||||
|
{ label: 'Default', value: null },
|
||||||
|
{ label: 'Rose', value: '#D98AAF' },
|
||||||
|
{ label: 'Coral', value: '#E0785C' },
|
||||||
|
{ label: 'Honey', value: '#C68B2E' },
|
||||||
|
{ label: 'Green', value: '#4F9E7F' },
|
||||||
|
{ label: 'Sky', value: '#4E8FCC' },
|
||||||
|
{ label: 'Lavender', value: '#7D63C4' },
|
||||||
|
{ label: 'Plum', value: '#3D2E39' },
|
||||||
|
]
|
||||||
|
|
||||||
|
// Highlighter colors — soft pastels so dark text stays readable on top.
|
||||||
|
const HIGHLIGHTS: { label: string; value: string | null }[] = [
|
||||||
|
{ label: 'None', value: null },
|
||||||
|
{ label: 'Yellow', value: '#FFF1A8' },
|
||||||
|
{ label: 'Pink', value: '#FAD4E4' },
|
||||||
|
{ label: 'Mint', value: '#CDEFE2' },
|
||||||
|
{ label: 'Peach', value: '#FBE0CF' },
|
||||||
|
{ label: 'Lavender', value: '#E6DCFA' },
|
||||||
|
{ label: 'Sky', value: '#D6E8FB' },
|
||||||
|
]
|
||||||
|
|
||||||
|
// Font-size presets. `null` clears back to the document default.
|
||||||
|
const SIZES: { label: string; value: string | null; em: string }[] = [
|
||||||
|
{ label: 'Small', value: '0.85em', em: '0.85em' },
|
||||||
|
{ label: 'Normal', value: null, em: '1em' },
|
||||||
|
{ label: 'Large', value: '1.3em', em: '1.3em' },
|
||||||
|
{ label: 'Title', value: '1.7em', em: '1.7em' },
|
||||||
|
]
|
||||||
|
|
||||||
|
// A round color chip used in the color/highlight palettes.
|
||||||
|
function Swatch({
|
||||||
|
color,
|
||||||
|
active,
|
||||||
|
onClick,
|
||||||
|
title,
|
||||||
|
}: {
|
||||||
|
color: string | null
|
||||||
|
active: boolean
|
||||||
|
onClick: () => void
|
||||||
|
title: string
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={title}
|
||||||
|
aria-label={title}
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={onClick}
|
||||||
|
className="flex h-7 w-7 items-center justify-center"
|
||||||
|
style={{
|
||||||
|
borderRadius: 'var(--radius-pill)',
|
||||||
|
background: color ?? 'var(--color-surface)',
|
||||||
|
border: active ? '2px solid var(--color-accent)' : '1px solid var(--color-border)',
|
||||||
|
// The "clear" chip (no color) shows a tiny diagonal stroke.
|
||||||
|
backgroundImage: color
|
||||||
|
? undefined
|
||||||
|
: 'linear-gradient(135deg, transparent 44%, var(--color-accent) 44%, var(--color-accent) 56%, transparent 56%)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// 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.
|
||||||
|
const [menu, setMenu] = useState<'color' | 'highlight' | 'size' | 'link' | 'table' | 'outline' | null>(null)
|
||||||
|
const [linkUrl, setLinkUrl] = useState('')
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
const state = useEditorState({
|
const state = useEditorState({
|
||||||
editor,
|
editor,
|
||||||
selector: ({ editor }) =>
|
selector: ({ editor }) =>
|
||||||
@@ -59,27 +182,92 @@ export function Toolbar({ editor, onVoiceCheck, voicing }: Props) {
|
|||||||
bold: editor.isActive('bold'),
|
bold: editor.isActive('bold'),
|
||||||
italic: editor.isActive('italic'),
|
italic: editor.isActive('italic'),
|
||||||
underline: editor.isActive('underline'),
|
underline: editor.isActive('underline'),
|
||||||
|
strike: editor.isActive('strike'),
|
||||||
h1: editor.isActive('heading', { level: 1 }),
|
h1: editor.isActive('heading', { level: 1 }),
|
||||||
h2: editor.isActive('heading', { level: 2 }),
|
h2: editor.isActive('heading', { level: 2 }),
|
||||||
|
h3: editor.isActive('heading', { level: 3 }),
|
||||||
bullet: editor.isActive('bulletList'),
|
bullet: editor.isActive('bulletList'),
|
||||||
|
ordered: editor.isActive('orderedList'),
|
||||||
left: editor.isActive({ textAlign: 'left' }),
|
left: editor.isActive({ textAlign: 'left' }),
|
||||||
center: editor.isActive({ textAlign: 'center' }),
|
center: editor.isActive({ textAlign: 'center' }),
|
||||||
right: editor.isActive({ textAlign: 'right' }),
|
right: editor.isActive({ textAlign: 'right' }),
|
||||||
|
link: editor.isActive('link'),
|
||||||
|
inTable: editor.isActive('table'),
|
||||||
|
color: editor.getAttributes('textStyle').color ?? null,
|
||||||
|
highlight: editor.getAttributes('highlight').color ?? null,
|
||||||
|
fontSize: editor.getAttributes('textStyle').fontSize ?? null,
|
||||||
|
canUndo: editor.can().undo(),
|
||||||
|
canRedo: editor.can().redo(),
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!editor || !state) return null
|
if (!editor || !state) return null
|
||||||
|
|
||||||
|
const close = () => setMenu(null)
|
||||||
|
|
||||||
|
// Open the link popover, pre-filling the field with any link already on the
|
||||||
|
// selection so it can be edited rather than retyped.
|
||||||
|
const openLink = () => {
|
||||||
|
setLinkUrl(editor.getAttributes('link').href ?? '')
|
||||||
|
setMenu(menu === 'link' ? null : 'link')
|
||||||
|
}
|
||||||
|
|
||||||
|
const applyLink = () => {
|
||||||
|
const url = linkUrl.trim()
|
||||||
|
if (!url) {
|
||||||
|
editor.chain().focus().extendMarkRange('link').unsetLink().run()
|
||||||
|
} else {
|
||||||
|
// Default to https:// when the writer omits a scheme.
|
||||||
|
const href = /^(https?:|mailto:|\/)/i.test(url) ? url : `https://${url}`
|
||||||
|
editor.chain().focus().extendMarkRange('link').setLink({ href }).run()
|
||||||
|
}
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect the document's headings (with their positions) for the outline. Read
|
||||||
|
// fresh each time the popover opens, so it always reflects the current doc.
|
||||||
|
const headings: { level: number; text: string; pos: number }[] = []
|
||||||
|
if (menu === 'outline') {
|
||||||
|
editor.state.doc.descendants((node, pos) => {
|
||||||
|
if (node.type.name === 'heading') {
|
||||||
|
headings.push({ level: (node.attrs.level as number) || 1, text: node.textContent || '(无标题)', pos })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scroll a heading into view without moving the selection (which would pop the
|
||||||
|
// rewrite bubble). domAtPos resolves the heading's DOM node to scroll to.
|
||||||
|
const gotoHeading = (pos: number) => {
|
||||||
|
const dom = editor.view.domAtPos(pos + 1)
|
||||||
|
const el = dom.node.nodeType === Node.TEXT_NODE ? dom.node.parentElement : (dom.node as HTMLElement)
|
||||||
|
el?.scrollIntoView({ block: 'start', behavior: 'smooth' })
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
|
||||||
|
const onPickImage = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0]
|
||||||
|
if (file) uploadImageInto(editor.view, file)
|
||||||
|
e.target.value = '' // allow re-picking the same file
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="mb-4 flex items-center gap-0.5 self-start px-2 py-1.5"
|
className="petal-toolbar mb-4 flex items-center gap-0.5 self-start px-2 py-1.5"
|
||||||
style={{
|
style={{
|
||||||
borderRadius: 'var(--radius-pill)',
|
borderRadius: 'var(--radius-card)',
|
||||||
background: 'var(--color-surface)',
|
background: 'var(--color-surface)',
|
||||||
boxShadow: 'var(--shadow-soft)',
|
boxShadow: 'var(--shadow-soft)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<TBtn label="Undo" disabled={!state.canUndo} onClick={() => editor.chain().focus().undo().run()}>
|
||||||
|
↶
|
||||||
|
</TBtn>
|
||||||
|
<TBtn label="Redo" disabled={!state.canRedo} onClick={() => editor.chain().focus().redo().run()}>
|
||||||
|
↷
|
||||||
|
</TBtn>
|
||||||
|
<Divider />
|
||||||
|
|
||||||
<TBtn label="Bold" active={state.bold} onClick={() => editor.chain().focus().toggleBold().run()}>
|
<TBtn label="Bold" active={state.bold} onClick={() => editor.chain().focus().toggleBold().run()}>
|
||||||
<span className="font-extrabold">B</span>
|
<span className="font-extrabold">B</span>
|
||||||
</TBtn>
|
</TBtn>
|
||||||
@@ -93,51 +281,301 @@ export function Toolbar({ editor, onVoiceCheck, voicing }: Props) {
|
|||||||
>
|
>
|
||||||
<span className="underline">U</span>
|
<span className="underline">U</span>
|
||||||
</TBtn>
|
</TBtn>
|
||||||
|
<TBtn label="Strikethrough" active={state.strike} onClick={() => editor.chain().focus().toggleStrike().run()}>
|
||||||
|
<span className="line-through">S</span>
|
||||||
|
</TBtn>
|
||||||
<Divider />
|
<Divider />
|
||||||
<TBtn
|
|
||||||
label="Heading 1"
|
{/* Text color */}
|
||||||
active={state.h1}
|
<Popover
|
||||||
onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
|
open={menu === 'color'}
|
||||||
|
onClose={close}
|
||||||
|
width={188}
|
||||||
|
trigger={
|
||||||
|
<TBtn label="Text color" active={menu === 'color'} onClick={() => setMenu(menu === 'color' ? null : 'color')}>
|
||||||
|
<span className="flex flex-col items-center leading-none">
|
||||||
|
<span className="text-sm font-bold">A</span>
|
||||||
|
<span
|
||||||
|
className="mt-0.5 h-1 w-4 rounded-full"
|
||||||
|
style={{ background: state.color ?? 'var(--color-accent)' }}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
</TBtn>
|
||||||
|
}
|
||||||
>
|
>
|
||||||
|
<div className="grid grid-cols-4 gap-1.5">
|
||||||
|
{TEXT_COLORS.map((c) => (
|
||||||
|
<Swatch
|
||||||
|
key={c.label}
|
||||||
|
color={c.value}
|
||||||
|
title={c.label}
|
||||||
|
active={state.color === c.value}
|
||||||
|
onClick={() => {
|
||||||
|
if (c.value) editor.chain().focus().setColor(c.value).run()
|
||||||
|
else editor.chain().focus().unsetColor().run()
|
||||||
|
close()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
|
{/* Highlight */}
|
||||||
|
<Popover
|
||||||
|
open={menu === 'highlight'}
|
||||||
|
onClose={close}
|
||||||
|
width={170}
|
||||||
|
trigger={
|
||||||
|
<TBtn
|
||||||
|
label="Highlight"
|
||||||
|
active={menu === 'highlight' || !!state.highlight}
|
||||||
|
onClick={() => setMenu(menu === 'highlight' ? null : 'highlight')}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="flex h-5 w-5 items-center justify-center rounded text-xs font-bold"
|
||||||
|
style={{ background: state.highlight ?? '#FFF1A8', color: 'var(--color-plum)' }}
|
||||||
|
>
|
||||||
|
H
|
||||||
|
</span>
|
||||||
|
</TBtn>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-4 gap-1.5">
|
||||||
|
{HIGHLIGHTS.map((c) => (
|
||||||
|
<Swatch
|
||||||
|
key={c.label}
|
||||||
|
color={c.value}
|
||||||
|
title={c.label}
|
||||||
|
active={state.highlight === c.value}
|
||||||
|
onClick={() => {
|
||||||
|
if (c.value) editor.chain().focus().setHighlight({ color: c.value }).run()
|
||||||
|
else editor.chain().focus().unsetHighlight().run()
|
||||||
|
close()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
|
{/* Font size */}
|
||||||
|
<Popover
|
||||||
|
open={menu === 'size'}
|
||||||
|
onClose={close}
|
||||||
|
width={140}
|
||||||
|
trigger={
|
||||||
|
<TBtn label="Text size" active={menu === 'size'} onClick={() => setMenu(menu === 'size' ? null : 'size')}>
|
||||||
|
<span className="text-xs font-bold tracking-tight">
|
||||||
|
<span className="text-[0.7rem]">A</span>
|
||||||
|
<span className="text-sm">A</span>
|
||||||
|
</span>
|
||||||
|
</TBtn>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col gap-0.5">
|
||||||
|
{SIZES.map((s) => {
|
||||||
|
const active = state.fontSize === s.value
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={s.label}
|
||||||
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={() => {
|
||||||
|
if (s.value) editor.chain().focus().setFontSize(s.value).run()
|
||||||
|
else editor.chain().focus().unsetFontSize().run()
|
||||||
|
close()
|
||||||
|
}}
|
||||||
|
className="flex items-center justify-between rounded px-2 py-1 text-left"
|
||||||
|
style={{
|
||||||
|
background: active ? 'var(--color-surface-alt)' : 'transparent',
|
||||||
|
color: active ? 'var(--color-accent-hover)' : 'var(--color-plum)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ fontSize: s.em }}>{s.label}</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</Popover>
|
||||||
|
<Divider />
|
||||||
|
|
||||||
|
<TBtn label="Heading 1" active={state.h1} onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}>
|
||||||
H1
|
H1
|
||||||
</TBtn>
|
</TBtn>
|
||||||
<TBtn
|
<TBtn label="Heading 2" active={state.h2} onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}>
|
||||||
label="Heading 2"
|
|
||||||
active={state.h2}
|
|
||||||
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
|
|
||||||
>
|
|
||||||
H2
|
H2
|
||||||
</TBtn>
|
</TBtn>
|
||||||
<TBtn
|
<TBtn label="Heading 3" active={state.h3} onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}>
|
||||||
label="Bullet list"
|
H3
|
||||||
active={state.bullet}
|
</TBtn>
|
||||||
onClick={() => editor.chain().focus().toggleBulletList().run()}
|
<TBtn label="Bullet list" active={state.bullet} onClick={() => editor.chain().focus().toggleBulletList().run()}>
|
||||||
>
|
|
||||||
•
|
•
|
||||||
</TBtn>
|
</TBtn>
|
||||||
|
<TBtn label="Numbered list" active={state.ordered} onClick={() => editor.chain().focus().toggleOrderedList().run()}>
|
||||||
|
1.
|
||||||
|
</TBtn>
|
||||||
<Divider />
|
<Divider />
|
||||||
<TBtn
|
|
||||||
label="Align left"
|
<TBtn label="Align left" active={state.left} onClick={() => editor.chain().focus().setTextAlign('left').run()}>
|
||||||
active={state.left}
|
|
||||||
onClick={() => editor.chain().focus().setTextAlign('left').run()}
|
|
||||||
>
|
|
||||||
⇤
|
⇤
|
||||||
</TBtn>
|
</TBtn>
|
||||||
<TBtn
|
<TBtn label="Align center" active={state.center} onClick={() => editor.chain().focus().setTextAlign('center').run()}>
|
||||||
label="Align center"
|
|
||||||
active={state.center}
|
|
||||||
onClick={() => editor.chain().focus().setTextAlign('center').run()}
|
|
||||||
>
|
|
||||||
↔
|
↔
|
||||||
</TBtn>
|
</TBtn>
|
||||||
<TBtn
|
<TBtn label="Align right" active={state.right} onClick={() => editor.chain().focus().setTextAlign('right').run()}>
|
||||||
label="Align right"
|
|
||||||
active={state.right}
|
|
||||||
onClick={() => editor.chain().focus().setTextAlign('right').run()}
|
|
||||||
>
|
|
||||||
⇥
|
⇥
|
||||||
</TBtn>
|
</TBtn>
|
||||||
<Divider />
|
<Divider />
|
||||||
|
|
||||||
|
{/* Link */}
|
||||||
|
<Popover
|
||||||
|
open={menu === 'link'}
|
||||||
|
onClose={close}
|
||||||
|
width={236}
|
||||||
|
trigger={
|
||||||
|
<TBtn label="Link" active={state.link || menu === 'link'} onClick={openLink}>
|
||||||
|
🔗
|
||||||
|
</TBtn>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
value={linkUrl}
|
||||||
|
onChange={(e) => setLinkUrl(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') applyLink()
|
||||||
|
if (e.key === 'Escape') close()
|
||||||
|
}}
|
||||||
|
placeholder="https://…"
|
||||||
|
className="w-full px-2 py-1.5 text-sm focus:outline-none"
|
||||||
|
style={{
|
||||||
|
borderRadius: 'var(--radius-input)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
color: 'var(--color-plum)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
{state.link ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={() => {
|
||||||
|
editor.chain().focus().extendMarkRange('link').unsetLink().run()
|
||||||
|
close()
|
||||||
|
}}
|
||||||
|
className="px-2 py-1 text-xs font-semibold"
|
||||||
|
style={{ color: 'var(--color-muted)' }}
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={applyLink}
|
||||||
|
className="px-3 py-1 text-xs font-bold"
|
||||||
|
style={{
|
||||||
|
borderRadius: 'var(--radius-pill)',
|
||||||
|
background: 'var(--color-accent)',
|
||||||
|
color: '#fff',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Apply
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
|
{/* Image */}
|
||||||
|
<input ref={fileInputRef} type="file" accept="image/*" hidden onChange={onPickImage} />
|
||||||
|
<TBtn label="Insert image" onClick={() => fileInputRef.current?.click()}>
|
||||||
|
🖼️
|
||||||
|
</TBtn>
|
||||||
|
|
||||||
|
{/* Table */}
|
||||||
|
<Popover
|
||||||
|
open={menu === 'table'}
|
||||||
|
onClose={close}
|
||||||
|
width={state.inTable ? 188 : 150}
|
||||||
|
trigger={
|
||||||
|
<TBtn label="Table" active={state.inTable || menu === 'table'} onClick={() => setMenu(menu === 'table' ? null : 'table')}>
|
||||||
|
▦
|
||||||
|
</TBtn>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{state.inTable ? (
|
||||||
|
<div className="flex flex-col gap-0.5 text-sm" style={{ color: 'var(--color-plum)' }}>
|
||||||
|
<TableAction label="Add row below" onClick={() => editor.chain().focus().addRowAfter().run()} />
|
||||||
|
<TableAction label="Add column right" onClick={() => editor.chain().focus().addColumnAfter().run()} />
|
||||||
|
<TableAction label="Toggle header row" onClick={() => editor.chain().focus().toggleHeaderRow().run()} />
|
||||||
|
<TableAction label="Delete row" onClick={() => editor.chain().focus().deleteRow().run()} />
|
||||||
|
<TableAction label="Delete column" onClick={() => editor.chain().focus().deleteColumn().run()} />
|
||||||
|
<TableAction
|
||||||
|
label="Delete table"
|
||||||
|
danger
|
||||||
|
onClick={() => {
|
||||||
|
editor.chain().focus().deleteTable().run()
|
||||||
|
close()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<GridPicker
|
||||||
|
onPick={(rows, cols) => {
|
||||||
|
editor.chain().focus().insertTable({ rows, cols, withHeaderRow: true }).run()
|
||||||
|
close()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Popover>
|
||||||
|
|
||||||
|
{/* Outline / document map */}
|
||||||
|
<Popover
|
||||||
|
open={menu === 'outline'}
|
||||||
|
onClose={close}
|
||||||
|
width={240}
|
||||||
|
trigger={
|
||||||
|
<TBtn label="Outline" active={menu === 'outline'} onClick={() => setMenu(menu === 'outline' ? null : 'outline')}>
|
||||||
|
☰
|
||||||
|
</TBtn>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="max-h-72 overflow-y-auto">
|
||||||
|
<p className="mb-1.5 px-1 text-xs font-bold" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
大纲 · Outline
|
||||||
|
</p>
|
||||||
|
{headings.length === 0 ? (
|
||||||
|
<p className="px-1 py-2 text-xs leading-snug" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
用 H1/H2/H3 添加标题,这里就会出现导航。<br />
|
||||||
|
Add headings to navigate them here.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col">
|
||||||
|
{headings.map((h, i) => (
|
||||||
|
<button
|
||||||
|
key={i}
|
||||||
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={() => gotoHeading(h.pos)}
|
||||||
|
className="truncate rounded px-1.5 py-1 text-left text-sm hover:bg-[var(--color-surface-alt)]"
|
||||||
|
style={{
|
||||||
|
paddingLeft: `${(h.level - 1) * 12 + 6}px`,
|
||||||
|
color: 'var(--color-plum)',
|
||||||
|
fontWeight: h.level === 1 ? 700 : 500,
|
||||||
|
}}
|
||||||
|
title={h.text}
|
||||||
|
>
|
||||||
|
{h.text}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Popover>
|
||||||
|
<Divider />
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-label="Check my voice"
|
aria-label="Check my voice"
|
||||||
@@ -159,6 +597,83 @@ 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A row in the in-table editing menu.
|
||||||
|
function TableAction({ label, onClick, danger }: { label: string; onClick: () => void; danger?: boolean }) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onClick={onClick}
|
||||||
|
className="rounded px-2 py-1 text-left"
|
||||||
|
style={{ color: danger ? 'var(--color-accent-hover)' : 'var(--color-plum)' }}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A hover-to-size grid for inserting a table. Hovering a cell highlights the
|
||||||
|
// rectangle from the top-left; clicking inserts that many rows × columns.
|
||||||
|
function GridPicker({ onPick }: { onPick: (rows: number, cols: number) => void }) {
|
||||||
|
const MAX = 6
|
||||||
|
const [hover, setHover] = useState<{ r: number; c: number }>({ r: 0, c: 0 })
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div
|
||||||
|
className="grid gap-0.5"
|
||||||
|
style={{ gridTemplateColumns: `repeat(${MAX}, 1fr)` }}
|
||||||
|
onMouseLeave={() => setHover({ r: 0, c: 0 })}
|
||||||
|
>
|
||||||
|
{Array.from({ length: MAX * MAX }).map((_, i) => {
|
||||||
|
const r = Math.floor(i / MAX) + 1
|
||||||
|
const c = (i % MAX) + 1
|
||||||
|
const on = r <= hover.r && c <= hover.c
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={i}
|
||||||
|
type="button"
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
onMouseEnter={() => setHover({ r, c })}
|
||||||
|
onClick={() => onPick(r, c)}
|
||||||
|
className="h-4 w-4"
|
||||||
|
style={{
|
||||||
|
borderRadius: 3,
|
||||||
|
background: on ? 'var(--color-accent)' : 'var(--color-surface-alt)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1.5 text-center text-xs" style={{ color: 'var(--color-muted)' }}>
|
||||||
|
{hover.r > 0 ? `${hover.r} × ${hover.c}` : 'Pick a size'}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,243 +1,351 @@
|
|||||||
import { useEffect, useRef } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import { isPetalsEnabled, onPetalsEnabledChange } from './petals'
|
||||||
|
|
||||||
// PetalFall is the cozy ambient layer: a full-window WebGL canvas that drifts a
|
// PetalFall is the cozy ambient layer: a fixed, non-interactive 2D canvas that
|
||||||
// handful of soft flower petals down the page. It sits behind everything,
|
// drifts soft cherry-blossom petals down the page. Each petal is a real
|
||||||
// ignores pointer events, and stays sparse so it reads as "occasional petals on
|
// petal-shaped sprite (notched sakura silhouette with a gentle gradient and
|
||||||
// a breeze" rather than confetti. Honors prefers-reduced-motion by rendering
|
// soft alpha), pre-rendered once per color and then blitted many times with
|
||||||
// nothing. No external libraries — a single tiny shader program animates every
|
// rotation + sway. It sits behind the chrome, ignores pointer events, pauses
|
||||||
// petal entirely on the GPU, so the CPU just spins a clock.
|
// when the tab is hidden, and renders nothing for prefers-reduced-motion.
|
||||||
|
|
||||||
// Each petal is a quad whose corners we expand in the vertex shader. We pack one
|
// Saturated-but-soft blossom colors. Each petal fades from a light, near-white
|
||||||
// quad as 6 vertices; per-vertex we send the corner offset (which corner) plus
|
// tip to its color at the base, so it reads as a real petal rather than a blob.
|
||||||
// the petal's static randomness (lane, speed, size, sway, tint, spin).
|
const PALETTE: { r: number; g: number; b: number }[] = [
|
||||||
const PETAL_COUNT = 26
|
{ r: 255, g: 150, b: 190 }, // rose pink
|
||||||
|
{ r: 255, g: 184, b: 205 }, // pale blossom
|
||||||
// Soft Petal-palette tints (rose / blush / lavender), as RGB 0..1.
|
{ r: 255, g: 158, b: 130 }, // warm peach
|
||||||
const TINTS: [number, number, number][] = [
|
{ r: 209, g: 160, b: 255 }, // lavender
|
||||||
[0.91, 0.63, 0.75], // accent rose #E8A0BF
|
{ r: 255, g: 122, b: 172 }, // deep rose
|
||||||
[1.0, 0.94, 0.96], // near-white blush
|
|
||||||
[0.96, 0.72, 0.63], // peach #F4B8A0
|
|
||||||
[0.77, 0.71, 0.91], // lavender #C5B4E8
|
|
||||||
[0.85, 0.55, 0.69], // deeper rose
|
|
||||||
]
|
]
|
||||||
|
|
||||||
const VERT = `
|
// Night-mode sparkle palette: soft starlight tones for the small twinkle accents
|
||||||
precision mediump float;
|
// scattered between the chunky cartoon stars (moonlit white, warm gold).
|
||||||
attribute vec2 a_corner; // quad corner in [-0.5,0.5]
|
const STAR_PALETTE: { r: number; g: number; b: number }[] = [
|
||||||
attribute vec4 a_rand; // x: lane(0..1), y: speed, z: size, w: phase
|
{ r: 255, g: 255, b: 255 }, // white
|
||||||
attribute vec4 a_rand2; // x: swayAmp, y: swayFreq, z: spin, w: tintIdx
|
{ r: 255, g: 240, b: 200 }, // warm gold
|
||||||
uniform float u_time;
|
]
|
||||||
uniform vec2 u_res;
|
|
||||||
varying vec2 v_uv;
|
|
||||||
varying float v_tint;
|
|
||||||
varying float v_alpha;
|
|
||||||
|
|
||||||
void main() {
|
// Chunky cartoon-star colors — bold, candy-bright fills à la a Mario power star
|
||||||
v_uv = a_corner + 0.5;
|
// or a Kirby warp star. Each is drawn with a glossy gradient + a puffy outline.
|
||||||
v_tint = a_rand2.w;
|
const CARTOON_COLORS: { r: number; g: number; b: number }[] = [
|
||||||
|
{ r: 255, g: 201, b: 56 }, // golden power-star
|
||||||
|
{ r: 255, g: 150, b: 190 }, // bubblegum pink
|
||||||
|
{ r: 130, g: 195, b: 255 }, // sky blue
|
||||||
|
{ r: 150, g: 225, b: 190 }, // mint
|
||||||
|
{ r: 200, g: 175, b: 255 }, // lavender
|
||||||
|
]
|
||||||
|
|
||||||
float lane = a_rand.x;
|
const SPRITE_PX = 160 // off-screen render resolution per petal sprite
|
||||||
float speed = a_rand.y;
|
|
||||||
float size = a_rand.z;
|
|
||||||
float phase = a_rand.w;
|
|
||||||
|
|
||||||
// Vertical fall: loop 0..1 over time, offset per petal so they don't sync.
|
function rgba(c: { r: number; g: number; b: number }, a: number): string {
|
||||||
float fall = fract(u_time * speed + phase);
|
return `rgba(${Math.round(c.r)}, ${Math.round(c.g)}, ${Math.round(c.b)}, ${a})`
|
||||||
// Map to clip space: start above the top (1.15) fall to below bottom (-1.15).
|
|
||||||
float y = 1.15 - fall * 2.3;
|
|
||||||
|
|
||||||
// Horizontal: a base lane plus a gentle sway as it descends.
|
|
||||||
float sway = a_rand2.x * sin(u_time * a_rand2.y + phase * 6.2831);
|
|
||||||
float x = (lane * 2.0 - 1.0) + sway;
|
|
||||||
|
|
||||||
// Spin the quad over time.
|
|
||||||
float ang = u_time * a_rand2.z + phase * 6.2831;
|
|
||||||
float c = cos(ang), s = sin(ang);
|
|
||||||
vec2 corner = a_corner * size;
|
|
||||||
// Keep petals visually square despite aspect ratio.
|
|
||||||
corner.x *= u_res.y / u_res.x;
|
|
||||||
vec2 rot = vec2(corner.x * c - corner.y * s, corner.x * s + corner.y * c);
|
|
||||||
|
|
||||||
// Fade in near the top and out near the bottom so they don't pop.
|
|
||||||
v_alpha = smoothstep(0.0, 0.12, fall) * (1.0 - smoothstep(0.86, 1.0, fall));
|
|
||||||
|
|
||||||
gl_Position = vec4(x + rot.x, y + rot.y, 0.0, 1.0);
|
|
||||||
}
|
}
|
||||||
`
|
function mixWhite(c: { r: number; g: number; b: number }, t: number) {
|
||||||
|
return { r: c.r + (255 - c.r) * t, g: c.g + (255 - c.g) * t, b: c.b + (255 - c.b) * t }
|
||||||
const FRAG = `
|
}
|
||||||
precision mediump float;
|
function scale(c: { r: number; g: number; b: number }, t: number) {
|
||||||
varying vec2 v_uv;
|
return { r: c.r * t, g: c.g * t, b: c.b * t }
|
||||||
varying float v_tint;
|
|
||||||
varying float v_alpha;
|
|
||||||
uniform vec3 u_tints[5];
|
|
||||||
|
|
||||||
// A soft petal/teardrop alpha mask centered in the quad.
|
|
||||||
float petalMask(vec2 uv) {
|
|
||||||
vec2 p = uv - vec2(0.5);
|
|
||||||
// Teardrop: pinch the top, round the bottom.
|
|
||||||
float r = length(vec2(p.x * 1.65, p.y * 1.15 + 0.12));
|
|
||||||
float body = smoothstep(0.5, 0.16, r);
|
|
||||||
// A subtle crease down the middle for a petal feel.
|
|
||||||
float crease = 1.0 - 0.18 * exp(-pow(p.x * 7.0, 2.0));
|
|
||||||
return body * crease;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void main() {
|
// Draw one petal sprite: a notched sakura silhouette filled with a tip→base
|
||||||
float m = petalMask(v_uv);
|
// gradient and a faint central highlight, on a transparent canvas.
|
||||||
if (m < 0.01) discard;
|
function makeSprite(color: { r: number; g: number; b: number }): HTMLCanvasElement {
|
||||||
int idx = int(v_tint + 0.5);
|
const s = SPRITE_PX
|
||||||
vec3 col = u_tints[0];
|
const cv = document.createElement('canvas')
|
||||||
if (idx == 1) col = u_tints[1];
|
cv.width = s
|
||||||
else if (idx == 2) col = u_tints[2];
|
cv.height = s
|
||||||
else if (idx == 3) col = u_tints[3];
|
const g = cv.getContext('2d')!
|
||||||
else if (idx == 4) col = u_tints[4];
|
g.translate(s / 2, s / 2)
|
||||||
gl_FragColor = vec4(col, m * v_alpha * 0.55);
|
|
||||||
}
|
|
||||||
`
|
|
||||||
|
|
||||||
function compile(gl: WebGLRenderingContext, type: number, src: string): WebGLShader | null {
|
const hw = s * 0.3 // half width
|
||||||
const sh = gl.createShader(type)
|
const hh = s * 0.44 // half height
|
||||||
if (!sh) return null
|
|
||||||
gl.shaderSource(sh, src)
|
g.beginPath()
|
||||||
gl.compileShader(sh)
|
g.moveTo(0, hh) // pointed base
|
||||||
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
|
g.bezierCurveTo(hw, hh * 0.42, hw * 0.92, -hh * 0.52, hw * 0.2, -hh * 0.92) // right side → near tip
|
||||||
console.error('petal shader compile failed', gl.getShaderInfoLog(sh))
|
g.quadraticCurveTo(0, -hh * 0.72, -hw * 0.2, -hh * 0.92) // the sakura notch
|
||||||
gl.deleteShader(sh)
|
g.bezierCurveTo(-hw * 0.92, -hh * 0.52, -hw, hh * 0.42, 0, hh) // left side → base
|
||||||
return null
|
g.closePath()
|
||||||
|
|
||||||
|
const grad = g.createLinearGradient(0, -hh, 0, hh)
|
||||||
|
grad.addColorStop(0, rgba(mixWhite(color, 0.55), 0.78)) // light, soft tip
|
||||||
|
grad.addColorStop(0.45, rgba(color, 0.88))
|
||||||
|
grad.addColorStop(1, rgba(scale(color, 0.8), 0.95)) // deeper base
|
||||||
|
g.fillStyle = grad
|
||||||
|
g.fill()
|
||||||
|
|
||||||
|
// A soft white sheen down the centre for a delicate, glossy feel.
|
||||||
|
const sheen = g.createLinearGradient(-hw * 0.3, 0, hw * 0.3, 0)
|
||||||
|
sheen.addColorStop(0, 'rgba(255,255,255,0)')
|
||||||
|
sheen.addColorStop(0.5, 'rgba(255,255,255,0.28)')
|
||||||
|
sheen.addColorStop(1, 'rgba(255,255,255,0)')
|
||||||
|
g.fillStyle = sheen
|
||||||
|
g.fill()
|
||||||
|
|
||||||
|
return cv
|
||||||
|
}
|
||||||
|
|
||||||
|
// Draw one star sprite: a soft radial glow with a crisp four-point sparkle on
|
||||||
|
// top, filled brightest at the core so it reads as a twinkling star.
|
||||||
|
function makeStarSprite(color: { r: number; g: number; b: number }): HTMLCanvasElement {
|
||||||
|
const s = SPRITE_PX
|
||||||
|
const cv = document.createElement('canvas')
|
||||||
|
cv.width = s
|
||||||
|
cv.height = s
|
||||||
|
const g = cv.getContext('2d')!
|
||||||
|
g.translate(s / 2, s / 2)
|
||||||
|
|
||||||
|
// Soft halo behind the sparkle.
|
||||||
|
const glow = g.createRadialGradient(0, 0, 0, 0, 0, s * 0.5)
|
||||||
|
glow.addColorStop(0, rgba(mixWhite(color, 0.5), 0.5))
|
||||||
|
glow.addColorStop(0.35, rgba(color, 0.16))
|
||||||
|
glow.addColorStop(1, rgba(color, 0))
|
||||||
|
g.fillStyle = glow
|
||||||
|
g.beginPath()
|
||||||
|
g.arc(0, 0, s * 0.5, 0, Math.PI * 2)
|
||||||
|
g.fill()
|
||||||
|
|
||||||
|
// Four-point sparkle: alternate a long outer radius with a small inner one so
|
||||||
|
// the points pinch in sharply.
|
||||||
|
const R = s * 0.46
|
||||||
|
const r = s * 0.08
|
||||||
|
g.beginPath()
|
||||||
|
for (let i = 0; i < 8; i++) {
|
||||||
|
const ang = (i * Math.PI) / 4 - Math.PI / 2
|
||||||
|
const rad = i % 2 === 0 ? R : r
|
||||||
|
const x = Math.cos(ang) * rad
|
||||||
|
const y = Math.sin(ang) * rad
|
||||||
|
if (i === 0) g.moveTo(x, y)
|
||||||
|
else g.lineTo(x, y)
|
||||||
}
|
}
|
||||||
return sh
|
g.closePath()
|
||||||
|
const core = g.createRadialGradient(0, 0, 0, 0, 0, R)
|
||||||
|
core.addColorStop(0, rgba(mixWhite(color, 0.7), 0.98))
|
||||||
|
core.addColorStop(0.5, rgba(color, 0.9))
|
||||||
|
core.addColorStop(1, rgba(color, 0.2))
|
||||||
|
g.fillStyle = core
|
||||||
|
g.fill()
|
||||||
|
|
||||||
|
return cv
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deterministic-ish pseudo random (we can't use Math.random at module scope for
|
// Draw one chunky cartoon star — a fat five-point star with a glossy radial
|
||||||
// SSR safety, but here in an effect it's fine; kept simple).
|
// fill, a soft outer glow so it pops off the dark sky, a puffy rounded outline
|
||||||
function rand(): number {
|
// (round line joins → Kirby-ish soft points), and a little corner shine. Reads
|
||||||
return Math.random()
|
// like a game power-up rather than a delicate sparkle.
|
||||||
|
function makeCartoonStar(base: { r: number; g: number; b: number }): HTMLCanvasElement {
|
||||||
|
const s = SPRITE_PX
|
||||||
|
const cv = document.createElement('canvas')
|
||||||
|
cv.width = s
|
||||||
|
cv.height = s
|
||||||
|
const g = cv.getContext('2d')!
|
||||||
|
g.translate(s / 2, s / 2)
|
||||||
|
|
||||||
|
const R = s * 0.4 // outer point radius
|
||||||
|
const r = R * 0.46 // inner radius — small ⇒ chunky, defined points
|
||||||
|
|
||||||
|
// Soft outer glow so the star separates from the night background.
|
||||||
|
const glow = g.createRadialGradient(0, 0, R * 0.3, 0, 0, R * 1.35)
|
||||||
|
glow.addColorStop(0, rgba(base, 0.35))
|
||||||
|
glow.addColorStop(1, rgba(base, 0))
|
||||||
|
g.fillStyle = glow
|
||||||
|
g.beginPath()
|
||||||
|
g.arc(0, 0, R * 1.35, 0, Math.PI * 2)
|
||||||
|
g.fill()
|
||||||
|
|
||||||
|
// Five-point star path (start at the top point).
|
||||||
|
const star = () => {
|
||||||
|
g.beginPath()
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
const ang = -Math.PI / 2 + (i * Math.PI) / 5
|
||||||
|
const rad = i % 2 === 0 ? R : r
|
||||||
|
const x = Math.cos(ang) * rad
|
||||||
|
const y = Math.sin(ang) * rad
|
||||||
|
if (i === 0) g.moveTo(x, y)
|
||||||
|
else g.lineTo(x, y)
|
||||||
|
}
|
||||||
|
g.closePath()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Candy fill: bright near the top-left, deepening toward the lower edge.
|
||||||
|
const fill = g.createRadialGradient(-R * 0.25, -R * 0.3, R * 0.1, 0, 0, R * 1.1)
|
||||||
|
fill.addColorStop(0, rgba(mixWhite(base, 0.7), 1))
|
||||||
|
fill.addColorStop(0.5, rgba(base, 1))
|
||||||
|
fill.addColorStop(1, rgba(scale(base, 0.82), 1))
|
||||||
|
star()
|
||||||
|
g.fillStyle = fill
|
||||||
|
g.fill()
|
||||||
|
|
||||||
|
// Puffy outline in a deeper shade of the same hue (round joins soften the
|
||||||
|
// points so it feels hand-drawn, not spiky).
|
||||||
|
g.lineJoin = 'round'
|
||||||
|
g.lineCap = 'round'
|
||||||
|
g.lineWidth = s * 0.05
|
||||||
|
g.strokeStyle = rgba(scale(base, 0.5), 0.95)
|
||||||
|
star()
|
||||||
|
g.stroke()
|
||||||
|
|
||||||
|
// Glossy shine: a small soft white blob up in the top-left lobe.
|
||||||
|
const shine = g.createRadialGradient(-R * 0.22, -R * 0.32, 0, -R * 0.22, -R * 0.32, R * 0.3)
|
||||||
|
shine.addColorStop(0, 'rgba(255,255,255,0.85)')
|
||||||
|
shine.addColorStop(1, 'rgba(255,255,255,0)')
|
||||||
|
g.fillStyle = shine
|
||||||
|
g.beginPath()
|
||||||
|
g.ellipse(-R * 0.22, -R * 0.32, R * 0.26, R * 0.18, -0.5, 0, Math.PI * 2)
|
||||||
|
g.fill()
|
||||||
|
|
||||||
|
return cv
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PetalFall() {
|
interface Petal {
|
||||||
|
baseX: number
|
||||||
|
y: number
|
||||||
|
size: number
|
||||||
|
vy: number // fall speed (px/s)
|
||||||
|
angle: number
|
||||||
|
spin: number // rad/s
|
||||||
|
swayAmp: number
|
||||||
|
swayFreq: number
|
||||||
|
swayPhase: number
|
||||||
|
alpha: number
|
||||||
|
sprite: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PetalFall({ night = false }: { night?: boolean }) {
|
||||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||||
|
const [enabled, setEnabled] = useState(isPetalsEnabled)
|
||||||
|
|
||||||
|
// Let the status-bar toggle switch the ambient layer on/off live.
|
||||||
|
useEffect(() => onPetalsEnabledChange(setEnabled), [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!enabled) {
|
||||||
|
// User turned the ambient petals off — wipe any frame left on the canvas.
|
||||||
|
const el = canvasRef.current
|
||||||
|
el?.getContext('2d')?.clearRect(0, 0, el.width, el.height)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const reduce =
|
const reduce =
|
||||||
typeof window !== 'undefined' &&
|
typeof window !== 'undefined' &&
|
||||||
window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
||||||
if (reduce) return // respect users who don't want ambient motion
|
if (reduce) return // respect users who don't want ambient motion
|
||||||
|
|
||||||
const canvas = canvasRef.current
|
const el = canvasRef.current
|
||||||
if (!canvas) return
|
if (!el) return
|
||||||
const gl = canvas.getContext('webgl', { alpha: true, premultipliedAlpha: false, antialias: true })
|
const c2d = el.getContext('2d')
|
||||||
if (!gl) return // no WebGL — silently skip the effect
|
if (!c2d) return
|
||||||
|
|
||||||
const vs = compile(gl, gl.VERTEX_SHADER, VERT)
|
|
||||||
const fs = compile(gl, gl.FRAGMENT_SHADER, FRAG)
|
|
||||||
if (!vs || !fs) return
|
|
||||||
const prog = gl.createProgram()!
|
|
||||||
gl.attachShader(prog, vs)
|
|
||||||
gl.attachShader(prog, fs)
|
|
||||||
gl.linkProgram(prog)
|
|
||||||
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
|
|
||||||
console.error('petal program link failed', gl.getProgramInfoLog(prog))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
gl.useProgram(prog)
|
|
||||||
|
|
||||||
// Build interleaved vertex data: 6 verts per petal, each with corner(2),
|
|
||||||
// rand(4), rand2(4) = 10 floats.
|
|
||||||
const FLOATS_PER_VERT = 10
|
|
||||||
const corners = [
|
|
||||||
[-0.5, -0.5],
|
|
||||||
[0.5, -0.5],
|
|
||||||
[-0.5, 0.5],
|
|
||||||
[-0.5, 0.5],
|
|
||||||
[0.5, -0.5],
|
|
||||||
[0.5, 0.5],
|
|
||||||
]
|
|
||||||
const data = new Float32Array(PETAL_COUNT * 6 * FLOATS_PER_VERT)
|
|
||||||
let o = 0
|
|
||||||
for (let i = 0; i < PETAL_COUNT; i++) {
|
|
||||||
const lane = rand()
|
|
||||||
const speed = 0.018 + rand() * 0.03 // slow, gentle fall
|
|
||||||
const size = 0.05 + rand() * 0.06
|
|
||||||
const phase = rand()
|
|
||||||
const swayAmp = 0.04 + rand() * 0.09
|
|
||||||
const swayFreq = 0.4 + rand() * 0.7
|
|
||||||
const spin = (rand() - 0.5) * 1.2
|
|
||||||
const tint = Math.floor(rand() * TINTS.length)
|
|
||||||
for (let c = 0; c < 6; c++) {
|
|
||||||
data[o++] = corners[c][0]
|
|
||||||
data[o++] = corners[c][1]
|
|
||||||
data[o++] = lane
|
|
||||||
data[o++] = speed
|
|
||||||
data[o++] = size
|
|
||||||
data[o++] = phase
|
|
||||||
data[o++] = swayAmp
|
|
||||||
data[o++] = swayFreq
|
|
||||||
data[o++] = spin
|
|
||||||
data[o++] = tint
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const buf = gl.createBuffer()
|
|
||||||
gl.bindBuffer(gl.ARRAY_BUFFER, buf)
|
|
||||||
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW)
|
|
||||||
|
|
||||||
const stride = FLOATS_PER_VERT * 4
|
|
||||||
const aCorner = gl.getAttribLocation(prog, 'a_corner')
|
|
||||||
const aRand = gl.getAttribLocation(prog, 'a_rand')
|
|
||||||
const aRand2 = gl.getAttribLocation(prog, 'a_rand2')
|
|
||||||
gl.enableVertexAttribArray(aCorner)
|
|
||||||
gl.vertexAttribPointer(aCorner, 2, gl.FLOAT, false, stride, 0)
|
|
||||||
gl.enableVertexAttribArray(aRand)
|
|
||||||
gl.vertexAttribPointer(aRand, 4, gl.FLOAT, false, stride, 2 * 4)
|
|
||||||
gl.enableVertexAttribArray(aRand2)
|
|
||||||
gl.vertexAttribPointer(aRand2, 4, gl.FLOAT, false, stride, 6 * 4)
|
|
||||||
|
|
||||||
const uTime = gl.getUniformLocation(prog, 'u_time')
|
|
||||||
const uRes = gl.getUniformLocation(prog, 'u_res')
|
|
||||||
const uTints = gl.getUniformLocation(prog, 'u_tints')
|
|
||||||
gl.uniform3fv(uTints, TINTS.flat())
|
|
||||||
|
|
||||||
gl.enable(gl.BLEND)
|
|
||||||
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
|
|
||||||
gl.disable(gl.DEPTH_TEST)
|
|
||||||
|
|
||||||
// Non-null aliases so the render closures keep the narrowed types.
|
// Non-null aliases so the render closures keep the narrowed types.
|
||||||
const view = canvas
|
const canvas = el
|
||||||
const glc = gl
|
const ctx = c2d
|
||||||
|
|
||||||
|
// Night sky = chunky cartoon stars (the stars of the show) with a couple of
|
||||||
|
// small twinkle sparkles mixed in for depth. Random sprite pick weights it
|
||||||
|
// ~70% chunky stars.
|
||||||
|
const sprites = night
|
||||||
|
? [...CARTOON_COLORS.map(makeCartoonStar), ...STAR_PALETTE.map(makeStarSprite)]
|
||||||
|
: PALETTE.map(makeSprite)
|
||||||
const dpr = Math.min(window.devicePixelRatio || 1, 2)
|
const dpr = Math.min(window.devicePixelRatio || 1, 2)
|
||||||
|
let W = window.innerWidth
|
||||||
|
let H = window.innerHeight
|
||||||
|
|
||||||
|
// Scale petal count to the viewport so it stays sparse and gentle.
|
||||||
|
const count = Math.round(Math.min(46, Math.max(16, (W * H) / 46000)))
|
||||||
|
const rnd = (a: number, b: number) => a + Math.random() * (b - a)
|
||||||
|
|
||||||
|
// Stars are smaller, drift down a touch slower, sway less, and barely spin
|
||||||
|
// (they twinkle in place instead of tumbling like petals).
|
||||||
|
const spawn = (initial: boolean): Petal =>
|
||||||
|
night
|
||||||
|
? {
|
||||||
|
baseX: rnd(0, W),
|
||||||
|
y: initial ? rnd(-H, H) : rnd(-60, -20),
|
||||||
|
size: rnd(13, 32),
|
||||||
|
vy: rnd(14, 36),
|
||||||
|
angle: rnd(0, Math.PI * 2),
|
||||||
|
// Every star visibly spins — random direction, and a guaranteed
|
||||||
|
// minimum speed (a 5-point star is symmetric every 72°, so a slow
|
||||||
|
// rate reads as motionless). Varied so no two turn quite alike.
|
||||||
|
spin: (Math.random() < 0.5 ? -1 : 1) * rnd(0.5, 2.2),
|
||||||
|
swayAmp: 0, // stars fall straight down — no petal-like drift
|
||||||
|
swayFreq: rnd(0.4, 1.1), // still drives the twinkle shimmer below
|
||||||
|
swayPhase: rnd(0, Math.PI * 2),
|
||||||
|
alpha: rnd(0.55, 0.9),
|
||||||
|
sprite: Math.floor(Math.random() * sprites.length),
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
baseX: rnd(0, W),
|
||||||
|
y: initial ? rnd(-H, H) : rnd(-60, -20),
|
||||||
|
size: rnd(16, 38),
|
||||||
|
vy: rnd(22, 52),
|
||||||
|
angle: rnd(0, Math.PI * 2),
|
||||||
|
spin: rnd(-0.9, 0.9),
|
||||||
|
swayAmp: rnd(14, 42),
|
||||||
|
swayFreq: rnd(0.3, 0.85),
|
||||||
|
swayPhase: rnd(0, Math.PI * 2),
|
||||||
|
alpha: rnd(0.5, 0.82),
|
||||||
|
sprite: Math.floor(Math.random() * sprites.length),
|
||||||
|
}
|
||||||
|
|
||||||
|
let petals = Array.from({ length: count }, () => spawn(true))
|
||||||
|
|
||||||
function resize() {
|
function resize() {
|
||||||
const w = Math.floor(window.innerWidth * dpr)
|
W = window.innerWidth
|
||||||
const h = Math.floor(window.innerHeight * dpr)
|
H = window.innerHeight
|
||||||
if (view.width !== w || view.height !== h) {
|
canvas.width = Math.floor(W * dpr)
|
||||||
view.width = w
|
canvas.height = Math.floor(H * dpr)
|
||||||
view.height = h
|
canvas.style.width = `${W}px`
|
||||||
}
|
canvas.style.height = `${H}px`
|
||||||
glc.viewport(0, 0, view.width, view.height)
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
|
||||||
glc.uniform2f(uRes, view.width, view.height)
|
|
||||||
}
|
}
|
||||||
resize()
|
resize()
|
||||||
window.addEventListener('resize', resize)
|
window.addEventListener('resize', resize)
|
||||||
|
|
||||||
let raf = 0
|
let raf = 0
|
||||||
let running = true
|
let running = true
|
||||||
const start = performance.now()
|
let last = performance.now()
|
||||||
function frame() {
|
|
||||||
|
function frame(now: number) {
|
||||||
if (!running) return
|
if (!running) return
|
||||||
const t = (performance.now() - start) / 1000
|
const dt = Math.min(0.05, (now - last) / 1000) // clamp big gaps (tab wake)
|
||||||
glc.clearColor(0, 0, 0, 0)
|
last = now
|
||||||
glc.clear(glc.COLOR_BUFFER_BIT)
|
const t = now / 1000
|
||||||
glc.uniform1f(uTime, t)
|
ctx.clearRect(0, 0, W, H)
|
||||||
glc.drawArrays(glc.TRIANGLES, 0, PETAL_COUNT * 6)
|
|
||||||
|
for (const p of petals) {
|
||||||
|
p.y += p.vy * dt
|
||||||
|
p.angle += p.spin * dt
|
||||||
|
const x = p.baseX + p.swayAmp * Math.sin(t * p.swayFreq + p.swayPhase)
|
||||||
|
|
||||||
|
// Recycle once fully past the bottom.
|
||||||
|
if (p.y - p.size > H) {
|
||||||
|
Object.assign(p, spawn(false))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stars shimmer gently (shallow pulse so the chunky ones glow rather
|
||||||
|
// than blink); petals hold a steady alpha.
|
||||||
|
const alpha = night
|
||||||
|
? p.alpha * (0.8 + 0.2 * Math.sin(t * p.swayFreq * 2.2 + p.swayPhase))
|
||||||
|
: p.alpha
|
||||||
|
|
||||||
|
ctx.save()
|
||||||
|
ctx.translate(x, p.y)
|
||||||
|
ctx.rotate(p.angle)
|
||||||
|
ctx.globalAlpha = alpha
|
||||||
|
ctx.drawImage(sprites[p.sprite], -p.size / 2, -p.size / 2, p.size, p.size)
|
||||||
|
ctx.restore()
|
||||||
|
}
|
||||||
raf = requestAnimationFrame(frame)
|
raf = requestAnimationFrame(frame)
|
||||||
}
|
}
|
||||||
// Pause when the tab is hidden to save the battery.
|
|
||||||
const onVisibility = () => {
|
const onVisibility = () => {
|
||||||
if (document.hidden) {
|
if (document.hidden) {
|
||||||
running = false
|
running = false
|
||||||
cancelAnimationFrame(raf)
|
cancelAnimationFrame(raf)
|
||||||
} else if (!running) {
|
} else if (!running) {
|
||||||
running = true
|
running = true
|
||||||
|
last = performance.now()
|
||||||
raf = requestAnimationFrame(frame)
|
raf = requestAnimationFrame(frame)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -249,12 +357,9 @@ export function PetalFall() {
|
|||||||
cancelAnimationFrame(raf)
|
cancelAnimationFrame(raf)
|
||||||
window.removeEventListener('resize', resize)
|
window.removeEventListener('resize', resize)
|
||||||
document.removeEventListener('visibilitychange', onVisibility)
|
document.removeEventListener('visibilitychange', onVisibility)
|
||||||
gl.deleteBuffer(buf)
|
petals = []
|
||||||
gl.deleteProgram(prog)
|
|
||||||
gl.deleteShader(vs)
|
|
||||||
gl.deleteShader(fs)
|
|
||||||
}
|
}
|
||||||
}, [])
|
}, [night, enabled])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<canvas
|
<canvas
|
||||||
|
|||||||
36
web/src/effects/petals.ts
Normal file
36
web/src/effects/petals.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
// The on/off preference for the ambient falling-petals layer (PetalFall). Some
|
||||||
|
// people find drifting petals distracting rather than cozy, so the whole effect
|
||||||
|
// is opt-out-able and the choice persists in localStorage so it survives reloads.
|
||||||
|
// Mirrors the tiny pub/sub used for the sound mute toggle (../audio/sounds).
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'petal.petals'
|
||||||
|
|
||||||
|
let enabled = readEnabled()
|
||||||
|
const listeners = new Set<(on: boolean) => void>()
|
||||||
|
|
||||||
|
function readEnabled(): boolean {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(STORAGE_KEY) !== 'off'
|
||||||
|
} catch {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPetalsEnabled(): boolean {
|
||||||
|
return enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setPetalsEnabled(on: boolean): void {
|
||||||
|
enabled = on
|
||||||
|
try {
|
||||||
|
localStorage.setItem(STORAGE_KEY, on ? 'on' : 'off')
|
||||||
|
} catch {
|
||||||
|
/* private mode — choice just won't persist */
|
||||||
|
}
|
||||||
|
listeners.forEach((fn) => fn(on))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onPetalsEnabledChange(fn: (on: boolean) => void): () => void {
|
||||||
|
listeners.add(fn)
|
||||||
|
return () => listeners.delete(fn)
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
import { api, type Suggestion } from '../api/client'
|
import { api, type Suggestion } from '../api/client'
|
||||||
|
import { mechanicsFindings } from '../components/Companion/prose'
|
||||||
|
|
||||||
const DEBOUNCE_MS = 4000
|
const DEBOUNCE_MS = 4000
|
||||||
|
|
||||||
@@ -13,6 +14,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
|
||||||
@@ -20,18 +23,52 @@ export function useCheckpoint(docId: string | null) {
|
|||||||
const [llmDown, setLlmDown] = useState(false)
|
const [llmDown, setLlmDown] = useState(false)
|
||||||
|
|
||||||
const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined)
|
const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined)
|
||||||
|
// Pending auto-retry timer for a failed checkpoint (see runCheck).
|
||||||
|
const retryRef = useRef<ReturnType<typeof setTimeout>>(undefined)
|
||||||
const docIdRef = useRef(docId)
|
const docIdRef = useRef(docId)
|
||||||
docIdRef.current = docId
|
docIdRef.current = docId
|
||||||
|
|
||||||
|
// Latest plaintext, kept fresh by schedule(), so the deterministic mechanics
|
||||||
|
// pass (detected client-side, see prose.ts) reads the current document when the
|
||||||
|
// debounce fires — no need to re-thread text through every call. null until the
|
||||||
|
// first edit of the current doc, so a tone-only check before any edit doesn't
|
||||||
|
// submit an empty batch and wipe the doc's persisted mechanics rows.
|
||||||
|
const latestTextRef = useRef<string | null>(null)
|
||||||
|
|
||||||
// Token to discard responses from a doc we've since navigated away from.
|
// Token to discard responses from a doc we've since navigated away from.
|
||||||
const runRef = useRef(0)
|
const runRef = useRef(0)
|
||||||
|
|
||||||
const runCheck = useCallback(async () => {
|
// Backoff schedule for re-running a checkpoint that failed. A paste fires
|
||||||
|
// exactly ONE checkpoint, and nothing re-fires until the next keystroke — so a
|
||||||
|
// single transient failure (a momentary stall on the shared inference box)
|
||||||
|
// would otherwise strand the user on "resting" indefinitely after a paste.
|
||||||
|
// These delays clear the server's 30s per-doc floor by the later attempts, and
|
||||||
|
// a failed pass now releases its slot server-side so a retry can truly re-run.
|
||||||
|
const RETRY_DELAYS_MS = [3000, 12000, 35000]
|
||||||
|
|
||||||
|
const runCheck = useCallback(async (attempt = 0) => {
|
||||||
const id = docIdRef.current
|
const id = docIdRef.current
|
||||||
if (!id) return
|
if (!id) return
|
||||||
|
clearTimeout(retryRef.current)
|
||||||
const run = ++runRef.current
|
const run = ++runRef.current
|
||||||
setChecking(true)
|
setChecking(true)
|
||||||
|
let retrying = false
|
||||||
try {
|
try {
|
||||||
|
// Deterministic mechanics first: detect client-side and persist as the
|
||||||
|
// 'mechanics' family before the grammar pass, so the checkpoint's unified
|
||||||
|
// response already carries them. Best-effort and only on the initial try —
|
||||||
|
// a grammar retry shouldn't re-submit unchanged findings. A mechanics
|
||||||
|
// failure must not block the grammar pass.
|
||||||
|
if (attempt === 0 && latestTextRef.current !== null) {
|
||||||
|
try {
|
||||||
|
// Render the mechanics fixes immediately — they're instant (no LLM), so
|
||||||
|
// the unified set they return shouldn't wait on the slow grammar pass.
|
||||||
|
const withMech = await api.submitMechanics(id, mechanicsFindings(latestTextRef.current))
|
||||||
|
if (run === runRef.current && id === docIdRef.current) setSuggestions(withMech)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('mechanics submit failed', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
const fresh = await api.checkDoc(id)
|
const fresh = await api.checkDoc(id)
|
||||||
if (run === runRef.current && id === docIdRef.current) {
|
if (run === runRef.current && id === docIdRef.current) {
|
||||||
setSuggestions(fresh)
|
setSuggestions(fresh)
|
||||||
@@ -39,48 +76,90 @@ export function useCheckpoint(docId: string | null) {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('checkpoint failed', err)
|
console.error('checkpoint failed', err)
|
||||||
if (run === runRef.current) setLlmDown(true)
|
if (run !== runRef.current) return
|
||||||
} finally {
|
if (attempt < RETRY_DELAYS_MS.length) {
|
||||||
if (run === runRef.current) setChecking(false)
|
// Keep trying quietly — don't flag "resting" until retries are exhausted.
|
||||||
}
|
retrying = true
|
||||||
}, [])
|
retryRef.current = setTimeout(() => void runCheck(attempt + 1), RETRY_DELAYS_MS[attempt])
|
||||||
|
} else {
|
||||||
// Run the voice-consistency pass now (explicit "Check my voice" action). Like
|
setLlmDown(true)
|
||||||
// runCheck it returns the unified pending set, so grammar highlights survive.
|
|
||||||
// Shares the run token so navigating away discards a late voice response.
|
|
||||||
const runVoice = useCallback(async () => {
|
|
||||||
const id = docIdRef.current
|
|
||||||
if (!id) return
|
|
||||||
const run = ++runRef.current
|
|
||||||
setVoicing(true)
|
|
||||||
try {
|
|
||||||
const full = await api.voiceDoc(id)
|
|
||||||
if (run === runRef.current && id === docIdRef.current) {
|
|
||||||
setSuggestions(full)
|
|
||||||
setLlmDown(false)
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
|
||||||
console.error('voice pass failed', err)
|
|
||||||
if (run === runRef.current) setLlmDown(true)
|
|
||||||
} finally {
|
} finally {
|
||||||
if (run === runRef.current) setVoicing(false)
|
// Stay in the "checking" state while a retry is queued so the breathing dot
|
||||||
|
// keeps reassuring rather than flickering off between attempts.
|
||||||
|
if (run === runRef.current && !retrying) setChecking(false)
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// Call on every edit; schedules a check 4s after typing settles.
|
// runExplicitPass drives a whole-document, explicit-action pass (voice,
|
||||||
const schedule = useCallback(() => {
|
// collocation): it returns the unified pending set, so the other families'
|
||||||
|
// highlights survive, and shares the run token so navigating away discards a
|
||||||
|
// late response. It supersedes any queued grammar retry AND clears the
|
||||||
|
// checkpoint's "checking" state, so the breathing rose dot can't linger on
|
||||||
|
// after the retry timer it would have cleared is cancelled here.
|
||||||
|
const runExplicitPass = useCallback(
|
||||||
|
async (call: (id: string) => Promise<Suggestion[]>, setBusy: (b: boolean) => void, label: string) => {
|
||||||
|
const id = docIdRef.current
|
||||||
|
if (!id) return
|
||||||
|
// An explicit action fully supersedes a queued auto-check and grammar
|
||||||
|
// retry, and takes over the indicator — clear the stranded "checking" dot.
|
||||||
|
clearTimeout(debounceRef.current)
|
||||||
|
clearTimeout(retryRef.current)
|
||||||
|
setChecking(false)
|
||||||
|
const run = ++runRef.current
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
const full = await call(id)
|
||||||
|
if (run === runRef.current && id === docIdRef.current) {
|
||||||
|
setSuggestions(full)
|
||||||
|
setLlmDown(false)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`${label} failed`, err)
|
||||||
|
if (run === runRef.current) setLlmDown(true)
|
||||||
|
} finally {
|
||||||
|
// setBusy is THIS invocation's own flag (a newer run sets its own), so
|
||||||
|
// clear it unconditionally — otherwise an overlapping pass that bumped
|
||||||
|
// the run token would strand this spinner on "Reading…" forever.
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Run the voice-consistency pass now (explicit "Check my voice" action).
|
||||||
|
const runVoice = useCallback(
|
||||||
|
() => runExplicitPass(api.voiceDoc, setVoicing, 'voice pass'),
|
||||||
|
[runExplicitPass],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Run the collocation coach now (explicit "Make it sound natural" action).
|
||||||
|
const runCollocation = useCallback(
|
||||||
|
() => runExplicitPass(api.collocationDoc, setCollocating, 'collocation pass'),
|
||||||
|
[runExplicitPass],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Call on every edit; schedules a check 4s after typing settles. Pass the
|
||||||
|
// current plaintext so the mechanics pass sees the latest document; omit it
|
||||||
|
// (e.g. a tone-only change) to reuse the last text.
|
||||||
|
const schedule = useCallback((text?: string) => {
|
||||||
|
if (text !== undefined) latestTextRef.current = text
|
||||||
clearTimeout(debounceRef.current)
|
clearTimeout(debounceRef.current)
|
||||||
debounceRef.current = setTimeout(runCheck, DEBOUNCE_MS)
|
clearTimeout(retryRef.current) // a fresh edit supersedes any queued retry
|
||||||
|
debounceRef.current = setTimeout(() => void runCheck(), DEBOUNCE_MS)
|
||||||
}, [runCheck])
|
}, [runCheck])
|
||||||
|
|
||||||
// Load existing pending suggestions whenever the document changes, and cancel
|
// Load existing pending suggestions whenever the document changes, and cancel
|
||||||
// any in-flight debounce from the previous doc.
|
// any in-flight debounce from the previous doc.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
clearTimeout(debounceRef.current)
|
clearTimeout(debounceRef.current)
|
||||||
|
clearTimeout(retryRef.current)
|
||||||
runRef.current++
|
runRef.current++
|
||||||
|
latestTextRef.current = null // unknown until the new doc's first edit
|
||||||
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
|
||||||
@@ -97,12 +176,18 @@ export function useCheckpoint(docId: string | null) {
|
|||||||
}
|
}
|
||||||
}, [docId])
|
}, [docId])
|
||||||
|
|
||||||
useEffect(() => () => clearTimeout(debounceRef.current), [])
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
clearTimeout(debounceRef.current)
|
||||||
|
clearTimeout(retryRef.current)
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
// Drop one suggestion locally (after accept/dismiss) without a refetch.
|
// Drop one suggestion locally (after accept/dismiss) without a refetch.
|
||||||
const removeSuggestion = useCallback((id: string) => {
|
const removeSuggestion = useCallback((id: string) => {
|
||||||
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 }
|
||||||
}
|
}
|
||||||
|
|||||||
59
web/src/hooks/useFocusTrap.ts
Normal file
59
web/src/hooks/useFocusTrap.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
|
||||||
|
// useFocusTrap makes a slide-over / modal keyboard-accessible. Attach the
|
||||||
|
// returned ref to the dialog container and, while it's mounted, it:
|
||||||
|
// • moves focus into the panel on open (so Tab/Escape work without a click),
|
||||||
|
// • keeps Tab/Shift+Tab cycling within the panel instead of escaping to the
|
||||||
|
// page behind the backdrop, and
|
||||||
|
// • restores focus to whatever was focused before it opened on unmount.
|
||||||
|
// Escape handling stays with each panel, which has its own close semantics.
|
||||||
|
export function useFocusTrap<T extends HTMLElement>() {
|
||||||
|
const ref = useRef<T>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const node = ref.current
|
||||||
|
if (!node) return
|
||||||
|
|
||||||
|
// Remember where focus was so we can hand it back when the panel closes.
|
||||||
|
const previouslyFocused = document.activeElement as HTMLElement | null
|
||||||
|
|
||||||
|
const focusables = () =>
|
||||||
|
Array.from(
|
||||||
|
node.querySelectorAll<HTMLElement>(
|
||||||
|
'a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])',
|
||||||
|
),
|
||||||
|
).filter((el) => el.offsetParent !== null)
|
||||||
|
|
||||||
|
// Focus the first interactive element, or the container itself as a fallback.
|
||||||
|
const first = focusables()[0]
|
||||||
|
if (first) first.focus()
|
||||||
|
else node.focus()
|
||||||
|
|
||||||
|
const onKeyDown = (e: KeyboardEvent) => {
|
||||||
|
if (e.key !== 'Tab') return
|
||||||
|
const items = focusables()
|
||||||
|
if (items.length === 0) {
|
||||||
|
e.preventDefault()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const firstEl = items[0]
|
||||||
|
const lastEl = items[items.length - 1]
|
||||||
|
const active = document.activeElement
|
||||||
|
if (e.shiftKey && active === firstEl) {
|
||||||
|
e.preventDefault()
|
||||||
|
lastEl.focus()
|
||||||
|
} else if (!e.shiftKey && active === lastEl) {
|
||||||
|
e.preventDefault()
|
||||||
|
firstEl.focus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
node.addEventListener('keydown', onKeyDown)
|
||||||
|
return () => {
|
||||||
|
node.removeEventListener('keydown', onKeyDown)
|
||||||
|
previouslyFocused?.focus?.()
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return ref
|
||||||
|
}
|
||||||
25
web/src/hooks/useNightMode.ts
Normal file
25
web/src/hooks/useNightMode.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { isBedtime } from '../lib/night'
|
||||||
|
|
||||||
|
// Tracks whether it's late enough to shift Petal into its calm night mode (dark
|
||||||
|
// theme + falling stars instead of petals). Re-checks once a minute so the swap
|
||||||
|
// happens on its own as the clock rolls past 11pm — no reload needed. Returns
|
||||||
|
// the boolean and also toggles a `petal-night` class on <html> so the CSS token
|
||||||
|
// overrides cascade to everything (body background, panels, portals included).
|
||||||
|
export function useNightMode(): boolean {
|
||||||
|
const [night, setNight] = useState(() => isBedtime())
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const tick = () => setNight(isBedtime())
|
||||||
|
tick()
|
||||||
|
const id = setInterval(tick, 60_000)
|
||||||
|
return () => clearInterval(id)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
document.documentElement.classList.toggle('petal-night', night)
|
||||||
|
return () => document.documentElement.classList.remove('petal-night')
|
||||||
|
}, [night])
|
||||||
|
|
||||||
|
return night
|
||||||
|
}
|
||||||
@@ -20,6 +20,8 @@
|
|||||||
--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-sage: #B7C7B9; /* mechanics — calm sage, a gentle tidy-up nudge */
|
||||||
--color-success: #8FCFA8; /* saved / accepted */
|
--color-success: #8FCFA8; /* saved / accepted */
|
||||||
|
|
||||||
/* Typography */
|
/* Typography */
|
||||||
@@ -37,6 +39,23 @@
|
|||||||
--shadow-soft: 0 4px 20px rgba(180, 130, 160, 0.12);
|
--shadow-soft: 0 4px 20px rgba(180, 130, 160, 0.12);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Night mode — toggled by adding `petal-night` to <html> (useNightMode) once the
|
||||||
|
clock passes ~11pm. We only re-point the palette tokens; every Tailwind color
|
||||||
|
utility reads them via var(), so the whole UI shifts to a calm, dim, moonlit
|
||||||
|
theme without touching component markup. Pastel accent/type colors are kept —
|
||||||
|
they read beautifully on the dark plum ground. Falling petals become stars. */
|
||||||
|
html.petal-night {
|
||||||
|
--color-bg: #14111E; /* deep night plum-indigo */
|
||||||
|
--color-surface: #211C30; /* raised panels */
|
||||||
|
--color-surface-alt: #2A2440; /* alt surface / hover wash */
|
||||||
|
--color-border: #38304E; /* dim lavender border */
|
||||||
|
--color-plum: #ECE3F2; /* ink → soft moonlit lavender-white */
|
||||||
|
--color-muted: #9F93B8; /* muted lavender-grey, lifted for contrast */
|
||||||
|
--color-accent: #E8A0BF; /* rose still primary — pops on dark */
|
||||||
|
--color-accent-hover: #F2B7D2;/* lighter on hover against the dark */
|
||||||
|
--shadow-soft: 0 6px 28px rgba(0, 0, 0, 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
html, body, #root {
|
html, body, #root {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
@@ -47,6 +66,8 @@ body {
|
|||||||
color: var(--color-plum);
|
color: var(--color-plum);
|
||||||
font-family: var(--font-ui);
|
font-family: var(--font-ui);
|
||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
|
/* Gentle dusk/dawn fade when night mode flips. */
|
||||||
|
transition: background 600ms ease, color 600ms ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Gentle, consistent motion across interactive elements */
|
/* Gentle, consistent motion across interactive elements */
|
||||||
@@ -98,6 +119,93 @@ button, a, input {
|
|||||||
padding: 0.1em 0.35em;
|
padding: 0.1em 0.35em;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
}
|
}
|
||||||
|
/* Top formatting bar: a single line at rest so it stays slim, expanding to
|
||||||
|
reveal every control on hover (or while a control inside it has focus, e.g.
|
||||||
|
the link input or an open popover). The clipped right edge fades out as a hint
|
||||||
|
that more is available. */
|
||||||
|
.petal-toolbar {
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
max-width: 100%;
|
||||||
|
-webkit-mask-image: linear-gradient(to right, #000 90%, transparent 100%);
|
||||||
|
mask-image: linear-gradient(to right, #000 90%, transparent 100%);
|
||||||
|
}
|
||||||
|
.petal-toolbar:hover,
|
||||||
|
.petal-toolbar:focus-within {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
overflow: visible;
|
||||||
|
-webkit-mask-image: none;
|
||||||
|
mask-image: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Highlighter mark — inline background swatch behind the text. */
|
||||||
|
.petal-prose mark {
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 0.05em 0.15em;
|
||||||
|
/* color comes from the inline style the Highlight extension writes */
|
||||||
|
}
|
||||||
|
/* Inserted images: rounded, soft-shadowed, never wider than the column. The
|
||||||
|
selected-node ring matches the rest of the rose theme. Scoped to the editor's
|
||||||
|
own <img> (not a class) since Tiptap doesn't always carry the configured
|
||||||
|
class through to the rendered node. */
|
||||||
|
.petal-prose img {
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
border-radius: var(--radius-card);
|
||||||
|
box-shadow: var(--shadow-soft);
|
||||||
|
}
|
||||||
|
.petal-prose img.ProseMirror-selectednode {
|
||||||
|
outline: 2px solid var(--color-accent);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
/* Tables: soft pink grid, rounded outer corners, a tinted header row. Targeted
|
||||||
|
by element within the editor — Tiptap renders the <table> without our
|
||||||
|
configured class, so a `.petal-table` selector would never match. The wrapper
|
||||||
|
Tiptap adds (.tableWrapper) handles horizontal overflow scroll. */
|
||||||
|
.petal-prose .tableWrapper {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
.petal-prose table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
margin: 0.4em 0;
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: var(--radius-input);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
table-layout: fixed;
|
||||||
|
}
|
||||||
|
.petal-prose td,
|
||||||
|
.petal-prose th {
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
padding: 0.4em 0.6em;
|
||||||
|
vertical-align: top;
|
||||||
|
position: relative;
|
||||||
|
min-width: 3em;
|
||||||
|
}
|
||||||
|
.petal-prose th {
|
||||||
|
background: var(--color-surface-alt);
|
||||||
|
font-weight: 700;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
/* The cell being edited / the active selection inside a table. */
|
||||||
|
.petal-prose .selectedCell::after {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
background: var(--color-surface-alt);
|
||||||
|
opacity: 0.5;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
/* The column-resize handle Tiptap draws between columns. */
|
||||||
|
.petal-prose .column-resize-handle {
|
||||||
|
position: absolute;
|
||||||
|
right: -2px;
|
||||||
|
top: 0;
|
||||||
|
bottom: -2px;
|
||||||
|
width: 4px;
|
||||||
|
background: var(--color-accent);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
/* Placeholder shown on the empty first paragraph (Tiptap Placeholder ext). */
|
/* Placeholder shown on the empty first paragraph (Tiptap Placeholder ext). */
|
||||||
.petal-prose p.is-editor-empty:first-child::before {
|
.petal-prose p.is-editor-empty:first-child::before {
|
||||||
content: attr(data-placeholder);
|
content: attr(data-placeholder);
|
||||||
@@ -126,6 +234,8 @@ 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); }
|
||||||
|
.petal-suggestion-mechanics { border-bottom-color: var(--color-sage); }
|
||||||
|
|
||||||
@keyframes petal-suggestion-in {
|
@keyframes petal-suggestion-in {
|
||||||
from { opacity: 0; transform: translateY(4px); }
|
from { opacity: 0; transform: translateY(4px); }
|
||||||
@@ -136,6 +246,81 @@ button, a, input {
|
|||||||
animation: petal-suggestion-in 200ms ease both;
|
animation: petal-suggestion-in 200ms ease both;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Text emphasized from its margin card (or a hover) — a soft wash so the
|
||||||
|
card↔text link reads at a glance, both directions. */
|
||||||
|
.petal-suggestion-active {
|
||||||
|
background: var(--color-surface-alt);
|
||||||
|
box-shadow: 0 0 0 3px var(--color-surface-alt);
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- Suggestion margin rail -------------------------------------------------
|
||||||
|
The right-hand "comment column": every outstanding suggestion as a card,
|
||||||
|
vertically aligned to the text it flags, so the whole queue is visible at a
|
||||||
|
glance instead of one-highlight-at-a-time on hover. It floats in the whitespace
|
||||||
|
just right of the editor column and is only mounted when there's room for it
|
||||||
|
(EditorCore measures the gap). Cards are absolutely positioned by a resolved
|
||||||
|
top (anchor + collision avoidance), so the container only anchors the column. */
|
||||||
|
.petal-rail {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 100%;
|
||||||
|
margin-left: 32px;
|
||||||
|
width: 300px;
|
||||||
|
/* Below the companion mascot (z-40): where a stacked card reaches the
|
||||||
|
bottom-right corner it simply tucks behind the sleeping cat. */
|
||||||
|
z-index: 10;
|
||||||
|
}
|
||||||
|
.petal-rail-card {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-left: 3px solid var(--color-border); /* type color set inline */
|
||||||
|
border-radius: var(--radius-card);
|
||||||
|
box-shadow: var(--shadow-soft);
|
||||||
|
padding: 0.7rem 0.85rem;
|
||||||
|
/* `top` eases so re-stacking (accept/dismiss/edit) glides instead of jumping.
|
||||||
|
The entrance uses fill `backwards` so its translateY doesn't linger and fight
|
||||||
|
the active-state transform once it's done. */
|
||||||
|
transition: top 240ms cubic-bezier(0.2, 0.7, 0.3, 1), box-shadow 200ms ease,
|
||||||
|
transform 200ms ease, border-color 200ms ease;
|
||||||
|
animation: petal-suggestion-in 220ms ease backwards;
|
||||||
|
}
|
||||||
|
.petal-rail-card-active {
|
||||||
|
transform: translateX(-5px);
|
||||||
|
box-shadow: 0 8px 26px rgba(180, 130, 160, 0.24);
|
||||||
|
border-top-color: var(--color-accent);
|
||||||
|
border-right-color: var(--color-accent);
|
||||||
|
border-bottom-color: var(--color-accent);
|
||||||
|
}
|
||||||
|
.petal-rail-x {
|
||||||
|
color: var(--color-muted);
|
||||||
|
font-size: 0.72rem;
|
||||||
|
line-height: 1;
|
||||||
|
padding: 2px 5px;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
}
|
||||||
|
.petal-rail-x:hover {
|
||||||
|
background: var(--color-surface-alt);
|
||||||
|
color: var(--color-plum);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- Find & Replace ---------------------------------------------------------
|
||||||
|
In-document search (Ctrl/Cmd+F). Every match gets a soft honey wash; the
|
||||||
|
current match is brighter with a rose ring so it stands out as you step
|
||||||
|
through. Decorations, like every other highlight layer here. */
|
||||||
|
.petal-find-match {
|
||||||
|
background: var(--color-highlight, #fff1a8);
|
||||||
|
border-radius: 3px;
|
||||||
|
box-shadow: 0 0 0 1px var(--color-border);
|
||||||
|
}
|
||||||
|
.petal-find-match-active {
|
||||||
|
background: var(--color-peach);
|
||||||
|
box-shadow: 0 0 0 2px var(--color-accent);
|
||||||
|
}
|
||||||
|
|
||||||
/* --- Spell check ------------------------------------------------------------
|
/* --- Spell check ------------------------------------------------------------
|
||||||
Browser-side nspell flags misspellings with a soft rose wavy underline (a
|
Browser-side nspell flags misspellings with a soft rose wavy underline (a
|
||||||
gentler take on the classic red squiggle, to fit the pastel palette). Like the
|
gentler take on the classic red squiggle, to fit the pastel palette). Like the
|
||||||
@@ -218,9 +403,17 @@ button, a, input {
|
|||||||
The cozy corner mascot. Gently bobs while awake, settles and sways slowly
|
The cozy corner mascot. Gently bobs while awake, settles and sways slowly
|
||||||
while napping; its speech bubble pops in; little zzz drift up when asleep. */
|
while napping; its speech bubble pops in; little zzz drift up when asleep. */
|
||||||
.petal-companion {
|
.petal-companion {
|
||||||
|
/* Mascot size scales with the viewport width: ~original on a laptop, up to
|
||||||
|
~2× on a large desktop. Tune the middle (vw) term to taste. */
|
||||||
|
--petal-companion-size: clamp(10rem, 17vw, 20rem);
|
||||||
animation: petal-bob 3.2s ease-in-out infinite;
|
animation: petal-bob 3.2s ease-in-out infinite;
|
||||||
transition: transform 200ms ease;
|
transition: transform 200ms ease;
|
||||||
}
|
}
|
||||||
|
/* The Lottie art sits inside the round badge with a little breathing room. */
|
||||||
|
.petal-companion-art {
|
||||||
|
width: 88%;
|
||||||
|
height: 88%;
|
||||||
|
}
|
||||||
.petal-companion:hover {
|
.petal-companion:hover {
|
||||||
transform: translateY(-2px) scale(1.04);
|
transform: translateY(-2px) scale(1.04);
|
||||||
}
|
}
|
||||||
@@ -246,10 +439,10 @@ button, a, input {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.petal-zzz {
|
.petal-zzz {
|
||||||
top: 6px;
|
top: calc(var(--petal-companion-size) * 0.04);
|
||||||
right: 14px;
|
right: calc(var(--petal-companion-size) * 0.1);
|
||||||
font-weight: 800;
|
font-weight: 800;
|
||||||
font-size: 1.1rem;
|
font-size: calc(var(--petal-companion-size) * 0.12);
|
||||||
animation: petal-zzz 2.4s ease-in-out infinite;
|
animation: petal-zzz 2.4s ease-in-out infinite;
|
||||||
}
|
}
|
||||||
@keyframes petal-zzz {
|
@keyframes petal-zzz {
|
||||||
@@ -388,7 +581,7 @@ button, a, input {
|
|||||||
the writing. It hides itself in print and is skipped entirely for users who
|
the writing. It hides itself in print and is skipped entirely for users who
|
||||||
prefer reduced motion (the component renders nothing in that case). */
|
prefer reduced motion (the component renders nothing in that case). */
|
||||||
.petal-fall {
|
.petal-fall {
|
||||||
opacity: 0.85;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Honor reduced-motion globally: still the looping ambient animations and drop
|
/* Honor reduced-motion globally: still the looping ambient animations and drop
|
||||||
|
|||||||
11
web/src/lib/night.ts
Normal file
11
web/src/lib/night.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// Shared "is it late?" definition, used by both the companion's bedtime nag and
|
||||||
|
// the night-mode theme/starfall switch so they always agree. Local clock — the
|
||||||
|
// writer's own machine (millenia's timezone in deployment).
|
||||||
|
|
||||||
|
export const BEDTIME_FROM = 23 // local hour the night window opens (11pm)…
|
||||||
|
export const BEDTIME_TO = 4 // …and closes (4am); past this we assume an early start
|
||||||
|
|
||||||
|
export function isBedtime(d: Date = new Date()): boolean {
|
||||||
|
const h = d.getHours()
|
||||||
|
return h >= BEDTIME_FROM || h < BEDTIME_TO
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user