DEV Community

Ahmed Ashour
Ahmed Ashour

Posted on

Building a khatmah planner in React Native: a reading plan that recalculates instead of piling up debt

I build BetterMuslim, a React Native and Expo app for Muslim daily habits. This is about one feature in it, the khatmah planner: a plan to read the whole Qur'an mushaf (604 pages) by a date you choose. The code is plain TypeScript, and the interesting part was not the UI. It was three rules that are easy to get wrong.

The problem

Most reading plans I tried work like a debt tracker. Miss three days and the app greets you with "you owe 60 pages". People close the app and never come back.

I wanted the opposite:

  1. The day's target recalculates from what is left, instead of piling up as a debt.
  2. A page only counts if it was actually read, not swiped past.
  3. Marking a day done must not break the streaks of every other habit in the app.

Rule 1: recalculate, don't accrue

The plan is just a start date and a finish date. Today's target is whatever is left, spread over the days that remain:

export function dailyTargetAt(
  plan: KhatmahPlan,
  readPages: Iterable<number>,
  todayKey: string
): number {
  const remaining = TOTAL_PAGES - new Set(readPages).size;
  if (remaining <= 0) return 0;
  // Past the finish date there are no days left to spread over; it is all due now.
  const daysLeft = todayKey >= plan.finishDate ? 1 : daysInclusive(todayKey, plan.finishDate);
  return Math.max(1, Math.ceil(remaining / daysLeft));
}
Enter fullscreen mode Exit fullscreen mode

The headline stays "read these pages today". When the target grows past 1.75 times the original, the app offers to move the finish date instead. The suggested date has to actually put you back on the pace you chose, so it is computed from the original daily target, not by adding a few days:

export function suggestedFinishDate(plan, readPages, todayKey): string {
  const remaining = TOTAL_PAGES - new Set(readPages).size;
  const perDay = originalDailyTarget(plan);
  const daysNeeded = Math.max(1, Math.ceil(remaining / perDay));
  const finish = new Date(toUTC(todayKey) + (daysNeeded - 1) * MS_PER_DAY);
  return finish.toISOString().slice(0, 10);
}
Enter fullscreen mode Exit fullscreen mode

Dates are compared as UTC midnights from yyyy-MM-dd keys, so a daylight saving change cannot make a day 23 or 25 hours long and shift the count by one.

Progress is a set of pages, not a high-water mark. If someone opens Al-Kahf on a Friday, that is reading, and it counts. So "Continue" opens the first unread page, and the juz bead ring only fills a bead when every page of that juz is read. A bead that filled on the first page would show 30 of 30 long before the end.

Rule 2: a page counts after 10 seconds

If a page counted the moment it appeared, a fast swipe through the mushaf would finish a juz. So a page counts after it has been the visible page for 10 unbroken seconds, and backgrounding the app cancels it (a phone face down in a pocket is not reading):

export const PAGE_DWELL_MS = 10_000;

useEffect(() => {
  if (!enabled || !Number.isInteger(page)) return;
  if (countedRef.current.has(page)) return;
  let cancelled = false;

  const timer = setTimeout(() => {
    if (cancelled) return;
    countedRef.current.add(page);
    void KhatmahService.markPageRead(page, formatDateKey(new Date()));
  }, PAGE_DWELL_MS);

  const appState = AppState.addEventListener('change', (state) => {
    if (state !== 'active') { cancelled = true; clearTimeout(timer); }
  });

  return () => { cancelled = true; clearTimeout(timer); appState.remove(); };
}, [page, enabled]);
Enter fullscreen mode Exit fullscreen mode

The hook reads counted pages through a ref. The reader re-renders on every tap of its floating bar, and a re-render with the same page must not restart the timer.

Rule 3: don't change the global completion rule

This was the one that cost me the most thought. Across the app, a counter habit is done at value > 0. The khatmah habit needs to be done at the day's page target (say 21 pages), but changing the global rule would break the streak of every azkar habit sitting at 40 of 100 taps.

My first idea was to special case the habit by checking whether a plan exists. That has a flaw: when falling behind raises today's target from 20 to 28, yesterday would be judged against 28 and a finished day would turn into a failed one. History would rewrite itself to look worse.

So the target is written onto the day's own record, and the rule keys off the record:

export function isRecordValueComplete(
  record: Partial<Pick<SubHabitRecord, 'value' | 'target'>> | undefined | null
): boolean {
  if (!record) return false;
  const target = Number(record.target);
  if (Number.isFinite(target) && target > 0) return Number(record.value) >= target;
  return Boolean(record.value);
}
Enter fullscreen mode Exit fullscreen mode

Old records have no target, so they keep the old rule. A finished day keeps the target it carried. A missing, zero or nonsense target falls back to the old rule instead of locking the habit.

The bug the emulator found

I tested on an Android emulator in Arabic. After reading one page the Home screen showed 1/8 habits done, when it should have been 0/8. Home flattens each day into a Record<string, boolean> with Boolean(record.value) before the sections see it, so the target never reached the completion check. The fix was to decide completion where the record is still whole, which is why isRecordValueComplete takes just the record and not the habit.

Two self inflicted problems from the same session:

  • My new card mounted useHabitsData(), which created a second live copy of the habits layer, fetching and syncing next to Home's. It hung the app. It now reads the cache once.
  • Metro started returning 500 on its manifest endpoint. It was not my code. Fifteen orphaned jest-worker processes from repeated test runs had used up process creation. Killing them fixed it.

Pace presets, and a Hijri edge case

The pace sheet offers presets stored as a number of days: one page a day (604 days), a page after each prayer (ceil(604 / 5)), half a juz, a juz a day (30), 15 days, a week. There is also a Ramadan pace: during Ramadan it means finish by Eid, otherwise finish before the next Ramadan.

I did not compute that date arithmetically. Hijri months are 29 or 30 days depending on the calendar, so the code walks forward one day at a time, converts each date, and stops at the first day whose month changes. The finish date is shown on the option, so someone whose country sights the moon a day apart sees it before choosing.

What I would do differently

  • I would have written the Supabase migration and run it before the client code. The reading plan tables, row level security and the new target column on the daily records exist as a migration, but I had no Docker on that machine, so sync was untested when I wrote this up. Everything worked from local storage first, which is the right order for the user, but I should have validated the schema sooner.
  • I wrote 37 new tests before the code, and the plan arithmetic is pure, so it runs without a device. I would do the same for the Home flattening, where the bug actually was. A test on that path would have caught the 1/8 without an emulator.
  • I only built three paces first (30 days, a juz a day, 15 days) and added the rest later. People plan by pages or by a deadline, so I would have started with that fuller list.

If you are building habit tracking, my main takeaway is to attach the rule to the record, not to the habit. It keeps history stable when the rules change.

BetterMuslim is my own app, if you want to see the khatmah planner in use: bettermuslim.net.

Top comments (0)