diff --git a/README.md b/README.md index 5aae887..5b03492 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ and progress. - **Book map:** a strip along the right edge marking chapters, notes and bookmarks; hover to preview. - **Chapter progress:** a hairline under the toolbar that fills as you read. - **Bookmarks:** click the ribbon on a page or press B. +- **Define:** select a word and press D for its dictionary entry, from Wiktionary. - **Long books:** pages render as you reach them, so 1,000-page textbooks stay quick. - **Backups:** export everything to one file and restore it anywhere. - **Offline:** once installed, your library opens without a connection. @@ -88,6 +89,7 @@ Press ? in the app for the full list. | Ctrl+F or / | Find in the book; F3 / Shift+F3 step through matches | | N | New margin note on the current page, quoting any selected text | | H | Highlight the selected text in the colour used last | +| D | Look up the selected word in the dictionary | | B | Bookmark the current page | | Shift+R | Open or close the notes review | | F | Focus mode (Esc also leaves) | @@ -155,6 +157,7 @@ src/ palette/ Go to: pages, chapters, bookmarks, notes and actions in one box bookmap/ The book map along the reader's right edge focus/ Focus mode and the reading ruler + define/ Dictionary lookups (Wiktionary) notes/ Margin notes (bold/italic editing), collated review, Markdown export search/ Full-text index and in-page highlights settings/ Library & storage: linked folder, backups, persistent storage diff --git a/docs/DATA.md b/docs/DATA.md index 7dff275..c4e1507 100644 --- a/docs/DATA.md +++ b/docs/DATA.md @@ -171,5 +171,7 @@ OneDrive could work the same way (a Microsoft Entra app with Microsoft Graph); i Nothing leaves the reader's devices except through services they choose (their own cloud folder, a Google Drive folder they link, or backup files). Scriptorium has no analytics and makes -no network requests of its own beyond loading the app. With a Google Drive folder linked, the -browser talks to Google directly; nothing passes through any other server. +no network requests of its own beyond loading the app and dictionary lookups: when the reader asks +to define a word, that word (and nothing else) is sent to [Wiktionary](https://en.wiktionary.org). +With a Google Drive folder linked, the browser talks to Google directly; nothing passes through +any other server. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b507bee..cb3e021 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -128,6 +128,7 @@ Ctrl/Cmd+F for in-book search). Press `?` in the reader to see them all. | --- | --- | | `B` | Toggle bookmark on the current page | | `N` | Create a margin note at the middle of the visible part of the current page (quoting selected text, if any) | +| `D` | Look up the selected word or short phrase in the dictionary (Wiktionary) | | `G` | Go to: a page (printed labels work; `#N` for a PDF page number), chapter, bookmark, note or action | | `F` | Focus mode (`Esc` also leaves) | | `R` | Reading ruler | @@ -168,6 +169,7 @@ builds on the dependable local reading and note-taking loop. - ✅ **Chapter progress:** show progress within outline sections as well as across the book (pages and percentages — no time estimates). - **Reading insights:** offer optional reading statistics. - ✅ **Focus mode:** reduce interface chrome while preserving essential navigation; with an optional reading ruler. +- **Define:** ✅ select a word and press D for its dictionary entry from Wiktionary (online). Still to come: an optional offline dictionary download. - **Rich notes:** ✅ bold and italic (Ctrl+B / Ctrl+I); Markdown and LaTeX if readers need more. - **Flashcards:** create spaced-repetition cards from notes for a later review session ([#6](https://github.com/Kevin-Taha/Scriptorium/issues/6)). - **Read aloud:** listen with a high-quality, local voice while the current sentence is highlighted ([#7](https://github.com/Kevin-Taha/Scriptorium/issues/7)). diff --git a/e2e/define.spec.ts b/e2e/define.spec.ts new file mode 100644 index 0000000..e528908 --- /dev/null +++ b/e2e/define.spec.ts @@ -0,0 +1,69 @@ +import { expect, type Page, test } from '@playwright/test'; +import { goToPage, importFixture } from './support/reader'; + +/** Selects `word` (by default, all of it) in the text-layer span on page 3 that contains `phrase`. */ +async function select(page: Page, phrase: string, word?: string): Promise { + const span = page.locator('.page-sheet[data-page="3"] .textLayer span', { hasText: phrase }).first(); + await expect(span).toBeAttached(); + await span.evaluate((element, target) => { + const node = [...element.childNodes].find((child) => child.textContent?.includes(target ?? ''))!; + const start = target ? node.textContent!.indexOf(target) : 0; + const range = document.createRange(); + range.setStart(node, start); + range.setEnd(node, target ? start + target.length : node.textContent!.length); + const selection = window.getSelection()!; + selection.removeAllRanges(); + selection.addRange(range); + }, word); +} + +const HEADING = '1.1 Position and Displacement'; +const card = (page: Page, word: string) => page.getByRole('dialog', { name: `Definition of ${word}` }); + +test.beforeEach(async ({ page }) => { + // Wiktionary, stood in for: the page's policy must still allow the request for it to arrive here. + await page.route('https://en.wiktionary.org/api/rest_v1/page/definition/**', (route) => { + const word = decodeURIComponent(new URL(route.request().url()).pathname.split('/').pop()!); + if (word !== 'displacement') return route.fulfill({ status: 404, body: '' }); + return route.fulfill({ + json: { + en: [ + { + partOfSpeech: 'Noun', + language: 'English', + definitions: [{ definition: 'The act of displacing.' }], + }, + ], + }, + }); + }); + await importFixture(page); + await goToPage(page, 3); +}); + +test('Define looks up the selected word, from the toolbar or with D', async ({ page }) => { + await select(page, HEADING, 'Displacement'); + const toolbar = page.getByRole('toolbar', { name: 'Selection actions' }); + await toolbar.getByRole('button', { name: 'Define' }).click(); + await expect(card(page, 'Displacement')).toContainText('The act of displacing.'); + await expect(card(page, 'Displacement').getByRole('link', { name: 'Wiktionary' })).toHaveAttribute( + 'href', + 'https://en.wiktionary.org/wiki/displacement#English', + ); + await expect(toolbar).toHaveCount(0); + await page.keyboard.press('Escape'); + await expect(card(page, 'Displacement')).toHaveCount(0); + + await select(page, HEADING, 'Position'); + await page.keyboard.press('d'); + await expect(card(page, 'Position')).toContainText('No dictionary entry found.'); +}); + +test('Define is offered only for a word or short phrase', async ({ page }) => { + const toolbar = page.getByRole('toolbar', { name: 'Selection actions' }); + await select(page, 'useful quantity'); + await expect(toolbar.getByRole('button', { name: 'Add margin note' })).toBeVisible(); + await expect(toolbar.getByRole('button', { name: 'Define' })).toHaveCount(0); + await page.keyboard.press('d'); + await expect(page.getByRole('dialog', { name: /^Definition of/ })).toHaveCount(0); +}); diff --git a/src/features/commands/commands.ts b/src/features/commands/commands.ts index 82c0bd7..e76741c 100644 --- a/src/features/commands/commands.ts +++ b/src/features/commands/commands.ts @@ -106,6 +106,13 @@ export const COMMANDS = { 'zoom-out': { label: 'Zoom out', group: 'Read', scope: 'reader', keys: [{ key: '-' }] }, 'fit-width': { label: 'Fit page width', group: 'Read', scope: 'reader', keys: [{ key: '0' }] }, sidebar: { label: 'Show or hide the sidebar', group: 'Read', scope: 'reader', keys: [{ key: '[' }] }, + define: { + label: 'Look up the selected word', + detail: 'In the dictionary (Wiktionary)', + group: 'Read', + scope: 'reader', + keys: [{ key: 'd' }], + }, bookmark: { label: 'Bookmark the page', group: 'Annotate', scope: 'reader', keys: [{ key: 'b' }] }, note: { diff --git a/src/features/define/DefineCard.tsx b/src/features/define/DefineCard.tsx new file mode 100644 index 0000000..cf7df30 --- /dev/null +++ b/src/features/define/DefineCard.tsx @@ -0,0 +1,161 @@ +import { useEffect, useLayoutEffect, useRef } from 'react'; +import { createPortal } from 'react-dom'; +import { ExternalLink } from 'lucide-react'; +import { isEditableTarget } from '@/lib/util'; +import { matches } from '../commands/keys'; +import { placePeek, type Box, type PeekSide } from '../reader/linkPeekGeometry'; +import { closeDefinition, type Lookup, lookUp, lookUpSelection, useDefineStore } from './defineStore'; +import './define.css'; + +/** Keeps the card this far inside the document area. */ +const BOUNDS_INSET = 8; + +/** + * A dictionary card for the selected word: select a word or short phrase and press `D` + * (or Define in the selection toolbar). Mount once in the reader. + */ +export function DefineCard() { + useDefineShortcut(); + const term = useDefineStore((s) => s.term); + const anchor = useDefineStore((s) => s.anchor); + const lookup = useDefineStore((s) => s.lookup); + if (!term || !anchor) return null; + return createPortal(, document.body); +} + +/** `D` looks up the selected text. It does nothing (and swallows nothing) without a selection, or while typing. */ +function useDefineShortcut(): void { + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (event.defaultPrevented || event.repeat || !matches(event, 'define')) return; + if (isEditableTarget(event.target) || document.querySelector('dialog:modal')) return; + if (lookUpSelection()) event.preventDefault(); + }; + window.addEventListener('keydown', onKeyDown); + return () => window.removeEventListener('keydown', onKeyDown); + }, []); +} + +function Card({ term, anchor, lookup }: { term: string; anchor: Box; lookup: Lookup }) { + const cardRef = useRef(null); + const sideRef = useRef('below'); + + // Take focus so the card's links are next in the tab order; Esc hands it back. + useEffect(() => { + const card = cardRef.current; + const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; + card?.focus({ preventScroll: true }); + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return; + // Esc closes only the card, not focus mode or the Return pill too. + event.preventDefault(); + const hadFocus = !!card?.contains(document.activeElement); + closeDefinition(); + if (hadFocus) previous?.focus({ preventScroll: true }); + }; + const onPointerDown = (event: PointerEvent) => { + if (!card?.contains(event.target as Node)) closeDefinition(); + }; + const onScroll = (event: Event) => { + if (!card?.contains(event.target as Node)) closeDefinition(); + }; + document.addEventListener('keydown', onKeyDown, true); + document.addEventListener('pointerdown', onPointerDown, true); + document.addEventListener('scroll', onScroll, { capture: true, passive: true }); + window.addEventListener('resize', closeDefinition); + return () => { + document.removeEventListener('keydown', onKeyDown, true); + document.removeEventListener('pointerdown', onPointerDown, true); + document.removeEventListener('scroll', onScroll, true); + window.removeEventListener('resize', closeDefinition); + }; + }, []); + + // Following "plural of vector" removes the focused button; keep focus in the card. + useEffect(() => { + const card = cardRef.current; + if (term && card && !card.contains(document.activeElement)) card.focus({ preventScroll: true }); + }, [term]); + + // Beside the selection, against the card's current size (it grows when the entry arrives). + useLayoutEffect(() => { + const card = cardRef.current; + if (!card) return; + const viewport = document.querySelector('.reader__viewport')?.getBoundingClientRect(); + const placement = placePeek( + anchor, + { width: card.offsetWidth, height: card.offsetHeight }, + { + top: Math.max(viewport?.top ?? 0, 0) + BOUNDS_INSET, + left: Math.max(viewport?.left ?? 0, 0) + BOUNDS_INSET, + bottom: Math.min(viewport?.bottom ?? Infinity, window.innerHeight) - BOUNDS_INSET, + right: Math.min(viewport?.right ?? Infinity, window.innerWidth) - BOUNDS_INSET, + }, + { prefer: sideRef.current }, + ); + sideRef.current = placement.side; + card.style.top = `${placement.top}px`; + card.style.left = `${placement.left}px`; + card.dataset.side = placement.side; + }); + + const entry = lookup.status === 'found' ? lookup.entry : null; + + return ( +
+

{term}

+
+ {lookup.status === 'loading' &&

Looking up…

} + {lookup.status === 'not-found' &&

No dictionary entry found.

} + {lookup.status === 'unavailable' && ( +

Couldn’t reach the dictionary. Check your connection.

+ )} + {entry?.language &&

No English entry. In {entry.language}:

} + {entry?.parts.map((part, index) => ( + // Wiktionary repeats a part of speech for each etymology, so position is the identity. + // biome-ignore lint/suspicious/noArrayIndexKey: the list is replaced whole, never reordered +
+ {part.partOfSpeech &&

{part.partOfSpeech}

} +
    + {part.senses.map((sense, senseIndex) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: as above +
  1. + {sense.formOf ? : sense.text} +
  2. + ))} +
+
+ ))} +
+ {entry && ( + + Wiktionary + + )} +
+ ); +} + +/** "plural of vector", with the base word as a button that looks it up in this card. */ +function FormOf({ text, word }: { text: string; word: string }) { + const at = text.lastIndexOf(word); + if (at === -1) return <>{text}; + return ( + <> + {text.slice(0, at)} + + {text.slice(at + word.length)} + + ); +} diff --git a/src/features/define/define.css b/src/features/define/define.css new file mode 100644 index 0000000..9c50953 --- /dev/null +++ b/src/features/define/define.css @@ -0,0 +1,112 @@ +/* Define: a dictionary card beside the selected word. */ + +.define-card { + position: fixed; + z-index: var(--z-popover); + display: flex; + flex-direction: column; + gap: var(--space-2); + width: min(360px, calc(100vw - 2 * var(--space-4))); + max-height: min(420px, calc(100vh - 2 * var(--space-6))); + padding: var(--space-3) var(--space-4); + overflow-y: auto; + color: var(--color-text); + background: var(--color-surface-raised); + border: 1px solid var(--color-border-subtle); + border-radius: var(--radius-md); + box-shadow: var(--shadow-lg); + transform-origin: top left; + animation: define-card-in var(--duration-fast) var(--ease-out); +} + +.define-card[data-side='above'] { + --define-card-shift: 4px; + transform-origin: bottom left; +} + +/* The card takes focus only to hand it to its links, which show their own rings. */ +.define-card:focus { + outline: none; +} + +@keyframes define-card-in { + from { + opacity: 0; + transform: translateY(var(--define-card-shift, -4px)) scale(0.97); + } +} + +.define-card__term { + font-family: var(--font-serif); + font-size: var(--font-size-lg); + font-weight: var(--font-weight-semibold); + line-height: var(--leading-tight); + overflow-wrap: break-word; +} + +.define-card__body { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.define-card__status { + font-size: var(--font-size-sm); + line-height: var(--leading-snug); + color: var(--color-text-secondary); +} + +.define-card__pos { + margin-bottom: var(--space-1); + font-size: var(--font-size-sm); + font-style: italic; + font-weight: var(--font-weight-regular); + color: var(--color-text-secondary); +} + +.define-card__senses { + display: flex; + flex-direction: column; + gap: var(--space-1); + padding-left: 1.25em; + font-family: var(--font-serif); + font-size: var(--font-size-md); + line-height: var(--leading-normal); + list-style: decimal; +} + +.define-card__senses li::marker { + font-size: var(--font-size-sm); + color: var(--color-text-muted); +} + +.define-card__word { + font: inherit; + color: var(--color-accent); + text-decoration: underline; + text-underline-offset: 2px; +} + +.define-card__word:hover { + color: var(--color-accent-hover); +} + +.define-card__source { + display: inline-flex; + align-self: flex-end; + align-items: center; + gap: var(--space-1); + font-size: var(--font-size-xs); + color: var(--color-text-muted); + text-decoration: none; +} + +.define-card__source:hover { + color: var(--color-text); + text-decoration: underline; +} + +.define-card__source .lucide { + width: 12px; + height: 12px; +} diff --git a/src/features/define/defineStore.ts b/src/features/define/defineStore.ts new file mode 100644 index 0000000..ceb797c --- /dev/null +++ b/src/features/define/defineStore.ts @@ -0,0 +1,64 @@ +import { create } from 'zustand'; +import { readPageSelection } from '../notes/selectionNote'; +import type { Box } from '../reader/linkPeekGeometry'; +import { useReaderStore } from '../reader/readerStore'; +import { type DictionaryEntry, LookupUnavailableError, lookUpWord, termFromSelection } from './dictionary'; + +export type Lookup = + | { status: 'loading' } + | { status: 'found'; entry: DictionaryEntry } + | { status: 'not-found' } + | { status: 'unavailable' }; + +export interface DefineState { + /** The word being looked up; null when no lookup is showing. */ + term: string | null; + /** Viewport rectangle of the selected text, for placing the card. */ + anchor: Box | null; + lookup: Lookup; +} + +const IDLE: DefineState = { term: null, anchor: null, lookup: { status: 'loading' } }; + +export const useDefineStore = create()(() => IDLE); + +let pending: AbortController | null = null; + +/** Looks up the selected text if it is a word or short phrase. False, doing nothing, otherwise. */ +export function lookUpSelection(): boolean { + const selection = readPageSelection(); + const term = selection && termFromSelection(selection.text); + if (!selection || !term) return false; + const { top, left, bottom, right } = selection.endRect; + lookUp(term, { top, left, bottom, right }); + return true; +} + +/** Shows the dictionary entry for `term` beside `anchor` (by default, where the card already is). */ +export function lookUp(term: string, anchor: Box | null = useDefineStore.getState().anchor): void { + pending?.abort(); + const abort = new AbortController(); + pending = abort; + useDefineStore.setState({ term, anchor, lookup: { status: 'loading' } }); + lookUpWord(term, abort.signal).then( + (entry) => { + if (pending !== abort) return; + useDefineStore.setState({ lookup: entry ? { status: 'found', entry } : { status: 'not-found' } }); + }, + (error: unknown) => { + if (pending !== abort) return; + if (!(error instanceof LookupUnavailableError)) console.error(error); + useDefineStore.setState({ lookup: { status: 'unavailable' } }); + }, + ); +} + +export function closeDefinition(): void { + pending?.abort(); + pending = null; + useDefineStore.setState(IDLE); +} + +useReaderStore.subscribe((state, previous) => { + if (state.docId !== previous.docId) closeDefinition(); +}); diff --git a/src/features/define/dictionary.test.ts b/src/features/define/dictionary.test.ts new file mode 100644 index 0000000..ef994fd --- /dev/null +++ b/src/features/define/dictionary.test.ts @@ -0,0 +1,112 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + clearDictionaryCache, + LookupUnavailableError, + lookUpWord, + parseEntry, + termFromSelection, +} from './dictionary'; + +const link = (word: string) => `${word}`; + +const IMPULSE = { + en: [ + { + partOfSpeech: 'Noun', + language: 'English', + definitions: [ + { definition: `A ${link('thrust')}; a ${link('push')}.` }, + { definition: ' ' }, + { definition: `The ${link('integral')} of force over time.` }, + ], + }, + { partOfSpeech: 'Verb', language: 'English', definitions: [{ definition: `To ${link('impel')}.` }] }, + ], + fr: [{ partOfSpeech: 'Noun', language: 'French', definitions: [{ definition: 'impulsion' }] }], +}; + +describe('termFromSelection', () => { + it('trims punctuation around a word or short phrase', () => { + expect(termFromSelection(' “impulse,” ')).toBe('impulse'); + expect(termFromSelection('(null space)')).toBe('null space'); + }); + + it('rejects passages, numbers and single characters', () => { + expect(termFromSelection('one two three four five')).toBeNull(); + expect(termFromSelection('2.3')).toBeNull(); + expect(termFromSelection('x')).toBeNull(); + }); +}); + +describe('parseEntry', () => { + it('keeps English senses as plain text, by part of speech, with a link to the entry', () => { + expect(parseEntry('impulse', IMPULSE)).toEqual({ + word: 'impulse', + parts: [ + { + partOfSpeech: 'Noun', + senses: [{ text: 'A thrust; a push.' }, { text: 'The integral of force over time.' }], + }, + { partOfSpeech: 'Verb', senses: [{ text: 'To impel.' }] }, + ], + url: 'https://en.wiktionary.org/wiki/impulse#English', + }); + }); + + it('notes the word a form refers to', () => { + const plural = `plural of ${link('vector')}`; + const entry = parseEntry('vectors', { + en: [{ partOfSpeech: 'Noun', definitions: [{ definition: plural }] }], + }); + expect(entry?.parts[0].senses).toEqual([{ text: 'plural of vector', formOf: 'vector' }]); + }); + + it('falls back to another language, and to nothing', () => { + expect(parseEntry('impulsion', { fr: IMPULSE.fr })).toMatchObject({ + language: 'French', + url: 'https://en.wiktionary.org/wiki/impulsion#French', + }); + expect( + parseEntry('nothing', { en: [{ partOfSpeech: 'Noun', definitions: [{ definition: ' ' }] }] }), + ).toBeNull(); + }); +}); + +describe('lookUpWord', () => { + const fetchMock = vi.fn(); + const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200 }); + + beforeEach(() => { + clearDictionaryCache(); + fetchMock.mockReset(); + vi.stubGlobal('fetch', fetchMock); + }); + afterEach(() => vi.unstubAllGlobals()); + + it('asks Wiktionary once per word', async () => { + fetchMock.mockResolvedValue(json(IMPULSE)); + expect((await lookUpWord('impulse'))?.parts).toHaveLength(2); + await lookUpWord('impulse'); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toBe( + 'https://en.wiktionary.org/api/rest_v1/page/definition/impulse?redirect=true', + ); + }); + + it('tries lower case when a capitalised word has no English entry', async () => { + fetchMock.mockImplementation(async (url) => + String(url).includes('/Impulse') ? new Response('', { status: 404 }) : json(IMPULSE), + ); + expect((await lookUpWord('Impulse'))?.word).toBe('impulse'); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('returns null for an unknown word and throws when Wiktionary is unreachable', async () => { + fetchMock.mockResolvedValueOnce(new Response('', { status: 404 })); + expect(await lookUpWord('qwzx')).toBeNull(); + fetchMock.mockRejectedValueOnce(new TypeError('Failed to fetch')); + await expect(lookUpWord('offline')).rejects.toBeInstanceOf(LookupUnavailableError); + fetchMock.mockResolvedValueOnce(new Response('', { status: 503 })); + await expect(lookUpWord('busy')).rejects.toBeInstanceOf(LookupUnavailableError); + }); +}); diff --git a/src/features/define/dictionary.ts b/src/features/define/dictionary.ts new file mode 100644 index 0000000..e46110a --- /dev/null +++ b/src/features/define/dictionary.ts @@ -0,0 +1,134 @@ +/** + * Dictionary lookups from Wiktionary (Wikimedia's REST API). The selected word is the only thing + * sent; results are kept in memory so looking a word up again doesn't ask twice. + */ + +const API = 'https://en.wiktionary.org/api/rest_v1/page/definition/'; +const PAGE = 'https://en.wiktionary.org/wiki/'; +/** Longest selection treated as a word or phrase to look up, in words and characters. */ +const MAX_WORDS = 4; +const MAX_LENGTH = 50; +/** Parts of speech and senses shown per part of speech: a glance, not the whole entry. */ +const MAX_PARTS = 3; +const MAX_SENSES = 3; +const CACHE_SIZE = 50; + +export interface Sense { + text: string; + /** For "plural of vector" and the like: the word it is a form of. */ + formOf?: string; +} + +export interface PartOfSpeech { + partOfSpeech: string; + senses: Sense[]; +} + +export interface DictionaryEntry { + word: string; + /** Set when the entries are for another language (no English entry exists). */ + language?: string; + parts: PartOfSpeech[]; + /** The full entry on Wiktionary. */ + url: string; +} + +/** Thrown when Wiktionary can't be reached (offline, blocked); `null` results mean "no entry". */ +export class LookupUnavailableError extends Error {} + +const EDGE_PUNCTUATION = /^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu; + +/** The word or short phrase to look up for selected text, or null when the selection is a passage. */ +export function termFromSelection(raw: string): string | null { + const text = raw.replace(/\s+/g, ' ').trim().replace(EDGE_PUNCTUATION, ''); + if (text.length < 2 || text.length > MAX_LENGTH || !/\p{L}/u.test(text)) return null; + return text.split(' ').length > MAX_WORDS ? null : text; +} + +interface RawDefinition { + definition?: string; +} +interface RawUsage { + partOfSpeech?: string; + language?: string; + definitions?: RawDefinition[]; +} +type RawResponse = Record; + +/** Plain text of a definition's HTML, and the base word when it is a "form of" another. */ +function readSense(html: string): Sense | null { + const doc = new DOMParser().parseFromString(html, 'text/html'); + const text = (doc.body.textContent ?? '').replace(/\s+/g, ' ').trim(); + if (!text) return null; + const formOf = doc.querySelector('.form-of-definition-link')?.textContent?.trim(); + return formOf ? { text, formOf } : { text }; +} + +/** The entry shown for a response: its English senses, or another language's when there are none. */ +export function parseEntry(word: string, response: RawResponse): DictionaryEntry | null { + const language = response.en ? 'en' : Object.keys(response)[0]; + const usages = (language && response[language]) || []; + const parts: PartOfSpeech[] = []; + for (const usage of usages) { + const senses = (usage.definitions ?? []) + .map((definition) => readSense(definition.definition ?? '')) + .filter((sense): sense is Sense => sense !== null) + .slice(0, MAX_SENSES); + if (senses.length > 0) parts.push({ partOfSpeech: usage.partOfSpeech ?? '', senses }); + if (parts.length === MAX_PARTS) break; + } + if (parts.length === 0) return null; + const otherLanguage = language === 'en' ? undefined : usages[0]?.language; + const anchor = otherLanguage ?? 'English'; + return { + word, + ...(otherLanguage ? { language: otherLanguage } : {}), + parts, + url: `${PAGE}${encodeURIComponent(word.replace(/ /g, '_'))}#${encodeURIComponent(anchor.replace(/ /g, '_'))}`, + }; +} + +const cache = new Map(); + +async function fetchEntry(word: string, signal?: AbortSignal): Promise { + if (cache.has(word)) return cache.get(word)!; + let response: Response; + try { + response = await fetch(`${API}${encodeURIComponent(word.replace(/ /g, '_'))}?redirect=true`, { + signal, + headers: { Accept: 'application/json' }, + }); + } catch (error) { + if (signal?.aborted) throw error; + throw new LookupUnavailableError('Wiktionary could not be reached'); + } + if (response.status === 404) return remember(word, null); + if (!response.ok) throw new LookupUnavailableError(`Wiktionary answered ${response.status}`); + return remember(word, parseEntry(word, (await response.json()) as RawResponse)); +} + +function remember(key: string, entry: DictionaryEntry | null): DictionaryEntry | null { + cache.delete(key); + cache.set(key, entry); + for (const oldKey of cache.keys()) { + if (cache.size <= CACHE_SIZE) break; + cache.delete(oldKey); + } + return entry; +} + +/** + * Looks a word up as selected, then in lower case ("Impulse" at the start of a + * sentence), preferring an English entry. Null when Wiktionary has none. + */ +export async function lookUpWord(word: string, signal?: AbortSignal): Promise { + const lower = word.toLowerCase(); + const exact = await fetchEntry(word, signal); + if (lower === word || (exact && !exact.language)) return exact; + return (await fetchEntry(lower, signal)) ?? exact; +} + +/** Forgets cached lookups (tests). */ +export function clearDictionaryCache(): void { + cache.clear(); +} diff --git a/src/features/notes/SelectionNotePopover.tsx b/src/features/notes/SelectionNotePopover.tsx index e7db96f..7c7ab4f 100644 --- a/src/features/notes/SelectionNotePopover.tsx +++ b/src/features/notes/SelectionNotePopover.tsx @@ -1,7 +1,9 @@ import { useEffect, useRef, useState } from 'react'; -import { Highlighter, MessageSquarePlus } from 'lucide-react'; +import { BookA, Highlighter, MessageSquarePlus } from 'lucide-react'; import { NOTE_COLORS } from '@/lib/types'; import { ariaKeyShortcuts, keyLabel, withShortcut } from '../commands/keys'; +import { termFromSelection } from '../define/dictionary'; +import { lookUpSelection, useDefineStore } from '../define/defineStore'; import { useFloatingPosition, type FloatingAnchor } from './floatingPosition'; import { highlightSelection } from './highlightActions'; import { HighlightPopover } from './HighlightPopover'; @@ -15,7 +17,7 @@ import './notes.css'; /** * Everything that appears over the page for annotating: the toolbar for a text - * selection (highlight in a colour, or add a margin note), the popover for an + * selection (highlight in a colour, add a margin note, or look a word up), the popover for an * existing highlight, and the `H` shortcut. Mount once in the reader. */ export function SelectionNotePopover() { @@ -31,7 +33,9 @@ export function SelectionNotePopover() { /** Floating toolbar shown while text on a page is selected. */ function SelectionToolbar() { const [anchor, setAnchor] = useState(null); + const [isTerm, setIsTerm] = useState(false); const editing = useNotesStore((s) => s.editingId !== null); + const defining = useDefineStore((s) => s.term !== null); const lastColor = useHighlightsStore((s) => s.lastColor); const popoverRef = useRef(null); @@ -41,6 +45,7 @@ function SelectionToolbar() { const evaluate = () => { const selection = useNotesStore.getState().editingId === null ? readPageSelection() : null; + setIsTerm(!!selection && termFromSelection(selection.text) !== null); setAnchor( selection ? { @@ -92,7 +97,11 @@ function SelectionToolbar() { }; }, []); - const visible = anchor !== null && !editing; + const visible = anchor !== null && !editing && !defining; + // A lookup takes the toolbar's place; closing the card leaves the page clear. + useEffect(() => { + if (defining) setAnchor(null); + }, [defining]); useFloatingPosition(popoverRef, anchor, visible); if (!visible) return null; @@ -130,7 +139,9 @@ function SelectionToolbar() {