SLOPSHOPPER

prayer-times

The current prayer and how long is left, the next prayer, and zawal, above the prompt. Computed on your computer from your location; nothing is sent anywhere.

bandcommandtoasttimer
★ 393v0.1.5MITupdated 2026-10-23hamzafer/claude-code-mods/mods/prayer-times
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · prayer-times
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /prayers ⎿ prayer-times: Set your latitude and longitude in /config (prayer-times). They stay on this computer. 🕌 prayer-times: set your latitude and longitude in /config. They stay on this computer ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
🕌 prayer-times: set your latitude and longitude in /config. They stay on this computer ⟨Claude Code's own drawing⟩
README

<h1 align="center">Claude Code mods</h1>

<a href="https://www.npmjs.com/package/claude-code-mods"><img src="https://img.shields.io/npm/v/claude-code-mods.svg" alt="npm"></a> <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT"></a> <a href="https://github.com/hamzafer/claude-code-mods/actions/workflows/ci.yml"><img src="https://github.com/hamzafer/claude-code-mods/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI"></a>

<a href="#-install">Install</a> · <a href="#-the-mods">All mods</a> · <a href="docs/mods.md">Docs</a> · <a href="https://claude.dev/blog/getting-started-with-claude-code-mods/">What are mods?</a>

<table> <tr> <td align="center" width="33%"><a href="docs/mods.md#-context-bar"><img src="images/context-bar.png" alt="context-bar: Claude Code context window usage as a stacked bar, a color per category" width="260"></a><br>📊 <b>context-bar</b><br>what fills your context</td> <td align="center" width="33%"><a href="docs/mods.md#-review-watch"><img src="images/review-watch.png" alt="review-watch: live lines for running Codex and subagent code reviews in Claude Code" width="260"></a><br>🔍 <b>review-watch</b><br>running code reviews, live</td> <td align="center" width="33%"><a href="docs/mods.md#-md-preview"><img src="images/md-preview.png" alt="md-preview: Markdown that Claude Code edits, rendered like GitHub next to the diff" width="260"></a><br>📝 <b>md-preview</b><br>Markdown rendered like GitHub</td> </tr> <tr> <td align="center" width="33%"><a href="docs/mods.md#-blast-radius"><img src="images/gallery/blast-radius.png" alt="blast-radius: a Claude Code hook holds rm -rf and lists the files it would delete" width="260"></a><br>💥 <b>blast-radius</b><br>see what <code>rm -rf</code> would delete</td> <td align="center" width="33%"><a href="docs/mods.md#-now-playing"><img src="images/now-playing.png" alt="now-playing: Spotify track, progress bar and synced lyrics inside Claude Code" width="260"></a><br>🎵 <b>now-playing</b><br>Spotify and its lyrics, live</td> <td align="center" width="33%"><a href="docs/mods.md#-reels-and-snake"><img src="images/reels-demo.gif" alt="reels: YouTube Shorts in a Claude Code pane while it works" width="260"></a><br>📱 <b>reels</b><br>Shorts while Claude works</td> </tr> <tr> <td align="center" width="33%"><a href="docs/mods.md#-where-am-i"><img src="images/gallery/where-am-i.png" alt="where-am-i: the session goal, current step and what waits on you, above the Claude Code prompt" width="260"></a><br>📍 <b>where-am-i</b><br>goal, now, waiting on you</td> <td align="center" width="33%"><a href="docs/mods.md#-lines-above-the-prompt"><img src="images/gallery/lines.png" alt="token-weather, usage-meter and other Claude Code status lines stacked above the prompt" width="260"></a><br>🌦️ <b>token-weather and friends</b><br>lines above the prompt</td> <td align="center" width="33%"><a href="#mission-control"><img src="images/gallery/mission-control.png" alt="mission-control: Claude Code subagents, tool calls and the files they touch, live" width="260"></a><br>🛰️ <b>mission-control</b><br>agents and the code they touch</td> </tr> <tr> <td align="center" width="33%"><a href="docs/mods.md#-switchboard"><img src="images/switchboard.png" alt="switchboard: subagents routed from opus to sonnet and haiku, with confidence and cost" width="260"></a><br>🔀 <b>switchboard</b><br>cheaper models for subagents</td> <td align="center" width="33%"><a href="docs/mods.md#-agent-radar"><img src="images/agent-radar.png" alt="agent-radar: a running subagent and two background shells with their latest output" width="260"></a><br>📡 <b>agent-radar</b><br>subagents and shells, live</td> <td align="center" width="33%"><a href="docs/mods.md#-reels-and-snake"><img src="images/snake.png" alt="snake: a game of Snake in a Claude Code pane" width="260"></a><br>🐍 <b>snake</b><br>a game while Claude works</td> </tr> </table>

🚀 Install

npx claude-code-mods@latest

