dsh-token-receipt 1.0.0 → 1.1.1

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
@@ -10,6 +10,8 @@ window.__ModuleLoader__.load({
10
10
  const h = React.createElement
11
11
  const NS = 'token-receipt'
12
12
  const PANEL = 'token-receipt'
13
+ /** Kept in sync with package.json by tests/version-guard.test.js. */
14
+ const CLIENT_VERSION = '1.1.1'
13
15
  const DAY_MS = 24 * 60 * 60 * 1000
14
16
  const MIN_PROCESSING_MS = 850
15
17
  const EXPORT_SCALE = 3
@@ -21,14 +23,14 @@ window.__ModuleLoader__.load({
21
23
 
22
24
  const FONT_CSS = `
23
25
  @font-face {
24
- font-family: 'Inter';
26
+ font-family: 'TokenReceiptInter';
25
27
  font-style: normal;
26
28
  font-weight: 100 900;
27
29
  font-display: swap;
28
30
  src: url(data:font/woff2;base64,${INTER_FONT}) format('woff2');
29
31
  }
30
32
  @font-face {
31
- font-family: 'JetBrains Mono';
33
+ font-family: 'TokenReceiptMono';
32
34
  font-style: normal;
33
35
  font-weight: 100 800;
34
36
  font-display: swap;
@@ -40,21 +42,26 @@ window.__ModuleLoader__.load({
40
42
  zh: {
41
43
  nav: 'Token 账单',
42
44
  title: 'Token 账单',
43
- subtitle: '把 token 用量打印成一张有手感的小票。选择日、周或月,打印后还能保存 PNG。',
45
+ subtitle: '把 token 用量打印成一张有手感的小票。选择统计周期,打印后可复制图片或保存 PNG。',
44
46
  print: '打印账单',
45
47
  again: '重播打印',
46
48
  printingButton: '打印中…',
49
+ copyImage: '复制图片',
50
+ copyingImage: '复制中…',
51
+ copiedImage: '已复制',
52
+ copyFailed: '复制失败',
53
+ clipboardUnsupported: '当前环境不支持复制图片到剪贴板',
47
54
  savePng: '保存 PNG',
48
- printPaper: '打印 / PDF',
49
55
  savingPng: '生成中…',
50
56
  savedPng: '已保存',
51
57
  saveFailed: '保存失败',
52
58
  day: '日',
53
59
  week: '周',
54
60
  month: '月',
55
- daily: '每日',
56
- weekly: '每周',
57
- monthly: '每月',
61
+ days30: '近 30 天',
62
+ days90: '近 90 天',
63
+ all: '全部',
64
+ allTime: '全部时间',
58
65
  today: '今天',
59
66
  yesterday: '昨天',
60
67
  thisWeek: '本周',
@@ -70,7 +77,6 @@ window.__ModuleLoader__.load({
70
77
  completeStatus: '账单打印完成',
71
78
  errorStatus: '读取用量失败',
72
79
  readyStatus: '准备就绪',
73
- total: '总计',
74
80
  usage: 'Token 用量',
75
81
  billNo: '账单号',
76
82
  period: '周期',
@@ -82,11 +88,9 @@ window.__ModuleLoader__.load({
82
88
  reasoning: '推理',
83
89
  requests: '请求',
84
90
  sessions: '会话',
85
- models: '模型',
86
91
  model: '模型',
87
92
  moreModels: '其余 {n} 个模型',
88
93
  noUsage: '当前周期没有用量记录',
89
- emptyHint: '这个周期还没有产生 token 用量。',
90
94
  dataNote: '用量保留在本机,仅联网读取公开模型价格。',
91
95
  currency: '币种',
92
96
  autoCurrency: '跟随语言',
@@ -94,38 +98,46 @@ window.__ModuleLoader__.load({
94
98
  estimatedTotal: '预估总计',
95
99
  partialTotal: '已计价小计',
96
100
  totalTokens: 'Token 总量',
97
- referencePrice: '参考估算 · models.dev',
98
101
  partialPrice: '有 {n} 次请求未计价,金额为部分小计。',
99
102
  unavailablePrice: '价格暂不可用,用量已保留。',
100
103
  stalePrice: '使用上次获取的价格,稍后可重试。',
101
- fallbackPrice: 'WorkBuddy 按 DeepSeek Flash 官方参考价估算。',
102
104
  exchangeRate: '人民币按 1 USD ≈ 6.67 CNY 换算。',
103
105
  unpriced: '未计价',
104
106
  priceRetry: '重新获取价格',
105
- priceAsOf: '价格更新',
106
107
  fetchError: '读取用量失败',
107
108
  retry: '重试',
108
109
  thankYou: '感谢每一次提问',
109
110
  receiptLabel: 'Token 用量账单',
111
+ exportNotReady: '账单尚未就绪',
112
+ exportClosed: '导出完成前账单已关闭',
113
+ exportChanged: '保存过程中语言或币种已变更,请重试。',
114
+ exportFailed: '生成 PNG 失败',
115
+ updateAvailable: 'Token 账单已更新到 {version},当前界面仍是旧版。',
116
+ updateReload: '刷新界面',
110
117
  },
111
118
  en: {
112
119
  nav: 'Token receipt',
113
120
  title: 'Token receipt',
114
- subtitle: 'Print token usage as a tactile receipt. Pick a day, week, or month, then print or save a PNG.',
121
+ subtitle: 'Print token usage as a tactile receipt. Pick a period, then copy the image or save a PNG.',
115
122
  print: 'Print bill',
116
123
  again: 'Replay print',
117
124
  printingButton: 'Printing…',
125
+ copyImage: 'Copy image',
126
+ copyingImage: 'Copying…',
127
+ copiedImage: 'Copied',
128
+ copyFailed: 'Copy failed',
129
+ clipboardUnsupported: 'Image clipboard copy is not supported in this browser',
118
130
  savePng: 'Save PNG',
119
- printPaper: 'Print / PDF',
120
131
  savingPng: 'Rendering…',
121
132
  savedPng: 'Saved',
122
133
  saveFailed: 'Save failed',
123
134
  day: 'Day',
124
135
  week: 'Week',
125
136
  month: 'Month',
126
- daily: 'Daily',
127
- weekly: 'Weekly',
128
- monthly: 'Monthly',
137
+ days30: '30 days',
138
+ days90: '90 days',
139
+ all: 'All',
140
+ allTime: 'All time',
129
141
  today: 'Today',
130
142
  yesterday: 'Yesterday',
131
143
  thisWeek: 'This week',
@@ -138,10 +150,9 @@ window.__ModuleLoader__.load({
138
150
  pickDate: 'Pick a date',
139
151
  preparing: 'Preparing usage',
140
152
  printingStatus: 'Printing your receipt',
141
- completeStatus: 'Order complete',
153
+ completeStatus: 'Receipt complete',
142
154
  errorStatus: 'Could not read usage',
143
155
  readyStatus: 'Ready to print',
144
- total: 'Total',
145
156
  usage: 'Token usage',
146
157
  billNo: 'Bill no',
147
158
  period: 'Period',
@@ -153,11 +164,9 @@ window.__ModuleLoader__.load({
153
164
  reasoning: 'Reasoning',
154
165
  requests: 'Requests',
155
166
  sessions: 'Sessions',
156
- models: 'Models',
157
167
  model: 'Model',
158
168
  moreModels: '+{n} more models',
159
169
  noUsage: 'No usage recorded',
160
- emptyHint: 'No token usage in this period yet.',
161
170
  dataNote: 'Usage stays local. Only public model prices are fetched online.',
162
171
  currency: 'Currency',
163
172
  autoCurrency: 'Follow language',
@@ -165,38 +174,46 @@ window.__ModuleLoader__.load({
165
174
  estimatedTotal: 'Estimated total',
166
175
  partialTotal: 'Priced subtotal',
167
176
  totalTokens: 'Total tokens',
168
- referencePrice: 'Reference estimate · models.dev',
169
177
  partialPrice: '{n} requests unpriced; subtotal excludes them.',
170
178
  unavailablePrice: 'Prices unavailable. Usage is still recorded.',
171
179
  stalePrice: 'Using previously fetched prices. Retry to refresh.',
172
- fallbackPrice: 'WorkBuddy uses DeepSeek Flash official reference rates.',
173
180
  exchangeRate: 'CNY converted at 1 USD ≈ 6.67 CNY.',
174
181
  unpriced: 'Unpriced',
175
182
  priceRetry: 'Retry prices',
176
- priceAsOf: 'Prices updated',
177
183
  fetchError: 'Could not read usage',
178
184
  retry: 'Retry',
179
185
  thankYou: 'Thank you for prompting',
180
186
  receiptLabel: 'Token usage receipt',
187
+ exportNotReady: 'Receipt is not ready',
188
+ exportClosed: 'Receipt was closed before export completed',
189
+ exportChanged: 'Receipt language or currency changed while saving. Please retry.',
190
+ exportFailed: 'Canvas export failed',
191
+ updateAvailable: 'Token receipt has been updated to {version}. This window is still showing the old version.',
192
+ updateReload: 'Reload UI',
181
193
  },
182
194
  ja: {
183
195
  nav: "トークン明細",
184
196
  title: "トークン明細",
185
- subtitle: "トークン使用量と推定料金をレシートに。日・週・月を選び、印刷や PNG 保存ができます。",
197
+ subtitle: "トークン使用量と推定料金をレシートに。期間を選び、画像のコピーや PNG 保存ができます。",
186
198
  print: "明細を印刷",
187
199
  again: "印刷を再生",
188
200
  printingButton: "印刷中…",
201
+ copyImage: "画像をコピー",
202
+ copyingImage: "コピー中…",
203
+ copiedImage: "コピーしました",
204
+ copyFailed: "コピーできませんでした",
205
+ clipboardUnsupported: "この環境では画像のクリップボードコピーに対応していません",
189
206
  savePng: "PNG を保存",
190
- printPaper: "印刷 / PDF",
191
207
  savingPng: "生成中…",
192
208
  savedPng: "保存しました",
193
209
  saveFailed: "保存できませんでした",
194
210
  day: "日",
195
211
  week: "週",
196
212
  month: "月",
197
- daily: "日次",
198
- weekly: "週次",
199
- monthly: "月次",
213
+ days30: "直近30日",
214
+ days90: "直近90日",
215
+ all: "全期間",
216
+ allTime: "全期間",
200
217
  today: "今日",
201
218
  yesterday: "昨日",
202
219
  thisWeek: "今週",
@@ -212,7 +229,6 @@ window.__ModuleLoader__.load({
212
229
  completeStatus: "印刷が完了しました",
213
230
  errorStatus: "使用量を読み込めませんでした",
214
231
  readyStatus: "印刷できます",
215
- total: "合計",
216
232
  usage: "トークン使用量",
217
233
  billNo: "明細番号",
218
234
  period: "期間",
@@ -224,11 +240,9 @@ window.__ModuleLoader__.load({
224
240
  reasoning: "推論",
225
241
  requests: "リクエスト",
226
242
  sessions: "セッション",
227
- models: "モデル",
228
243
  model: "モデル",
229
244
  moreModels: "その他 {n} モデル",
230
245
  noUsage: "この期間の使用記録はありません",
231
- emptyHint: "この期間のトークン使用量はまだありません。",
232
246
  dataNote: "使用量は端末内に保管し、公開モデル料金のみをオンラインで取得します。",
233
247
  currency: "通貨",
234
248
  autoCurrency: "言語に合わせる",
@@ -236,28 +250,49 @@ window.__ModuleLoader__.load({
236
250
  estimatedTotal: "推定合計",
237
251
  partialTotal: "計算済み小計",
238
252
  totalTokens: "総トークン数",
239
- referencePrice: "参考料金 · models.dev",
240
253
  partialPrice: "{n} 件は料金未計算のため、小計に含まれません。",
241
254
  unavailablePrice: "料金を取得できません。使用量は保持されています。",
242
255
  stalePrice: "前回取得した料金を使用中です。後ほど再試行してください。",
243
- fallbackPrice: "WorkBuddy は DeepSeek Flash の公式参考料金で計算します。",
244
256
  exchangeRate: "人民元は 1 USD ≈ 6.67 CNY で換算。",
245
257
  unpriced: "料金未計算",
246
258
  priceRetry: "料金を再取得",
247
- priceAsOf: "料金更新",
248
259
  fetchError: "使用量を読み込めませんでした",
249
260
  retry: "再試行",
250
261
  thankYou: "ご利用ありがとうございます",
251
262
  receiptLabel: "トークン使用明細",
263
+ exportNotReady: "明細の準備ができていません",
264
+ exportClosed: "出力完了前に明細が閉じられました",
265
+ exportChanged: "保存中に言語または通貨が変更されました。もう一度お試しください。",
266
+ exportFailed: "PNG の書き出しに失敗しました",
267
+ updateAvailable: 'Token レシートは {version} に更新されました。この画面はまだ旧バージョンです。',
268
+ updateReload: '画面を更新',
252
269
  },
253
270
  }
254
271
 
255
- const REDUCED =
256
- typeof window !== 'undefined' &&
257
- typeof window.matchMedia === 'function' &&
258
- window.matchMedia('(prefers-reduced-motion: reduce)').matches
272
+ function prefersReducedMotion() {
273
+ return (
274
+ typeof window !== 'undefined' &&
275
+ typeof window.matchMedia === 'function' &&
276
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
277
+ )
278
+ }
279
+
280
+ function waitWithAbort(ms, signal) {
281
+ if (ms <= 0 || signal.aborted) return Promise.resolve()
282
+ return new Promise((resolve) => {
283
+ const onAbort = () => {
284
+ clearTimeout(timer)
285
+ resolve()
286
+ }
287
+ const timer = setTimeout(() => {
288
+ signal.removeEventListener('abort', onAbort)
289
+ resolve()
290
+ }, ms)
291
+ signal.addEventListener('abort', onAbort, { once: true })
292
+ })
293
+ }
259
294
 
260
- const CSS = `${FONT_CSS}
295
+ const CSS = `
261
296
  .tr-page, .tr-page * { box-sizing: border-box; }
262
297
  .tr-page {
263
298
  --tr-g1: #fcfcfc;
@@ -293,7 +328,7 @@ window.__ModuleLoader__.load({
293
328
  overflow: auto;
294
329
  background: var(--tr-page-bg);
295
330
  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;
331
+ font-family: "TokenReceiptInter", Inter, "Inter Fallback", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
297
332
  font-synthesis: none;
298
333
  }
299
334
  body[data-ds-dark-theme] .tr-page {
@@ -336,28 +371,38 @@ body[data-ds-dark-theme] .tr-page {
336
371
  .tr-btn:hover:not(:disabled) { border-color: var(--tr-g4); background: var(--tr-g3); color: var(--tr-g12); }
337
372
  .tr-btn:active:not(:disabled) { transform: translateY(1px); }
338
373
  .tr-btn:disabled { opacity: .55; cursor: default; }
374
+ .tr-btn:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
339
375
  .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
376
  .tr-btn-primary:hover:not(:disabled) { background: var(--tr-g11); border-color: transparent; }
341
377
  .tr-filter-group { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
342
378
  .tr-currency { display: flex; align-items: center; gap: 7px; color: var(--tr-page-muted); font-size: 11px; }
343
379
  .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; }
380
+ .tr-currency select:disabled { opacity: .55; cursor: default; }
344
381
  .tr-currency select:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
345
382
  .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
383
  .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); }
384
+ .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); }
385
+ .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; }
386
+ .tr-periodbtn:hover:not(:disabled):not(.is-active) { background: var(--tr-g2); color: var(--tr-g12); }
387
+ .tr-periodbtn:active:not(:disabled) { transform: translateY(1px); }
388
+ .tr-periodbtn:disabled { opacity: .55; cursor: default; }
389
+ .tr-periodbtn:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
350
390
  .tr-periodbtn.is-active { background: var(--tr-g12); color: var(--tr-g1); }
351
391
  .tr-daternav { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; }
352
392
  .tr-datenav { display: flex; align-items: center; border: 1px solid var(--tr-g3); border-radius: 8px; background: var(--tr-g1); padding: 3px; }
353
393
  .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
394
  .tr-navbtn:hover:not(:disabled) { background: var(--tr-g2); color: var(--tr-g12); }
395
+ .tr-navbtn:active:not(:disabled) { transform: translateY(1px); }
355
396
  .tr-navbtn:disabled { opacity: .35; cursor: default; }
397
+ .tr-navbtn:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
356
398
  .tr-datebox { position: relative; min-width: 132px; padding: 0 20px 0 7px; text-align: center; cursor: pointer; border-radius: 6px; }
399
+ .tr-datebox.is-static { padding: 2px 12px; cursor: default; min-width: 132px; }
357
400
  .tr-datebox:focus-within { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
358
401
  .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); }
402
+ .tr-datebox:not(.is-static):hover:not(:has(.tr-datepicker:disabled)) { background: var(--tr-g2); }
403
+ .tr-datebox:has(.tr-datepicker:disabled) { opacity: .55; cursor: default; }
360
404
  .tr-datepicker { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; padding: 0; opacity: 0; cursor: pointer; }
405
+ .tr-datepicker:disabled { cursor: default; }
361
406
  .tr-datemain { display: block; white-space: nowrap; font-size: 12.5px; font-weight: 600; line-height: 1.25; font-variant-numeric: tabular-nums; }
362
407
  .tr-daterel { display: block; margin-top: 1px; color: var(--tr-page-muted); font-size: 9.5px; line-height: 1.25; white-space: nowrap; }
363
408
  .tr-todaybtn { height: 32px; padding: 0 11px; font-size: 11px; }
@@ -372,8 +417,10 @@ body[data-ds-dark-theme] .tr-page {
372
417
  .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
418
  .tr-machine-btn::before { content: ""; position: absolute; inset: 3px 0 0; border-radius: 12px; background: #292926; box-shadow: inset 0 -1px 0 #141412; }
374
419
  .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); }
420
+ .tr-machine-btn:hover:not(:disabled)::after { transform: translateY(2px); }
421
+ .tr-machine-btn:active:not(:disabled)::after { transform: translateY(3px); }
422
+ .tr-machine-btn:disabled { opacity: .55; cursor: default; }
423
+ .tr-machine-btn:focus-visible { outline: 2px solid var(--tr-g9); outline-offset: 2px; }
377
424
  .tr-machine-btn > span { position: relative; z-index: 2; display: inline-flex; align-items: center; gap: 5px; height: 32px; }
378
425
  .tr-machine-btn svg { width: 12px; height: 12px; }
379
426
  .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 +431,6 @@ body[data-ds-dark-theme] .tr-page {
384
431
  .tr-screen-right { flex: none; text-align: right; }
385
432
  .tr-screen-label { margin: 0; color: var(--tr-screen-muted); font-size: 12px; line-height: 1.3; }
386
433
  .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
434
  .tr-status { position: relative; z-index: 1; display: flex; align-items: center; gap: 8px; min-height: 20px; margin-top: 15px; }
389
435
  .tr-status-icon { flex: none; display: grid; place-items: center; width: 20px; height: 20px; }
390
436
  .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 +446,6 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
400
446
  .tr-paper-wrap[data-stage="printing"] { opacity: 1; animation: tr-feed 1.75s linear both; }
401
447
  .tr-paper-wrap[data-stage="printing"].is-reduced { animation: none; transform: translateY(0); }
402
448
  .tr-paper-wrap[data-stage="complete"] { opacity: 1; transform: translateY(0); }
403
- .tr-paper-wrap[data-stage="idle"] { opacity: 0; }
404
449
  .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
450
  .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
451
  @keyframes tr-feed {
@@ -426,9 +471,9 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
426
471
  100% { transform: translateY(0); }
427
472
  }
428
473
 
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; }
474
+ .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)); }
475
+ .tr-page:lang(ja) { font-family: "TokenReceiptInter", Inter, "Hiragino Kaku Gothic ProN", "Yu Gothic", Meiryo, "Noto Sans JP", sans-serif; }
476
+ .tr-page:lang(ja) .tr-paper { font-family: "TokenReceiptMono", "JetBrains Mono", "Hiragino Kaku Gothic ProN", "Yu Gothic", Meiryo, "Noto Sans JP", monospace; }
432
477
  .tr-paper-head { text-align: center; }
433
478
  .tr-paper-logo { display: block; width: 40px; height: 40px; margin: 0 auto; color: var(--tr-paper-ink); opacity: .9; }
434
479
  .tr-paper-kicker { margin: 13px 0 0; font-size: 9px; font-weight: 700; letter-spacing: .22em; text-transform: uppercase; }
@@ -443,53 +488,50 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
443
488
  .tr-price-notes p { margin: 0; font-size: 7px; line-height: 12px; opacity: .55; overflow-wrap: anywhere; }
444
489
  .tr-item { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; font-size: 9px; line-height: 16px; }
445
490
  .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
491
  .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
492
  .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
493
  .tr-summary { display: flex; flex-direction: column; gap: 6px; margin: 0; }
451
494
  .tr-summary-row { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; font-size: 9px; line-height: 9px; }
452
495
  .tr-summary-row dt { margin: 0; color: var(--tr-paper-ink); opacity: .55; }
453
496
  .tr-summary-row dd { margin: 0; font-variant-numeric: tabular-nums; }
454
497
  .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
498
  .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; }
499
+ .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
500
  .tr-meta { display: grid; grid-template-columns: minmax(0,1fr) auto; gap: 4px 16px; font-size: 8px; line-height: 12px; }
459
501
  .tr-meta dt { margin: 0; color: var(--tr-paper-ink); opacity: .55; }
460
502
  .tr-meta dd { margin: 0; text-align: right; font-variant-numeric: tabular-nums; }
461
503
  .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; }
504
+ .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
505
  .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
506
  .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
507
 
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; }
508
+ .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
509
  .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
510
  .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
511
  .tr-save-error strong { flex: none; }
470
512
  .tr-save-error span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--tr-page-muted); }
471
513
  .tr-save-error .tr-btn { margin-left: auto; }
472
514
  .tr-error strong { display: block; margin-bottom: 3px; font-size: 12.5px; }
473
- .tr-error span { color: var(--dsw-alias-label-secondary); }
515
+ .tr-error span { color: var(--tr-page-muted); }
474
516
  .tr-error button { margin-top: 9px; }
475
517
  .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
518
  .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
519
  @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; }
520
+ body:has(.tr-page) * { visibility: hidden !important; }
521
+ body:has(.tr-page) .tr-page, body:has(.tr-page) .tr-page * { visibility: visible !important; }
522
+ 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
523
  .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; }
524
+ .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
525
  .tr-stage { padding: 0 !important; background: none !important; }
484
526
  .tr-printer { width: 100% !important; }
485
- .tr-output { width: auto !important; height: auto !important; margin: 0 !important; padding: 0 !important; overflow: visible !important; }
527
+ .tr-output { width: auto !important; min-height: 0 !important; height: auto !important; margin: 0 !important; padding: 0 !important; overflow: visible !important; }
486
528
  .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; }
529
+ .tr-paper { width: 307px !important; margin: 0 auto !important; box-shadow: none !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
488
530
  }
489
531
  @media (prefers-reduced-motion: reduce) {
490
532
  .tr-spin { animation: none; }
491
- .tr-btn, .tr-navbtn, .tr-machine-btn::after { transition: none; }
492
- .tr-btn:active:not(:disabled) { transform: none; }
533
+ .tr-btn, .tr-periodbtn, .tr-navbtn, .tr-machine-btn::after { transition: none; }
534
+ .tr-btn:active:not(:disabled), .tr-periodbtn:active:not(:disabled), .tr-navbtn:active:not(:disabled) { transform: none; }
493
535
  .tr-paper-wrap[data-stage="printing"] { animation: none; transform: translateY(0); }
494
536
  }
495
537
  @media (max-width: 720px) {
@@ -508,8 +550,6 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
508
550
  }
509
551
  `
510
552
 
511
- const PANEL_LABEL = { zh: 'Token 账单', en: 'Token receipt', ja: 'トークン明細' }
512
-
513
553
  // Official DSH whale geometry from dsh-web-frontend/dist/favicon.svg.
514
554
  // Share the path between the receipt and its Canvas PNG export.
515
555
  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 +612,15 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
572
612
  )
573
613
  }
574
614
 
615
+ function CopyIcon() {
616
+ return h(
617
+ 'svg',
618
+ { width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
619
+ h('rect', { x: 9, y: 9, width: 11, height: 11, rx: 2 }),
620
+ h('path', { d: 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1' }),
621
+ )
622
+ }
623
+
575
624
  function Spinner() {
576
625
  return h(
577
626
  'svg',
@@ -609,22 +658,112 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
609
658
  )
610
659
  }
611
660
 
661
+ function normalizeLocale(raw) {
662
+ const language = String(raw || 'en').trim().toLowerCase().split(/[-_]/)[0]
663
+ return language === 'zh' ? 'zh' : language === 'ja' ? 'ja' : 'en'
664
+ }
665
+
612
666
  function useLocale(ctx) {
613
667
  const [snapshot, setSnapshot] = React.useState(() => ctx.locale.getSnapshot())
614
- React.useEffect(() => ctx.locale.subscribe(() => setSnapshot(ctx.locale.getSnapshot())), [])
615
- return snapshot.active || 'en'
668
+ React.useEffect(() => {
669
+ setSnapshot(ctx.locale.getSnapshot())
670
+ return ctx.locale.subscribe(() => setSnapshot(ctx.locale.getSnapshot()))
671
+ }, [ctx])
672
+ return normalizeLocale(snapshot && snapshot.active)
616
673
  }
617
674
 
618
- function translatedCopy(ctx) {
619
- const t = ctx.locale.bind(NS)
675
+ function translatedCopy(ctx, locale) {
676
+ const rawActive = ctx && ctx.locale && typeof ctx.locale.getSnapshot === 'function' ? ctx.locale.getSnapshot().active : undefined
677
+ const lang = normalizeLocale(locale || rawActive)
678
+ const fallbackDict = DICT[lang] || DICT.en
679
+ const regionalMismatch = typeof rawActive === 'string' && !Object.hasOwn(DICT, rawActive) && lang !== 'en'
680
+ const t = ctx && ctx.locale && typeof ctx.locale.bind === 'function' ? ctx.locale.bind(NS) : null
620
681
  const out = {}
621
682
  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]
683
+ const value = t ? t(key) : null
684
+ const usable =
685
+ typeof value === 'string' &&
686
+ value.length > 0 &&
687
+ value !== key &&
688
+ value !== `${NS}.${key}` &&
689
+ !(regionalMismatch && value === DICT.en[key])
690
+ out[key] = usable ? value : fallbackDict[key] || DICT.en[key]
624
691
  }
625
692
  return out
626
693
  }
627
694
 
695
+ /**
696
+ * Watch the Host's package version while this page keeps running. DSH Desktop
697
+ * does not refresh an installed plugin's browser bundle in place, so when the
698
+ * Host has been updated this banner offers the page reload that activates it.
699
+ */
700
+ function installUpdateGuard(ctx) {
701
+ if (
702
+ typeof window === 'undefined' ||
703
+ typeof document === 'undefined' ||
704
+ typeof window.addEventListener !== 'function' ||
705
+ typeof window.removeEventListener !== 'function' ||
706
+ typeof document.createElement !== 'function' ||
707
+ !document.body
708
+ ) return undefined
709
+ let banner = null
710
+ let checking = false
711
+ let timer = null
712
+ const copy = translatedCopy(ctx)
713
+ const showBanner = (version) => {
714
+ if (banner !== null && String(banner.dataset.version) === version) return
715
+ const text = String(copy.updateAvailable || 'Token receipt has been updated to {version}.').replace('{version}', version)
716
+ if (banner === null) {
717
+ banner = document.createElement('div')
718
+ banner.id = 'dsh-token-receipt-update'
719
+ banner.setAttribute('role', 'status')
720
+ banner.setAttribute('data-token-receipt-update', '')
721
+ banner.style.cssText = 'position:fixed;z-index:2147483647;left:50%;bottom:20px;transform:translateX(-50%);display:flex;align-items:center;gap:12px;max-width:min(560px,calc(100vw - 32px));box-sizing:border-box;padding:10px 14px;border-radius:10px;border:1px solid var(--dsw-alias-border-l2,#3a3a3a);background:var(--dsw-alias-bg-layer-1,#1f1f1f);color:var(--dsw-alias-label-primary,#fff);box-shadow:0 8px 24px rgba(0,0,0,.28);font:500 13px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif'
722
+ const message = document.createElement('span')
723
+ message.setAttribute('data-token-receipt-update-message', '')
724
+ const button = document.createElement('button')
725
+ button.type = 'button'
726
+ button.setAttribute('data-token-receipt-update-reload', '')
727
+ button.style.cssText = 'flex:none;border:0;border-radius:7px;padding:5px 10px;background:var(--dsw-alias-label-primary,#fff);color:var(--dsw-alias-bg-layer-1,#1f1f1f);font:600 12px/1.3 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;cursor:pointer'
728
+ button.textContent = copy.updateReload || 'Reload UI'
729
+ button.addEventListener('click', () => window.location.reload())
730
+ banner.appendChild(message)
731
+ banner.appendChild(button)
732
+ document.body.appendChild(banner)
733
+ }
734
+ const message = banner.querySelector('[data-token-receipt-update-message]')
735
+ if (message !== null) message.textContent = text
736
+ banner.dataset.version = version
737
+ }
738
+ const check = async () => {
739
+ if (checking) return
740
+ checking = true
741
+ try {
742
+ const response = await fetch('/api/token-receipt?version=1', { cache: 'no-store', headers: { accept: 'application/json' } })
743
+ if (!response.ok) return
744
+ const payload = await response.json().catch(() => null)
745
+ const version = payload && payload.ok === true && typeof payload.version === 'string' ? payload.version : null
746
+ if (version !== null && version !== CLIENT_VERSION) showBanner(version)
747
+ } catch {
748
+ // A stale page must not throw because the host is restarting or the probe is unavailable.
749
+ } finally {
750
+ checking = false
751
+ }
752
+ }
753
+ const onFocus = () => { void check() }
754
+ const onVisibility = () => { if (document.visibilityState === 'visible') void check() }
755
+ timer = window.setInterval(check, 30000)
756
+ window.addEventListener('focus', onFocus)
757
+ document.addEventListener('visibilitychange', onVisibility)
758
+ void check()
759
+ return () => {
760
+ if (timer !== null) window.clearInterval(timer)
761
+ window.removeEventListener('focus', onFocus)
762
+ document.removeEventListener('visibilitychange', onVisibility)
763
+ if (banner !== null) { banner.remove(); banner = null }
764
+ }
765
+ }
766
+
628
767
  function pad(n) {
629
768
  return String(n).padStart(2, '0')
630
769
  }
@@ -650,13 +789,31 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
650
789
  return new Date(date.getFullYear(), date.getMonth(), 1)
651
790
  }
652
791
 
792
+ const PERIODS = ['day', 'week', 'month', 'days30', 'days90', 'all']
793
+
794
+ function isSteppablePeriod(period) {
795
+ return period === 'day' || period === 'week' || period === 'month'
796
+ }
797
+
653
798
  function shiftAnchor(period, anchor, delta) {
654
799
  if (period === 'week') return addDays(startOfWeek(anchor), delta * 7)
655
800
  if (period === 'month') return new Date(anchor.getFullYear(), anchor.getMonth() + delta, 1)
656
801
  return addDays(startOfDay(anchor), delta)
657
802
  }
658
803
 
659
- function periodRange(period, anchor) {
804
+ function periodRange(period, anchor, now = new Date()) {
805
+ if (period === 'days30') {
806
+ const today = startOfDay(now)
807
+ return { start: addDays(today, -29), end: addDays(today, 1) }
808
+ }
809
+ if (period === 'days90') {
810
+ const today = startOfDay(now)
811
+ return { start: addDays(today, -89), end: addDays(today, 1) }
812
+ }
813
+ if (period === 'all') {
814
+ const today = startOfDay(now)
815
+ return { start: new Date(1), end: addDays(today, 1) }
816
+ }
660
817
  const start = period === 'week' ? startOfWeek(anchor) : period === 'month' ? startOfMonth(anchor) : startOfDay(anchor)
661
818
  let end
662
819
  if (period === 'week') end = addDays(start, 7)
@@ -673,59 +830,103 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
673
830
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}`
674
831
  }
675
832
 
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
833
+ function parseDateKey(value, now = new Date()) {
834
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(value || ''))
835
+ if (!match) return null
836
+ const year = Number(match[1])
837
+ const month = Number(match[2])
838
+ const day = Number(match[3])
839
+ if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31) return null
840
+ const date = new Date(year, month - 1, day)
841
+ if (
842
+ Number.isNaN(date.getTime()) ||
843
+ date.getFullYear() !== year ||
844
+ date.getMonth() !== month - 1 ||
845
+ date.getDate() !== day
846
+ ) {
847
+ return null
848
+ }
849
+ const today = startOfDay(now)
850
+ return date.getTime() > today.getTime() ? today : date
681
851
  }
682
852
 
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
853
+ function parseMonthKey(value, now = new Date()) {
854
+ const match = /^(\d{4})-(\d{2})$/.exec(String(value || ''))
855
+ if (!match) return null
856
+ const year = Number(match[1])
857
+ const month = Number(match[2])
858
+ if (year < 1970 || month < 1 || month > 12) return null
859
+ const date = new Date(year, month - 1, 1)
860
+ if (
861
+ Number.isNaN(date.getTime()) ||
862
+ date.getFullYear() !== year ||
863
+ date.getMonth() !== month - 1 ||
864
+ date.getDate() !== 1
865
+ ) {
866
+ return null
867
+ }
868
+ const today = startOfDay(now)
869
+ return date.getTime() > today.getTime() ? today : date
688
870
  }
689
871
 
690
- function periodKey(period, start) {
691
- return period === 'month' ? monthKey(start) : dateKey(start)
872
+ function periodKey(period, start, endExclusive) {
873
+ if (period === 'month') return monthKey(start)
874
+ if (period === 'days30' || period === 'days90' || period === 'all') {
875
+ return dateKey(addDays(endExclusive || addDays(startOfDay(new Date()), 1), -1))
876
+ }
877
+ return dateKey(start)
692
878
  }
693
879
 
694
880
  function fullDate(date, locale) {
695
- if (locale === 'zh' || locale === 'ja') return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
881
+ const lang = normalizeLocale(locale)
882
+ if (lang === 'zh' || lang === 'ja') return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
696
883
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
697
884
  }
698
885
 
699
886
  function shortDate(date, locale) {
700
- if (locale === 'zh' || locale === 'ja') return `${date.getMonth() + 1}月${date.getDate()}日`
887
+ const lang = normalizeLocale(locale)
888
+ if (lang === 'zh' || lang === 'ja') return `${date.getMonth() + 1}月${date.getDate()}日`
701
889
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }).toUpperCase()
702
890
  }
703
891
 
704
892
  function monthYear(date, locale) {
705
- if (locale === 'zh' || locale === 'ja') return `${date.getFullYear()}年${date.getMonth() + 1}月`
893
+ const lang = normalizeLocale(locale)
894
+ if (lang === 'zh' || lang === 'ja') return `${date.getFullYear()}年${date.getMonth() + 1}月`
706
895
  return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })
707
896
  }
708
897
 
709
898
  function periodLabel(period, start, endExclusive, locale) {
710
- if (period === 'day') return fullDate(start, locale)
711
- if (period === 'month') return monthYear(start, locale)
899
+ const lang = normalizeLocale(locale)
900
+ if (period === 'day') return fullDate(start, lang)
901
+ if (period === 'month') return monthYear(start, lang)
712
902
  const last = addDays(endExclusive, -1)
713
- if (locale === 'zh' || locale === 'ja') {
903
+ if (period === 'all') {
904
+ if (!start || start.getTime() <= DAY_MS) return (DICT[lang] || DICT.en).allTime
905
+ if (start.getTime() >= last.getTime()) return fullDate(last, lang)
906
+ }
907
+ if (lang === 'zh' || lang === 'ja') {
714
908
  const firstPart = `${start.getFullYear()}年${start.getMonth() + 1}月${start.getDate()}日`
715
909
  const secondYear = last.getFullYear() !== start.getFullYear() ? `${last.getFullYear()}年` : ''
716
910
  const secondPart = `${secondYear}${last.getMonth() + 1}月${last.getDate()}日`
717
- return locale === 'ja' ? `${firstPart}〜${secondPart}` : `${firstPart} – ${secondPart}`
911
+ return lang === 'ja' ? `${firstPart}〜${secondPart}` : `${firstPart} – ${secondPart}`
718
912
  }
719
- const first = start.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
913
+ const firstOpts =
914
+ start.getFullYear() !== last.getFullYear()
915
+ ? { month: 'short', day: 'numeric', year: 'numeric' }
916
+ : { month: 'short', day: 'numeric' }
917
+ const first = start.toLocaleDateString('en-US', firstOpts)
720
918
  const second = last.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
721
919
  return `${first} – ${second}`
722
920
  }
723
921
 
724
922
  function periodName(period, copy) {
725
- return period === 'week' ? copy.week : period === 'month' ? copy.month : copy.day
923
+ return Object.hasOwn(copy, period) && copy[period] ? copy[period] : copy.day
726
924
  }
727
925
 
728
926
  function relativeLabel(period, start, copy) {
927
+ if (period === 'days30') return copy.days30
928
+ if (period === 'days90') return copy.days90
929
+ if (period === 'all') return start && start.getTime() > DAY_MS ? copy.allTime : ''
729
930
  const now = new Date()
730
931
  if (period === 'day') {
731
932
  const diff = Math.round((startOfDay(now).getTime() - start.getTime()) / DAY_MS)
@@ -745,13 +946,26 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
745
946
  return ''
746
947
  }
747
948
 
949
+ function resolveDisplayStart(period, fallbackStart, data) {
950
+ if (period !== 'all') return fallbackStart
951
+ return typeof data?.firstAt === 'number' && Number.isFinite(data.firstAt) && data.firstAt > DAY_MS
952
+ ? startOfDay(new Date(data.firstAt))
953
+ : new Date(1)
954
+ }
955
+
748
956
  function currentPeriodStart(period) {
749
957
  return periodRange(period, new Date()).start
750
958
  }
751
959
 
960
+ const EXACT_FORMATTERS = {
961
+ zh: new Intl.NumberFormat('zh-CN'),
962
+ ja: new Intl.NumberFormat('ja-JP'),
963
+ en: new Intl.NumberFormat('en-US'),
964
+ }
965
+
752
966
  function fmtExact(value, locale) {
753
967
  const n = Number(value) || 0
754
- return new Intl.NumberFormat(locale === 'zh' ? 'zh-CN' : locale === 'ja' ? 'ja-JP' : 'en-US').format(n)
968
+ return EXACT_FORMATTERS[normalizeLocale(locale)].format(n)
755
969
  }
756
970
 
757
971
  function fmtCompact(value) {
@@ -772,7 +986,18 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
772
986
  }
773
987
 
774
988
  function billNumber(period, date, total, requests) {
775
- const code = period === 'week' ? 'W' : period === 'month' ? 'M' : 'D'
989
+ const code =
990
+ period === 'week'
991
+ ? 'W'
992
+ : period === 'month'
993
+ ? 'M'
994
+ : period === 'days30'
995
+ ? '30D'
996
+ : period === 'days90'
997
+ ? '90D'
998
+ : period === 'all'
999
+ ? 'ALL'
1000
+ : 'D'
776
1001
  return `TR-${code}-${String(date || '').replaceAll('-', '')}-${hashSuffix(`${period}:${date}:${total}:${requests}`)}`
777
1002
  }
778
1003
 
@@ -788,34 +1013,41 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
788
1013
  const JPY_RATE_DATE = '2026-11-13'
789
1014
 
790
1015
  function defaultCurrencyForLocale(locale) {
791
- const language = String(locale || 'en').toLowerCase().split(/[-_]/)[0]
792
- return language === 'zh' ? 'cny' : language === 'ja' ? 'jpy' : 'usd'
1016
+ const lang = normalizeLocale(locale)
1017
+ return lang === 'zh' ? 'cny' : lang === 'ja' ? 'jpy' : 'usd'
793
1018
  }
794
1019
 
795
1020
  function resolveCurrencyPreference(preference, locale) {
796
1021
  return Object.hasOwn(DISPLAY_RATES, preference) ? preference : defaultCurrencyForLocale(locale)
797
1022
  }
798
1023
 
1024
+ const MONEY_FORMATTERS = {
1025
+ standard: new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }),
1026
+ standardSmall: new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 6 }),
1027
+ jpy: new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 }),
1028
+ jpySmall: new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 6 }),
1029
+ }
1030
+
799
1031
  function fmtMoney(usd, currency = 'usd') {
800
1032
  if (typeof usd !== 'number' || !Number.isFinite(usd)) return '—'
801
1033
  const selected = Object.hasOwn(DISPLAY_RATES, currency) ? currency : 'usd'
802
1034
  const amount = usd * DISPLAY_RATES[selected]
803
1035
  const symbol = selected === 'usd' ? '$' : '¥'
804
1036
  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}`
1037
+ const isJpy = selected === 'jpy'
1038
+ const small = amount > 0 && amount < (isJpy ? 1 : .01)
1039
+ const formatter = isJpy
1040
+ ? small ? MONEY_FORMATTERS.jpySmall : MONEY_FORMATTERS.jpy
1041
+ : small ? MONEY_FORMATTERS.standardSmall : MONEY_FORMATTERS.standard
1042
+ return `${symbol}${formatter.format(amount)}`
809
1043
  }
810
1044
 
811
1045
  function groupModels(models) {
812
1046
  const grouped = new Map()
813
1047
  for (const model of models || []) {
814
1048
  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 }
1049
+ const existing = grouped.get(name) || { model: name, total: 0, requests: 0, costUsd: null, complete: true }
816
1050
  existing.total += Number(model.total) || 0
817
- existing.input += Number(model.input) || 0
818
- existing.output += Number(model.output) || 0
819
1051
  existing.requests += Number(model.requests) || 0
820
1052
  // Host prices each provider independently before these display rows merge.
821
1053
  const cost = model.pricing && model.pricing.totalUsd
@@ -832,7 +1064,8 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
832
1064
 
833
1065
  function Receipt(props) {
834
1066
  const { copy, locale, data, period, paperRef, currency: selectedCurrency = 'auto' } = props
835
- const currency = resolveCurrencyPreference(selectedCurrency, locale)
1067
+ const lang = normalizeLocale(locale)
1068
+ const currency = resolveCurrencyPreference(selectedCurrency, lang)
836
1069
  const totals = data.totals
837
1070
  const pricing = data.pricing
838
1071
  const breakdown = pricing?.breakdown
@@ -849,7 +1082,9 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
849
1082
  }
850
1083
  const rangeStart = new Date(data.from)
851
1084
  const rangeEnd = new Date(data.to)
1085
+ const displayStart = resolveDisplayStart(period, rangeStart, data)
852
1086
  const issued = new Date(data.generatedAt)
1087
+ const issuedText = Number.isNaN(issued.getTime()) ? '—' : `${pad(issued.getHours())}:${pad(issued.getMinutes())}`
853
1088
  const billNo = billNumber(period, data.date, totals.totalTokens, totals.requests)
854
1089
  const partial = pricing?.status === 'partial'
855
1090
  const hasPrice = typeof pricing?.totalUsd === 'number' && Number.isFinite(pricing.totalUsd)
@@ -869,17 +1104,17 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
869
1104
  h('span', { className: 'tr-item-value', title: model.costUsd === null ? copy.unpriced : undefined },
870
1105
  model.costUsd === null ? '—' : `${model.complete ? '' : '≈'}${fmtMoney(model.costUsd, currency)}`),
871
1106
  ),
872
- h('p', { className: 'tr-item-detail' }, `${fmtExact(model.total, locale)} tokens · ${fmtExact(model.requests, locale)} ${copy.requests}`),
1107
+ h('p', { className: 'tr-item-detail' }, `${fmtExact(model.total, lang)} tokens · ${fmtExact(model.requests, lang)} ${copy.requests.toLowerCase()}`),
873
1108
  )
874
1109
  return h(
875
1110
  'article',
876
- { className: 'tr-paper', lang: locale, 'data-currency': currency, 'aria-label': copy.receiptLabel, ref: paperRef },
1111
+ { className: 'tr-paper', lang, 'data-currency': currency, 'aria-label': copy.receiptLabel, ref: paperRef },
877
1112
  h(
878
1113
  'div',
879
1114
  { className: 'tr-paper-head' },
880
1115
  h('span', { className: 'tr-paper-logo' }, h(WhaleGlyph, { size: 40 })),
881
1116
  h('p', { className: 'tr-paper-kicker' }, 'TOKEN RECEIPT'),
882
- h('p', { className: 'tr-paper-date' }, periodLabel(period, rangeStart, rangeEnd, locale)),
1117
+ h('p', { className: 'tr-paper-date' }, periodLabel(period, displayStart, rangeEnd, lang)),
883
1118
  ),
884
1119
  h('div', { className: 'tr-rule' }),
885
1120
  h('p', { className: 'tr-section-label' }, copy.model),
@@ -900,12 +1135,12 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
900
1135
  h(
901
1136
  'dl',
902
1137
  { 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,
1138
+ h('dt', null, copy.totalTokens), h('dd', null, fmtExact(totals.totalTokens, lang)),
1139
+ h('dt', null, `${copy.requests} / ${copy.sessions}`), h('dd', null, `${fmtExact(totals.requests, lang)} / ${fmtExact(totals.sessions, lang)}`),
1140
+ totals.reasoningTokens > 0 ? h(React.Fragment, null, h('dt', null, copy.reasoning), h('dd', null, fmtExact(totals.reasoningTokens, lang))) : null,
906
1141
  h('dt', null, copy.billNo), h('dd', null, billNo),
907
1142
  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())}`),
1143
+ h('dt', null, copy.generated), h('dd', null, issuedText),
909
1144
  h('dt', null, copy.currency), h('dd', null, currency.toUpperCase()),
910
1145
  ),
911
1146
  notes.length > 0 ? h('div', { className: 'tr-price-notes' }, notes.map((note) => h('p', { key: note }, note))) : null,
@@ -978,59 +1213,103 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
978
1213
  })
979
1214
  }
980
1215
 
981
- async function exportReceiptPng(paperEl, billNo) {
982
- if (!paperEl) throw new Error('Receipt is not ready')
1216
+ function collectWrappedLines(textNode, lineHeight) {
1217
+ const range = document.createRange()
1218
+ const lines = []
1219
+ const raw = textNode.nodeValue || ''
1220
+ for (let offset = 0; offset < raw.length; ) {
1221
+ const codePoint = raw.codePointAt(offset)
1222
+ const step = codePoint > 0xffff ? 2 : 1
1223
+ range.setStart(textNode, offset)
1224
+ range.setEnd(textNode, offset + step)
1225
+ const charRect = range.getBoundingClientRect()
1226
+ const glyph = raw.slice(offset, offset + step)
1227
+ offset += step
1228
+ if (charRect.width === 0) continue
1229
+ const charTop = charRect.top
1230
+ const charBottom = typeof charRect.bottom === 'number' ? charRect.bottom : charTop + charRect.height
1231
+ const charMid = (charTop + charBottom) / 2
1232
+ let line = lines[lines.length - 1]
1233
+ if (!line || Math.abs(line.mid - charMid) > lineHeight * 0.5) {
1234
+ line = { text: '', top: charTop, bottom: charBottom, mid: charMid }
1235
+ lines.push(line)
1236
+ } else {
1237
+ line.top = Math.min(line.top, charTop)
1238
+ line.bottom = Math.max(line.bottom, charBottom)
1239
+ line.mid = (line.top + line.bottom) / 2
1240
+ }
1241
+ line.text += glyph
1242
+ }
1243
+ return lines
1244
+ }
1245
+
1246
+ function errorMessage(error) {
1247
+ if (error instanceof Error) return error.message
1248
+ if (error && typeof error.message === 'string') return error.message
1249
+ return String(error)
1250
+ }
1251
+
1252
+ async function renderReceiptPngBlob(paperEl, copy) {
1253
+ const errCopy = copy || DICT.en
1254
+ if (!paperEl) throw new Error(errCopy.exportNotReady)
983
1255
  const exportCurrency = paperEl.dataset.currency
984
1256
  const exportLanguage = paperEl.lang
985
1257
  const assertReceiptUnchanged = () => {
986
- if (!paperEl.isConnected) throw new Error('Receipt was closed before export completed')
1258
+ if (!paperEl.isConnected) throw new Error(errCopy.exportClosed)
987
1259
  if (paperEl.dataset.currency !== exportCurrency || paperEl.lang !== exportLanguage) {
988
- throw new Error('Receipt language or currency changed while saving. Please retry.')
1260
+ throw new Error(errCopy.exportChanged)
989
1261
  }
990
1262
  }
991
1263
  await document.fonts.ready
992
1264
  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))
1265
+
1266
+ let texture = null
1267
+ try {
1268
+ texture = await loadImage(`data:image/svg+xml;base64,${PAPER_TEXTURE}`)
1269
+ } catch {
1270
+ /* texture is decorative */
1271
+ }
1272
+ assertReceiptUnchanged()
1273
+
1274
+ const paperRect = paperEl.getBoundingClientRect()
1275
+ const originX = paperRect.left
1276
+ const originY = paperRect.top
1277
+ const width = Math.max(1, Math.round(paperRect.width))
1278
+ const height = Math.max(1, Math.round(paperRect.height))
996
1279
  const canvas = document.createElement('canvas')
997
1280
  canvas.width = width * EXPORT_SCALE
998
1281
  canvas.height = height * EXPORT_SCALE
999
1282
  const ctx = canvas.getContext('2d')
1283
+ if (!ctx) throw new Error(errCopy.exportFailed)
1000
1284
  ctx.scale(EXPORT_SCALE, EXPORT_SCALE)
1285
+
1001
1286
  ctx.save()
1002
1287
  paperClipPath(ctx, width, height)
1003
1288
  ctx.clip()
1004
1289
  const paperStyle = getComputedStyle(paperEl)
1005
1290
  ctx.fillStyle = paperStyle.backgroundColor || '#fcfcfc'
1006
1291
  ctx.fillRect(0, 0, width, height)
1007
- try {
1008
- const texture = await loadImage(`data:image/svg+xml;base64,${PAPER_TEXTURE}`)
1292
+ if (texture) {
1009
1293
  ctx.save()
1010
1294
  ctx.globalCompositeOperation = 'soft-light'
1011
1295
  ctx.drawImage(texture, 0, 0, width, height)
1012
1296
  ctx.restore()
1013
- } catch {
1014
- /* texture is decorative */
1015
1297
  }
1016
1298
  ctx.restore()
1017
1299
 
1018
- assertReceiptUnchanged()
1019
- const paperRect = paperEl.getBoundingClientRect()
1020
- const originX = paperRect.left
1021
- const originY = paperRect.top
1022
-
1023
1300
  const logo = paperEl.querySelector('.tr-paper-logo')
1024
- if (logo) {
1301
+ if (logo && typeof Path2D === 'function') {
1025
1302
  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 */
1303
+ if (logoRect.width > 0 && logoRect.height > 0) {
1304
+ const logoStyle = getComputedStyle(logo)
1305
+ const alpha = parseFloat(logoStyle.opacity)
1306
+ ctx.save()
1307
+ ctx.translate(logoRect.left - originX, logoRect.top - originY)
1308
+ ctx.scale(logoRect.width / 50, logoRect.height / 50)
1309
+ ctx.fillStyle = logoStyle.color
1310
+ ctx.globalAlpha = Number.isFinite(alpha) ? alpha : 1
1311
+ ctx.fill(new Path2D(WHALE_PATH))
1312
+ ctx.restore()
1034
1313
  }
1035
1314
  }
1036
1315
 
@@ -1052,38 +1331,23 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1052
1331
  if (barcode) {
1053
1332
  const barcodeRect = barcode.getBoundingClientRect()
1054
1333
  const barcodeStyle = getComputedStyle(barcode)
1334
+ const alpha = parseFloat(barcodeStyle.opacity)
1055
1335
  ctx.save()
1056
1336
  ctx.fillStyle = barcodeStyle.color
1337
+ ctx.globalAlpha = Number.isFinite(alpha) ? alpha : 1
1057
1338
  const pattern = [1, 2, 2, 2, 1, 3]
1339
+ const rightEdge = barcodeRect.right - originX
1058
1340
  let x = barcodeRect.left - originX
1059
1341
  let index = 0
1060
- while (x < barcodeRect.right - originX) {
1342
+ while (x < rightEdge) {
1061
1343
  const segment = pattern[index % pattern.length]
1062
- if (index % 2 === 0) ctx.fillRect(x, barcodeRect.top - originY, segment, barcodeRect.height)
1344
+ if (index % 2 === 0) ctx.fillRect(x, barcodeRect.top - originY, Math.min(segment, rightEdge - x), barcodeRect.height)
1063
1345
  x += segment
1064
1346
  index += 1
1065
1347
  }
1066
1348
  ctx.restore()
1067
1349
  }
1068
1350
 
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
1351
  const walker = document.createTreeWalker(paperEl, NodeFilter.SHOW_TEXT)
1088
1352
  let node = walker.nextNode()
1089
1353
  while (node) {
@@ -1093,7 +1357,8 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1093
1357
  node = walker.nextNode()
1094
1358
  if (!text || !element || element.closest('svg') || element.closest('style')) continue
1095
1359
  const style = getComputedStyle(element)
1096
- if (style.display === 'none' || Number(style.opacity) === 0) continue
1360
+ const textAlpha = parseFloat(style.opacity)
1361
+ if (style.display === 'none' || textAlpha === 0) continue
1097
1362
  const bounds = element.getBoundingClientRect()
1098
1363
  if (bounds.width === 0 || bounds.height === 0) continue
1099
1364
  const value = style.textTransform === 'uppercase' ? text.toUpperCase() : text
@@ -1103,7 +1368,7 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1103
1368
  ctx.save()
1104
1369
  ctx.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`
1105
1370
  ctx.fillStyle = style.color
1106
- ctx.globalAlpha = Number(style.opacity) || 1
1371
+ ctx.globalAlpha = Number.isFinite(textAlpha) ? textAlpha : 1
1107
1372
  ctx.textAlign = align
1108
1373
  ctx.textBaseline = 'middle'
1109
1374
  if ('letterSpacing' in ctx) ctx.letterSpacing = style.letterSpacing === 'normal' ? '0px' : style.letterSpacing
@@ -1114,25 +1379,13 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1114
1379
  }
1115
1380
  const lineHeight = parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.2
1116
1381
  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
- }
1382
+ // Group wrapped runs by vertical midpoint so mixed CJK + ASCII fonts stay on one line.
1383
+ const lines = collectWrappedLines(textNode, lineHeight)
1133
1384
  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)
