@unson/brainbase-mcp 0.47.6 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ui/inbox.js CHANGED
@@ -35,6 +35,13 @@ const GROUPS = Object.keys(INBOX_GROUP_LABELS);
35
35
  const TABS = ['waiting', 'notices'];
36
36
  const VIEWS = ['waiting', 'later', 'cleared'];
37
37
 
38
+ /** The three sections of the 今日決めること layout, in order. */
39
+ export const INBOX_TODAY_SECTIONS = Object.freeze([
40
+ Object.freeze({ id: 'decide', label: '決めること', groups: Object.freeze(['answer', 'approve']) }),
41
+ Object.freeze({ id: 'batch', label: 'まとめて片付くもの', groups: Object.freeze(['triage']) }),
42
+ Object.freeze({ id: 'look', label: '見るだけ', groups: Object.freeze(['task']) }),
43
+ ]);
44
+
38
45
  const el = makeWorkspaceElement;
39
46
 
40
47
  // Why a read failed, in the viewer's words; the code stays beside it for support.
@@ -149,13 +156,16 @@ function at(base, dayOffset, hour) {
149
156
  }
150
157
 
151
158
  /** あとで: this evening (only before 18:00), tomorrow morning, next Monday morning — by the viewer's clock. */
152
- export function inboxLaterChoices(now = new Date()) {
159
+ export function inboxLaterChoices(now = new Date(), { style } = {}) {
160
+ const today = style === 'today';
153
161
  const choices = [];
154
- const evening = at(now, 0, 18);
155
- if (evening.getTime() > now.getTime()) choices.push({ id: 'evening', label: '今日の夕方', until: evening });
156
- choices.push({ id: 'tomorrow', label: '明日の朝', until: at(now, 1, 9) });
162
+ const evening = at(now, 0, today ? 21 : 18);
163
+ if (evening.getTime() > now.getTime()) {
164
+ choices.push({ id: 'evening', label: today ? '今夜 21:00' : '今日の夕方', until: evening });
165
+ }
166
+ choices.push({ id: 'tomorrow', label: today ? '明日の朝 9:00' : '明日の朝', until: at(now, 1, 9) });
157
167
  const toMonday = ((8 - now.getDay()) % 7) || 7;
158
- choices.push({ id: 'monday', label: '来週の月曜の朝', until: at(now, toMonday, 9) });
168
+ choices.push({ id: 'monday', label: today ? '来週の月曜 9:00' : '来週の月曜の朝', until: at(now, toMonday, 9) });
159
169
  return choices;
160
170
  }
161
171
 
@@ -240,6 +250,42 @@ function relativeTime(value, now) {
240
250
  return days < 30 ? `${days}日前` : formatShort(value);
241
251
  }
242
252
 
253
+ function waitingDays(value, now) {
254
+ const time = timeOf(value);
255
+ if (time === null) return null;
256
+ return Math.max(0, Math.floor((now.getTime() - time) / 86_400_000));
257
+ }
258
+
259
+ const DUE_SOON_MS = 86_400_000;
260
+
261
+ /**
262
+ * How a due time reads on a row: past it is 期限切れ, within a day it is the
263
+ * time left, otherwise the date. Only the words change; whether the request
264
+ * has lapsed is the host's record, never this clock.
265
+ */
266
+ export function inboxDueLabel(value, now = new Date()) {
267
+ const time = timeOf(value);
268
+ if (time === null) return null;
269
+ const left = time - now.getTime();
270
+ if (left <= 0) return { state: 'expired', text: '期限切れ' };
271
+ if (left <= DUE_SOON_MS) {
272
+ const minutes = Math.ceil(left / 60_000);
273
+ return { state: 'soon', text: minutes < 60 ? `期限まであと${minutes}分` : `期限まであと${Math.floor(minutes / 60)}時間` };
274
+ }
275
+ return { state: 'later', text: `期限 ${formatShort(value)}` };
276
+ }
277
+
278
+ /** The named facts of a row (依頼・対象 …), in the host's order; anything without both words is left out. */
279
+ function factsOf(item) {
280
+ return (Array.isArray(item?.facts) ? item.facts : [])
281
+ .map((fact) => ({ label: textOf(fact?.label), value: textOf(fact?.value) }))
282
+ .filter((fact) => fact.label && fact.value);
283
+ }
284
+
285
+ function doneTextOf(action) {
286
+ return textOf(action?.doneLabel) ?? `「${action.label}」を実行しました`;
287
+ }
288
+
243
289
  export function createInboxUI({
244
290
  root,
245
291
  page,
@@ -250,6 +296,10 @@ export function createInboxUI({
250
296
  onNavigate,
251
297
  onCount,
252
298
  now = () => new Date(),
299
+ layout: layoutOption = 'tabs',
300
+ undoWindowMs: undoWindowMsOption = 0,
301
+ doneShownMs: doneShownMsOption = 1100,
302
+ timers: timersOption,
253
303
  } = {}) {
254
304
  if (!root) throw new TypeError('root is required');
255
305
  if (!port || typeof port.readInbox !== 'function' || typeof port.setDisposition !== 'function') {
@@ -259,34 +309,114 @@ export function createInboxUI({
259
309
  if (!doc || typeof doc.createElement !== 'function') throw new Error('document_unavailable');
260
310
  const crumbs = Array.isArray(page?.crumbs) ? page.crumbs : ['受信箱'];
261
311
  const readNow = () => (typeof now === 'function' ? now() : now);
312
+ const layout = layoutOption === 'today' ? 'today' : 'tabs';
313
+ const undoWindowMs = Number.isFinite(undoWindowMsOption) && undoWindowMsOption > 0 ? undoWindowMsOption : 0;
314
+ const doneShownMs = Number.isFinite(doneShownMsOption) && doneShownMsOption >= 0 ? doneShownMsOption : 1100;
315
+ const timers = {
316
+ set: typeof timersOption?.set === 'function' ? timersOption.set : (fn, ms) => globalThis.setTimeout(fn, ms),
317
+ clear: typeof timersOption?.clear === 'function' ? timersOption.clear : (id) => globalThis.clearTimeout(id),
318
+ };
319
+
320
+ function normalizedRoute(route) {
321
+ const next = normalizeRoute(route);
322
+ return layout === 'today' ? { ...next, tab: 'waiting' } : next;
323
+ }
262
324
 
263
325
  const state = {
264
- route: normalizeRoute(initialRoute),
326
+ route: normalizedRoute(initialRoute),
265
327
  phase: 'idle',
266
328
  result: null,
267
329
  reason: null,
268
330
  dispositions: new Map(),
269
331
  laterOpen: null,
270
332
  notice: null,
333
+ noticeOwner: null,
271
334
  notices: null,
335
+ pending: new Map(),
336
+ sent: new Set(),
337
+ // A row whose action was sent and has not answered: its buttons stay still.
338
+ running: new Map(),
339
+ // A row whose action succeeded: its result shows for a moment before the rows are read again.
340
+ done: new Map(),
341
+ // The one action waiting for its second press (an action with `confirm`).
342
+ confirming: null,
343
+ // Where focus goes on the next render ({ itemId, target: 'confirm' | 'action', actionId }).
344
+ focus: null,
345
+ // A result to read out with the next count (an action sent after its undo window).
346
+ said: null,
272
347
  destroyed: false,
273
348
  };
274
349
  let generation = 0;
350
+ const doneTimers = new Set();
351
+ // The element to focus once the next render is in place (the confirm band's buttons).
352
+ let focusTarget = null;
353
+ // One live region kept across renders, so a changed count or a result is read out once.
354
+ const announcer = el(doc, 'p', { className: 'bb-inbox-announcer bb-ws-visually-hidden', attrs: { role: 'status', 'aria-live': 'polite' } });
355
+ let lastAnnouncedCount = null;
356
+
357
+ function announce(text) {
358
+ announcer.textContent = text;
359
+ }
360
+
361
+ function setNotice(message, owner = null) {
362
+ state.notice = message;
363
+ state.noticeOwner = owner;
364
+ }
365
+
366
+ function clearNotice() {
367
+ state.notice = null;
368
+ state.noticeOwner = null;
369
+ }
370
+
371
+ function clearNoticeFor(owner) {
372
+ if (!state.notice || !state.noticeOwner) return;
373
+ if (state.noticeOwner.itemId !== owner.itemId || state.noticeOwner.actionId !== owner.actionId) return;
374
+ clearNotice();
375
+ }
275
376
 
276
377
  function go(route) {
277
- const next = normalizeRoute({ ...state.route, ...route });
378
+ const next = normalizedRoute({ ...state.route, ...route });
278
379
  if (typeof onRouteChange === 'function') onRouteChange(next);
279
380
  else applyRoute(next);
280
381
  }
281
382
 
282
- function reportCount() {
283
- if (typeof onCount !== 'function') return;
284
- onCount(state.result ? countInboxWaiting({ ...state.result, dispositions: [...state.dispositions.values()] }, readNow()) : { count: null, unreadable: [] });
383
+ function countNow() {
384
+ if (!state.result) return { count: null, unreadable: [] };
385
+ const current = readNow();
386
+ const base = countInboxWaiting({ ...state.result, dispositions: [...state.dispositions.values()] }, current);
387
+ // Rows waiting to be sent, sent, or showing their result are not waiting any more.
388
+ const gone = new Set([...state.pending.keys(), ...state.sent, ...state.done.keys()]);
389
+ if (gone.size === 0 || base.count === null) return base;
390
+ const rows = new Map(readableItems(state.result).map((item) => [item.id, item]));
391
+ let count = base.count;
392
+ for (const id of gone) {
393
+ const row = rows.get(id);
394
+ if (!row) continue;
395
+ if (activeDisposition(row, state.dispositions, current)) continue;
396
+ count -= unitsOf(row);
397
+ }
398
+ return { count: Math.max(0, count), unreadable: base.unreadable };
399
+ }
400
+
401
+ /** Tells the host the count, and reads it out when it changed (never the first one) or with a result. */
402
+ function reportCount({ said = null } = {}) {
403
+ const counted = countNow();
404
+ if (typeof onCount === 'function') onCount(counted);
405
+ const words = said ?? state.said;
406
+ state.said = null;
407
+ if (words) announce(counted.count === null ? words : `${words}。対応待ち ${counted.count}件`);
408
+ else if (lastAnnouncedCount !== null && counted.count !== null && counted.count !== lastAnnouncedCount) announce(`対応待ち ${counted.count}件`);
409
+ if (counted.count !== null) lastAnnouncedCount = counted.count;
410
+ }
411
+
412
+ function noticesWanted() {
413
+ return layout === 'today' ? typeof port.readNotices === 'function' : state.route.tab === 'notices';
285
414
  }
286
415
 
287
416
  async function loadNotices() {
288
417
  if (typeof port.readNotices !== 'function') {
289
418
  state.notices = { phase: 'not_collected' };
419
+ if (!state.destroyed) render();
290
420
  return;
291
421
  }
292
422
  let result;
@@ -295,9 +425,11 @@ export function createInboxUI({
295
425
  } catch (error) {
296
426
  result = { status: 'unavailable', reason: error instanceof Error ? error.message : 'request_failed' };
297
427
  }
428
+ if (state.destroyed) return;
298
429
  state.notices = result?.status === 'ok' && Array.isArray(result.items)
299
430
  ? { phase: 'ok', items: result.items }
300
431
  : { phase: 'unavailable', reason: result?.reason ?? 'response_invalid' };
432
+ render();
301
433
  }
302
434
 
303
435
  async function load() {
@@ -312,27 +444,36 @@ export function createInboxUI({
312
444
  } catch (error) {
313
445
  result = { status: 'unavailable', reason: error instanceof Error ? error.message : 'request_failed' };
314
446
  }
315
- if (state.route.tab === 'notices' && state.notices === null) await loadNotices();
316
447
  if (current !== generation || state.destroyed) return;
448
+ state.done.clear();
317
449
  if (result?.status === 'ok' && Array.isArray(result.sources) && Array.isArray(result.items)) {
318
450
  state.result = result;
319
451
  state.dispositions = dispositionMap(result.dispositions);
320
452
  state.phase = 'ready';
321
453
  state.reason = null;
454
+ state.sent.clear();
455
+ // A confirm band is for the row as it was; a changed or gone row closes it.
456
+ const confirming = state.confirming;
457
+ if (confirming && !readableItems(result).some((item) => item.id === confirming.itemId && (item.revision ?? null) === confirming.revision)) {
458
+ state.confirming = null;
459
+ }
322
460
  } else {
323
461
  state.result = null;
324
462
  state.phase = 'error';
325
463
  state.reason = result?.reason ?? 'response_invalid';
326
464
  }
465
+ // The inbox is shown as soon as it arrives; notices are read beside it and
466
+ // never hold back the rows or the count when they are slow or failing.
327
467
  render();
328
468
  reportCount();
469
+ if (noticesWanted() && state.notices === null) void loadNotices();
329
470
  }
330
471
 
331
472
  function applyRoute(route) {
332
- state.route = normalizeRoute(route);
473
+ state.route = normalizedRoute(route);
333
474
  state.laterOpen = null;
334
- if (state.route.tab === 'notices' && state.notices === null) {
335
- void loadNotices().then(() => render());
475
+ if (noticesWanted() && state.notices === null) {
476
+ void loadNotices();
336
477
  }
337
478
  render();
338
479
  }
@@ -342,7 +483,7 @@ export function createInboxUI({
342
483
  if (change.state === 'open') state.dispositions.delete(item.id);
343
484
  else state.dispositions.set(item.id, { itemId: item.id, revision: change.revision, state: change.state, until: change.until ?? null, at: readNow().toISOString() });
344
485
  state.laterOpen = null;
345
- state.notice = null;
486
+ clearNotice();
346
487
  render();
347
488
  reportCount();
348
489
  let result;
@@ -354,26 +495,145 @@ export function createInboxUI({
354
495
  if (state.destroyed || result?.status === 'ok') return;
355
496
  if (previous) state.dispositions.set(item.id, previous);
356
497
  else state.dispositions.delete(item.id);
357
- state.notice = `${failureTitle}。理由: ${reasonText(result?.reason ?? 'response_invalid')}。`;
498
+ setNotice(`${failureTitle}。理由: ${reasonText(result?.reason ?? 'response_invalid')}。`);
358
499
  render();
359
500
  reportCount();
360
501
  }
361
502
 
362
503
  async function runAction(item, action) {
504
+ // The row stays still while its action is out: a second press sends nothing.
505
+ if (state.running.has(item.id) || state.done.has(item.id)) return;
506
+ const owner = { itemId: item.id, actionId: action.id };
507
+ state.running.set(item.id, action.id);
508
+ state.laterOpen = null;
509
+ render();
363
510
  let result;
364
511
  try {
365
512
  result = await port.runAction(item.id, action.id);
366
513
  } catch (error) {
367
514
  result = { status: 'unavailable', reason: error instanceof Error ? error.message : 'request_failed' };
368
515
  }
516
+ state.running.delete(item.id);
369
517
  if (state.destroyed) return;
370
518
  if (result?.status === 'ok') {
371
- state.notice = null;
519
+ if (undoWindowMs > 0) clearNoticeFor(owner);
520
+ else clearNotice();
521
+ await showDone(item, action);
522
+ return;
523
+ }
524
+ setNotice(`「${action.label}」を実行できませんでした。理由: ${reasonText(result?.reason ?? 'response_invalid')}。`, owner);
525
+ render();
526
+ }
527
+
528
+ /** The host said yes: the row shows its result for a moment, then the rows are read again. */
529
+ function showDone(item, action) {
530
+ const said = doneTextOf(action);
531
+ state.done.set(item.id, said);
532
+ render();
533
+ reportCount({ said });
534
+ return new Promise((resolve) => {
535
+ const timerId = timers.set(() => {
536
+ doneTimers.delete(timerId);
537
+ resolve(load());
538
+ }, doneShownMs);
539
+ doneTimers.add(timerId);
540
+ });
541
+ }
542
+
543
+ function clearPendingTimer(entry) {
544
+ if (entry.timerId !== null && entry.timerId !== undefined) timers.clear(entry.timerId);
545
+ }
546
+
547
+ async function commitPending(entry) {
548
+ if (state.pending.get(entry.item.id) !== entry || state.destroyed) return;
549
+ clearPendingTimer(entry);
550
+ entry.sent = true;
551
+ render();
552
+ let result;
553
+ try {
554
+ result = await port.runAction(entry.item.id, entry.action.id);
555
+ } catch (error) {
556
+ result = { status: 'unavailable', reason: error instanceof Error ? error.message : 'request_failed' };
557
+ }
558
+ if (state.pending.get(entry.item.id) === entry) state.pending.delete(entry.item.id);
559
+ if (state.destroyed) return;
560
+ if (result?.status === 'ok') {
561
+ state.sent.add(entry.item.id);
562
+ state.said = doneTextOf(entry.action);
563
+ clearNoticeFor({ itemId: entry.item.id, actionId: entry.action.id });
372
564
  await load();
373
565
  return;
374
566
  }
375
- state.notice = `「${action.label}」を実行できませんでした。理由: ${reasonText(result?.reason ?? 'response_invalid')}。`;
567
+ setNotice(`「${entry.action.label}」を実行できませんでした。理由: ${reasonText(result?.reason ?? 'response_invalid')}。`, { itemId: entry.item.id, actionId: entry.action.id });
568
+ render();
569
+ reportCount();
570
+ }
571
+
572
+ function pressAction(item, action) {
573
+ if (undoWindowMs <= 0) {
574
+ void runAction(item, action);
575
+ return;
576
+ }
577
+ const entry = { item, action, timerId: null };
578
+ state.pending.set(item.id, entry);
579
+ clearNotice();
580
+ entry.timerId = timers.set(() => { void commitPending(entry); }, undoWindowMs);
581
+ render();
582
+ reportCount();
583
+ }
584
+
585
+ /** A press on a row's action: one with `confirm` first turns the row's buttons into the confirm band. */
586
+ function pressFromRow(item, action) {
587
+ if (state.running.has(item.id) || state.done.has(item.id)) return;
588
+ if (textOf(action.confirm)) {
589
+ state.confirming = { itemId: item.id, actionId: action.id, revision: item.revision ?? null };
590
+ state.focus = { itemId: item.id, target: 'confirm' };
591
+ state.laterOpen = null;
592
+ render();
593
+ return;
594
+ }
595
+ pressAction(item, action);
596
+ }
597
+
598
+ function confirmingAction(item, actions) {
599
+ const confirming = state.confirming;
600
+ if (!confirming || confirming.itemId !== item.id || confirming.revision !== (item.revision ?? null)) return null;
601
+ return actions.find((action) => action.id === confirming.actionId && textOf(action.confirm)) ?? null;
602
+ }
603
+
604
+ function renderConfirm(item, action) {
605
+ const band = el(doc, 'div', { className: 'bb-inbox-confirm', attrs: { role: 'group', 'aria-label': `「${action.label}」の確認` } });
606
+ band.append(el(doc, 'p', { className: 'bb-inbox-confirm-text', text: textOf(action.confirm) }));
607
+ const buttons = el(doc, 'div', { className: 'bb-inbox-row-actions' });
608
+ const send = workspaceButton(doc, {
609
+ text: action.label,
610
+ variant: action.tone === 'danger' ? 'danger' : 'primary',
611
+ onClick: () => {
612
+ state.confirming = null;
613
+ pressAction(item, action);
614
+ },
615
+ });
616
+ const cancel = workspaceButton(doc, {
617
+ text: 'やめる',
618
+ variant: 'quiet',
619
+ onClick: () => {
620
+ state.confirming = null;
621
+ state.focus = { itemId: item.id, target: 'action', actionId: action.id };
622
+ render();
623
+ },
624
+ });
625
+ if (state.focus?.itemId === item.id && state.focus.target === 'confirm') focusTarget = send;
626
+ buttons.append(send, cancel);
627
+ band.append(buttons);
628
+ return band;
629
+ }
630
+
631
+ function undoPending(entry) {
632
+ if (entry.sent === true) return;
633
+ clearPendingTimer(entry);
634
+ state.pending.delete(entry.item.id);
376
635
  render();
636
+ reportCount();
377
637
  }
378
638
 
379
639
  function openItem(item, event) {
@@ -406,7 +666,7 @@ export function createInboxUI({
406
666
 
407
667
  function renderLaterMenu(item) {
408
668
  const menu = el(doc, 'div', { className: 'bb-inbox-later-menu', attrs: { role: 'group', 'aria-label': 'あとでの時刻' } });
409
- for (const choice of inboxLaterChoices(readNow())) {
669
+ for (const choice of inboxLaterChoices(readNow(), layout === 'today' ? { style: 'today' } : {})) {
410
670
  menu.append(workspaceButton(doc, {
411
671
  text: choice.label,
412
672
  variant: 'quiet',
@@ -416,19 +676,53 @@ export function createInboxUI({
416
676
  return menu;
417
677
  }
418
678
 
679
+ function renderFacts(facts) {
680
+ const list = el(doc, 'dl', { className: 'bb-inbox-facts' });
681
+ for (const fact of facts) {
682
+ const pair = el(doc, 'div', { className: 'bb-inbox-fact' });
683
+ pair.append(el(doc, 'dt', { text: fact.label }), el(doc, 'dd', { text: fact.value }));
684
+ list.append(pair);
685
+ }
686
+ return list;
687
+ }
688
+
419
689
  function renderRow(item, view) {
420
- const row = el(doc, 'div', { className: `bb-inbox-row${item.blocking === true ? ' is-blocking' : ''}`, attrs: { role: 'listitem', 'data-inbox-item': item.id } });
690
+ const running = view === 'waiting' && state.running.has(item.id);
691
+ const done = view === 'waiting' ? state.done.get(item.id) ?? null : null;
692
+ const row = el(doc, 'div', {
693
+ className: `bb-inbox-row${item.blocking === true ? ' is-blocking' : ''}${running ? ' is-running' : ''}${done ? ' is-done' : ''}`,
694
+ attrs: { role: 'listitem', 'data-inbox-item': item.id, 'aria-busy': running ? 'true' : undefined },
695
+ });
421
696
  const main = el(doc, 'div', { className: 'bb-inbox-row-main' });
422
697
  const href = textOf(item.href);
423
698
  const title = el(doc, href ? 'a' : 'span', { className: 'bb-inbox-title', text: item.title, attrs: href ? { href } : {} });
424
699
  if (href) title.addEventListener('click', (event) => openItem(item, event));
425
700
  main.append(title);
701
+ const facts = factsOf(item);
702
+ if (facts.length > 0) main.append(renderFacts(facts));
426
703
  const meta = el(doc, 'div', { className: 'bb-inbox-meta' });
427
704
  if (item.blocking === true) meta.append(el(doc, 'span', { className: 'bb-inbox-blocking', text: '止めています' }));
428
- const due = formatShort(item.dueAt);
429
- if (due) meta.append(el(doc, 'span', { className: 'bb-inbox-due', text: `期限 ${due}` }));
430
- const received = relativeTime(item.receivedAt, readNow());
431
- if (received) meta.append(el(doc, 'span', { text: received, attrs: { title: formatShort(item.receivedAt) ?? undefined } }));
705
+ const due = inboxDueLabel(item.dueAt, readNow());
706
+ if (due) {
707
+ meta.append(el(doc, 'span', {
708
+ className: `bb-inbox-due${due.state === 'later' ? '' : ` is-${due.state}`}`,
709
+ text: due.text,
710
+ attrs: { title: due.state === 'later' ? undefined : `期限 ${formatShort(item.dueAt)}` },
711
+ }));
712
+ }
713
+ if (layout === 'today') {
714
+ const days = waitingDays(item.receivedAt, readNow());
715
+ if (days !== null) {
716
+ meta.append(el(doc, 'span', {
717
+ className: `bb-inbox-wait${days > 3 ? ' is-long' : ''}`,
718
+ text: days === 0 ? '今日' : `待ち ${days}日`,
719
+ attrs: { title: formatShort(item.receivedAt) ?? undefined },
720
+ }));
721
+ }
722
+ } else {
723
+ const received = relativeTime(item.receivedAt, readNow());
724
+ if (received) meta.append(el(doc, 'span', { text: received, attrs: { title: formatShort(item.receivedAt) ?? undefined } }));
725
+ }
432
726
  const disposition = state.dispositions.get(item.id);
433
727
  if (view === 'later' && disposition?.until) meta.append(el(doc, 'span', { className: 'bb-inbox-until', text: `${formatShort(disposition.until)}に戻ります` }));
434
728
  if (textOf(item.detail)) main.append(el(doc, 'p', { className: 'bb-inbox-detail', text: item.detail }));
@@ -436,30 +730,52 @@ export function createInboxUI({
436
730
  row.append(main);
437
731
 
438
732
  const controls = el(doc, 'div', { className: 'bb-inbox-row-actions' });
733
+ if (done) {
734
+ controls.append(el(doc, 'span', { className: 'bb-inbox-done', text: `✓ ${done}` }));
735
+ row.append(controls);
736
+ return row;
737
+ }
439
738
  if (view === 'waiting') {
440
- if (typeof port.runAction === 'function') {
441
- for (const action of Array.isArray(item.actions) ? item.actions : []) {
442
- if (!textOf(action?.id) || !textOf(action?.label)) continue;
443
- controls.append(workspaceButton(doc, { text: action.label, variant: action.tone === 'primary' ? 'primary' : action.tone === 'danger' ? 'danger' : 'default', onClick: () => void runAction(item, action) }));
444
- }
739
+ const actions = typeof port.runAction === 'function'
740
+ ? (Array.isArray(item.actions) ? item.actions : []).filter((action) => textOf(action?.id) && textOf(action?.label))
741
+ : [];
742
+ const confirming = running ? null : confirmingAction(item, actions);
743
+ if (confirming) {
744
+ row.append(renderConfirm(item, confirming));
745
+ return row;
746
+ }
747
+ const hasPrimary = actions.some((action) => action.tone === 'primary');
748
+ for (const action of actions) {
749
+ const button = workspaceButton(doc, {
750
+ text: action.label,
751
+ variant: action.tone === 'primary' ? 'primary' : action.tone === 'danger' ? 'danger' : 'default',
752
+ disabled: running,
753
+ onClick: () => pressFromRow(item, action),
754
+ });
755
+ if (state.focus?.itemId === item.id && state.focus.target === 'action' && state.focus.actionId === action.id) focusTarget = button;
756
+ controls.append(button);
445
757
  }
446
758
  controls.append(
447
759
  workspaceButton(doc, {
448
760
  text: 'あとで',
449
761
  variant: 'quiet',
762
+ disabled: running,
450
763
  attrs: { 'aria-expanded': state.laterOpen === item.id ? 'true' : 'false', 'aria-haspopup': 'true' },
451
764
  onClick: () => {
452
765
  state.laterOpen = state.laterOpen === item.id ? null : item.id;
453
766
  render();
454
767
  },
455
768
  }),
456
- workspaceButton(doc, { text: '片付けた', variant: 'quiet', onClick: () => void dispose(item, { state: 'cleared', revision: item.revision ?? null }, '片付けられませんでした') }),
457
769
  );
770
+ if (!(layout === 'today' && hasPrimary)) {
771
+ controls.append(workspaceButton(doc, { text: '片付けた', variant: 'quiet', disabled: running, onClick: () => void dispose(item, { state: 'cleared', revision: item.revision ?? null }, '片付けられませんでした') }));
772
+ }
773
+ if (running) controls.append(el(doc, 'span', { className: 'bb-inbox-running', text: '送っています' }));
458
774
  } else {
459
775
  controls.append(workspaceButton(doc, { text: '対応待ちに戻す', variant: 'quiet', onClick: () => void dispose(item, { state: 'open' }, '対応待ちに戻せませんでした') }));
460
776
  }
461
777
  row.append(controls);
462
- if (state.laterOpen === item.id) row.append(renderLaterMenu(item));
778
+ if (state.laterOpen === item.id && !running) row.append(renderLaterMenu(item));
463
779
  return row;
464
780
  }
465
781
 
@@ -473,6 +789,7 @@ export function createInboxUI({
473
789
  function partition(now) {
474
790
  const shown = { waiting: [], later: [], cleared: [] };
475
791
  for (const item of readableItems(state.result)) {
792
+ if (state.pending.has(item.id) || state.sent.has(item.id)) continue;
476
793
  const disposition = activeDisposition(item, state.dispositions, now);
477
794
  shown[disposition ? disposition.state : 'waiting'].push(item);
478
795
  }
@@ -511,6 +828,53 @@ export function createInboxUI({
511
828
  return view;
512
829
  }
513
830
 
831
+ function renderTodayWaiting(shown) {
832
+ const view = el(doc, 'div', { className: 'bb-inbox-waiting is-today' });
833
+ const sources = state.result.sources;
834
+ for (const definition of INBOX_TODAY_SECTIONS) {
835
+ const rows = sortInboxItems(shown.waiting.filter((item) => definition.groups.includes(item.group)));
836
+ const problems = sources.filter((source) => definition.groups.includes(source.group) && source.status !== 'ok');
837
+ if (rows.length > 0 || problems.length > 0) {
838
+ const section = el(doc, 'section', {
839
+ className: 'bb-inbox-group bb-inbox-today-section',
840
+ attrs: { 'data-section': definition.id, 'data-group': definition.id, 'aria-label': definition.label },
841
+ });
842
+ section.append(el(doc, 'h2', { className: 'bb-inbox-group-title', text: definition.label }));
843
+ if (rows.length > 0) {
844
+ const list = el(doc, 'div', { className: 'bb-inbox-list', attrs: { role: 'list' } });
845
+ for (const item of rows) list.append(renderRow(item, 'waiting'));
846
+ section.append(list);
847
+ }
848
+ for (const source of problems) section.append(sourceLine(source));
849
+ view.append(section);
850
+ }
851
+ if (definition.id === 'look' && typeof port.readNotices === 'function' && state.notices !== null) {
852
+ view.append(renderNotices());
853
+ }
854
+ }
855
+ const uncollected = (Array.isArray(state.result.uncollected) ? state.result.uncollected : []).filter(textOf);
856
+ if (uncollected.length > 0) {
857
+ view.append(el(doc, 'p', { className: 'bb-inbox-uncollected', text: `まだ集めていない種類があります(${uncollected.join('・')})。件数には入っていません。` }));
858
+ }
859
+ const links = el(doc, 'div', { className: 'bb-inbox-elsewhere' });
860
+ if (shown.later.length > 0) links.append(workspaceButton(doc, { text: `あとで ${shown.later.length}件`, variant: 'quiet', onClick: () => go({ view: 'later' }) }));
861
+ if (shown.cleared.length > 0) links.append(workspaceButton(doc, { text: `片付けた ${shown.cleared.length}件`, variant: 'quiet', onClick: () => go({ view: 'cleared' }) }));
862
+ if (links.children.length > 0) view.append(links);
863
+ return view;
864
+ }
865
+
866
+ function renderUndoBand() {
867
+ const entries = [...state.pending.values()];
868
+ if (entries.length === 0) return null;
869
+ const undoable = entries.filter((entry) => entry.sent !== true);
870
+ const target = undoable.length > 0 ? undoable[undoable.length - 1] : null;
871
+ const shown = target ?? entries[entries.length - 1];
872
+ const band = el(doc, 'div', { className: 'bb-inbox-undo', attrs: { role: 'status' } });
873
+ band.append(el(doc, 'span', { text: target ? `「${shown.action.label}」を実行します。` : `「${shown.action.label}」を実行しています。` }));
874
+ if (target) band.append(workspaceButton(doc, { text: '元に戻す', variant: 'quiet', onClick: () => undoPending(target) }));
875
+ return band;
876
+ }
877
+
514
878
  function renderSet(shown, which) {
515
879
  const view = el(doc, 'div', { className: 'bb-inbox-set' });
516
880
  view.append(workspaceButton(doc, { text: '対応待ちへ', variant: 'quiet', onClick: () => go({ view: 'waiting' }) }));
@@ -544,21 +908,55 @@ export function createInboxUI({
544
908
  function render() {
545
909
  if (state.destroyed) return;
546
910
  const current = readNow();
911
+ focusTarget = null;
547
912
  const shown = state.result ? partition(current) : null;
548
- const waitingCount = shown ? shown.waiting.reduce((sum, item) => sum + unitsOf(item), 0) : null;
549
- const view = el(doc, 'div', { className: 'bb-inbox', attrs: { 'data-contract-version': INBOX_UI_CONTRACT_VERSION } });
913
+ // A row showing its result is still drawn but no longer waiting.
914
+ const stillWaiting = (item) => !state.done.has(item.id);
915
+ const waitingCount = shown ? shown.waiting.filter(stillWaiting).reduce((sum, item) => sum + unitsOf(item), 0) : null;
916
+ const isToday = layout === 'today';
917
+ const view = el(doc, 'div', {
918
+ className: `bb-inbox${isToday ? ' is-today' : ''}`,
919
+ attrs: { 'data-contract-version': INBOX_UI_CONTRACT_VERSION },
920
+ });
550
921
  view.append(workspacePageHeader(doc, { crumbs, title: '受信箱', source: page?.source ?? undefined }));
551
- view.append(renderTabs(waitingCount));
922
+ if (!isToday) view.append(renderTabs(waitingCount));
923
+ if (isToday && shown) {
924
+ const decideGroups = INBOX_TODAY_SECTIONS[0].groups;
925
+ const decideCount = shown.waiting
926
+ .filter((item) => decideGroups.includes(item.group) && stillWaiting(item))
927
+ .reduce((sum, item) => sum + unitsOf(item), 0);
928
+ // 決めることの取得元(answer・approve)が読めていないのに0件を「ありません」と
929
+ // 断定しない。読めなかったときは件数ではなく、読めなかったことを出す。
930
+ const decideUnreadable = (state.result.sources ?? [])
931
+ .some((source) => decideGroups.includes(source.group) && source.status === 'unavailable');
932
+ const decideUnknown = decideCount === 0 && decideUnreadable;
933
+ view.append(el(doc, 'p', {
934
+ className: `bb-inbox-today-count${decideUnknown ? ' is-unreadable' : ''}`,
935
+ text: decideCount > 0
936
+ ? `今日決めること ${decideCount}件`
937
+ : decideUnreadable
938
+ ? '今日決めることを読めませんでした。0件ではありません。'
939
+ : '今日決めることはありません',
940
+ attrs: decideUnknown ? { role: 'status' } : {},
941
+ }));
942
+ }
552
943
  if (state.phase === 'loading') view.append(el(doc, 'div', { className: 'bb-inbox-loading', text: '読み込んでいます', attrs: { role: 'status' } }));
944
+ const undoBand = renderUndoBand();
945
+ if (undoBand) view.append(undoBand);
553
946
  if (state.notice) view.append(workspaceNotice(doc, { label: 'できませんでした', text: state.notice, tone: 'warning', role: 'alert' }));
554
- if (state.route.tab === 'notices') {
947
+ if (!isToday && state.route.tab === 'notices') {
555
948
  view.append(renderNotices());
556
949
  } else if (state.phase === 'error' && !shown) {
557
950
  view.append(workspaceErrorCard(doc, { title: '受信箱を読めませんでした', message: `理由: ${reasonText(state.reason)}。0件ではありません。`, onRetry: () => void load() }));
558
951
  } else if (shown) {
559
- view.append(state.route.view === 'waiting' ? renderWaiting(shown) : renderSet(shown, state.route.view));
952
+ if (isToday) view.append(state.route.view === 'waiting' ? renderTodayWaiting(shown) : renderSet(shown, state.route.view));
953
+ else view.append(state.route.view === 'waiting' ? renderWaiting(shown) : renderSet(shown, state.route.view));
954
+ }
955
+ root.replaceChildren(view, announcer);
956
+ if (state.focus) {
957
+ focusTarget?.focus?.({ preventScroll: true });
958
+ state.focus = null;
560
959
  }
561
- root.replaceChildren(view);
562
960
  }
563
961
 
564
962
  const controller = {
@@ -570,6 +968,20 @@ export function createInboxUI({
570
968
  destroy() {
571
969
  state.destroyed = true;
572
970
  generation += 1;
971
+ for (const timerId of doneTimers) timers.clear(timerId);
972
+ doneTimers.clear();
973
+ const remaining = [...state.pending.values()];
974
+ state.pending.clear();
975
+ for (const entry of remaining) {
976
+ clearPendingTimer(entry);
977
+ if (entry.sent === true || typeof port.runAction !== 'function') continue;
978
+ try {
979
+ const result = port.runAction(entry.item.id, entry.action.id);
980
+ if (result && typeof result.catch === 'function') result.catch(() => {});
981
+ } catch {
982
+ // The press still happened; there is no screen left to show the result on.
983
+ }
984
+ }
573
985
  root.replaceChildren();
574
986
  },
575
987
  };