Tick the mods you want in a checklist, see what each one adds, and press Enter to install. Untick a mod to disable it (its settings stay). Restart Claude Code after. @latest makes npx skip an old cached copy.

  • --project installs for this project only
  • --dry-run prints the claude commands instead of running them
  • --pick a,b turns on exactly these mods, no checklist (--pick "" turns all off)
  • --yes-community installs picked community mods without asking (outside a terminal they are skipped without it)
  • --help shows usage

It edits the Claude profile that claude uses here, shown at the top. For another profile, set it first: CLAUDE_CONFIG_DIR=~/.claude-other npx claude-code-mods@latest.

Order your bands

Press o in the checklist to order your bands (the lines above the prompt). Move the cursor with up/down or j/k, move a band with Shift+up/down or K/J, and press Enter to save. Esc goes back without saving. The order goes to <config dir>/claude-code-mods/bands.json, where the config dir is CLAUDE_CONFIG_DIR or ~/.claude. Restart Claude Code to apply it. Bands not in the file sit on top.

Other ways

By hand:

claude plugin marketplace add hamzafer/claude-code-mods
claude plugin install context-bar@claude-code-mods

To try one without installing:

git clone https://github.com/hamzafer/claude-code-mods && cd claude-code-mods
claude --plugin-dir mods/context-bar

Needs Claude Code 2.1.287+. A few mods need more (Chrome, gh, a connector); the tables say which.

🧩 The mods

👀 See what's happening

ModWhat it doesCommand
🛰️mission-controlLive map of agents, tool calls and the code they touch/mission
📊context-barYour context window as one stacked bar, a color per category, with token counts and where it compacts/context-bar
🌦️token-weatherContext fill from Clear to Compact soon, plus a prompt-cache countdown
⏱️cache-clockA prompt-cache line under your status line, from Claude Code's own figures: time left, hit rate and misses, and the tokens your next message re-caches once it goes cold. Needs Node and Claude Code 2.1.287+/cache-clock setup
📍where-am-iGoal, doing now, waiting on you, next step/where
➡️next-steps2 or 3 likely next prompts after each turn, one key to draft one. language sets their language, layout: rows keeps one per row1 2 3, 0 hides
💰usage-meter5-hour and 7-day plan usage, the reset countdown and the session's cost
🔥heatmapA GitHub-style grid of your Claude Code time, with your streak, peak hours and top projects/heatmap
💳openai-balanceYour OpenAI API credit: an estimated balance with a gauge, today's spend, where the money mostly went, and the last call. Needs an OpenAI organization Admin key/openai-balance
🪙openrouter-balanceYour OpenRouter credit: the real balance with a gauge, today's spend and the model the money mostly went to. A regular API key shows the balance too when OpenRouter allows it, plus its own spend and limit/openrouter-balance
📡agent-radarOne live line per running subagent or background shell/radar
🔍review-watchOne live line per running code review (Codex or a review subagent) with the model, target, elapsed time and Codex's latest output. A toast lists the findings when it ends
🌐browser-lanesWhether this session has a browser, and who holds it/browser
🕌prayer-timesThe current prayer and how long is left, the next one, and zawal. Computed on your computer, Hanafi or standard Asr/prayers
🎬replay-theaterSteps through the last turn's edits, one diff at a time/replay
📝md-previewRenders the Markdown files Claude edits like GitHub does, with before and after side by side. Needs Chrome and a terminal that shows images/md

🛡️ Guard your repo

ModWhat it doesCommand
💥blast-radiusHolds rm -r, force pushes and migrations, shows what they'd delete, cancels after 60 s with no answer

💸 Spend less

ModWhat it doesCommand
🔀switchboardPicks the model for each subagent that doesn't name one, with OpenAI's Decisions API or Jev, from its short label only. Shows what every subagent cost/route

🔧 My setup (fork and adapt)

These are built around my own tools and rules. Fork them and change the rules to yours.

ModWhat it doesCommand
👀glanceOne line with what needs you: next meeting, PRs, Linear issues, Slack DMs. Needs gh and the Google Calendar, Linear and Slack connectors/glance
🚦merge-gateHolds gh pr merge until CI is green and Codex reviewed once. Needs gh and the Codex CLI. Reviews run on one fixed model; change it to yours/gate
📏rulebook-guardEnforces my writing and git rules: rewrites em dashes, asks before --amend, unformatted pushes, emails and phone numbers in notes
💾session-saverSaves where you left off, shows it on resume. Needs unpause/park [note]

🎮 For fun (opt-in)

ModWhat it doesCommand
📱reelsYouTube Shorts while Claude works, pauses when it's done/reels
🐍snakeSnake while Claude works/snake
🎵now-playingWhat Spotify is playing, with a progress bar, the lyric being sung, and ⏮ ⏸ ⏭ buttons. Needs macOS and the Spotify app/music

🤝 Community mods