1385
+ const rawLine = line.text.replace(/\s+/g, ' ').trim()
1386
+ if (!rawLine) continue
1387
+ const lineText = style.textTransform === 'uppercase' ? rawLine.toUpperCase() : rawLine
1388
+ ctx.fillText(lineText, x, (line.top + line.bottom) / 2 - originY)
1136
1389
  }
1137
1390
  } else {
1138
1391
  ctx.fillText(printable, x, y)
@@ -1140,96 +1393,203 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1140
1393
  ctx.restore()
1141
1394
  }
1142
1395
 
1143
- const blob = await new Promise((resolve, reject) => canvas.toBlob((value) => (value ? resolve(value) : reject(new Error('Canvas export failed'))), 'image/png'))
1396
+ const blob = await new Promise((resolve, reject) =>
1397
+ canvas.toBlob((value) => (value ? resolve(value) : reject(new Error(errCopy.exportFailed))), 'image/png'),
1398
+ )
1399
+ assertReceiptUnchanged()
1400
+ return blob
1401
+ }
1402
+
1403
+ async function exportReceiptPng(paperEl, billNo, copy) {
1404
+ const blob = await renderReceiptPngBlob(paperEl, copy)
1144
1405
  downloadBlob(blob, `token-receipt-${billNo || 'bill'}.png`)
1145
1406
  }
