dsh-token-receipt 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -21,14 +21,14 @@ window.__ModuleLoader__.load({
21
21
 
22
22
  const FONT_CSS = `
23
23
  @font-face {
24
- font-family: 'Inter';
24
+ font-family: 'TokenReceiptInter';
25
25
  font-style: normal;
26
26
  font-weight: 100 900;
27
27
  font-display: swap;
28
28
  src: url(data:font/woff2;base64,${INTER_FONT}) format('woff2');
29
29
  }
30
30
  @font-face {
31
- font-family: 'JetBrains Mono';
31
+ font-family: 'TokenReceiptMono';
32
32
  font-style: normal;
33
33
  font-weight: 100 800;
34
34
  font-display: swap;
@@ -40,21 +40,26 @@ window.__ModuleLoader__.load({
40
40
  zh: {
41
41
  nav: 'Token 账单',
42
42
  title: 'Token 账单',
43
- subtitle: '把 token 用量打印成一张有手感的小票。选择日、周或月,打印后还能保存 PNG。',
43
+ subtitle: '把 token 用量打印成一张有手感的小票。选择统计周期,打印后可复制图片或保存 PNG。',
44
44
  print: '打印账单',
45
45
  again: '重播打印',
46
46
  printingButton: '打印中…',
47
+ copyImage: '复制图片',
48
+ copyingImage: '复制中…',
49
+ copiedImage: '已复制',
50
+ copyFailed: '复制失败',
51
+ clipboardUnsupported: '当前环境不支持复制图片到剪贴板',
47
52
  savePng: '保存 PNG',
48
- printPaper: '打印 / PDF',
49
53
  savingPng: '生成中…',
50
54
  savedPng: '已保存',
51
55
  saveFailed: '保存失败',
52
56
  day: '日',
53
57
  week: '周',
54
58
  month: '月',
55
- daily: '每日',
56
- weekly: '每周',
57
- monthly: '每月',
59
+ days30: '近 30 天',
60
+ days90: '近 90 天',
61
+ all: '全部',
62
+ allTime: '全部时间',
58
63
  today: '今天',
59
64
  yesterday: '昨天',
60
65
  thisWeek: '本周',
@@ -70,7 +75,6 @@ window.__ModuleLoader__.load({
70
75
  completeStatus: '账单打印完成',
71
76
  errorStatus: '读取用量失败',
72
77
  readyStatus: '准备就绪',
73
- total: '总计',
74
78
  usage: 'Token 用量',
75
79
  billNo: '账单号',
76
80
  period: '周期',
@@ -82,11 +86,9 @@ window.__ModuleLoader__.load({
82
86
  reasoning: '推理',
83
87
  requests: '请求',
84
88
  sessions: '会话',
85
- models: '模型',
86
89
  model: '模型',
87
90
  moreModels: '其余 {n} 个模型',
88
91
  noUsage: '当前周期没有用量记录',
89
- emptyHint: '这个周期还没有产生 token 用量。',
90
92
  dataNote: '用量保留在本机,仅联网读取公开模型价格。',
91
93
  currency: '币种',
92
94
  autoCurrency: '跟随语言',
@@ -94,38 +96,44 @@ window.__ModuleLoader__.load({
94
96
  estimatedTotal: '预估总计',
95
97
  partialTotal: '已计价小计',
96
98
  totalTokens: 'Token 总量',
97
- referencePrice: '参考估算 · models.dev',
98
99
  partialPrice: '有 {n} 次请求未计价,金额为部分小计。',
99
100
  unavailablePrice: '价格暂不可用,用量已保留。',
100
101
  stalePrice: '使用上次获取的价格,稍后可重试。',
101
- fallbackPrice: 'WorkBuddy 按 DeepSeek Flash 官方参考价估算。',
102
102
  exchangeRate: '人民币按 1 USD ≈ 6.67 CNY 换算。',
103
103
  unpriced: '未计价',
104
104
  priceRetry: '重新获取价格',
105
- priceAsOf: '价格更新',
106
105
  fetchError: '读取用量失败',
107
106
  retry: '重试',
108
107
  thankYou: '感谢每一次提问',
109
108
  receiptLabel: 'Token 用量账单',
109
+ exportNotReady: '账单尚未就绪',
110
+ exportClosed: '导出完成前账单已关闭',
111
+ exportChanged: '保存过程中语言或币种已变更,请重试。',
112
+ exportFailed: '生成 PNG 失败',
110
113
  },
111
114
  en: {
112
115
  nav: 'Token receipt',
113
116
  title: 'Token receipt',
114
- subtitle: 'Print token usage as a tactile receipt. Pick a day, week, or month, then print or save a PNG.',
117
+ subtitle: 'Print token usage as a tactile receipt. Pick a period, then copy the image or save a PNG.',
115
118
  print: 'Print bill',
116
119
  again: 'Replay print',
117
120
  printingButton: 'Printing…',
121
+ copyImage: 'Copy image',
122
+ copyingImage: 'Copying…',
123
+ copiedImage: 'Copied',
124
+ copyFailed: 'Copy failed',
125
+ clipboardUnsupported: 'Image clipboard copy is not supported in this browser',
118
126
  savePng: 'Save PNG',
119
- printPaper: 'Print / PDF',
120
127
  savingPng: 'Rendering…',
121
128
  savedPng: 'Saved',
122
129
  saveFailed: 'Save failed',
123
130
  day: 'Day',
124
131
  week: 'Week',
125
132
  month: 'Month',
126
- daily: 'Daily',
127
- weekly: 'Weekly',
128
- monthly: 'Monthly',
133
+ days30: '30 days',
134
+ days90: '90 days',
135
+ all: 'All',
136
+ allTime: 'All time',
129
137
  today: 'Today',
130
138
  yesterday: 'Yesterday',
131
139
  thisWeek: 'This week',
@@ -138,10 +146,9 @@ window.__ModuleLoader__.load({
138
146
  pickDate: 'Pick a date',
139
147
  preparing: 'Preparing usage',
140
148
  printingStatus: 'Printing your receipt',
141
- completeStatus: 'Order complete',
149
+ completeStatus: 'Receipt complete',
142
150
  errorStatus: 'Could not read usage',
143
151
  readyStatus: 'Ready to print',
144
- total: 'Total',
145
152
  usage: 'Token usage',
146
153
  billNo: 'Bill no',
147
154
  period: 'Period',
@@ -153,11 +160,9 @@ window.__ModuleLoader__.load({
153
160
  reasoning: 'Reasoning',
154
161
  requests: 'Requests',
155
162
  sessions: 'Sessions',
156
- models: 'Models',
157
163
  model: 'Model',
158
164
  moreModels: '+{n} more models',
159
165
  noUsage: 'No usage recorded',
160
- emptyHint: 'No token usage in this period yet.',
161
166
  dataNote: 'Usage stays local. Only public model prices are fetched online.',
162
167
  currency: 'Currency',
163
168
  autoCurrency: 'Follow language',
@@ -165,38 +170,44 @@ window.__ModuleLoader__.load({
165
170
  estimatedTotal: 'Estimated total',
166
171
  partialTotal: 'Priced subtotal',
167
172
  totalTokens: 'Total tokens',
168
- referencePrice: 'Reference estimate · models.dev',
169
173
  partialPrice: '{n} requests unpriced; subtotal excludes them.',
170
174
  unavailablePrice: 'Prices unavailable. Usage is still recorded.',
171
175
  stalePrice: 'Using previously fetched prices. Retry to refresh.',
172
- fallbackPrice: 'WorkBuddy uses DeepSeek Flash official reference rates.',
173
176
  exchangeRate: 'CNY converted at 1 USD ≈ 6.67 CNY.',
174
177
  unpriced: 'Unpriced',
175
178
  priceRetry: 'Retry prices',
176
- priceAsOf: 'Prices updated',
177
179
  fetchError: 'Could not read usage',
178
180
  retry: 'Retry',
179
181
  thankYou: 'Thank you for prompting',
180
182
  receiptLabel: 'Token usage receipt',
183
+ exportNotReady: 'Receipt is not ready',
184
+ exportClosed: 'Receipt was closed before export completed',
185
+ exportChanged: 'Receipt language or currency changed while saving. Please retry.',
186
+ exportFailed: 'Canvas export failed',
181
187
  },
182
188
  ja: {
183
189
  nav: "トークン明細",
184
190
  title: "トークン明細",
185
- subtitle: "トークン使用量と推定料金をレシートに。日・週・月を選び、印刷や PNG 保存ができます。",
191
+ subtitle: "トークン使用量と推定料金をレシートに。期間を選び、画像のコピーや PNG 保存ができます。",
186
192
  print: "明細を印刷",
187
193
  again: "印刷を再生",
188
194
  printingButton: "印刷中…",
195
+ copyImage: "画像をコピー",
196
+ copyingImage: "コピー中…",
197
+ copiedImage: "コピーしました",
198
+ copyFailed: "コピーできませんでした",
199
+ clipboardUnsupported: "この環境では画像のクリップボードコピーに対応していません",
189
200
  savePng: "PNG を保存",
190
- printPaper: "印刷 / PDF",
191
201
  savingPng: "生成中…",
192
202
  savedPng: "保存しました",
193
203
  saveFailed: "保存できませんでした",
194
204
  day: "日",
195
205
  week: "週",
196
206
  month: "月",
197
- daily: "日次",
198
- weekly: "週次",
199
- monthly: "月次",
207
+ days30: "直近30日",
208
+ days90: "直近90日",
209
+ all: "全期間",
210
+ allTime: "全期間",
200
211
  today: "今日",
201
212
  yesterday: "昨日",
202
213
  thisWeek: "今週",
@@ -212,7 +223,6 @@ window.__ModuleLoader__.load({
212
223
  completeStatus: "印刷が完了しました",
213
224
  errorStatus: "使用量を読み込めませんでした",
214
225
  readyStatus: "印刷できます",
215
- total: "合計",
216
226
  usage: "トークン使用量",
217
227
  billNo: "明細番号",
218
228
  period: "期間",
@@ -224,11 +234,9 @@ window.__ModuleLoader__.load({
224
234
  reasoning: "推論",
225
235
  requests: "リクエスト",
226
236
  sessions: "セッション",
227
- models: "モデル",
228
237
  model: "モデル",
229
238
  moreModels: "その他 {n} モデル",
230
239
  noUsage: "この期間の使用記録はありません",
231
- emptyHint: "この期間のトークン使用量はまだありません。",
232
240
  dataNote: "使用量は端末内に保管し、公開モデル料金のみをオンラインで取得します。",
233
241
  currency: "通貨",
234
242
  autoCurrency: "言語に合わせる",
@@ -236,28 +244,47 @@ window.__ModuleLoader__.load({
236
244
  estimatedTotal: "推定合計",
237
245
  partialTotal: "計算済み小計",
238
246
  totalTokens: "総トークン数",
239
- referencePrice: "参考料金 · models.dev",
240
247
  partialPrice: "{n} 件は料金未計算のため、小計に含まれません。",
241
248
  unavailablePrice: "料金を取得できません。使用量は保持されています。",
242
249
  stalePrice: "前回取得した料金を使用中です。後ほど再試行してください。",
243
- fallbackPrice: "WorkBuddy は DeepSeek Flash の公式参考料金で計算します。",
244
250
  exchangeRate: "人民元は 1 USD ≈ 6.67 CNY で換算。",
245
251
  unpriced: "料金未計算",
246
252
  priceRetry: "料金を再取得",
247
- priceAsOf: "料金更新",
248
253
  fetchError: "使用量を読み込めませんでした",
249
254
  retry: "再試行",
250
255
  thankYou: "ご利用ありがとうございます",
251
256
  receiptLabel: "トークン使用明細",
257
+ exportNotReady: "明細の準備ができていません",
258
+ exportClosed: "出力完了前に明細が閉じられました",
259
+ exportChanged: "保存中に言語または通貨が変更されました。もう一度お試しください。",
260
+ exportFailed: "PNG の書き出しに失敗しました",
252
261
  },
253
262
  }
254
263
 
255
- const REDUCED =
256
- typeof window !== 'undefined' &&
257
- typeof window.matchMedia === 'function' &&
258
- window.matchMedia('(prefers-reduced-motion: reduce)').matches
264
+ function prefersReducedMotion() {
265
+ return (
266
+ typeof window !== 'undefined' &&
267
+ typeof window.matchMedia === 'function' &&
268
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
269
+ )
270
+ }
271
+
272
+ function waitWithAbort(ms, signal) {
273
+ if (ms <= 0 || signal.aborted) return Promise.resolve()
274
+ return new Promise((resolve) => {
275
+ const onAbort = () => {
276
+ clearTimeout(timer)
277
+ resolve()
278
+ }
279
+ const timer = setTimeout(() => {
280
+ signal.removeEventListener('abort', onAbort)
281
+ resolve()
282
+ }, ms)
283
+ signal.addEventListener('abort', onAbort, { once: true })
284
+ })
285
+ }
259
286
 
260
- const CSS = `${FONT_CSS}
287
+ const CSS = `
261
288
  .tr-page, .tr-page * { box-sizing: border-box; }
262
289
  .tr-page {
263
290
  --tr-g1: #fcfcfc;
@@ -293,7 +320,7 @@ window.__ModuleLoader__.load({
293
320
  overflow: auto;
294
321
  background: var(--tr-page-bg);
295
322
  color: var(--tr-page-ink);
296
- font-family: Inter, "Inter Fallback", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
323
+ font-family: "TokenReceiptInter", Inter, "Inter Fallback", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
297
324
  font-synthesis: none;
298
325
  }
299
326
  body[data-ds-dark-theme] .tr-page {
@@ -336,28 +363,38 @@ body[data-ds-dark-theme] .tr-page {
336
363
  .tr-btn:hover:not(:disabled) { border-color: var(--tr-g4); background: var(--tr-g3); color: var(--tr-g12); }
337
364
  .tr-btn:active:not(:disabled) { transform: translateY(1px); }
338
365
  .tr-btn:disabled { opacity: .55; cursor: default; }
366
+ .tr-btn:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
339
367
  .tr-btn-primary { border-color: transparent; background: var(--tr-g12); color: var(--tr-g1); box-shadow: 0 1px 0 rgba(255,255,255,.12) inset; }
340
368
  .tr-btn-primary:hover:not(:disabled) { background: var(--tr-g11); border-color: transparent; }
341
369
  .tr-filter-group { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
342
370
  .tr-currency { display: flex; align-items: center; gap: 7px; color: var(--tr-page-muted); font-size: 11px; }
343
371
  .tr-currency select { border: 1px solid var(--tr-g3); border-radius: 8px; padding: 8px; background: var(--tr-g1); color: var(--tr-page-ink); font: inherit; cursor: pointer; }
372
+ .tr-currency select:disabled { opacity: .55; cursor: default; }
344
373
  .tr-currency select:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
345
374
  .tr-price-feedback { display: flex; align-items: center; gap: 8px; justify-content: center; flex-wrap: wrap; margin-top: 12px; color: var(--tr-page-muted); font-size: 11px; text-align: center; }
346
375
  .tr-controls { display: flex; align-items: center; justify-content: space-between; gap: 14px; flex-wrap: wrap; margin-bottom: 20px; }
347
- .tr-periods { display: inline-flex; padding: 3px; border: 1px solid var(--tr-g3); border-radius: 8px; background: var(--tr-g1); }
348
- .tr-periodbtn { height: 30px; padding: 0 16px; border: 0; border-radius: 7px; background: transparent; color: var(--tr-g11); font: inherit; font-size: 12px; font-weight: 600; cursor: pointer; }
349
- .tr-periodbtn:hover:not(.is-active) { background: var(--tr-g2); color: var(--tr-g12); }
376
+ .tr-periods { display: inline-flex; flex-wrap: wrap; gap: 2px; padding: 3px; border: 1px solid var(--tr-g3); border-radius: 8px; background: var(--tr-g1); }
377
+ .tr-periodbtn { height: 30px; padding: 0 12px; border: 0; border-radius: 7px; background: transparent; color: var(--tr-g11); font: inherit; font-size: 12px; font-weight: 600; cursor: pointer; }
378
+ .tr-periodbtn:hover:not(:disabled):not(.is-active) { background: var(--tr-g2); color: var(--tr-g12); }
379
+ .tr-periodbtn:active:not(:disabled) { transform: translateY(1px); }
380
+ .tr-periodbtn:disabled { opacity: .55; cursor: default; }
381
+ .tr-periodbtn:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
350
382
  .tr-periodbtn.is-active { background: var(--tr-g12); color: var(--tr-g1); }
351
383
  .tr-daternav { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; }
352
384
  .tr-datenav { display: flex; align-items: center; border: 1px solid var(--tr-g3); border-radius: 8px; background: var(--tr-g1); padding: 3px; }
353
385
  .tr-navbtn { display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 0; border-radius: 7px; background: transparent; color: var(--tr-g11); cursor: pointer; }
354
386
  .tr-navbtn:hover:not(:disabled) { background: var(--tr-g2); color: var(--tr-g12); }
387
+ .tr-navbtn:active:not(:disabled) { transform: translateY(1px); }
355
388
  .tr-navbtn:disabled { opacity: .35; cursor: default; }
389
+ .tr-navbtn:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
356
390
  .tr-datebox { position: relative; min-width: 132px; padding: 0 20px 0 7px; text-align: center; cursor: pointer; border-radius: 6px; }
391
+ .tr-datebox.is-static { padding: 2px 12px; cursor: default; min-width: 132px; }
357
392
  .tr-datebox:focus-within { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
358
393
  .tr-dateicon { position: absolute; top: 50%; right: 6px; display: grid; place-items: center; color: var(--tr-page-muted); pointer-events: none; transform: translateY(-50%); opacity: .75; }
359
- .tr-datebox:hover { background: var(--tr-g2); }
394
+ .tr-datebox:not(.is-static):hover:not(:has(.tr-datepicker:disabled)) { background: var(--tr-g2); }
395
+ .tr-datebox:has(.tr-datepicker:disabled) { opacity: .55; cursor: default; }
360
396
  .tr-datepicker { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; padding: 0; opacity: 0; cursor: pointer; }
397
+ .tr-datepicker:disabled { cursor: default; }
361
398
  .tr-datemain { display: block; white-space: nowrap; font-size: 12.5px; font-weight: 600; line-height: 1.25; font-variant-numeric: tabular-nums; }
362
399
  .tr-daterel { display: block; margin-top: 1px; color: var(--tr-page-muted); font-size: 9.5px; line-height: 1.25; white-space: nowrap; }
363
400
  .tr-todaybtn { height: 32px; padding: 0 11px; font-size: 11px; }
@@ -372,8 +409,10 @@ body[data-ds-dark-theme] .tr-page {
372
409
  .tr-machine-btn { position: relative; display: inline-grid; height: 35px; padding: 0 12px 3px; border: 0; border-radius: 12px; background: transparent; color: #eeeeec; font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; }
373
410
  .tr-machine-btn::before { content: ""; position: absolute; inset: 3px 0 0; border-radius: 12px; background: #292926; box-shadow: inset 0 -1px 0 #141412; }
374
411
  .tr-machine-btn::after { content: ""; position: absolute; top: 0; right: 0; left: 0; height: 32px; border-radius: 12px; background: #4a4a46; box-shadow: inset 0 1px 0 #64645e; transition: transform .15s cubic-bezier(0.23, 1, 0.32, 1); }
375
- .tr-machine-btn:hover::after { transform: translateY(2px); }
376
- .tr-machine-btn:active::after { transform: translateY(3px); }
412
+ .tr-machine-btn:hover:not(:disabled)::after { transform: translateY(2px); }
413
+ .tr-machine-btn:active:not(:disabled)::after { transform: translateY(3px); }
414
+ .tr-machine-btn:disabled { opacity: .55; cursor: default; }
415
+ .tr-machine-btn:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
377
416
  .tr-machine-btn > span { position: relative; z-index: 2; display: inline-flex; align-items: center; gap: 5px; height: 32px; }
378
417
  .tr-machine-btn svg { width: 12px; height: 12px; }
379
418
  .tr-screen { position: relative; z-index: 2; overflow: hidden; border: 1px solid var(--tr-screen-border); border-radius: 12px; background: var(--tr-screen-bg); padding: 16px; color: var(--tr-screen-ink); box-shadow: inset 0 2px 4px color-mix(in oklab, var(--tr-screen-border) 80%, transparent); }
@@ -384,7 +423,6 @@ body[data-ds-dark-theme] .tr-page {
384
423
  .tr-screen-right { flex: none; text-align: right; }
385
424
  .tr-screen-label { margin: 0; color: var(--tr-screen-muted); font-size: 12px; line-height: 1.3; }
386
425
  .tr-screen-total { margin: 2px 0 0; font-size: 16px; font-weight: 600; line-height: 1; font-variant-numeric: tabular-nums; letter-spacing: 0; }
387
- .tr-screen-unit { font-size: 9px; font-weight: 500; letter-spacing: .08em; text-transform: uppercase; opacity: .55; }
388
426
  .tr-status { position: relative; z-index: 1; display: flex; align-items: center; gap: 8px; min-height: 20px; margin-top: 15px; }
389
427
  .tr-status-icon { flex: none; display: grid; place-items: center; width: 20px; height: 20px; }
390
428
  .tr-status-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--tr-screen-muted); font-size: 12px; font-weight: 500; line-height: 1; }
@@ -400,7 +438,6 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
400
438
  .tr-paper-wrap[data-stage="printing"] { opacity: 1; animation: tr-feed 1.75s linear both; }
401
439
  .tr-paper-wrap[data-stage="printing"].is-reduced { animation: none; transform: translateY(0); }
402
440
  .tr-paper-wrap[data-stage="complete"] { opacity: 1; transform: translateY(0); }
403
- .tr-paper-wrap[data-stage="idle"] { opacity: 0; }
404
441
  .tr-paper-wrap::before { content: ""; position: absolute; z-index: 0; top: 12px; right: 12px; bottom: 16px; left: 12px; border-radius: 2px; box-shadow: var(--tr-paper-shadow); pointer-events: none; }
405
442
  .tr-paper-wrap::after { content: ""; position: absolute; z-index: 0; right: 8%; bottom: 0; left: 8%; height: 12px; border-radius: 999px; background: var(--tr-paper-soft); filter: blur(10px); transform: translateY(6px); pointer-events: none; }
406
443
  @keyframes tr-feed {
@@ -426,9 +463,9 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
426
463
  100% { transform: translateY(0); }
427
464
  }
428
465
 
429
- .tr-paper { position: relative; z-index: 1; width: 100%; min-height: 20rem; padding: 28px 24px 32px; background-color: var(--tr-paper-bg); background-image: url("data:image/svg+xml;base64,${PAPER_TEXTURE}"); background-size: cover; background-blend-mode: soft-light; color: var(--tr-paper-ink); font-family: "JetBrains Mono", "JetBrains Mono Fallback", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 16px; clip-path: polygon(0 0, 100% 0, 100% calc(100% - 4px), 98.75% 100%, 97.5% calc(100% - 4px), 96.25% 100%, 95% calc(100% - 4px), 93.75% 100%, 92.5% calc(100% - 4px), 91.25% 100%, 90% calc(100% - 4px), 88.75% 100%, 87.5% calc(100% - 4px), 86.25% 100%, 85% calc(100% - 4px), 83.75% 100%, 82.5% calc(100% - 4px), 81.25% 100%, 80% calc(100% - 4px), 78.75% 100%, 77.5% calc(100% - 4px), 76.25% 100%, 75% calc(100% - 4px), 73.75% 100%, 72.5% calc(100% - 4px), 71.25% 100%, 70% calc(100% - 4px), 68.75% 100%, 67.5% calc(100% - 4px), 66.25% 100%, 65% calc(100% - 4px), 63.75% 100%, 62.5% calc(100% - 4px), 61.25% 100%, 60% calc(100% - 4px), 58.75% 100%, 57.5% calc(100% - 4px), 56.25% 100%, 55% calc(100% - 4px), 53.75% 100%, 52.5% calc(100% - 4px), 51.25% 100%, 50% calc(100% - 4px), 48.75% 100%, 47.5% calc(100% - 4px), 46.25% 100%, 45% calc(100% - 4px), 43.75% 100%, 42.5% calc(100% - 4px), 41.25% 100%, 40% calc(100% - 4px), 38.75% 100%, 37.5% calc(100% - 4px), 36.25% 100%, 35% calc(100% - 4px), 33.75% 100%, 32.5% calc(100% - 4px), 31.25% 100%, 30% calc(100% - 4px), 28.75% 100%, 27.5% calc(100% - 4px), 26.25% 100%, 25% calc(100% - 4px), 23.75% 100%, 22.5% calc(100% - 4px), 21.25% 100%, 20% calc(100% - 4px), 18.75% 100%, 17.5% calc(100% - 4px), 16.25% 100%, 15% calc(100% - 4px), 13.75% 100%, 12.5% calc(100% - 4px), 11.25% 100%, 10% calc(100% - 4px), 8.75% 100%, 7.5% calc(100% - 4px), 6.25% 100%, 5% calc(100% - 4px), 3.75% 100%, 2.5% calc(100% - 4px), 1.25% 100%, 0% calc(100% - 4px)); }
430
- .tr-page:lang(ja) { font-family: Inter, "Hiragino Kaku Gothic ProN", "Yu Gothic", Meiryo, "Noto Sans JP", sans-serif; }
431
- .tr-page:lang(ja) .tr-paper { font-family: "JetBrains Mono", "Hiragino Kaku Gothic ProN", "Yu Gothic", Meiryo, "Noto Sans JP", monospace; }
466
+ .tr-paper { position: relative; z-index: 1; width: 100%; min-height: 20rem; padding: 28px 24px 32px; background-color: var(--tr-paper-bg); background-image: url("data:image/svg+xml;base64,${PAPER_TEXTURE}"); background-size: cover; background-blend-mode: soft-light; color: var(--tr-paper-ink); font-family: "TokenReceiptMono", "JetBrains Mono", "JetBrains Mono Fallback", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 16px; clip-path: polygon(0 0, 100% 0, 100% calc(100% - 4px), 98.75% 100%, 97.5% calc(100% - 4px), 96.25% 100%, 95% calc(100% - 4px), 93.75% 100%, 92.5% calc(100% - 4px), 91.25% 100%, 90% calc(100% - 4px), 88.75% 100%, 87.5% calc(100% - 4px), 86.25% 100%, 85% calc(100% - 4px), 83.75% 100%, 82.5% calc(100% - 4px), 81.25% 100%, 80% calc(100% - 4px), 78.75% 100%, 77.5% calc(100% - 4px), 76.25% 100%, 75% calc(100% - 4px), 73.75% 100%, 72.5% calc(100% - 4px), 71.25% 100%, 70% calc(100% - 4px), 68.75% 100%, 67.5% calc(100% - 4px), 66.25% 100%, 65% calc(100% - 4px), 63.75% 100%, 62.5% calc(100% - 4px), 61.25% 100%, 60% calc(100% - 4px), 58.75% 100%, 57.5% calc(100% - 4px), 56.25% 100%, 55% calc(100% - 4px), 53.75% 100%, 52.5% calc(100% - 4px), 51.25% 100%, 50% calc(100% - 4px), 48.75% 100%, 47.5% calc(100% - 4px), 46.25% 100%, 45% calc(100% - 4px), 43.75% 100%, 42.5% calc(100% - 4px), 41.25% 100%, 40% calc(100% - 4px), 38.75% 100%, 37.5% calc(100% - 4px), 36.25% 100%, 35% calc(100% - 4px), 33.75% 100%, 32.5% calc(100% - 4px), 31.25% 100%, 30% calc(100% - 4px), 28.75% 100%, 27.5% calc(100% - 4px), 26.25% 100%, 25% calc(100% - 4px), 23.75% 100%, 22.5% calc(100% - 4px), 21.25% 100%, 20% calc(100% - 4px), 18.75% 100%, 17.5% calc(100% - 4px), 16.25% 100%, 15% calc(100% - 4px), 13.75% 100%, 12.5% calc(100% - 4px), 11.25% 100%, 10% calc(100% - 4px), 8.75% 100%, 7.5% calc(100% - 4px), 6.25% 100%, 5% calc(100% - 4px), 3.75% 100%, 2.5% calc(100% - 4px), 1.25% 100%, 0% calc(100% - 4px)); }
467
+ .tr-page:lang(ja) { font-family: "TokenReceiptInter", Inter, "Hiragino Kaku Gothic ProN", "Yu Gothic", Meiryo, "Noto Sans JP", sans-serif; }
468
+ .tr-page:lang(ja) .tr-paper { font-family: "TokenReceiptMono", "JetBrains Mono", "Hiragino Kaku Gothic ProN", "Yu Gothic", Meiryo, "Noto Sans JP", monospace; }
432
469
  .tr-paper-head { text-align: center; }
433
470
  .tr-paper-logo { display: block; width: 40px; height: 40px; margin: 0 auto; color: var(--tr-paper-ink); opacity: .9; }
434
471
  .tr-paper-kicker { margin: 13px 0 0; font-size: 9px; font-weight: 700; letter-spacing: .22em; text-transform: uppercase; }
@@ -443,53 +480,50 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
443
480
  .tr-price-notes p { margin: 0; font-size: 7px; line-height: 12px; opacity: .55; overflow-wrap: anywhere; }
444
481
  .tr-item { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; font-size: 9px; line-height: 16px; }
445
482
  .tr-item-name { min-width: 0; flex: 1; letter-spacing: .08em; text-transform: uppercase; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 700; }
446
- .tr-item-dots { flex: 1; min-width: 8px; border-bottom: 1px dotted color-mix(in oklab, var(--tr-paper-ink) 34%, transparent); transform: translateY(-3px); }
447
483
  .tr-item-value { flex: none; font-variant-numeric: tabular-nums; font-weight: 700; }
448
- .tr-more { margin-top: 2px; color: var(--tr-paper-ink); opacity: .55; font-size: 8px; line-height: 12px; }
449
484
  .tr-empty { padding: 6px 0; text-align: center; color: var(--tr-paper-ink); opacity: .55; font-size: 9px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
450
485
  .tr-summary { display: flex; flex-direction: column; gap: 6px; margin: 0; }
451
486
  .tr-summary-row { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; font-size: 9px; line-height: 9px; }
452
487
  .tr-summary-row dt { margin: 0; color: var(--tr-paper-ink); opacity: .55; }
453
488
  .tr-summary-row dd { margin: 0; font-variant-numeric: tabular-nums; }
454
489
  .tr-total { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; padding-top: 8px; }
455
- .tr-total dd { white-space: nowrap; }
456
490
  .tr-total dt { margin: 0; font-size: 10px; font-weight: 700; letter-spacing: .8px; text-transform: uppercase; }
457
- .tr-total dd { margin: 0; font-size: 15px; font-weight: 700; line-height: 15px; letter-spacing: -.6px; font-variant-numeric: tabular-nums; }
491
+ .tr-total dd { margin: 0; white-space: nowrap; font-size: 15px; font-weight: 700; line-height: 15px; letter-spacing: -.6px; font-variant-numeric: tabular-nums; }
458
492
  .tr-meta { display: grid; grid-template-columns: minmax(0,1fr) auto; gap: 4px 16px; font-size: 8px; line-height: 12px; }
459
493
  .tr-meta dt { margin: 0; color: var(--tr-paper-ink); opacity: .55; }
460
494
  .tr-meta dd { margin: 0; text-align: right; font-variant-numeric: tabular-nums; }
461
495
  .tr-barcodewrap { margin-top: 14px; text-align: center; }
462
- .tr-barcode { width: 128px; height: 28px; margin: 0 auto; background-image: repeating-linear-gradient(90deg, currentColor 0 1px, transparent 1px 3px, currentColor 3px 5px, transparent 5px 7px, currentColor 7px 8px, transparent 8px 11px); opacity: .85; }
496
+ .tr-barcode { width: 128px; height: 28px; margin: 0 auto; background-image: repeating-linear-gradient(90deg, currentColor 0 1px, transparent 1px 3px, currentColor 3px 5px, transparent 5px 7px, currentColor 7px 8px, transparent 8px 11px); opacity: .85; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
463
497
  .tr-barcode-label { margin: 4px 0 0; color: var(--tr-paper-ink); opacity: .5; font-size: 7px; line-height: 10.5px; letter-spacing: 1.26px; text-transform: uppercase; }
464
498
  .tr-thanks { margin: 8px 0 0; text-align: center; color: var(--tr-paper-ink); opacity: .5; font-size: 7px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; }
465
499
 
466
- .tr-error { width: 100%; max-width: 540px; margin: 14px auto 0; padding: 13px 16px; border: 1px solid color-mix(in srgb, #e5484d 34%, var(--dsw-alias-border-l1)); border-radius: 10px; background: color-mix(in srgb, #e5484d 7%, var(--dsw-alias-bg-layer-1)); color: var(--dsw-alias-label-primary); font-size: 12.5px; line-height: 1.5; text-align: center; }
500
+ .tr-error { width: 100%; max-width: 540px; margin: 14px auto 0; padding: 13px 16px; border: 1px solid color-mix(in srgb, #e5484d 34%, var(--tr-g3)); border-radius: 10px; background: color-mix(in srgb, #e5484d 7%, var(--tr-g2)); color: var(--tr-page-ink); font-size: 12.5px; line-height: 1.5; text-align: center; }
467
501
  .tr-sr-only { position: absolute !important; width: 1px !important; height: 1px !important; padding: 0 !important; margin: -1px !important; overflow: hidden !important; clip: rect(0, 0, 0, 0) !important; white-space: nowrap !important; border: 0 !important; }
468
502
  .tr-save-error { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; max-width: 540px; margin: 0 auto 14px; padding: 9px 12px; border: 1px solid color-mix(in srgb, #e5484d 34%, var(--tr-g3)); border-radius: 8px; background: color-mix(in srgb, #e5484d 7%, var(--tr-g2)); color: var(--tr-page-ink); font-size: 11.5px; line-height: 1.4; }
469
503
  .tr-save-error strong { flex: none; }
470
504
  .tr-save-error span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--tr-page-muted); }
471
505
  .tr-save-error .tr-btn { margin-left: auto; }
472
506
  .tr-error strong { display: block; margin-bottom: 3px; font-size: 12.5px; }
473
- .tr-error span { color: var(--dsw-alias-label-secondary); }
507
+ .tr-error span { color: var(--tr-page-muted); }
474
508
  .tr-error button { margin-top: 9px; }
475
509
  .tr-foot { display: flex; align-items: center; gap: 7px; justify-content: center; margin-top: 16px; color: var(--tr-page-muted); font-size: 11px; line-height: 1.5; text-align: center; }
476
510
  .tr-foot i { flex: none; width: 5px; height: 5px; border-radius: 50%; background: #30a46c; box-shadow: 0 0 0 3px rgba(48,164,108,.14); }
477
511
  @media print {
478
- body * { visibility: hidden !important; }
479
- .tr-page, .tr-page * { visibility: visible !important; }
480
- .tr-page { position: absolute !important; inset: 0 !important; height: auto !important; background: #fff !important; color: #111 !important; }
512
+ body:has(.tr-page) * { visibility: hidden !important; }
513
+ body:has(.tr-page) .tr-page, body:has(.tr-page) .tr-page * { visibility: visible !important; }
514
+ body:has(.tr-page) .tr-page { position: static !important; height: auto !important; min-height: 0 !important; overflow: visible !important; background: #fff !important; color: #111 !important; --tr-paper-bg: #fff !important; --tr-paper-ink: #111 !important; }
481
515
  .tr-shell { max-width: none !important; padding: 0 !important; }
482
- .tr-head, .tr-controls, .tr-foot, .tr-error, .tr-save-error, .tr-price-feedback, .tr-machine { display: none !important; }
516
+ .tr-head, .tr-controls, .tr-foot, .tr-error, .tr-save-error, .tr-price-feedback, .tr-machine, .tr-output::before, .tr-paper-wrap::before, .tr-paper-wrap::after { display: none !important; }
483
517
  .tr-stage { padding: 0 !important; background: none !important; }
484
518
  .tr-printer { width: 100% !important; }
485
- .tr-output { width: auto !important; height: auto !important; margin: 0 !important; padding: 0 !important; overflow: visible !important; }
519
+ .tr-output { width: auto !important; min-height: 0 !important; height: auto !important; margin: 0 !important; padding: 0 !important; overflow: visible !important; }
486
520
  .tr-paper-wrap { opacity: 1 !important; transform: none !important; animation: none !important; }
487
- .tr-paper { width: 307px !important; margin: 0 auto !important; box-shadow: none !important; }
521
+ .tr-paper { width: 307px !important; margin: 0 auto !important; box-shadow: none !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
488
522
  }
489
523
  @media (prefers-reduced-motion: reduce) {
490
524
  .tr-spin { animation: none; }
491
- .tr-btn, .tr-navbtn, .tr-machine-btn::after { transition: none; }
492
- .tr-btn:active:not(:disabled) { transform: none; }
525
+ .tr-btn, .tr-periodbtn, .tr-navbtn, .tr-machine-btn::after { transition: none; }
526
+ .tr-btn:active:not(:disabled), .tr-periodbtn:active:not(:disabled), .tr-navbtn:active:not(:disabled) { transform: none; }
493
527
  .tr-paper-wrap[data-stage="printing"] { animation: none; transform: translateY(0); }
494
528
  }
495
529
  @media (max-width: 720px) {
@@ -508,8 +542,6 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
508
542
  }
509
543
  `
510
544
 
511
- const PANEL_LABEL = { zh: 'Token 账单', en: 'Token receipt', ja: 'トークン明細' }
512
-
513
545
  // Official DSH whale geometry from dsh-web-frontend/dist/favicon.svg.
514
546
  // Share the path between the receipt and its Canvas PNG export.
515
547
  const WHALE_PATH = "M48.8354 10.0479C48.3232 9.79199 48.1025 10.2798 47.8032 10.5278C47.7007 10.6079 47.6143 10.7119 47.5273 10.8076C46.7793 11.624 45.9048 12.1597 44.7622 12.0957C43.0923 12 41.666 12.5356 40.4058 13.8398C40.1377 12.2319 39.2476 11.272 37.8926 10.6558C37.1836 10.3359 36.4668 10.0156 35.9702 9.31982C35.6235 8.82373 35.5293 8.27197 35.356 7.72754C35.2456 7.3999 35.1353 7.06396 34.7651 7.00781C34.3633 6.94385 34.2056 7.2876 34.0479 7.57568C33.418 8.75195 33.1733 10.0479 33.1973 11.3599C33.2524 14.312 34.4736 16.6641 36.8999 18.3359C37.1758 18.5278 37.2466 18.7197 37.1597 19C36.9946 19.5757 36.7974 20.1357 36.624 20.7119C36.5137 21.0801 36.3486 21.1597 35.9624 21C34.6309 20.4321 33.481 19.5918 32.4644 18.5757C30.7393 16.8721 29.1792 14.9917 27.2334 13.52C26.7764 13.1758 26.3193 12.856 25.8467 12.5518C23.8618 10.584 26.1069 8.96777 26.627 8.77588C27.1704 8.57568 26.8159 7.8877 25.0591 7.896C23.3022 7.90381 21.6953 8.50391 19.647 9.30371C19.3477 9.42383 19.0322 9.51172 18.7095 9.58398C16.8501 9.22363 14.9199 9.14355 12.9033 9.37598C9.10596 9.80762 6.07275 11.6396 3.84326 14.7681C1.16455 18.5278 0.53418 22.7998 1.30664 27.2559C2.11768 31.9521 4.46582 35.8398 8.07373 38.8799C11.8159 42.0322 16.1255 43.5762 21.041 43.2803C24.0269 43.104 27.3516 42.6963 31.1016 39.4561C32.0469 39.936 33.0396 40.1279 34.686 40.272C35.9546 40.3921 37.1758 40.208 38.1211 40.0078C39.6021 39.688 39.4995 38.2881 38.9639 38.0322C34.623 35.9678 35.5762 36.8081 34.71 36.1279C36.9155 33.4639 40.2402 30.6958 41.54 21.728C41.6426 21.0161 41.5557 20.5679 41.54 19.9917C41.5322 19.6396 41.6108 19.5039 42.0049 19.4639C43.0923 19.3359 44.1479 19.0317 45.1167 18.4878C47.9292 16.9199 49.064 14.3438 49.3315 11.2559C49.3711 10.7837 49.3237 10.2959 48.8354 10.0479ZM24.3262 37.8398C20.1196 34.4639 18.0791 33.3521 17.2358 33.3999C16.4482 33.4482 16.5898 34.3682 16.7632 34.9678C16.9443 35.5601 17.1812 35.9683 17.5117 36.4878C17.7402 36.832 17.8979 37.3442 17.2832 37.728C15.9282 38.584 13.5728 37.4399 13.4624 37.3838C10.7207 35.7358 8.42822 33.5601 6.81348 30.584C5.25342 27.7197 4.34766 24.6479 4.19775 21.3677C4.1582 20.5757 4.38672 20.2959 5.15869 20.1519C6.17529 19.96 7.22314 19.9199 8.23926 20.0718C12.5327 20.7119 16.1885 22.6719 19.2529 25.7759C21.002 27.5439 22.3252 29.6558 23.6885 31.7202C25.1377 33.9121 26.6978 36 28.6831 37.7119C29.3843 38.312 29.9434 38.7681 30.479 39.104C28.8643 39.2881 26.1699 39.3281 24.3262 37.8398ZM26.3433 24.6001C26.3433 24.248 26.6191 23.9678 26.9658 23.9678C27.0444 23.9678 27.1152 23.9839 27.1782 24.0078C27.2651 24.04 27.3438 24.0879 27.4067 24.1602C27.5171 24.272 27.5801 24.4321 27.5801 24.6001C27.5801 24.9521 27.3042 25.2319 26.9575 25.2319C26.6108 25.2319 26.3433 24.9521 26.3433 24.6001ZM32.6064 27.8799C32.2046 28.0479 31.8027 28.1919 31.4165 28.208C30.8179 28.2397 30.1641 27.9922 29.8096 27.688C29.2583 27.2158 28.8643 26.9521 28.6987 26.1279C28.6279 25.7759 28.6675 25.2319 28.7305 24.9199C28.8721 24.248 28.7144 23.8159 28.2495 23.4238C27.8716 23.104 27.3911 23.0161 26.8633 23.0161C26.666 23.0161 26.4849 22.9277 26.3511 22.856C26.1304 22.7441 25.9492 22.4639 26.1226 22.1201C26.1777 22.0078 26.4458 21.7358 26.5088 21.688C27.2256 21.272 28.0527 21.4077 28.8169 21.7197C29.5259 22.0161 30.0615 22.5601 30.834 23.3281C31.6216 24.2559 31.7632 24.5117 32.2124 25.208C32.5669 25.752 32.8901 26.312 33.1104 26.9521C33.2446 27.3521 33.0713 27.6802 32.6064 27.8799Z"
@@ -572,6 +604,15 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
572
604
  )
573
605
  }
