Shows context, 5-hour and weekly limit usage in the band above the prompt

プロンプト入力欄の上の帯に、コンテキストの使用率と、5 時間制限と週間制限の使用率を表示する mod です。
ctx ██░░░░░░░░ 19% 5h ████░░░░░░ 43% 2h34m 7d █░░░░░░░░░ 9% 1d21h 14:05
HH:MM は、表示している利用制限の値を測った時刻ですデスクトップアプリでは、5h と 7d にアプリの使用量の表示と同じ値を出します。 5h と 7d の値は、このマシンのセッション間で共有します。別のセッションで使った分も、1 分ほどで反映されます。 ctx の値は、セッションごとのものです。
5h と 7d の使用率を、あとで集計できるようにファイルに書き残せます。 既定ではオフで、オンにしたときだけ書きます。
| 設定 | 既定 | 内容 |
|---|---|---|
log | false | true にすると記録を書く |
logDir | ~/.claude/usage-band/ | 記録を書くフォルダ(~ はホームフォルダ。絶対パスも使える) |
設定は、usage-band の設定の「使用率を記録する」(log)と「記録の置き場」(logDir)で変えます。
記録は日ごとのファイル usage-YYYYMMDD.jsonl(日付はこのマシンの日付)に、1 行に 1 つの JSON で書き足します。
{"ts":"2026-10-06T03:12:45.120Z","src":"card","five_hour":{"used":43,"resets_at":"2026-10-06T05:59:59.852Z"},"seven_day":{"used":9,"resets_at":"2026-10-07T23:59:59.852Z"}}
ts: 行を書いた時刻src: 値を読んだ元。card はデスクトップアプリの使用量の表示、response は Claude Code が受け取った応答five_hour、seven_day: 使用率(used、%)とリセットの時刻(resets_at)。値は読んだままです。利用制限の種類が増えると、その種類の名前(例 spend_limit)の項目も並びますClaude Code v2.1.286 以降で動作を確認しています。 インストール方法は、リポジトリの README を見てください。
hooks/register.js 573 lines1// Shows context, 5-hour limit and weekly limit usage in the band above the prompt.
2// On a narrow band the parts give way in a fixed order (fitBand): the clock first, then the
3// reset countdowns, then the bars shorten, then the bars go; the labels and percentages stay.
4// Every meter keeps its width (flexShrink 0), so none of them overlaps another or wraps.
5// The context figure is this session's own. The rate-limit figures are the account's. Where the
6// desktop app's own usage card answers (its ccd_session_mgmt server's get_usage), the 5h and weekly
7// figures come from it, so the band shows what the app shows; elsewhere (the terminal) they come
8// from the session's last API response, which lags the card by a few minutes. The newest reading
9// any session made is shared through $.store, and every session shows the newer of its own and
10// the stored.
11// With the `log` option on, each reading a session publishes to the store is also appended to
12// a daily JSON Lines file under `logDir`, so the readings can be aggregated later.
13
14// This session's context, from $.session.usage() or session.measure; never shared
15let context = null
16// This session's own rate-limit readings, { rateLimits, measuredAt, src }, one per source:
17// measuredAt is $.clock.now() ms when the figures arrived here (neither source gives a time of
18// its own), src is 'card' (the app's usage card) or 'response' (the last API response)
19let fromCard = null
20let fromResponse = null
21// Whether the last read of the card answered with figures; while it does, the card's reading is
22// this session's own and the response's is not used
23let cardOk = false
24// When the last read of the card started, for the throttle
25let cardAt = null
26// The read of the card in flight, which a second caller waits on instead of reading again
27let cardPending = null
28// A read of the card put off by the throttle, kept so a final session.end can stop it
29let cardLater = null
30// The read after a /clear or /resume (session.end), kept so a later end can stop it
31let switchLater = null
32// The reading drawn: own, or the stored one when that is newer
33let shown = null
34// Refreshes the countdowns; kept so a later session.start or session.end can stop it
35let ticker = null
36// register()'s options, defaults filled in
37let config = null
38// The last reading appended to the log, so a reading stored again (after another session's older
39// write landed last) is not logged twice
40let logged = null
41// Log appends run one after another, so two in one session never read the same old file
42let logQueue = Promise.resolve()
43// Whether this session has shown its one toast about the log
44let logWarned = false
45
46// session.end reasons after which the session is gone; /clear, /resume and logout keep it running
47const FINAL_REASONS = ['prompt_input_exit', 'other']
48// session.end reasons after which the process goes on with another conversation
49const SWITCH_REASONS = ['clear', 'resume']
50// How long after such an end the figures are read again
51const AFTER_SWITCH_MS = 1_000
52const TICK_MS = 60_000
53// The $.store key holding the newest reading any session made
54const STORE_KEY = 'rateLimits'
55// Two resetsAt this close are the same window; the next window resets at least 5 hours later
56const SAME_WINDOW_MS = 3_600_000
57// Two resetsAt this close are the same figures: the card's carry milliseconds that may move
58// between reads
59const SAME_RESET_MS = 60_000
60
61// The desktop app's usage card, and the windows of it the band shows, by label
62const CARD = { server: 'ccd_session_mgmt', tool: 'get_usage' }
63// The same tool as the model calls it
64const CARD_TOOL = 'mcp__ccd_session_mgmt__get_usage'
65const CARD_KINDS = { '5-hour limit': 'five_hour', 'Weekly · all models': 'seven_day' }
66// The card is read at most once in this many milliseconds; a read asked for sooner runs when
67// they have passed
68const CARD_GAP_MS = 10_000
69
70const LABELS = { five_hour: '5h', seven_day: '7d', spend_limit: '$' }
71
72const DEFAULTS = { log: false, logDir: '~/.claude/usage-band/' }
73
74// Usage at or above these percentages turns the meter yellow, then red
75const WARNING_AT = 50
76const ERROR_AT = 80
77
78// The text bar's cells, at full length and shortened
79const BAR_CELLS = { full: 10, short: 5 }
80const METER_GAP = 3
81// The band's last columns, which the terminal may draw over
82const BAND_RESERVED_COLUMNS = 2
83// The SVG bar's size in pixels, at full length and shortened
84const SVG_BAR = { full: 96, short: 48, height: 10 }
85// Pixels taken as one cell, to size the SVG bar in cells (an estimate: the desktop app does not
86// report its font's advance)
87const PX_PER_CELL = 8
88const SVG_COLORS = { success: '#4caf50', warning: '#e0a526', error: '#e5534b', track: 'rgba(128,128,128,0.3)' }
89
90// How the band may give way, widest first
91const STEPS = [
92 { bar: 'full', hasResets: true, hasClock: true },
93 { bar: 'full', hasResets: true, hasClock: false },
94 { bar: 'full', hasResets: false, hasClock: false },
95 { bar: 'short', hasResets: false, hasClock: false },
96 { bar: null, hasResets: false, hasClock: false },
97]
98
99export function register(on, options) {
100 config = configOf(options)
101 // Fires again on an enable or a worker respawn, which may keep this module's variables
102 on('session.start', async ($, e, next) => {
103 ticker?.cancel()
104 await readUsage($)
105 await readCard($)
106 await sync($)
107 // Counts the resets down, polls this session's figures and picks up the stored ones
108 ticker = $.clock.every(TICK_MS, () => void refresh($))
109 $.ui.invalidate('ui.render')
110 return next(e)
111 })
112
113 // The desktop app (or another client) joined the session: read the figures again
114 on('session.attach', async ($, e, next) => {
115 await refresh($)
116 return next(e)
117 })
118
119 // A final end stops the timers. /clear and /resume end the conversation while the process goes
120 // on under another: session.measure reports the new context only after the next turn, so the
121 // figures are read again once the new conversation is in place (AFTER_SWITCH_MS). A compaction
122 // or a fork raises no event an installed mod is sure to hear (the classic SessionStart is not
123 // passed to installed mods everywhere); the ticker reads them within TICK_MS.
124 on('session.end', async ($, e, next) => {
125 if (FINAL_REASONS.includes(e.reason)) {
126 ticker?.cancel()
127 cardLater?.cancel()
128 cardLater = null
129 switchLater?.cancel()
130 switchLater = null
131 } else if (SWITCH_REASONS.includes(e.reason)) {
132 switchLater?.cancel()
133 switchLater = $.clock.after(AFTER_SWITCH_MS, () => {
134 switchLater = null
135 void refresh($)
136 })
137 }
138 return next(e)
139 })
140
141 // Fires after each turn, and when a rate-limit window moves a whole point
142 on('session.measure', async ($, e, next) => {
143 context = e.context
144 fromResponse = taken(fromResponse, e.rateLimits, await $.clock.now(), 'response')
145 // The response moved, so the account's usage did: the card has likely moved too
146 if (e.changed?.includes('rateLimits')) await readCard($)
147 await sync($)
148 $.ui.invalidate('ui.render')
149 return next(e)
150 })
151
152 // The model asked the app for its usage: the band takes the same answer. The call itself is
153 // passed on and its result returned as is.
154 on('tool.call', { tool: CARD_TOOL }, async ($, e, next) => {
155 const answer = await next(e)
156 await takeCardAnswer($, answer)
157 return answer
158 })
159
160 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
161 const elements = $.ui.resolve(e)
162 const now = await $.clock.now()
163 const meters = [{ label: 'ctx', used: context?.percent, resetsAt: null }]
164 for (const limit of shown?.rateLimits ?? []) {
165 const resetsAt = limit.resetsAt == null ? null : Date.parse(limit.resetsAt)
166 // A window that reset since the last measurement starts again from zero
167 const reset = resetsAt != null && resetsAt <= now
168 meters.push({
169 label: LABELS[limit.kind] ?? limit.kind,
170 used: reset ? 0 : limit.percentUsed,
171 resetsAt: reset ? null : resetsAt,
172 })
173 }
174 for (const m of meters) {
175 m.percent = percentText(m.used)
176 m.reset = m.resetsAt == null ? null : untilReset(m.resetsAt - now)
177 }
178 const stamp = shown && shown.rateLimits.length > 0 ? clockText(shown.measuredAt) : null
179 const fit = fitBand(meters, stamp, e.surface, widthOf(e))
180
181 const children = meters.map((m) => meter(elements, e.surface, fit, m))
182 // When the shown rate-limit figures were measured, by whichever session
183 if (stamp && fit.hasClock) {
184 const time = elements.Text({ dimColor: true, wrap: 'truncate-end', children: [stamp] })
185 children.push(elements.Box({ key: 'rate-time', flexDirection: 'row', flexShrink: 0, alignItems: 'center', children: [time] }))
186 }
187 const line = elements.Box({ flexDirection: 'row', flexWrap: 'nowrap', columnGap: METER_GAP, children })
188 // Keep what later mods draw in the band
189 const rest = await next(e)
190 if (!rest) return line
191 return elements.Box({ flexDirection: 'column', children: [line, rest] })
192 })
193}
194
195async function readUsage($) {
196 const usage = await $.session.usage()
197 context = usage.context
198 fromResponse = taken(fromResponse, usage.rateLimits, await $.clock.now(), 'response')
199}
200
201// Polls this session's figures, syncs with the store and redraws; a failed read keeps the last
202// figures
203async function refresh($) {
204 try {
205 await readUsage($)
206 } catch {}
207 await readCard($)
208 await sync($)
209 $.ui.invalidate('ui.render')
210}
211
212// Reads the app's usage card into fromCard, at most once per CARD_GAP_MS: a read asked for sooner
213// is put off until then (one at a time), and a caller during a read waits on that read. Never
214// throws; a card that does not answer with figures (no such server, as in the terminal, an
215// error, or a status other than ok) leaves cardOk false, so the response's figures are used.
216function readCard($) {
217 if (cardPending) return cardPending
218 cardPending = (async () => {
219 try {
220 const now = await $.clock.now()
221 if (cardAt != null && now - cardAt < CARD_GAP_MS) {
222 cardLater ??= $.clock.after(cardAt + CARD_GAP_MS - now, () => {
223 cardLater = null
224 void refreshCard($)
225 })
226 return
227 }
228 cardAt = now
229 const limits = await cardLimits($)
230 cardOk = limits != null
231 if (cardOk) fromCard = taken(fromCard, limits, await $.clock.now(), 'card')
232 } catch {
233 cardOk = false
234 }
235 })().finally(() => {
236 cardPending = null
237 })
238 return cardPending
239}
240
241// The read the throttle put off: reads the card, syncs and redraws
242async function refreshCard($) {
243 await readCard($)
244 await sync($)
245 $.ui.invalidate('ui.render')
246}
247
248// The model called the card's tool itself: takes what it answered as a read of the card, so the
249// band shows the figures Claude reports. Silent on anything it cannot use.
250async function takeCardAnswer($, answer) {
251 try {
252 if (!answer || answer.isError || answer.deny != null) return
253 const text = typeof answer.text === 'string' ? answer.text : firstText(answer.result?.content ?? answer.result)
254 const limits = cardLimitsOf(text)
255 if (!limits) return
256 const now = await $.clock.now()
257 cardAt = now
258 cardOk = true
259 fromCard = taken(fromCard, limits, now, 'card')
260 await sync($)
261 $.ui.invalidate('ui.render')
262 } catch {}
263}
264
265// The card's 5h and weekly windows as rate limits, read with $.mcp.call; null when the card
266// cannot be read or has neither window
267async function cardLimits($) {
268 let result
269 try {
270 result = await $.mcp.call(CARD.server, CARD.tool, {})
271 } catch {
272 return null
273 }
274 if (!result || result.isError) return null
275 return cardLimitsOf(firstText(result.content))
276}
277
278// The text of the first text block among MCP content blocks; undefined when there is none
279function firstText(blocks) {
280 if (!Array.isArray(blocks)) return undefined
281 return blocks.find((b) => b?.type === 'text' && typeof b.text === 'string')?.text
282}
283
284// The card's 5h and weekly windows from get_usage's text, percentUsed and resetsAt as given; null
285// when the text is not the card's JSON, its status is not ok, or it has neither window
286function cardLimitsOf(text) {
287 if (typeof text !== 'string') return null
288 let data
289 try {
290 data = JSON.parse(text)
291 } catch {
292 return null
293 }
294 const plan = data?.plan
295 if (plan?.status !== 'ok' || !Array.isArray(plan.windows)) return null
296 const limits = []
297 for (const w of plan.windows) {
298 const kind = Object.hasOwn(CARD_KINDS, w?.label) ? CARD_KINDS[w.label] : null
299 if (!kind || typeof w.percentUsed !== 'number' || limits.some((l) => l.kind === kind)) continue
300 const limit = { kind, percentUsed: w.percentUsed }
301 if (typeof w.resetsAt === 'string') limit.resetsAt = w.resetsAt
302 limits.push(limit)
303 }
304 return limits.length > 0 ? limits : null
305}
306
307// `limits` as a new reading from `src`, or `prev` when they are empty or the same figures, so
308// measuredAt says how old the figures are, not when they were last asked for
309function taken(prev, limits, now, src) {
310 if (!Array.isArray(limits) || limits.length === 0) return prev
311 if (prev && sameFigures(prev.rateLimits, limits)) return prev
312 return { rateLimits: limits, measuredAt: now, src }
313}
314
315// Whether two lists of windows say the same: the same kinds and percentages in the same order,
316// and resets within SAME_RESET_MS of each other
317function sameFigures(a, b) {
318 if (a.length !== b.length) return false
319 return a.every((x, i) => {
320 const y = b[i]
321 if (x.kind !== y.kind || x.percentUsed !== y.percentUsed) return false
322 if (x.resetsAt == null || y.resetsAt == null) return x.resetsAt == null && y.resetsAt == null
323 return Math.abs(Date.parse(x.resetsAt) - Date.parse(y.resetsAt)) < SAME_RESET_MS
324 })
325}
326
327// This session's own reading: the card's while the card answers, else the response's
328function ownReading() {
329 return cardOk && fromCard ? fromCard : fromResponse
330}
331
332// Publishes this session's reading when it is newer than the stored one, and shows the newer of
333// the two; while the card answers, shows the card's reading whatever is stored, since the band
334// is to match the app and a stored response reading may run ahead of the card. Read, compare, write: two sessions syncing at once may both write, and the later
335// write wins even if it is the older reading. That loses at most a moment's difference, and the
336// session holding the newer reading writes it again on its next sync (within a minute).
337async function sync($) {
338 const own = ownReading()
339 let stored = null
340 try {
341 stored = asReading(await $.store.get(STORE_KEY))
342 } catch {}
343 if (own && newer(own, stored) === own) {
344 try {
345 await $.store.set(STORE_KEY, own)
346 } catch {}
347 if (config.log && own !== logged) {
348 const reading = own
349 logged = reading
350 logQueue = logQueue.then(() => appendLog($, reading))
351 await logQueue
352 }
353 }
354 shown = cardOk && fromCard ? fromCard : newer(own, stored)
355}
356
357// register()'s options; a value of the wrong type keeps the default
358function configOf(options) {
359 const logDir = options?.logDir
360 return {
361 log: typeof options?.log === 'boolean' ? options.log : DEFAULTS.log,
362 logDir: typeof logDir === 'string' && logDir.trim() !== '' ? logDir.trim() : DEFAULTS.logDir,
363 }
364}
365
366// Appends one line for `reading` to the day's file. $.fs has no append, so the day's file is
367// read whole and written back. Never throws: a failure shows one toast per session at most.
368// Two sessions appending at the same moment could lose a line; only the session holding a newer
369// reading writes, so that takes two new readings within one read and write.
370async function appendLog($, reading) {
371 try {
372 const now = await $.clock.now()
373 const dir = await logDirPath($)
374 if (dir == null) {
375 warnLog($, 'usage-band: ホームフォルダが分からないため、使用率の記録を書けません。usage-band の設定「記録の置き場」(logDir)にフォルダを指定してください')
376 return
377 }
378 const path = dir + '/' + logFileName(now)
379 let text = ''
380 // A file that exists but cannot be read is left alone rather than overwritten
381 if (await $.fs.exists(path)) text = await $.fs.read(path)
382 if (text !== '' && !text.endsWith('\n')) text += '\n'
383 await $.fs.write(path, text + logLine(reading, now) + '\n')
384 } catch (error) {
385 warnLog($, 'usage-band: 使用率の記録を書けませんでした(' + String(error?.message ?? error) + ')')
386 }
387}
388
389function warnLog($, text) {
390 if (logWarned) return
391 logWarned = true
392 $.ui.toast(text)
393}
394
395// logDir as an absolute path with forward slashes and no trailing slash; a leading `~` is the
396// home folder (USERPROFILE on Windows, else HOME). null when `~` is used and neither is set.
397async function logDirPath($) {
398 let dir = config.logDir.replace(/\\/g, '/')
399 if (dir === '~' || dir.startsWith('~/')) {
400 const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
401 if (!home) return null
402 dir = home.replace(/\\/g, '/').replace(/\/+$/, '') + dir.slice(1)
403 }
404 return dir.length > 1 ? dir.replace(/\/+$/, '') : dir
405}
406
407// usage-YYYYMMDD.jsonl, by the local date
408function logFileName(ms) {
409 const d = new Date(ms)
410 const pad = (n) => String(n).padStart(2, '0')
411 return 'usage-' + d.getFullYear() + pad(d.getMonth() + 1) + pad(d.getDate()) + '.jsonl'
412}
413
414// One JSON object: ts (when written), src (where the figures came from: 'card' or 'response')
415// and, per window kind, the raw percentage and reset time
416function logLine(reading, now) {
417 const line = { ts: new Date(now).toISOString(), src: reading.src ?? 'response' }
418 for (const limit of reading.rateLimits) {
419 line[limit.kind] = { used: limit.percentUsed, resets_at: limit.resetsAt ?? null }
420 }
421 return JSON.stringify(line)
422}
423
424// A stored value as a reading, or null when it is not one (unset, or written by something else)
425function asReading(value) {
426 if (!value || !Array.isArray(value.rateLimits) || typeof value.measuredAt !== 'number') return null
427 return value
428}
429
430// The newer of two readings; b when they tie. The figures decide first: a percentage never falls
431// within a window, so a reading behind the other is older whatever its time says (a stale reading
432// stamped late, such as the one a re-fired session.start takes in an idle session). The time
433// decides otherwise.
434function newer(a, b) {
435 if (!a) return b
436 if (!b) return a
437 const aBehind = isBehind(a.rateLimits, b.rateLimits)
438 const bBehind = isBehind(b.rateLimits, a.rateLimits)
439 if (aBehind !== bBehind) return aBehind ? b : a
440 return a.measuredAt > b.measuredAt ? a : b
441}
442
443// Whether some window in a is an earlier window than in b, or the same window used less
444function isBehind(a, b) {
445 return a.some((x) => {
446 const y = b.find((l) => l.kind === x.kind)
447 if (!y || x.resetsAt == null || y.resetsAt == null) return false
448 const gap = Date.parse(y.resetsAt) - Date.parse(x.resetsAt)
449 if (gap > SAME_WINDOW_MS) return true
450 return Math.abs(gap) <= SAME_WINDOW_MS && x.percentUsed < y.percentUsed
451 })
452}
453
454function statusOf(used) {
455 if (used >= ERROR_AT) return 'error'
456 if (used >= WARNING_AT) return 'warning'
457 return 'success'
458}
459
460function percentText(used) {
461 return typeof used === 'number' ? Math.round(used) + '%' : '—'
462}
463
464// The cells across the band: the site's own width, else what the surface measured; null when
465// neither is known
466function widthOf(e) {
467 const n = e.props?.bodyColumns
468 if (typeof n === 'number' && n > 0) return n
469 const v = e.viewport?.columns
470 return typeof v === 'number' && v > 0 ? v : null
471}
472
473// Character cells a text takes: two for a wide (CJK, full-width) character, one otherwise
474function cells(text) {
475 let n = 0
476 for (const ch of String(text)) {
477 const c = ch.codePointAt(0)
478 n += c >= 0x1100 && (c <= 0x115f || (c >= 0x2e80 && c <= 0xa4cf) || (c >= 0xac00 && c <= 0xd7a3) || (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe4f) || (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6)) ? 2 : 1
479 }
480 return n
481}
482
483// The cells a bar takes at a length ('full', 'short')
484function barCells(surface, length) {
485 return surface === 'desktop' ? Math.ceil(SVG_BAR[length] / PX_PER_CELL) : BAR_CELLS[length]
486}
487
488// The first step of STEPS whose parts fit on one line in `columns`: everything when the width
489// is unknown, the narrowest step when nothing fits
490function fitBand(meters, stamp, surface, columns) {
491 if (columns == null) return STEPS[0]
492 const room = columns - BAND_RESERVED_COLUMNS
493 for (const step of STEPS) {
494 let width = METER_GAP * (meters.length - 1)
495 for (const m of meters) {
496 width += cells(m.label) + 1 + cells(m.percent)
497 if (step.bar) width += 1 + barCells(surface, step.bar)
498 if (step.hasResets && m.reset) width += 1 + cells(m.reset)
499 }
500 if (step.hasClock && stamp) width += METER_GAP + cells(stamp)
501 if (width <= room) return step
502 }
503 return STEPS[STEPS.length - 1]
504}
505
506// Local time as HH:MM
507function clockText(ms) {
508 const d = new Date(ms)
509 return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0')
510}
511
512// One meter: the label, the bar as `fit` says, and the percentage with its countdown when `fit`
513// keeps it. The Box does not shrink, so its parts never wrap or slide under the next meter.
514function meter({ Box, Text, Svg }, surface, fit, { label, used, percent, reset }) {
515 const known = typeof used === 'number'
516 const status = known ? statusOf(used) : null
517 const value = fit.hasResets && reset ? percent + ' ' + reset : percent
518 const children = [Text({ wrap: 'truncate-end', children: [label] })]
519 if (fit.bar && surface === 'desktop') {
520 const width = SVG_BAR[fit.bar]
521 children.push(
522 Svg({
523 source: svgBar(known ? used : 0, status, width),
524 alt: label + ' ' + percent + (reset ? ' ' + reset : ''),
525 width,
526 height: SVG_BAR.height,
527 }),
528 )
529 } else if (fit.bar) {
530 children.push(textBar(Text, known ? used : 0, status, BAR_CELLS[fit.bar]))
531 }
532 children.push(Text({ wrap: 'truncate-end', ...(known ? { color: status } : { dimColor: true }), children: [value] }))
533 return Box({ key: 'meter-' + label, flexDirection: 'row', flexShrink: 0, columnGap: 1, alignItems: 'center', children })
534}
535
536// Used cells in the status color, the rest dim, nested in one Text so they stay on one line
537function textBar(Text, used, status, total) {
538 const filled = Math.round((clamp(used) / 100) * total)
539 return Text({
540 wrap: 'truncate-end',
541 children: [
542 Text({ ...(status ? { color: status } : { dimColor: true }), children: ['█'.repeat(filled)] }),
543 Text({ dimColor: true, children: ['░'.repeat(total - filled)] }),
544 ],
545 })
546}
547
548function svgBar(used, status, width) {
549 const { height } = SVG_BAR
550 const fill = Math.round((clamp(used) / 100) * width)
551 return [
552 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`,
553 `<clipPath id="c"><rect width="${width}" height="${height}" rx="${height / 2}"/></clipPath>`,
554 `<g clip-path="url(#c)">`,
555 `<rect width="${width}" height="${height}" fill="${SVG_COLORS.track}"/>`,
556 fill > 0 ? `<rect width="${fill}" height="${height}" fill="${SVG_COLORS[status ?? 'success']}"/>` : '',
557 '</g></svg>',
558 ].join('')
559}
560
561function clamp(percent) {
562 return Math.min(Math.max(percent, 0), 100)
563}
564
565function untilReset(ms) {
566 const minutes = Math.max(0, Math.ceil(ms / 60_000))
567 const days = Math.floor(minutes / 1440)
568 const hours = Math.floor((minutes % 1440) / 60)
569 if (days > 0) return days + 'd' + hours + 'h'
570 if (hours > 0) return hours + 'h' + (minutes % 60) + 'm'
571 return (minutes % 60) + 'm'
572}
573