1146
1407
 
1408
+ async function copyReceiptPng(paperEl, copy) {
1409
+ const errCopy = copy || DICT.en
1410
+ if (!paperEl) throw new Error(errCopy.exportNotReady)
1411
+ const nav = typeof navigator !== 'undefined' ? navigator : typeof window !== 'undefined' ? window.navigator : undefined
1412
+ const ClipboardItemCtor =
1413
+ typeof ClipboardItem === 'function'
1414
+ ? ClipboardItem
1415
+ : typeof window !== 'undefined' && typeof window.ClipboardItem === 'function'
1416
+ ? window.ClipboardItem
1417
+ : null
1418
+ if (!nav || !nav.clipboard || typeof nav.clipboard.write !== 'function' || !ClipboardItemCtor) {
1419
+ throw new Error(errCopy.clipboardUnsupported)
1420
+ }
1421
+ const blobPromise = renderReceiptPngBlob(paperEl, errCopy)
1422
+ // Attach a no-op rejection handler so synchronous ClipboardItem failures do not leak unhandled rejections.
1423
+ blobPromise.catch(() => {})
1424
+ let item = null
1425
+ try {
1426
+ item = new ClipboardItemCtor({ 'image/png': blobPromise })
1427
+ } catch {
1428
+ item = null
1429
+ }
1430
+ if (item) {
1431
+ try {
1432
+ await nav.clipboard.write([item])
1433
+ return
1434
+ } catch (err) {
1435
+ const blob = await blobPromise
1436
+ if (!(err instanceof TypeError) && err?.name !== 'TypeError') throw err
1437
+ await nav.clipboard.write([new ClipboardItemCtor({ 'image/png': blob })])
1438
+ return
1439
+ }
1440
+ }
1441
+ const blob = await blobPromise
1442
+ await nav.clipboard.write([new ClipboardItemCtor({ 'image/png': blob })])
1443
+ }
1444
+
1147
1445
  function Panel(props) {
1148
1446
  const ctx = props.ctx
1149
1447
  const locale = useLocale(ctx)
1150
- const copy = React.useMemo(() => translatedCopy(ctx), [locale])
1448
+ const copy = React.useMemo(() => translatedCopy(ctx, locale), [ctx, locale])
1151
1449
  const [period, setPeriod] = React.useState('day')
1152
1450
  const [currencyPreference, setCurrencyPreference] = React.useState('auto')
1153
1451
  const currency = resolveCurrencyPreference(currencyPreference, locale)
1154
1452
  const [anchor, setAnchor] = React.useState(() => startOfDay(new Date()))
1155
1453
  const [stage, setStage] = React.useState('processing')
1454
+ const [printRunId, setPrintRunId] = React.useState(0)
1156
1455
  const [data, setData] = React.useState(null)
1157
1456
  const [error, setError] = React.useState(null)
1158
1457
  const [saveState, setSaveState] = React.useState('idle')
1159
1458
  const [saveMessage, setSaveMessage] = React.useState('')
1459
+ const [copyState, setCopyState] = React.useState('idle')
1460
+ const [copyMessage, setCopyMessage] = React.useState('')
1461
+ const mountedRef = React.useRef(true)
1160
1462
  const abortRef = React.useRef(null)
1161
1463
  const timerRef = React.useRef(null)
1162
1464
  const saveTimerRef = React.useRef(null)
1163
- const firstRunRef = React.useRef(true)
1465
+ const copyTimerRef = React.useRef(null)
1164
1466
  const paperRef = React.useRef(null)
1165
1467
  const savingRef = React.useRef(false)
1166
1468
  const range = React.useMemo(() => periodRange(period, anchor), [period, anchor])
1167
1469
  const currentStart = currentPeriodStart(period)
1168
1470
  const nextDisabled = range.start.getTime() >= currentStart.getTime()
1169
- const rel = relativeLabel(period, range.start, copy)
1471
+ const displayStart = resolveDisplayStart(period, range.start, data)
1472
+ const rel = relativeLabel(period, displayStart, copy)
1473
+
1474
+ const clearExportTimers = () => {
1475
+ if (saveTimerRef.current) {
1476
+ clearTimeout(saveTimerRef.current)
1477
+ saveTimerRef.current = null
1478
+ }
1479
+ if (copyTimerRef.current) {
1480
+ clearTimeout(copyTimerRef.current)
1481
+ copyTimerRef.current = null
1482
+ }
1483
+ }
1170
1484
 
1171
- const runPrint = React.useCallback(async (animate = true) => {
1485
+ React.useEffect(() => {
1486
+ mountedRef.current = true
1487
+ return () => {
1488
+ mountedRef.current = false
1489
+ clearExportTimers()
1490
+ }
1491
+ }, [])
1492
+
1493
+ const updateAnchor = React.useCallback((nextOrUpdater) => {
1494
+ setAnchor((prev) => {
1495
+ const candidate = typeof nextOrUpdater === 'function' ? nextOrUpdater(prev) : nextOrUpdater
1496
+ const today = startOfDay(new Date())
1497
+ const clamped = candidate.getTime() > today.getTime() ? today : candidate
1498
+ return prev.getTime() === clamped.getTime() ? prev : clamped
1499
+ })
1500
+ }, [])
1501
+
1502
+ const runPrint = React.useCallback(async (animate = true, refresh = false) => {
1172
1503
  if (savingRef.current) return
1173
1504
  if (abortRef.current) abortRef.current.abort()
1174
1505
  if (timerRef.current) {
1175
1506
  clearTimeout(timerRef.current)
1176
1507
  timerRef.current = null
1177
1508
  }
1509
+ clearExportTimers()
1178
1510
  const controller = new AbortController()
1179
1511
  abortRef.current = controller
1512
+ const isStale = () => !mountedRef.current || controller.signal.aborted || abortRef.current !== controller
1513
+ const reduced = prefersReducedMotion()
1514
+ const shouldAnimate = Boolean(animate) && !reduced
1180
1515
  const startedAt = Date.now()
1181
1516
  setStage('processing')
1182
1517
  setError(null)
1183
1518
  setData(null)
1184
1519
  setSaveState('idle')
1185
1520
  setSaveMessage('')
1521
+ setCopyState('idle')
1522
+ setCopyMessage('')
1186
1523
  const from = range.start.getTime()
1187
1524
  const to = range.end.getTime()
1188
- const key = periodKey(period, range.start)
1525
+ const key = periodKey(period, range.start, range.end)
1526
+ const url =
1527
+ `/api/token-receipt?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&date=${encodeURIComponent(key)}&period=${encodeURIComponent(period)}` +
1528
+ (refresh ? '&refresh=1' : '')
1189
1529
  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
- )
1530
+ const response = await fetch(url, { signal: controller.signal, headers: { accept: 'application/json' } })
1531
+ if (isStale()) return
1194
1532
  const payload = await response.json().catch(() => null)
1533
+ if (isStale()) return
1195
1534
  if (!response.ok || !payload || payload.ok !== true) {
1196
1535
  throw new Error((payload && payload.error) || `HTTP ${response.status}`)
1197
1536
  }
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))
1537
+ const remaining = shouldAnimate ? MIN_PROCESSING_MS - (Date.now() - startedAt) : 0
1538
+ if (remaining > 0) {
1539
+ await waitWithAbort(remaining, controller.signal)
1201
1540
  }
1202
- if (controller.signal.aborted) return
1541
+ if (isStale()) return
1203
1542
  setData(payload)
1204
- if (!animate || REDUCED) {
1543
+ if (!shouldAnimate) {
1205
1544
  setStage('complete')
1206
1545
  } else {
1546
+ setPrintRunId((n) => n + 1)
1207
1547
  setStage('printing')
1208
- timerRef.current = setTimeout(() => setStage('complete'), 1900)
1548
+ timerRef.current = setTimeout(() => {
1549
+ timerRef.current = null
1550
+ if (!isStale()) setStage('complete')
1551
+ }, 1900)
1209
1552
  }
1210
1553
  } catch (fetchError) {
1211
- if (fetchError && fetchError.name === 'AbortError') return
1212
- setError(fetchError instanceof Error ? fetchError.message : String(fetchError))
1554
+ if (isStale()) return
1555
+ setError(errorMessage(fetchError))
1213
1556
  setStage('error')
1214
1557
  }
1215
1558
  }, [period, range])
