Daily learning in Claude Code: Chitas (Chumash with Rashi, Tehillim, Tanya), Rambam, Hayom Yom and Daf Yomi (with Rashi), powered by Shafeh, on one line above…

Your daily learning inside Claude Code: today's Chitas, Rambam, Hayom Yom and Daf Yomi, and a Library of Mishnayos, Shas and Mishneh Torah to learn through at your own pace, in Hebrew that reads right. · Website
In a Claude Code session:
/plugin marketplace add sharshi/daily-learning-plugin
/plugin install dl@daily-learning
Then /dl opens the sidebar. Needs Claude Code 2.1.286+ and python3.

✡ 25 Tishrei 5787 · Parashat Bereshit 📅 Today's learning 📚 Library ▶ Ketubot 5 ×
One line above the prompt: today's date, 📅 Today's learning, 📚 Library, and ▶ where you left each Library collection. Each opens the sidebar there; × hides the line until tomorrow.
On a longer-running task, the same line offers to fill the wait:
⏳ Claude's working. Learn while you wait: ▶ Ketubot 5 📅 Chumash + Rashi later
▶ picks up where you left the Library; 📅 opens the next part of today you haven't read yet (or Today's learning, once you've opened them all). Either one opens the sidebar right there. later puts the launcher back.
In the sidebar, 📅 Today is a menu of the day's sections; each opens into its full text, and next › walks through the day in order:
📚 Library (l) is for learning through whole works:
Pick a collection, a seder or sefer, a masechta or hilchos, then a perek or daf. Continue picks up where you left each one, in any session; next › runs straight on into the next masechta. Texts load from Shafeh only when you open them.
All of it is on the sidebar's ⚙ Settings page (s), and in /config under dl.
/dl | Open the sidebar |
/dl-toggle | Hide or show the line above the prompt |
/dl:text | Print today's text in the chat, to ask Claude about it |
t l s | Today, Library, Settings |
1–7 | A section from today's menu |
j k | Next, previous (perek, amud, daf) |
All calendar and text requests go to Shafeh. No Sefaria or Hebcal requests or fallback. Tanya English is the exact daily slice; each Rambam chapter keeps its own number even across hilchos boundaries. Rashi on Shas is shown as amud-level commentary, without inventing alignment to Gemara passages.
Daf Yomi uses Shafeh's calculated cycle. Shekalim, Kinnim and Middot currently lack bundled Gemara text; the plugin reports missing text rather than substituting another reading. English is shown only where Shafeh supplies a translation.
Bundled translations retain their source terms: Tanya — Kehot Publication Society (CC-BY-NC); Rambam — Eliyahu Touger / Moznaim (CC-BY-NC); Tanach — JPS 1917 (public domain). Shas uses the William Davidson Edition (CC-BY-NC). Hayom Yom is © Kehot Publication Society, distributed by Shafeh from Beis Seforim; see the source notices on Shafeh.
claude --plugin-dir . # run from a clone; edits apply on /reload-plugins
claude plugin test . # sidebar/library tests
python3 -m unittest discover -s tests -p 'test_*.py' # Python client tests
claude plugin validate . # what the mod does, and anything the engine would refuse
hooks/register.tsx is the mod (line, sidebar, fetching); hooks/data.ts, library.ts, hebrew.ts and svg.ts are pure helpers it draws with; scripts/dl.py fetches the day's text. An installed copy is a snapshot: bump version in .claude-plugin/plugin.json, then claude plugin update dl@daily-learning.
Code: MIT (LICENSE). Fonts: SIL Open Font License 1.1, Shlomo © SIL International and Shlomo Orbach, Frank Ruhl Libre © The Frank Ruhl Libre Project Authors (fonts/).
hooks/register.tsx 898 lines1// dl (Daily Learning): today's learning in a band above the prompt, and the full text in a
2// sidebar (/dl). Both are cached per Gregorian day, in memory and in
3// the mod's $.store. Data: ./data.ts; Hebrew layout: ./hebrew.ts.
4
5import { atom, read, update } from "claude-code";
6import type { EngineInterface as Host, Register, RenderChildren } from "claude-code";
7
8import type { Day, Status, TabId } from "../types";
9import { briefFrom, calendarUrl, DAY_V, linesFor, todayKey, toDay } from "./data";
10import type { English } from "./data";
11import { COLL_ORDER, COLLS, findBook, libPart, parseShape, step, textRef, unitLabel, unitName } from "./library";
12import type { Coll, LibBook } from "./library";
13import type { Brief } from "./data";
14import { cleanHe, cleanText, termVisual, visual, wrap } from "./hebrew";
15import { svgPages } from "./svg";
16import type { EmbeddedFont, FontKey, Line } from "./svg";
17
18const PANE = "dl";
19const TABS: [TabId, string][] = [
20 ["chumash", "Chumash + Rashi"], ["tehillim", "Tehillim"],
21 ["tanya", "Tanya"], ["rambam1", "Rambam ×1"], ["rambam3", "Rambam ×3"], ["hayom", "Hayom Yom"],
22 ["daf", "Daf Yomi"],
23];
24
25
26// ---- pane state ---------------------------------------------------------
27const day = atom({ plugin: "dl", key: "day" } as const, null);
28const status = atom({ plugin: "dl", key: "status" } as const, null);
29const tab = atom({ plugin: "dl", key: "tab" } as const, null);
30const pageAtom = atom({ plugin: "dl", key: "page" } as const, "read");
31const libPos = atom({ plugin: "dl", key: "libPos" } as const, {});
32const libShapes = atom({ plugin: "dl", key: "libShapes" } as const, {});
33const libText = atom({ plugin: "dl", key: "libText" } as const, null);
34const libStatus = atom({ plugin: "dl", key: "libStatus" } as const, null);
35const libLast = atom({ plugin: "dl", key: "libLast" } as const, {});
36const prefsOver = atom({ plugin: "dl", key: "prefsOver" } as const, {});
37const todayOpened = atom({ plugin: "dl", key: "todayOpened" } as const, null);
38const perek = atom({ plugin: "dl", key: "perek" } as const, null);
39
40// ---- band state ---------------------------------------------------------
41let state: { key: string | null; data: Brief | null; error: string | null; loading: boolean } =
42 { key: null, data: null, error: null, loading: false };
43// The day the band was dismissed for (YYYY-MM-DD), kept in the store so new
44// sessions that day stay quiet; a new day brings the band back.
45let hiddenFor: string | null = null;
46
47async function setHidden($: Host, key: string | null) {
48 hiddenFor = key;
49 if (key) await $.store.set("hidden", key);
50 else await $.store.delete("hidden");
51 $.ui.invalidate("ui.render");
52}
53
54async function getJSON($: Host, url: string) {
55 const res = await $.http.fetch(url, {
56 headers: { "User-Agent": "daily-learning (+https://github.com/sharshi/daily-learning-plugin)", Accept: "application/json" },
57 });
58 if (!res.ok) throw new Error(`${res.status} ${url}`);
59 return JSON.parse(res.text);
60}
61
62// Fetch what the band needs for Gregorian day `d` and shape it.
63async function buildBrief($: Host, d: Date): Promise<Brief> {
64 return briefFrom(await getJSON($, calendarUrl(d)));
65}
66
67// The band's brief for `key`: from memory, the store, or the network. The band
68// redraws when it lands.
69async function ensure($: Host, key: string) {
70 if (state.key === key && (state.data || state.loading)) return;
71 state = { key, data: null, error: null, loading: true };
72 const storeKey = `brief-shafeh-${key}`;
73 try {
74 const cached = (await $.store.get(storeKey)) as Brief | undefined;
75 if (cached) {
76 state.data = cached;
77 return;
78 }
79 const data = await buildBrief($, new Date(`${key}T12:00:00`));
80 if (state.key !== key) return; // day rolled over mid-fetch
81 state.data = data;
82 // Keep only today's brief in the store.
83 for (const k of await $.store.keys()) if (k.startsWith("brief-") && k !== storeKey) await $.store.delete(k);
84 await $.store.set(storeKey, data);
85 } catch (e: any) {
86 if (state.key === key) state.error = e?.message || String(e);
87 } finally {
88 if (state.key === key) state.loading = false;
89 $.ui.invalidate("ui.render");
90 }
91}
92
93// The fetch in flight, by day. A module variable, not $.state: a reload drops
94// it with the fetch it tracked, so a "loading" left by an old module never
95// blocks the next load.
96let dayFetch: { key: string; done: Promise<void> } | null = null;
97
98function ensureDay($: Host) {
99 const key = todayKey();
100 if (dayFetch?.key !== key) dayFetch = { key, done: loadDay($, key) };
101 return dayFetch.done;
102}
103
104async function loadDay($: Host, key: string) {
105 const d0 = await read($, day);
106 if (d0?.key === key && d0.v === DAY_V) {
107 await update($, status, () => ({ key, phase: "ready" }) as Status);
108 return;
109 }
110 await update($, status, () => ({ key, phase: "loading" }) as Status);
111 const storeKey = `day-v${DAY_V}-${key}`;
112 try {
113 let d = (await $.store.get(storeKey)) as Day | undefined;
114 // Older builds kept a Day under day-<date>; the prune below removes it.
115 if (!d) {
116 const script = `${$.plugin.root}/scripts/dl.py`;
117 const r = await $.process.run(["python3", script, "--json", "--full"], { timeoutMs: 300_000 });
118 if (r.exitCode !== 0) throw new Error(r.stderr.trim().split("\n").pop() || `exit ${r.exitCode}`);
119 d = toDay(key, JSON.parse(r.stdout));
120 for (const k of await $.store.keys()) if (k.startsWith("day-") && k !== storeKey) await $.store.delete(k);
121 await $.store.set(storeKey, d);
122 }
123 await update($, day, () => d!);
124 await update($, status, () => ({ key, phase: "ready" }) as Status);
125 } catch (e: any) {
126 if (dayFetch?.key === key) dayFetch = null; // let the next open retry
127 await update($, status, () => ({ key, phase: "error", error: e?.message || String(e) }) as Status);
128 }
129}
130
131// A section whose text did not load is left out of
132// the sidebar and the band instead of pointing at a page that does not load.
133const hasText = (d: Day, id: TabId) => (d.parts[id] ?? []).some((p) => p.he.length || p.en.length);
134const shownTabs = (d: Day | null) => TABS.filter(([id]) => !d || hasText(d, id));
135
136// Open the sidebar on a section of the day, or on the day's menu.
137async function openPane($: Host, t?: TabId) {
138 await update($, tab, () => t ?? null);
139 await update($, pageAtom, () => "read");
140 void ensureDay($);
141 await $.ui.open({ id: PANE, title: "Daily Learning", focus: true });
142}
143
144// Terminals with a bidi of their own, which get termVisual's order (see
145// hebrew.ts); every other terminal gets visual's.
146const RLM = "\u200F";
147const BIDI_TERMINALS = new Set(["Apple_Terminal"]);
148
149// The chosen font as WOFF, base64, for the Desktop app's SVG pages; null for
150// "System", until read, or if it can't be (the Desktop app then gets text).
151let embedded: EmbeddedFont | null = null;
152
153async function loadFont($: Host, choice: unknown) {
154 const f = FONTS[String(choice)];
155 if (!f) return;
156 try {
157 const r = await $.fs.read(`${$.plugin.root}/fonts/${f.file}.woff`, { as: "bytes" });
158 embedded = typeof r === "string" ? null : { key: f.key, base64: r.base64 };
159 $.ui.invalidate("ui.render");
160 } catch {}
161}
162
163// ---- library ----------------------------------------------------------------
164// Everything loads when first needed: a collection's structure when it is
165// opened (kept for good: it doesn't change), a unit's text when it is read
166// (the store keeps the last LIB_KEEP). One fetch at a time per thing.
167const LIB_KEEP = 12;
168const libFetching = new Map<string, Promise<void>>();
169const once = (what: string, run: () => Promise<void>) => {
170 if (!libFetching.has(what)) libFetching.set(what, run().finally(() => libFetching.delete(what)));
171 return libFetching.get(what)!;
172};
173// Text colours, as theme keys so they follow the person's light or dark theme:
174// the body in the theme's own text colour (not the terminal's default, which
175// a dark terminal under a light theme draws pale on the pane), amber titles
176// (yellow in dark, a darker amber in light), indigo Rashi, blue headings.
177const BODY = "text", TITLE = "warning", RASHI = "permission", ACCENT = "ide";
178
179const shafeh = (path: string) => `https://shafeh.org/api/v1/${path}`;
180
181function ensureShape($: Host, coll: Coll) {
182 return once(`shape:${coll}`, async () => {
183 const existing = (await read($, libShapes))[coll];
184 if (existing?.sections.length && existing.sections.every((s) => s.books.every((b) => b.key))) return;
185 await update($, libStatus, () => ({ what: COLLS[coll].name, phase: "loading" as const }));
186 try {
187 const key = `lib-shape-shafeh-${coll}`;
188 let shape = (await $.store.get(key)) as ReturnType<typeof parseShape> | undefined;
189 if (!shape?.sections?.length) {
190 shape = parseShape(coll, await getJSON($, shafeh(COLLS[coll].shape)));
191 await $.store.set(key, shape);
192 }
193 await update($, libShapes, (v) => ({ ...v, [coll]: shape }));
194 await update($, libStatus, () => null);
195 } catch (e: any) {
196 await update($, libStatus, () => ({ what: COLLS[coll].name, phase: "error" as const, error: e?.message || String(e) }));
197 }
198 });
199}
200
201function ensureLibText($: Host, coll: Coll, b: LibBook, unit: number) {
202 const ref = textRef(b, unit);
203 return once(`text:${ref}`, async () => {
204 const existing = await read($, libText);
205 if (existing?.ref === ref && existing.part.link?.startsWith("https://shafeh.org/")) return;
206 await update($, libStatus, () => ({ what: ref, phase: "loading" as const }));
207 try {
208 const key = `lib-text-shafeh-${ref}`;
209 let part = (await $.store.get(key)) as ReturnType<typeof libPart> | undefined;
210 if (!part) {
211 const key = encodeURIComponent(b.key!);
212 let text;
213 if (coll === "bavli") {
214 const amudim = [];
215 for (const side of ["a", "b"]) {
216 // Last/first dapim may contain a single amud. Only a 404 means
217 // absent: network and server errors must leave the reading retryable.
218 const url = shafeh(`shas/${key}/${unit}${side}`);
219 try { amudim.push(await getJSON($, url)); }
220 catch (error) { if (!String(error).startsWith("Error: 404 ")) throw error; }
221 }
222 if (!amudim.length) throw new Error("No text available for this daf");
223 text = { amudim };
224 } else {
225 text = await getJSON($, shafeh(`${coll === "mt" ? "rambam" : "mishnah"}/${key}/${unit}`));
226 }
227 part = libPart(coll, b, unit, text);
228 // Keep the newest LIB_KEEP texts.
229 const recent = (((await $.store.get("lib-recent")) as string[] | undefined) ?? []).filter((k) => k !== key);
230 recent.unshift(key);
231 for (const old of recent.splice(LIB_KEEP)) await $.store.delete(old);
232 await $.store.set("lib-recent", recent);
233 await $.store.set(key, part);
234 }
235 await update($, libText, () => ({ ref, part: part! }));
236 await update($, libStatus, () => null);
237 } catch (e: any) {
238 await update($, libStatus, () => ({ what: ref, phase: "error" as const, error: e?.message || String(e) }));
239 }
240 });
241}
242
243// Open a unit: move the menu there, remember it as where this collection was
244// last read, and load its text.
245async function openUnit($: Host, coll: Coll, b: LibBook, unit: number) {
246 await update($, libPos, () => ({ coll, section: b.section, book: b.title, unit }));
247 const at = await $.clock.now();
248 const last = await update($, libLast, (v) => ({ ...v, [coll]: { book: b.title, unit, at } }));
249 await $.store.set("lib-last", last);
250 void ensureLibText($, coll, b, unit);
251}
252
253// Where a collection was last read, as "Ketubot 5" (the book's short name).
254const lastLabel = (l: { book: string; unit: number }) => `${l.book.replace(/^(Mishnah|Mishneh Torah,) /, "")} ${l.unit}`;
255
256// Continue a collection where it was left: load its structure if need be,
257// open the unit, and show it in the Library.
258async function continueLib($: Host, c: Coll) {
259 const l = (await read($, libLast))[c];
260 if (!l) return;
261 await ensureShape($, c);
262 const sh = (await read($, libShapes))[c];
263 const bk = sh ? findBook(sh, l.book) : undefined;
264 if (bk) await openUnit($, c, bk, l.unit);
265}
266
267// ---- while Claude works -----------------------------------------------------
268// A turn that runs long turns the line above the prompt into a suggestion to
269// learn meanwhile: where the Library was left, or the next section of today
270// not yet opened. Gone when the turn ends; at most once every 30 minutes;
271// never on a day the line was hidden; never takes the keyboard.
272const WAIT_MS: Record<string, number> = { "After 45 seconds": 45_000, "After 2 minutes": 120_000 };
273const SUGGEST_GAP_MS = 30 * 60_000;
274let waitTimer: { cancel: () => void } | null = null;
275let suggesting = false; // the suggestion is on the line now
276let suggestedTurn = false; // it was shown during this turn
277
278async function startWait($: Host, setting: unknown) {
279 waitTimer?.cancel();
280 waitTimer = null;
281 const ms = WAIT_MS[String(setting ?? "After 45 seconds")];
282 if (!ms) return;
283 waitTimer = $.clock.after(ms, () => void suggest($));
284}
285
286async function suggest($: Host) {
287 waitTimer = null;
288 if (hiddenFor === todayKey()) return;
289 const now = await $.clock.now();
290 const last = (await $.store.get("suggest-last")) as number | undefined;
291 if (last != null && now - last < SUGGEST_GAP_MS) return;
292 await $.store.set("suggest-last", now);
293 suggesting = suggestedTurn = true;
294 $.ui.invalidate("ui.render");
295}
296
297function endWait($: Host) {
298 waitTimer?.cancel();
299 waitTimer = null;
300 if (suggesting) { suggesting = false; $.ui.invalidate("ui.render"); }
301 if (suggestedTurn) { suggestedTurn = false; $.ui.toast("Daily Learning: Claude is done."); }
302}
303
304// Note a section of today as opened (the suggestion offers the next one not).
305async function markOpened($: Host, id: TabId) {
306 const key = todayKey();
307 const v = await update($, todayOpened, (o) => {
308 const ids = o?.key === key ? o.ids : [];
309 return { key, ids: ids.includes(id) ? ids : [...ids, id] };
310 });
311 await $.store.set("today-opened", v);
312}
313
314// ---- settings -------------------------------------------------------------
315// The sidebar's settings are the plugin's own (userConfig): they persist, show
316// in /config, and the settings page changes them with $.config.set, which
317// reloads the mod with the new values.
318const ENGLISH: Record<string, English> = { "Off": "off", "Staggered": "staggered", "Side by side": "side" };
319const SIZES: Record<string, number> = { "Small": 0.88, "Medium": 1, "Large": 1.18 };
320
321type Prefs = { font: string; english: English; nikkud: boolean; rashi: boolean; size: string };
322function prefsOf(o: Record<string, unknown>): Prefs {
323 return {
324 font: String(o.hebrew_font ?? "Frank Ruhl"),
325 english: ENGLISH[String(o.english)] ?? "off",
326 nikkud: o.nikkud !== false,
327 rashi: o.rashi !== false,
328 size: SIZES[String(o.text_size)] ? String(o.text_size) : "Medium",
329 };
330}
331
332// A setting's /config row key. Builds name plugin rows differently
333// (`dl.nikkud`, `dl@daily-learning.nikkud`, ...), so it's looked up in the
334// list by the owning plugin and the field rather than guessed.
335async function rowKey($: Host, field: string) {
336 const rows = await $.config.list();
337 const ours = (r: (typeof rows)[number]) => /^dl(@|$)/.test(String(r.provider?.plugin ?? "")) || /^dl[@.]/.test(r.key);
338 const tail = new RegExp(`(^|[^A-Za-z0-9_])${field}$`);
339 return (rows.find((r) => r.key === `dl.${field}`)
340 ?? rows.find((r) => ours(r) && tail.test(r.key))
341 ?? rows.find((r) => tail.test(r.key) && /(^|[^A-Za-z0-9_])dl([^A-Za-z0-9_]|$)/.test(r.key)))?.key;
342}
343
344const PREF_FIELDS = ["hebrew_font", "english", "nikkud", "rashi", "text_size", "wait_suggest"];
345const optionsKey = (o: Record<string, unknown>) => JSON.stringify(PREF_FIELDS.map((f) => o[f] ?? null));
346
347// Change one setting from the sidebar. It takes effect at once and is kept in
348// the plugin's store, over the plugin's options; it is also written to
349// /config where this build lists the plugin's rows there (the Desktop app's
350// may not), which reloads the mod with it. A later change in /config wins.
351async function setPref($: Host, field: string, value: string | boolean) {
352 const over = await update($, prefsOver, (v) => ({ ...v, [field]: value }));
353 await $.store.set("prefs-over", over);
354 if (field === "hebrew_font") { void applyFont($, value); void loadFont($, value); }
355 try {
356 const key = await rowKey($, field);
357 if (key) await $.config.set({ key, value });
358 } catch {}
359}
360
361// ---- ui -----------------------------------------------------------------
362// The "Hebrew font" setting's choices: each font's key (for its letter widths),
363// its file under fonts/, and the family name inside it (Shlomo's is inherited
364// from SIL's Ezra).
365const FONTS: Record<string, { key: FontKey; file: string; family: string }> = {
366 "Shlomo": { key: "shlomo", file: "Shlomo", family: "Ezra SIL SR" },
367 "Frank Ruhl": { key: "frank", file: "FrankRuhlLibre-Regular", family: "Frank Ruhl Libre" },
368};
369
370// Install the chosen font and map Ghostty's Hebrew to it, or take the mapping
371// back out for "System". Says so only when something changed.
372async function applyFont($: Host, choice: unknown) {
373 const script = `${$.plugin.root}/scripts/install-font.sh`;
374 const f = FONTS[String(choice)];
375 const argv = f ? ["/bin/sh", script, f.file, f.family] : ["/bin/sh", script, "--remove"];
376 try {
377 const r = await $.process.run(argv, { timeoutMs: 30_000 });
378 const changed = r.stdout.split("\n").filter((l) => l.startsWith("changed:"));
379 if (r.exitCode !== 0)
380 $.ui.toast(`Daily Learning: Hebrew font setting failed: ${r.stderr.trim().split("\n").pop() || `install-font.sh exited ${r.exitCode}`}`);
381 else if (changed.length)
382 $.ui.toast(`Daily Learning: ${changed.map((l) => l.slice(9)).join("; ")}. Reload Ghostty's config (cmd+shift+,) to see it.`);
383 } catch (err: any) {
384 $.ui.toast(`Daily Learning: Hebrew font setting failed: ${err?.message || err}`);
385 }
386}
387
388export const register: Register = (on, options) => {
389 const opts = options as Record<string, unknown>;
390 on("session.start", async ($, e, next) => {
391 // Sidebar choices stand until /config changes one of the plugin's options.
392 let over = ((await $.store.get("prefs-over")) as Record<string, string | boolean> | undefined) ?? {};
393 if ((await $.store.get("prefs-seen")) !== optionsKey(opts)) {
394 over = {};
395 await $.store.set("prefs-over", over);
396 await $.store.set("prefs-seen", optionsKey(opts));
397 }
398 await update($, prefsOver, () => over);
399 const font = over.hebrew_font ?? options.hebrew_font;
400 void applyFont($, font);
401 void loadFont($, font);
402 const last = (await $.store.get("lib-last")) as Partial<Record<Coll, { book: string; unit: number; at?: number }>> | undefined;
403 if (last) await update($, libLast, () => last);
404 const opened = (await $.store.get("today-opened")) as { key: string; ids: TabId[] } | undefined;
405 if (opened?.key === todayKey()) await update($, todayOpened, () => opened);
406 hiddenFor = ((await $.store.get("hidden")) as string | undefined) ?? null;
407 await $.command.register({ name: "dl-toggle", description: "Show or hide the daily learning line above the prompt" });
408 await $.command.register({ name: "dl", description: "Open today's learning in a sidebar" });
409 void ensure($, todayKey());
410 void ensureDay($); // warm the sidebar text: from the store when cached
411 return next(e);
412 });
413
414 // A turn's start and end drive the suggestion to learn meanwhile.
415 on("prompt.submit", async ($, e, next) => {
416 const over = await read($, prefsOver);
417 void startWait($, over.wait_suggest ?? options.wait_suggest);
418 return next(e);
419 });
420 on("turn.complete", async ($, e, next) => {
421 endWait($);
422 return next(e);
423 });
424
425 on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
426 const { Box, Text, Button } = $.ui.resolve(e);
427 const key = todayKey();
428 if (hiddenFor === key) return next(e);
429 const last = await read($, libLast);
430 void ensure($, key); // no-op unless the date rolled over
431
432 if (state.loading && !state.data)
433 return <Box paddingX={1}><Text dimColor>✡ dl · loading…</Text></Box>;
434 if (state.error && !state.data)
435 return <Box paddingX={1}><Text color="red">✡ dl · {state.error}</Text></Box>;
436 if (!state.data) return next(e);
437
438 // While a long turn runs: the suggestion, in place of the launcher.
439 if (suggesting) {
440 const [dd, opened] = await Promise.all([read($, day), read($, todayOpened)]);
441 const recent = COLL_ORDER.filter((c) => last?.[c]).sort((a, b) => (last![b]!.at ?? 0) - (last![a]!.at ?? 0))[0];
442 const today = dd?.key === key ? shownTabs(dd) : [];
443 const done = opened?.key === key ? opened.ids : [];
444 const nextToday = today.find(([id]) => !done.includes(id));
445 const go = async (run: () => Promise<unknown>) => {
446 suggesting = false;
447 await $.ui.open({ id: PANE, title: "Daily Learning", focus: true });
448 await run();
449 $.ui.invalidate("ui.render");
450 };
451 return (
452 <Box paddingX={1} flexDirection="row" flexWrap="wrap" columnGap={3}>
453 <Text color={TITLE}>⏳ Claude's working. Learn while you wait:</Text>
454 {recent ? <Button key="wait-lib" plain label={`▶ ${lastLabel(last![recent]!)}`}
455 onPress={() => go(async () => { await continueLib($, recent); await update($, pageAtom, () => "library"); })} /> : null}
456 {nextToday
457 ? <Button key="wait-today" plain label={`📅 ${nextToday[1]}`}
458 onPress={() => go(async () => { void ensureDay($); await update($, tab, () => nextToday[0]); await update($, pageAtom, () => "read"); await markOpened($, nextToday[0]); })} />
459 : <Button key="wait-today" plain label="📅 Today's learning"
460 onPress={() => go(async () => { void ensureDay($); await update($, tab, () => null); await update($, pageAtom, () => "read"); })} />}
461 <Button key="wait-later" plain label="later" onPress={() => { suggesting = false; $.ui.invalidate("ui.render"); }} />
462 </Box>
463 );
464 }
465
466 // One line, a launcher: the date, then Today's learning, the Library, and
467 // a continue button for each Library collection being read; × hides the
468 // line for the rest of the day.
469 const { heb } = state.data;
470 const date = `✡ ${heb.hd} ${heb.hm} ${heb.hy}` + (heb.events.length ? ` · ${heb.events.join(", ")}` : "");
471 const show = async (to: "read" | "library") => {
472 if (to === "read") void ensureDay($);
473 await $.ui.open({ id: PANE, title: "Daily Learning", focus: true });
474 if (to === "read") await update($, tab, () => null);
475 else await update($, libPos, () => ({}));
476 await update($, pageAtom, () => to);
477 };
478 return (
479 <Box paddingX={1} flexDirection="row" flexWrap="wrap" columnGap={3}>
480 <Text key="date" color={ACCENT}>{date}</Text>
481 <Button key="band-today" plain label="📅 Today's learning" onPress={() => show("read")} />
482 <Button key="band-library" plain label="📚 Library" onPress={() => show("library")} />
483 {COLL_ORDER.filter((c) => last?.[c]).map((c) => (
484 <Button key={`band-lib-${c}`} plain label={`▶ ${lastLabel(last![c]!)}`} onPress={async () => {
485 await $.ui.open({ id: PANE, title: "Daily Learning", focus: true });
486 await continueLib($, c);
487 await update($, pageAtom, () => "library");
488 }} />
489 ))}
490 <Button key="dismiss" plain role="dismiss" label="×" onPress={() => setHidden($, key)} />
491 </Box>
492 );
493 });
494
495 // /dl-toggle hides the line for today, or brings it back.
496 on("command.run", { command: "dl-toggle" }, async ($) => {
497 const key = todayKey();
498 const hide = hiddenFor !== key;
499 await setHidden($, hide ? key : null);
500 return { text: hide ? "Hidden for today (/dl-toggle shows it again)." : "Shown." };
501 });
502
503 // /dl opens the sidebar and fetches the text in the background.
504 on("command.run", { command: "dl" }, async ($) => {
505 await openPane($);
506 return { text: "Opened the sidebar. Keys: t Today · l Library · s Settings · number keys pick from today's menu · j/k next/previous · ↑↓ scroll · Esc back to prompt." };
507 });
508
509 on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
510 const { Box, Text, Button } = $.ui.resolve(e);
511 const Svg = e.surface === "desktop" ? $.ui.resolve(e).Svg : null;
512 const [d, st, t, pk, pg, lp, shapes, lt, ls, ll, po] = await Promise.all([
513 read($, day), read($, status), read($, tab), read($, perek), read($, pageAtom),
514 read($, libPos), read($, libShapes), read($, libText), read($, libStatus), read($, libLast), read($, prefsOver),
515 ]);
516 const prefs = prefsOf({ ...opts, ...po });
517 const nk = prefs.nikkud;
518 // Load on sight: a render never writes state, so start it on a timer.
519 if ((d?.key !== todayKey() || d.v !== DAY_V) && st?.phase !== "error") $.clock.after(0, () => void ensureDay($));
520 const width = Math.max(20, e.props.bodyColumns - 1);
521 // Where the Hebrew is drawn decides its order: reversed here for a terminal
522 // with no bidi, word order only for one that reverses each word, and reading
523 // order for the Desktop app, which lays it out itself.
524 const term = e.surface === "terminal" ? await $.env.get("TERM_PROGRAM") : undefined;
525 const isBidiTerminal = e.surface === "terminal" && BIDI_TERMINALS.has(term ?? "");
526 const isFlipped = e.surface === "terminal" && !isBidiTerminal;
527 // How a line of Hebrew words is ordered for this surface. The Desktop app
528 // lays Hebrew out itself but in a left-to-right line, so each line is
529 // wrapped in right-to-left marks to keep edge punctuation on the Hebrew side.
530 const order = isFlipped ? visual : isBidiTerminal ? termVisual : (ws: string[]) => RLM + ws.join(" ") + RLM;
531
532 // A Hebrew paragraph, wrapped here and right-aligned line by line, each line
533 // ordered for the surface. `label` (a halacha's or a verse's "א.") leads the
534 // paragraph in bold, at the right end of its first line.
535 const he = (s: string, k: string, color?: string, label?: string, w = width) => {
536 const txt = cleanHe(s, nk);
537 if (!txt) return null;
538 const lines = wrap(label ? `${label} ${txt}` : txt, w);
539 return (
540 <Box key={k} flexDirection="column" alignItems="flex-end">
541 {lines.map((ws, li) =>
542 label && li === 0
543 ? <Box flexDirection="row">
544 <Text color={color ?? BODY}>{order(ws.slice(1))} </Text>
545 <Text bold color={color ?? BODY}>{order(ws.slice(0, 1))}</Text>
546 </Box>
547 : <Text wrap="truncate" color={color ?? BODY}>{order(ws)}</Text>)}
548 </Box>
549 );
550 };
551 const en = (s: string, k: string, color?: string, label?: string) => {
552 const txt = cleanText(s);
553 if (!txt) return null;
554 return (
555 <Box key={k} flexDirection="row">
556 {label ? <Text bold dimColor={!color} color={color ?? BODY}>{label} </Text> : null}
557 <Text dimColor={!color} color={color ?? BODY}>{txt}</Text>
558 </Box>
559 );
560 };
561 // A bold chapter heading, right-aligned like the Hebrew under it.
562 const heading = (s: string, k: string) => (
563 <Box key={k} flexDirection="column" alignItems="flex-end">
564 <Text bold color={ACCENT}>{order(s.split(" "))}</Text>
565 </Box>
566 );
567
568 // A line of the body drawn as terminal text; a pair puts the English in
569 // the left half and the Hebrew in the right.
570 const half = Math.max(10, Math.floor((width - 2) / 2));
571 const draw = (l: Line, k: string) =>
572 l.kind === "gap" ? <Text key={k}> </Text>
573 : l.kind === "heading" ? heading(l.text, k)
574 : l.kind === "he" ? he(l.text, k, l.rashi ? RASHI : undefined, l.label)
575 : l.kind === "en" ? en(l.text, k, l.rashi ? RASHI : undefined, l.label)
576 : (
577 <Box key={k} flexDirection="row" justifyContent="space-between">
578 <Box width={half} flexDirection="column">{en(l.en, `${k}e`, l.rashi ? RASHI : undefined, l.enLabel)}</Box>
579 <Box width={half} flexDirection="column">{he(l.he, `${k}h`, l.rashi ? RASHI : undefined, l.label, half)}</Box>
580 </Box>
581 );
582
583 // The body's lines in the Desktop app: one SVG with the Hebrew font in it,
584 // or text when the font isn't at hand or the page is too big for an SVG.
585 const page = (lines: Line[], k: string) => {
586 if (e.surface === "desktop" && embedded) {
587 // About 7.8 CSS pixels a column, so the page draws near its real size
588 // and its text sits with the app's own.
589 const svgs = svgPages(lines.map((l) =>
590 l.kind === "he" ? { ...l, text: cleanHe(l.text, nk) }
591 : l.kind === "heading" ? { ...l, text: cleanHe(l.text, nk) }
592 : l.kind === "en" ? { ...l, text: cleanText(l.text) }
593 : l.kind === "pair" ? { ...l, he: cleanHe(l.he, nk), en: cleanText(l.en) } : l),
594 embedded, { width: (width + 1) * 7.8, scale: SIZES[prefs.size]! });
595 if (svgs && Svg) return svgs.map((src, i) => <Svg key={`${k}svg${i}`} source={src} alt="The day's text in Hebrew" />);
596 }
597 return lines.map((l, i) => draw(l, `${k}l${i}`));
598 };
599
600 // The settings page: each setting a row of choices; a press writes it.
601 const settings = () => {
602 const row = (field: string, title: string, choices: [string, string | boolean][], current: string | boolean, hint: string) => (
603 <Box key={`set-${field}`} flexDirection="column" marginBottom={1}>
604 <Text bold color={BODY}>{title}</Text>
605 <Box flexDirection="row" flexWrap="wrap">
606 {choices.map(([label, value]) => (
607 <Button key={`set-${field}-${label.replace(/\W+/g, "-").toLowerCase()}`} label={label}
608 variant={value === current ? "primary" : "secondary"} dimColor={value !== current}
609 onPress={() => value === current ? undefined : setPref($, field, value)} />
610 ))}
611 </Box>
612 <Text dimColor>{hint}</Text>
613 </Box>
614 );
615 const onOff: [string, boolean][] = [["On", true], ["Off", false]];
616 return [
617 row("hebrew_font", "Hebrew font", [["Frank Ruhl", "Frank Ruhl"], ["Shlomo", "Shlomo"], ["System", "System"]], prefs.font,
618 "Drawn in the Desktop app; installed and mapped in Ghostty. System leaves fonts alone."),
619 row("english", "English", [["Off", "Off"], ["Staggered", "Staggered"], ["Side by side", "Side by side"]],
620 Object.keys(ENGLISH).find((k) => ENGLISH[k] === prefs.english)!, "Staggered: under each paragraph. Side by side: English left, Hebrew right."),
621 row("nikkud", "Nikkud", onOff, prefs.nikkud, "The Hebrew with or without vowels."),
622 row("rashi", "Rashi", onOff, prefs.rashi, "Under each verse of Chumash and each passage of the Daf."),
623 row("wait_suggest", "While Claude works", [["After 45 seconds", "After 45 seconds"], ["After 2 minutes", "After 2 minutes"], ["Off", "Off"]],
624 String((po.wait_suggest ?? opts.wait_suggest) || "After 45 seconds"), "When a turn runs long, suggest learning on the line above the prompt (at most every 30 minutes)."),
625 row("text_size", "Text size", [["Small", "Small"], ["Medium", "Medium"], ["Large", "Large"]], prefs.size,
626 e.surface === "terminal" ? "For the Desktop app; a terminal uses its own size." : "The sidebar's text in the Desktop app."),
627 <Button key="settings-done" dimColor label="‹ Back to the text" onPress={() => update($, pageAtom, () => "read")} />,
628 ];
629 };
630
631 // The Library: collection › section › book › unit, one level at a time,
632 // each loaded when first opened. Breadcrumbs go back up; Continue goes to
633 // where a collection was last read; next and previous cross into the
634 // next book.
635 const library = () => {
636 // Hebrew in a label goes through the surface's ordering, like the text.
637 const heb = (x: string) => order(x.split(" "));
638 const pos = lp ?? {};
639 const go = (p: typeof pos) => update($, libPos, () => p);
640 const coll = pos.coll;
641 const shape = coll ? shapes?.[coll] : undefined;
642 if (coll && !shape) $.clock.after(0, () => void ensureShape($, coll));
643 const book = shape ? findBook(shape, pos.book) : undefined;
644 if (coll && book && pos.unit != null && lt?.ref !== textRef(book, pos.unit) && ls?.phase !== "error")
645 $.clock.after(0, () => void ensureLibText($, coll, book, pos.unit!));
646
647 const crumbs = [
648 <Button key="crumb-library" plain dimColor label="📚 Library" onPress={() => go({})} />,
649 ...(coll ? [<Text key="c1" dimColor> › </Text>, <Button key="crumb-coll" plain dimColor label={COLLS[coll].name} onPress={() => go({ coll })} />] : []),
650 ...(coll && pos.section && (shape?.sections.length ?? 0) > 1
651 ? [<Text key="c2" dimColor> › </Text>, <Button key="crumb-section" plain dimColor label={pos.section} onPress={() => go({ coll, section: pos.section })} />] : []),
652 ...(book ? [<Text key="c3" dimColor> › </Text>, <Button key="crumb-book" plain dimColor label={book.name} onPress={() => go({ coll, section: pos.section, book: book.title })} />] : []),
653 ];
654 const head = <Box key="crumbs" flexDirection="row" flexWrap="wrap" marginBottom={1}>{crumbs}</Box>;
655 const loading = ls && ls.phase === "loading" ? <Text key="loading" dimColor>Loading {ls.what}…</Text> : null;
656 const failed = ls && ls.phase === "error"
657 ? <Box key="failed" flexDirection="column"><Text color="red">Could not load {ls.what}: {ls.error}</Text>
658 <Button key="retry" variant="primary" label="Try again" onPress={async () => { await update($, libStatus, () => null); }} /></Box>
659 : null;
660 // "Continue: Berakhot 5" for a collection read before.
661 const cont = (c: Coll) => {
662 const l = ll?.[c];
663 if (!l) return null;
664 const s2 = shapes?.[c], b2 = s2 ? findBook(s2, l.book) : undefined;
665 const label = b2 ? `Continue ${unitLabel(b2, l.unit)}` : `Continue ${lastLabel(l)}`;
666 return <Button key={`continue-${c}`} variant="primary" label={label} onPress={() => continueLib($, c)} />;
667 };
668
669 // Collections.
670 if (!coll) return [
671 head,
672 ...COLL_ORDER.map((c) => (
673 <Box key={`coll-${c}`} flexDirection="column" marginBottom={1}>
674 <Box flexDirection="row">
675 <Button key={`open-${c}`} dimColor label={`${COLLS[c].name} · ${heb(COLLS[c].he)}`} onPress={() => go({ coll: c })} />
676 {cont(c)}
677 </Box>
678 <Text dimColor>{COLLS[c].blurb}</Text>
679 </Box>
680 )),
681 ];
682 if (!shape) return [head, failed ?? loading ?? <Text key="wait" dimColor>Loading {COLLS[coll].name}…</Text>];
683
684 // Sections (sedarim, sefarim); skipped when there is only one.
685 const section = pos.section ?? (shape.sections.length === 1 ? shape.sections[0]!.name : undefined);
686 if (!section) return [
687 head,
688 <Box key="cont" flexDirection="row">{cont(coll)}</Box>,
689 ...shape.sections.map((sec) => (
690 <Button key={`section-${sec.name.replace(/\W+/g, "-")}`} dimColor label={`${sec.name} · ${heb(sec.he)} (${sec.books.length})`}
691 onPress={() => go({ coll, section: sec.name })} />
692 )),
693 ];
694
695 // Books (masechtos, hilchos).
696 if (!book) {
697 const sec = shape.sections.find((x) => x.name === section);
698 return [
699 head,
700 ...(sec?.books ?? []).map((b) => (
701 <Button key={`book-${b.title.replace(/\W+/g, "-")}`}
702 label={`${b.name} · ${heb(b.he)} (${b.last - b.first + 1} ${COLLS[coll].unit === "daf" ? "dapim" : "perakim"})`}
703 variant={ll?.[coll]?.book === b.title ? "primary" : "secondary"} dimColor={ll?.[coll]?.book !== b.title}
704 onPress={() => go({ coll, section, book: b.title })} />
705 )),
706 ];
707 }
708
709 // Units (perakim, dapim): a grid, the last one read marked.
710 if (pos.unit == null) {
711 const lastHere = ll?.[coll]?.book === book.title ? ll[coll]!.unit : undefined;
712 return [
713 head,
714 <Text key="pick" dimColor>{book.name} · {heb(book.he)}: pick a {COLLS[coll].unit}</Text>,
715 <Box key="grid" flexDirection="row" flexWrap="wrap">
716 {Array.from({ length: book.last - book.first + 1 }, (_, i) => book.first + i).map((u) => (
717 <Button key={`unit-${u}`} label={heb(unitName(coll, u).split(" ")[1]!)}
718 variant={u === lastHere ? "primary" : "secondary"} dimColor={u !== lastHere}
719 onPress={() => openUnit($, coll, book, u)} />
720 ))}
721 </Box>,
722 ];
723 }
724
725 // Reading: the unit's text, with previous and next across books.
726 const unit = pos.unit;
727 const prev = step(shape, book.title, unit, -1), next = step(shape, book.title, unit, 1);
728 const nav = (where: "top" | "end") => (
729 <Box key={`libnav-${where}`} flexDirection="row" justifyContent="space-between">
730 {prev ? <Button key={`lib-prev-${where}`} plain dimColor hotkey={where === "end" ? "k" : undefined}
731 label={`‹ ${unitLabel(prev.book, prev.unit)}`} onPress={() => openUnit($, coll, prev.book, prev.unit)} /> : <Text> </Text>}
732 <Text dimColor>{unitLabel(book, unit)}</Text>
733 {next ? <Button key={`lib-next-${where}`} plain hotkey={where === "end" ? "j" : undefined} variant="primary"
734 label={`${unitLabel(next.book, next.unit)} ›`} onPress={() => openUnit($, coll, next.book, next.unit)} /> : <Text dimColor>end ✓</Text>}
735 </Box>
736 );
737 const part = lt?.ref === textRef(book, unit) ? lt.part : null;
738 const lines = part ? (part.sections ?? []).flatMap((_, i) => linesFor(part, i, { english: prefs.english, rashi: prefs.rashi })) : [];
739 return [
740 head,
741 nav("top"),
742 ...(part ? [<Text key="ltitle" color={TITLE} bold>{part.title}</Text>, <Text key="lsp"> </Text>]
743 : [failed ?? loading ?? <Text key="lwait" dimColor>Loading {unitLabel(book, unit)}…</Text>]),
744 ...(part ? page(lines, "lib") : []),
745 nav("end"),
746 ];
747 };
748
749 const openTab = async (id: TabId | null) => {
750 await update($, tab, () => id);
751 await update($, pageAtom, () => "read");
752 if (id) await markOpened($, id);
753 };
754
755 // Today: a menu of the day's sections, each with what it is today.
756 const todayMenu = (shown: [TabId, string][]) => [
757 <Text key="today-title" bold color={BODY}>Today's learning</Text>,
758 <Text key="today-sp"> </Text>,
759 ...shown.map(([id, label], i) => (
760 <Box key={`today-${id}`} flexDirection="column" marginBottom={1}>
761 <Button key={`tab-${id}`} dimColor label={label} hotkey={String(i + 1)} onPress={() => openTab(id)} />
762 <Text dimColor wrap="truncate"> {d!.parts[id]?.[0]?.title ?? ""}</Text>
763 </Box>
764 )),
765 ];
766
767 const body = () => {
768 if (pg === "settings") return settings();
769 if (pg === "library") return library();
770 if (!d || d.key !== todayKey()) {
771 if (st?.phase === "error") return <Text color="red">Could not load: {st.error}</Text>;
772 return <Text dimColor>Loading today's text… (the first fetch takes a little while)</Text>;
773 }
774 const shown = shownTabs(d);
775 // No section chosen (or one hidden today, or kept from an older build): the menu.
776 const ti = shown.findIndex(([id]) => id === t);
777 if (ti < 0) return todayMenu(shown);
778 const tabId = shown[ti]![0];
779 const parts = d.parts[tabId] ?? [];
780 // Back to the menu, and on to the day's previous or next section.
781 const crumbs = (
782 <Box key="today-crumbs" flexDirection="row" marginBottom={1}>
783 <Button key="crumb-today" plain dimColor label="📅 Today" onPress={() => openTab(null)} />
784 <Text dimColor> › </Text><Text color={BODY}>{shown[ti]![1]}</Text>
785 </Box>
786 );
787 const prevTab = shown[ti - 1], nextTab = shown[ti + 1];
788 const dayNav = (
789 <Box key="day-nav" flexDirection="row" justifyContent="space-between" marginTop={1}>
790 {prevTab ? <Button key="day-prev" plain dimColor label={`‹ ${prevTab[1]}`} onPress={() => openTab(prevTab[0])} /> : <Text> </Text>}
791 {nextTab ? <Button key="day-next" variant="primary" label={`${nextTab[1]} ›`} onPress={() => openTab(nextTab[0])} />
792 : <Button key="day-done" variant="primary" label="Today's menu ›" onPress={() => openTab(null)} />}
793 </Box>
794 );
795 if (!parts.length) return [crumbs, <Text key="none" dimColor>Nothing listed for this today.</Text>, dayNav];
796 return [crumbs, ...parts.map((p, pi) => {
797 const sections = p.sections ?? [];
798 const n = sections.length;
799 const at = Math.min(pk?.key === d.key ? pk.at[tabId] ?? 0 : 0, Math.max(n - 1, 0));
800 const go = (i: number) => update($, perek, (v) =>
801 ({ key: d.key, at: { ...(v?.key === d.key ? v.at : {}), [tabId]: i } }));
802 // Previous and next section (perek, amud), above the text and below it.
803 const nav = (where: "top" | "end") => n > 1 ? (
804 <Box key={`${pi}nav-${where}`} flexDirection="row" justifyContent="space-between">
805 {at > 0
806 ? <Button key={`prev-${where}`} plain dimColor hotkey={where === "end" ? "k" : undefined}
807 label={`‹ ${p.unit} ${sections[at - 1]!.short}`} onPress={() => go(at - 1)} />
808 : <Text> </Text>}
809 <Text dimColor>{p.unit} {at + 1} of {n}</Text>
810 {at < n - 1
811 ? <Button key={`next-${where}`} hotkey={where === "end" ? "j" : undefined}
812 variant="primary" label={`next ${p.unit} ${sections[at + 1]!.short} ›`} onPress={() => go(at + 1)} />
813 : <Text dimColor>done ✓</Text>}
814 </Box>
815 ) : null;
816 const empty = !p.he.length && !p.en.length;
817 return (
818 <Box key={`p${pi}`} flexDirection="column" marginBottom={1}>
819 <Text color={TITLE} bold>{p.title}</Text>
820 {empty && <Text dimColor>Text unavailable from Shafeh for this reading:</Text>}
821 {empty && (p.chabad || p.link) && <Text dimColor>{p.chabad || p.link}</Text>}
822 <Text> </Text>
823 {nav("top")}
824 {page(linesFor(p, at, { english: prefs.english, rashi: prefs.rashi }), `p${pi}`)}
825 {nav("end")}
826 </Box>
827 );
828 }), dayNav];
829 };
830
831 const hebDate = d?.hebrew ? cleanHe(d.hebrew, nk) : "";
832 // Missing text hides its tab, so its "... text: 404" line says nothing useful.
833 const issues = (d?.errors ?? []).filter((x) => !/ text: /.test(x));
834 // The header: date, tabs, toggles. Rows are packed here (a Button draws as
835 // "[ label ]", a plain one as "k: label") so the header's height is known.
836 const pack = <T,>(items: T[], w: (x: T) => number) => {
837 const rows: T[][] = [];
838 let row: T[] = [], n = 0;
839 for (const x of items) {
840 if (row.length && n + w(x) > width + 1) { rows.push(row); row = []; n = 0; }
841 row.push(x); n += w(x);
842 }
843 if (row.length) rows.push(row);
844 return rows;
845 };
846 // Where to go: today's learning, the Library, the settings. The current one is marked.
847 const navItems: [string, string, "read" | "library" | "settings", string][] = [
848 ["today", "📅 Today", "read", "t"], ["library", "📚 Library", "library", "l"], ["settings", "⚙ Settings", "settings", "s"],
849 ];
850 const navRows = pack(navItems, ([, label]) => label.length + 4);
851 const header = [
852 <Box key="date" flexDirection="row" justifyContent="space-between">
853 <Text color={ACCENT} bold wrap="truncate">✡ {d?.title ?? "Daily Learning"}</Text>
854 {hebDate ? <Text color={ACCENT} wrap="truncate">{order(hebDate.split(" "))}</Text> : null}
855 </Box>,
856 ...navRows.map((row, r) => (
857 <Box key={`nav${r}`} flexDirection="row">
858 {row.map(([key, label, to, hotkey]) => (
859 <Button key={key} label={label} hotkey={hotkey}
860 variant={pg === to ? "primary" : "secondary"} dimColor={pg !== to}
861 onPress={() => to === "read" && pg === "read" ? openTab(null) : update($, pageAtom, () => to)} />
862 ))}
863 </Box>
864 )),
865 e.surface === "terminal" ? <Text key="rule" dimColor>{"─".repeat(width)}</Text> : <Text key="rule"> </Text>,
866 ];
867
868 // In the terminal the header stays put: it is drawn over the body at the
869 // window's current top (the pane redraws as it scrolls), on a layer of
870 // spaces that blanks the text scrolling beneath it, and a spacer of the
871 // same height keeps the body's first rows clear of it.
872 if (e.surface === "terminal") {
873 const top = e.props.scroll?.offset ?? 0;
874 const tall = header.length; // not `h`: that name is JSX's element factory
875 return (
876 <Box flexDirection="column">
877 {Array.from({ length: tall }, (_, i) => <Text key={`gap${i}`}> </Text>)}
878 {body()}
879 {issues.length ? <Text dimColor>Issues: {issues.join("; ")}</Text> : null}
880 <Box key="blank" position="absolute" top={top} left={0} flexDirection="column">
881 {Array.from({ length: tall }, (_, i) => <Text key={`blank${i}`}>{" ".repeat(width + 1)}</Text>)}
882 </Box>
883 <Box key="header" position="absolute" top={top} left={0} flexDirection="column" width={width + 1}>
884 {header}
885 </Box>
886 </Box>
887 );
888 }
889 return (
890 <Box flexDirection="column">
891 {header}
892 {body()}
893 {issues.length ? <Text dimColor>Issues: {issues.join("; ")}</Text> : null}
894 </Box>
895 );
896 });
897};
898hooks/data.ts 198 lines1// The day's learning, shaped for drawing. Pure: the fetching happens in
2// register.tsx, the one file the engine lets call $.
3// - the band: Shafeh Today;
4// - the sidebar: scripts/dl.py --json --full, shaped into a Day.
5
6import type { Day, Part, Section, TabId } from "../types";
7import { gematria } from "./hebrew";
8import type { Line } from "./svg";
9
10// Bump when the provider or Day shape changes so old cached readings refetch.
11export const DAY_V = 9;
12
13// What the band shows: the Hebrew date and one [label, ref] row per section.
14export type Brief = {
15 heb: { hd: number; hm: string; hy: number; hebrew: string; events: string[] };
16 sections: [string, string][];
17};
18
19// The local Gregorian date as YYYY-MM-DD: what caches are keyed by.
20export function todayKey(d = new Date()) {
21 const p = (n: number) => String(n).padStart(2, "0");
22 return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
23}
24
25// ---- band ---------------------------------------------------------------
26export const calendarUrl = (d: Date) => `https://shafeh.org/api/v1/today?date=${todayKey(d)}`;
27
28export function briefFrom(j: any): Brief {
29 const h = j.hebrew_date ?? {};
30 const labels: Record<string, string> = { chitas_chumash: "Chumash", tehillim: "Tehillim", chitas_tanya: "Tanya",
31 rambam: "Rambam ×3", rambam_1: "Rambam ×1", hayom_yom: "Hayom Yom", daf_yomi: "Daf Yomi" };
32 return {
33 heb: { hd: h.day, hm: h.month_name, hy: h.year, hebrew: h.hebrew ?? "", events: j.holiday ? [j.holiday.english] : [] },
34 sections: (j.limudim ?? []).filter((r: any) => labels[r.key]).map((r: any) => [labels[r.key], r.value]),
35 };
36}
37
38// ---- sidebar ------------------------------------------------------------
39// Sefaria nests chapters as arrays of arrays; flatten to paragraphs.
40function flat(v: unknown): string[] {
41 if (v == null) return [];
42 if (Array.isArray(v)) return v.flatMap(flat);
43 return [String(v)];
44}
45
46function part(title: string, s: any, text: any): Part {
47 return { title, link: s?.link, chabad: s?.chabad, he: flat(text?.he), en: flat(text?.en) };
48}
49
50// Each verse of a Chumash reading numbered as Rambam's halachot are ("כא.",
51// "21."), with a heading where each chapter starts (פרק ד) as Rambam's perakim
52// have. From the ref's start ("Genesis 2:20-3:21") and the text's chapters,
53// which a range spanning several needs; none when the counts don't add up.
54export function verseLabels(ref: string, text: any): NonNullable<Part["labels"]> | undefined {
55 const m = /(\d+):(\d+)(-\d+:\d+)?(?:-\d+)?$/.exec(ref ?? "");
56 const verses = flat(text?.he).length;
57 if (!m || !verses) return undefined;
58 const chapters: number[] = Array.isArray(text?.he_chapters) && text.he_chapters.length
59 ? text.he_chapters.map((c: unknown[]) => c.length)
60 : m[3] ? [] : [verses];
61 if (chapters.reduce((a, b) => a + b, 0) !== verses) return undefined;
62 const out: NonNullable<Part["labels"]> = [];
63 chapters.forEach((n, ci) => {
64 const c = Number(m[1]) + ci;
65 for (let k = 0; k < n; k++) {
66 const v = (ci === 0 ? Number(m[2]) : 1) + k;
67 out.push({ he: `${gematria(v)}.`, en: `${v}.`, ...(k === 0 ? { heading: `פרק ${gematria(c)}` } : {}) });
68 }
69 });
70 return out;
71}
72
73// A Rambam reading, one perek at a time, its halachot numbered; the first
74// perek's number comes from the ref ("Mishneh Torah, Damages to Property 12-14" → 12).
75function rambamPart(title: string, r: any, chabad?: string): Part {
76 const p = part(title, { ...r, chabad }, r.text);
77 if (r.chapters?.length) {
78 p.sections = r.chapters.map((c: any): Section => ({ name: `${c.name} · פרק ${gematria(c.number)}`,
79 short: gematria(c.number), he: c.he, en: c.en }));
80 p.he = p.sections!.flatMap((s) => s.he);
81 p.en = p.sections!.flatMap((s) => s.en);
82 p.unit = "perek";
83 p.numbered = true;
84 return p;
85 }
86 const he: string[][] = r.text?.he_chapters ?? [];
87 const en: string[][] = r.text?.en_chapters ?? [];
88 const first = Number(/(\d+)(?:-\d+)?$/.exec(r.ref ?? "")?.[1] ?? 1);
89 if (he.length) {
90 p.sections = he.map((h, i): Section => ({
91 name: `פרק ${gematria(first + i)}`, short: gematria(first + i), he: h, en: en[i] ?? [],
92 }));
93 p.unit = "perek";
94 p.numbered = true;
95 }
96 return p;
97}
98
99// The daf, one amud at a time ("18a" → דף יח., "18b" → דף יח:), each passage
100// with its Rashi.
101function dafPart(d: any): Part {
102 const amudim: any[] = d.amudim ?? [];
103 const p: Part = { title: `Daf Yomi · ${d.display}`, link: d.link, he: [], en: [] };
104 if (!amudim.length) return p;
105 p.sections = amudim.map((a): Section => {
106 const m = /^(\d+)([ab])$/.exec(a.amud ?? "");
107 const short = m ? `${gematria(Number(m[1]))}${m[2] === "a" ? "." : ":"}` : String(a.amud ?? "");
108 return { name: `דף ${short}`, short, he: a.he ?? [], en: a.en ?? [], rashi: a.rashi_he ?? [], notes: a.rashi_notes ?? [] };
109 });
110 p.he = amudim.flatMap((a) => a.he ?? []);
111 p.en = amudim.flatMap((a) => a.en ?? []);
112 p.unit = "amud";
113 return p;
114}
115
116// dl.py's --json output as the Day the sidebar draws, one list of parts per tab.
117export function toDay(key: string, j: any): Day {
118 const s = j.sections || {};
119 const ch = s.chumash, rb = s.rambam || {};
120 const labels = ch && verseLabels(ch.ref, ch.text);
121 const parts: Record<TabId, Part[]> = {
122 chumash: ch ? [{
123 ...part(`${ch.parsha} · ${ch.aliyah} (${ch.ref}) with Rashi`, ch, ch.text),
124 ...(labels ? { labels } : {}),
125 ...(ch.rashi ? { rashi: { he: ch.rashi.he_verses || [], en: ch.rashi.en_verses || [] } } : {}),
126 }] : [],
127 tehillim: s.tehillim ? [part(`Tehillim ${s.tehillim.ref} (day ${s.tehillim.day_of_month})`, s.tehillim, s.tehillim.text)] : [],
128 // "Tanya, Part IV; Iggeret HaKodesh 25:1-5" → "Iggeret HaKodesh 25:1-5"
129 tanya: s.tanya ? [part(`Tanya · ${s.tanya.display}${s.tanya.ref && s.tanya.ref !== s.tanya.display ? ` (${String(s.tanya.ref).split("; ").pop()})` : ""}`, s.tanya, s.tanya.text)] : [],
130 rambam1: rb.one_perek ? [rambamPart(`Rambam ×1 · ${rb.one_perek.display}`, rb.one_perek, rb.chabad)] : [],
131 rambam3: rb.three_perakim ? [rambamPart(`Rambam ×3 · ${rb.three_perakim.display}`, rb.three_perakim, rb.chabad)] : [],
132 hayom: s.hayom_yom ? [part(s.hayom_yom.ref, s.hayom_yom, s.hayom_yom.text)] : [],
133 daf: s.daf_yomi ? [dafPart(s.daf_yomi)] : [],
134 };
135 const hd = j.hebrew || {};
136 return {
137 v: DAY_V,
138 key,
139 title: `${j.weekday} ${j.gregorian} · ${hd.hd} ${hd.hm} ${hd.hy}`,
140 hebrew: hd.hebrew || "",
141 parts,
142 errors: j.errors || [],
143 };
144}
145
146// How the body shows English and Rashi (the sidebar's settings).
147export type English = "off" | "staggered" | "side";
148export type LineOptions = { english: English; rashi: boolean };
149
150// What a part draws, line by line: for a sectioned part, section `at` under
151// its heading; otherwise verse by verse. Each paragraph is followed by its
152// English (staggered: under it; side: beside it) and its Rashi.
153export function linesFor(p: Part, at: number, opt: LineOptions): Line[] {
154 const out: Line[] = [];
155 const showEn = opt.english !== "off";
156 const para = (he: string[], en: string[], rashi: string[][] | undefined, rashiEn: string[][] | undefined,
157 numbered: boolean, labels?: Part["labels"]) => {
158 const paired = he.length === en.length;
159 // Rashi lines up with the paragraphs when it has no more entries than they
160 // do: Sefaria leaves the list short when the last ones have no Rashi.
161 const r = opt.rashi && rashi && rashi.length <= he.length ? rashi : null;
162 he.forEach((h, i) => {
163 if (labels?.[i]?.heading) out.push({ kind: "heading", text: labels[i]!.heading! });
164 const label = numbered ? `${gematria(i + 1)}.` : labels?.[i]?.he;
165 const enLabel = numbered ? `${i + 1}.` : labels?.[i]?.en;
166 if (opt.english === "side" && paired) {
167 out.push({ kind: "pair", he: h, en: en[i]!, ...(label ? { label, enLabel } : {}) });
168 } else {
169 out.push({ kind: "he", text: h, ...(label ? { label } : {}) });
170 if (showEn && paired) out.push({ kind: "en", text: en[i]!, ...(enLabel ? { label: enLabel } : {}) });
171 }
172 const rh = r?.[i] ?? [], re = showEn && r ? rashiEn?.[i] ?? [] : [];
173 if (opt.english === "side" && rh.length && rh.length === re.length) {
174 rh.forEach((c, j) => out.push({ kind: "pair", he: c, en: re[j]!, rashi: true }));
175 } else {
176 rh.forEach((c) => out.push({ kind: "he", text: c, rashi: true }));
177 re.forEach((c) => out.push({ kind: "en", text: c, rashi: true }));
178 }
179 out.push({ kind: "gap" });
180 });
181 if (showEn && !paired) en.forEach((x) => out.push({ kind: "en", text: x }, { kind: "gap" }));
182 // Rashi that did not line up with the paragraphs still shows, after them.
183 if (opt.rashi && rashi && !r) rashi.flat().forEach((c) => out.push({ kind: "he", text: c, rashi: true }));
184 };
185 if (p.sections?.length) {
186 const s = p.sections[Math.min(Math.max(at, 0), p.sections.length - 1)]!;
187 out.push({ kind: "heading", text: s.name });
188 para(s.he, s.en, s.rashi, undefined, !!p.numbered);
189 if (opt.rashi && s.notes?.length) {
190 out.push({ kind: "heading", text: "רש״י" });
191 s.notes.forEach((text) => out.push({ kind: "he", text, rashi: true }, { kind: "gap" }));
192 }
193 } else {
194 para(p.he, p.en, p.rashi?.he, p.rashi?.en, false, p.labels);
195 }
196 return out;
197}
198hooks/library.ts 82 lines1// Shafeh's library indexes and bundled text, fetched lazily by register.tsx.
2import type { Coll, LibBook, LibSection, LibShape, Part, Section } from "../types";
3import { gematria } from "./hebrew";
4export type { Coll, LibBook, LibPos, LibSection, LibShape } from "../types";
5
6export const COLLS: Record<Coll, { name: string; he: string; shape: string; unit: "perek" | "daf"; blurb: string }> = {
7 mishnah: { name: "Mishnayos", he: "משניות", shape: "mishnah", unit: "perek", blurb: "Six sedarim, 63 masechtos" },
8 bavli: { name: "Shas", he: "ש״ס בבלי", shape: "shas", unit: "daf", blurb: "Talmud Bavli, daf by daf, with Rashi" },
9 mt: { name: "Mishneh Torah", he: "משנה תורה", shape: "rambam", unit: "perek", blurb: "The Rambam's 14 sefarim, perek by perek" },
10};
11export const COLL_ORDER: Coll[] = ["mishnah", "bavli", "mt"];
12
13// Keep titles stable across the provider change, so existing Continue bookmarks survive.
14const LEGACY_NAMES: Record<string, string> = {
15 berachos: "Berakhot", shabbos: "Shabbat", sukkah: "Sukkah", taanis: "Taanit", yevamos: "Yevamot",
16 kesubos: "Ketubot", gitin: "Gittin", bava_basra: "Bava Batra", makkos: "Makkot", shevuos: "Shevuot",
17 horiyos: "Horayot", horayos: "Horayot", menachos: "Menachot", bechoros: "Bekhorot", arachin: "Arakhin", kerisos: "Keritot",
18 midos: "Middot", middos: "Middot", nedarim: "Nedarim", kilayim: "Kilayim", sheviis: "Sheviit", terumos: "Terumot",
19 maasros: "Maasrot", chalah: "Challah", bikurim: "Bikkurim", eduyos: "Eduyot", avos: "Avot",
20 keilim: "Kelim", ohalos: "Oholot", negaim: "Negaim", taharos: "Tahorot", mikvaos: "Mikvaot",
21 machshirin: "Makhshirin", tvul_yom: "Tevul Yom", uktzin: "Oktzin",
22};
23export function parseShape(coll: Coll, json: any): LibShape {
24 const sections: LibSection[] = [];
25 for (const s of (coll === "mt" ? json.sefarim : json.sedarim) ?? []) {
26 const name = coll === "mt" ? `Sefer ${s.sefer}` : `Seder ${s.en}`;
27 const books: LibBook[] = (coll === "mt" ? s.sections : s.masechtos).map((b: any) => {
28 const key = b.key ?? b.slug;
29 const en = LEGACY_NAMES[key] ?? b.en ?? b.name;
30 const title = coll === "mishnah" && key === "avos" ? "Pirkei Avot" : coll === "mt" ? `Mishneh Torah, ${en}` : coll === "mishnah" ? `Mishnah ${en}` : en;
31 return { key, title, he: b.he, name: en, section: name,
32 first: coll === "bavli" ? parseInt(b.first_amud, 10) : 1,
33 last: coll === "bavli" ? parseInt(b.last_amud, 10) : (b.perakim ?? b.chapters) };
34 });
35 sections.push({ name, he: s.he, books });
36 }
37 return { sections };
38}
39
40export const books = (shape: LibShape) => shape.sections.flatMap((s) => s.books);
41export const findBook = (shape: LibShape, title?: string) => books(shape).find((b) => b.title === title);
42
43// A unit's name: פרק ג, or דף ה.
44export const unitName = (coll: Coll, n: number) => `${COLLS[coll].unit === "daf" ? "דף" : "פרק"} ${gematria(n)}`;
45// The same in English, for buttons and titles: "Berakhot 5", "Sabbath 3".
46export const unitLabel = (b: LibBook, n: number) => `${b.name} ${n}`;
47
48// The next or previous unit, across books: after a book's last unit comes the
49// next book's first, and before its first, the previous book's last.
50export function step(shape: LibShape, title: string, unit: number, dir: 1 | -1): { book: LibBook; unit: number } | null {
51 const all = books(shape);
52 const i = all.findIndex((b) => b.title === title);
53 if (i < 0) return null;
54 const b = all[i]!;
55 const u = unit + dir;
56 if (u >= b.first && u <= b.last) return { book: b, unit: u };
57 const nb = all[i + dir];
58 return nb ? { book: nb, unit: dir > 0 ? nb.first : nb.last } : null;
59}
60
61// Stable display/cache identity; requests use the book's explicit corpus key.
62export const textRef = (b: LibBook, unit: number) => `${b.title} ${unit}`;
63
64export function libPart(coll: Coll, b: LibBook, unit: number, text: any): Part {
65 const title = `${COLLS[coll].name} · ${unitLabel(b, unit)}`;
66 const path = coll === "mt" ? "rambam" : coll === "mishnah" ? "mishnah" : "shas";
67 const link = coll === "mishnah" ? "https://shafeh.org/api/v1/mishnah/" + b.key + "/" + unit
68 : `https://shafeh.org/${path}/${b.key}/${coll === "bavli" ? text.amudim[0].daf : unit}`;
69 if (coll !== "bavli") {
70 const values = coll === "mt" ? text.halachos : text.mishnayos;
71 const s: Section = { name: `${b.he} ${unitName(coll, unit)}`, short: gematria(unit),
72 he: values.map((v: any) => v.text ?? v.he), en: values.some((v: any) => v.english) ? values.map((v: any) => v.english ?? "") : [] };
73 return { title, link, he: s.he, en: s.en, sections: [s], numbered: true };
74 }
75 const sections: Section[] = text.amudim.map((a: any) => {
76 const short = `${gematria(unit)}${a.daf.endsWith("a") ? "." : ":"}`;
77 return { name: `${b.he} דף ${short}`, short, he: a.lines.map((v: any) => v.he), en: [],
78 notes: (a.rashi ?? []).map((r: any) => `${r.d} — ${r.c}`) };
79 });
80 return { title, link, he: sections.flatMap((s) => s.he), en: [], sections, unit: "amud" };
81}
82hooks/hebrew.ts 108 lines1// Hebrew text for a terminal: cleanup, mark order, wrapping, and the three ways
2// a line of Hebrew is ordered for the surface that draws it. Pure functions.
3
4// Combining marks: te'amim (cantillation) and nikkud (vowels, dagesh, shin dots).
5const MARK = /[\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7]/;
6const TEAMIM = /[\u0591-\u05AF\u05BD]/g;
7const NIKKUD = /[\u05B0-\u05BC\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7]/g;
8const HEB = /[\u05D0-\u05EA]/;
9const MIRROR: Record<string, string> = { "(": ")", ")": "(", "[": "]", "]": "[", "{": "}", "}": "{", "<": ">", ">": "<" };
10
11// Sefaria text to plain text: no HTML, entities, or {ס}/{פ} section markers.
12export function cleanText(s: string) {
13 return s
14 .replace(/<br\s*\/?>/gi, " ")
15 .replace(/<[^>]+>/g, "")
16 .replace(/ | | | /g, " ")
17 .replace(/&/g, "&").replace(/"/g, '"').replace(/'|'/g, "'")
18 .replace(/&[a-z]+;/g, "")
19 .replace(/\{[\u05E1\u05E4]\}/g, "")
20 .replace(/\s+/g, " ")
21 .trim();
22}
23
24// Hebrew for display: te'amim and paseq dropped, nikkud kept or dropped, marks
25// in the order fonts expect.
26export function cleanHe(s: string, withNikkud: boolean) {
27 let t = cleanText(s).replace(TEAMIM, "").replace(/\s*\u05C0\s*/g, " ");
28 if (!withNikkud) t = t.replace(NIKKUD, "");
29 return markOrder(t);
30}
31
32// Unicode's canonical order puts a letter's vowel before its dagesh (בְּ is
33// bet, sheva, dagesh), but terminals don't reorder marks the way text shapers
34// do, and fonts place a dagesh or shin dot right only when it comes first.
35// So each letter's marks go: shin/sin dot, dagesh, rafe, then the rest.
36const MARK_RANK: Record<string, number> = { "\u05C1": 0, "\u05C2": 0, "\u05BC": 1, "\u05BF": 2 };
37const rank = (m: string) => MARK_RANK[m] ?? 3;
38export function markOrder(t: string) {
39 return t.replace(/([\u05D0-\u05EA\uFB1D-\uFB4F])([\u0591-\u05C7]+)/g, (_, base: string, marks: string) =>
40 base + [...marks].map((m, i) => [m, i] as const)
41 .sort((a, b) => rank(a[0]) - rank(b[0]) || a[1] - b[1]).map(([m]) => m).join(""));
42}
43
44// A number in Hebrew letters, as halachot and chapters are counted: יא, טו, טז, קכ.
45export function gematria(n: number) {
46 const units = ["", "א", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט"];
47 const tens = ["", "י", "כ", "ל", "מ", "נ", "ס", "ע", "פ", "צ"];
48 const hundreds = ["", "ק", "ר", "ש", "ת"];
49 const out = hundreds[Math.min(4, Math.floor(n / 100))] ?? "";
50 const rest = n % 100;
51 if (rest === 15) return out + "טו";
52 if (rest === 16) return out + "טז";
53 return out + tens[Math.floor(rest / 10)] + units[rest % 10];
54}
55
56// Base letters with their marks, so reversing keeps each vowel on its letter.
57export function clusters(w: string) {
58 const out: string[] = [];
59 for (const ch of w) {
60 if (MARK.test(ch) && out.length) out[out.length - 1] += ch;
61 else out.push(ch);
62 }
63 return out;
64}
65
66// Words into lines of at most `width` cells; marks take no cell.
67export function wrap(s: string, width: number) {
68 const lines: string[][] = [];
69 let line: string[] = [], n = 0;
70 for (const w of s.split(" ").filter(Boolean)) {
71 const c = clusters(w).length;
72 if (line.length && n + 1 + c > width) { lines.push(line); line = []; n = 0; }
73 n += (line.length ? 1 : 0) + c;
74 line.push(w);
75 }
76 if (line.length) lines.push(line);
77 return lines;
78}
79
80// Visual order for a terminal that draws everything left to right (Ghostty):
81// words right to left, letters inside a Hebrew word reversed, brackets
82// mirrored, numbers and Latin kept as is.
83export function visual(words: string[]) {
84 return words
85 .slice()
86 .reverse()
87 .map((w) => (HEB.test(w) ? clusters(w).reverse().map((c) => MIRROR[c] ?? c).join("") : w))
88 .join(" ");
89}
90
91// Visual order for a terminal that turns each word around itself (macOS
92// Terminal, which inside Claude Code gets the screen a word at a time): words
93// right to left, letters as written, and the punctuation at each end of a word
94// moved to the other end, mirrored, since the terminal leaves it where it is
95// sent. No direction controls (LRM, RLM, overrides): Terminal draws them as boxes.
96export function termVisual(words: string[]) {
97 const across = (p: string) => [...p].reverse().map((c) => MIRROR[c] ?? c).join("");
98 return words
99 .slice()
100 .reverse()
101 .map((w) => {
102 if (!HEB.test(w)) return w;
103 const m = /^([^\u05D0-\u05EA\uFB1D-\uFB4F]*)(.*?)([^\u05D0-\u05EA\uFB1D-\uFB4F\u0591-\u05C7]*)$/su.exec(w)!;
104 return across(m[3]!) + m[2] + across(m[1]!);
105 })
106 .join(" ");
107}
108hooks/svg.ts 162 lines1// The Desktop app's Hebrew: one SVG per reading, with the chosen font embedded,
2// so the app's own text engine shapes the nikkud and lays the lines right to
3// left. The terminal draws the same Line list as text (see register.tsx).
4
5import { ADVANCE } from "./font-metrics";
6
7// A bundled font: which (for its letter widths), and its WOFF as base64.
8export type FontKey = keyof typeof ADVANCE;
9export type EmbeddedFont = { key: FontKey; base64: string };
10
11// One line of the sidebar body, before it is drawn. A "pair" is a paragraph
12// with its English beside it (English on the left, Hebrew on the right).
13export type Line =
14 | { kind: "he"; text: string; label?: string; rashi?: boolean }
15 | { kind: "en"; text: string; label?: string; rashi?: boolean }
16 | { kind: "pair"; he: string; en: string; label?: string; enLabel?: string; rashi?: boolean }
17 | { kind: "heading"; text: string }
18 | { kind: "gap" };
19
20// How the page is drawn: its width in CSS pixels (the sidebar's, so the SVG
21// draws at about its real size) and a text-size factor (1 = medium).
22export type PageOptions = { width: number; scale: number };
23
24// An Svg element's source is capped at 131072 characters.
25export const SVG_LIMIT = 131072;
26
27const PAD = 6;
28const GUTTER = 18;
29const EN_EM = 0.5; // the system sans: about half an em a character
30
31const MARK = /[\u0591-\u05C7]/;
32const xml = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
33
34// A Hebrew word's width in ems, by the font's own advances; marks take none.
35function ems(w: string, adv: Record<number, number>) {
36 let n = 0;
37 for (const ch of w) if (!MARK.test(ch)) n += adv[ch.codePointAt(0)!] ?? 0.55;
38 return n;
39}
40
41// Words into lines no wider than `max`, each word measured by `measure`.
42function fit(words: string[], max: number, measure: (w: string) => number, space: number) {
43 const lines: string[][] = [];
44 let line: string[] = [], n = 0;
45 for (const w of words) {
46 const c = measure(w);
47 if (line.length && n + space + c > max) { lines.push(line); line = []; n = 0; }
48 n += (line.length ? space : 0) + c;
49 line.push(w);
50 }
51 if (line.length) lines.push(line);
52 return lines;
53}
54
55const words = (text: string, label?: string) => [...(label ? [label] : []), ...text.split(" ").filter(Boolean)];
56
57// The page as SVGs: one when it fits an Svg element, else several, split
58// between paragraphs, each with the font. Null when even one paragraph alone
59// is too big (the caller then draws it as text).
60export function svgPages(lines: Line[], font: EmbeddedFont, opt: PageOptions = { width: 560, scale: 1 }): string[] | null {
61 const adv = ADVANCE[font.key];
62 const W = Math.max(280, Math.round(opt.width));
63 // Sizes chosen to sit with the app's own ~14px text: Hebrew a little larger,
64 // since a Hebrew face looks smaller than a Latin one at the same size.
65 const s = opt.scale;
66 const HE = { size: 18 * s, line: 30 * s };
67 const EN = { size: 14 * s, line: 21 * s };
68 const HEADING = { size: 19 * s, line: 32 * s };
69 const GAP = 10 * s;
70 const at = (n: number) => Math.round(n);
71
72 const heLines = (text: string, label: string | undefined, width: number) =>
73 fit(words(text, label), width / HE.size, (w) => ems(w, adv), adv[0x20] ?? 0.3);
74 const enLines = (text: string, label: string | undefined, width: number) =>
75 fit(words(text, label), width / (EN.size * EN_EM), (w) => w.length, 1);
76 // Classes: h Hebrew, e English, t heading, r Rashi, b bold.
77 const text = (cls: string, ws: string[], first: boolean, label: string | undefined, x: number, y: number) => {
78 const head = label && first ? `<tspan class="b">${xml(ws[0]!)}</tspan> ` : "";
79 const rest = xml((label && first ? ws.slice(1) : ws).join(" "));
80 return `<text class="${cls}" x="${at(x)}" y="${at(y)}">${head}${rest}</text>`;
81 };
82
83 // Each paragraph (up to a gap) becomes a block of text drawn from y = 0.
84 type Block = { body: string[]; height: number };
85 const blocks: Block[] = [];
86 let cur: Block = { body: [], height: 0 };
87 const right = W - PAD;
88 const full = W - 2 * PAD;
89 const half = (full - GUTTER) / 2;
90 for (const l of lines) {
91 let y = cur.height;
92 if (l.kind === "gap") {
93 cur.height += GAP;
94 blocks.push(cur); cur = { body: [], height: 0 };
95 continue;
96 }
97 if (l.kind === "heading") {
98 y += HEADING.line;
99 cur.body.push(`<text class="t" x="${right}" y="${at(y - HEADING.line * 0.3)}">${xml(l.text)}</text>`);
100 } else if (l.kind === "he") {
101 heLines(l.text, l.label, full).forEach((ws, i) => {
102 y += HE.line;
103 cur.body.push(text(l.rashi ? "h r" : "h", ws, i === 0, l.label, right, y - HE.line * 0.3));
104 });
105 } else if (l.kind === "en") {
106 enLines(l.text, l.label, full).forEach((ws, i) => {
107 y += EN.line;
108 cur.body.push(text(l.rashi ? "e r" : "e", ws, i === 0, l.label, PAD, y - EN.line * 0.28));
109 });
110 } else {
111 // Side by side: both columns start on the same row; the taller sets the height.
112 const y0 = y;
113 const he = heLines(l.he, l.label, half);
114 const en = enLines(l.en, l.enLabel, half);
115 he.forEach((ws, i) => cur.body.push(text(l.rashi ? "h r" : "h", ws, i === 0, l.label, right, y0 + (i + 1) * HE.line - HE.line * 0.3)));
116 en.forEach((ws, i) => cur.body.push(text(l.rashi ? "e r" : "e", ws, i === 0, l.enLabel, PAD, y0 + (i + 1) * EN.line - EN.line * 0.28)));
117 y = y0 + Math.max(he.length * HE.line, en.length * EN.line);
118 }
119 cur.height = y;
120 }
121 if (cur.body.length || cur.height) blocks.push(cur);
122
123 const style =
124 `<style>` +
125 `@font-face{font-family:DLHebrew;src:url(data:font/woff;base64,${font.base64}) format("woff")}` +
126 `.h,.t{font-family:DLHebrew,"SF Hebrew","Arial Hebrew",serif;direction:rtl}` +
127 `.h{font-size:${at(HE.size)}px;fill:#1f1f1f}.t{font-size:${at(HEADING.size)}px;font-weight:bold;fill:#2b8aa6}` +
128 `.e{font-family:-apple-system,system-ui,sans-serif;font-size:${at(EN.size)}px;fill:#6b6b6b}` +
129 `.r{fill:#4b5bd6}.b{font-weight:bold}` +
130 `@media (prefers-color-scheme:dark){.h{fill:#e8e8e8}.e{fill:#a3a3a3}.r{fill:#b1b9f9}.t{fill:#62c4e0}}` +
131 `</style>`;
132 const svg = (parts: string[], height: number) => {
133 const h = Math.ceil(height + 2 * PAD);
134 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${h}" width="${W}" height="${h}">${style}` +
135 `<g transform="translate(0 ${PAD})">${parts.join("")}</g></svg>`;
136 };
137
138 // Pack the blocks into as few SVGs as fit.
139 const room = SVG_LIMIT - svg([], 0).length - 64;
140 const pages: string[] = [];
141 let parts: string[] = [], height = 0, size = 0;
142 for (const b of blocks) {
143 const g = `<g transform="translate(0 ${at(height)})">${b.body.join("")}</g>`;
144 if (g.length > room) return null;
145 if (size + g.length > room && parts.length) {
146 pages.push(svg(parts, height)); parts = []; height = 0; size = 0;
147 const g2 = `<g transform="translate(0 0)">${b.body.join("")}</g>`;
148 parts.push(g2); size += g2.length; height += b.height;
149 continue;
150 }
151 parts.push(g); size += g.length; height += b.height;
152 }
153 if (parts.length) pages.push(svg(parts, height));
154 return pages;
155}
156
157// The page as one SVG, or null when it needs more than one (tests, mostly).
158export function svgPage(lines: Line[], font: EmbeddedFont, opt?: PageOptions): string | null {
159 const pages = svgPages(lines, font, opt);
160 return pages && pages.length === 1 ? pages[0]! : null;
161}
162hooks/font-metrics.ts 262 lines1// Generated by scripts/make-woff.py from fonts/*.ttf: each character's advance
2// width, in ems, per bundled font, for wrapping Hebrew in the Desktop app.
3// Combining marks take no width; a character missing here is taken as 0.55em.
4export const ADVANCE: Record<"shlomo" | "frank", Record<number, number>> = {
5 shlomo: {
6 0x0020: 0.342,
7 0x0021: 0.433,
8 0x0022: 0.333,
9 0x0023: 0.743,
10 0x0024: 0.563,
11 0x0025: 0.861,
12 0x0026: 0.713,
13 0x0027: 0.171,
14 0x0028: 0.537,
15 0x0029: 0.537,
16 0x002A: 0.504,
17 0x002B: 0.833,
18 0x002C: 0.211,
19 0x002D: 0.321,
20 0x002E: 0.289,
21 0x002F: 0.501,
22 0x0030: 0.554,
23 0x0031: 0.554,
24 0x0032: 0.554,
25 0x0033: 0.554,
26 0x0034: 0.554,
27 0x0035: 0.554,
28 0x0036: 0.554,
29 0x0037: 0.554,
30 0x0038: 0.554,
31 0x0039: 0.554,
32 0x003A: 0.293,
33 0x003B: 0.289,
34 0x003C: 0.833,
35 0x003D: 0.833,
36 0x003E: 0.833,
37 0x003F: 0.523,
38 0x0040: 0.936,
39 0x0041: 0.664,
40 0x0042: 0.609,
41 0x0043: 0.633,
42 0x0044: 0.698,
43 0x0045: 0.585,
44 0x0046: 0.542,
45 0x0047: 0.698,
46 0x0048: 0.743,
47 0x0049: 0.33,
48 0x004A: 0.479,
49 0x004B: 0.638,
50 0x004C: 0.526,
51 0x004D: 0.871,
52 0x004E: 0.716,
53 0x004F: 0.736,
54 0x0050: 0.565,
55 0x0051: 0.742,
56 0x0052: 0.65,
57 0x0053: 0.53,
58 0x0054: 0.599,
59 0x0055: 0.704,
60 0x0056: 0.666,
61 0x0057: 0.931,
62 0x0058: 0.633,
63 0x0059: 0.625,
64 0x005A: 0.587,
65 0x005B: 0.32,
66 0x005C: 0.501,
67 0x005D: 0.32,
68 0x005E: 0.958,
69 0x005F: 0.5,
70 0x0060: 0.35,
71 0x0061: 0.512,
72 0x0062: 0.55,
73 0x0063: 0.47,
74 0x0064: 0.562,
75 0x0065: 0.495,
76 0x0066: 0.326,
77 0x0067: 0.53,
78 0x0068: 0.572,
79 0x0069: 0.303,
80 0x006A: 0.308,
81 0x006B: 0.539,
82 0x006C: 0.297,
83 0x006D: 0.855,
84 0x006E: 0.577,
85 0x006F: 0.548,
86 0x0070: 0.561,
87 0x0071: 0.542,
88 0x0072: 0.396,
89 0x0073: 0.409,
90 0x0074: 0.34,
91 0x0075: 0.569,
92 0x0076: 0.529,
93 0x0077: 0.783,
94 0x0078: 0.513,
95 0x0079: 0.53,
96 0x007A: 0.475,
97 0x007B: 0.624,
98 0x007C: 0.5,
99 0x007D: 0.624,
100 0x007E: 0.833,
101 0x05BE: 0.465,
102 0x05C3: 0.397,
103 0x05D0: 0.596,
104 0x05D1: 0.665,
105 0x05D2: 0.362,
106 0x05D3: 0.674,
107 0x05D4: 0.674,
108 0x05D5: 0.337,
109 0x05D6: 0.345,
110 0x05D7: 0.674,
111 0x05D8: 0.662,
112 0x05D9: 0.337,
113 0x05DA: 0.674,
114 0x05DB: 0.616,
115 0x05DC: 0.656,
116 0x05DD: 0.659,
117 0x05DE: 0.649,
118 0x05DF: 0.367,
119 0x05E0: 0.35,
120 0x05E1: 0.622,
121 0x05E2: 0.592,
122 0x05E3: 0.616,
123 0x05E4: 0.616,
124 0x05E5: 0.591,
125 0x05E6: 0.641,
126 0x05E7: 0.609,
127 0x05E8: 0.674,
128 0x05E9: 0.698,
129 0x05EA: 0.658,
130 0x05F3: 0.259,
131 0x05F4: 0.462,
132 },
133 frank: {
134 0x0020: 0.239,
135 0x0021: 0.285,
136 0x0022: 0.364,
137 0x0023: 0.497,
138 0x0024: 0.527,
139 0x0025: 0.859,
140 0x0026: 0.722,
141 0x0027: 0.212,
142 0x0028: 0.333,
143 0x0029: 0.333,
144 0x002A: 0.344,
145 0x002B: 0.532,
146 0x002C: 0.264,
147 0x002D: 0.343,
148 0x002E: 0.278,
149 0x002F: 0.32,
150 0x0030: 0.563,
151 0x0031: 0.47,
152 0x0032: 0.546,
153 0x0033: 0.545,
154 0x0034: 0.535,
155 0x0035: 0.529,
156 0x0036: 0.557,
157 0x0037: 0.52,
158 0x0038: 0.533,
159 0x0039: 0.557,
160 0x003A: 0.278,
161 0x003B: 0.273,
162 0x003C: 0.59,
163 0x003D: 0.536,
164 0x003E: 0.59,
165 0x003F: 0.467,
166 0x0040: 0.74,
167 0x0041: 0.646,
168 0x0042: 0.618,
169 0x0043: 0.651,
170 0x0044: 0.725,
171 0x0045: 0.587,
172 0x0046: 0.548,
173 0x0047: 0.664,
174 0x0048: 0.759,
175 0x0049: 0.345,
176 0x004A: 0.379,
177 0x004B: 0.639,
178 0x004C: 0.576,
179 0x004D: 0.838,
180 0x004E: 0.702,
181 0x004F: 0.71,
182 0x0050: 0.57,
183 0x0051: 0.71,
184 0x0052: 0.605,
185 0x0053: 0.521,
186 0x0054: 0.576,
187 0x0055: 0.734,
188 0x0056: 0.65,
189 0x0057: 0.912,
190 0x0058: 0.658,
191 0x0059: 0.619,
192 0x005A: 0.573,
193 0x005B: 0.292,
194 0x005C: 0.328,
195 0x005D: 0.292,
196 0x005E: 0.583,
197 0x005F: 0.497,
198 0x0060: 0.385,
199 0x0061: 0.49,
200 0x0062: 0.563,
201 0x0063: 0.483,
202 0x0064: 0.549,
203 0x0065: 0.506,
204 0x0066: 0.309,
205 0x0067: 0.566,
206 0x0068: 0.579,
207 0x0069: 0.296,
208 0x006A: 0.24,
209 0x006B: 0.518,
210 0x006C: 0.281,
211 0x006D: 0.856,
212 0x006E: 0.587,
213 0x006F: 0.531,
214 0x0070: 0.563,
215 0x0071: 0.537,
216 0x0072: 0.395,
217 0x0073: 0.441,
218 0x0074: 0.303,
219 0x0075: 0.583,
220 0x0076: 0.492,
221 0x0077: 0.706,
222 0x0078: 0.495,
223 0x0079: 0.483,
224 0x007A: 0.466,
225 0x007B: 0.283,
226 0x007C: 0.26,
227 0x007D: 0.283,
228 0x007E: 0.535,
229 0x05BE: 0.322,
230 0x05C3: 0.278,
231 0x05D0: 0.53,
232 0x05D1: 0.482,
233 0x05D2: 0.34,
234 0x05D3: 0.451,
235 0x05D4: 0.53,
236 0x05D5: 0.275,
237 0x05D6: 0.254,
238 0x05D7: 0.545,
239 0x05D8: 0.532,
240 0x05D9: 0.273,
241 0x05DA: 0.483,
242 0x05DB: 0.476,
243 0x05DC: 0.486,
244 0x05DD: 0.538,
245 0x05DE: 0.537,
246 0x05DF: 0.229,
247 0x05E0: 0.334,
248 0x05E1: 0.507,
249 0x05E2: 0.475,
250 0x05E3: 0.485,
251 0x05E4: 0.505,
252 0x05E5: 0.429,
253 0x05E6: 0.477,
254 0x05E7: 0.5,
255 0x05E8: 0.477,
256 0x05E9: 0.613,
257 0x05EA: 0.566,
258 0x05F3: 0.17,
259 0x05F4: 0.322,
260 },
261};
262types/index.d.ts 71 lines1// State contract for the dl (Daily Learning) mod: the values the sidebar pane draws from.
2
3// The Library's collections, and their structure as Sefaria's shape API gives
4// it: sections (sedarim, sefarim) of books (masechtos, hilchos), each with its
5// first and last unit (perek, or daf).
6export type Coll = "mishnah" | "bavli" | "mt";
7export type LibBook = { title: string; he: string; name: string; section: string; first: number; last: number; key?: string };
8export type LibSection = { name: string; he: string; books: LibBook[] };
9export type LibShape = { sections: LibSection[] };
10// Where the reader is: a collection, a section, a book, a unit.
11export type LibPos = { coll?: Coll; section?: string; book?: string; unit?: number };
12
13export type TabId = "chumash" | "tehillim" | "tanya" | "rambam1" | "rambam3" | "hayom" | "daf";
14
15// One block of text in a tab: a ref, its links, and parallel he/en paragraphs.
16// `rashi` holds Rashi's comments per verse, aligned with `he` (Chumash only).
17export type Part = {
18 title: string; link?: string; chabad?: string; he: string[]; en: string[];
19 rashi?: { he: string[][]; en: string[][] };
20 // A reading read one section at a time (Rambam's perakim, the daf's amudim):
21 // `unit` names them in the next/previous buttons, `numbered` leads each
22 // paragraph with its number (a halacha's א.), and `rashi` is per paragraph.
23 sections?: Section[];
24 unit?: "perek" | "amud";
25 numbered?: boolean;
26 // Each paragraph's own number, aligned with `he` (a Chumash verse's "ב."),
27 // and the heading drawn above it where a chapter starts (פרק ג).
28 labels?: { he: string; en: string; heading?: string }[];
29};
30
31// One section: `name` heads it (פרק יב, דף יח.), `short` names it in a button (יב, יח.).
32export type Section = { name: string; short: string; he: string[]; en: string[]; rashi?: string[][]; notes?: string[] };
33
34export type Day = {
35 v: number; // shape version: a cached Day of another version is fetched again
36 key: string; // Gregorian YYYY-MM-DD
37 title: string; // "Tuesday 2026-10-06 · 25 Tishrei 5787"
38 hebrew: string; // Hebrew date in Hebrew letters
39 parts: Record<TabId, Part[]>;
40 errors: string[];
41};
42
43export type Status = { key: string; phase: "loading" | "ready" | "error"; error?: string };
44
45declare module "claude-code" {
46 interface PluginState {
47 dl: {
48 day: Day | null;
49 status: Status | null;
50 tab: TabId | null; // null: the menu of the day's sections
51 // Which page the sidebar shows: the day's text, its settings, or the Library.
52 page: "read" | "settings" | "library";
53 // The Library: where the menu is, the collections loaded so far, the unit
54 // open (its ref and text), what is loading, and where each collection
55 // was last read.
56 libPos: LibPos;
57 libShapes: Partial<Record<Coll, LibShape>>;
58 libText: { ref: string; part: Part } | null;
59 libStatus: { what: string; phase: "loading" | "error"; error?: string } | null;
60 libLast: Partial<Record<Coll, { book: string; unit: number; at?: number }>>;
61 // Today's sections opened so far, for the date they belong to.
62 todayOpened: { key: string; ids: TabId[] } | null;
63 // Settings chosen on the sidebar's settings page, over the plugin's
64 // options (userConfig) until /config changes one of those.
65 prefsOver: Record<string, string | boolean>;
66 // Which section (perek, amud) each sectioned tab shows, for which day.
67 perek: { key: string; at: Partial<Record<TabId, number>> } | null;
68 };
69 }
70}
71