Mods by other people, in their own marketplaces. They're not maintained here, so read the code before you install. They also show up last in the npx claude-code-mods@latest checklist.

ModWhat it doesInstall
🖼️image-view by @jarrodwattsSee the images you paste into Claude Code: thumbnails above the prompt instead of bare [Image #1] tagsclaude plugin marketplace add jarrodwatts/claude-image-view then claude plugin install image-view@claude-image-view
🏷️last-prompt-title by @zhangbububuSession titles that follow your latest prompt: cut for the CLI, written by Haiku for the desktop sidebarclaude plugin marketplace add zhangbububu/session-titles then claude plugin install last-prompt-title@session-titles
🌏cc-zh by @jiangnanquanSimplified Chinese UI localization via static dictionary: slash-command descriptions, /config labels, spinner, hints, notices, command output, tool summaries and turn duration. Zero tokens / network; verified on CC 2.1.296claude plugin marketplace add jiangnanquan/claude-code-zh then claude plugin install cc-zh@claude-code-zh
🎛️subagent-tuner by @KruhlikauPicks the model and effort of every subagent: a Manual/Auto band, a pick pane, review → Opus and search → Haiku, and a saved default that overrides what the agent asked forclaude plugin marketplace add Kruhlikau/subagent-tuner then claude plugin install subagent-tuner@subagent-tuner
🛒mod-store by @hellosverreAn app store in a pane: /mods browses, searches and installs about 2,700 community mods, with what each one can access shown before you install. Or ask Claude to find oneclaude plugin marketplace add hellosverre/mod-store then claude plugin install mod-store@mod-store
📈cache-meter by @T-AI-LabsThe share of each turn the prompt cache served, next to the context fill, with an auto-compact threshold and Compact and Clear buttonsclaude plugin marketplace add T-AI-Labs/claude-code-mods then claude plugin install cache-meter@T-AI-Labs
⏳usage-limits by @T-AI-Labs5-hour and weekly plan limits in percent, with the time left until each resetsclaude plugin marketplace add T-AI-Labs/claude-code-mods then claude plugin install usage-limits@T-AI-Labs
🟣pixel-pulse by @air01adityaA purple pixel strip above the prompt that drifts right to left and glows under the pointer, and a purple pixel spiral in place of the working spinner. Desktop app only; it only drawsclaude plugin marketplace add air01aditya/pixel-pulse then claude plugin install pixel-pulse@pixel-pulse
🔗open-paths by @kiankhoobanClick a file path in Claude's reply and the file opens in its app: Word, Preview or Excel for documents, your editor at the line for app.py:42, Finder for folders. Launchers, scripts and unknown types are never openedclaude plugin marketplace add kiankhooban/open-paths then claude plugin install open-paths@open-paths
🎼workflow-conductor by @bruwTerminal UI for planning, running and understanding complex agent workflows inside Claude Code: define the workflow as a graph, have Claude script and run it, and watch the run on the same graph. Needs Claude Code 2.1.296+ and a terminal 110+ columns wideclaude plugin marketplace add bruw/workflow-conductor then claude plugin install workflow-conductor@workflow-conductor
💸bedrock-meter by @weidu-tpvisionToken and USD meter for Claude Code on Amazon Bedrock: session cost, context fill, cache hit rate and today's total above the prompt, priced at AWS's own on-demand rates (refreshed weekly from the AWS price list), with a per-model breakdown in /bedrock-costclaude plugin marketplace add weidu-tpvision/claude-mods then claude plugin install bedrock-meter@weidu-claude-mods
📱brainrot-break by @BordyVA TikTok-style feed of 350+ pixel art mini-videos in a pane while Claude answers: scroll, like, pick your themes, and an end card when Claude is done. Every video is a small simulation drawn locally: no tokens, no model calls. Terminal and desktop app, in 6 languages. Try it in the browserclaude plugin marketplace add BordyV/brainrot-break then claude plugin install brainrot-break@brainrot-break

Built one? Open a PR that adds a row.

<a id="mission-control"></a>

🛰️ Flagship: mission-control

Every subagent, every tool call and every file they touch, in a pane next to the chat. Shown at 4x: two subagents building a logout feature across four files.

mission-control at 4x: two subagents and a logout feature landing across four files

Install it like any mod, restart, and type /mission (or /mission code to open the code map). q closes it.

  • 🤖 w shows the agents and every tool call, live
  • 🗺️ c shows the code map, with import arrows
  • 🔵 Blue while the agent reads a file
  • 🟠 Orange while it writes
  • 🟢 Green when done, with one line on what changed

The Code view runs on macOS and Linux and needs Google Chrome or Chromium and a terminal that shows images (Ghostty, kitty, iTerm2). The Who view works everywhere.

📚 More

Source 3 files
hooks/register.tsx 357 lines
1// Prayer Times: which prayer is it, and how long is left?
2//   One line above the prompt: the current prayer and the time left to pray it, then the
3//   next one; zawal and the makruh minutes after sunrise and before sunset in red. The times
4//   are computed on this computer from the latitude and longitude in /config (the sun's
5//   position, as prayer apps do it), so the location is never sent anywhere.
6//   /prayers lists today's times. A toast says when a prayer begins, and again when its time
7//   is nearly over.
8import { atom, read, update } from 'claude-code'
9import type { EngineInterface, Register, Timer } from 'claude-code'
10
11import { bandsFile, parseOrder, stackBands } from './bands'
12
13const MIN = 60_000
14const SOON_MIN = 20 // the time left turns yellow under this many minutes
15const LAST_MIN = 5 // and red under this many
16
17// The sun's angle below the horizon for Fajr and Isha; Makkah's Isha is a fixed 90 minutes after Maghrib.
18const METHODS = {
19  karachi: { fajr: 18, isha: 18 },
20  mwl: { fajr: 18, isha: 17 },
21  isna: { fajr: 15, isha: 15 },
22  egypt: { fajr: 19.5, isha: 17.5 },
23  makkah: { fajr: 18.5, isha: 90 / 60, ishaIsMinutes: true },
24} as const
25
26export type Config = {
27  latitude: number
28  longitude: number
29  method: keyof typeof METHODS
30  asr: 'hanafi' | 'standard'
31  highLatitude: 'angle' | 'seventh' | 'middle'
32  adjust?: Partial<Record<Adjustable, number>> // minutes, to match a mosque's timetable
33}
34
35type Adjustable = 'fajr' | 'sunrise' | 'dhuhr' | 'asr' | 'sunset' | 'isha'
36
37// A day's times in hours after midnight UTC of that date (some may fall before 0 or past 24).
38export type Times = { fajr: number; sunrise: number; noon: number; dhuhr: number; asr: number; sunset: number; isha: number; estimated?: boolean }
39
40// Held by the host, so the line keeps ticking across a hot reload.
41const now = atom({ plugin: 'prayer-times', key: 'now' } as const, 0)
42
43let bandOrder: Promise<string[]> | undefined // read once per session: restart to apply
44
45export const register: Register = (on, options) => {
46  const cfg = configFrom(options)
47  const makruh = num(options.makruhMinutes, 15)
48  const zawal = num(options.zawalMinutes, 5)
49  const toasts = options.toasts !== false
50  const warnMinutes = Math.min(120, num(options.warnMinutes, 15))
51  let toasted = ''
52  let warned = ''
53  let timer: Timer | undefined // one timer, even if session.start fires again
54
55  on('session.start', async ($, e, next) => {
56    const r = await next(e)
57    await $.command.register({ name: 'prayers', description: "Today's prayer times" }).catch(() => {})
58    const first = await $.clock.now()
59    await update($, now, () => first)
60    // The line moves each minute; a toast marks the start of each prayer, and another its last minutes.
61    timer?.cancel()
62    timer = $.clock.every(30_000, () => {
63      void (async () => {
64        const t = await $.clock.now()
65        await update($, now, () => t)
66        if (!cfg || !toasts) return
67        const s = status(cfg, new Date(t), makruh, zawal)
68        const key = `${s.current?.name}@${s.current?.start.toDateString()}`
69        if (s.current && t - s.current.start.getTime() < 60_000 && key !== toasted) {
70          toasted = key
71          $.ui.toast(`🕌 ${s.current.name} has begun · until ${hhmm(s.current.end)}`)
72        }
73        const due = deadlineDue(s, new Date(t), warnMinutes, warned, makruh)
74        if (due) {
75          warned = due.key
76          $.ui.toast(due.text)
77        }
78      })().catch(() => {})
79    })
80    return r
81  })
82
83  on('command.run', { command: 'prayers' }, async () => {
84    if (!cfg) return { text: 'Set your latitude and longitude in /config (prayer-times). They stay on this computer.' }
85    const d = new Date()
86    const t = timesFor(cfg, d)
87    const at = (h: number) => hhmm(atHours(d, h))
88    return {
89      text:
90        `Fajr ${at(t.fajr)} · Sunrise ${at(t.sunrise)} · Zawal ${at(t.noon - zawal / 60)} · Dhuhr ${at(t.dhuhr)} · ` +
91        `Asr ${at(t.asr)} · Maghrib ${at(t.sunset)} · Isha ${at(t.isha)} (${cfg.method}, ${cfg.asr} Asr` +
92        `${t.estimated ? ', no sunrise or sunset today: estimated from latitude 65°' : ''})`,
93    }
94  })
95
96  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
97    const rest = await next(e) // what other mods and Claude Code draw here stays
98    if (e.props.hasSurvey) return rest
99    const t = (await read($, now)) || Date.now() // subscribes the line to the clock
100    const { Box, Text } = $.ui.resolve(e)
101    if (!cfg) {
102      const ask = (
103        <Box paddingX={1}>
104          <Text dimColor wrap="truncate-end">{'🕌 prayer-times: set your latitude and longitude in /config. They stay on this computer'}</Text>
105        </Box>
106      )
107      return stackBands(rest, 'prayer-times', ask, 'above', await (bandOrder ??= readBandOrder($).catch(() => []))) // above what other mods draw, unless the band order says otherwise
108    }
109    const s = status(cfg, new Date(t), makruh, zawal)
110    const mine = (
111      <Box paddingX={1}>
112        <Text wrap="truncate-end">
113          {s.parts.map((p, i) => {
114            // A leading emoji is drawn plain: some terminals shift or clip a bold one.
115            const icon = /^(\p{Extended_Pictographic}\uFE0F?) /u.exec(p.text)?.[1]
116            const label = icon ? p.text.slice(icon.length) : p.text
117            return (
118              <Text>
119                {i > 0 && <Text dimColor>{' · '}</Text>}
120                {icon && <Text>{icon}</Text>}
121                <Text color={p.color} bold={p.bold} dimColor={p.dim}>{label}</Text>
122              </Text>
123            )
124          })}
125        </Text>
126      </Box>
127    )
128    return stackBands(rest, 'prayer-times', mine, 'above', await (bandOrder ??= readBandOrder($).catch(() => []))) // above what other mods draw, unless the band order says otherwise
129  })
130}
131
132// The band order file, as the claude-code-mods checklist saves it; [] on any error.
133async function readBandOrder($: EngineInterface): Promise<string[]> {
134  const file = bandsFile(await $.env.get('CLAUDE_CONFIG_DIR'), await $.env.get('HOME'))
135  return file && (await $.fs.exists(file)) ? parseOrder(await $.fs.read(file)) : []
136}
137
138// Forgets the cached band order, for tests.
139export function resetBandOrder() {
140  bandOrder = undefined
141}
142
143const DHUHR_AFTER = 2 / 60 // Dhuhr starts this long after the sun's highest point
144
145type Part = { text: string; color?: string; bold?: boolean; dim?: boolean }
146type Window = { name: string; start: Date; end: Date }
147
148// What the line says at `at`: the prayer whose time it is and what is left, or the forbidden window, then the next prayer.
149export function status(cfg: Config, at: Date, makruh = 15, zawal = 5) {
150  // Times are UTC hours of each local date, so far from UTC (e.g. UTC+13) a day's prayers can sit two dates back.
151  const windows = [-2, -1, 0, 1].flatMap(offset => dayWindows(cfg, addDays(at, offset), makruh, zawal))
152  const inside = (w: Window) => w.start <= at && at < w.end
153  const prayers = windows.filter(w => !w.name.startsWith('!'))
154  const current = prayers.find(inside)
155  const blocked = windows.find(w => w.name.startsWith('!') && inside(w))
156  const next = prayers.find(w => w.start > at)!
157  const parts: Part[] = []
158
159  if (blocked) {
160    const label = blocked.name === '!zawal' ? 'Zawal' : blocked.name === '!sunrise' ? 'Sunrise' : 'Sunset near'
161    parts.push({ text: `⛔ ${label}`, color: 'red', bold: true })
162    if (blocked.name === '!sunset' && current) parts.push({ text: `${current.name} ${until(current.end, at)} left, makruh now`, color: 'red' })
163    else parts.push({ text: `no prayer for ${until(blocked.end, at)}`, color: 'red' })
164  } else if (current) {
165    const left = (current.end.getTime() - at.getTime()) / MIN
166    parts.push({ text: `🕌 ${current.name}`, bold: true })
167    parts.push({ text: `${until(current.end, at)} left`, color: left < LAST_MIN ? 'red' : left < SOON_MIN ? 'yellow' : 'green', bold: left < SOON_MIN })
168  } else {
169    parts.push({ text: `🕌 ${next.name} in ${until(next.start, at)}`, bold: true })
170  }
171  if (current || blocked) parts.push({ text: `next ${next.name} ${hhmm(next.start)}`, dim: true })
172  // Before Dhuhr, say when zawal comes.
173  const z = windows.find(w => w.name === '!zawal' && w.start > at)
174  if (z && next.name === 'Dhuhr' && !blocked) parts.push({ text: `zawal ${hhmm(z.start)}`, dim: true })
175  if (timesFor(cfg, at).estimated) parts.push({ text: 'estimated (no sunrise or sunset today)', dim: true })
176  return { parts, current, next, blocked }
177}
178
179// The warning that the current prayer's time is nearly over, once per window (`warned` is the last key warned).
180// It also comes when the session starts inside the last minutes, but not for a window no longer than the warning,
181// whose start toast already says when it ends. Asr warns too: its time runs to sunset, through the makruh minutes.
182// Asr's real deadline is the start of the makruh minutes before sunset, so it warns before those.
183export function deadlineDue(s: Pick<ReturnType<typeof status>, 'current'>, at: Date, warnMinutes: number, warned: string, makruh = 0) {
184  const w = s.current
185  if (!w || !(warnMinutes > 0)) return null
186  const key = `${w.name}@${w.start.getTime()}`
187  const end = w.name === 'Asr' && makruh > 0 ? new Date(w.end.getTime() - makruh * MIN) : w.end
188  const left = (end.getTime() - at.getTime()) / MIN
189  const length = (w.end.getTime() - w.start.getTime()) / MIN
190  if (key === warned || left <= 0 || left > warnMinutes || length <= warnMinutes) return null
191  if (end !== w.end) return { key, text: `⏳ Asr: makruh in ${Math.ceil(left)} min (${hhmm(end)}), sunset ${hhmm(w.end)}` }
192  return { key, text: `⏳ ${w.name} ends in ${Math.ceil(left)} min (${hhmm(w.end)})` }
193}
194
195// One day's windows: each prayer from its start to its end (Hanafi), and the times not to pray, marked with `!`.
196function dayWindows(cfg: Config, day: Date, makruh: number, zawal: number): Window[] {
197  const t = timesFor(cfg, day)
198  const tomorrow = timesFor(cfg, addDays(day, 1))
199  const at = (h: number) => atHours(day, h)
200  return [
201    { name: 'Fajr', start: at(t.fajr), end: at(t.sunrise) },
202    { name: '!sunrise', start: at(t.sunrise), end: at(t.sunrise + makruh / 60) },
203    { name: '!zawal', start: at(t.noon - zawal / 60), end: at(t.noon + DHUHR_AFTER) },
204    { name: 'Dhuhr', start: at(t.dhuhr), end: at(t.asr) },
205    { name: 'Asr', start: at(t.asr), end: at(t.sunset) },
206    { name: '!sunset', start: at(t.sunset - makruh / 60), end: at(t.sunset) },
207    { name: 'Maghrib', start: at(t.sunset), end: at(t.isha) },
208    { name: 'Isha', start: at(t.isha), end: at(24 + tomorrow.fajr) },
209  ]
210}
211
212// The day's times at the computer's own time zone for that date.
213// The times for the computer's local date, as UTC hours, so a daylight-saving change that day can't shift them.
214export function timesFor(cfg: Config, day: Date): Times {
215  const t = computeTimes(cfg, day.getFullYear(), day.getMonth() + 1, day.getDate(), 0)
216  for (const [k, m] of Object.entries(cfg.adjust ?? {})) t[k as Adjustable] += m / 60
217  return t
218}
219
220// `asr+2 isha-5` as minutes per time. Dhuhr moves Dhuhr's start only (zawal stays on the sun's highest point); Maghrib moves sunset.
221export function adjustFrom(text: string): Config['adjust'] {
222  const names: Record<string, Adjustable> = { fajr: 'fajr', sunrise: 'sunrise', dhuhr: 'dhuhr', asr: 'asr', maghrib: 'sunset', isha: 'isha' }
223  const out: Partial<Record<Adjustable, number>> = {}
224  for (const m of text.toLowerCase().matchAll(/(fajr|sunrise|dhuhr|asr|maghrib|isha)\s*([+-]?)\s*(\d+(?:\.\d+)?)/g)) out[names[m[1]!]!] = (m[2] === '-' ? -1 : 1) * Number(m[3])
225  return out
226}
227
228// The sun's position for the day, then the times it reaches each prayer's angle (the PrayTimes method).
229export function computeTimes(cfg: Config, year: number, month: number, day: number, zone: number): Times {
230  const t = solve(cfg, year, month, day, zone)
231  if (Number.isFinite(t.sunrise) && Number.isFinite(t.sunset)) return t
232  // Polar day or night: no sunrise or sunset at all. Use the nearest latitude that has them (65°), as many scholars advise.
233  return { ...solve({ ...cfg, latitude: Math.sign(cfg.latitude) * 65 }, year, month, day, zone), estimated: true }
234}
235
236function solve(cfg: Config, year: number, month: number, day: number, zone: number): Times {
237  const { latitude: lat, longitude: lng } = cfg
238  const m = METHODS[cfg.method]
239  const jdate = julian(year, month, day) - lng / (15 * 24)
240  const sun = (t: number) => sunPosition(jdate + t)
241  const midDay = (t: number) => fix(12 - sun(t).equation, 24)
242  const angleTime = (angle: number, t: number, before: boolean) => {
243    const decl = sun(t).declination
244    const noon = midDay(t)
245    const cos = (-sin(angle) - sin(decl) * sin(lat)) / (cos_(decl) * cos_(lat))
246    const span = acos(cos) / 15 // NaN when the sun never reaches the angle
247    return noon + (before ? -span : span)
248  }
249  const asrTime = (factor: number, t: number) => {
250    const decl = sun(t).declination
251    return angleTime(-acot(factor + tan(Math.abs(lat - decl))), t, false)
252  }
253  const factor = cfg.asr === 'hanafi' ? 2 : 1
254
255  // Two passes: the first from rough guesses, the second from the first's answers.
256  let h = { fajr: 5, sunrise: 6, noon: 12, asr: 13, sunset: 18, isha: 18 }
257  for (let pass = 0; pass < 2; pass++) {
258    const d = (x: number) => x / 24
259    h = {
260      fajr: angleTime(m.fajr, d(h.fajr), true),
261      sunrise: angleTime(0.833, d(h.sunrise), true),
262      noon: midDay(d(h.noon)),
263      asr: asrTime(factor, d(h.asr)),
264      sunset: angleTime(0.833, d(h.sunset), false),
265      isha: 'ishaIsMinutes' in m ? NaN : angleTime(m.isha, d(h.isha), false),
266    }
267  }
268  const shift = zone - lng / 15
269  const out: Times = { fajr: h.fajr + shift, sunrise: h.sunrise + shift, noon: h.noon + shift, dhuhr: h.noon + shift + DHUHR_AFTER, asr: h.asr + shift, sunset: h.sunset + shift, isha: h.isha + shift }
270  if ('ishaIsMinutes' in m) out.isha = out.sunset + m.isha
271
272  // Far from the equator the sun may never get low enough: Fajr and Isha take a share of the night instead.
273  const night = 24 - (out.sunset - out.sunrise)
274  const share = (angle: number) => (cfg.highLatitude === 'seventh' ? 1 / 7 : cfg.highLatitude === 'middle' ? 1 / 2 : angle / 60)
275  const fajrMax = share(m.fajr) * night
276  if (!Number.isFinite(out.fajr) || out.sunrise - out.fajr > fajrMax) out.fajr = out.sunrise - fajrMax
277  if (!('ishaIsMinutes' in m)) {
278    const ishaMax = share(m.isha) * night
279    if (!Number.isFinite(out.isha) || out.isha - out.sunset > ishaMax) out.isha = out.sunset + ishaMax
280  }
281  return out
282}
283
284function sunPosition(jd: number) {
285  const D = jd - 2451545
286  const g = fix(357.529 + 0.98560028 * D, 360)
287  const q = fix(280.459 + 0.98564736 * D, 360)
288  const L = fix(q + 1.915 * sin(g) + 0.02 * sin(2 * g), 360)
289  const e = 23.439 - 0.00000036 * D
290  const ra = atan2(cos_(e) * sin(L), cos_(L)) / 15
291  return { declination: asin(sin(e) * sin(L)), equation: q / 15 - fix(ra, 24) }
292}
293
294function julian(year: number, month: number, day: number) {
295  if (month <= 2) {
296    year -= 1
297    month += 12
298  }
299  const a = Math.floor(year / 100)
300  const b = 2 - a + Math.floor(a / 4)
301  return Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + day + b - 1524.5
302}
303
304const rad = (d: number) => (d * Math.PI) / 180
305const deg = (r: number) => (r * 180) / Math.PI
306const sin = (d: number) => Math.sin(rad(d))
307const cos_ = (d: number) => Math.cos(rad(d))
308const tan = (d: number) => Math.tan(rad(d))
309const asin = (x: number) => deg(Math.asin(x))
310const acos = (x: number) => deg(Math.acos(x))
311const atan2 = (y: number, x: number) => deg(Math.atan2(y, x))
312const acot = (x: number) => deg(Math.atan(1 / x))
313const fix = (a: number, b: number) => {
314  const r = a - b * Math.floor(a / b)
315  return r < 0 ? r + b : r
316}
317
318function configFrom(options: Record<string, unknown>): Config | null {
319  const latitude = Number(options.latitude)
320  const longitude = Number(options.longitude)
321  const isSet = (v: unknown) => v !== undefined && v !== null && v !== ''
322  if (!isSet(options.latitude) || !isSet(options.longitude) || !(Math.abs(latitude) <= 90) || !(Math.abs(longitude) <= 180)) return null
323  const method = String(options.method ?? 'karachi') as Config['method']
324  return {
325    latitude,
326    longitude,
327    method: method in METHODS ? method : 'karachi',
328    asr: options.asr === 'standard' ? 'standard' : 'hanafi',
329    highLatitude: options.highLatitude === 'seventh' || options.highLatitude === 'middle' ? options.highLatitude : 'angle',
330    adjust: adjustFrom(String(options.adjust ?? '')),
331  }
332}
333
334function num(value: unknown, fallback: number) {
335  const n = Number(value)
336  return value === undefined || value === null || value === '' || !Number.isFinite(n) ? fallback : Math.max(0, n)
337}
338
339function addDays(d: Date, n: number) {
340  return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n, 12)
341}
342
343// The instant `hours` after midnight UTC of the day's local date.
344export function atHours(day: Date, hours: number) {
345  return new Date(Date.UTC(day.getFullYear(), day.getMonth(), day.getDate()) + Math.round(hours * 60) * MIN)
346}
347
348export function hhmm(d: Date) {
349  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
350}
351
352// Time left until `end`, rounded up to the minute: `42m`, `1h 05m`.
353export function until(end: Date, at: Date) {
354  const m = Math.max(0, Math.ceil((end.getTime() - at.getTime()) / MIN))
355  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
356}
357
hooks/bands.ts 73 lines
1// Band order: every band mod ships this same file (canonical copy: shared/bands.ts in the repo).
2//   The order file, <configDir>/claude-code-mods/bands.json, lists mod names top to bottom
3//   (the last sits right above the prompt). Each band mod wraps its band in a Box keyed
4//   `band:<name>` and returns one column keyed `bands`; the next band mod unpacks that
5//   column, adds its own band and sorts again, so the last one to draw sorts them all.
6//   Edit shared/bands.ts, then copy it over every mod's hooks/bands.ts (a repo test checks).
7//   Reading the file needs $, which Claude Code follows only within one file, so each mod
8//   reads it in its own register file with bandsFile and parseOrder, once per session.
9import type { RenderElement, RenderNode } from 'claude-code'
10
11const COLUMN = 'bands'
12const PREFIX = 'band:'
13
14// Where the checklist saves the order: CLAUDE_CONFIG_DIR, or ~/.claude. Undefined with neither.
15export function bandsFile(configDir: string | undefined, home: string | undefined): string | undefined {
16  const dir = configDir ? configDir.replace(/\/+$/, '') : home ? `${home}/.claude` : ''
17  return dir ? `${dir}/claude-code-mods/bands.json` : undefined
18}
19
20// The names in an order file; [] when it is no JSON or not { order: string[] }.
21export function parseOrder(text: string): string[] {
22  try {
23    const order = (JSON.parse(text) as { order?: unknown } | null)?.order
24    return Array.isArray(order) && order.every(n => typeof n === 'string') ? order : []
25  } catch {
26    return []
27  }
28}
29
30/**
31 * One column of bands: `mine` wrapped in a Box keyed `band:<name>`, placed
32 * `at` (above or below) what `next(e)` returned, then sorted by `order`.
33 * With an order, items that are no band come first, then bands not in the
34 * order (in their current order), then the listed ones in file order. With
35 * no order nothing moves, so the screen looks as it did before.
36 */
37export function stackBands(rest: RenderElement | null | undefined, name: string, mine: RenderNode, at: 'above' | 'below', order: string[]): RenderElement {
38  const own: RenderElement = { type: 'Box', props: { key: PREFIX + name, flexDirection: 'column' }, children: [mine] }
39  const others = unpack(rest)
40  const items = at === 'above' ? [own, ...others] : [...others, own]
41  return { type: 'Box', props: { key: COLUMN, flexDirection: 'column' }, children: order.length ? sorted(items, order) : items }
42}
43
44// Another band mod's column gives up its items; anything else is one item.
45function unpack(rest: RenderElement | null | undefined): RenderNode[] {
46  if (!rest) return []
47  if (!isColumn(rest)) return [rest]
48  const kids = rest.children ?? []
49  const owner = rest.part?.plugin
50  // The engine stamped the column with its owner: that stamp belongs on the owner's own band.
51  return kids.map(k => (owner && typeof k !== 'string' && bandName(k) === owner && !('part' in k && k.part) ? { ...k, part: rest.part } : k))
52}
53
54function isColumn(el: RenderElement): el is RenderElement & { type: 'Box' } {
55  return el.type === 'Box' && el.props?.key === COLUMN
56}
57
58function bandName(node: RenderNode): string | undefined {
59  if (typeof node === 'string' || node.type !== 'Box') return undefined
60  const key = node.props?.key
61  return typeof key === 'string' && key.startsWith(PREFIX) ? key.slice(PREFIX.length) : undefined
62}
63
64function sorted(items: RenderNode[], order: string[]): RenderNode[] {
65  const rank = (n: RenderNode) => {
66    const name = bandName(n)
67    if (name === undefined) return -2 // not a band: first
68    const i = order.indexOf(name)
69    return i < 0 ? -1 : i // a band not in the order: on top of the listed ones
70  }
71  return items.map((n, i) => ({ n, i, r: rank(n) })).sort((a, b) => a.r - b.r || a.i - b.i).map(x => x.n)
72}
73
types/index.d.ts 8 lines
1export type Tick = number // the last clock tick, so the line redraws each minute
2
3declare module 'claude-code' {
4  interface PluginState {
5    'prayer-times': { now: Tick }
6  }
7}
8