1216
1559
 
1217
1560
  React.useEffect(() => {
1218
- const animate = firstRunRef.current
1219
- firstRunRef.current = false
1220
- runPrint(animate)
1561
+ runPrint(true)
1221
1562
  return () => {
1222
1563
  if (abortRef.current) abortRef.current.abort()
1223
- if (timerRef.current) clearTimeout(timerRef.current)
1224
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
1564
+ if (timerRef.current) {
1565
+ clearTimeout(timerRef.current)
1566
+ timerRef.current = null
1567
+ }
1225
1568
  }
1226
1569
  }, [runPrint])
1227
1570
 
1228
1571
  const busy = stage === 'processing' || stage === 'printing'
1229
- const locked = busy || saveState === 'saving'
1572
+ const locked = saveState === 'saving' || copyState === 'copying'
1573
+ const actionLocked = busy || locked
1574
+ const reduced = prefersReducedMotion()
1230
1575
  const primaryLabel = busy ? copy.printingButton : stage === 'complete' ? copy.again : copy.print
1576
+ const copyLabel = copyState === 'copying' ? copy.copyingImage : copyState === 'copied' ? copy.copiedImage : copyState === 'error' ? copy.copyFailed : copy.copyImage
1231
1577
  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)
1578
+ const actionStatusText =
1579
+ copyState === 'copying'
1580
+ ? copy.copyingImage
1581
+ : copyState === 'copied'
1582
+ ? copy.copiedImage
1583
+ : copyState === 'error'
1584
+ ? `${copy.copyFailed}: ${copyMessage}`
1585
+ : saveState === 'saving'
1586
+ ? copy.savingPng
1587
+ : saveState === 'saved'
1588
+ ? copy.savedPng
1589
+ : saveState === 'error'
1590
+ ? `${copy.saveFailed}: ${saveMessage}`
1591
+ : ''
1592
+ const dateText = periodLabel(period, displayStart, range.end, locale)
1233
1593
  const screenSub = period === 'day' ? `${rel ? `${rel} · ` : ''}${shortDate(range.start, locale)}` : dateText
