SLOPSHOPPER

turkish-practice

Turkish practice from the daily lesson files: a line under each answer, a band above the prompt, and a /tr drill pane

panebandcommandtimer
v0.1.0no licenseupdated 2026-10-11arslan-charyyev/claude-mods/turkish-practice
A shopper browsing a rack in a slop shop
README

turkish-practice

Turkish flashcards with spaced repetition, in the Claude Desktop Code tab. The cards come from my daily lessons, and every answer goes back to the lesson job, so the next lesson reacts to my mistakes.

It draws in the Desktop app only. In a terminal session it loads, but it draws nothing.

What it shows

  • The band above the prompt shows the card that is due, but only a card that takes one press: a new word, or an A to D choice. A translate card needs typing, so it waits for the pane, and the band shows how many wait. An answered card makes room for the next one when Claude's next answer ends, or at once on → Next. An unanswered card stays, so no card goes by unseen. ⏭ Skip skips a card for the rest of the day, ▾ Hide folds the band to one line with the card type, ▴ Show unfolds it, and ⤢ Open opens the pane. The band stays folded or unfolded across sessions until the next press.
  • /tr opens a pane with two tabs. Practice shows card after card, translate cards included, with today's progress ring and counts. When the pane closes, a translate card with no answer goes back to wait. Lesson shows today's lesson, with the answers hidden until a press, and /tr lesson opens the pane at that tab.

The cards

Each item (a word or a sentence) moves through card types from easy to hard:

CardWhat I doItems
New wordRead the word, its meaning, and an examplewords
What does it mean?Pick the English meaning, A to Dwords with wrong options
Fill the gapPick the missing word, A to D. The options look alike, or only the context tells them apartitems with a cloze
Translate into TurkishType the Turkish sentenceall

A sentence gets no "What does it mean?" card, because with whole sentences as options the answer shows at a glance. Its choice card is "Fill the gap", with one word per option. A sentence from a cards file brings its own cloze. Two lesson sentences that differ in one word, such as the contrast pair gelmem / gelemem, give each other a cloze: the English is the hint, and the other word is a wrong option. Misspellings of the right word fill the options up to four, as a spelling check: one breaks the vowel harmony (gelmam), one has a Turkish letter without its dots or cedilla (icmem). A misspelling that is a real word in the lessons is never an option. A lesson sentence without such a partner goes straight to the translate card.

A right answer moves the item to the next card type, which comes back 10 minutes later. At the translate card, a right answer moves it to the next interval instead: 1, 3, 7, 21, then 60 days. A wrong answer moves it one card type back and brings it back in 3 minutes. Translate answers are graded word by word: missing Turkish letters (karanlik for karanlık) count as right and are not flagged, so an English keyboard is enough, and a different sentence asks me whether mine is right too, because Turkish word order is free.

The next card is the item that has been due longest. When nothing is due, a new item comes, at most 20 a day, only from the lessons and cards of the last 7 days: newest day first, in the order of its cards file.

Every session shows the same card. The progress, today's counts, the skipped cards, and the folded band live in the mod's store, which all sessions share. A session looks at the store every 3 seconds, so an answer in one session moves the others on to the same next card. The options of a choice card come in the same order everywhere. A card you answered stays until → Next or Claude's next answer, even when another session moves on. A session also reads the lesson files again every minute, so a lesson the job writes while sessions run reaches all of them.

Data

The learning data stays in ~/.claude/turkish, outside this repository:

FileWritten byWhat it holds
lessons/<date>.mdthe daily lesson jobThe lesson. Its examples, contrast pair, drill with answers, and sentence of the day become sentence items. Two of them that differ in one word give each other a gap card.
cards/<date>.jsonthe daily lesson jobWords with checked wrong meanings, and sentences with whole-word gap cards. A cards item replaces a lesson item with the same Turkish.
practice-log.jsonthis modEvery answer: the item, the card type, what I gave, what was expected, and whether it was right
practice-state.jsonthis modWhere each item stands: card type, interval, and wrong answers so far

The lesson job reads the last two files to choose between a new lesson and a focus lesson on my mistakes, and to drop what I know already. Its prompts are in lesson-job/, and lesson-job/DAILY-LESSON-PROMPT.md is the authority on the cards file format. In short:

{
  "point": "4. Ability and inability",
  "items": [
    { "kind": "word", "tr": "kira", "en": "rent", "example": { "tr": "Bu ay kirayı ödeyemem.", "en": "I can't pay the rent this month." }, "distractors": ["cherry", "rule", "bill"] },
    { "kind": "sentence", "tr": "Bu çayı içemem.", "en": "I can't drink this tea.",
      "cloze": { "text": "Bu çayı ___.", "hint": "The tea is too hot.", "options": ["içemem", "içmem", "içebilirim", "içmiyorum"], "answer": "içemem", "explain": "`iç-eme-m`: a limit." } }
  ]
}

The mod skips an item that has no tr or en, and drops a cloze without exactly one ___, with duplicate options, or without its answer among the options.

The scheduler state, the daily new-item count, and the log also live in the mod's own store, ~/.claude/plugins/store/turkish-practice_inline-*.json, which every session shares.

Setup

In ~/.claude/settings.json:

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "/mnt/data/Dev/projects/linux/arslan-charyyev/claude-mods/turkish-practice",
    "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1"
  }
}

CLAUDE_CODE_ENABLE_FUNCTION_HOOKS turns mods on in Claude Code engines older than 2.1.287, such as 2.1.286 in Claude Desktop 2.19675.0. Version 2.1.287 and later ignore it, so remove it once the Desktop app ships such an engine. The Desktop app draws mods from 2.19675.0 on.

Files

FileWhat it does
hooks/register.jsThe hooks: loading, the band, the pane, the /tr command, and saving answers
hooks/srs.jsThe scheduler: items, card stages, intervals, and the next card
hooks/lesson.jsThe lesson parser and the translation grading
hooks/svg.jsThe progress ring
tests/claude plugin test suites, with shared fixtures in fixtures.ts
lesson-job/The prompts of the daily lesson job, which writes the lessons and the cards

Test

