Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <kbd>B</kbd>.
- **Define:** select a word and press <kbd>D</kbd> 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.
Expand All @@ -88,6 +89,7 @@ Press <kbd>?</kbd> in the app for the full list.
| <kbd>Ctrl</kbd>+<kbd>F</kbd> or <kbd>/</kbd> | Find in the book; <kbd>F3</kbd> / <kbd>Shift</kbd>+<kbd>F3</kbd> step through matches |
| <kbd>N</kbd> | New margin note on the current page, quoting any selected text |
| <kbd>H</kbd> | Highlight the selected text in the colour used last |
| <kbd>D</kbd> | Look up the selected word in the dictionary |
| <kbd>B</kbd> | Bookmark the current page |
| <kbd>Shift</kbd>+<kbd>R</kbd> | Open or close the notes review |
| <kbd>F</kbd> | Focus mode (<kbd>Esc</kbd> also leaves) |
Expand Down Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions docs/DATA.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 2 additions & 0 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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 <kbd>D</kbd> for its dictionary entry from Wiktionary (online). Still to come: an optional offline dictionary download.
- **Rich notes:** ✅ bold and italic (<kbd>Ctrl</kbd>+<kbd>B</kbd> / <kbd>Ctrl</kbd>+<kbd>I</kbd>); 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)).
Expand Down
69 changes: 69 additions & 0 deletions e2e/define.spec.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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 <a href="/wiki/displace">displacing</a>.' }],
},
],
},
});
});
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);
});
7 changes: 7 additions & 0 deletions src/features/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
161 changes: 161 additions & 0 deletions src/features/define/DefineCard.tsx
Original file line number Diff line number Diff line change
@@ -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(<Card term={term} anchor={anchor} lookup={lookup} />, 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<HTMLDivElement>(null);
const sideRef = useRef<PeekSide>('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 (
<div
ref={cardRef}
role="dialog"
aria-label={`Definition of ${term}`}
aria-busy={lookup.status === 'loading'}
className="define-card"
tabIndex={-1}
>
<h2 className="define-card__term">{term}</h2>
<div className="define-card__body" aria-live="polite">
{lookup.status === 'loading' && <p className="define-card__status">Looking up…</p>}
{lookup.status === 'not-found' && <p className="define-card__status">No dictionary entry found.</p>}
{lookup.status === 'unavailable' && (
<p className="define-card__status">Couldn’t reach the dictionary. Check your connection.</p>
)}
{entry?.language && <p className="define-card__status">No English entry. In {entry.language}:</p>}
{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
<section key={index} className="define-card__part">
{part.partOfSpeech && <h3 className="define-card__pos">{part.partOfSpeech}</h3>}
<ol className="define-card__senses">
{part.senses.map((sense, senseIndex) => (
// biome-ignore lint/suspicious/noArrayIndexKey: as above
<li key={senseIndex}>
{sense.formOf ? <FormOf text={sense.text} word={sense.formOf} /> : sense.text}
</li>
))}
</ol>
</section>
))}
</div>
{entry && (
<a className="define-card__source" href={entry.url} target="_blank" rel="noopener noreferrer">
Wiktionary
<ExternalLink aria-hidden="true" />
</a>
)}
</div>
);
}

/** "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)}
<button type="button" className="define-card__word" onClick={() => lookUp(word)}>
{word}
</button>
{text.slice(at + word.length)}
</>
);
}
Loading
Loading