1234
1594
  const inputType = period === 'month' ? 'month' : 'date'
1235
1595
  const inputValue = period === 'month' ? monthKey(anchor) : dateKey(anchor)
@@ -1239,31 +1599,94 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1239
1599
  if (savingRef.current || next === period) return
1240
1600
  setPeriod(next)
1241
1601
  }
1602
+ const handleToday = () => {
1603
+ if (savingRef.current) return
1604
+ setPeriod('day')
1605
+ updateAnchor(startOfDay(new Date()))
1606
+ }
1607
+ const handleDateInputClick = (event) => {
1608
+ if (locked || savingRef.current || event.currentTarget.disabled) return
1609
+ try {
1610
+ event.currentTarget.showPicker?.()
1611
+ } catch {
1612
+ /* showPicker may throw if unsupported or already open */
1613
+ }
1614
+ }
1242
1615
  const handlePickDate = (event) => {
1243
1616
  if (savingRef.current) return
1244
1617
  const value = event.target.value
1245
1618
  if (!value) return
1246
1619
  const parsed = period === 'month' ? parseMonthKey(value) : parseDateKey(value)
1247
- if (parsed) setAnchor(period === 'month' ? startOfMonth(parsed) : startOfDay(parsed))
1620
+ if (parsed) updateAnchor(period === 'month' ? startOfMonth(parsed) : startOfDay(parsed))
1248
1621
  }