claude plugin validate .
capped claude plugin test
Source 4 files
hooks/register.js 730 lines
1// turkish-practice: Turkish flashcards with spaced repetition, for the Desktop Code tab.
2// - The band above the prompt shows the card that is due; an answered card
3//   moves on when Claude's next answer ends, or on Next. It shows only the
4//   cards answered with one press: a typed card waits for the pane
5// - /tr opens a pane to practice card after card, and today's lesson
6// The learning data lives in ~/.claude/turkish: the lessons and cards the daily
7// lesson job writes, and the practice log and state this mod writes back.
8import { parseLesson, lessonBody, grade, localDate } from './lesson.js'
9import { progressRing } from './svg.js'
10import { itemsFromLessons, itemsFromCards, mergeItems, pickCard, nextDue, answer, summary, itemId, stageFor, seededShuffle, NEW_PER_DAY, DAY } from './srs.js'
11
12const PANE = 'turkish-drill'
13// New items come only from the lessons and cards of this many recent days
14const NEW_LOOKBACK = 7
15const LOG_LIMIT = 2000
16const RIGHT = '#3fa55a'
17const WRONG = '#e05252'
18const LETTERS = ['A', 'B', 'C', 'D']
19
20let base = ''
21let loadedDate = ''
22let filesStamp = ''
23let todayMd = ''
24let items = []
25let recentDates = new Set()
26
27// The shared state: every session reads it from the store, and a write in one
28// session reaches the others within SYNC_MS. `rev` changes with each write.
29let srs = {}
30let newToday = 0
31let dayStats = { right: 0, wrong: 0 }
32let skipped = new Set()
33let isBandCollapsed = false
34let rev = ''
35
36// The card on show, shared by the band and the pane:
37// { item, stage, isNew, isAhead?, options?, result? }
38let card = null
39let tab = 'practice'
40let isAnswersShown = false
41// While the pane is closed, the band picks the cards: no typed cards then
42let isPaneOpen = false
43
44// How often a session looks for another session's answers, and for new lesson files
45const SYNC_MS = 3000
46const FILES_MS = 60000
47
48async function lessonFiles($, today) {
49  const dated = (list, ext) =>
50    list.filter((x) => x.kind === 'file' && new RegExp('^\\d{4}-\\d{2}-\\d{2}\\' + ext + '$').test(x.name) && x.name.slice(0, 10) <= today)
51  const lessons = dated(await $.fs.list(base + '/lessons'), '.md')
52  const cards = (await $.fs.exists(base + '/cards')) ? dated(await $.fs.list(base + '/cards'), '.json') : []
53  const stamp = [...lessons, ...cards].map((x) => x.name + ':' + x.size + ':' + x.mtimeMs).join('|')
54  return { lessons: lessons.map((x) => x.name).sort(), cards: cards.map((x) => x.name), stamp }
55}
56
57// Read the lessons and the cards files again when they changed: the lesson job
58// writes them while sessions run
59async function loadItems($) {
60  const today = localDate(await $.clock.now())
61  const files = await lessonFiles($, today)
62  if (files.stamp === filesStamp && today === loadedDate) return false
63
64  const lessons = []
65  for (const name of files.lessons) lessons.push(parseLesson(await $.fs.read(base + '/lessons/' + name), name.slice(0, 10)))
66  todayMd = files.lessons.length > 0 ? await $.fs.read(base + '/lessons/' + files.lessons[files.lessons.length - 1]) : ''
67
68  const cardFiles = []
69  for (const name of files.cards) {
70    try {
71      cardFiles.push({ ...JSON.parse(await $.fs.read(base + '/cards/' + name)), date: name.slice(0, 10) })
72    } catch (error) {
73      $.ui.log('skipped cards/' + name + ': ' + error.message)
74    }
75  }
76
77  items = mergeItems(itemsFromLessons(lessons), itemsFromCards(cardFiles))
78  const dates = [...new Set([...files.lessons.map((n) => n.slice(0, 10)), ...cardFiles.map((f) => f.date)])].sort()
79  recentDates = new Set(dates.slice(-NEW_LOOKBACK))
80  filesStamp = files.stamp
81  loadedDate = today
82  return true
83}
84
85// Read the shared state from the store
86async function loadShared($) {
87  const today = localDate(await $.clock.now())
88  const saved = await $.store.get('srs')
89  srs = saved && typeof saved === 'object' ? saved : {}
90  const daily = await $.store.get('daily')
91  newToday = daily && daily.day === today ? daily.newCount : 0
92  const log = await $.store.get('log')
93  dayStats = statsFor(Array.isArray(log) ? log : [], today)
94  const savedSkips = await $.store.get('skipped')
95  skipped = new Set(savedSkips && savedSkips.day === today && Array.isArray(savedSkips.ids) ? savedSkips.ids : [])
96  isBandCollapsed = (await $.store.get('bandCollapsed')) === true
97  rev = (await $.store.get('rev')) ?? ''
98}
99
100// Mark a write, so the other sessions read the shared state again
101async function bump($) {
102  rev = (await $.clock.now()) + '-' + Math.random().toString(36).slice(2, 8)
103  await $.store.set('rev', rev)
104}
105
106async function load($) {
107  const home = await $.env.get('HOME')
108  base = home + '/.claude/turkish'
109  filesStamp = ''
110  await loadItems($)
111  const now = await $.clock.now()
112
113  // The prototype kept missed drill items in a list: they start as due translate cards
114  const missed = await $.store.get('missed')
115  if (Array.isArray(missed) && missed.length > 0) {
116    const saved = await $.store.get('srs')
117    const all = saved && typeof saved === 'object' ? saved : {}
118    for (const m of missed) {
119      const id = itemId('sentence', m.tr)
120      if (!all[id]) all[id] = { stage: 'produce', box: 0, due: now, reps: 0, lapses: 1 }
121    }
122    await $.store.set('srs', all)
123    await $.store.set('missed', [])
124  }
125
126  await loadShared($)
127  card = null
128  pickNext(now)
129}
130
131// Bring this session in step: new lesson files, a new day, another session's
132// answers. A card with no answer yet is picked again, so every session shows
133// the same one; an answered card stays until Next.
134async function sync($, { files = false } = {}) {
135  const changedFiles = files ? await loadItems($) : false
136  const storeRev = (await $.store.get('rev')) ?? ''
137  if (!changedFiles && storeRev === rev) return
138  await loadShared($)
139  const isKept = card && (card.result || (card.isAhead && !changedFiles))
140  if (!isKept) pickNext(await $.clock.now())
141  $.ui.invalidate('ui.render')
142}
143
144function statsFor(log, day) {
145  const todays = log.filter((x) => x.day === day && typeof x.isRight === 'boolean')
146  return { right: todays.filter((x) => x.isRight).length, wrong: todays.filter((x) => !x.isRight).length }
147}
148
149// The cards the band can show: the ones answered with one press
150function fitsBand(item, stage) {
151  return stageFor(item, stage) !== 'produce'
152}
153
154const fits = () => (isPaneOpen ? undefined : fitsBand)
155
156// Show a card. The options of a choice card are shuffled the same way in every
157// session, and anew each time the item comes back.
158function show(pick, isAhead = false) {
159  if (!pick) {
160    card = null
161    return
162  }
163  const { item } = pick
164  const stage = stageFor(item, pick.stage)
165  const seed = item.id + '|' + stage + '|' + (srs[item.id]?.reps ?? 0)
166  const options =
167    stage === 'recognize'
168      ? seededShuffle([item.en, ...item.distractors], seed)
169      : stage === 'cloze'
170        ? seededShuffle(item.cloze.options, seed)
171        : undefined
172  // The same card as before keeps its object, so nothing on screen moves
173  if (card && !card.result && card.item.id === item.id && card.stage === stage) return
174  card = { item, stage, isNew: pick.isNew, isAhead, options }
175}
176
177function pickNext(now) {
178  const open = items.filter((it) => !skipped.has(it.id))
179  show(pickCard(open, srs, now, newToday, (it) => recentDates.has(it.date), fits()))
180}
181
182// Practice ahead: the item that comes due next, at its own stage
183function practiceMore() {
184  const it = nextDue(items.filter((x) => !skipped.has(x.id)), srs, fits())
185  if (it) show({ item: it, stage: srs[it.id].stage, isNew: false }, true)
186}
187
188// Skip an item for the rest of the day, in every session
189async function skipItem($, id) {
190  const today = localDate(await $.clock.now())
191  const saved = await $.store.get('skipped')
192  const ids = saved && saved.day === today && Array.isArray(saved.ids) ? saved.ids : []
193  skipped = new Set([...ids, id])
194  await $.store.set('skipped', { day: today, ids: [...skipped] })
195  await bump($)
196}
197
198// Save one answer: the item's new state, today's new-item count, and the log.
199// The store is read again right before each write, because other sessions share it.
200async function record($, c, isRight, given, verdict) {
201  const now = await $.clock.now()
202  const day = localDate(now)
203  const savedSrs = await $.store.get('srs')
204  const all = savedSrs && typeof savedSrs === 'object' ? savedSrs : {}
205  // Another session answered this card already: the first answer counts
206  if (c.isNew && all[c.item.id]) c.isNew = false
207  all[c.item.id] = answer(c.item, all[c.item.id], c.stage, isRight, now)
208  srs = all
209  await $.store.set('srs', all)
210
211  if (c.isNew) {
212    const daily = await $.store.get('daily')
213    newToday = (daily && daily.day === day ? daily.newCount : 0) + 1
214    await $.store.set('daily', { day, newCount: newToday })
215  }
216
217  const entry = {
218    at: new Date(now).toISOString(),
219    day,
220    id: c.item.id,
221    kind: c.item.kind,
222    card: c.stage,
223    lesson: c.item.date,
224    en: c.item.en,
225    expected: c.stage === 'cloze' ? wholeWordGap(c.item.cloze).word(c.item.cloze.answer) : c.stage === 'recognize' ? c.item.en : c.item.tr,
226    answer: given,
227    verdict,
228    ...(c.stage === 'intro' ? {} : { isRight }),
229  }
230  const savedLog = await $.store.get('log')
231  const log = [...(Array.isArray(savedLog) ? savedLog : []), entry].slice(-LOG_LIMIT)
232  await $.store.set('log', log)
233  dayStats = statsFor(log, day)
234  await bump($)
235
236  // Files beside the lessons, for the daily lesson job
237  await $.fs.write(base + '/practice-log.json', JSON.stringify(log, null, 2) + '\n')
238  const state = items
239    .filter((it) => all[it.id])
240    .map((it) => ({ id: it.id, kind: it.kind, tr: it.tr, en: it.en, lesson: it.date, ...all[it.id], due: new Date(all[it.id].due).toISOString() }))
241  await $.fs.write(base + '/practice-state.json', JSON.stringify(state, null, 2) + '\n')
242}
243
244async function openPane($) {
245  await $.ui.open({ id: PANE, title: 'Türkçe', focus: true, closeOnEscape: true })
246}
247
248// The pane has time for typed cards: once it is up, they come back into the picks,
249// and a card with no answer yet makes room for the item that has been due longest
250async function paneShown($) {
251  if (isPaneOpen) return
252  isPaneOpen = true
253  if (!card || !card.result) {
254    pickNext(await $.clock.now())
255    $.ui.invalidate('ui.render')
256  }
257}
258
259function untilText(ms) {
260  if (ms <= 0) return 'now'
261  const minutes = Math.round(ms / 60000)
262  if (minutes < 60) return 'in ' + minutes + ' min'
263  const hours = Math.round(minutes / 60)
264  if (hours < 24) return 'in ' + hours + ' h'
265  return 'in ' + Math.round(ms / DAY) + ' days'
266}
267
268// The line above a typed answer's result: [is it good news, the text]
269const HEADLINES = {
270  exact: [true, '✓ Doğru!'],
271  // Typed on an English keyboard (`aksam` for `akşam`): as right as an exact answer
272  letters: [true, '✓ Doğru!'],
273  different: [false, '✗ Not quite. Compare the words'],
274  skipped: [false, 'The answer'],
275  variant: [true, '✓ Counted as right'],
276  wrong: [false, '✗ Counted as wrong. It comes back soon'],
277}
278
279const LABELS = { intro: 'New word', recognize: 'What does it mean?', cloze: 'Fill the gap', produce: 'Translate into Turkish' }
280
281// A cloze gap drawn as a whole word: a cards file may cut the gap inside a word
282// ("iç___." with the option "emem"), but each option shows as the whole word ("içemem")
283function wholeWordGap(z) {
284  const m = z.text.match(/([\p{L}'’]*)___([\p{L}'’]*)/u)
285  return { text: z.text.replace(m[0], '___'), word: (option) => m[1] + option + m[2] }
286}
287
288// The card itself, for the band (compact) and the pane (large).
289// Every control calls back into the module, so both drawings stay in step.
290function cardView($, el, isLarge) {
291  const { Box, Text, Button, Input, Markdown } = el
292  const redraw = () => $.ui.invalidate('ui.render')
293  const c = card
294  const it = c.item
295  const r = c.result
296  const gap = c.stage === 'cloze' ? wholeWordGap(it.cloze) : null
297  // The band's label line carries the flag already; the pane's does not
298  const flag = isLarge ? '🇹🇷 ' : ''
299  const heading = (text) => (isLarge ? Markdown({ key: 'tr-prompt', text: '### ' + text }) : Text({ bold: true, wrap: 'wrap', children: [text] }))
300  const row = (children) => Box({ flexDirection: 'row', columnGap: 1, children })
301  const next = () =>
302    Button({
303      key: 'tr-next',
304      label: '→ Next',
305      variant: 'primary',
306      autoFocus: true,
307      onPress: async () => {
308        pickNext(await $.clock.now())
309        redraw()
310      },
311    })
312  const note = () => (it.note ? [Markdown({ key: 'tr-note', text: it.note })] : [])
313  const verdictLine = (isRight, text) => Text({ bold: true, color: isRight ? RIGHT : WRONG, wrap: 'wrap', children: [text] })
314
315  // The options of a choice card, A to D; `shown` turns an option into its label
316  const choices = (correct, onChoose, shown = (option) => option) =>
317    Box({
318      flexDirection: isLarge ? 'column' : 'row',
319      flexWrap: 'wrap',
320      columnGap: 1,
321      rowGap: isLarge ? 1 : 0,
322      children: c.options.map((option, i) =>
323        Button({
324          key: 'tr-option-' + i,
325          label: LETTERS[i] + '. ' + shown(option),
326          variant: 'secondary',
327          onPress: async () => {
328            const isRight = option === correct
329            c.result = { isRight, given: option }
330            redraw()
331            await onChoose(option, isRight)
332          },
333        }),
334      ),
335    })
336
337  if (c.stage === 'intro') {
338    return [
339      heading(flag + it.tr + ' — ' + it.en),
340      ...(it.example ? [Text({ wrap: 'wrap', children: [it.example.tr] }), Text({ italic: true, dimColor: true, wrap: 'wrap', children: [it.example.en] })] : []),
341      ...note(),
342      row([
343        Button({
344          key: 'tr-got-it',
345          label: '✓ Got it',
346          variant: 'primary',
347          autoFocus: true,
348          onPress: async () => {
349            // Save first: the next pick must see this item as no longer new
350            await record($, c, true, '', 'seen')
351            pickNext(await $.clock.now())
352            redraw()
353          },
354        }),
355      ]),
356    ]
357  }
358
359  if (c.stage === 'recognize') {
360    if (!r) return [heading(flag + it.tr), choices(it.en, (option, isRight) => record($, c, isRight, option, isRight ? 'right' : 'wrong'))]
361    return [
362      heading(flag + it.tr),
363      verdictLine(r.isRight, r.isRight ? '✓ Doğru! ' + it.en : '✗ It means: ' + it.en),
364      ...note(),
365      row([next()]),
366    ]
367  }
368
369  if (c.stage === 'cloze') {
370    const z = it.cloze
371    // The translation, then the hint; a lesson cloze has the translation as its hint
372    const context = [it.en, ...(z.hint && z.hint !== it.en ? [z.hint] : [])].join(' · ')
373    const prompt = [Text({ italic: true, dimColor: true, wrap: 'wrap', children: [context] }), heading(gap.text)]
374    if (!r) return [...prompt, choices(z.answer, (option, isRight) => record($, c, isRight, gap.word(option), isRight ? 'right' : 'wrong'), gap.word)]
375    return [
376      ...prompt,
377      verdictLine(r.isRight, (r.isRight ? '✓ Doğru! ' : '✗ ') + z.text.replace('___', z.answer)),
378      ...(z.explain ? [Markdown({ key: 'tr-explain', text: z.explain })] : note()),
379      row([next()]),
380    ]
381  }
382
383  // produce: type the Turkish
384  const prompt = heading(it.en)
385  if (!r) {
386    return [
387      prompt,
388      Input({
389        key: 'tr-answer',
390        label: 'Türkçe',
391        placeholder: 'Type the Turkish sentence',
392        value: '',
393        submitLabel: 'Check',
394        ...(isLarge ? { autoFocus: true } : {}),
395        onSubmit: async (value) => {
396          if (!value.trim()) return
397          const g = grade(value, it.tr)
398          c.result = { given: value.trim(), ...g, isPending: g.verdict === 'different' }
399          redraw()
400          // A clear result is saved now; a different answer waits for the self-check
401          if (g.verdict !== 'different') await record($, c, true, value.trim(), g.verdict)
402        },
403      }),
404      row([
405        Button({
406          key: 'tr-show',
407          label: 'Show the answer',
408          variant: 'secondary',
409          onPress: async () => {
410            c.result = { given: '', verdict: 'skipped', words: grade('', it.tr).words, isRight: false }
411            redraw()
412            await record($, c, false, '', 'skipped')
413          },
414        }),
415      ]),
416    ]
417  }
418  const selfCheck = async (isRight) => {
419    c.result = { ...r, verdict: isRight ? 'variant' : 'wrong', isPending: false }
420    redraw()
421    await record($, c, isRight, r.given, isRight ? 'variant' : 'wrong')
422  }
423  // The expected sentence once, as written; after a typed answer the words that differ are colored
424  const sentence = Box({
425    key: 'tr-expected',
426    flexDirection: 'row',
427    flexWrap: 'wrap',
428    columnGap: 1,
429    children: r.words.map((w) =>
430      r.given && w.status === 'missing'
431        ? Text({ bold: true, color: WRONG, children: [w.raw] })
432        : Text({ bold: true, children: [w.raw] }),
433    ),
434  })
435  const [isGood, headline] = HEADLINES[r.verdict]
436  return [
437    prompt,
438    verdictLine(isGood, headline),
439    ...(r.given ? [Text({ dimColor: true, wrap: 'wrap', children: ['You wrote: ' + r.given] })] : []),
440    sentence,
441    ...note(),
442    row(
443      r.isPending
444        ? [
445            Button({ key: 'tr-variant', label: '✓ Mine is right too', variant: 'secondary', onPress: () => selfCheck(true) }),
446            Button({ key: 'tr-wrong', label: '✗ Mine is wrong', variant: 'primary', autoFocus: true, onPress: () => selfCheck(false) }),
447          ]
448        : [next()],
449    ),
450  ]
451}
452
453export function register(on) {
454  on('session.start', async ($, e, next) => {
455    try {
456      await load($)
457    } catch (error) {
458      $.ui.log('could not read the lessons: ' + error.message)
459    }
460    await $.command.register({
461      name: 'tr',
462      description: 'Turkish flashcards and today\'s lesson',
463      argumentHint: '[lesson]',
464      immediate: true,
465    })
466    // Keep in step with the other sessions, and with the lesson files now and then
467    let ticks = 0
468    let isSyncing = false
469    $.clock.every(SYNC_MS, async () => {
470      if (isSyncing) return
471      isSyncing = true
472      ticks++
473      try {
474        await sync($, { files: ticks % (FILES_MS / SYNC_MS) === 0 })
475      } catch (error) {
476        $.ui.log('could not sync: ' + error.message)
477      } finally {
478        isSyncing = false
479      }
480    })
481    return next(e)
482  })
483
484  // When Claude's answer ends, an answered card makes room for the next one.
485  // An unanswered card stays, so no card is passed over unseen.
486  on('turn.complete', async ($, e, next) => {
487    const result = await next(e)
488    if (e.agentId || e.reason !== 'answer') return result
489    await sync($, { files: true })
490    if (!card || (card.result && !card.result.isPending)) {
491      pickNext(await $.clock.now())
492      $.ui.invalidate('ui.render')
493    }
494    return result
495  })
496
497  on('command.run', { command: 'tr' }, async ($, e) => {
498    await sync($, { files: true })
499    tab = e.args.trim() === 'lesson' ? 'lesson' : 'practice'
500    await openPane($)
501    await paneShown($)
502    $.ui.invalidate('ui.render')
503    return {}
504  })
505
506  // A typed card with no answer yet goes back to wait when the pane closes
507  on('ui.close', async ($, e, next) => {
508    const result = await next(e)
509    if (e.id !== PANE) return result
510    isPaneOpen = false
511    if (card && !fitsBand(card.item, card.stage) && !(card.result && card.result.isPending)) {
512      pickNext(await $.clock.now())
513      $.ui.invalidate('ui.render')
514    }
515    return result
516  })
517
518  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
519    const theirs = await next(e)
520    if (e.surface !== 'desktop' || items.length === 0) return theirs
521    const el = $.ui.resolve(e)
522    const { Box, Text, Button } = el
523    const redraw = () => $.ui.invalidate('ui.render')
524    const now = await $.clock.now()
525    // Small text buttons: a glyph and a word, as no Button has a tooltip
526    const icon = (key, label, onPress) => Button({ key, label, plain: true, dimColor: true, onPress })
527    const openIcon = icon('tr-open', '⤢ Open', async () => {
528      tab = 'practice'
529      await openPane($)
530      await paneShown($)
531      redraw()
532    })
533    const setCollapsed = async (value) => {
534      isBandCollapsed = value
535      redraw()
536      await $.store.set('bandCollapsed', value)
537      await bump($)
538    }
539    // Typed cards that are due: they wait for the pane
540    const typedDue = items.filter((it) => srs[it.id] && srs[it.id].due <= now && !fitsBand(it, srs[it.id].stage)).length
541
542    let band
543    if (!card || !fitsBand(card.item, card.stage)) {
544      // A typed card is on show only while the pane is up: the band points there
545      const soon = nextDue(items, srs, fitsBand)
546      const status = card
547        ? 'A translate card is open in the pane'
548        : typedDue > 0
549          ? typedDue + (typedDue === 1 ? ' translate card waits' : ' translate cards wait') + ' for the pane'
550          : soon
551            ? 'Next review ' + untilText(srs[soon.id].due - now)
552            : 'No cards yet'
553      band = Box({
554        flexDirection: 'row',
555        alignItems: 'center',
556        columnGap: 2,
557        children: [
558          Text({ bold: true, children: [card ? '🇹🇷 Translate into Turkish' : '🇹🇷 All caught up'] }),
559          Box({ flexGrow: 1, children: [Text({ dimColor: true, children: [status] })] }),
560          ...(soon && !card
561            ? [
562                Button({
563                  key: 'tr-more',
564                  label: 'Practice more',
565                  variant: 'secondary',
566                  onPress: () => {
567                    practiceMore()
568                    redraw()
569                  },
570                }),
571              ]
572            : []),
573          openIcon,
574        ],
575      })
576    } else if (isBandCollapsed) {
577      band = Box({
578        flexDirection: 'row',
579        alignItems: 'center',
580        columnGap: 2,
581        children: [
582          Box({ flexGrow: 1, children: [Text({ dimColor: true, children: ['🇹🇷 ' + LABELS[card.stage] + (card.isNew ? ' · new' : '')] })] }),
583          icon('tr-expand', '▴ Show', () => setCollapsed(false)),
584          openIcon,
585        ],
586      })
587    } else {
588      band = Box({
589        flexDirection: 'column',
590        children: [
591          Box({
592            flexDirection: 'row',
593            alignItems: 'center',
594            justifyContent: 'space-between',
595            children: [
596              Text({ dimColor: true, children: ['🇹🇷 ' + LABELS[card.stage] + (card.isNew ? ' · new' : '')] }),
597              Box({
598                flexDirection: 'row',
599                columnGap: 2,
600                children: [
601                  ...(card.result
602                    ? []
603                    : [
604                        icon('tr-skip', '⏭ Skip', async () => {
605                          await skipItem($, card.item.id)
606                          pickNext(await $.clock.now())
607                          redraw()
608                        }),
609                      ]),
610                  icon('tr-collapse', '▾ Hide', () => setCollapsed(true)),
611                  openIcon,
612                ],
613              }),
614            ],
615          }),
616          ...cardView($, el, false),
617        ],
618      })
619    }
620    return theirs ? Box({ flexDirection: 'column', rowGap: 1, children: [band, theirs] }) : band
621  })
622
623  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
624    if (e.requestId !== PANE || e.surface !== 'desktop') return next(e)
625    // A pane that is up without /tr (a reload, a restore) counts as open too
626    await paneShown($)
627    const el = $.ui.resolve(e)
628    const { Box, Text, Button, Markdown, Svg } = el
629    const redraw = () => $.ui.invalidate('ui.render')
630    const now = await $.clock.now()
631    const counts = summary(items, srs, now)
632
633    const tabButton = (name, label) =>
634      Button({
635        key: 'tr-tab-' + name,
636        label,
637        variant: tab === name ? 'primary' : 'secondary',
638        onPress: () => {
639          tab = name
640          redraw()
641        },
642      })
643    const header = Box({
644      flexDirection: 'row',
645      alignItems: 'center',
646      justifyContent: 'space-between',
647      children: [
648        Box({ flexDirection: 'row', columnGap: 1, children: [tabButton('practice', 'Practice'), tabButton('lesson', 'Lesson')] }),
649        Box({
650          flexDirection: 'row',
651          alignItems: 'center',
652          columnGap: 1,
653          children: [
654            Svg({ source: progressRing(dayStats.right, dayStats.wrong), alt: 'Today: ' + dayStats.right + ' right, ' + dayStats.wrong + ' wrong', width: 44, height: 44 }),
655            Box({
656              flexDirection: 'column',
657              children: [
658                Text({ dimColor: true, children: [counts.due + ' due · ' + Math.max(0, NEW_PER_DAY - newToday) + ' new left'] }),
659                Text({ dimColor: true, children: [counts.learning + ' learning · ' + counts.known + ' known'] }),
660              ],
661            }),
662          ],
663        }),
664      ],
665    })
666
667    let body
668    if (tab === 'lesson') {
669      const i = todayMd.search(/^## Answers/m)
670      const answers = i === -1 ? '' : todayMd.slice(i)
671      body = [
672        Markdown({ key: 'tr-lesson', text: (lessonBody(todayMd) || 'No lesson file found.').slice(0, 10000) }),
673        ...(answers
674          ? [
675              Box({
676                flexDirection: 'row',
677                children: [
678                  Button({
679                    key: 'tr-answers',
680                    label: isAnswersShown ? 'Hide answers' : 'Show answers',
681                    variant: 'secondary',
682                    onPress: () => {
683                      isAnswersShown = !isAnswersShown
684                      redraw()
685                    },
686                  }),
687                ],
688              }),
689            ]
690          : []),
691        ...(isAnswersShown && answers ? [Markdown({ key: 'tr-lesson-answers', text: answers.slice(0, 10000) })] : []),
692      ]
693    } else if (!card) {
694      const soon = nextDue(items, srs)
695      body = [
696        Markdown({
697          key: 'tr-done',
698          text: '### All caught up\n\n' + (soon ? 'The next review is due ' + untilText(srs[soon.id].due - now) + '.' : 'No cards yet. The lessons in `' + base + '` feed the cards.'),
699        }),
700        ...(soon
701          ? [
702              Box({
703                flexDirection: 'row',
704                children: [
705                  Button({
706                    key: 'tr-more',
707                    label: 'Practice more',
708                    variant: 'primary',
709                    autoFocus: true,
710                    onPress: () => {
711                      practiceMore()
712                      redraw()
713                    },
714                  }),
715                ],
716              }),
717            ]
718          : []),
719      ]
720    } else {
721      body = [
722        Text({ dimColor: true, children: [LABELS[card.stage] + (card.isNew ? ' · new' : '') + ' · from the ' + card.item.date + ' lesson'] }),
723        ...cardView($, el, true),
724      ]
725    }
726
727    return Box({ flexDirection: 'column', rowGap: 1, padding: 1, children: [header, ...body] })
728  })
729}
730
hooks/lesson.js 155 lines
1// Pure helpers: parse a daily lesson file and grade a drill answer.
2// No mods API here, so node and the test kit can both import this file.
3
4const SOTD = /🇹🇷\s*\*\*(.+?)\*\*\s*—\s*\*(.+?)\*/
5const BOLD_PAIR_NUMBERED = /^\d+\.\s+\*\*(.+?)\*\*\s+—\s+(.+)$/
6const BOLD_PAIR_BULLET = /^-\s+\*\*(.+?)\*\*\s+—\s+(.+)$/
7const NUMBERED = /^\d+\.\s+(.+)$/
8
9// Split a lesson into { heading: body } by its `## ` headings
10export function sections(md) {
11  const out = []
12  let current = { heading: '', lines: [] }
13  for (const line of md.split('\n')) {
14    if (line.startsWith('## ')) {
15      out.push(current)
16      current = { heading: line.slice(3).trim(), lines: [] }
17    } else {
18      current.lines.push(line)
19    }
20  }
21  out.push(current)
22  return out
23}
24
25// "Et yemem, sebze yerim. (`ye-me-m`: a choice.)" -> { tr, note }
26export function splitNote(text) {
27  const t = text.trim()
28  // Some lessons write the answer in bold: "**Bu ay kirayı ödeyemem.** (`kira-yı`: ...)"
29  const bold = t.match(/^\*\*(.+?)\*\*\s*(.*)$/)
30  if (bold) {
31    const rest = bold[2].trim()
32    return { tr: bold[1].trim(), note: rest.startsWith('(') && rest.endsWith(')') ? rest.slice(1, -1).trim() : rest }
33  }
34  if (!t.endsWith(')')) return { tr: t, note: '' }
35  let depth = 0
36  for (let i = t.length - 1; i >= 0; i--) {
37    if (t[i] === ')') depth++
38    else if (t[i] === '(') {
39      depth--
40      if (depth === 0) {
41        const tr = t.slice(0, i).trim()
42        // A parenthesis inside the sentence itself, not a trailing note
43        if (!/[.?!]$/.test(tr)) return { tr: t, note: '' }
44        return { tr, note: t.slice(i + 1, -1).trim() }
45      }
46    }
47  }
48  return { tr: t, note: '' }
49}
50
51// Read one lesson file into sentences (Turkish with English) and drill items
52export function parseLesson(md, date) {
53  const sentences = []
54  const drill = []
55  let prompts = []
56  let answers = []
57
58  for (const { heading, lines } of sections(md)) {
59    if (/^Five examples/i.test(heading)) {
60      for (const line of lines) {
61        const m = line.match(BOLD_PAIR_NUMBERED)
62        if (m) sentences.push({ tr: m[1].trim(), en: m[2].trim(), kind: 'example', date })
63      }
64    } else if (/^The contrast/i.test(heading)) {
65      for (const line of lines) {
66        const m = line.match(BOLD_PAIR_BULLET)
67        if (m) sentences.push({ tr: m[1].trim(), en: m[2].trim(), kind: 'contrast', date })
68      }
69    } else if (/^Sentence of the day/i.test(heading)) {
70      const m = lines.join('\n').match(SOTD)
71      if (m) sentences.push({ tr: m[1].trim(), en: m[2].trim(), kind: 'sotd', date })
72    } else if (/^Production drill/i.test(heading)) {
73      prompts = lines.map((l) => l.match(NUMBERED)).filter(Boolean).map((m) => m[1].trim())
74    } else if (/^Answers/i.test(heading)) {
75      // The drill answers sit between a "Drill:" line and the next "Xxx:" label line
76      let inDrill = false
77      for (const line of lines) {
78        const label = line.trim()
79        if (/^Drill:?$/i.test(label)) inDrill = true
80        else if (/^[A-Z][\w -]*:$/.test(label)) inDrill = false
81        else if (inDrill) {
82          const m = line.match(NUMBERED)
83          if (m) answers.push(splitNote(m[1]))
84        }
85      }
86    }
87  }
88
89  // Pair a prompt with its answer only when the counts agree, so no answer lands on the wrong prompt
90  if (prompts.length > 0 && prompts.length === answers.length) {
91    prompts.forEach((en, i) => drill.push({ en, tr: answers[i].tr, note: answers[i].note, kind: 'drill', date }))
92  }
93  return { date, sentences, drill }
94}
95
96// The lesson text a learner reads first: everything above the answers
97export function lessonBody(md) {
98  const i = md.search(/^## Answers/m)
99  return (i === -1 ? md : md.slice(0, i)).trim()
100}
101
102// Lowercase with Turkish rules (İ -> i, I -> ı), drop punctuation and extra spaces.
103// An apostrophe joins its word ("İstanbul'a" -> "istanbula"), so a word stays one word.
104export function normalize(text) {
105  return text
106    .toLocaleLowerCase('tr')
107    .replace(/['‘’`]/g, '')
108    .replace(/[.,!?;:"“”()]/g, ' ')
109    .replace(/\s+/g, ' ')
110    .trim()
111}
112
113// The words of a sentence as written, without the punctuation at their edges
114function displayWords(text) {
115  return text
116    .split(/\s+/)
117    .map((w) => w.replace(/^[.,!?;:"“”()`]+|[.,!?;:"“”()`]+$/g, ''))
118    .filter(Boolean)
119}
120
121// Fold the Turkish letters to their ASCII look-alikes: "karanlık" -> "karanlik"
122export function fold(text) {
123  return text.replace(/[ıİçÇğĞöÖşŞüÜâÂîÎûÛ]/g, (c) => ({ ı: 'i', İ: 'i', ç: 'c', Ç: 'c', ğ: 'g', Ğ: 'g', ö: 'o', Ö: 'o', ş: 's', Ş: 's', ü: 'u', Ü: 'u', â: 'a', Â: 'a', î: 'i', Î: 'i', û: 'u', Û: 'u' })[c])
124}
125
126// Compare an answer with the expected sentence, word by word.
127// verdict: 'exact', 'letters' (right apart from Turkish letters), or 'different'.
128// Each expected word is 'ok', 'letters', or 'missing' in the answer.
129export function grade(answer, expected) {
130  const a = normalize(answer)
131  const x = normalize(expected)
132  const given = new Set(a.split(' '))
133  const givenFolded = new Set(a.split(' ').map(fold))
134  const shown = displayWords(expected)
135  const raw = expected.trim().split(/\s+/)
136  const keys = x.split(' ')
137  // Show each word as written ("Oda", not "oda") when the splits agree;
138  // `raw` also keeps the punctuation, to draw the sentence itself
139  const isAligned = shown.length === keys.length && raw.length === keys.length
140  const words = keys.map((key, i) => ({
141    word: isAligned ? shown[i] : key,
142    raw: isAligned ? raw[i] : key,
143    status: given.has(key) ? 'ok' : givenFolded.has(fold(key)) ? 'letters' : 'missing',
144  }))
145  const verdict = a === x ? 'exact' : fold(a) === fold(x) ? 'letters' : 'different'
146  return { verdict, words }
147}
148
149// YYYY-MM-DD in local time
150export function localDate(ms) {
151  const d = new Date(ms)
152  const pad = (n) => String(n).padStart(2, '0')
153  return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate())
154}
155
hooks/svg.js 31 lines
1// Pure SVG builders for the Desktop pane. The app draws an Svg as an isolated
2// image, so the markup cannot read the app's theme: every color here is a
3// mid-tone that reads on both a dark and a light background.
4
5const FONT = "Inter, 'Segoe UI', Ubuntu, Roboto, system-ui, sans-serif"
6const RIGHT = '#3fa55a'
7const WRONG = '#e05252'
8const TRACK = 'rgba(128, 128, 128, 0.45)'
9const LABEL = '#8f8f8f'
10
11// Today's progress: a ring split into right (green) and wrong (red), the
12// number of answers in the middle; an empty grey ring before the first answer
13export function progressRing(right, wrong, size = 44) {
14  const r = size / 2 - 4
15  const c = 2 * Math.PI * r
16  const total = right + wrong
17  const cx = size / 2
18  const arc = (length, offset, color) =>
19    `<circle cx="${cx}" cy="${cx}" r="${r}" fill="none" stroke="${color}" stroke-width="5" stroke-linecap="butt" ` +
20    `stroke-dasharray="${length} ${c - length}" stroke-dashoffset="${-offset}" transform="rotate(-90 ${cx} ${cx})"/>`
21  const rightLen = total === 0 ? 0 : (c * right) / total
22  return (
23    `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" font-family="${FONT}">` +
24    `<circle cx="${cx}" cy="${cx}" r="${r}" fill="none" stroke="${TRACK}" stroke-width="5"/>` +
25    (right > 0 ? arc(rightLen, 0, RIGHT) : '') +
26    (wrong > 0 ? arc(c - rightLen, rightLen, WRONG) : '') +
27    `<text x="${cx}" y="${cx + 5}" text-anchor="middle" font-size="14" font-weight="700" fill="${LABEL}">${total}</text>` +
28    `</svg>`
29  )
30}
31
hooks/srs.js 265 lines
1// Pure spaced-repetition logic: items, card stages, intervals, and the next card.
2// No mods API here, so node and the test kit can both import this file.
3//
4// An item is one thing to learn: a word or a sentence. It moves through card
5// stages from easy to hard. A right answer moves it one stage on; at the last
6// stage (translate) it moves to a longer interval instead. A wrong answer moves
7// it one stage back and brings it back soon.
8//
9//   word:     intro -> (recognize) -> (cloze) -> produce
10//   sentence:                         (cloze) -> produce
11//
12// recognize: pick the meaning of a word (A-D), only when it has wrong options
13// cloze:     pick the missing word (A-D), only when the item has a cloze
14// produce:   type the Turkish for the English
15//
16// A sentence gets no meaning card: with whole sentences as options, the
17// answer shows at a glance. Its choice card is the cloze, one word per option.
18
19import { normalize } from './lesson.js'
20
21export const MINUTE = 60 * 1000
22export const DAY = 24 * 60 * MINUTE
23// Days until the next review after each right answer at the translate stage
24export const INTERVALS = [1, 3, 7, 21, 60]
25// A learning step: the item comes back later in the same day
26export const LEARN_STEP = 10 * MINUTE
27// A wrong answer: the item comes back within the same sitting
28export const RETRY_STEP = 3 * MINUTE
29// New items a day
30export const NEW_PER_DAY = 20
31
32export function itemId(kind, tr) {
33  return (kind === 'word' ? 'w:' : 's:') + normalize(tr)
34}
35
36const ALL_STAGES = ['intro', 'recognize', 'cloze', 'produce']
37
38export function stagesOf(item) {
39  return [
40    ...(item.kind === 'word' ? ['intro'] : []),
41    ...(item.kind === 'word' && item.distractors.length > 0 ? ['recognize'] : []),
42    ...(item.cloze ? ['cloze'] : []),
43    'produce',
44  ]
45}
46
47// The stage an item shows when its saved stage is not one of its own (a
48// sentence saved at the meaning card that this item no longer has): the next one it has
49export function stageFor(item, stage) {
50  const stages = stagesOf(item)
51  const at = ALL_STAGES.indexOf(stage)
52  return stages.find((x) => ALL_STAGES.indexOf(x) >= at) ?? stages[stages.length - 1]
53}
54
55// Sentence items from parsed lessons. Two sentences that differ in one word
56// (the contrast pair is one) give each other a cloze: that word, with the
57// other sentence's word as the wrong option, and the English as the hint.
58// Misspellings of the answer fill the options up to four.
59export function itemsFromLessons(lessons) {
60  const raw = []
61  for (const l of lessons) {
62    for (const s of [...l.sentences, ...l.drill]) {
63      // Lesson items come after a day's cards items: their order starts at 1000
64      raw.push({ kind: 'sentence', tr: s.tr, en: s.en, note: s.note ?? '', date: l.date, source: 'lesson', order: 1000 + raw.length })
65    }
66  }
67  const byId = new Map()
68  for (const it of raw) {
69    const id = itemId(it.kind, it.tr)
70    if (!byId.has(id)) byId.set(id, { ...it, id })
71  }
72  const all = [...byId.values()]
73  // Every word of the lessons: a misspelling that is a real word is never an option
74  const vocab = new Set(all.flatMap((it) => normalize(it.tr).split(' ')))
75  for (const it of all) {
76    it.distractors = []
77    const cloze = pairCloze(it, all, vocab)
78    if (cloze) it.cloze = cloze
79  }
80  return all
81}
82
83const EDGE = /^([^\p{L}]*)(.*?)([^\p{L}]*)$/u
84
85// The cloze from the sentences that differ from `it` in one word only, at the
86// place where most of them differ
87function pairCloze(it, all, vocab) {
88  const words = it.tr.split(/\s+/)
89  const byPlace = new Map()
90  for (const o of all) {
91    if (o.id === it.id || o.en === it.en) continue
92    const other = o.tr.split(/\s+/)
93    if (other.length !== words.length) continue
94    const diff = words.flatMap((w, i) => (normalize(w) === normalize(other[i]) ? [] : [i]))
95    if (diff.length !== 1) continue
96    const option = other[diff[0]].match(EDGE)[2]
97    if (!option) continue
98    byPlace.set(diff[0], [...(byPlace.get(diff[0]) ?? []), option])
99  }
100  if (byPlace.size === 0) return undefined
101  const [place, wrong] = [...byPlace.entries()].sort((a, b) => b[1].length - a[1].length || a[0] - b[0])[0]
102  const [, before, answer, after] = words[place].match(EDGE)
103  const options = [...new Set([answer, ...wrong])].slice(0, 4)
104  if (options.length < 2) return undefined
105  const taken = (w) => vocab.has(normalize(w)) || options.some((o) => normalize(o) === normalize(w))
106  options.push(...misspellings(answer, taken).slice(0, 4 - options.length))
107  const text = words.map((w, i) => (i === place ? before + '___' + after : w)).join(' ')
108  return { text, hint: it.en, options, answer }
109}
110
111// A small seeded generator, so every session shuffles the options the same way
112function seeded(text) {
113  let h = 2166136261
114  for (const c of text) h = Math.imul(h ^ c.codePointAt(0), 16777619)
115  return () => {
116    h = Math.imul(h ^ (h >>> 15), 2246822507)
117    h = Math.imul(h ^ (h >>> 13), 3266489909)
118    return ((h ^= h >>> 16) >>> 0) / 4294967296
119  }
120}
121
122export function seededShuffle(list, seed) {
123  const random = seeded(seed)
124  const out = [...list]
125  for (let i = out.length - 1; i > 0; i--) {
126    const j = Math.floor(random() * (i + 1))
127    ;[out[i], out[j]] = [out[j], out[i]]
128  }
129  return out
130}
131
132// A vowel that breaks the vowel harmony, and a Turkish letter without its dots
133// or its cedilla (or with them where none belong)
134const HARMONY_SWAPS = { e: 'a', a: 'e' }
135const LETTER_SWAPS = { ı: 'i', i: 'ı', ş: 's', s: 'ş', ç: 'c', c: 'ç', ğ: 'g', g: 'ğ', ö: 'o', o: 'ö', ü: 'u', u: 'ü' }
136
137// Misspellings of a word, one letter off each, for the wrong options of a cloze.
138// The end of a word carries the suffixes, so the changes start there; the first
139// letter stays. One of each kind comes first, then the rest. `taken` rules out
140// a real word and an option the cloze already has.
141export function misspellings(word, taken) {
142  const letters = Array.from(word)
143  const variants = (swaps) => {
144    const out = []
145    for (let i = letters.length - 1; i > 0; i--) {
146      const swap = swaps[letters[i]]
147      if (!swap) continue
148      const v = [...letters.slice(0, i), swap, ...letters.slice(i + 1)].join('')
149      if (!taken(v) && !out.includes(v)) out.push(v)
150    }
151    return out
152  }
153  const harmony = variants(HARMONY_SWAPS)
154  const letter = variants(LETTER_SWAPS)
155  const first = [harmony[0], letter[0]].filter(Boolean)
156  return [...new Set([...first, ...harmony.slice(1), ...letter.slice(1)])]
157}
158
159// Items from the daily cards files (cards/<date>.json), which the lesson job
160// writes with checked wrong options and cloze gaps
161export function itemsFromCards(files) {
162  const out = []
163  for (const f of files) {
164    for (const [order, c] of (f.items ?? []).entries()) {
165      if (!c || (c.kind !== 'word' && c.kind !== 'sentence') || !c.tr || !c.en) continue
166      const cloze = validCloze(c.cloze) ? c.cloze : undefined
167      out.push({
168        id: itemId(c.kind, c.tr),
169        kind: c.kind,
170        tr: c.tr,
171        en: c.en,
172        note: c.note ?? '',
173        example: c.example?.tr && c.example?.en ? c.example : undefined,
174        distractors: Array.isArray(c.distractors) ? c.distractors.filter((d) => typeof d === 'string' && d !== c.en).slice(0, 3) : [],
175        ...(cloze ? { cloze } : {}),
176        date: f.date,
177        source: 'cards',
178        order,
179      })
180    }
181  }
182  return out
183}
184
185function validCloze(c) {
186  return (
187    c &&
188    typeof c.text === 'string' &&
189    c.text.includes('___') &&
190    Array.isArray(c.options) &&
191    c.options.length >= 2 &&
192    c.options.includes(c.answer) &&
193    new Set(c.options).size === c.options.length
194  )
195}
196
197// A cards item replaces a lesson item with the same Turkish, and keeps the
198// lesson's cloze when it has none of its own
199export function mergeItems(lessonItems, cardItems) {
200  const byId = new Map(lessonItems.map((it) => [it.id, it]))
201  for (const c of cardItems) {
202    const old = byId.get(c.id)
203    byId.set(c.id, old && old.cloze && !c.cloze ? { ...c, cloze: old.cloze } : c)
204  }
205  return [...byId.values()]
206}
207
208// The card to show now: the item that has been due longest, then a new item
209// while today's budget lasts (newest day first; within a day, the cards file's
210// order, then the lesson's).
211// `newAllowed` limits new items to the recent lessons, and `fits(item, stage)`
212// limits the card types (the band shows no typed cards).
213export function pickCard(items, state, now, newToday, newAllowed = () => true, fits = () => true) {
214  const due = items
215    .filter((it) => state[it.id] && state[it.id].due <= now && fits(it, state[it.id].stage))
216    .sort((a, b) => state[a.id].due - state[b.id].due)
217  if (due.length > 0) return { item: due[0], stage: state[due[0].id].stage, isNew: false }
218  if (newToday >= NEW_PER_DAY) return null
219  const fresh = items
220    .filter((it) => !state[it.id] && newAllowed(it) && fits(it, stagesOf(it)[0]))
221    .sort((a, b) => (a.date === b.date ? a.order - b.order : a.date < b.date ? 1 : -1))
222  if (fresh.length === 0) return null
223  return { item: fresh[0], stage: stagesOf(fresh[0])[0], isNew: true }
224}
225
226// The next item to come due, for "Practice more" and the "next review" line
227export function nextDue(items, state, fits = () => true) {
228  return items.filter((it) => state[it.id] && fits(it, state[it.id].stage)).sort((a, b) => state[a.id].due - state[b.id].due)[0] ?? null
229}
230
231// The new state of an item after one answer at one stage
232export function answer(item, prev, stage, isRight, now) {
233  const stages = stagesOf(item)
234  const i = Math.max(0, stages.indexOf(stage))
235  const base = prev ?? { stage, box: 0, due: now, reps: 0, lapses: 0 }
236  const reps = base.reps + 1
237  if (!isRight) {
238    // One stage back, but never back to the intro
239    const back = Math.max(stages[0] === 'intro' ? 1 : 0, i - 1)
240    return { ...base, stage: stages[back], box: 0, due: now + RETRY_STEP, reps, lapses: base.lapses + 1 }
241  }
242  if (i < stages.length - 1) {
243    // Still learning: the next, harder card later today
244    return { ...base, stage: stages[i + 1], due: now + (stage === 'intro' ? MINUTE : LEARN_STEP), reps }
245  }
246  // Translate stage: the next interval
247  const box = Math.min(base.box + 1, INTERVALS.length)
248  return { ...base, stage, box, due: now + INTERVALS[box - 1] * DAY, reps }
249}
250
251// Counts for the header: due now, learning, known
252export function summary(items, state, now) {
253  let due = 0
254  let learning = 0
255  let known = 0
256  for (const it of items) {
257    const s = state[it.id]
258    if (!s) continue
259    if (s.due <= now) due++
260    if (s.box === 0) learning++
261    else known++
262  }
263  return { due, learning, known }
264}
265