574
606
 
607
+ function CopyIcon() {
608
+ return h(
609
+ 'svg',
610
+ { width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
611
+ h('rect', { x: 9, y: 9, width: 11, height: 11, rx: 2 }),
612
+ h('path', { d: 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1' }),
613
+ )
614
+ }
615
+
575
616
  function Spinner() {
576
617
  return h(
577
618
  'svg',
@@ -609,18 +650,36 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
609
650
  )
610
651
  }
611
652
 
653
+ function normalizeLocale(raw) {
654
+ const language = String(raw || 'en').trim().toLowerCase().split(/[-_]/)[0]
655
+ return language === 'zh' ? 'zh' : language === 'ja' ? 'ja' : 'en'
656
+ }
657
+
612
658
  function useLocale(ctx) {
613
659
  const [snapshot, setSnapshot] = React.useState(() => ctx.locale.getSnapshot())
614
- React.useEffect(() => ctx.locale.subscribe(() => setSnapshot(ctx.locale.getSnapshot())), [])
615
- return snapshot.active || 'en'
660
+ React.useEffect(() => {
661
+ setSnapshot(ctx.locale.getSnapshot())
662
+ return ctx.locale.subscribe(() => setSnapshot(ctx.locale.getSnapshot()))
663
+ }, [ctx])
664
+ return normalizeLocale(snapshot && snapshot.active)
616
665
  }
617
666
 
618
- function translatedCopy(ctx) {
619
- const t = ctx.locale.bind(NS)
667
+ function translatedCopy(ctx, locale) {
668
+ const rawActive = ctx && ctx.locale && typeof ctx.locale.getSnapshot === 'function' ? ctx.locale.getSnapshot().active : undefined
669
+ const lang = normalizeLocale(locale || rawActive)
670
+ const fallbackDict = DICT[lang] || DICT.en
671
+ const regionalMismatch = typeof rawActive === 'string' && !Object.hasOwn(DICT, rawActive) && lang !== 'en'
672
+ const t = ctx && ctx.locale && typeof ctx.locale.bind === 'function' ? ctx.locale.bind(NS) : null
620
673
  const out = {}
621
674
  for (const key of Object.keys(DICT.en)) {
622
- const value = t(key)
623
- out[key] = typeof value === 'string' && value !== key ? value : DICT.en[key]
675
+ const value = t ? t(key) : null
676
+ const usable =
677
+ typeof value === 'string' &&
678
+ value.length > 0 &&
679
+ value !== key &&
680
+ value !== `${NS}.${key}` &&
681
+ !(regionalMismatch && value === DICT.en[key])
682
+ out[key] = usable ? value : fallbackDict[key] || DICT.en[key]
624
683
  }
625
684
  return out
626
685
  }
@@ -650,13 +709,31 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
650
709
  return new Date(date.getFullYear(), date.getMonth(), 1)
651
710
  }
652
711
 
712
+ const PERIODS = ['day', 'week', 'month', 'days30', 'days90', 'all']
713
+
714
+ function isSteppablePeriod(period) {
715
+ return period === 'day' || period === 'week' || period === 'month'
716
+ }
717
+
653
718
  function shiftAnchor(period, anchor, delta) {
654
719
  if (period === 'week') return addDays(startOfWeek(anchor), delta * 7)
655
720
  if (period === 'month') return new Date(anchor.getFullYear(), anchor.getMonth() + delta, 1)
656
721
  return addDays(startOfDay(anchor), delta)
657
722
  }
658
723
 
659
- function periodRange(period, anchor) {
724
+ function periodRange(period, anchor, now = new Date()) {
725
+ if (period === 'days30') {
726
+ const today = startOfDay(now)
727
+ return { start: addDays(today, -29), end: addDays(today, 1) }
728
+ }
729
+ if (period === 'days90') {
730
+ const today = startOfDay(now)
731
+ return { start: addDays(today, -89), end: addDays(today, 1) }
732
+ }
733
+ if (period === 'all') {
734
+ const today = startOfDay(now)
735
+ return { start: new Date(1), end: addDays(today, 1) }
736
+ }
660
737
  const start = period === 'week' ? startOfWeek(anchor) : period === 'month' ? startOfMonth(anchor) : startOfDay(anchor)
661
738
  let end
662
739
  if (period === 'week') end = addDays(start, 7)
@@ -673,59 +750,103 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
673
750
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}`
674
751
  }
675
752
 
676
- function parseDateKey(value) {
677
- const parts = String(value).split('-').map(Number)
678
- if (parts.length < 3 || !parts[0] || !parts[1] || !parts[2]) return null
679
- const date = new Date(parts[0], parts[1] - 1, parts[2])
680
- return Number.isNaN(date.getTime()) ? null : date
753
+ function parseDateKey(value, now = new Date()) {
754
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(value || ''))
755
+ if (!match) return null
756
+ const year = Number(match[1])
757
+ const month = Number(match[2])
758
+ const day = Number(match[3])
759
+ if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31) return null
760
+ const date = new Date(year, month - 1, day)
761
+ if (
762
+ Number.isNaN(date.getTime()) ||
763
+ date.getFullYear() !== year ||
764
+ date.getMonth() !== month - 1 ||
765
+ date.getDate() !== day
766
+ ) {
767
+ return null
768
+ }
769
+ const today = startOfDay(now)
770
+ return date.getTime() > today.getTime() ? today : date
681
771
  }
682
772
 
683
- function parseMonthKey(value) {
684
- const parts = String(value).split('-').map(Number)
685
- if (parts.length < 2 || !parts[0] || !parts[1]) return null
686
- const date = new Date(parts[0], parts[1] - 1, 1)
687
- return Number.isNaN(date.getTime()) ? null : date
773
+ function parseMonthKey(value, now = new Date()) {
774
+ const match = /^(\d{4})-(\d{2})$/.exec(String(value || ''))
775
+ if (!match) return null
776
+ const year = Number(match[1])
777
+ const month = Number(match[2])
778
+ if (year < 1970 || month < 1 || month > 12) return null
779
+ const date = new Date(year, month - 1, 1)
780
+ if (
781
+ Number.isNaN(date.getTime()) ||
782
+ date.getFullYear() !== year ||
783
+ date.getMonth() !== month - 1 ||
784
+ date.getDate() !== 1
785
+ ) {
786
+ return null
787
+ }
788
+ const today = startOfDay(now)
789
+ return date.getTime() > today.getTime() ? today : date
688
790
  }
689
791
 
690
- function periodKey(period, start) {
691
- return period === 'month' ? monthKey(start) : dateKey(start)
792
+ function periodKey(period, start, endExclusive) {
793
+ if (period === 'month') return monthKey(start)
794
+ if (period === 'days30' || period === 'days90' || period === 'all') {
795
+ return dateKey(addDays(endExclusive || addDays(startOfDay(new Date()), 1), -1))
796
+ }
797
+ return dateKey(start)
692
798
  }
693
799
 
694
800
  function fullDate(date, locale) {
695
- if (locale === 'zh' || locale === 'ja') return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
801
+ const lang = normalizeLocale(locale)
802
+ if (lang === 'zh' || lang === 'ja') return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
696
803
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
697
804
  }
698
805
 
699
806
  function shortDate(date, locale) {
700
- if (locale === 'zh' || locale === 'ja') return `${date.getMonth() + 1}月${date.getDate()}日`
807
+ const lang = normalizeLocale(locale)
808
+ if (lang === 'zh' || lang === 'ja') return `${date.getMonth() + 1}月${date.getDate()}日`
701
809
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }).toUpperCase()
702
810
  }
703
811
 
704
812
  function monthYear(date, locale) {
705
- if (locale === 'zh' || locale === 'ja') return `${date.getFullYear()}年${date.getMonth() + 1}月`
813
+ const lang = normalizeLocale(locale)
814
+ if (lang === 'zh' || lang === 'ja') return `${date.getFullYear()}年${date.getMonth() + 1}月`
706
815
  return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })
707
816
  }
708
817
 
709
818
  function periodLabel(period, start, endExclusive, locale) {
710
- if (period === 'day') return fullDate(start, locale)
711
- if (period === 'month') return monthYear(start, locale)
819
+ const lang = normalizeLocale(locale)
820
+ if (period === 'day') return fullDate(start, lang)
821
+ if (period === 'month') return monthYear(start, lang)
712
822
  const last = addDays(endExclusive, -1)
713
- if (locale === 'zh' || locale === 'ja') {
823
+ if (period === 'all') {
824
+ if (!start || start.getTime() <= DAY_MS) return (DICT[lang] || DICT.en).allTime
825
+ if (start.getTime() >= last.getTime()) return fullDate(last, lang)
826
+ }
827
+ if (lang === 'zh' || lang === 'ja') {
714
828
  const firstPart = `${start.getFullYear()}年${start.getMonth() + 1}月${start.getDate()}日`
715
829
  const secondYear = last.getFullYear() !== start.getFullYear() ? `${last.getFullYear()}年` : ''
716
830
  const secondPart = `${secondYear}${last.getMonth() + 1}月${last.getDate()}日`
717
- return locale === 'ja' ? `${firstPart}〜${secondPart}` : `${firstPart} – ${secondPart}`
831
+ return lang === 'ja' ? `${firstPart}〜${secondPart}` : `${firstPart} – ${secondPart}`
718
832
  }
719
- const first = start.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
833
+ const firstOpts =
834
+ start.getFullYear() !== last.getFullYear()
835
+ ? { month: 'short', day: 'numeric', year: 'numeric' }
836
+ : { month: 'short', day: 'numeric' }
837
+ const first = start.toLocaleDateString('en-US', firstOpts)
720
838
  const second = last.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
721
839
  return `${first} – ${second}`
722
840
  }
723
841
 
724
842
  function periodName(period, copy) {
725
- return period === 'week' ? copy.week : period === 'month' ? copy.month : copy.day
843
+ return Object.hasOwn(copy, period) && copy[period] ? copy[period] : copy.day
726
844
  }
727
845
 
728
846
  function relativeLabel(period, start, copy) {
847
+ if (period === 'days30') return copy.days30
848
+ if (period === 'days90') return copy.days90
849
+ if (period === 'all') return start && start.getTime() > DAY_MS ? copy.allTime : ''
729
850
  const now = new Date()
730
851
  if (period === 'day') {
731
852
  const diff = Math.round((startOfDay(now).getTime() - start.getTime()) / DAY_MS)
@@ -745,13 +866,26 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
745
866
  return ''
746
867
  }
747
868
 
869
+ function resolveDisplayStart(period, fallbackStart, data) {
870
+ if (period !== 'all') return fallbackStart
871
+ return typeof data?.firstAt === 'number' && Number.isFinite(data.firstAt) && data.firstAt > DAY_MS
872
+ ? startOfDay(new Date(data.firstAt))
873
+ : new Date(1)
874
+ }
875
+
748
876
  function currentPeriodStart(period) {
749
877
  return periodRange(period, new Date()).start
750
878
  }
751
879
 
880
+ const EXACT_FORMATTERS = {
881
+ zh: new Intl.NumberFormat('zh-CN'),
882
+ ja: new Intl.NumberFormat('ja-JP'),
883
+ en: new Intl.NumberFormat('en-US'),
884
+ }
885
+
752
886
  function fmtExact(value, locale) {
753
887
  const n = Number(value) || 0
754
- return new Intl.NumberFormat(locale === 'zh' ? 'zh-CN' : locale === 'ja' ? 'ja-JP' : 'en-US').format(n)
888
+ return EXACT_FORMATTERS[normalizeLocale(locale)].format(n)
755
889
  }
756
890
 
757
891
  function fmtCompact(value) {
@@ -772,7 +906,18 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
772
906
  }
773
907
 
774
908
  function billNumber(period, date, total, requests) {
775
- const code = period === 'week' ? 'W' : period === 'month' ? 'M' : 'D'
909
+ const code =
910
+ period === 'week'
911
+ ? 'W'
912
+ : period === 'month'
913
+ ? 'M'
914
+ : period === 'days30'
915
+ ? '30D'
916
+ : period === 'days90'
917
+ ? '90D'
918
+ : period === 'all'
919
+ ? 'ALL'
920
+ : 'D'
776
921
  return `TR-${code}-${String(date || '').replaceAll('-', '')}-${hashSuffix(`${period}:${date}:${total}:${requests}`)}`
777
922
  }
778
923
 
@@ -788,34 +933,41 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
788
933
  const JPY_RATE_DATE = '2026-11-13'
789
934
 
790
935
  function defaultCurrencyForLocale(locale) {
791
- const language = String(locale || 'en').toLowerCase().split(/[-_]/)[0]
792
- return language === 'zh' ? 'cny' : language === 'ja' ? 'jpy' : 'usd'
936
+ const lang = normalizeLocale(locale)
937
+ return lang === 'zh' ? 'cny' : lang === 'ja' ? 'jpy' : 'usd'
793
938
  }
794
939
 
795
940
  function resolveCurrencyPreference(preference, locale) {
796
941
  return Object.hasOwn(DISPLAY_RATES, preference) ? preference : defaultCurrencyForLocale(locale)
797
942
  }
798
943
 
944
+ const MONEY_FORMATTERS = {
945
+ standard: new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }),
946
+ standardSmall: new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 6 }),
947
+ jpy: new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 }),
948
+ jpySmall: new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 6 }),
949
+ }
950
+
799
951
  function fmtMoney(usd, currency = 'usd') {
800
952
  if (typeof usd !== 'number' || !Number.isFinite(usd)) return '—'
801
953
  const selected = Object.hasOwn(DISPLAY_RATES, currency) ? currency : 'usd'
802
954
  const amount = usd * DISPLAY_RATES[selected]
803
955
  const symbol = selected === 'usd' ? '$' : '¥'
804
956
  if (amount > 0 && amount < .000001) return `<${symbol}0.000001`
805
- const minimum = selected === 'jpy' ? 0 : 2
806
- const small = amount > 0 && amount < (selected === 'jpy' ? 1 : .01)
807
- const number = new Intl.NumberFormat('en-US', { minimumFractionDigits: minimum, maximumFractionDigits: small ? 6 : minimum }).format(amount)
808
- return `${symbol}${number}`
957
+ const isJpy = selected === 'jpy'
958
+ const small = amount > 0 && amount < (isJpy ? 1 : .01)
959
+ const formatter = isJpy
960
+ ? small ? MONEY_FORMATTERS.jpySmall : MONEY_FORMATTERS.jpy
961
+ : small ? MONEY_FORMATTERS.standardSmall : MONEY_FORMATTERS.standard
962
+ return `${symbol}${formatter.format(amount)}`
809
963
  }
810
964
 
811
965
  function groupModels(models) {
812
966
  const grouped = new Map()
813
967
  for (const model of models || []) {
814
968
  const name = shortModelName(model.model)
815
- const existing = grouped.get(name) || { model: name, total: 0, input: 0, output: 0, requests: 0, costUsd: null, complete: true }
969
+ const existing = grouped.get(name) || { model: name, total: 0, requests: 0, costUsd: null, complete: true }
816
970
  existing.total += Number(model.total) || 0
817
- existing.input += Number(model.input) || 0
818
- existing.output += Number(model.output) || 0
819
971
  existing.requests += Number(model.requests) || 0
820
972
  // Host prices each provider independently before these display rows merge.
821
973
  const cost = model.pricing && model.pricing.totalUsd
@@ -832,7 +984,8 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
832
984
 
833
985
  function Receipt(props) {
834
986
  const { copy, locale, data, period, paperRef, currency: selectedCurrency = 'auto' } = props
835
- const currency = resolveCurrencyPreference(selectedCurrency, locale)
987
+ const lang = normalizeLocale(locale)
988
+ const currency = resolveCurrencyPreference(selectedCurrency, lang)
836
989
  const totals = data.totals
837
990
  const pricing = data.pricing
838
991
  const breakdown = pricing?.breakdown
@@ -849,7 +1002,9 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
849
1002
  }
850
1003
  const rangeStart = new Date(data.from)
851
1004
  const rangeEnd = new Date(data.to)
1005
+ const displayStart = resolveDisplayStart(period, rangeStart, data)
852
1006
  const issued = new Date(data.generatedAt)
1007
+ const issuedText = Number.isNaN(issued.getTime()) ? '—' : `${pad(issued.getHours())}:${pad(issued.getMinutes())}`
853
1008
  const billNo = billNumber(period, data.date, totals.totalTokens, totals.requests)
854
1009
  const partial = pricing?.status === 'partial'
855
1010
  const hasPrice = typeof pricing?.totalUsd === 'number' && Number.isFinite(pricing.totalUsd)
@@ -869,17 +1024,17 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
869
1024
  h('span', { className: 'tr-item-value', title: model.costUsd === null ? copy.unpriced : undefined },
870
1025
  model.costUsd === null ? '—' : `${model.complete ? '' : '≈'}${fmtMoney(model.costUsd, currency)}`),
871
1026
  ),
872
- h('p', { className: 'tr-item-detail' }, `${fmtExact(model.total, locale)} tokens · ${fmtExact(model.requests, locale)} ${copy.requests}`),
1027
+ h('p', { className: 'tr-item-detail' }, `${fmtExact(model.total, lang)} tokens · ${fmtExact(model.requests, lang)} ${copy.requests.toLowerCase()}`),
873
1028
  )
874
1029
  return h(
875
1030
  'article',
876
- { className: 'tr-paper', lang: locale, 'data-currency': currency, 'aria-label': copy.receiptLabel, ref: paperRef },
1031
+ { className: 'tr-paper', lang, 'data-currency': currency, 'aria-label': copy.receiptLabel, ref: paperRef },
877
1032
  h(
878
1033
  'div',
879
1034
  { className: 'tr-paper-head' },
880
1035
  h('span', { className: 'tr-paper-logo' }, h(WhaleGlyph, { size: 40 })),
881
1036
  h('p', { className: 'tr-paper-kicker' }, 'TOKEN RECEIPT'),
882
- h('p', { className: 'tr-paper-date' }, periodLabel(period, rangeStart, rangeEnd, locale)),
1037
+ h('p', { className: 'tr-paper-date' }, periodLabel(period, displayStart, rangeEnd, lang)),
883
1038
  ),
884
1039
  h('div', { className: 'tr-rule' }),
885
1040
  h('p', { className: 'tr-section-label' }, copy.model),
@@ -900,12 +1055,12 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
900
1055
  h(
901
1056
  'dl',
902
1057
  { className: 'tr-meta' },
903
- h('dt', null, copy.totalTokens), h('dd', null, fmtExact(totals.totalTokens, locale)),
904
- h('dt', null, `${copy.requests} / ${copy.sessions}`), h('dd', null, `${fmtExact(totals.requests, locale)} / ${fmtExact(totals.sessions, locale)}`),
905
- totals.reasoningTokens > 0 ? h(React.Fragment, null, h('dt', null, copy.reasoning), h('dd', null, fmtExact(totals.reasoningTokens, locale))) : null,
1058
+ h('dt', null, copy.totalTokens), h('dd', null, fmtExact(totals.totalTokens, lang)),
1059
+ h('dt', null, `${copy.requests} / ${copy.sessions}`), h('dd', null, `${fmtExact(totals.requests, lang)} / ${fmtExact(totals.sessions, lang)}`),
1060
+ totals.reasoningTokens > 0 ? h(React.Fragment, null, h('dt', null, copy.reasoning), h('dd', null, fmtExact(totals.reasoningTokens, lang))) : null,
906
1061
  h('dt', null, copy.billNo), h('dd', null, billNo),
907
1062
  h('dt', null, copy.period), h('dd', null, periodName(period, copy)),
908
- h('dt', null, copy.generated), h('dd', null, `${pad(issued.getHours())}:${pad(issued.getMinutes())}`),
1063
+ h('dt', null, copy.generated), h('dd', null, issuedText),
909
1064
  h('dt', null, copy.currency), h('dd', null, currency.toUpperCase()),
910
1065
  ),
911
1066
  notes.length > 0 ? h('div', { className: 'tr-price-notes' }, notes.map((note) => h('p', { key: note }, note))) : null,
@@ -978,59 +1133,103 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
978
1133
  })
979
1134
  }
980
1135
 
981
- async function exportReceiptPng(paperEl, billNo) {
982
- if (!paperEl) throw new Error('Receipt is not ready')
1136
+ function collectWrappedLines(textNode, lineHeight) {
1137
+ const range = document.createRange()
1138
+ const lines = []
1139
+ const raw = textNode.nodeValue || ''
1140
+ for (let offset = 0; offset < raw.length; ) {
1141
+ const codePoint = raw.codePointAt(offset)
1142
+ const step = codePoint > 0xffff ? 2 : 1
1143
+ range.setStart(textNode, offset)
1144
+ range.setEnd(textNode, offset + step)
1145
+ const charRect = range.getBoundingClientRect()
1146
+ const glyph = raw.slice(offset, offset + step)
1147
+ offset += step
1148
+ if (charRect.width === 0) continue
1149
+ const charTop = charRect.top
1150
+ const charBottom = typeof charRect.bottom === 'number' ? charRect.bottom : charTop + charRect.height
1151
+ const charMid = (charTop + charBottom) / 2
1152
+ let line = lines[lines.length - 1]
1153
+ if (!line || Math.abs(line.mid - charMid) > lineHeight * 0.5) {
1154
+ line = { text: '', top: charTop, bottom: charBottom, mid: charMid }
1155
+ lines.push(line)
1156
+ } else {
1157
+ line.top = Math.min(line.top, charTop)
1158
+ line.bottom = Math.max(line.bottom, charBottom)
1159
+ line.mid = (line.top + line.bottom) / 2
1160
+ }
1161
+ line.text += glyph
1162
+ }
1163
+ return lines
1164
+ }
1165
+
1166
+ function errorMessage(error) {
1167
+ if (error instanceof Error) return error.message
1168
+ if (error && typeof error.message === 'string') return error.message
1169
+ return String(error)
1170
+ }
1171
+
1172
+ async function renderReceiptPngBlob(paperEl, copy) {
1173
+ const errCopy = copy || DICT.en
1174
+ if (!paperEl) throw new Error(errCopy.exportNotReady)
983
1175
  const exportCurrency = paperEl.dataset.currency
984
1176
  const exportLanguage = paperEl.lang
985
1177
  const assertReceiptUnchanged = () => {
986
- if (!paperEl.isConnected) throw new Error('Receipt was closed before export completed')
1178
+ if (!paperEl.isConnected) throw new Error(errCopy.exportClosed)
987
1179
  if (paperEl.dataset.currency !== exportCurrency || paperEl.lang !== exportLanguage) {
988
- throw new Error('Receipt language or currency changed while saving. Please retry.')
1180
+ throw new Error(errCopy.exportChanged)
989
1181
  }
990
1182
  }
991
1183
  await document.fonts.ready
992
1184
  assertReceiptUnchanged()
993
- const rect = paperEl.getBoundingClientRect()
994
- const width = Math.max(1, Math.round(rect.width))
995
- const height = Math.max(1, Math.round(rect.height))
1185
+
1186
+ let texture = null
1187
+ try {
1188
+ texture = await loadImage(`data:image/svg+xml;base64,${PAPER_TEXTURE}`)
1189
+ } catch {
1190
+ /* texture is decorative */
1191
+ }
1192
+ assertReceiptUnchanged()
1193
+
1194
+ const paperRect = paperEl.getBoundingClientRect()
1195
+ const originX = paperRect.left
1196
+ const originY = paperRect.top
1197
+ const width = Math.max(1, Math.round(paperRect.width))
1198
+ const height = Math.max(1, Math.round(paperRect.height))
996
1199
  const canvas = document.createElement('canvas')
997
1200
  canvas.width = width * EXPORT_SCALE
998
1201
  canvas.height = height * EXPORT_SCALE
999
1202
  const ctx = canvas.getContext('2d')
1203
+ if (!ctx) throw new Error(errCopy.exportFailed)
1000
1204
  ctx.scale(EXPORT_SCALE, EXPORT_SCALE)
1205
+
1001
1206
  ctx.save()
1002
1207
  paperClipPath(ctx, width, height)
1003
1208
  ctx.clip()
1004
1209
  const paperStyle = getComputedStyle(paperEl)
1005
1210
  ctx.fillStyle = paperStyle.backgroundColor || '#fcfcfc'
1006
1211
  ctx.fillRect(0, 0, width, height)
1007
- try {
1008
- const texture = await loadImage(`data:image/svg+xml;base64,${PAPER_TEXTURE}`)
1212
+ if (texture) {
1009
1213
  ctx.save()
1010
1214
  ctx.globalCompositeOperation = 'soft-light'
1011
1215
  ctx.drawImage(texture, 0, 0, width, height)
1012
1216
  ctx.restore()
1013
- } catch {
1014
- /* texture is decorative */
1015
1217
  }
1016
1218
  ctx.restore()
1017
1219
 
1018
- assertReceiptUnchanged()
1019
- const paperRect = paperEl.getBoundingClientRect()
1020
- const originX = paperRect.left
1021
- const originY = paperRect.top
1022
-
1023
1220
  const logo = paperEl.querySelector('.tr-paper-logo')
1024
- if (logo) {
1221
+ if (logo && typeof Path2D === 'function') {
1025
1222
  const logoRect = logo.getBoundingClientRect()
1026
- const logoColor = getComputedStyle(logo).color
1027
- const logoSvg =
1028
- `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 50 50" fill="${logoColor}"><path d="${WHALE_PATH}"/></svg>`
1029
- try {
1030
- const image = await loadImage(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(logoSvg)}`)
1031
- ctx.drawImage(image, logoRect.left - originX, logoRect.top - originY, logoRect.width, logoRect.height)
1032
- } catch {
1033
- /* logo is decorative */
1223
+ if (logoRect.width > 0 && logoRect.height > 0) {
1224
+ const logoStyle = getComputedStyle(logo)
1225
+ const alpha = parseFloat(logoStyle.opacity)
1226
+ ctx.save()
1227
+ ctx.translate(logoRect.left - originX, logoRect.top - originY)
1228
+ ctx.scale(logoRect.width / 50, logoRect.height / 50)
1229
+ ctx.fillStyle = logoStyle.color
1230
+ ctx.globalAlpha = Number.isFinite(alpha) ? alpha : 1
1231
+ ctx.fill(new Path2D(WHALE_PATH))
1232
+ ctx.restore()
1034
1233
  }
1035
1234
  }
1036
1235
 
@@ -1052,38 +1251,23 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1052
1251
  if (barcode) {
1053
1252
  const barcodeRect = barcode.getBoundingClientRect()
1054
1253
  const barcodeStyle = getComputedStyle(barcode)
1254
+ const alpha = parseFloat(barcodeStyle.opacity)
1055
1255
  ctx.save()
1056
1256
  ctx.fillStyle = barcodeStyle.color
1257
+ ctx.globalAlpha = Number.isFinite(alpha) ? alpha : 1
1057
1258
  const pattern = [1, 2, 2, 2, 1, 3]
1259
+ const rightEdge = barcodeRect.right - originX
1058
1260
  let x = barcodeRect.left - originX
1059
1261
  let index = 0
1060
- while (x < barcodeRect.right - originX) {
1262
+ while (x < rightEdge) {
1061
1263
  const segment = pattern[index % pattern.length]
1062
- if (index % 2 === 0) ctx.fillRect(x, barcodeRect.top - originY, segment, barcodeRect.height)
1264
+ if (index % 2 === 0) ctx.fillRect(x, barcodeRect.top - originY, Math.min(segment, rightEdge - x), barcodeRect.height)
1063
1265
  x += segment
1064
1266
  index += 1
1065
1267
  }
1066
1268
  ctx.restore()
1067
1269
  }
1068
1270
 
1069
- for (const item of paperEl.querySelectorAll('.tr-item')) {
1070
- const dots = item.querySelector('.tr-item-dots')
1071
- if (!dots) continue
1072
- const dotsRect = dots.getBoundingClientRect()
1073
- if (dotsRect.width <= 0) continue
1074
- const dotsStyle = getComputedStyle(dots)
1075
- ctx.save()
1076
- ctx.strokeStyle = dotsStyle.borderBottomColor || dotsStyle.color
1077
- ctx.lineWidth = 1
1078
- ctx.setLineDash([1, 3])
1079
- ctx.beginPath()
1080
- ctx.moveTo(dotsRect.left - originX, dotsRect.top - originY + dotsRect.height / 2)
1081
- ctx.lineTo(dotsRect.right - originX, dotsRect.top - originY + dotsRect.height / 2)
1082
- ctx.stroke()
1083
- ctx.restore()
1084
- }
1085
-
1086
- assertReceiptUnchanged()
1087
1271
  const walker = document.createTreeWalker(paperEl, NodeFilter.SHOW_TEXT)
1088
1272
  let node = walker.nextNode()
1089
1273
  while (node) {
@@ -1093,7 +1277,8 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1093
1277
  node = walker.nextNode()
1094
1278
  if (!text || !element || element.closest('svg') || element.closest('style')) continue
1095
1279
  const style = getComputedStyle(element)
1096
- if (style.display === 'none' || Number(style.opacity) === 0) continue
1280
+ const textAlpha = parseFloat(style.opacity)
1281
+ if (style.display === 'none' || textAlpha === 0) continue
1097
1282
  const bounds = element.getBoundingClientRect()
1098
1283
  if (bounds.width === 0 || bounds.height === 0) continue
1099
1284
  const value = style.textTransform === 'uppercase' ? text.toUpperCase() : text
@@ -1103,7 +1288,7 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1103
1288
  ctx.save()
1104
1289
  ctx.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`
1105
1290
  ctx.fillStyle = style.color
1106
- ctx.globalAlpha = Number(style.opacity) || 1
1291
+ ctx.globalAlpha = Number.isFinite(textAlpha) ? textAlpha : 1
1107
1292
  ctx.textAlign = align
1108
1293
  ctx.textBaseline = 'middle'
1109
1294
  if ('letterSpacing' in ctx) ctx.letterSpacing = style.letterSpacing === 'normal' ? '0px' : style.letterSpacing
@@ -1114,25 +1299,13 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1114
1299
  }
1115
1300
  const lineHeight = parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.2
1116
1301
  if (style.whiteSpace !== 'nowrap' && bounds.height > lineHeight * 1.5) {
1117
- // Use the browser's actual line breaks, including CJK notes, in the PNG.
1118
- const range = document.createRange()
1119
- const lines = []
1120
- const raw = textNode.nodeValue || ''
1121
- for (let offset = 0; offset < raw.length; offset += 1) {
1122
- range.setStart(textNode, offset)
1123
- range.setEnd(textNode, offset + 1)
1124
- const charRect = range.getBoundingClientRect()
1125
- if (charRect.width === 0) continue
1126
- let line = lines[lines.length - 1]
1127
- if (!line || Math.abs(line.top - charRect.top) > 1) {
1128
- line = { text: '', top: charRect.top, height: charRect.height }
1129
- lines.push(line)
1130
- }
1131
- line.text += raw[offset]
1132
- }
1302
+ // Group wrapped runs by vertical midpoint so mixed CJK + ASCII fonts stay on one line.
1303
+ const lines = collectWrappedLines(textNode, lineHeight)
1133
1304
  for (const line of lines) {
1134
- const lineText = style.textTransform === 'uppercase' ? line.text.trim().toUpperCase() : line.text.trim()
1135
- ctx.fillText(lineText, x, line.top - originY + line.height / 2)
1305
+ const rawLine = line.text.replace(/\s+/g, ' ').trim()
1306
+ if (!rawLine) continue
1307
+ const lineText = style.textTransform === 'uppercase' ? rawLine.toUpperCase() : rawLine
1308
+ ctx.fillText(lineText, x, (line.top + line.bottom) / 2 - originY)
1136
1309
  }
1137
1310
  } else {
1138
1311
  ctx.fillText(printable, x, y)
@@ -1140,96 +1313,203 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1140
1313
  ctx.restore()
1141
1314
  }
1142
1315
 
1143
- const blob = await new Promise((resolve, reject) => canvas.toBlob((value) => (value ? resolve(value) : reject(new Error('Canvas export failed'))), 'image/png'))
1316
+ const blob = await new Promise((resolve, reject) =>
1317
+ canvas.toBlob((value) => (value ? resolve(value) : reject(new Error(errCopy.exportFailed))), 'image/png'),
1318
+ )
1319
+ assertReceiptUnchanged()
1320
+ return blob
1321
+ }
1322
+
1323
+ async function exportReceiptPng(paperEl, billNo, copy) {
1324
+ const blob = await renderReceiptPngBlob(paperEl, copy)
1144
1325
  downloadBlob(blob, `token-receipt-${billNo || 'bill'}.png`)
1145
1326
  }
1146
1327
 
1328
+ async function copyReceiptPng(paperEl, copy) {
1329
+ const errCopy = copy || DICT.en
1330
+ if (!paperEl) throw new Error(errCopy.exportNotReady)
1331
+ const nav = typeof navigator !== 'undefined' ? navigator : typeof window !== 'undefined' ? window.navigator : undefined
1332
+ const ClipboardItemCtor =
1333
+ typeof ClipboardItem === 'function'
1334
+ ? ClipboardItem
1335
+ : typeof window !== 'undefined' && typeof window.ClipboardItem === 'function'
1336
+ ? window.ClipboardItem
1337
+ : null
1338
+ if (!nav || !nav.clipboard || typeof nav.clipboard.write !== 'function' || !ClipboardItemCtor) {
1339
+ throw new Error(errCopy.clipboardUnsupported)
1340
+ }
1341
+ const blobPromise = renderReceiptPngBlob(paperEl, errCopy)
1342
+ // Attach a no-op rejection handler so synchronous ClipboardItem failures do not leak unhandled rejections.
1343
+ blobPromise.catch(() => {})
1344
+ let item = null
1345
+ try {
1346
+ item = new ClipboardItemCtor({ 'image/png': blobPromise })
1347
+ } catch {
1348
+ item = null
1349
+ }
1350
+ if (item) {
1351
+ try {
1352
+ await nav.clipboard.write([item])
1353
+ return
1354
+ } catch (err) {
1355
+ const blob = await blobPromise
1356
+ if (!(err instanceof TypeError) && err?.name !== 'TypeError') throw err
1357
+ await nav.clipboard.write([new ClipboardItemCtor({ 'image/png': blob })])
1358
+ return
1359
+ }
1360
+ }
1361
+ const blob = await blobPromise
1362
+ await nav.clipboard.write([new ClipboardItemCtor({ 'image/png': blob })])
1363
+ }
1364
+
1147
1365
  function Panel(props) {
1148
1366
  const ctx = props.ctx
1149
1367
  const locale = useLocale(ctx)
1150
- const copy = React.useMemo(() => translatedCopy(ctx), [locale])
1368
+ const copy = React.useMemo(() => translatedCopy(ctx, locale), [ctx, locale])
1151
1369
  const [period, setPeriod] = React.useState('day')
1152
1370
  const [currencyPreference, setCurrencyPreference] = React.useState('auto')
1153
1371
  const currency = resolveCurrencyPreference(currencyPreference, locale)
1154
1372
  const [anchor, setAnchor] = React.useState(() => startOfDay(new Date()))
1155
1373
  const [stage, setStage] = React.useState('processing')
1374
+ const [printRunId, setPrintRunId] = React.useState(0)
1156
1375
  const [data, setData] = React.useState(null)
1157
1376
  const [error, setError] = React.useState(null)
1158
1377
  const [saveState, setSaveState] = React.useState('idle')
1159
1378
  const [saveMessage, setSaveMessage] = React.useState('')
1379
+ const [copyState, setCopyState] = React.useState('idle')
1380
+ const [copyMessage, setCopyMessage] = React.useState('')
1381
+ const mountedRef = React.useRef(true)
1160
1382
  const abortRef = React.useRef(null)
1161
1383
  const timerRef = React.useRef(null)
1162
1384
  const saveTimerRef = React.useRef(null)
1163
- const firstRunRef = React.useRef(true)
1385
+ const copyTimerRef = React.useRef(null)
1164
1386
  const paperRef = React.useRef(null)
1165
1387
  const savingRef = React.useRef(false)
1166
1388
  const range = React.useMemo(() => periodRange(period, anchor), [period, anchor])
1167
1389
  const currentStart = currentPeriodStart(period)
1168
1390
  const nextDisabled = range.start.getTime() >= currentStart.getTime()
1169
- const rel = relativeLabel(period, range.start, copy)
1391
+ const displayStart = resolveDisplayStart(period, range.start, data)
1392
+ const rel = relativeLabel(period, displayStart, copy)
1170
1393
 
1171
- const runPrint = React.useCallback(async (animate = true) => {
1394
+ const clearExportTimers = () => {
1395
+ if (saveTimerRef.current) {
1396
+ clearTimeout(saveTimerRef.current)
1397
+ saveTimerRef.current = null
1398
+ }
1399
+ if (copyTimerRef.current) {
1400
+ clearTimeout(copyTimerRef.current)
1401
+ copyTimerRef.current = null
1402
+ }
1403
+ }
1404
+
1405
+ React.useEffect(() => {
1406
+ mountedRef.current = true
1407
+ return () => {
1408
+ mountedRef.current = false
1409
+ clearExportTimers()
1410
+ }
1411
+ }, [])
1412
+
1413
+ const updateAnchor = React.useCallback((nextOrUpdater) => {
1414
+ setAnchor((prev) => {
1415
+ const candidate = typeof nextOrUpdater === 'function' ? nextOrUpdater(prev) : nextOrUpdater
1416
+ const today = startOfDay(new Date())
1417
+ const clamped = candidate.getTime() > today.getTime() ? today : candidate
1418
+ return prev.getTime() === clamped.getTime() ? prev : clamped
1419
+ })
1420
+ }, [])
1421
+
1422
+ const runPrint = React.useCallback(async (animate = true, refresh = false) => {
1172
1423
  if (savingRef.current) return
1173
1424
  if (abortRef.current) abortRef.current.abort()
1174
1425
  if (timerRef.current) {
1175
1426
  clearTimeout(timerRef.current)
1176
1427
  timerRef.current = null
1177
1428
  }
1429
+ clearExportTimers()
1178
1430
  const controller = new AbortController()
1179
1431
  abortRef.current = controller
1432
+ const isStale = () => !mountedRef.current || controller.signal.aborted || abortRef.current !== controller
1433
+ const reduced = prefersReducedMotion()
1434
+ const shouldAnimate = Boolean(animate) && !reduced
1180
1435
  const startedAt = Date.now()
1181
1436
  setStage('processing')
1182
1437
  setError(null)
1183
1438
  setData(null)
1184
1439
  setSaveState('idle')
1185
1440
  setSaveMessage('')
1441
+ setCopyState('idle')
1442
+ setCopyMessage('')
1186
1443
  const from = range.start.getTime()
1187
1444
  const to = range.end.getTime()
1188
- const key = periodKey(period, range.start)
1445
+ const key = periodKey(period, range.start, range.end)
1446
+ const url =
1447
+ `/api/token-receipt?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&date=${encodeURIComponent(key)}&period=${encodeURIComponent(period)}` +
1448
+ (refresh ? '&refresh=1' : '')
1189
1449
  try {
1190
- const response = await fetch(
1191
- `/api/token-receipt?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&date=${encodeURIComponent(key)}&period=${encodeURIComponent(period)}`,
1192
- { signal: controller.signal, headers: { accept: 'application/json' } },
1193
- )
1450
+ const response = await fetch(url, { signal: controller.signal, headers: { accept: 'application/json' } })
1451
+ if (isStale()) return
1194
1452
  const payload = await response.json().catch(() => null)
1453
+ if (isStale()) return
1195
1454
  if (!response.ok || !payload || payload.ok !== true) {
1196
1455
  throw new Error((payload && payload.error) || `HTTP ${response.status}`)
1197
1456
  }
1198
- const remaining = animate ? MIN_PROCESSING_MS - (Date.now() - startedAt) : 0
1199
- if (remaining > 0 && !controller.signal.aborted) {
1200
- await new Promise((resolve) => setTimeout(resolve, remaining))
1457
+ const remaining = shouldAnimate ? MIN_PROCESSING_MS - (Date.now() - startedAt) : 0
1458
+ if (remaining > 0) {
1459
+ await waitWithAbort(remaining, controller.signal)
1201
1460
  }
1202
- if (controller.signal.aborted) return
1461
+ if (isStale()) return
1203
1462
  setData(payload)
1204
- if (!animate || REDUCED) {
1463
+ if (!shouldAnimate) {
1205
1464
  setStage('complete')
1206
1465
  } else {
1466
+ setPrintRunId((n) => n + 1)
1207
1467
  setStage('printing')
1208
- timerRef.current = setTimeout(() => setStage('complete'), 1900)
1468
+ timerRef.current = setTimeout(() => {
1469
+ timerRef.current = null
1470
+ if (!isStale()) setStage('complete')
1471
+ }, 1900)
1209
1472
  }
1210
1473
  } catch (fetchError) {
1211
- if (fetchError && fetchError.name === 'AbortError') return
1212
- setError(fetchError instanceof Error ? fetchError.message : String(fetchError))
1474
+ if (isStale()) return
1475
+ setError(errorMessage(fetchError))
1213
1476
  setStage('error')
1214
1477
  }
1215
1478
  }, [period, range])
1216
1479
 
1217
1480
  React.useEffect(() => {
1218
- const animate = firstRunRef.current
1219
- firstRunRef.current = false
1220
- runPrint(animate)
1481
+ runPrint(true)
1221
1482
  return () => {
1222
1483
  if (abortRef.current) abortRef.current.abort()
1223
- if (timerRef.current) clearTimeout(timerRef.current)
1224
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
1484
+ if (timerRef.current) {
1485
+ clearTimeout(timerRef.current)
1486
+ timerRef.current = null
1487
+ }
1225
1488
  }
1226
1489
  }, [runPrint])
1227
1490
 
1228
1491
  const busy = stage === 'processing' || stage === 'printing'
1229
- const locked = busy || saveState === 'saving'
1492
+ const locked = saveState === 'saving' || copyState === 'copying'
1493
+ const actionLocked = busy || locked
1494
+ const reduced = prefersReducedMotion()
1230
1495
  const primaryLabel = busy ? copy.printingButton : stage === 'complete' ? copy.again : copy.print
1496
+ const copyLabel = copyState === 'copying' ? copy.copyingImage : copyState === 'copied' ? copy.copiedImage : copyState === 'error' ? copy.copyFailed : copy.copyImage
1231
1497
  const saveLabel = saveState === 'saving' ? copy.savingPng : saveState === 'saved' ? copy.savedPng : saveState === 'error' ? copy.saveFailed : copy.savePng
1232
- const dateText = periodLabel(period, range.start, range.end, locale)
1498
+ const actionStatusText =
1499
+ copyState === 'copying'
1500
+ ? copy.copyingImage
1501
+ : copyState === 'copied'
1502
+ ? copy.copiedImage
1503
+ : copyState === 'error'
1504
+ ? `${copy.copyFailed}: ${copyMessage}`
1505
+ : saveState === 'saving'
1506
+ ? copy.savingPng
1507
+ : saveState === 'saved'
1508
+ ? copy.savedPng
1509
+ : saveState === 'error'
1510
+ ? `${copy.saveFailed}: ${saveMessage}`
1511
+ : ''
1512
+ const dateText = periodLabel(period, displayStart, range.end, locale)
1233
1513
  const screenSub = period === 'day' ? `${rel ? `${rel} · ` : ''}${shortDate(range.start, locale)}` : dateText
1234
1514
  const inputType = period === 'month' ? 'month' : 'date'
1235
1515
  const inputValue = period === 'month' ? monthKey(anchor) : dateKey(anchor)
@@ -1239,31 +1519,94 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1239
1519
  if (savingRef.current || next === period) return
1240
1520
  setPeriod(next)
1241
1521
  }
1522
+ const handleToday = () => {
1523
+ if (savingRef.current) return
1524
+ setPeriod('day')
1525
+ updateAnchor(startOfDay(new Date()))
1526
+ }
1527
+ const handleDateInputClick = (event) => {
1528
+ if (locked || savingRef.current || event.currentTarget.disabled) return
1529
+ try {
1530
+ event.currentTarget.showPicker?.()
1531
+ } catch {
1532
+ /* showPicker may throw if unsupported or already open */
1533
+ }
1534
+ }
1242
1535
  const handlePickDate = (event) => {
1243
1536
  if (savingRef.current) return
1244
1537
  const value = event.target.value
1245
1538
  if (!value) return
1246
1539
  const parsed = period === 'month' ? parseMonthKey(value) : parseDateKey(value)
1247
- if (parsed) setAnchor(period === 'month' ? startOfMonth(parsed) : startOfDay(parsed))
1540
+ if (parsed) updateAnchor(period === 'month' ? startOfMonth(parsed) : startOfDay(parsed))
1248
1541
  }
1249
- const handleSave = async () => {
1542
+ const runPaperAction = async ({
1543
+ action,
1544
+ logLabel,
1545
+ pendingState,
1546
+ doneState,
1547
+ setState,
1548
+ setMessage,
1549
+ clearOtherState,
1550
+ clearOtherMessage,
1551
+ actionTimerRef,
1552
+ }) => {
1250
1553
  if (!data || !paperRef.current || savingRef.current || busy) return
1251
1554
  savingRef.current = true
1252
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
1253
- setSaveState('saving')
1254
- setSaveMessage('')
1555
+ clearExportTimers()
1556
+ clearOtherState('idle')
1557
+ clearOtherMessage('')
1558
+ setState(pendingState)
1559
+ setMessage('')
1255
1560
  try {
1256
- await exportReceiptPng(paperRef.current, billNumber(period, data.date, data.totals.totalTokens, data.totals.requests))
1257
- setSaveState('saved')
1258
- saveTimerRef.current = setTimeout(() => setSaveState('idle'), 3200)
1259
- } catch (saveError) {
1260
- console.error('[token-receipt] PNG export failed', saveError)
1261
- setSaveState('error')
1262
- setSaveMessage(saveError instanceof Error ? saveError.message : String(saveError))
1561
+ await action(paperRef.current)
1562
+ if (!mountedRef.current) return
1563
+ setState(doneState)
1564
+ actionTimerRef.current = setTimeout(() => {
1565
+ actionTimerRef.current = null
1566
+ if (mountedRef.current) setState('idle')
1567
+ }, 3200)
1568
+ } catch (actionError) {
1569
+ if (!mountedRef.current) return
1570
+ console.error(logLabel, actionError)
1571
+ setState('error')
1572
+ setMessage(errorMessage(actionError))
1263
1573
  } finally {
1264
1574
  savingRef.current = false
1265
1575
  }
1266
1576
  }
1577
+ const handleCopy = () =>
1578
+ runPaperAction({
1579
+ action: (paperEl) => copyReceiptPng(paperEl, copy),
1580
+ logLabel: '[token-receipt] PNG copy failed',
1581
+ pendingState: 'copying',
1582
+ doneState: 'copied',
1583
+ setState: setCopyState,
1584
+ setMessage: setCopyMessage,
1585
+ clearOtherState: setSaveState,
1586
+ clearOtherMessage: setSaveMessage,
1587
+ actionTimerRef: copyTimerRef,
1588
+ })
1589
+ const handleSave = () =>
1590
+ runPaperAction({
1591
+ action: (paperEl) =>
1592
+ exportReceiptPng(
1593
+ paperEl,
1594
+ billNumber(period, data.date, data.totals.totalTokens, data.totals.requests),
1595
+ copy,
1596
+ ),
1597
+ logLabel: '[token-receipt] PNG export failed',
1598
+ pendingState: 'saving',
1599
+ doneState: 'saved',
1600
+ setState: setSaveState,
1601
+ setMessage: setSaveMessage,
1602
+ clearOtherState: setCopyState,
1603
+ clearOtherMessage: setCopyMessage,
1604
+ actionTimerRef: saveTimerRef,
1605
+ })
1606
+
1607
+ const exportErrorTitle = copyState === 'error' ? copy.copyFailed : saveState === 'error' ? copy.saveFailed : ''
1608
+ const exportErrorMessage = copyState === 'error' ? copyMessage : saveState === 'error' ? saveMessage : ''
1609
+ const exportRetryHandler = copyState === 'error' ? handleCopy : handleSave
1267
1610
 
1268
1611
  return h(
1269
1612
  'div',
@@ -1279,22 +1622,22 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1279
1622
  h(
1280
1623
  'div',
1281
1624
  { className: 'tr-actions' },
1282
- h('span', { className: 'tr-sr-only', role: 'status', 'aria-live': 'polite' }, saveState === 'saving' ? copy.savingPng : saveState === 'saved' ? copy.savedPng : saveState === 'error' ? `${copy.saveFailed}: ${saveMessage}` : ''),
1625
+ h('span', { className: 'tr-sr-only', role: 'status', 'aria-live': 'polite' }, actionStatusText),
1283
1626
  h(
1284
1627
  'button',
1285
- { className: 'tr-btn', type: 'button', disabled: !data || locked, onClick: () => window.print() },
1286
- h(PrinterGlyph, { size: 14 }),
1287
- copy.printPaper,
1628
+ { className: 'tr-btn', type: 'button', disabled: !data || actionLocked, onClick: handleCopy },
1629
+ copyState === 'copied' ? h(CheckCircle) : h(CopyIcon),
1630
+ copyLabel,
1288
1631
  ),
1289
1632
  h(
1290
1633
  'button',
1291
- { className: 'tr-btn', type: 'button', disabled: !data || locked, onClick: handleSave },
1634
+ { className: 'tr-btn', type: 'button', disabled: !data || actionLocked, onClick: handleSave },
1292
1635
  saveState === 'saved' ? h(CheckCircle) : h(DownloadIcon),
1293
1636
  saveLabel,
1294
1637
  ),
1295
1638
  h(
1296
1639
  'button',
1297
- { className: 'tr-btn tr-btn-primary', type: 'button', disabled: locked, onClick: () => runPrint(true) },
1640
+ { className: 'tr-btn tr-btn-primary', type: 'button', disabled: actionLocked, onClick: () => runPrint(true) },
1298
1641
  stage === 'complete' ? h(ReplayIcon) : h(PrinterGlyph, { size: 15 }),
1299
1642
  primaryLabel,
1300
1643
  ),
@@ -1309,44 +1652,59 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1309
1652
  h(
1310
1653
  'div',
1311
1654
  { className: 'tr-periods', role: 'group', 'aria-label': copy.period },
1312
- ['day', 'week', 'month'].map((value) =>
1655
+ PERIODS.map((value) =>
1313
1656
  h('button', { key: value, className: `tr-periodbtn${period === value ? ' is-active' : ''}`, type: 'button', 'aria-pressed': period === value, disabled: locked, onClick: () => handlePeriod(value) }, copy[value]),
1314
1657
  ),
1315
1658
  ),
1316
1659
  h('label', { className: 'tr-currency' }, copy.currency,
1317
- h('select', { value: currencyPreference, disabled: locked, 'aria-label': copy.currency, onChange: (event) => setCurrencyPreference(event.target.value) },
1660
+ h('select', { value: currencyPreference, disabled: locked, 'aria-label': copy.currency, onChange: (event) => { if (!savingRef.current) setCurrencyPreference(event.target.value) } },
1318
1661
  h('option', { value: 'auto' }, `${copy.autoCurrency} (${defaultCurrencyForLocale(locale).toUpperCase()})`),
1319
1662
  h('option', { value: 'usd' }, 'USD'), h('option', { value: 'cny' }, 'CNY'), h('option', { value: 'jpy' }, 'JPY'))),
1320
1663
  ),
1321
1664
  h(
1322
1665
  'div',
1323
1666
  { className: 'tr-daternav' },
1324
- h(
1325
- 'div',
1326
- { className: 'tr-datenav' },
1327
- h('button', { className: 'tr-navbtn', type: 'button', 'aria-label': copy.prevPeriod, disabled: locked, onClick: () => setAnchor((value) => shiftAnchor(period, value, -1)) }, h(Chevron, { dir: 'left' })),
1328
- h(
1329
- 'label',
1330
- { className: 'tr-datebox', title: copy.pickDate },
1331
- h('span', { className: 'tr-datemain' }, dateText),
1332
- rel ? h('span', { className: 'tr-daterel' }, rel) : null,
1333
- h('span', { className: 'tr-dateicon', 'aria-hidden': true }, h(CalendarIcon)),
1334
- h('input', { className: 'tr-datepicker', disabled: locked, type: inputType, value: inputValue, max: inputMax, 'aria-label': copy.pickDate, onChange: handlePickDate }),
1335
- ),
1336
- h('button', { className: 'tr-navbtn', type: 'button', 'aria-label': copy.nextPeriod, disabled: locked || nextDisabled, onClick: () => setAnchor((value) => shiftAnchor(period, value, 1)) }, h(Chevron, { dir: 'right' })),
1337
- ),
1338
- rel !== copy.today && rel !== copy.thisWeek && rel !== copy.thisMonth
1339
- ? h('button', { className: 'tr-btn tr-todaybtn', type: 'button', disabled: locked, onClick: () => { setPeriod('day'); setAnchor(startOfDay(new Date())) } }, copy.backToday)
1340
- : null,
1667
+ isSteppablePeriod(period)
1668
+ ? h(
1669
+ React.Fragment,
1670
+ null,
1671
+ h(
1672
+ 'div',
1673
+ { className: 'tr-datenav' },
1674
+ h('button', { className: 'tr-navbtn', type: 'button', 'aria-label': copy.prevPeriod, disabled: locked, onClick: () => { if (!savingRef.current) updateAnchor((value) => shiftAnchor(period, value, -1)) } }, h(Chevron, { dir: 'left' })),
1675
+ h(
1676
+ 'label',
1677
+ { className: 'tr-datebox', title: copy.pickDate },
1678
+ h('span', { className: 'tr-datemain' }, dateText),
1679
+ rel ? h('span', { className: 'tr-daterel' }, rel) : null,
1680
+ h('span', { className: 'tr-dateicon', 'aria-hidden': true }, h(CalendarIcon)),
1681
+ h('input', { className: 'tr-datepicker', disabled: locked, type: inputType, value: inputValue, max: inputMax, 'aria-label': copy.pickDate, onClick: handleDateInputClick, onChange: handlePickDate }),
1682
+ ),
1683
+ h('button', { className: 'tr-navbtn', type: 'button', 'aria-label': copy.nextPeriod, disabled: locked || nextDisabled, onClick: () => { if (!savingRef.current) updateAnchor((value) => shiftAnchor(period, value, 1)) } }, h(Chevron, { dir: 'right' })),
1684
+ ),
1685
+ rel !== copy.today && rel !== copy.thisWeek && rel !== copy.thisMonth
1686
+ ? h('button', { className: 'tr-btn tr-todaybtn', type: 'button', disabled: locked, onClick: handleToday }, copy.backToday)
1687
+ : null,
1688
+ )
1689
+ : h(
1690
+ 'div',
1691
+ { className: 'tr-datenav' },
1692
+ h(
1693
+ 'div',
1694
+ { className: 'tr-datebox is-static' },
1695
+ h('span', { className: 'tr-datemain' }, dateText),
1696
+ rel ? h('span', { className: 'tr-daterel' }, rel) : null,
1697
+ ),
1698
+ ),
1341
1699
  ),
1342
1700
  ),
1343
- saveState === 'error'
1701
+ copyState === 'error' || saveState === 'error'
1344
1702
  ? h(
1345
1703
  'div',
1346
1704
  { className: 'tr-save-error', role: 'alert' },
1347
- h('strong', null, copy.saveFailed),
1348
- h('span', null, saveMessage),
1349
- h('button', { className: 'tr-btn', type: 'button', onClick: handleSave }, copy.retry),
1705
+ h('strong', null, exportErrorTitle),
1706
+ h('span', null, exportErrorMessage),
1707
+ h('button', { className: 'tr-btn', type: 'button', disabled: !data || actionLocked, onClick: exportRetryHandler }, copy.retry),
1350
1708
  )
1351
1709
  : null,
1352
1710
  h(
@@ -1362,7 +1720,7 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1362
1720
  'div',
1363
1721
  { className: 'tr-machine-head' },
1364
1722
  h('div', { className: 'tr-brand' }, h(PrinterGlyph, { size: 22 }), h('span', null, 'TOKEN RECEIPT')),
1365
- h('button', { className: 'tr-machine-btn', type: 'button', disabled: locked, onClick: () => { setPeriod('day'); setAnchor(startOfDay(new Date())) } }, h('span', null, h(HomeIcon), copy.today)),
1723
+ h('button', { className: 'tr-machine-btn', type: 'button', disabled: locked, onClick: handleToday }, h('span', null, h(HomeIcon), copy.today)),
1366
1724
  ),
1367
1725
  h(
1368
1726
  'div',
@@ -1388,14 +1746,14 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1388
1746
  { className: 'tr-error', role: 'alert' },
1389
1747
  h('strong', null, copy.fetchError),
1390
1748
  h('span', null, error),
1391
- h('div', null, h('button', { className: 'tr-btn', type: 'button', onClick: () => runPrint(true) }, copy.retry)),
1749
+ h('div', null, h('button', { className: 'tr-btn', type: 'button', disabled: actionLocked, onClick: () => runPrint(true) }, copy.retry)),
1392
1750
  )
1393
1751
  : h(
1394
1752
  'div',
1395
1753
  { className: 'tr-output' },
1396
1754
  h(
1397
1755
  'div',
1398
- { className: `tr-paper-wrap${REDUCED ? ' is-reduced' : ''}`, 'data-stage': stage === 'processing' ? 'processing' : stage, 'aria-hidden': stage !== 'complete' },
1756
+ { key: printRunId, className: `tr-paper-wrap${reduced ? ' is-reduced' : ''}`, 'data-stage': stage === 'processing' ? 'processing' : stage, 'aria-hidden': stage !== 'complete' },
1399
1757
  data ? h(Receipt, { copy, locale, data, period, paperRef, currency }) : null,
1400
1758
  ),
1401
1759
  ),
@@ -1403,7 +1761,7 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1403
1761
  data && (data.pricing?.status !== 'complete' || data.pricing?.stale)
1404
1762
  ? h('div', { className: 'tr-price-feedback', role: 'status' },
1405
1763
  h('span', null, data.pricing?.stale ? copy.stalePrice : data.pricing?.status === 'partial' ? copy.partialPrice.replace('{n}', data.pricing.unpricedRequests) : copy.unavailablePrice),
1406
- h('button', { className: 'tr-btn', type: 'button', disabled: locked, onClick: () => runPrint(false) }, copy.priceRetry))
1764
+ h('button', { className: 'tr-btn', type: 'button', disabled: actionLocked, onClick: () => runPrint(false, true) }, copy.priceRetry))
1407
1765
  : null,
1408
1766
  h('div', { className: 'tr-foot' }, h('i', null), copy.dataNote),
1409
1767
  ),
@@ -1412,14 +1770,26 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1412
1770
  }
1413
1771
 
1414
1772
  function apply(ctx) {
1773
+ ctx.effect(() => {
1774
+ if (typeof document === 'undefined' || !document.head || typeof document.createElement !== 'function') return
1775
+ const existing = typeof document.getElementById === 'function' ? document.getElementById('dsh-token-receipt-fonts') : null
1776
+ if (existing) return
1777
+ const styleEl = document.createElement('style')
1778
+ styleEl.id = 'dsh-token-receipt-fonts'
1779
+ styleEl.textContent = FONT_CSS
1780
+ document.head.appendChild(styleEl)
1781
+ return () => {
1782
+ styleEl.remove()
1783
+ }
1784
+ }, 'token-receipt: fonts')
1415
1785
  ctx.effect(() => {
1416
1786
  if (ctx.locale.getSnapshot().locales.some((language) => language.id === 'ja')) return
1417
1787
  return ctx.locale.addLanguage({ id: 'ja', label: '日本語', fallback: 'en' })
1418
1788
  }, 'token-receipt: Japanese language')
1419
1789
  ctx.effect(() => ctx.locale.register(NS, DICT), 'token-receipt: dictionaries')
1420
1790
  const label = () => {
1421
- const active = ctx.locale.getSnapshot().active || 'en'
1422
- return ((DICT[active] || DICT.en).nav)
1791
+ const lang = normalizeLocale(ctx.locale.getSnapshot().active)
1792
+ return (DICT[lang] || DICT.en).nav
1423
1793
  }
1424
1794
  ctx.slots.inject('sidebar.panellist', () =>
1425
1795
  ctx.slots.register({ name: 'sidebar.panellist', id: PANEL, order: 7, label }, (props) => h(PrinterGlyph, { size: (props && props.size) || 18 })),