1249
- const handleSave = async () => {
1622
+ const runPaperAction = async ({
1623
+ action,
1624
+ logLabel,
1625
+ pendingState,
1626
+ doneState,
1627
+ setState,
1628
+ setMessage,
1629
+ clearOtherState,
1630
+ clearOtherMessage,
1631
+ actionTimerRef,
1632
+ }) => {
1250
1633
  if (!data || !paperRef.current || savingRef.current || busy) return
1251
1634
  savingRef.current = true
1252
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
1253
- setSaveState('saving')
1254
- setSaveMessage('')
1635
+ clearExportTimers()
1636
+ clearOtherState('idle')
1637
+ clearOtherMessage('')
1638
+ setState(pendingState)
1639
+ setMessage('')
1255
1640
  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))
1641
+ await action(paperRef.current)
1642
+ if (!mountedRef.current) return
1643
+ setState(doneState)
1644
+ actionTimerRef.current = setTimeout(() => {
1645
+ actionTimerRef.current = null
1646
+ if (mountedRef.current) setState('idle')
1647
+ }, 3200)
1648
+ } catch (actionError) {
1649
+ if (!mountedRef.current) return
1650
+ console.error(logLabel, actionError)
1651
+ setState('error')
1652
+ setMessage(errorMessage(actionError))
1263
1653
  } finally {
1264
1654
  savingRef.current = false
1265
1655
  }
1266
1656
  }
1657
+ const handleCopy = () =>
1658
+ runPaperAction({
1659
+ action: (paperEl) => copyReceiptPng(paperEl, copy),
1660
+ logLabel: '[token-receipt] PNG copy failed',
1661
+ pendingState: 'copying',
1662
+ doneState: 'copied',
1663
+ setState: setCopyState,
1664
+ setMessage: setCopyMessage,
1665
+ clearOtherState: setSaveState,
1666
+ clearOtherMessage: setSaveMessage,
1667
+ actionTimerRef: copyTimerRef,
1668
+ })
1669
+ const handleSave = () =>
1670
+ runPaperAction({
1671
+ action: (paperEl) =>
1672
+ exportReceiptPng(
1673
+ paperEl,
1674
+ billNumber(period, data.date, data.totals.totalTokens, data.totals.requests),
1675
+ copy,
1676
+ ),
1677
+ logLabel: '[token-receipt] PNG export failed',
1678
+ pendingState: 'saving',
1679
+ doneState: 'saved',
1680
+ setState: setSaveState,
1681
+ setMessage: setSaveMessage,
1682
+ clearOtherState: setCopyState,
1683
+ clearOtherMessage: setCopyMessage,
1684
+ actionTimerRef: saveTimerRef,
1685
+ })
1686
+
1687
+ const exportErrorTitle = copyState === 'error' ? copy.copyFailed : saveState === 'error' ? copy.saveFailed : ''
1688
+ const exportErrorMessage = copyState === 'error' ? copyMessage : saveState === 'error' ? saveMessage : ''
1689
+ const exportRetryHandler = copyState === 'error' ? handleCopy : handleSave
1267
1690
 
1268
1691
  return h(
1269
1692
  'div',
@@ -1279,22 +1702,22 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1279
1702
  h(
1280
1703
  'div',
1281
1704
  { 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}` : ''),
1705
+ h('span', { className: 'tr-sr-only', role: 'status', 'aria-live': 'polite' }, actionStatusText),
1283
1706
  h(
1284
1707
  'button',
1285
- { className: 'tr-btn', type: 'button', disabled: !data || locked, onClick: () => window.print() },
1286
- h(PrinterGlyph, { size: 14 }),
1287
- copy.printPaper,
1708
+ { className: 'tr-btn', type: 'button', disabled: !data || actionLocked, onClick: handleCopy },
1709
+ copyState === 'copied' ? h(CheckCircle) : h(CopyIcon),
1710
+ copyLabel,
1288
1711
  ),
1289
1712
  h(
1290
1713
  'button',
1291
- { className: 'tr-btn', type: 'button', disabled: !data || locked, onClick: handleSave },
1714
+ { className: 'tr-btn', type: 'button', disabled: !data || actionLocked, onClick: handleSave },
1292
1715
  saveState === 'saved' ? h(CheckCircle) : h(DownloadIcon),
1293
1716
  saveLabel,
1294
1717
  ),
1295
1718
  h(
1296
1719
  'button',
1297
- { className: 'tr-btn tr-btn-primary', type: 'button', disabled: locked, onClick: () => runPrint(true) },
1720
+ { className: 'tr-btn tr-btn-primary', type: 'button', disabled: actionLocked, onClick: () => runPrint(true) },
1298
1721
  stage === 'complete' ? h(ReplayIcon) : h(PrinterGlyph, { size: 15 }),
1299
1722
  primaryLabel,
1300
1723
  ),
@@ -1309,44 +1732,59 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1309
1732
  h(
1310
1733
  'div',
1311
1734
  { className: 'tr-periods', role: 'group', 'aria-label': copy.period },
1312
- ['day', 'week', 'month'].map((value) =>
1735
+ PERIODS.map((value) =>
1313
1736
  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
1737
  ),
1315
1738
  ),
1316
1739
  h('label', { className: 'tr-currency' }, copy.currency,
1317
- h('select', { value: currencyPreference, disabled: locked, 'aria-label': copy.currency, onChange: (event) => setCurrencyPreference(event.target.value) },
1740
+ h('select', { value: currencyPreference, disabled: locked, 'aria-label': copy.currency, onChange: (event) => { if (!savingRef.current) setCurrencyPreference(event.target.value) } },
1318
1741
  h('option', { value: 'auto' }, `${copy.autoCurrency} (${defaultCurrencyForLocale(locale).toUpperCase()})`),
1319
1742
  h('option', { value: 'usd' }, 'USD'), h('option', { value: 'cny' }, 'CNY'), h('option', { value: 'jpy' }, 'JPY'))),
1320
1743
  ),
1321
1744
  h(
1322
1745
  'div',
1323
1746
  { 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,
1747
+ isSteppablePeriod(period)
1748
+ ? h(
1749
+ React.Fragment,
1750
+ null,
1751
+ h(
1752
+ 'div',
1753
+ { className: 'tr-datenav' },
1754
+ 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' })),
1755
+ h(
1756
+ 'label',
1757
+ { className: 'tr-datebox', title: copy.pickDate },
1758
+ h('span', { className: 'tr-datemain' }, dateText),
1759
+ rel ? h('span', { className: 'tr-daterel' }, rel) : null,
1760
+ h('span', { className: 'tr-dateicon', 'aria-hidden': true }, h(CalendarIcon)),
1761
+ h('input', { className: 'tr-datepicker', disabled: locked, type: inputType, value: inputValue, max: inputMax, 'aria-label': copy.pickDate, onClick: handleDateInputClick, onChange: handlePickDate }),
1762
+ ),
1763
+ 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' })),
1764
+ ),
1765
+ rel !== copy.today && rel !== copy.thisWeek && rel !== copy.thisMonth
1766
+ ? h('button', { className: 'tr-btn tr-todaybtn', type: 'button', disabled: locked, onClick: handleToday }, copy.backToday)
1767
+ : null,
1768
+ )
1769
+ : h(
1770
+ 'div',
1771
+ { className: 'tr-datenav' },
1772
+ h(
1773
+ 'div',
1774
+ { className: 'tr-datebox is-static' },
1775
+ h('span', { className: 'tr-datemain' }, dateText),
1776
+ rel ? h('span', { className: 'tr-daterel' }, rel) : null,
1777
+ ),
1778
+ ),
1341
1779
  ),
1342
1780
  ),
1343
- saveState === 'error'
1781
+ copyState === 'error' || saveState === 'error'
1344
1782
  ? h(
1345
1783
  'div',
1346
1784
  { 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),
1785
+ h('strong', null, exportErrorTitle),
1786
+ h('span', null, exportErrorMessage),
1787
+ h('button', { className: 'tr-btn', type: 'button', disabled: !data || actionLocked, onClick: exportRetryHandler }, copy.retry),
1350
1788
  )
1351
1789
  : null,
1352
1790
  h(
@@ -1362,7 +1800,7 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1362
1800
  'div',
1363
1801
  { className: 'tr-machine-head' },
1364
1802
  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)),
1803
+ h('button', { className: 'tr-machine-btn', type: 'button', disabled: locked, onClick: handleToday }, h('span', null, h(HomeIcon), copy.today)),
1366
1804
  ),
1367
1805
  h(
1368
1806
  'div',
@@ -1388,14 +1826,14 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1388
1826
  { className: 'tr-error', role: 'alert' },
1389
1827
  h('strong', null, copy.fetchError),
1390
1828
  h('span', null, error),
1391
- h('div', null, h('button', { className: 'tr-btn', type: 'button', onClick: () => runPrint(true) }, copy.retry)),
1829
+ h('div', null, h('button', { className: 'tr-btn', type: 'button', disabled: actionLocked, onClick: () => runPrint(true) }, copy.retry)),
1392
1830
  )
1393
1831
  : h(
1394
1832
  'div',
1395
1833
  { className: 'tr-output' },
1396
1834
  h(
1397
1835
  'div',
1398
- { className: `tr-paper-wrap${REDUCED ? ' is-reduced' : ''}`, 'data-stage': stage === 'processing' ? 'processing' : stage, 'aria-hidden': stage !== 'complete' },
1836
+ { key: printRunId, className: `tr-paper-wrap${reduced ? ' is-reduced' : ''}`, 'data-stage': stage === 'processing' ? 'processing' : stage, 'aria-hidden': stage !== 'complete' },
1399
1837
  data ? h(Receipt, { copy, locale, data, period, paperRef, currency }) : null,
1400
1838
  ),
1401
1839
  ),
@@ -1403,7 +1841,7 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1403
1841
  data && (data.pricing?.status !== 'complete' || data.pricing?.stale)
1404
1842
  ? h('div', { className: 'tr-price-feedback', role: 'status' },
1405
1843
  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))
1844
+ h('button', { className: 'tr-btn', type: 'button', disabled: actionLocked, onClick: () => runPrint(false, true) }, copy.priceRetry))
1407
1845
  : null,
1408
1846
  h('div', { className: 'tr-foot' }, h('i', null), copy.dataNote),
1409
1847
  ),
@@ -1412,14 +1850,27 @@ body[data-ds-dark-theme] .tr-slot { border-color: var(--tr-g1); background: var(
1412
1850
  }
1413
1851
 
1414
1852
  function apply(ctx) {
1853
+ ctx.effect(() => installUpdateGuard(ctx), 'token-receipt: update guard')
1854
+ ctx.effect(() => {
1855
+ if (typeof document === 'undefined' || !document.head || typeof document.createElement !== 'function') return
1856
+ const existing = typeof document.getElementById === 'function' ? document.getElementById('dsh-token-receipt-fonts') : null
1857
+ if (existing) return
1858
+ const styleEl = document.createElement('style')
1859
+ styleEl.id = 'dsh-token-receipt-fonts'
1860
+ styleEl.textContent = FONT_CSS
1861
+ document.head.appendChild(styleEl)
1862
+ return () => {
1863
+ styleEl.remove()
1864
+ }
1865
+ }, 'token-receipt: fonts')
1415
1866
  ctx.effect(() => {
1416
1867
  if (ctx.locale.getSnapshot().locales.some((language) => language.id === 'ja')) return
1417
1868
  return ctx.locale.addLanguage({ id: 'ja', label: '日本語', fallback: 'en' })
1418
1869
  }, 'token-receipt: Japanese language')
1419
1870
  ctx.effect(() => ctx.locale.register(NS, DICT), 'token-receipt: dictionaries')
1420
1871
  const label = () => {
1421
- const active = ctx.locale.getSnapshot().active || 'en'
1422
- return ((DICT[active] || DICT.en).nav)
1872
+ const lang = normalizeLocale(ctx.locale.getSnapshot().active)
1873
+ return (DICT[lang] || DICT.en).nav
1423
1874
  }
1424
1875
  ctx.slots.inject('sidebar.panellist', () =>
1425
1876
  ctx.slots.register({ name: 'sidebar.panellist', id: PANEL, order: 7, label }, (props) => h(PrinterGlyph, { size: (props && props.size) || 18 })),