From 38919104e72fd5e85b99938e3805ea8cd6eee152 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Mon, 9 Nov 2026 21:33:14 +0900 Subject: [PATCH 01/24] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E3=81=AE=E9=80=81?= =?UTF-8?q?=E3=82=8A=E5=85=88=E3=81=AE=E7=A8=AE=E9=A1=9E=E3=81=A8=E5=87=BA?= =?UTF-8?q?=E6=9D=A5=E4=BA=8B=E3=81=AE=E8=A8=80=E3=81=84=E6=96=B9=E3=82=92?= =?UTF-8?q?=E6=B1=BA=E3=82=81=E3=82=8B=E9=96=A2=E6=95=B0=E3=82=92=E8=B6=B3?= =?UTF-8?q?=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/device.ts | 25 +++ lib/notifications.ts | 357 ++++++++++++++++++++++++++++++++ tests/lib/device.test.ts | 37 +++- tests/lib/notifications.test.ts | 201 ++++++++++++++++++ 4 files changed, 619 insertions(+), 1 deletion(-) create mode 100644 lib/notifications.ts create mode 100644 tests/lib/notifications.test.ts diff --git a/lib/device.ts b/lib/device.ts index 906d77a1..546be7bc 100644 --- a/lib/device.ts +++ b/lib/device.ts @@ -38,6 +38,31 @@ export function describeDevice(label: string): Device { } } +const MACHINE_OF: [RegExp, string][] = [ + [/\biPad\b/, 'iPad'], + [/\biPhone\b|\biPod\b/, 'iPhone'], + [/\bAndroid\b/, 'Android'], + [/\bWindows NT\b/, 'Windows'], + [/\bMac OS X\b|\bMacintosh\b/, 'Mac'], + [/\bCrOS\b/, 'Chromebook'], + [/\bLinux\b|\bX11\b/, 'Linux'], +] + +export const THIS_BROWSER = 'このブラウザ' + +/** The browser a page is open in, as a person names it: the machine, then the browser, `Windows の Chrome`. */ +export function browserHere(agent: string): string { + const browser = browserOf(agent.trim()) + + if (browser === undefined || !browser.aBrowser) { + return THIS_BROWSER + } + + const machine = MACHINE_OF.find(([seen]) => seen.test(agent))?.[1] + + return machine === undefined ? browser.name : `${machine} の ${browser.name}` +} + function platformOf(agent: string): Platform | undefined { if (/\biPad\b/.test(agent)) { return { name: `iPadOS${appleVersionOf(agent)}`, kind: 'タブレット' } diff --git a/lib/notifications.ts b/lib/notifications.ts new file mode 100644 index 00000000..e75f9ad4 --- /dev/null +++ b/lib/notifications.ts @@ -0,0 +1,357 @@ +import { formatClock, formatMoment, formatRecentMoment } from '@/lib/format' +import { + NOT_YET_IN_THIS_BUILD, + shapeFor, + wordFor, +} from '@/lib/not-yet-in-this-build' + +export type WebhookKind = 'slack' | 'discord' + +export type DestinationKind = WebhookKind | 'webPush' + +export type DeliveryFailure = + 'timeout' | 'rateLimited' | 'rejected' | 'tls' | 'unreachable' + +export type DestinationResult = + | { state: 'sent'; at: string } + | { state: 'failed' | 'givenUp'; at: string; failure: DeliveryFailure } + +/** A place notices are sent to. A webhook's address never comes back from Carina, only its last four characters. */ +export interface NotificationDestination { + id: string + name: string + kind: DestinationKind + urlTail?: string + enabled: boolean + lastResult?: DestinationResult +} + +export type NotificationEvent = + | 'recordingStarted' + | 'recordingCompleted' + | 'recordingTruncated' + | 'recordingFailed' + | 'encodeStarted' + | 'encodeCompleted' + | 'encodeFailed' + | 'reservationCompeting' + | 'reservationMissed' + | 'programmeMoved' + | 'qualityRaised' + | 'qualityResolved' + | 'deviceDisconnected' + +export interface NotificationRuleSet { + id: string + name: string + enabled: boolean + events: NotificationEvent[] + destinationIds: string[] +} + +export type RuleSetDraft = Omit + +export type DeliveryState = 'queued' | 'sent' | 'failed' | 'givenUp' + +export interface NotificationDelivery { + id: string + at: string + event: NotificationEvent | 'programmeStarting' + subject: string + destinationId: string + destinationName: string + state: DeliveryState + failure?: DeliveryFailure +} + +export const LEADS = [0, 1, 3, 5, 10] as const + +export type LeadMinutes = (typeof LEADS)[number] + +export interface NotificationSettings { + leadMinutes: LeadMinutes + hasPublicOrigin: boolean +} + +/** A notice that a programme is about to start, set from the guide without recording it. */ +export interface ProgrammeWatch { + id: string + leadMinutes: LeadMinutes + destinationIds: string[] +} + +export type NotificationWrite = + | { state: 'ok' } + | { state: 'unauthenticated' } + | { state: 'rejected'; message: string } + +export type TestSending = + | { state: 'ok'; delivered: true } + | { state: 'ok'; delivered: false; failure: DeliveryFailure } + | { state: 'unauthenticated' } + | { state: 'rejected'; message: string } + +export type BrowserPermission = 'default' | 'granted' | 'denied' + +export const RULE_SETS_AT_MOST = 20 + +export const KIND_LABEL: Record = { + slack: 'Slack', + discord: 'Discord', + webPush: 'Web Push', +} + +export const FAILURE_LABEL: Record = { + timeout: '時間切れ', + rateLimited: '回数の上限', + rejected: '断られた', + tls: '暗号化の失敗', + unreachable: 'つながらない', +} + +const SLACK_HOST = 'hooks.slack.com' + +const DISCORD_HOSTS = new Set(['discord.com', 'discordapp.com']) + +const DISCORD_PATH = '/api/webhooks/' + +/** Which service a webhook's address is for, as Carina decides it (BR-NT-001/002); `undefined` for an address it refuses. */ +export function webhookKindOf(address: string): WebhookKind | undefined { + let url: URL + + try { + url = new URL(address.trim()) + } catch { + return undefined + } + + if ( + url.protocol !== 'https:' || + url.port !== '' || + url.username !== '' || + url.password !== '' + ) { + return undefined + } + + if (url.hostname === SLACK_HOST) { + return 'slack' + } + + return DISCORD_HOSTS.has(url.hostname) && + url.pathname.startsWith(DISCORD_PATH) + ? 'discord' + : undefined +} + +export function registeringAs(kind: WebhookKind): string { + return `${KIND_LABEL[kind]} として登録します` +} + +export function tailOf(urlTail: string): string { + return `…${urlTail}` +} + +export interface EventGroup { + name: string + prefix: string + events: { event: NotificationEvent; label: string }[] +} + +/** The events a rule set chooses from, grouped as the editor lays them out. A group's prefix is what its labels are read after in a summary. */ +export const EVENT_GROUPS: EventGroup[] = [ + { + name: '録画', + prefix: '録画の', + events: [ + { event: 'recordingStarted', label: '開始' }, + { event: 'recordingCompleted', label: '完了' }, + { event: 'recordingTruncated', label: '欠け' }, + { event: 'recordingFailed', label: '失敗' }, + ], + }, + { + name: 'エンコード', + prefix: 'エンコードの', + events: [ + { event: 'encodeStarted', label: '開始' }, + { event: 'encodeCompleted', label: '完了' }, + { event: 'encodeFailed', label: '失敗' }, + ], + }, + { + name: '予約', + prefix: '', + events: [ + { event: 'reservationCompeting', label: '競合' }, + { event: 'reservationMissed', label: '取り逃し' }, + { event: 'programmeMoved', label: '番組の移動' }, + ], + }, + { + name: '品質', + prefix: '', + events: [ + { event: 'qualityRaised', label: '異常の発生' }, + { event: 'qualityResolved', label: '解消' }, + ], + }, + { + name: '機器', + prefix: '', + events: [{ event: 'deviceDisconnected', label: '切断' }], + }, +] + +export const NO_EVENTS = 'なし' + +/** A rule set's events in words: each group's chosen labels joined after its prefix, the groups parted by a dot. */ +export function eventsSummary(events: readonly NotificationEvent[]): string { + const chosen = new Set(events) + const said = EVENT_GROUPS.flatMap((group) => { + const labels = group.events + .filter(({ event }) => chosen.has(event)) + .map(({ label }) => label) + + return labels.length === 0 ? [] : [`${group.prefix}${labels.join('・')}`] + }) + + return said.length === 0 ? NO_EVENTS : said.join(' · ') +} + +export const EVENT_LABEL: Record = { + recordingStarted: '録画の開始', + recordingCompleted: '録画の完了', + recordingTruncated: '録画の欠け', + recordingFailed: '録画の失敗', + encodeStarted: 'エンコードの開始', + encodeCompleted: 'エンコードの完了', + encodeFailed: 'エンコードの失敗', + reservationCompeting: '予約の競合', + reservationMissed: '予約の取り逃し', + programmeMoved: '番組の移動', + qualityRaised: '品質の異常の発生', + qualityResolved: '品質の異常の解消', + deviceDisconnected: '機器の切断', + programmeStarting: '放送開始の通知', +} + +export function eventLabelOf(event: NotificationDelivery['event']): string { + return wordFor(EVENT_LABEL, event) +} + +export function leadLabel(lead: LeadMinutes): string { + return lead === 0 ? '開始時' : `${lead} 分前` +} + +/** The words on the chip a programme wears once its start is to be told. */ +export function leadChipWords(lead: LeadMinutes): string { + return lead === 0 ? '開始時に通知' : `開始 ${lead} 分前に通知` +} + +/** What the toast says once a programme's start is to be told. */ +export function leadToastWords(lead: LeadMinutes): string { + return lead === 0 ? '開始時に通知します' : `開始の ${lead} 分前に通知します` +} + +export function isLead(value: number): value is LeadMinutes { + return (LEADS as readonly number[]).includes(value) +} + +export type Verdict = 'ok' | 'warn' | 'err' | 'calm' + +export interface Said { + verdict: Verdict + words: string + why?: string +} + +function failureWord(failure: DeliveryFailure | undefined): string | undefined { + return failure === undefined ? undefined : wordFor(FAILURE_LABEL, failure) +} + +/** How the last notice sent to a destination went: reached it, still being tried, or given up on. */ +export function lastResultSaid( + result: DestinationResult, + now: number = Date.now(), +): Said { + if (result.state === 'sent') { + return { + verdict: 'ok', + words: `届いた ${formatRecentMoment(result.at, now)}`, + } + } + + return { + verdict: result.state === 'failed' ? 'warn' : 'err', + words: result.state === 'failed' ? '届いていない' : '届かなかった', + why: failureWord(result.failure), + } +} + +const DELIVERY_SAID: Record = { + queued: { verdict: 'calm', words: '送信待ち' }, + sent: { verdict: 'ok', words: '届いた' }, + failed: { verdict: 'warn', words: '送り直し中' }, + givenUp: { verdict: 'err', words: '届かなかった' }, +} + +const UNKNOWN_STATE: Said = { verdict: 'calm', words: NOT_YET_IN_THIS_BUILD } + +/** One delivery's state as its chip says it, with the reason when it has not reached its destination. */ +export function deliverySaid(delivery: NotificationDelivery): Said { + const said = shapeFor(DELIVERY_SAID, delivery.state, UNKNOWN_STATE) + + return said.verdict === 'warn' || said.verdict === 'err' + ? { ...said, why: failureWord(delivery.failure) } + : said +} + +/** The answer to a test send, beside the button that asked for it. */ +export function testSaid(sending: Extract): Said { + return sending.delivered + ? { verdict: 'ok', words: '届いた' } + : { + verdict: 'err', + words: '届かなかった', + why: failureWord(sending.failure), + } +} + +export function withWhy(said: Said): string { + return said.why === undefined ? said.words : `${said.words} · ${said.why}` +} + +export function deliveryMoment(at: string): string { + return formatMoment(at) +} + +export function deliveryClock(at: string): string { + return formatClock(new Date(at).getTime()) +} + +export function ruleSetsFull(count: number): boolean { + return count >= RULE_SETS_AT_MOST +} + +export const NAME_LONGEST = 64 + +/** Whether a destination or rule set name can be kept: one to 64 characters once trimmed. */ +export function nameFits(name: string): boolean { + const trimmed = name.trim() + + return trimmed.length > 0 && [...trimmed].length <= NAME_LONGEST +} + +/** The destinations a new single notice goes to when nobody chose: every one that is on. */ +export function destinationsByDefault( + destinations: readonly Pick[], +): string[] { + return destinations.filter(({ enabled }) => enabled).map(({ id }) => id) +} + +export function toggled(chosen: readonly T[], one: T): T[] { + return chosen.includes(one) + ? chosen.filter((each) => each !== one) + : [...chosen, one] +} diff --git a/tests/lib/device.test.ts b/tests/lib/device.test.ts index 72dcb0b1..f1bd97d7 100644 --- a/tests/lib/device.test.ts +++ b/tests/lib/device.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import { test } from 'node:test' -import { describeDevice } from '@/lib/device' +import { browserHere, describeDevice } from '@/lib/device' const WINDOWS = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' @@ -117,3 +117,38 @@ test('a browser on a system this build does not read is named without one', () = { name: 'Firefox', kind: undefined }, ) }) + +test('the browser a page is open in is named by the machine, then the browser', () => { + assert.equal( + browserHere(`${WINDOWS} ${WEBKIT} Chrome/150.0.0.0 Safari/537.36`), + 'Windows の Chrome', + ) + assert.equal( + browserHere( + 'Mozilla/5.0 (iPhone; CPU iPhone OS 19_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/19.0 Mobile/15E148 Safari/604.1', + ), + 'iPhone の Safari', + ) + assert.equal( + browserHere( + 'Mozilla/5.0 (iPad; CPU OS 19_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/19.0 Mobile/15E148 Safari/604.1', + ), + 'iPad の Safari', + ) + assert.equal( + browserHere(`${MAC} Gecko/20100101 Firefox/140.0`), + 'Mac の Firefox', + ) + assert.equal( + browserHere( + `Mozilla/5.0 (Linux; Android 16; Pixel 10) ${WEBKIT} Chrome/150.0.0.0 Mobile Safari/537.36`, + ), + 'Android の Chrome', + ) +}) + +test('a browser on a machine it cannot name is the browser alone, and anything else is this browser', () => { + assert.equal(browserHere(`Mozilla/5.0 ${WEBKIT} Chrome/150.0.0.0`), 'Chrome') + assert.equal(browserHere('VLC/3.0.21 LibVLC/3.0.21'), 'このブラウザ') + assert.equal(browserHere(''), 'このブラウザ') +}) diff --git a/tests/lib/notifications.test.ts b/tests/lib/notifications.test.ts new file mode 100644 index 00000000..e038ebf1 --- /dev/null +++ b/tests/lib/notifications.test.ts @@ -0,0 +1,201 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' + +import { + deliverySaid, + destinationsByDefault, + eventLabelOf, + eventsSummary, + isLead, + lastResultSaid, + leadChipWords, + leadLabel, + leadToastWords, + nameFits, + registeringAs, + ruleSetsFull, + testSaid, + toggled, + webhookKindOf, + withWhy, + type NotificationDelivery, +} from '@/lib/notifications' + +test('a Slack address is Slack, and both Discord hosts are Discord under their webhook path', () => { + assert.equal( + webhookKindOf('https://hooks.slack.com/services/T000/B000/XXXX'), + 'slack', + ) + assert.equal( + webhookKindOf('https://discord.com/api/webhooks/1234/abcd'), + 'discord', + ) + assert.equal( + webhookKindOf('https://discordapp.com/api/webhooks/1234/abcd'), + 'discord', + ) + assert.equal( + webhookKindOf(' https://HOOKS.SLACK.COM:443/services/T000 '), + 'slack', + ) +}) + +test('an address Carina refuses has no kind', () => { + for (const refused of [ + '', + 'hooks.slack.com/services/T000', + 'http://hooks.slack.com/services/T000', + 'https://hooks.slack.com:8443/services/T000', + 'https://hooks.slack.com.evil.example/services/T000', + 'https://user:secret@hooks.slack.com/services/T000', + 'https://127.0.0.1/services/T000', + 'https://[::ffff:10.0.0.3]/api/webhooks/1', + 'https://discord.com/channels/1234', + 'https://hook.example.jp/carina', + ]) { + assert.equal(webhookKindOf(refused), undefined, refused) + } +}) + +test('the line under the address names the service it will be kept as', () => { + assert.equal(registeringAs('slack'), 'Slack として登録します') + assert.equal(registeringAs('discord'), 'Discord として登録します') +}) + +test('a rule set says its events group by group, each group after its prefix', () => { + assert.equal( + eventsSummary([ + 'recordingTruncated', + 'recordingFailed', + 'encodeFailed', + 'reservationCompeting', + 'reservationMissed', + 'qualityRaised', + 'deviceDisconnected', + ]), + '録画の欠け・失敗 · エンコードの失敗 · 競合・取り逃し · 異常の発生 · 切断', + ) + assert.equal( + eventsSummary([ + 'encodeCompleted', + 'recordingCompleted', + 'recordingStarted', + ]), + '録画の開始・完了 · エンコードの完了', + ) + assert.equal(eventsSummary([]), 'なし') +}) + +test('every event has a label, and one this build does not know is said as such', () => { + assert.equal(eventLabelOf('programmeStarting'), '放送開始の通知') + assert.equal(eventLabelOf('qualityRaised'), '品質の異常の発生') + assert.equal( + eventLabelOf('somethingNew' as NotificationDelivery['event']), + '未知の値', + ) +}) + +test('the lead is said as the start itself or minutes before it', () => { + assert.equal(leadLabel(0), '開始時') + assert.equal(leadLabel(3), '3 分前') + assert.equal(leadChipWords(0), '開始時に通知') + assert.equal(leadChipWords(10), '開始 10 分前に通知') + assert.equal(leadToastWords(0), '開始時に通知します') + assert.equal(leadToastWords(3), '開始の 3 分前に通知します') + assert.ok(isLead(5)) + assert.ok(!isLead(2)) +}) + +test('the last result of a destination is good, being retried or given up', () => { + const now = Date.parse('2026-11-09T12:30:00Z') + + assert.deepEqual( + lastResultSaid({ state: 'sent', at: '2026-11-09T12:03:00Z' }, now), + { verdict: 'ok', words: '届いた 21:03' }, + ) + assert.deepEqual( + lastResultSaid( + { state: 'failed', at: '2026-11-09T12:03:00Z', failure: 'timeout' }, + now, + ), + { verdict: 'warn', words: '届いていない', why: '時間切れ' }, + ) + assert.deepEqual( + lastResultSaid( + { state: 'givenUp', at: '2026-11-09T12:03:00Z', failure: 'rejected' }, + now, + ), + { verdict: 'err', words: '届かなかった', why: '断られた' }, + ) +}) + +test('a delivery wears its reason only while it has not arrived', () => { + const delivery: NotificationDelivery = { + id: 'd', + at: '2026-11-09T12:03:00Z', + event: 'recordingTruncated', + subject: '港町レシピ帖', + destinationId: 'a', + destinationName: '家の Slack', + state: 'sent', + } + + assert.deepEqual(deliverySaid(delivery), { verdict: 'ok', words: '届いた' }) + assert.equal( + withWhy(deliverySaid({ ...delivery, state: 'failed', failure: 'timeout' })), + '送り直し中 · 時間切れ', + ) + assert.equal( + withWhy( + deliverySaid({ ...delivery, state: 'givenUp', failure: 'rejected' }), + ), + '届かなかった · 断られた', + ) + assert.equal( + withWhy(deliverySaid({ ...delivery, state: 'queued' })), + '送信待ち', + ) + assert.deepEqual( + deliverySaid({ + ...delivery, + state: 'bounced' as NotificationDelivery['state'], + }), + { verdict: 'calm', words: '未知の値' }, + ) +}) + +test('a test send says whether it arrived, and why not when it did not', () => { + assert.equal(withWhy(testSaid({ state: 'ok', delivered: true })), '届いた') + assert.equal( + withWhy(testSaid({ state: 'ok', delivered: false, failure: 'timeout' })), + '届かなかった · 時間切れ', + ) +}) + +test('rule sets stop at twenty', () => { + assert.ok(!ruleSetsFull(19)) + assert.ok(ruleSetsFull(20)) +}) + +test('a name is one to sixty-four characters once trimmed', () => { + assert.ok(!nameFits(' ')) + assert.ok(nameFits(' 家の Slack ')) + assert.ok(nameFits('あ'.repeat(64))) + assert.ok(!nameFits('あ'.repeat(65))) +}) + +test('a new single notice goes to every destination that is on', () => { + assert.deepEqual( + destinationsByDefault([ + { id: 'a', enabled: true }, + { id: 'b', enabled: false }, + { id: 'c', enabled: true }, + ]), + ['a', 'c'], + ) +}) + +test('a choice toggles in and out', () => { + assert.deepEqual(toggled(['a', 'b'], 'a'), ['b']) + assert.deepEqual(toggled(['b'], 'a'), ['b', 'a']) +}) From 2224571c5cfa9f9ce8cdb12217c84690b5133b0a Mon Sep 17 00:00:00 2001 From: fyui001 Date: Mon, 9 Nov 2026 21:53:50 +0900 Subject: [PATCH 02/24] =?UTF-8?q?=E3=83=99=E3=83=AB=E3=81=AE=E5=9B=B3?= =?UTF-8?q?=E3=81=A8=E9=80=9A=E7=9F=A5=E3=81=AE=E8=A8=80=E3=81=84=E6=96=B9?= =?UTF-8?q?=E3=81=AE=E9=96=A2=E6=95=B0=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- components/vela/icons.tsx | 19 +++++++++++++++++++ lib/notifications.ts | 20 ++++++++++++++++++-- stories/foundations/Icons.stories.tsx | 2 ++ tests/lib/notifications.test.ts | 13 +++++++++++++ tests/storybook/every-test-runs.test.ts | 1 + 5 files changed, 53 insertions(+), 2 deletions(-) diff --git a/components/vela/icons.tsx b/components/vela/icons.tsx index 79bde42c..4718551f 100644 --- a/components/vela/icons.tsx +++ b/components/vela/icons.tsx @@ -691,6 +691,25 @@ export function LinkIcon(props: IconProps) { ) } +export function BellIcon(props: IconProps) { + return ( + + + + + ) +} + +export function BellOffIcon(props: IconProps) { + return ( + + + + + + ) +} + export function CopyIcon(props: IconProps) { return ( diff --git a/lib/notifications.ts b/lib/notifications.ts index e75f9ad4..c2cff1e7 100644 --- a/lib/notifications.ts +++ b/lib/notifications.ts @@ -144,6 +144,22 @@ export function webhookKindOf(address: string): WebhookKind | undefined { : undefined } +export interface AddressReading { + kind?: WebhookKind + refused: boolean +} + +/** What an address typed so far says: the service it will be kept as, or that Carina would refuse it. An empty field says neither. */ +export function readAddress(address: string): AddressReading { + if (address.trim() === '') { + return { refused: false } + } + + const kind = webhookKindOf(address) + + return { kind, refused: kind === undefined } +} + export function registeringAs(kind: WebhookKind): string { return `${KIND_LABEL[kind]} として登録します` } @@ -322,8 +338,8 @@ export function withWhy(said: Said): string { return said.why === undefined ? said.words : `${said.words} · ${said.why}` } -export function deliveryMoment(at: string): string { - return formatMoment(at) +export function deliveryMoment(at: string, now: number = Date.now()): string { + return formatMoment(at, now) } export function deliveryClock(at: string): string { diff --git a/stories/foundations/Icons.stories.tsx b/stories/foundations/Icons.stories.tsx index d1718111..1e50316d 100644 --- a/stories/foundations/Icons.stories.tsx +++ b/stories/foundations/Icons.stories.tsx @@ -99,6 +99,8 @@ const ACTIONS: [string, ComponentType][] = [ ['EyeIcon', Icons.EyeIcon], ['EyeOffIcon', Icons.EyeOffIcon], ['LinkIcon', Icons.LinkIcon], + ['BellIcon', Icons.BellIcon], + ['BellOffIcon', Icons.BellOffIcon], ['CopyIcon', Icons.CopyIcon], ['SunIcon', Icons.SunIcon], ['MoonIcon', Icons.MoonIcon], diff --git a/tests/lib/notifications.test.ts b/tests/lib/notifications.test.ts index e038ebf1..e58b126f 100644 --- a/tests/lib/notifications.test.ts +++ b/tests/lib/notifications.test.ts @@ -12,6 +12,7 @@ import { leadLabel, leadToastWords, nameFits, + readAddress, registeringAs, ruleSetsFull, testSaid, @@ -57,6 +58,18 @@ test('an address Carina refuses has no kind', () => { } }) +test('an empty address says nothing, a refused one says so, and a good one names its kind', () => { + assert.deepEqual(readAddress(' '), { refused: false }) + assert.deepEqual(readAddress('https://hook.example.jp/carina'), { + kind: undefined, + refused: true, + }) + assert.deepEqual(readAddress('https://hooks.slack.com/services/T0'), { + kind: 'slack', + refused: false, + }) +}) + test('the line under the address names the service it will be kept as', () => { assert.equal(registeringAs('slack'), 'Slack として登録します') assert.equal(registeringAs('discord'), 'Discord として登録します') diff --git a/tests/storybook/every-test-runs.test.ts b/tests/storybook/every-test-runs.test.ts index 9219a852..5fe18b37 100644 --- a/tests/storybook/every-test-runs.test.ts +++ b/tests/storybook/every-test-runs.test.ts @@ -133,6 +133,7 @@ const THE_SUITE = [ 'tests/lib/live-wire.test.ts', 'tests/lib/motion.test.ts', 'tests/lib/not-yet-in-this-build.test.ts', + 'tests/lib/notifications.test.ts', 'tests/lib/packed-rows.test.ts', 'tests/lib/path.test.ts', 'tests/lib/phone-bar.test.ts', From 45150496c109c3b16a5b43fee2275a55c0c6bf56 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Mon, 9 Nov 2026 21:53:50 +0900 Subject: [PATCH 03/24] =?UTF-8?q?=E8=A8=AD=E5=AE=9A=E3=81=AE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E3=81=AE=E7=94=BB=E9=9D=A2=E3=81=AE=E9=83=A8=E5=93=81?= =?UTF-8?q?=E3=81=A8=E7=89=A9=E8=AA=9E=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../notifications/add-destination-dialog.tsx | 310 +++++++ components/notifications/delivery-log.tsx | 162 ++++ components/notifications/destination-list.tsx | 248 ++++++ .../notifications/edit-destination-dialog.tsx | 174 ++++ components/notifications/lead-choice.tsx | 42 + components/notifications/notice-dialog.tsx | 106 +++ .../notifications/notifications-page.tsx | 217 +++++ components/notifications/notify-only-row.tsx | 196 +++++ components/notifications/pick-chip.tsx | 71 ++ components/notifications/programme-notice.tsx | 177 ++++ components/notifications/remove-button.tsx | 107 +++ components/notifications/rule-set-dialog.tsx | 223 +++++ components/notifications/rule-set-list.tsx | 215 +++++ components/notifications/webhook-field.tsx | 67 ++ stories/fixtures/notifications.ts | 218 +++++ stories/screens/Notifications.stories.tsx | 765 ++++++++++++++++++ 16 files changed, 3298 insertions(+) create mode 100644 components/notifications/add-destination-dialog.tsx create mode 100644 components/notifications/delivery-log.tsx create mode 100644 components/notifications/destination-list.tsx create mode 100644 components/notifications/edit-destination-dialog.tsx create mode 100644 components/notifications/lead-choice.tsx create mode 100644 components/notifications/notice-dialog.tsx create mode 100644 components/notifications/notifications-page.tsx create mode 100644 components/notifications/notify-only-row.tsx create mode 100644 components/notifications/pick-chip.tsx create mode 100644 components/notifications/programme-notice.tsx create mode 100644 components/notifications/remove-button.tsx create mode 100644 components/notifications/rule-set-dialog.tsx create mode 100644 components/notifications/rule-set-list.tsx create mode 100644 components/notifications/webhook-field.tsx create mode 100644 stories/fixtures/notifications.ts create mode 100644 stories/screens/Notifications.stories.tsx diff --git a/components/notifications/add-destination-dialog.tsx b/components/notifications/add-destination-dialog.tsx new file mode 100644 index 00000000..0c88cd70 --- /dev/null +++ b/components/notifications/add-destination-dialog.tsx @@ -0,0 +1,310 @@ +'use client' + +import { useId, useState, useTransition, type ReactNode } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + nameFits, + readAddress, + type BrowserPermission, + type NotificationWrite, +} from '@/lib/notifications' +import { Button } from '@/components/ui/button' +import { Dialog } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { InlineAlert } from '@/components/vela/banner' +import { Field } from '@/components/vela/field' +import { + BellIcon, + ChevronRightIcon, + LinkIcon, + PlusIcon, +} from '@/components/vela/icons' +import { pressable } from '@/components/vela/tactile' +import { + NoticeDialogContent, + NoticeDialogFooter, + NoticeDialogHeader, + NoticeLabel, +} from '@/components/notifications/notice-dialog' +import { WebhookField } from '@/components/notifications/webhook-field' + +export interface WebhookDraft { + name: string + url: string +} + +export interface BrowserDraft { + name: string +} + +export const ADD_DESTINATION = '送り先を追加' + +const SIGNED_OUT = signedOut('追加') + +export const DENIED_HERE = + 'このブラウザは通知を拒否しています。サイトの設定で許可してください' + +type Step = 'pick' | 'webhook' | 'browser' + +/** `追加` and the dialog it opens: first which kind of destination, then the form for that kind, with a way back to the choice. */ +export function AddDestinationDialog({ + here, + permission, + onAddWebhook, + onAddBrowser, +}: { + here: string + permission: BrowserPermission + onAddWebhook: (draft: WebhookDraft) => Promise + onAddBrowser: (draft: BrowserDraft) => Promise +}) { + const [open, setOpen] = useState(false) + const [step, setStep] = useState('pick') + + const openTo = (next: boolean) => { + setOpen(next) + + if (next) { + setStep('pick') + } + } + + return ( + + + + {step === 'pick' && } + {step === 'webhook' && ( + setStep('pick')} + onClose={() => setOpen(false)} + onAdd={onAddWebhook} + /> + )} + {step === 'browser' && ( + setStep('pick')} + onClose={() => setOpen(false)} + onAdd={onAddBrowser} + /> + )} + + + ) +} + +function KindPicker({ + here, + onPick, +}: { + here: string + onPick: (step: Step) => void +}) { + return ( + <> + +
    + } + name="Slack・Discord" + says="Webhook の URL に送ります" + onPick={() => onPick('webhook')} + /> + } + name="このブラウザ" + says={`${here} に通知を出します`} + onPick={() => onPick('browser')} + /> +
+ + ) +} + +function KindOption({ + icon, + name, + says, + onPick, +}: { + icon: ReactNode + name: string + says: string + onPick: () => void +}) { + return ( +
  • + +
  • + ) +} + +function useAdding(onClose: () => void) { + const [refusal, setRefusal] = useState() + const [pending, startTransition] = useTransition() + + const add = (write: () => Promise) => { + setRefusal(undefined) + + startTransition(async () => { + const result = await write() + + if (result.state === 'ok') { + onClose() + + return + } + + setRefusal( + result.state === 'unauthenticated' ? SIGNED_OUT : result.message, + ) + }) + } + + return { refusal, pending, add } +} + +function WebhookForm({ + onBack, + onClose, + onAdd, +}: { + onBack: () => void + onClose: () => void + onAdd: (draft: WebhookDraft) => Promise +}) { + const id = useId() + const [name, setName] = useState('') + const [url, setUrl] = useState('') + const { refusal, pending, add } = useAdding(onClose) + const { kind } = readAddress(url) + const ready = kind !== undefined && nameFits(name) && !pending + + return ( + <> + +
    + + 名前 + setName(event.target.value)} + /> + + + + {refusal && {refusal}} + +
    + + + + + + ) +} + +function BrowserForm({ + here, + permission, + onBack, + onClose, + onAdd, +}: { + here: string + permission: BrowserPermission + onBack: () => void + onClose: () => void + onAdd: (draft: BrowserDraft) => Promise +}) { + const id = useId() + const [name, setName] = useState(here) + const { refusal, pending, add } = useAdding(onClose) + const denied = permission === 'denied' + + return ( + <> + +
    + + 名前 + setName(event.target.value)} + /> + + + {denied && {DENIED_HERE}} + {refusal && {refusal}} + +
    + + + + + + ) +} diff --git a/components/notifications/delivery-log.tsx b/components/notifications/delivery-log.tsx new file mode 100644 index 00000000..78b75f1b --- /dev/null +++ b/components/notifications/delivery-log.tsx @@ -0,0 +1,162 @@ +'use client' + +import { cn } from '@/lib/utils' +import { + deliveryClock, + deliveryMoment, + deliverySaid, + eventLabelOf, + type NotificationDelivery, + type NotificationDestination, + type Verdict, +} from '@/lib/notifications' +import { Badge } from '@/components/ui/badge' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, +} from '@/components/ui/select' +import { ChipDot } from '@/components/vela/status' + +const EVERY = '__every__' + +export const EVERY_DESTINATION = 'すべての送り先' + +const CHIP_OF: Record = { + ok: 'ok', + warn: 'warn', + err: 'err', + calm: 'mute', +} + +const DOT_OF: Record = { + ok: 'bg-accent', + warn: 'bg-warn', + err: 'bg-rec', + calm: 'bg-ink-3', +} + +/** The columns of the log on a wide window; on a phone the time and destination share the first line, the event the second, and the state stands to the right of both. */ +const ROW_AREAS = cn( + 'grid grid-cols-[calc(150rem/16)_minmax(0,1fr)_calc(190rem/16)_calc(230rem/16)] items-center gap-x-4 px-4', + "[grid-template-areas:'tm_ev_to_st']", + "upright:grid-cols-[minmax(0,1fr)_auto] upright:gap-x-2.5 upright:gap-y-1 upright:px-3.5 upright:py-2.5 upright:[grid-template-areas:'meta_st'_'ev_st']", +) + +/** Which destination's deliveries the log shows: all of them, or one. */ +export function DeliveryFilter({ + destinations, + value, + onChange, +}: { + destinations: Pick[] + value?: string + onChange: (id: string | undefined) => void +}) { + const current = + destinations.find(({ id }) => id === value)?.name ?? EVERY_DESTINATION + + return ( + + ) +} + +export function DeliveryLog({ + deliveries, + now, +}: { + deliveries: NotificationDelivery[] + now: number +}) { + return ( +
    + +
      + {deliveries.map((delivery) => ( + + ))} +
    +
    + ) +} + +function DeliveryRow({ + delivery, + now, +}: { + delivery: NotificationDelivery + now: number +}) { + const said = deliverySaid(delivery) + + return ( +
  • + + + + {deliveryMoment(delivery.at, now)} + + + {deliveryClock(delivery.at)} + + + + + {delivery.destinationName} + + + + + {eventLabelOf(delivery.event)} + + {delivery.subject} + + + + + {said.words} + {said.why && · {said.why}} + + +
  • + ) +} diff --git a/components/notifications/destination-list.tsx b/components/notifications/destination-list.tsx new file mode 100644 index 00000000..5dc8eb89 --- /dev/null +++ b/components/notifications/destination-list.tsx @@ -0,0 +1,248 @@ +'use client' + +import { useState, useTransition } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + KIND_LABEL, + lastResultSaid, + tailOf, + testSaid, + withWhy, + type NotificationDestination, + type NotificationWrite, + type Said, + type TestSending, + type Verdict, +} from '@/lib/notifications' +import { wordFor } from '@/lib/not-yet-in-this-build' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { Switch } from '@/components/ui/switch' +import { Spinner } from '@/components/vela/progress' +import { StatusDot, type StatusTone } from '@/components/vela/status' +import { useToast } from '@/components/vela/toast' +import { + EditDestinationButton, + type DestinationRevision, +} from '@/components/notifications/edit-destination-dialog' +import { RemoveButton } from '@/components/notifications/remove-button' + +export interface DestinationActions { + onToggleDestination: ( + id: string, + enabled: boolean, + ) => Promise + onTestDestination: (id: string) => Promise + onReviseDestination: ( + id: string, + revision: DestinationRevision, + ) => Promise + onRemoveDestination: (id: string) => Promise +} + +export const DOT_OF: Record = { + ok: 'ok', + warn: 'warn', + err: 'err', + calm: 'off', +} + +const LINE_OF: Record = { + ok: 'text-ink-2', + warn: 'text-warn-text', + err: 'text-rec-text', + calm: 'text-ink-2', +} + +const TESTED_OF: Record = { + ok: 'text-acc-text', + warn: 'text-warn-text', + err: 'text-rec-text', + calm: 'text-ink-2', +} + +/** A row of a group, parted from the one above by a hair that starts where its words do. */ +export const GROUP_ROW = + 'relative before:absolute before:top-0 before:right-0 before:left-4 before:h-px before:bg-hair first:before:hidden upright:before:left-3.5' + +/** On a wide window the switch, the answer to a test and the buttons stand to the right of the name; on a phone the switch stays beside the name and the buttons go under it. */ +const ROW_AREAS = cn( + 'grid min-h-[calc(76rem/16)] grid-cols-[minmax(0,1fr)_auto_auto_auto] items-center gap-x-2 px-4 py-3', + "[grid-template-areas:'head_sw_res_acts'_'last_sw_res_acts']", + "upright:grid-cols-[minmax(0,1fr)_auto] upright:px-3.5 upright:[grid-template-areas:'head_sw'_'last_last'_'acts_acts'_'res_res']", +) + +const FLAT_ON_A_PHONE = 'upright:shadow-none' + +const SIGNED_OUT = signedOut('操作') + +function refusalOf(result: Exclude) { + return result.state === 'unauthenticated' ? SIGNED_OUT : result.message +} + +export function DestinationList({ + destinations, + actions, + now, +}: { + destinations: NotificationDestination[] + actions: DestinationActions + now: number +}) { + return ( +
      + {destinations.map((destination) => ( + + ))} +
    + ) +} + +function ResultLine({ said, tail }: { said?: Said; tail?: string }) { + if (!said && !tail) { + return null + } + + return ( + + {said && ( + <> + + {withWhy(said)} + + )} + {tail && ( + + {said && '· '} + {tailOf(tail)} + + )} + + ) +} + +function DestinationRow({ + destination, + actions, + now, +}: { + destination: NotificationDestination + actions: DestinationActions + now: number +}) { + const [enabled, setEnabled] = useState(destination.enabled) + const [tested, setTested] = useState() + const [testing, startTesting] = useTransition() + const say = useToast() + const { id, name, kind, urlTail, lastResult } = destination + const webhook = kind !== 'webPush' + + const toggle = async (next: boolean) => { + setEnabled(next) + + const result = await actions.onToggleDestination(id, next) + + if (result.state !== 'ok') { + setEnabled(!next) + say({ text: refusalOf(result) }) + } + } + + const test = () => + startTesting(async () => { + setTested(undefined) + + const result = await actions.onTestDestination(id) + + if (result.state === 'ok') { + setTested(testSaid(result)) + + return + } + + say({ text: refusalOf(result) }) + }) + + return ( +
  • + + + {name} + + + {wordFor(KIND_LABEL, kind)} + + {urlTail && ( + + {tailOf(urlTail)} + + )} + + + void toggle(next)} + className="mr-2.5 [grid-area:sw] upright:mr-0" + /> + + {tested && withWhy(tested)} + + + + {webhook && ( + + )} + actions.onRemoveDestination(id)} + className={FLAT_ON_A_PHONE} + /> + +
  • + ) +} diff --git a/components/notifications/edit-destination-dialog.tsx b/components/notifications/edit-destination-dialog.tsx new file mode 100644 index 00000000..9be1a045 --- /dev/null +++ b/components/notifications/edit-destination-dialog.tsx @@ -0,0 +1,174 @@ +'use client' + +import { useId, useState, useTransition } from 'react' + +import { signedOut } from '@/lib/signed-out' +import { + KIND_LABEL, + nameFits, + readAddress, + tailOf, + type NotificationDestination, + type NotificationWrite, +} from '@/lib/notifications' +import { wordFor } from '@/lib/not-yet-in-this-build' +import { Button } from '@/components/ui/button' +import { Dialog } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { Switch } from '@/components/ui/switch' +import { InlineAlert } from '@/components/vela/banner' +import { Field } from '@/components/vela/field' +import { + NoticeDialogContent, + NoticeDialogFooter, + NoticeDialogHeader, + NoticeLabel, +} from '@/components/notifications/notice-dialog' +import { WebhookField } from '@/components/notifications/webhook-field' + +/** What changing a destination sends: its name, whether it is on, and a new address only when one was typed. */ +export interface DestinationRevision { + name: string + enabled: boolean + url?: string +} + +const SIGNED_OUT = signedOut('変更') + +export function EditDestinationButton({ + destination, + onRevise, + className, +}: { + destination: NotificationDestination + onRevise: ( + id: string, + revision: DestinationRevision, + ) => Promise + className?: string +}) { + const [open, setOpen] = useState(false) + + return ( + + + + {open && ( + setOpen(false)} + onRevise={onRevise} + /> + )} + + + ) +} + +function EditDestinationForm({ + destination, + onClose, + onRevise, +}: { + destination: NotificationDestination + onClose: () => void + onRevise: ( + id: string, + revision: DestinationRevision, + ) => Promise +}) { + const id = useId() + const [name, setName] = useState(destination.name) + const [url, setUrl] = useState('') + const [enabled, setEnabled] = useState(destination.enabled) + const [refusal, setRefusal] = useState() + const [pending, startTransition] = useTransition() + const webhook = destination.kind !== 'webPush' + const { refused } = readAddress(url) + const ready = nameFits(name) && !refused && !pending + + const save = () => { + setRefusal(undefined) + + startTransition(async () => { + const typed = url.trim() + const result = await onRevise(destination.id, { + name: name.trim(), + enabled, + ...(typed === '' ? {} : { url: typed }), + }) + + if (result.state === 'ok') { + onClose() + + return + } + + setRefusal( + result.state === 'unauthenticated' ? SIGNED_OUT : result.message, + ) + }) + } + + return ( + <> + +
    + + 名前 + setName(event.target.value)} + /> + + {webhook && ( + + )} +
    + + +
    + + {refusal && {refusal}} + +
    + + + + + + ) +} diff --git a/components/notifications/lead-choice.tsx b/components/notifications/lead-choice.tsx new file mode 100644 index 00000000..96b73394 --- /dev/null +++ b/components/notifications/lead-choice.tsx @@ -0,0 +1,42 @@ +'use client' + +import { cn } from '@/lib/utils' +import { LEADS, isLead, leadLabel, type LeadMinutes } from '@/lib/notifications' +import { SegmentedControl } from '@/components/vela/segmented-control' + +const OPTIONS = LEADS.map((lead) => ({ + value: String(lead), + label: leadLabel(lead), +})) + +/** How long before a programme starts its notice is sent: at the start, or one, three, five or ten minutes before. */ +export function LeadChoice({ + value, + onValueChange, + disabled, + className, + 'aria-label': ariaLabel = '何分前', +}: { + value: LeadMinutes + onValueChange: (lead: LeadMinutes) => void + disabled?: boolean + className?: string + 'aria-label'?: string +}) { + return ( + { + const lead = Number(next) + + if (isLead(lead)) { + onValueChange(lead) + } + }} + className={cn('tabular-nums', className)} + /> + ) +} diff --git a/components/notifications/notice-dialog.tsx b/components/notifications/notice-dialog.tsx new file mode 100644 index 00000000..5a259446 --- /dev/null +++ b/components/notifications/notice-dialog.tsx @@ -0,0 +1,106 @@ +'use client' + +import type { ComponentProps, ReactNode } from 'react' + +import { cn } from '@/lib/utils' +import { + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog' +import { IconButton } from '@/components/vela/icon-button' +import { ChevronLeftIcon } from '@/components/vela/icons' +import { FieldLabel } from '@/components/vela/field' + +/** On a phone held upright the dialog is a sheet that rises from the foot of the window, square at the bottom. */ +const SHEET_ON_A_PHONE = cn( + 'upright:top-auto upright:bottom-0 upright:left-0 upright:w-full upright:max-w-none upright:translate-x-0 upright:translate-y-0', + 'upright:max-h-[90dvh] upright:rounded-t-xl upright:rounded-b-none upright:px-4 upright:pt-[calc(18rem/16)] upright:pb-9', + 'upright:[--from-scale:1] upright:[--from-y:24px]', +) + +export function NoticeDialogContent({ + className, + ...props +}: ComponentProps) { + return ( + event.preventDefault()} + className={cn(SHEET_ON_A_PHONE, className)} + {...props} + /> + ) +} + +/** The title row: a way back to the step before when there is one, then the title. The close button is the dialog's own. */ +export function NoticeDialogHeader({ + title, + description, + onBack, +}: { + title: string + description: string + onBack?: () => void +}) { + return ( + + {onBack && ( + + + + )} + {title} + {description} + + ) +} + +/** The buttons at a dialog's foot, to the right, with `削除` alone at the left where there is one; stacked the width of the sheet on a phone, the main one on top. */ +export function NoticeDialogFooter({ + start, + children, +}: { + start?: ReactNode + children: ReactNode +}) { + return ( +
    + {start} + + {children} + +
    + ) +} + +/** A field's name over it, small and quiet, as the rule editor writes it. */ +export function NoticeLabel({ + className, + ...props +}: ComponentProps) { + return ( + + ) +} + +export function NoticeGroupLabel({ + className, + ...props +}: ComponentProps<'span'>) { + return ( + + ) +} diff --git a/components/notifications/notifications-page.tsx b/components/notifications/notifications-page.tsx new file mode 100644 index 00000000..0aa3b98d --- /dev/null +++ b/components/notifications/notifications-page.tsx @@ -0,0 +1,217 @@ +'use client' + +import { useState, type ReactNode } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import type { + BrowserPermission, + LeadMinutes, + NotificationDelivery, + NotificationDestination, + NotificationRuleSet, + NotificationSettings, + NotificationWrite, +} from '@/lib/notifications' +import { Banner } from '@/components/vela/banner' +import { PageHeading } from '@/components/vela/section-heading' +import { SettingsGroup } from '@/components/vela/settings-rows' +import { useToast } from '@/components/vela/toast' +import { + AddDestinationDialog, + type BrowserDraft, + type WebhookDraft, +} from '@/components/notifications/add-destination-dialog' +import { + DeliveryFilter, + DeliveryLog, +} from '@/components/notifications/delivery-log' +import { + DestinationList, + type DestinationActions, +} from '@/components/notifications/destination-list' +import { LeadChoice } from '@/components/notifications/lead-choice' +import { + AddRuleSetButton, + RuleSetList, + type RuleSetActions, +} from '@/components/notifications/rule-set-list' + +export interface NotificationsScreen { + settings: NotificationSettings + destinations: NotificationDestination[] + ruleSets: NotificationRuleSet[] + deliveries: NotificationDelivery[] + /** The destination the log is narrowed to; every destination when absent. */ + deliveriesFor?: string +} + +export interface NotificationActions + extends DestinationActions, RuleSetActions { + onAddWebhook: (draft: WebhookDraft) => Promise + onAddBrowser: (draft: BrowserDraft) => Promise + onSettleLead: (lead: LeadMinutes) => Promise + onShowDeliveriesFor: (destinationId: string | undefined) => void +} + +export const NO_PUBLIC_ORIGIN = + 'リンクを載せるには公開のアドレスの設定が要ります' + +const LEAD_NAME = '単発の通知の既定' + +const SIGNED_OUT = signedOut('変更') + +function GroupTitle({ end, children }: { end?: ReactNode; children: string }) { + return ( +
    +

    {children}

    + {end &&
    {end}
    } +
    + ) +} + +function Nothing({ children }: { children: string }) { + return ( + +

    + {children} +

    +
    + ) +} + +/** Settings > notifications: where notices go, which events go where, how early a programme's start is told, and what was sent lately. */ +export function NotificationsView({ + screen, + actions, + here, + permission, + now, +}: { + screen: NotificationsScreen + actions: NotificationActions + /** This browser as a person names it, `Windows の Chrome`. */ + here: string + permission: BrowserPermission + /** The moment the screen was drawn for, which today's times are said against. */ + now: number +}) { + const { settings, destinations, ruleSets, deliveries } = screen + const [lead, setLead] = useState(settings.leadMinutes) + const [addingRuleSet, setAddingRuleSet] = useState(false) + const say = useToast() + + const settleLead = async (next: LeadMinutes) => { + const was = lead + + setLead(next) + + const result = await actions.onSettleLead(next) + + if (result.state !== 'ok') { + setLead(was) + say({ + text: result.state === 'unauthenticated' ? SIGNED_OUT : result.message, + }) + } + } + + return ( + <> + 通知 + + {!settings.hasPublicOrigin && ( + + {NO_PUBLIC_ORIGIN} + + )} + +
    + + } + > + 送り先 + + {destinations.length > 0 ? ( + + ) : ( + 送り先がありません + )} +
    + +
    + setAddingRuleSet(true)} + /> + } + > + ルールセット + + {ruleSets.length === 0 && ルールセットがありません} + +
    + +
    + 単発の通知 + +
    + + {LEAD_NAME} + + void settleLead(next)} + className={cn( + 'bg-bg', + 'upright:grid upright:grid-cols-5 upright:[&>button]:justify-center upright:[&>button]:px-0 upright:[&>button]:text-sub', + )} + /> +
    +
    +
    + +
    + 0 && ( + + ) + } + > + 直近の配送 + + {deliveries.length > 0 ? ( + + ) : ( + 配送の記録はありません + )} +
    + + ) +} diff --git a/components/notifications/notify-only-row.tsx b/components/notifications/notify-only-row.tsx new file mode 100644 index 00000000..b0e99c45 --- /dev/null +++ b/components/notifications/notify-only-row.tsx @@ -0,0 +1,196 @@ +'use client' + +import { useId, useState, useTransition } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + toggled, + type LeadMinutes, + type NotificationDestination, + type NotificationWrite, + type ProgrammeWatch, +} from '@/lib/notifications' +import { Badge } from '@/components/ui/badge' +import { IconButton } from '@/components/vela/icon-button' +import { CloseIcon } from '@/components/vela/icons' +import { useToast } from '@/components/vela/toast' +import { ROW_GROUND, RowTimes } from '@/components/reservations/reservation-row' +import { LeadChoice } from '@/components/notifications/lead-choice' +import { PickChip, PickChips } from '@/components/notifications/pick-chip' +import { NotifyBell } from '@/components/notifications/programme-notice' +import { NoticeGroupLabel } from '@/components/notifications/notice-dialog' + +/** A single notice as the reservation list shows it: the programme it is for, and when and where to. */ +export interface WatchedProgramme extends ProgrammeWatch { + title: string + channelName: string + startAt: string + endAt: string +} + +export interface WatchActions { + onChangeLead: (id: string, lead: LeadMinutes) => Promise + onChangeDestinations: ( + id: string, + destinationIds: string[], + ) => Promise + onCancel: (id: string) => Promise +} + +export const NOTIFY_ONLY = '通知' + +const FROM_THE_GUIDE = '手動' + +const SIGNED_OUT = signedOut('変更') + +/** The row's grid: the times, the bell and the title over where it came from, then the chip and the ×. Narrower times on a phone. */ +const ROW_GRID = + 'grid min-h-[calc(62rem/16)] grid-cols-[calc(76rem/16)_minmax(0,1fr)_auto] items-center gap-x-5 px-2.5 py-2 upright:grid-cols-[calc(50rem/16)_minmax(0,1fr)_auto] upright:gap-x-2 upright:pr-1.5 upright:pl-2.5' + +const ROW_LINE = + "relative before:absolute before:top-0 before:right-2.5 before:left-[calc(116rem/16)] before:border-t before:border-hair before:content-[''] first:before:hidden data-open:before:opacity-0 [&[data-open]+li]:before:opacity-0 upright:before:left-[calc(70rem/16)]" + +/** A notice that a programme starts, standing among the reservations: a bell where a reservation has its genre's dot, and `通知` where it has its state. Pressing the title opens how early and where to under it. */ +export function NotifyOnlyRow({ + watch, + destinations, + open, + onToggle, + actions, +}: { + watch: WatchedProgramme + destinations: Pick[] + open: boolean + onToggle: () => void + actions: WatchActions +}) { + const panel = useId() + const [lead, setLead] = useState(watch.leadMinutes) + const [sendTo, setSendTo] = useState(watch.destinationIds) + const [pending, startTransition] = useTransition() + const say = useToast() + + const refused = (result: NotificationWrite) => { + if (result.state === 'ok') { + return false + } + + say({ + text: result.state === 'unauthenticated' ? SIGNED_OUT : result.message, + }) + + return true + } + + const changeLead = async (next: LeadMinutes) => { + const was = lead + + setLead(next) + + if (refused(await actions.onChangeLead(watch.id, next))) { + setLead(was) + } + } + + const changeSendTo = async (destinationId: string) => { + const was = sendTo + const next = toggled(sendTo, destinationId) + + setSendTo(next) + + if (refused(await actions.onChangeDestinations(watch.id, next))) { + setSendTo(was) + } + } + + return ( +
  • +
    + + + + + {`${watch.channelName} · ${FROM_THE_GUIDE}`} + + + + {NOTIFY_ONLY} + + startTransition(async () => { + refused(await actions.onCancel(watch.id)) + }) + } + className="text-ink-3" + > + + + +
    + {open && ( +
    +
    + 何分前 + void changeLead(next)} + className="w-fit bg-bg [&>button]:h-7 gap-x-0 [&>button]:px-2 [&>button]:text-sub" + /> +
    +
    + + 送り先 + + + {destinations.map((destination) => ( + void changeSendTo(destination.id)} + className={cn( + 'h-[calc(30rem/16)] pr-3 pl-2.5 text-[calc(13rem/16)]', + !sendTo.includes(destination.id) && + 'bg-bg enabled:hover:bg-surface-2 dark:bg-bg dark:enabled:hover:bg-surface-2', + )} + > + {destination.name} + + ))} + +
    +
    + )} +
  • + ) +} diff --git a/components/notifications/pick-chip.tsx b/components/notifications/pick-chip.tsx new file mode 100644 index 00000000..e7b568a5 --- /dev/null +++ b/components/notifications/pick-chip.tsx @@ -0,0 +1,71 @@ +'use client' + +import type { ReactNode } from 'react' + +import { cn } from '@/lib/utils' +import { CheckIcon } from '@/components/vela/icons' +import { pressable } from '@/components/vela/tactile' + +/** A choice pressed in and out: a tick on the accent's tint while it is in, an empty ring while it is out. */ +export function PickChip({ + on, + onPress, + disabled, + className, + children, +}: { + on: boolean + onPress: () => void + disabled?: boolean + className?: string + children: ReactNode +}) { + return ( + + ) +} + +export function PickChips({ + className, + children, + ...props +}: { + className?: string + children: ReactNode + 'aria-label'?: string + 'aria-labelledby'?: string +}) { + return ( +
    + {children} +
    + ) +} diff --git a/components/notifications/programme-notice.tsx b/components/notifications/programme-notice.tsx new file mode 100644 index 00000000..d6ae9719 --- /dev/null +++ b/components/notifications/programme-notice.tsx @@ -0,0 +1,177 @@ +'use client' + +import { useState, useTransition } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + leadChipWords, + leadToastWords, + type LeadMinutes, + type NotificationWrite, + type ProgrammeWatch, +} from '@/lib/notifications' +import { Button } from '@/components/ui/button' +import { + Popover, + PopoverContent, + PopoverTrigger, +} from '@/components/ui/popover' +import { BellIcon, BellOffIcon, ChevronDownIcon } from '@/components/vela/icons' +import { pressable } from '@/components/vela/tactile' +import { useToast } from '@/components/vela/toast' +import { LeadChoice } from '@/components/notifications/lead-choice' + +export type WatchWrite = + | { state: 'ok'; watch: ProgrammeWatch } + | { state: 'unauthenticated' } + | { state: 'rejected'; message: string } + +export const NOTIFY_START = '放送開始を通知' + +export const STOP_NOTIFYING = '通知を取り消す' + +const SIGNED_OUT = signedOut('通知の設定') + +function refusalOf( + result: Exclude, +): string { + return result.state === 'unauthenticated' ? SIGNED_OUT : result.message +} + +/** Beside `録画予約` in a programme's detail: asks for a notice when the programme starts, without recording it, and once asked takes it back. The toast it leaves offers to take it back too. */ +export function NotifyStartButton({ + watch, + onWatch, + onUnwatch, + className, +}: { + watch?: ProgrammeWatch + onWatch: () => Promise + onUnwatch: () => Promise + className?: string +}) { + const [pending, startTransition] = useTransition() + const say = useToast() + + const unwatch = () => + startTransition(async () => { + const result = await onUnwatch() + + if (result.state !== 'ok') { + say({ text: refusalOf(result) }) + } + }) + + const ask = () => + startTransition(async () => { + const result = await onWatch() + + if (result.state !== 'ok') { + say({ text: refusalOf(result) }) + + return + } + + say({ + text: leadToastWords(result.watch.leadMinutes), + action: { label: '取り消す', onPress: () => void onUnwatch() }, + }) + }) + + if (watch) { + return ( + + ) + } + + return ( + + ) +} + +/** The amber chip a programme wears once its start is to be told, beside its time; pressing it picks how early. */ +export function NotifyLeadChip({ + leadMinutes, + onChangeLead, + defaultOpen, +}: { + leadMinutes: LeadMinutes + onChangeLead: (lead: LeadMinutes) => void + defaultOpen?: boolean +}) { + const [open, setOpen] = useState(defaultOpen ?? false) + + return ( + + + + {leadChipWords(leadMinutes)} + + + + { + onChangeLead(lead) + setOpen(false) + }} + className="bg-transparent p-0" + /> + + + ) +} + +/** The bell a programme is marked with where its start is to be told and it is not recorded: amber like a reservation, told apart by its shape. */ +export function NotifyBell({ + className, + label, +}: { + className?: string + /** Read out in place of the mark where nothing beside it says the same. */ + label?: string +}) { + return ( + + + ) +} diff --git a/components/notifications/remove-button.tsx b/components/notifications/remove-button.tsx new file mode 100644 index 00000000..5419a4e3 --- /dev/null +++ b/components/notifications/remove-button.tsx @@ -0,0 +1,107 @@ +'use client' + +import { useState, useTransition } from 'react' + +import { signedOut } from '@/lib/signed-out' +import type { NotificationWrite } from '@/lib/notifications' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Button } from '@/components/ui/button' +import { InlineAlert } from '@/components/vela/banner' +import { TrashIcon } from '@/components/vela/icons' +import { Spinner } from '@/components/vela/progress' + +const SIGNED_OUT = signedOut('削除') + +/** `削除` and the question it asks before anything goes: the name of what goes, and that it cannot come back. */ +export function RemoveButton({ + what, + name, + onRemove, + onRemoved, + size = 'sm', + className, +}: { + what: '送り先' | 'ルールセット' + name: string + onRemove: () => Promise + onRemoved?: () => void + size?: 'sm' | 'default' + className?: string +}) { + const [open, setOpen] = useState(false) + const [refusal, setRefusal] = useState() + const [pending, startTransition] = useTransition() + + const remove = () => + startTransition(async () => { + setRefusal(undefined) + + const result = await onRemove() + + if (result.state === 'ok') { + setOpen(false) + onRemoved?.() + + return + } + + setRefusal( + result.state === 'unauthenticated' ? SIGNED_OUT : result.message, + ) + }) + + return ( + <> + + + + + + この{what}を削除します + + {name} + 元に戻せません。 + + + + {refusal && {refusal}} + + + キャンセル + { + event.preventDefault() + remove() + }} + > + {pending ? : } + 削除する + + + + + + ) +} diff --git a/components/notifications/rule-set-dialog.tsx b/components/notifications/rule-set-dialog.tsx new file mode 100644 index 00000000..8ddb643c --- /dev/null +++ b/components/notifications/rule-set-dialog.tsx @@ -0,0 +1,223 @@ +'use client' + +import { useId, useState, useTransition } from 'react' + +import { signedOut } from '@/lib/signed-out' +import { + EVENT_GROUPS, + nameFits, + toggled, + type NotificationDestination, + type NotificationEvent, + type NotificationRuleSet, + type NotificationWrite, + type RuleSetDraft, +} from '@/lib/notifications' +import { Button } from '@/components/ui/button' +import { Dialog } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { Switch } from '@/components/ui/switch' +import { InlineAlert } from '@/components/vela/banner' +import { Field } from '@/components/vela/field' +import { + NoticeDialogContent, + NoticeDialogFooter, + NoticeDialogHeader, + NoticeGroupLabel, + NoticeLabel, +} from '@/components/notifications/notice-dialog' +import { PickChip, PickChips } from '@/components/notifications/pick-chip' +import { RemoveButton } from '@/components/notifications/remove-button' + +const SIGNED_OUT = signedOut('保存') + +const FRESH: RuleSetDraft = { + name: '', + enabled: true, + events: [], + destinationIds: [], +} + +/** The editor of a rule set: its name, whether it is on, the events it sends, and where it sends them. `削除` stands only for a rule set that already is. */ +export function RuleSetDialog({ + ruleSet, + destinations, + open, + onOpenChange, + onSave, + onRemove, +}: { + ruleSet?: NotificationRuleSet + destinations: Pick[] + open: boolean + onOpenChange: (open: boolean) => void + onSave: (draft: RuleSetDraft) => Promise + onRemove?: () => Promise +}) { + return ( + + + {open && ( + onOpenChange(false)} + onSave={onSave} + onRemove={onRemove} + /> + )} + + + ) +} + +function RuleSetForm({ + ruleSet, + destinations, + onClose, + onSave, + onRemove, +}: { + ruleSet?: NotificationRuleSet + destinations: Pick[] + onClose: () => void + onSave: (draft: RuleSetDraft) => Promise + onRemove?: () => Promise +}) { + const id = useId() + const from = ruleSet ?? FRESH + const [name, setName] = useState(from.name) + const [enabled, setEnabled] = useState(from.enabled) + const [events, setEvents] = useState(from.events) + const [sendTo, setSendTo] = useState(from.destinationIds) + const [refusal, setRefusal] = useState() + const [pending, startTransition] = useTransition() + const ready = nameFits(name) && sendTo.length > 0 && !pending + const title = ruleSet ? 'ルールセットを変更' : 'ルールセットを追加' + + const save = () => { + setRefusal(undefined) + + startTransition(async () => { + const result = await onSave({ + name: name.trim(), + enabled, + events, + destinationIds: sendTo, + }) + + if (result.state === 'ok') { + onClose() + + return + } + + setRefusal( + result.state === 'unauthenticated' ? SIGNED_OUT : result.message, + ) + }) + } + + return ( + <> + +
    + + 名前 + setName(event.target.value)} + /> + +
    + + +
    +
    + 出来事 +
    + {EVENT_GROUPS.map((group) => ( +
    + + {group.name} + + + {group.events.map(({ event, label }) => ( + setEvents(toggled(events, event))} + > + {label} + + ))} + +
    + ))} +
    +
    +
    + 送り先 + + {destinations.map((destination) => ( + setSendTo(toggled(sendTo, destination.id))} + > + {destination.name} + + ))} + +
    + + {refusal && {refusal}} + +
    + + ) + } + > + + + + + ) +} diff --git a/components/notifications/rule-set-list.tsx b/components/notifications/rule-set-list.tsx new file mode 100644 index 00000000..62bcaca2 --- /dev/null +++ b/components/notifications/rule-set-list.tsx @@ -0,0 +1,215 @@ +'use client' + +import { useState } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + eventsSummary, + ruleSetsFull, + type NotificationDestination, + type NotificationRuleSet, + type NotificationWrite, + type RuleSetDraft, +} from '@/lib/notifications' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { Switch } from '@/components/ui/switch' +import { PlusIcon } from '@/components/vela/icons' +import { pressable } from '@/components/vela/tactile' +import { useToast } from '@/components/vela/toast' +import { GROUP_ROW } from '@/components/notifications/destination-list' +import { RemoveButton } from '@/components/notifications/remove-button' +import { RuleSetDialog } from '@/components/notifications/rule-set-dialog' + +export interface RuleSetActions { + onAddRuleSet: (draft: RuleSetDraft) => Promise + onReviseRuleSet: ( + id: string, + draft: RuleSetDraft, + ) => Promise + onToggleRuleSet: (id: string, enabled: boolean) => Promise + onRemoveRuleSet: (id: string) => Promise +} + +const SIGNED_OUT = signedOut('操作') + +/** On a wide window the switch and the buttons stand to the right; on a phone the switch stays beside the name and the row itself opens the editor. */ +const ROW_AREAS = cn( + 'grid min-h-[calc(76rem/16)] grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-x-2 px-4 py-3', + "[grid-template-areas:'info_sw_acts']", + "upright:grid-cols-[minmax(0,1fr)_auto] upright:items-start upright:px-3.5 upright:[grid-template-areas:'info_sw']", +) + +/** `追加` over the rule sets, which stops at twenty, and before there is anywhere to send to. */ +export function AddRuleSetButton({ + count, + destinations, + onPress, +}: { + count: number + destinations: number + onPress: () => void +}) { + return ( + + ) +} + +export function RuleSetList({ + ruleSets, + destinations, + actions, + adding, + onAddingChange, +}: { + ruleSets: NotificationRuleSet[] + destinations: Pick[] + actions: RuleSetActions + adding: boolean + onAddingChange: (adding: boolean) => void +}) { + const [editing, setEditing] = useState() + const chosen = ruleSets.find(({ id }) => id === editing) + const nameOf = new Map(destinations.map(({ id, name }) => [id, name])) + + return ( + <> + {ruleSets.length > 0 && ( +
      + {ruleSets.map((ruleSet) => ( + { + const name = nameOf.get(id) + + return name === undefined ? [] : [name] + })} + onOpen={() => setEditing(ruleSet.id)} + actions={actions} + /> + ))} +
    + )} + + { + if (!open) { + setEditing(undefined) + onAddingChange(false) + } + }} + onSave={(draft) => + chosen + ? actions.onReviseRuleSet(chosen.id, draft) + : actions.onAddRuleSet(draft) + } + onRemove={chosen && (() => actions.onRemoveRuleSet(chosen.id))} + /> + + ) +} + +function RuleSetRow({ + ruleSet, + sendsTo, + onOpen, + actions, +}: { + ruleSet: NotificationRuleSet + sendsTo: string[] + onOpen: () => void + actions: RuleSetActions +}) { + const [enabled, setEnabled] = useState(ruleSet.enabled) + const say = useToast() + const { id, name } = ruleSet + + const toggle = async (next: boolean) => { + setEnabled(next) + + const result = await actions.onToggleRuleSet(id, next) + + if (result.state !== 'ok') { + setEnabled(!next) + say({ + text: result.state === 'unauthenticated' ? SIGNED_OUT : result.message, + }) + } + } + + return ( +
  • + + void toggle(next)} + className="mr-2.5 [grid-area:sw] upright:mr-0" + /> + + + actions.onRemoveRuleSet(id)} + /> + +
  • + ) +} diff --git a/components/notifications/webhook-field.tsx b/components/notifications/webhook-field.tsx new file mode 100644 index 00000000..f501f8c4 --- /dev/null +++ b/components/notifications/webhook-field.tsx @@ -0,0 +1,67 @@ +'use client' + +import { useState, type ReactNode } from 'react' + +import { readAddress, registeringAs } from '@/lib/notifications' +import { Input } from '@/components/ui/input' +import { InlineAlert } from '@/components/vela/banner' +import { Field, FieldHint } from '@/components/vela/field' +import { CheckIcon } from '@/components/vela/icons' +import { NoticeLabel } from '@/components/notifications/notice-dialog' + +export const REFUSED_ADDRESS = 'この URL は受け付けられません' + +/** A webhook's address, saying under it as it is typed which service it is for, and once the field is left whether it would be refused. */ +export function WebhookField({ + id, + value, + onChange, + placeholder, + hint, +}: { + id: string + value: string + onChange: (next: string) => void + placeholder?: string + hint: ReactNode +}) { + const [typing, setTyping] = useState(false) + const { kind, refused } = readAddress(value) + const saysRefused = refused && !typing + const alertId = `${id}-refused` + + return ( + + Webhook の URL + setTyping(true)} + onBlur={() => setTyping(false)} + onChange={(event) => onChange(event.target.value)} + className="tabular-nums" + /> + + {kind && ( + + + {registeringAs(kind)} + + )} + {saysRefused && ( + + {REFUSED_ADDRESS} + + )} + + {hint} + + ) +} diff --git a/stories/fixtures/notifications.ts b/stories/fixtures/notifications.ts new file mode 100644 index 00000000..6004b32c --- /dev/null +++ b/stories/fixtures/notifications.ts @@ -0,0 +1,218 @@ +import type { + NotificationDelivery, + NotificationDestination, + NotificationRuleSet, +} from '@/lib/notifications' +import type { NotificationsScreen } from '@/components/notifications/notifications-page' +import type { WatchedProgramme } from '@/components/notifications/notify-only-row' + +export const NOTIFICATIONS_NOW = Date.parse('2026-11-09T12:30:00Z') + +export const HOME_SLACK: NotificationDestination = { + id: 'dest-slack', + name: '家の Slack', + kind: 'slack', + urlTail: 'a1b2', + enabled: true, + lastResult: { state: 'sent', at: '2026-11-09T12:03:00Z' }, +} + +export const DISCORD_ROOM: NotificationDestination = { + id: 'dest-discord', + name: 'Discord の通知部屋', + kind: 'discord', + urlTail: '9f3e', + enabled: true, + lastResult: { + state: 'failed', + at: '2026-11-09T11:58:00Z', + failure: 'timeout', + }, +} + +export const IPAD_SAFARI: NotificationDestination = { + id: 'dest-ipad', + name: 'iPad の Safari', + kind: 'webPush', + enabled: true, + lastResult: { state: 'sent', at: '2026-11-09T12:03:00Z' }, +} + +export const DESTINATIONS: NotificationDestination[] = [ + HOME_SLACK, + DISCORD_ROOM, + IPAD_SAFARI, +] + +export const ONLY_WHEN_TROUBLED: NotificationRuleSet = { + id: 'rule-trouble', + name: '困ったときだけ', + enabled: true, + events: [ + 'recordingTruncated', + 'recordingFailed', + 'encodeFailed', + 'reservationCompeting', + 'reservationMissed', + 'qualityRaised', + 'deviceDisconnected', + ], + destinationIds: [HOME_SLACK.id, IPAD_SAFARI.id], +} + +export const RULE_SETS: NotificationRuleSet[] = [ + ONLY_WHEN_TROUBLED, + { + id: 'rule-record', + name: '録画の記録', + enabled: true, + events: ['recordingStarted', 'recordingCompleted', 'encodeCompleted'], + destinationIds: [DISCORD_ROOM.id], + }, + { + id: 'rule-away', + name: '留守の週', + enabled: false, + events: [ + 'recordingStarted', + 'recordingCompleted', + 'recordingTruncated', + 'recordingFailed', + 'encodeStarted', + 'encodeCompleted', + 'encodeFailed', + 'qualityRaised', + 'qualityResolved', + ], + destinationIds: [HOME_SLACK.id, DISCORD_ROOM.id], + }, +] + +const HARBOUR_RECIPES = '港町レシピ帖 #15「灯台守のパン」' + +function delivery( + id: string, + at: string, + event: NotificationDelivery['event'], + subject: string, + to: NotificationDestination, + state: NotificationDelivery['state'] = 'sent', + failure?: NotificationDelivery['failure'], +): NotificationDelivery { + return { + id, + at, + event, + subject, + destinationId: to.id, + destinationName: to.name, + state, + failure, + } +} + +export const DELIVERIES: NotificationDelivery[] = [ + delivery( + 'del-1', + '2026-11-09T12:03:00Z', + 'recordingTruncated', + HARBOUR_RECIPES, + HOME_SLACK, + ), + delivery( + 'del-2', + '2026-11-09T12:03:00Z', + 'recordingTruncated', + HARBOUR_RECIPES, + IPAD_SAFARI, + ), + delivery( + 'del-3', + '2026-11-09T11:58:00Z', + 'encodeCompleted', + 'ちびっこ忍者 第12話', + DISCORD_ROOM, + 'failed', + 'timeout', + ), + delivery( + 'del-4', + '2026-11-09T11:54:00Z', + 'recordingCompleted', + 'ドラマ「ひだまり荘の人々」#18', + DISCORD_ROOM, + ), + delivery( + 'del-5', + '2026-11-09T11:15:00Z', + 'recordingStarted', + HARBOUR_RECIPES, + DISCORD_ROOM, + ), + delivery( + 'del-6', + '2026-11-09T10:27:00Z', + 'programmeStarting', + 'ドキュメント 灯りの仕事', + HOME_SLACK, + ), + delivery( + 'del-7', + '2026-11-09T09:40:00Z', + 'reservationCompeting', + '深夜ドラマ「灯台守の娘」#3', + HOME_SLACK, + 'givenUp', + 'rejected', + ), + delivery( + 'del-8', + '2026-11-09T09:12:00Z', + 'qualityRaised', + '中央テレビ · ドロップ率', + IPAD_SAFARI, + ), +] + +export const NOTIFICATIONS_SCREEN: NotificationsScreen = { + settings: { leadMinutes: 3, hasPublicOrigin: false }, + destinations: DESTINATIONS, + ruleSets: RULE_SETS, + deliveries: DELIVERIES, +} + +export const EMPTY_NOTIFICATIONS_SCREEN: NotificationsScreen = { + settings: { leadMinutes: 3, hasPublicOrigin: true }, + destinations: [], + ruleSets: [], + deliveries: [], +} + +export const TWENTY_RULE_SETS: NotificationRuleSet[] = Array.from( + { length: 20 }, + (_, nth) => ({ + ...ONLY_WHEN_TROUBLED, + id: `rule-${nth + 1}`, + name: `ルールセット ${nth + 1}`, + }), +) + +export const WATCHED_DOCUMENTARY: WatchedProgramme = { + id: 'watch-doc', + title: 'ドキュメント 灯りの仕事「夜の港、最後の便まで」', + channelName: 'みなと総合1', + startAt: '2026-11-09T10:30:00Z', + endAt: '2026-11-09T11:15:00Z', + leadMinutes: 3, + destinationIds: [HOME_SLACK.id, IPAD_SAFARI.id], +} + +export const WATCHED_FOOTBALL: WatchedProgramme = { + id: 'watch-football', + title: 'サッカー中継 湾岸カップ 準決勝', + channelName: '第一テレビ', + startAt: '2026-11-09T13:00:00Z', + endAt: '2026-11-09T14:30:00Z', + leadMinutes: 5, + destinationIds: [HOME_SLACK.id], +} diff --git a/stories/screens/Notifications.stories.tsx b/stories/screens/Notifications.stories.tsx new file mode 100644 index 00000000..b53f91da --- /dev/null +++ b/stories/screens/Notifications.stories.tsx @@ -0,0 +1,765 @@ +import type { Meta, StoryObj } from '@storybook/nextjs' +import { useState } from 'react' +import { expect, fn, screen, userEvent, waitFor, within } from 'storybook/test' + +import type { NotificationWrite, TestSending } from '@/lib/notifications' +import { + NO_PUBLIC_ORIGIN, + NotificationsView, + type NotificationActions, +} from '@/components/notifications/notifications-page' +import { DENIED_HERE } from '@/components/notifications/add-destination-dialog' +import { REFUSED_ADDRESS } from '@/components/notifications/webhook-field' +import { inTheSettings } from '@/stories/frames' +import { PHONE } from '@/stories/rows-as-cards' +import { + DESTINATIONS, + DISCORD_ROOM, + EMPTY_NOTIFICATIONS_SCREEN, + HOME_SLACK, + NOTIFICATIONS_NOW, + NOTIFICATIONS_SCREEN, + TWENTY_RULE_SETS, +} from '@/stories/fixtures/notifications' + +const OK: NotificationWrite = { state: 'ok' } + +const SLACK_ADDRESS = 'https://hooks.slack.com/services/T0AB12CD/B0EF34GH/a1b2' + +const DISCORD_ADDRESS = 'https://discord.com/api/webhooks/1234567890/9f3e' + +const REFUSED = 'https://hook.example.jp/carina' + +const addWebhook = fn(async () => OK) + +const addBrowser = fn(async () => OK) + +const toggleDestination = fn( + async () => OK, +) + +const testDestination = fn( + async (id): Promise => + id === DISCORD_ROOM.id + ? { state: 'ok', delivered: false, failure: 'timeout' } + : { state: 'ok', delivered: true }, +) + +const reviseDestination = fn( + async () => OK, +) + +const removeDestination = fn( + async () => OK, +) + +const addRuleSet = fn(async () => OK) + +const reviseRuleSet = fn(async () => OK) + +const toggleRuleSet = fn(async () => OK) + +const removeRuleSet = fn(async () => OK) + +const settleLead = fn(async () => OK) + +const showDeliveriesFor = fn() + +const ACTIONS: NotificationActions = { + onAddWebhook: addWebhook, + onAddBrowser: addBrowser, + onToggleDestination: toggleDestination, + onTestDestination: testDestination, + onReviseDestination: reviseDestination, + onRemoveDestination: removeDestination, + onAddRuleSet: addRuleSet, + onReviseRuleSet: reviseRuleSet, + onToggleRuleSet: toggleRuleSet, + onRemoveRuleSet: removeRuleSet, + onSettleLead: settleLead, + onShowDeliveriesFor: showDeliveriesFor, +} + +const meta = { + title: 'Screens/設定・通知', + component: NotificationsView, + parameters: { + nextjs: { + appDirectory: true, + navigation: { pathname: '/settings/notifications' }, + }, + layout: 'fullscreen', + }, + args: { + screen: NOTIFICATIONS_SCREEN, + actions: ACTIONS, + here: 'Windows の Chrome', + permission: 'default', + now: NOTIFICATIONS_NOW, + }, + decorators: [inTheSettings], +} satisfies Meta + +export default meta +type Story = StoryObj + +async function openThePicker(canvasElement: HTMLElement) { + const canvas = within(canvasElement) + const destinations = canvas.getByRole('heading', { name: '送り先' }) + .parentElement as HTMLElement + + await userEvent.click( + within(destinations).getByRole('button', { name: '追加' }), + ) + + return screen.findByRole('dialog', { name: '送り先を追加' }) +} + +async function openTheWebhookForm(canvasElement: HTMLElement) { + const dialog = await openThePicker(canvasElement) + + await userEvent.click( + within(dialog).getByRole('button', { name: /Slack・Discord/ }), + ) + + return dialog +} + +async function openTheBrowserForm(canvasElement: HTMLElement) { + const dialog = await openThePicker(canvasElement) + + await userEvent.click( + within(dialog).getByRole('button', { name: /このブラウザ/ }), + ) + + return dialog +} + +export const 通常: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + const destinations = within(canvas.getByRole('list', { name: '送り先' })) + + await expect(canvas.getByText(NO_PUBLIC_ORIGIN)).toBeVisible() + await expect(destinations.getAllByRole('listitem')).toHaveLength(3) + await expect( + destinations.getByText('届いていない · 時間切れ'), + ).toBeVisible() + await expect( + destinations.getByRole('button', { name: '家の Slack を変更' }), + ).toBeVisible() + await expect( + destinations.queryByRole('button', { name: 'iPad の Safari を変更' }), + ).toBeNull() + await expect( + canvas.getByText( + '録画の欠け・失敗 · エンコードの失敗 · 競合・取り逃し · 異常の発生 · 切断', + ), + ).toBeVisible() + await expect( + within(canvas.getByRole('group', { name: '単発の通知の既定' })).getByRole( + 'button', + { name: '3 分前' }, + ), + ).toHaveAttribute('aria-pressed', 'true') + await expect( + within(canvas.getByRole('list', { name: '直近の配送' })).getAllByRole( + 'listitem', + ), + ).toHaveLength(8) + }, +} + +export const 公開のアドレスがある: Story = { + args: { + screen: { + ...NOTIFICATIONS_SCREEN, + settings: { leadMinutes: 3, hasPublicOrigin: true }, + }, + }, + play: async ({ canvasElement }) => { + await expect(within(canvasElement).queryByText(NO_PUBLIC_ORIGIN)).toBeNull() + }, +} + +export const 何もない: Story = { + args: { screen: EMPTY_NOTIFICATIONS_SCREEN }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await expect(canvas.getByText('送り先がありません')).toBeVisible() + await expect(canvas.getByText('ルールセットがありません')).toBeVisible() + await expect(canvas.getByText('配送の記録はありません')).toBeVisible() + + const ruleSets = canvas.getByRole('heading', { name: 'ルールセット' }) + .parentElement as HTMLElement + + await expect( + within(ruleSets).getByRole('button', { name: '追加' }), + ).toBeDisabled() + }, +} + +export const テスト送信: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + testDestination.mockClear() + + await userEvent.click( + canvas.getByRole('button', { name: '家の Slack にテスト送信' }), + ) + await userEvent.click( + canvas.getByRole('button', { name: 'Discord の通知部屋 にテスト送信' }), + ) + + await waitFor(() => expect(testDestination).toHaveBeenCalledTimes(2)) + await expect(await canvas.findByText('届いた')).toBeVisible() + await expect( + await canvas.findByText('届かなかった · 時間切れ'), + ).toBeVisible() + }, +} + +export const 有効を切り替える: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + const slack = canvas.getByRole('switch', { + name: '家の Slack を有効にする', + }) + + toggleDestination.mockClear() + + await userEvent.click(slack) + + await waitFor(() => + expect(toggleDestination).toHaveBeenCalledWith(HOME_SLACK.id, false), + ) + await expect(slack).not.toBeChecked() + }, +} + +export const 切り替えを断られる: Story = { + args: { + actions: { + ...ACTIONS, + onToggleRuleSet: async () => ({ + state: 'rejected', + message: 'このルールセットは残っていないため、変更できませんでした。', + }), + }, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + const away = canvas.getByRole('switch', { name: '留守の週 を有効にする' }) + + await userEvent.click(away) + + await expect( + await screen.findByText( + 'このルールセットは残っていないため、変更できませんでした。', + ), + ).toBeVisible() + await waitFor(() => expect(away).not.toBeChecked()) + }, +} + +export const 単発の通知の既定を変える: Story = { + play: async ({ canvasElement }) => { + const lead = within( + within(canvasElement).getByRole('group', { name: '単発の通知の既定' }), + ) + + settleLead.mockClear() + + await userEvent.click(lead.getByRole('button', { name: '5 分前' })) + + await waitFor(() => expect(settleLead).toHaveBeenCalledWith(5)) + await expect(lead.getByRole('button', { name: '5 分前' })).toHaveAttribute( + 'aria-pressed', + 'true', + ) + }, +} + +/** The log narrowed to one destination, as the page would answer the URL it is given. */ +function NarrowedLog(args: Story['args']) { + const [only, setOnly] = useState() + + return ( + only === undefined || delivery.destinationId === only, + ), + }} + actions={{ ...ACTIONS, onShowDeliveriesFor: setOnly }} + /> + ) +} + +export const 配送を送り先で絞る: Story = { + render: (args) => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('combobox', { name: '送り先' })) + await userEvent.click( + await screen.findByRole('option', { name: 'Discord の通知部屋' }), + ) + + await waitFor(() => + expect( + within(canvas.getByRole('list', { name: '直近の配送' })).getAllByRole( + 'listitem', + ), + ).toHaveLength(3), + ) + await expect( + canvas.getByRole('combobox', { name: '送り先' }), + ).toHaveTextContent('Discord の通知部屋') + }, +} + +export const 送り先を追加_種類を選ぶ: Story = { + play: async ({ canvasElement }) => { + const dialog = within(await openThePicker(canvasElement)) + + await expect( + dialog.getByRole('button', { name: /Webhook の URL に送ります/ }), + ).toBeVisible() + await expect( + dialog.getByText('Windows の Chrome に通知を出します'), + ).toBeVisible() + }, +} + +export const 送り先を追加_Slack: Story = { + play: async ({ canvasElement }) => { + const dialog = within(await openTheWebhookForm(canvasElement)) + const add = dialog.getByRole('button', { name: '追加' }) + + await expect(add).toBeDisabled() + + await userEvent.type(dialog.getByLabelText('名前'), '家の Slack') + await userEvent.type(dialog.getByLabelText('Webhook の URL'), SLACK_ADDRESS) + + await expect(dialog.getByText('Slack として登録します')).toBeVisible() + await expect( + dialog.getByText('保存したあとは末尾だけが見えます'), + ).toBeVisible() + await expect(add).toBeEnabled() + }, +} + +export const 送り先を追加する: Story = { + play: async ({ canvasElement }) => { + const dialog = within(await openTheWebhookForm(canvasElement)) + + addWebhook.mockClear() + + await userEvent.type(dialog.getByLabelText('名前'), '家の Slack') + await userEvent.type(dialog.getByLabelText('Webhook の URL'), SLACK_ADDRESS) + await userEvent.click(dialog.getByRole('button', { name: '追加' })) + + await waitFor(() => + expect(addWebhook).toHaveBeenCalledWith({ + name: '家の Slack', + url: SLACK_ADDRESS, + }), + ) + await waitFor(() => + expect(screen.queryByRole('dialog', { name: '送り先を追加' })).toBeNull(), + ) + }, +} + +export const 送り先を追加_Discord: Story = { + play: async ({ canvasElement }) => { + const dialog = within(await openTheWebhookForm(canvasElement)) + + await userEvent.type(dialog.getByLabelText('名前'), 'Discord の通知部屋') + await userEvent.type( + dialog.getByLabelText('Webhook の URL'), + DISCORD_ADDRESS, + ) + + await expect(dialog.getByText('Discord として登録します')).toBeVisible() + await expect(dialog.getByRole('button', { name: '追加' })).toBeEnabled() + }, +} + +export const 送り先を追加_受け付けないURL: Story = { + play: async ({ canvasElement }) => { + const dialog = within(await openTheWebhookForm(canvasElement)) + const address = dialog.getByLabelText('Webhook の URL') + + await userEvent.type(dialog.getByLabelText('名前'), '自作の受け口') + await userEvent.type(address, REFUSED) + + await expect(dialog.queryByText(REFUSED_ADDRESS)).toBeNull() + + await userEvent.tab() + + await expect(dialog.getByText(REFUSED_ADDRESS)).toBeVisible() + await expect(address).toHaveAttribute('aria-invalid', 'true') + await expect(dialog.getByRole('button', { name: '追加' })).toBeDisabled() + }, +} + +export const 送り先を追加_戻る: Story = { + play: async ({ canvasElement }) => { + const dialog = within(await openTheWebhookForm(canvasElement)) + + await userEvent.click(dialog.getByRole('button', { name: '戻る' })) + + await expect( + dialog.getByRole('button', { name: /Slack・Discord/ }), + ).toBeVisible() + await expect(dialog.queryByRole('button', { name: '戻る' })).toBeNull() + }, +} + +export const 送り先を追加_このブラウザ: Story = { + play: async ({ canvasElement }) => { + const dialog = within(await openTheBrowserForm(canvasElement)) + + addBrowser.mockClear() + + await expect(dialog.getByLabelText('名前')).toHaveValue('Windows の Chrome') + + await userEvent.click(dialog.getByRole('button', { name: '許可して追加' })) + + await waitFor(() => + expect(addBrowser).toHaveBeenCalledWith({ name: 'Windows の Chrome' }), + ) + }, +} + +export const 送り先を追加_通知を拒否している: Story = { + args: { permission: 'denied' }, + play: async ({ canvasElement }) => { + const dialog = within(await openTheBrowserForm(canvasElement)) + + await expect(dialog.getByText(DENIED_HERE)).toBeVisible() + await expect( + dialog.getByRole('button', { name: '許可して追加' }), + ).toBeDisabled() + }, +} + +export const 送り先の追加を断られる: Story = { + args: { + actions: { + ...ACTIONS, + onAddWebhook: async () => ({ + state: 'rejected', + message: 'この URL は受け付けられません。', + }), + }, + }, + play: async ({ canvasElement }) => { + const dialog = within(await openTheWebhookForm(canvasElement)) + + await userEvent.type(dialog.getByLabelText('名前'), '家の Slack') + await userEvent.type(dialog.getByLabelText('Webhook の URL'), SLACK_ADDRESS) + await userEvent.click(dialog.getByRole('button', { name: '追加' })) + + await expect( + await dialog.findByText('この URL は受け付けられません。'), + ).toBeVisible() + }, +} + +export const 送り先を変更: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click( + canvas.getByRole('button', { name: '家の Slack を変更' }), + ) + + const dialog = within( + await screen.findByRole('dialog', { name: '送り先を変更' }), + ) + const address = dialog.getByLabelText('Webhook の URL') + + await expect(dialog.getByLabelText('名前')).toHaveValue('家の Slack') + await expect(address).toHaveValue('') + await expect(address).toHaveAttribute( + 'placeholder', + '変えないときは空のまま', + ) + await expect(dialog.getByText('Slack · 末尾 …a1b2')).toBeVisible() + await expect(dialog.getByRole('switch', { name: '有効' })).toBeChecked() + }, +} + +export const 送り先の変更を保存する: Story = { + play: async ({ canvasElement }) => { + reviseDestination.mockClear() + + await userEvent.click( + within(canvasElement).getByRole('button', { name: '家の Slack を変更' }), + ) + + const dialog = within( + await screen.findByRole('dialog', { name: '送り先を変更' }), + ) + + await userEvent.click(dialog.getByRole('button', { name: '保存' })) + + await waitFor(() => + expect(reviseDestination).toHaveBeenCalledWith(HOME_SLACK.id, { + name: '家の Slack', + enabled: true, + }), + ) + }, +} + +export const 送り先を削除: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + removeDestination.mockClear() + + await userEvent.click( + canvas.getByRole('button', { name: 'Discord の通知部屋 を削除' }), + ) + + const asked = within(await screen.findByRole('alertdialog')) + + await expect(asked.getByText('この送り先を削除します')).toBeVisible() + await expect(asked.getByText('Discord の通知部屋')).toBeVisible() + + await userEvent.click(asked.getByRole('button', { name: '削除する' })) + + await waitFor(() => + expect(removeDestination).toHaveBeenCalledWith(DISCORD_ROOM.id), + ) + }, +} + +export const ルールセットを変更: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click( + canvas.getByRole('button', { name: '困ったときだけ を変更' }), + ) + + const dialog = within( + await screen.findByRole('dialog', { name: 'ルールセットを変更' }), + ) + const recording = within(dialog.getByRole('group', { name: '録画' })) + const to = within(dialog.getByRole('group', { name: '送り先' })) + + await expect(dialog.getByLabelText('名前')).toHaveValue('困ったときだけ') + await expect( + recording.getByRole('button', { name: '開始' }), + ).toHaveAttribute('aria-pressed', 'false') + await expect( + recording.getByRole('button', { name: '欠け' }), + ).toHaveAttribute('aria-pressed', 'true') + await expect( + to.getByRole('button', { name: 'Discord の通知部屋' }), + ).toHaveAttribute('aria-pressed', 'false') + await expect( + dialog.getByRole('button', { name: '困ったときだけ を削除' }), + ).toBeVisible() + }, +} + +export const ルールセットを保存する: Story = { + play: async ({ canvasElement }) => { + reviseRuleSet.mockClear() + + await userEvent.click( + within(canvasElement).getByRole('button', { + name: '困ったときだけ を変更', + }), + ) + + const dialog = within( + await screen.findByRole('dialog', { name: 'ルールセットを変更' }), + ) + const recording = within(dialog.getByRole('group', { name: '録画' })) + + await userEvent.click(recording.getByRole('button', { name: '開始' })) + await userEvent.click(dialog.getByRole('button', { name: '保存' })) + + await waitFor(() => + expect(reviseRuleSet).toHaveBeenCalledWith( + 'rule-trouble', + expect.objectContaining({ + events: expect.arrayContaining(['recordingStarted']), + }), + ), + ) + }, +} + +export const ルールセットを追加: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + const ruleSets = canvas.getByRole('heading', { name: 'ルールセット' }) + .parentElement as HTMLElement + + addRuleSet.mockClear() + + await userEvent.click( + within(ruleSets).getByRole('button', { name: '追加' }), + ) + + const dialog = within( + await screen.findByRole('dialog', { name: 'ルールセットを追加' }), + ) + const save = dialog.getByRole('button', { name: '保存' }) + + await expect(save).toBeDisabled() + await expect(dialog.queryByRole('button', { name: /を削除/ })).toBeNull() + + await userEvent.type(dialog.getByLabelText('名前'), '夜中の失敗') + await userEvent.click( + within(dialog.getByRole('group', { name: '録画' })).getByRole('button', { + name: '失敗', + }), + ) + + await expect(save).toBeDisabled() + + await userEvent.click( + within(dialog.getByRole('group', { name: '送り先' })).getByRole( + 'button', + { name: '家の Slack' }, + ), + ) + await userEvent.click(save) + + await waitFor(() => + expect(addRuleSet).toHaveBeenCalledWith({ + name: '夜中の失敗', + enabled: true, + events: ['recordingFailed'], + destinationIds: [HOME_SLACK.id], + }), + ) + }, +} + +export const ルールセットが上限: Story = { + args: { + screen: { ...NOTIFICATIONS_SCREEN, ruleSets: TWENTY_RULE_SETS }, + }, + play: async ({ canvasElement }) => { + const ruleSets = within(canvasElement).getByRole('heading', { + name: 'ルールセット', + }).parentElement as HTMLElement + + await expect( + within(ruleSets).getByRole('button', { name: '追加' }), + ).toBeDisabled() + }, +} + +export const 電話: Story = { + parameters: { screen: PHONE, coarse: true }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + const slack = within( + canvas + .getByRole('list', { name: '送り先' }) + .querySelector(`[data-destination="${HOME_SLACK.id}"]`) as HTMLElement, + ) + + await expect(slack.getByText('· …a1b2')).toBeVisible() + await expect( + canvas.queryByRole('button', { name: '困ったときだけ を変更' }), + ).toBeNull() + }, +} + +export const 電話_送り先を追加: Story = { + parameters: { screen: PHONE, coarse: true }, + args: { here: 'iPhone の Safari' }, + play: async ({ canvasElement }) => { + const dialog = await openThePicker(canvasElement) + const sheet = dialog.getBoundingClientRect() + + await expect( + within(dialog).getByText('iPhone の Safari に通知を出します'), + ).toBeVisible() + await expect(Math.round(sheet.bottom)).toBe(window.innerHeight) + await expect(Math.round(sheet.width)).toBe(window.innerWidth) + }, +} + +export const 電話_このブラウザ: Story = { + parameters: { screen: PHONE, coarse: true }, + args: { here: 'iPhone の Safari' }, + play: async ({ canvasElement }) => { + const dialog = within(await openTheBrowserForm(canvasElement)) + + await expect(dialog.getByLabelText('名前')).toHaveValue('iPhone の Safari') + }, +} + +export const 電話_ルールセットを変更: Story = { + parameters: { screen: PHONE, coarse: true }, + play: async ({ canvasElement }) => { + const ruleSets = within( + within(canvasElement).getByRole('list', { name: 'ルールセット' }), + ) + + await userEvent.click(ruleSets.getByRole('button', { name: /^録画の記録/ })) + + const dialog = await screen.findByRole('dialog', { + name: 'ルールセットを変更', + }) + + await expect(within(dialog).getByLabelText('名前')).toHaveValue( + '録画の記録', + ) + await expect(Math.round(dialog.getBoundingClientRect().bottom)).toBe( + window.innerHeight, + ) + }, +} + +export const 送り先が多い: Story = { + args: { + screen: { + ...NOTIFICATIONS_SCREEN, + destinations: [ + ...DESTINATIONS, + { + ...HOME_SLACK, + id: 'dest-slack-2', + name: '実家のリビングの Slack のお知らせ用チャンネル', + urlTail: 'c3d4', + enabled: false, + lastResult: { + state: 'givenUp', + at: '2026-11-08T12:03:00Z', + failure: 'rejected', + }, + }, + ], + }, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await expect( + canvas.getByRole('switch', { + name: '実家のリビングの Slack のお知らせ用チャンネル を有効にする', + }), + ).not.toBeChecked() + await expect(canvas.getByText('届かなかった · 断られた')).toBeVisible() + }, +} From a233559e5f7152519240d9b54c9cbeb83ef759dd Mon Sep 17 00:00:00 2001 From: fyui001 Date: Mon, 9 Nov 2026 21:53:50 +0900 Subject: [PATCH 04/24] =?UTF-8?q?=E5=8D=98=E7=99=BA=E3=81=AE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E3=81=AE=E3=83=9C=E3=82=BF=E3=83=B3=E3=81=A8=E6=9C=AD?= =?UTF-8?q?=E3=81=A8=E3=83=99=E3=83=AB=E3=81=A8=E4=BA=88=E7=B4=84=E4=B8=80?= =?UTF-8?q?=E8=A6=A7=E3=81=AE=E8=A1=8C=E3=81=AE=E7=89=A9=E8=AA=9E=E3=82=92?= =?UTF-8?q?=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../components/ProgrammeNotice.stories.tsx | 400 ++++++++++++++++++ 1 file changed, 400 insertions(+) create mode 100644 stories/components/ProgrammeNotice.stories.tsx diff --git a/stories/components/ProgrammeNotice.stories.tsx b/stories/components/ProgrammeNotice.stories.tsx new file mode 100644 index 00000000..bddb792c --- /dev/null +++ b/stories/components/ProgrammeNotice.stories.tsx @@ -0,0 +1,400 @@ +import type { Meta, StoryObj } from '@storybook/nextjs' +import { useState } from 'react' +import { expect, fn, screen, userEvent, waitFor, within } from 'storybook/test' + +import type { + LeadMinutes, + NotificationWrite, + ProgrammeWatch, +} from '@/lib/notifications' +import { + NOTIFY_START, + NotifyBell, + NotifyLeadChip, + NotifyStartButton, + STOP_NOTIFYING, + type WatchWrite, +} from '@/components/notifications/programme-notice' +import { + NOTIFY_ONLY, + NotifyOnlyRow, + type WatchActions, +} from '@/components/notifications/notify-only-row' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { ListIcon, RecordIcon } from '@/components/vela/icons' +import { Toasts } from '@/components/vela/toast' +import { PHONE } from '@/stories/rows-as-cards' +import { + DESTINATIONS, + HOME_SLACK, + WATCHED_DOCUMENTARY, + WATCHED_FOOTBALL, +} from '@/stories/fixtures/notifications' + +const OK: NotificationWrite = { state: 'ok' } + +const changeLead = fn(async () => OK) + +const changeDestinations = fn( + async () => OK, +) + +const cancel = fn(async () => OK) + +const WATCH_ACTIONS: WatchActions = { + onChangeLead: changeLead, + onChangeDestinations: changeDestinations, + onCancel: cancel, +} + +/** A programme's detail as far as the single notice reaches into it: the time with the chip beside it once set, and the row of actions with the button. */ +function DetailWithTheNotice({ watching }: { watching: boolean }) { + const [watch, setWatch] = useState( + watching + ? { id: 'watch-doc', leadMinutes: 3, destinationIds: [HOME_SLACK.id] } + : undefined, + ) + + const onWatch = async (): Promise => { + const made: ProgrammeWatch = { + id: 'watch-doc', + leadMinutes: 3, + destinationIds: [HOME_SLACK.id], + } + + setWatch(made) + + return { state: 'ok', watch: made } + } + + const onUnwatch = async (): Promise => { + setWatch(undefined) + + return OK + } + + return ( +
    +

    + みなと総合11 +

    +

    + ドキュメント 灯りの仕事「夜の港、最後の便まで」 +

    +

    + 11/09(月) 19:30 – 20:15 + 45 分 + {watch && ( + + setWatch({ ...watch, leadMinutes: lead }) + } + /> + )} +

    +

    + + ドキュメンタリー + + 字幕あり +

    +

    + 夜の街を支える人たちの一晩を追う。港の夜間便を待つ運転手、灯りを守る整備の人、最終便のあとに始まる片づけ。 +

    +
    + + + +
    +
    + ) +} + +const meta = { + title: 'Components/単発の通知', + component: DetailWithTheNotice, + parameters: { layout: 'centered' }, + args: { watching: false }, + decorators: [ + (Story) => ( + + + + ), + ], +} satisfies Meta + +export default meta +type Story = StoryObj + +export const 押す前: Story = { + play: async ({ canvasElement }) => { + await expect( + within(canvasElement).getByRole('button', { name: NOTIFY_START }), + ).toBeVisible() + }, +} + +export const 押すと知らせが出る: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('button', { name: NOTIFY_START })) + + await expect( + await screen.findByText('開始の 3 分前に通知します'), + ).toBeVisible() + await expect(canvas.getByText('開始 3 分前に通知')).toBeVisible() + }, +} + +export const 知らせから取り消す: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('button', { name: NOTIFY_START })) + + await expect( + await screen.findByText('開始の 3 分前に通知します'), + ).toBeVisible() + await expect( + canvas.getByRole('button', { name: STOP_NOTIFYING }), + ).toBeVisible() + await expect(canvas.getByText('開始 3 分前に通知')).toBeVisible() + + await userEvent.click(screen.getByRole('button', { name: '取り消す' })) + + await waitFor(() => + expect(canvas.getByRole('button', { name: NOTIFY_START })).toBeVisible(), + ) + }, +} + +export const 押したあと: Story = { + args: { watching: true }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await expect( + canvas.getByRole('button', { name: STOP_NOTIFYING }), + ).toBeVisible() + await expect( + canvas.getByRole('button', { name: /開始 3 分前に通知/ }), + ).toHaveAttribute('aria-expanded', 'false') + }, +} + +export const 札を押して分を選ぶ: Story = { + args: { watching: true }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click( + canvas.getByRole('button', { name: /開始 3 分前に通知/ }), + ) + + const leads = within(await screen.findByRole('group', { name: '何分前' })) + + await expect(leads.getByRole('button', { name: '3 分前' })).toHaveAttribute( + 'aria-pressed', + 'true', + ) + + await userEvent.click(leads.getByRole('button', { name: '開始時' })) + + await expect( + await canvas.findByRole('button', { name: /開始時に通知/ }), + ).toBeVisible() + }, +} + +export const 札を開いたまま: Story = { + render: () => ( +
    + {}} defaultOpen /> +
    + ), + play: async () => { + await expect( + await screen.findByRole('group', { name: '何分前' }), + ).toBeVisible() + }, +} + +/** Cells of the guide the way the bell sits in one: at the corner, the title leaving room for it. */ +function GuideCells() { + return ( +
    + {[ + { + time: '19:30', + title: 'ドキュメント 灯りの仕事', + line: '夜の街を支える人たちの一晩を追う。', + tone: 'bg-g-doc-deep', + dot: 'bg-g-doc-dot', + }, + { + time: '22:24', + title: '超巡! 星屑ステーション #9', + line: '小さな駅に流れ着いた星のかけらを、駅員見習いが届けていく。', + tone: 'bg-g-anime-deep', + dot: 'bg-g-anime-dot', + }, + ].map((cell) => ( +
    +

    +

    +

    + {cell.line} +

    + +
    + ))} +
    + ) +} + +export const 番組表のベル: Story = { + render: () => , + play: async ({ canvasElement }) => { + await expect( + within(canvasElement).getAllByText('放送開始を通知'), + ).toHaveLength(2) + }, +} + +/** Two single notices among the reservation list's rows, one of them open. */ +function ReservationRows({ firstOpen }: { firstOpen: boolean }) { + const [open, setOpen] = useState( + firstOpen ? WATCHED_DOCUMENTARY.id : undefined, + ) + + return ( +
      + {[WATCHED_DOCUMENTARY, WATCHED_FOOTBALL].map((watch) => ( + setOpen(open === watch.id ? undefined : watch.id)} + actions={WATCH_ACTIONS} + /> + ))} +
    + ) +} + +export const 予約一覧の行: Story = { + render: () => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await expect(canvas.getAllByText(NOTIFY_ONLY)).toHaveLength(2) + + changeLead.mockClear() + changeDestinations.mockClear() + + await userEvent.click( + canvas.getByRole('button', { name: /ドキュメント 灯りの仕事/ }), + ) + + const leads = within(canvas.getByRole('group', { name: '何分前' })) + + await userEvent.click(leads.getByRole('button', { name: '10 分前' })) + + await waitFor(() => + expect(changeLead).toHaveBeenCalledWith(WATCHED_DOCUMENTARY.id, 10), + ) + + const to = within(canvas.getByRole('group', { name: '送り先' })) + + await userEvent.click( + to.getByRole('button', { name: 'Discord の通知部屋' }), + ) + + await waitFor(() => + expect(changeDestinations).toHaveBeenCalledWith(WATCHED_DOCUMENTARY.id, [ + 'dest-slack', + 'dest-ipad', + 'dest-discord', + ]), + ) + }, +} + +export const 予約一覧の行_最後の送り先は外せない: Story = { + render: () => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('button', { name: /サッカー中継/ })) + + const to = within(canvas.getByRole('group', { name: '送り先' })) + + await expect(to.getByRole('button', { name: '家の Slack' })).toBeDisabled() + }, +} + +export const 予約一覧の行_取り消す: Story = { + render: () => , + play: async ({ canvasElement }) => { + cancel.mockClear() + + await userEvent.click( + within(canvasElement).getByRole('button', { + name: 'サッカー中継 湾岸カップ 準決勝 の通知を取り消す', + }), + ) + + await waitFor(() => + expect(cancel).toHaveBeenCalledWith(WATCHED_FOOTBALL.id), + ) + }, +} + +export const 予約一覧の行_電話: Story = { + parameters: { screen: PHONE, coarse: true, layout: 'fullscreen' }, + render: () => , + play: async ({ canvasElement }) => { + await expect( + within(canvasElement).getByRole('group', { name: '何分前' }), + ).toBeVisible() + }, +} + +export const 電話の番組詳細: Story = { + parameters: { screen: PHONE, coarse: true, layout: 'fullscreen' }, + args: { watching: true }, + play: async ({ canvasElement }) => { + await expect( + within(canvasElement).getByRole('button', { name: STOP_NOTIFYING }), + ).toBeVisible() + }, +} From 697d4bd7fcff55d9b01cf38e8e0d843f50ef3a57 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Mon, 9 Nov 2026 22:04:24 +0900 Subject: [PATCH 05/24] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E3=81=AE=E7=89=A9?= =?UTF-8?q?=E8=AA=9E=E3=81=8C=E8=A9=A6=E9=A8=93=E3=81=A8=E8=AA=AD=E3=81=BF?= =?UTF-8?q?=E4=B8=8A=E3=81=92=E3=81=AE=E9=96=A2=E9=96=80=E3=82=92=E9=80=9A?= =?UTF-8?q?=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB=E7=9B=B4=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- components/notifications/destination-list.tsx | 2 +- components/notifications/notify-only-row.tsx | 7 +++++-- stories/components/ProgrammeNotice.stories.tsx | 6 ++++-- stories/screens/Notifications.stories.tsx | 18 +++++++++++++----- 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/components/notifications/destination-list.tsx b/components/notifications/destination-list.tsx index 5dc8eb89..614b1daf 100644 --- a/components/notifications/destination-list.tsx +++ b/components/notifications/destination-list.tsx @@ -127,7 +127,7 @@ function ResultLine({ said, tail }: { said?: Said; tail?: string }) { )} {tail && ( - + {said && '· '} {tailOf(tail)} diff --git a/components/notifications/notify-only-row.tsx b/components/notifications/notify-only-row.tsx index b0e99c45..b13f57a1 100644 --- a/components/notifications/notify-only-row.tsx +++ b/components/notifications/notify-only-row.tsx @@ -171,7 +171,10 @@ export function NotifyOnlyRow({ 送り先 - + {destinations.map((destination) => ( void changeSendTo(destination.id)} className={cn( - 'h-[calc(30rem/16)] pr-3 pl-2.5 text-[calc(13rem/16)]', + 'pr-3 pl-2.5 text-[calc(13rem/16)]', !sendTo.includes(destination.id) && 'bg-bg enabled:hover:bg-surface-2 dark:bg-bg dark:enabled:hover:bg-surface-2', )} diff --git a/stories/components/ProgrammeNotice.stories.tsx b/stories/components/ProgrammeNotice.stories.tsx index bddb792c..f73d37bc 100644 --- a/stories/components/ProgrammeNotice.stories.tsx +++ b/stories/components/ProgrammeNotice.stories.tsx @@ -322,7 +322,7 @@ export const 予約一覧の行: Story = { changeDestinations.mockClear() await userEvent.click( - canvas.getByRole('button', { name: /ドキュメント 灯りの仕事/ }), + canvas.getByRole('button', { name: WATCHED_DOCUMENTARY.title }), ) const leads = within(canvas.getByRole('group', { name: '何分前' })) @@ -354,7 +354,9 @@ export const 予約一覧の行_最後の送り先は外せない: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement) - await userEvent.click(canvas.getByRole('button', { name: /サッカー中継/ })) + await userEvent.click( + canvas.getByRole('button', { name: WATCHED_FOOTBALL.title }), + ) const to = within(canvas.getByRole('group', { name: '送り先' })) diff --git a/stories/screens/Notifications.stories.tsx b/stories/screens/Notifications.stories.tsx index b53f91da..5073b263 100644 --- a/stories/screens/Notifications.stories.tsx +++ b/stories/screens/Notifications.stories.tsx @@ -213,10 +213,12 @@ export const テスト送信: Story = { canvas.getByRole('button', { name: 'Discord の通知部屋 にテスト送信' }), ) + const destinations = within(canvas.getByRole('list', { name: '送り先' })) + await waitFor(() => expect(testDestination).toHaveBeenCalledTimes(2)) - await expect(await canvas.findByText('届いた')).toBeVisible() + await expect(await destinations.findByText('届いた')).toBeVisible() await expect( - await canvas.findByText('届かなかった · 時間切れ'), + await destinations.findByText('届かなかった · 時間切れ'), ).toBeVisible() }, } @@ -694,7 +696,11 @@ export const 電話_送り先を追加: Story = { await expect( within(dialog).getByText('iPhone の Safari に通知を出します'), ).toBeVisible() - await expect(Math.round(sheet.bottom)).toBe(window.innerHeight) + await waitFor(() => + expect(Math.round(dialog.getBoundingClientRect().bottom)).toBe( + window.innerHeight, + ), + ) await expect(Math.round(sheet.width)).toBe(window.innerWidth) }, } @@ -725,8 +731,10 @@ export const 電話_ルールセットを変更: Story = { await expect(within(dialog).getByLabelText('名前')).toHaveValue( '録画の記録', ) - await expect(Math.round(dialog.getBoundingClientRect().bottom)).toBe( - window.innerHeight, + await waitFor(() => + expect(Math.round(dialog.getBoundingClientRect().bottom)).toBe( + window.innerHeight, + ), ) }, } From 267dda07e42483fba82f64f51e9e87174dd6b671 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Mon, 9 Nov 2026 22:18:42 +0900 Subject: [PATCH 06/24] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E3=82=92=E8=A8=AD?= =?UTF-8?q?=E5=AE=9A=E3=81=AE=E4=B8=80=E8=A6=A7=E3=81=A8=E9=9B=BB=E8=A9=B1?= =?UTF-8?q?=E3=81=AE=E5=B8=AF=E3=81=AB=E5=87=BA=E3=81=97=E3=80=81=E5=AF=BE?= =?UTF-8?q?=E8=A9=B1=E3=81=AE=E8=84=9A=E3=82=92=E3=81=BB=E3=81=8B=E3=81=AE?= =?UTF-8?q?=E5=AF=BE=E8=A9=B1=E3=81=A8=E5=90=8C=E3=81=98=E4=B8=AD=E5=A4=AE?= =?UTF-8?q?=E3=81=AB=E3=81=9D=E3=82=8D=E3=81=88=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../notifications/add-destination-dialog.tsx | 6 ++--- components/notifications/notice-dialog.tsx | 19 ++++----------- components/notifications/rule-set-dialog.tsx | 24 ++++++++----------- .../settings-entrance/settings-beside.tsx | 3 +++ .../settings-entrance-page.tsx | 16 ++++++++++++- .../settings-entrance/settings-frame.tsx | 4 ++++ lib/phone-bar.ts | 1 + stories/frames.tsx | 18 ++++++++++++++ stories/screens/Notifications.stories.tsx | 4 ++-- 9 files changed, 61 insertions(+), 34 deletions(-) diff --git a/components/notifications/add-destination-dialog.tsx b/components/notifications/add-destination-dialog.tsx index 0c88cd70..7aeef5ab 100644 --- a/components/notifications/add-destination-dialog.tsx +++ b/components/notifications/add-destination-dialog.tsx @@ -113,7 +113,7 @@ function KindPicker({ title={ADD_DESTINATION} description="送り先の種類を選びます。" /> -
      +
        } name="Slack・Discord" @@ -143,14 +143,14 @@ function KindOption({ onPick: () => void }) { return ( -
      • +
      • diff --git a/components/settings-entrance/settings-beside.tsx b/components/settings-entrance/settings-beside.tsx index 907ba282..2a24bf26 100644 --- a/components/settings-entrance/settings-beside.tsx +++ b/components/settings-entrance/settings-beside.tsx @@ -14,10 +14,12 @@ export function SettingsBeside({ status, values, hasMigration, + hasNotifications = false, }: { status: SystemStatus values: SettingsEntranceValues hasMigration: boolean + hasNotifications?: boolean }) { const sideways = usePhoneOnItsSide() const pathname = usePathname() @@ -36,6 +38,7 @@ export function SettingsBeside({ status={status} values={values} hasMigration={hasMigration} + hasNotifications={hasNotifications} current={pathname} /> diff --git a/components/settings-entrance/settings-entrance-page.tsx b/components/settings-entrance/settings-entrance-page.tsx index a14bfdae..0b2cdbf1 100644 --- a/components/settings-entrance/settings-entrance-page.tsx +++ b/components/settings-entrance/settings-entrance-page.tsx @@ -6,6 +6,7 @@ import { cn } from '@/lib/utils' import type { SystemStatus } from '@/repository/system' import { VelaMark } from '@/components/vela/marks' import { + BellIcon, ChannelIcon, ChevronRightIcon, EncodeIcon, @@ -139,6 +140,7 @@ function groupsOf( status: SystemStatus, values: SettingsEntranceValues, hasMigration: boolean, + hasNotifications: boolean, ): Group[] { const keeping: Item[] = [ { @@ -155,6 +157,15 @@ function groupsOf( }, ] + if (hasNotifications) { + keeping.push({ + href: '/settings/notifications' as Route, + label: '通知', + icon: BellIcon, + tile: TILE.keeping, + }) + } + if (hasMigration) { keeping.push({ href: '/settings/migration', @@ -341,12 +352,15 @@ export function SettingsEntranceView({ status, values, hasMigration, + hasNotifications = false, current, withValues = true, }: { status: SystemStatus values: SettingsEntranceValues hasMigration: boolean + /** Whether notifications stand in the list, after the integrity check. Off until their screen exists. */ + hasNotifications?: boolean current?: string /** Each setting's value after its name; the wide screen leaves them to the setting open beside. */ withValues?: boolean @@ -357,7 +371,7 @@ export function SettingsEntranceView({
        {current === undefined &&

        設定

        } - {groupsOf(status, values, hasMigration).map((group) => ( + {groupsOf(status, values, hasMigration, hasNotifications).map((group) => (
        @@ -62,6 +65,7 @@ export function SettingsFrame({ status={status} values={values} hasMigration={hasMigration} + hasNotifications={hasNotifications} /> ( ) +/** The settings frame with notifications in its list, for their stories until their screen is in the app. */ +export const inTheSettingsWithNotifications: Decorator = (Story) => ( + + + + + + + + + +) + export const inTheSettings: Decorator = (Story) => ( diff --git a/stories/screens/Notifications.stories.tsx b/stories/screens/Notifications.stories.tsx index 5073b263..03c7ed5b 100644 --- a/stories/screens/Notifications.stories.tsx +++ b/stories/screens/Notifications.stories.tsx @@ -10,7 +10,7 @@ import { } from '@/components/notifications/notifications-page' import { DENIED_HERE } from '@/components/notifications/add-destination-dialog' import { REFUSED_ADDRESS } from '@/components/notifications/webhook-field' -import { inTheSettings } from '@/stories/frames' +import { inTheSettingsWithNotifications } from '@/stories/frames' import { PHONE } from '@/stories/rows-as-cards' import { DESTINATIONS, @@ -97,7 +97,7 @@ const meta = { permission: 'default', now: NOTIFICATIONS_NOW, }, - decorators: [inTheSettings], + decorators: [inTheSettingsWithNotifications], } satisfies Meta export default meta From 1e379d431555add17cca3c243df2a88c27f90f11 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Tue, 10 Nov 2026 13:01:43 +0900 Subject: [PATCH 07/24] =?UTF-8?q?=E9=80=81=E3=82=8A=E5=85=88=E3=81=A8?= =?UTF-8?q?=E3=83=AB=E3=83=BC=E3=83=AB=E3=82=BB=E3=83=83=E3=83=88=E3=81=AE?= =?UTF-8?q?=E8=A1=8C=E3=81=AE=E6=93=8D=E4=BD=9C=E3=82=92=20=E2=80=A6=20?= =?UTF-8?q?=E3=81=AE=E3=83=A1=E3=83=8B=E3=83=A5=E3=83=BC=E3=81=AB=E3=81=BE?= =?UTF-8?q?=E3=81=A8=E3=82=81=E3=80=81=E7=A8=AE=E9=A1=9E=E3=81=AE=E6=9C=AD?= =?UTF-8?q?=E3=81=AB=E8=89=B2=E3=82=92=E4=BB=98=E3=81=91=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../notifications/add-destination-dialog.tsx | 4 +- components/notifications/destination-list.tsx | 132 ++++++++++-------- .../notifications/edit-destination-dialog.tsx | 23 +-- components/notifications/remove-button.tsx | 111 +++++++++------ components/notifications/row-menu.tsx | 87 ++++++++++++ components/notifications/rule-set-dialog.tsx | 1 - components/notifications/rule-set-list.tsx | 52 +++---- stories/screens/Notifications.stories.tsx | 98 ++++++++----- 8 files changed, 321 insertions(+), 187 deletions(-) create mode 100644 components/notifications/row-menu.tsx diff --git a/components/notifications/add-destination-dialog.tsx b/components/notifications/add-destination-dialog.tsx index 7aeef5ab..35d4bb79 100644 --- a/components/notifications/add-destination-dialog.tsx +++ b/components/notifications/add-destination-dialog.tsx @@ -116,8 +116,8 @@ function KindPicker({
          } - name="Slack・Discord" - says="Webhook の URL に送ります" + name="Webhook" + says="Slack・Discord の URL に送ります" onPick={() => onPick('webhook')} /> = { export const GROUP_ROW = 'relative before:absolute before:top-0 before:right-0 before:left-4 before:h-px before:bg-hair first:before:hidden upright:before:left-3.5' -/** On a wide window the switch, the answer to a test and the buttons stand to the right of the name; on a phone the switch stays beside the name and the buttons go under it. */ +/** The name and the last result on the left; the switch and the `…` on the right, beside the name on a phone. */ const ROW_AREAS = cn( - 'grid min-h-[calc(76rem/16)] grid-cols-[minmax(0,1fr)_auto_auto_auto] items-center gap-x-2 px-4 py-3', - "[grid-template-areas:'head_sw_res_acts'_'last_sw_res_acts']", - "upright:grid-cols-[minmax(0,1fr)_auto] upright:px-3.5 upright:[grid-template-areas:'head_sw'_'last_last'_'acts_acts'_'res_res']", + 'grid min-h-[calc(76rem/16)] grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-x-2 px-4 py-3', + "[grid-template-areas:'head_sw_more'_'last_sw_more']", + "upright:min-h-0 upright:gap-x-1 upright:px-3.5 upright:[grid-template-areas:'head_sw_more'_'last_last_last']", ) -const FLAT_ON_A_PHONE = 'upright:shadow-none' - const SIGNED_OUT = signedOut('操作') function refusalOf(result: Exclude) { @@ -108,27 +103,49 @@ export function DestinationList({ ) } -function ResultLine({ said, tail }: { said?: Said; tail?: string }) { - if (!said && !tail) { +const TEST_SENT = 'テスト送信' + +/** The line under the name: the answer to a test send while there is one, otherwise how the last notice went; on a phone the address's tail after it. */ +function ResultLine({ + said, + testing, + tested, + tail, +}: { + said?: Said + testing: boolean + tested?: Said + tail?: string +}) { + const shown = tested ?? said + const words = testing + ? `${TEST_SENT} · 送信中` + : tested && `${TEST_SENT} · ${withWhy(tested)}` + + if (!shown && !testing && !tail) { return null } return ( - {said && ( - <> - - {withWhy(said)} - + {testing && } + {!testing && shown && ( + + )} + {(words || said) && ( + {words || (said && withWhy(said))} )} {tail && ( - - {said && '· '} + + {(words || said) && '· '} {tailOf(tail)} )} @@ -148,6 +165,8 @@ function DestinationRow({ const [enabled, setEnabled] = useState(destination.enabled) const [tested, setTested] = useState() const [testing, startTesting] = useTransition() + const [editing, setEditing] = useState(false) + const [removing, setRemoving] = useState(false) const say = useToast() const { id, name, kind, urlTail, lastResult } = destination const webhook = kind !== 'webPush' @@ -180,7 +199,7 @@ function DestinationRow({ return (
        • - + {name} - - {wordFor(KIND_LABEL, kind)} - + {urlTail && ( {tailOf(urlTail)} @@ -200,49 +217,42 @@ function DestinationRow({ void toggle(next)} - className="mr-2.5 [grid-area:sw] upright:mr-0" + className="mr-1 [grid-area:sw] upright:mr-0.5" /> - - {tested && withWhy(tested)} - - - - {webhook && ( - - )} - actions.onRemoveDestination(id)} - className={FLAT_ON_A_PHONE} + setEditing(true) }] + : []), + ]} + onRemove={() => setRemoving(true)} + /> + {webhook && ( + - + )} + actions.onRemoveDestination(id)} + />
        • ) } diff --git a/components/notifications/edit-destination-dialog.tsx b/components/notifications/edit-destination-dialog.tsx index 9be1a045..01b8d781 100644 --- a/components/notifications/edit-destination-dialog.tsx +++ b/components/notifications/edit-destination-dialog.tsx @@ -35,36 +35,27 @@ export interface DestinationRevision { const SIGNED_OUT = signedOut('変更') -export function EditDestinationButton({ +export function EditDestinationDialog({ destination, + open, + onOpenChange, onRevise, - className, }: { destination: NotificationDestination + open: boolean + onOpenChange: (open: boolean) => void onRevise: ( id: string, revision: DestinationRevision, ) => Promise - className?: string }) { - const [open, setOpen] = useState(false) - return ( - - + {open && ( setOpen(false)} + onClose={() => onOpenChange(false)} onRevise={onRevise} /> )} diff --git a/components/notifications/remove-button.tsx b/components/notifications/remove-button.tsx index 5419a4e3..87ca955d 100644 --- a/components/notifications/remove-button.tsx +++ b/components/notifications/remove-button.tsx @@ -21,23 +21,22 @@ import { Spinner } from '@/components/vela/progress' const SIGNED_OUT = signedOut('削除') -/** `削除` and the question it asks before anything goes: the name of what goes, and that it cannot come back. */ -export function RemoveButton({ +/** The question asked before anything goes: the name of what goes, and that it cannot come back. */ +export function RemoveDialog({ what, name, + open, + onOpenChange, onRemove, onRemoved, - size = 'sm', - className, }: { what: '送り先' | 'ルールセット' name: string + open: boolean + onOpenChange: (open: boolean) => void onRemove: () => Promise onRemoved?: () => void - size?: 'sm' | 'default' - className?: string }) { - const [open, setOpen] = useState(false) const [refusal, setRefusal] = useState() const [pending, startTransition] = useTransition() @@ -48,7 +47,7 @@ export function RemoveButton({ const result = await onRemove() if (result.state === 'ok') { - setOpen(false) + onOpenChange(false) onRemoved?.() return @@ -59,49 +58,75 @@ export function RemoveButton({ ) }) + return ( + { + setRefusal(undefined) + onOpenChange(next) + }} + > + + + この{what}を削除します + + {name} + 元に戻せません。 + + + + {refusal && {refusal}} + + + キャンセル + { + event.preventDefault() + remove() + }} + > + {pending ? : } + 削除する + + + + + ) +} + +/** `削除` with its question, where it stands as a button of its own. */ +export function RemoveButton({ + what, + name, + onRemove, + onRemoved, +}: { + what: '送り先' | 'ルールセット' + name: string + onRemove: () => Promise + onRemoved?: () => void +}) { + const [open, setOpen] = useState(false) + return ( <> - - - - - この{what}を削除します - - {name} - 元に戻せません。 - - - - {refusal && {refusal}} - - - キャンセル - { - event.preventDefault() - remove() - }} - > - {pending ? : } - 削除する - - - - + ) } diff --git a/components/notifications/row-menu.tsx b/components/notifications/row-menu.tsx new file mode 100644 index 00000000..ac4eb976 --- /dev/null +++ b/components/notifications/row-menu.tsx @@ -0,0 +1,87 @@ +'use client' + +import type { ReactNode } from 'react' + +import { cn } from '@/lib/utils' +import { KIND_LABEL, type DestinationKind } from '@/lib/notifications' +import { shapeFor, wordFor } from '@/lib/not-yet-in-this-build' +import { Badge } from '@/components/ui/badge' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu' +import { MoreIcon, TrashIcon } from '@/components/vela/icons' + +/** The `…` of a row, drawn as the library's row draws it, always in sight since the row has no other way to its actions. */ +const MORE_TRIGGER = + 'tap-target inline-grid size-9 shrink-0 cursor-pointer place-items-center rounded-full text-ink-2 outline-none transition-[background-color,color] duration-[140ms] ease-toy hover:bg-surface-2 hover:text-ink focus-visible:shadow-ring data-[state=open]:bg-surface-2' + +export interface RowAction { + label: string + onSelect: () => void +} + +/** A row's `…` and the menu it opens: its actions, then a line, then `削除` in the colour of what cannot be undone. */ +export function RowMenu({ + name, + actions, + onRemove, + className, +}: { + name: string + actions: RowAction[] + onRemove: () => void + className?: string +}) { + return ( + + + + + + {actions.map((action) => ( + + {action.label} + + ))} + + + + 削除 + + + + ) +} + +/** Each kind of destination wears a tint of its own, borrowed from tints that say no verdict, so that none reads as a state. */ +const KIND_TINT: Record = { + slack: 'bg-g-music-deep text-g-music-text', + discord: 'bg-g-anime-deep text-g-anime-text', + webPush: 'bg-g-info-deep text-g-info-text', +} + +const UNKNOWN_KIND = 'bg-surface-2 text-ink-2' + +export function KindChip({ + kind, + className, +}: { + kind: DestinationKind + className?: string +}): ReactNode { + return ( + + {wordFor(KIND_LABEL, kind)} + + ) +} diff --git a/components/notifications/rule-set-dialog.tsx b/components/notifications/rule-set-dialog.tsx index 047a09b7..badd88f4 100644 --- a/components/notifications/rule-set-dialog.tsx +++ b/components/notifications/rule-set-dialog.tsx @@ -202,7 +202,6 @@ function RuleSetForm({ diff --git a/components/notifications/rule-set-list.tsx b/components/notifications/rule-set-list.tsx index 62bcaca2..037f3d57 100644 --- a/components/notifications/rule-set-list.tsx +++ b/components/notifications/rule-set-list.tsx @@ -16,10 +16,10 @@ import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Switch } from '@/components/ui/switch' import { PlusIcon } from '@/components/vela/icons' -import { pressable } from '@/components/vela/tactile' import { useToast } from '@/components/vela/toast' import { GROUP_ROW } from '@/components/notifications/destination-list' -import { RemoveButton } from '@/components/notifications/remove-button' +import { RemoveDialog } from '@/components/notifications/remove-button' +import { RowMenu } from '@/components/notifications/row-menu' import { RuleSetDialog } from '@/components/notifications/rule-set-dialog' export interface RuleSetActions { @@ -34,11 +34,11 @@ export interface RuleSetActions { const SIGNED_OUT = signedOut('操作') -/** On a wide window the switch and the buttons stand to the right; on a phone the switch stays beside the name and the row itself opens the editor. */ +/** The name, its events and destinations on the left; the switch and the `…` on the right, beside the name on a phone. */ const ROW_AREAS = cn( 'grid min-h-[calc(76rem/16)] grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-x-2 px-4 py-3', - "[grid-template-areas:'info_sw_acts']", - "upright:grid-cols-[minmax(0,1fr)_auto] upright:items-start upright:px-3.5 upright:[grid-template-areas:'info_sw']", + "[grid-template-areas:'info_sw_more']", + 'upright:min-h-0 upright:items-start upright:gap-x-1 upright:px-3.5', ) /** `追加` over the rule sets, which stops at twenty, and before there is anywhere to send to. */ @@ -137,6 +137,7 @@ function RuleSetRow({ actions: RuleSetActions }) { const [enabled, setEnabled] = useState(ruleSet.enabled) + const [removing, setRemoving] = useState(false) const say = useToast() const { id, name } = ruleSet @@ -155,14 +156,7 @@ function RuleSetRow({ return (
        • - + void toggle(next)} - className="mr-2.5 [grid-area:sw] upright:mr-0" + className="mr-1 [grid-area:sw] upright:mr-0.5" + /> + setRemoving(true)} + /> + actions.onRemoveRuleSet(id)} /> - - - actions.onRemoveRuleSet(id)} - /> -
        • ) } diff --git a/stories/screens/Notifications.stories.tsx b/stories/screens/Notifications.stories.tsx index 03c7ed5b..e271baaf 100644 --- a/stories/screens/Notifications.stories.tsx +++ b/stories/screens/Notifications.stories.tsx @@ -103,6 +103,18 @@ const meta = { export default meta type Story = StoryObj +/** Opens a row's `…` and picks one of its items. */ +async function fromTheMenu( + canvasElement: HTMLElement, + name: string, + item: string, +) { + await userEvent.click( + within(canvasElement).getByRole('button', { name: `${name} の操作` }), + ) + await userEvent.click(await screen.findByRole('menuitem', { name: item })) +} + async function openThePicker(canvasElement: HTMLElement) { const canvas = within(canvasElement) const destinations = canvas.getByRole('heading', { name: '送り先' }) @@ -146,11 +158,16 @@ export const 通常: Story = { destinations.getByText('届いていない · 時間切れ'), ).toBeVisible() await expect( - destinations.getByRole('button', { name: '家の Slack を変更' }), + destinations.getByRole('button', { name: '家の Slack の操作' }), ).toBeVisible() await expect( - destinations.queryByRole('button', { name: 'iPad の Safari を変更' }), + destinations.queryByRole('button', { name: /テスト送信|変更|削除/ }), ).toBeNull() + await expect( + destinations + .getAllByText(/^(Slack|Discord|Web Push)$/) + .map((chip) => chip.dataset.kind), + ).toEqual(['slack', 'discord', 'webPush']) await expect( canvas.getByText( '録画の欠け・失敗 · エンコードの失敗 · 競合・取り逃し · 異常の発生 · 切断', @@ -206,20 +223,49 @@ export const テスト送信: Story = { testDestination.mockClear() + await fromTheMenu(canvasElement, '家の Slack', 'テスト送信') + await fromTheMenu(canvasElement, 'Discord の通知部屋', 'テスト送信') + + const destinations = within(canvas.getByRole('list', { name: '送り先' })) + + await waitFor(() => expect(testDestination).toHaveBeenCalledTimes(2)) + await expect( + await destinations.findByText('テスト送信 · 届いた'), + ).toBeVisible() + await expect( + await destinations.findByText('テスト送信 · 届かなかった · 時間切れ'), + ).toBeVisible() + await expect(destinations.queryByText('届いていない · 時間切れ')).toBeNull() + }, +} + +export const 操作のメニュー: Story = { + play: async ({ canvasElement }) => { await userEvent.click( - canvas.getByRole('button', { name: '家の Slack にテスト送信' }), + within(canvasElement).getByRole('button', { name: '家の Slack の操作' }), ) + + const menu = within(await screen.findByRole('menu')) + + await expect( + menu.getAllByRole('menuitem').map((item) => item.textContent), + ).toEqual(['テスト送信', '変更', '削除']) + }, +} + +export const 操作のメニュー_ブラウザ: Story = { + play: async ({ canvasElement }) => { await userEvent.click( - canvas.getByRole('button', { name: 'Discord の通知部屋 にテスト送信' }), + within(canvasElement).getByRole('button', { + name: 'iPad の Safari の操作', + }), ) - const destinations = within(canvas.getByRole('list', { name: '送り先' })) + const menu = within(await screen.findByRole('menu')) - await waitFor(() => expect(testDestination).toHaveBeenCalledTimes(2)) - await expect(await destinations.findByText('届いた')).toBeVisible() await expect( - await destinations.findByText('届かなかった · 時間切れ'), - ).toBeVisible() + menu.getAllByRole('menuitem').map((item) => item.textContent), + ).toEqual(['テスト送信', '削除']) }, } @@ -332,7 +378,7 @@ export const 送り先を追加_種類を選ぶ: Story = { const dialog = within(await openThePicker(canvasElement)) await expect( - dialog.getByRole('button', { name: /Webhook の URL に送ります/ }), + dialog.getByRole('button', { name: /Slack・Discord の URL に送ります/ }), ).toBeVisible() await expect( dialog.getByText('Windows の Chrome に通知を出します'), @@ -481,9 +527,7 @@ export const 送り先を変更: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement) - await userEvent.click( - canvas.getByRole('button', { name: '家の Slack を変更' }), - ) + await fromTheMenu(canvasElement, '家の Slack', '変更') const dialog = within( await screen.findByRole('dialog', { name: '送り先を変更' }), @@ -505,9 +549,7 @@ export const 送り先の変更を保存する: Story = { play: async ({ canvasElement }) => { reviseDestination.mockClear() - await userEvent.click( - within(canvasElement).getByRole('button', { name: '家の Slack を変更' }), - ) + await fromTheMenu(canvasElement, '家の Slack', '変更') const dialog = within( await screen.findByRole('dialog', { name: '送り先を変更' }), @@ -530,9 +572,7 @@ export const 送り先を削除: Story = { removeDestination.mockClear() - await userEvent.click( - canvas.getByRole('button', { name: 'Discord の通知部屋 を削除' }), - ) + await fromTheMenu(canvasElement, 'Discord の通知部屋', '削除') const asked = within(await screen.findByRole('alertdialog')) @@ -551,9 +591,7 @@ export const ルールセットを変更: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement) - await userEvent.click( - canvas.getByRole('button', { name: '困ったときだけ を変更' }), - ) + await fromTheMenu(canvasElement, '困ったときだけ', '変更') const dialog = within( await screen.findByRole('dialog', { name: 'ルールセットを変更' }), @@ -581,11 +619,7 @@ export const ルールセットを保存する: Story = { play: async ({ canvasElement }) => { reviseRuleSet.mockClear() - await userEvent.click( - within(canvasElement).getByRole('button', { - name: '困ったときだけ を変更', - }), - ) + await fromTheMenu(canvasElement, '困ったときだけ', '変更') const dialog = within( await screen.findByRole('dialog', { name: 'ルールセットを変更' }), @@ -681,8 +715,8 @@ export const 電話: Story = { await expect(slack.getByText('· …a1b2')).toBeVisible() await expect( - canvas.queryByRole('button', { name: '困ったときだけ を変更' }), - ).toBeNull() + canvas.getByRole('button', { name: '困ったときだけ の操作' }), + ).toBeVisible() }, } @@ -718,11 +752,7 @@ export const 電話_このブラウザ: Story = { export const 電話_ルールセットを変更: Story = { parameters: { screen: PHONE, coarse: true }, play: async ({ canvasElement }) => { - const ruleSets = within( - within(canvasElement).getByRole('list', { name: 'ルールセット' }), - ) - - await userEvent.click(ruleSets.getByRole('button', { name: /^録画の記録/ })) + await fromTheMenu(canvasElement, '録画の記録', '変更') const dialog = await screen.findByRole('dialog', { name: 'ルールセットを変更', From c13bbb079937d9cce76fdc0187bac25250d4d33b Mon Sep 17 00:00:00 2001 From: fyui001 Date: Tue, 10 Nov 2026 14:08:47 +0900 Subject: [PATCH 08/24] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E3=81=AE=E7=89=A9?= =?UTF-8?q?=E8=AA=9E=E3=82=92=E6=96=B0=E3=81=97=E3=81=84=E5=8C=BA=E5=88=86?= =?UTF-8?q?=E3=81=91=E3=81=AB=E7=A7=BB=E3=81=97=E3=80=81=E9=80=9A=E5=B8=B8?= =?UTF-8?q?=E3=81=8B=E3=82=89=E9=9B=BB=E8=A9=B1=E3=81=AE=E9=A0=86=E3=81=AB?= =?UTF-8?q?=E4=B8=A6=E3=81=B9=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../components/ProgrammeNotice.stories.tsx | 209 +++++++++--------- stories/screens/Notifications.stories.tsx | 185 ++++++++-------- 2 files changed, 198 insertions(+), 196 deletions(-) diff --git a/stories/components/ProgrammeNotice.stories.tsx b/stories/components/ProgrammeNotice.stories.tsx index f73d37bc..cf2561af 100644 --- a/stories/components/ProgrammeNotice.stories.tsx +++ b/stories/components/ProgrammeNotice.stories.tsx @@ -123,7 +123,7 @@ function DetailWithTheNotice({ watching }: { watching: boolean }) { } const meta = { - title: 'Components/単発の通知', + title: 'Components/番組と局/単発の通知', component: DetailWithTheNotice, parameters: { layout: 'centered' }, args: { watching: false }, @@ -137,101 +137,8 @@ const meta = { } satisfies Meta export default meta -type Story = StoryObj - -export const 押す前: Story = { - play: async ({ canvasElement }) => { - await expect( - within(canvasElement).getByRole('button', { name: NOTIFY_START }), - ).toBeVisible() - }, -} - -export const 押すと知らせが出る: Story = { - play: async ({ canvasElement }) => { - const canvas = within(canvasElement) - - await userEvent.click(canvas.getByRole('button', { name: NOTIFY_START })) - - await expect( - await screen.findByText('開始の 3 分前に通知します'), - ).toBeVisible() - await expect(canvas.getByText('開始 3 分前に通知')).toBeVisible() - }, -} - -export const 知らせから取り消す: Story = { - play: async ({ canvasElement }) => { - const canvas = within(canvasElement) - - await userEvent.click(canvas.getByRole('button', { name: NOTIFY_START })) - - await expect( - await screen.findByText('開始の 3 分前に通知します'), - ).toBeVisible() - await expect( - canvas.getByRole('button', { name: STOP_NOTIFYING }), - ).toBeVisible() - await expect(canvas.getByText('開始 3 分前に通知')).toBeVisible() - - await userEvent.click(screen.getByRole('button', { name: '取り消す' })) - - await waitFor(() => - expect(canvas.getByRole('button', { name: NOTIFY_START })).toBeVisible(), - ) - }, -} -export const 押したあと: Story = { - args: { watching: true }, - play: async ({ canvasElement }) => { - const canvas = within(canvasElement) - - await expect( - canvas.getByRole('button', { name: STOP_NOTIFYING }), - ).toBeVisible() - await expect( - canvas.getByRole('button', { name: /開始 3 分前に通知/ }), - ).toHaveAttribute('aria-expanded', 'false') - }, -} - -export const 札を押して分を選ぶ: Story = { - args: { watching: true }, - play: async ({ canvasElement }) => { - const canvas = within(canvasElement) - - await userEvent.click( - canvas.getByRole('button', { name: /開始 3 分前に通知/ }), - ) - - const leads = within(await screen.findByRole('group', { name: '何分前' })) - - await expect(leads.getByRole('button', { name: '3 分前' })).toHaveAttribute( - 'aria-pressed', - 'true', - ) - - await userEvent.click(leads.getByRole('button', { name: '開始時' })) - - await expect( - await canvas.findByRole('button', { name: /開始時に通知/ }), - ).toBeVisible() - }, -} - -export const 札を開いたまま: Story = { - render: () => ( -
          - {}} defaultOpen /> -
          - ), - play: async () => { - await expect( - await screen.findByRole('group', { name: '何分前' }), - ).toBeVisible() - }, -} +type Story = StoryObj /** Cells of the guide the way the bell sits in one: at the corner, the title leaving room for it. */ function GuideCells() { @@ -280,15 +187,6 @@ function GuideCells() { ) } -export const 番組表のベル: Story = { - render: () => , - play: async ({ canvasElement }) => { - await expect( - within(canvasElement).getAllByText('放送開始を通知'), - ).toHaveLength(2) - }, -} - /** Two single notices among the reservation list's rows, one of them open. */ function ReservationRows({ firstOpen }: { firstOpen: boolean }) { const [open, setOpen] = useState( @@ -311,6 +209,109 @@ function ReservationRows({ firstOpen }: { firstOpen: boolean }) { ) } +export const 通常: Story = { + play: async ({ canvasElement }) => { + await expect( + within(canvasElement).getByRole('button', { name: NOTIFY_START }), + ).toBeVisible() + }, +} + +export const 押したあと: Story = { + args: { watching: true }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await expect( + canvas.getByRole('button', { name: STOP_NOTIFYING }), + ).toBeVisible() + await expect( + canvas.getByRole('button', { name: /開始 3 分前に通知/ }), + ).toHaveAttribute('aria-expanded', 'false') + }, +} + +export const 札を開いたまま: Story = { + render: () => ( +
          + {}} defaultOpen /> +
          + ), + play: async () => { + await expect( + await screen.findByRole('group', { name: '何分前' }), + ).toBeVisible() + }, +} + +export const 番組表のベル: Story = { + render: () => , + play: async ({ canvasElement }) => { + await expect( + within(canvasElement).getAllByText('放送開始を通知'), + ).toHaveLength(2) + }, +} + +export const 押すと知らせが出る: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('button', { name: NOTIFY_START })) + + await expect( + await screen.findByText('開始の 3 分前に通知します'), + ).toBeVisible() + await expect(canvas.getByText('開始 3 分前に通知')).toBeVisible() + }, +} + +export const 知らせから取り消す: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('button', { name: NOTIFY_START })) + + await expect( + await screen.findByText('開始の 3 分前に通知します'), + ).toBeVisible() + await expect( + canvas.getByRole('button', { name: STOP_NOTIFYING }), + ).toBeVisible() + await expect(canvas.getByText('開始 3 分前に通知')).toBeVisible() + + await userEvent.click(screen.getByRole('button', { name: '取り消す' })) + + await waitFor(() => + expect(canvas.getByRole('button', { name: NOTIFY_START })).toBeVisible(), + ) + }, +} + +export const 札を押して分を選ぶ: Story = { + args: { watching: true }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click( + canvas.getByRole('button', { name: /開始 3 分前に通知/ }), + ) + + const leads = within(await screen.findByRole('group', { name: '何分前' })) + + await expect(leads.getByRole('button', { name: '3 分前' })).toHaveAttribute( + 'aria-pressed', + 'true', + ) + + await userEvent.click(leads.getByRole('button', { name: '開始時' })) + + await expect( + await canvas.findByRole('button', { name: /開始時に通知/ }), + ).toBeVisible() + }, +} + export const 予約一覧の行: Story = { render: () => , play: async ({ canvasElement }) => { diff --git a/stories/screens/Notifications.stories.tsx b/stories/screens/Notifications.stories.tsx index e271baaf..e2519e00 100644 --- a/stories/screens/Notifications.stories.tsx +++ b/stories/screens/Notifications.stories.tsx @@ -81,7 +81,7 @@ const ACTIONS: NotificationActions = { } const meta = { - title: 'Screens/設定・通知', + title: 'Screens/設定/管理/通知', component: NotificationsView, parameters: { nextjs: { @@ -101,6 +101,7 @@ const meta = { } satisfies Meta export default meta + type Story = StoryObj /** Opens a row's `…` and picks one of its items. */ @@ -147,6 +148,26 @@ async function openTheBrowserForm(canvasElement: HTMLElement) { return dialog } +/** The log narrowed to one destination, as the page would answer the URL it is given. */ +function NarrowedLog(args: Story['args']) { + const [only, setOnly] = useState() + + return ( + only === undefined || delivery.destinationId === only, + ), + }} + actions={{ ...ACTIONS, onShowDeliveriesFor: setOnly }} + /> + ) +} + export const 通常: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement) @@ -217,6 +238,54 @@ export const 何もない: Story = { }, } +export const 送り先が多い: Story = { + args: { + screen: { + ...NOTIFICATIONS_SCREEN, + destinations: [ + ...DESTINATIONS, + { + ...HOME_SLACK, + id: 'dest-slack-2', + name: '実家のリビングの Slack のお知らせ用チャンネル', + urlTail: 'c3d4', + enabled: false, + lastResult: { + state: 'givenUp', + at: '2026-11-08T12:03:00Z', + failure: 'rejected', + }, + }, + ], + }, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await expect( + canvas.getByRole('switch', { + name: '実家のリビングの Slack のお知らせ用チャンネル を有効にする', + }), + ).not.toBeChecked() + await expect(canvas.getByText('届かなかった · 断られた')).toBeVisible() + }, +} + +export const ルールセットが上限: Story = { + args: { + screen: { ...NOTIFICATIONS_SCREEN, ruleSets: TWENTY_RULE_SETS }, + }, + play: async ({ canvasElement }) => { + const ruleSets = within(canvasElement).getByRole('heading', { + name: 'ルールセット', + }).parentElement as HTMLElement + + await expect( + within(ruleSets).getByRole('button', { name: '追加' }), + ).toBeDisabled() + }, +} + export const テスト送信: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement) @@ -253,7 +322,7 @@ export const 操作のメニュー: Story = { }, } -export const 操作のメニュー_ブラウザ: Story = { +export const 操作のメニュー_このブラウザ: Story = { play: async ({ canvasElement }) => { await userEvent.click( within(canvasElement).getByRole('button', { @@ -330,26 +399,6 @@ export const 単発の通知の既定を変える: Story = { }, } -/** The log narrowed to one destination, as the page would answer the URL it is given. */ -function NarrowedLog(args: Story['args']) { - const [only, setOnly] = useState() - - return ( - only === undefined || delivery.destinationId === only, - ), - }} - actions={{ ...ACTIONS, onShowDeliveriesFor: setOnly }} - /> - ) -} - export const 配送を送り先で絞る: Story = { render: (args) => , play: async ({ canvasElement }) => { @@ -404,28 +453,6 @@ export const 送り先を追加_Slack: Story = { }, } -export const 送り先を追加する: Story = { - play: async ({ canvasElement }) => { - const dialog = within(await openTheWebhookForm(canvasElement)) - - addWebhook.mockClear() - - await userEvent.type(dialog.getByLabelText('名前'), '家の Slack') - await userEvent.type(dialog.getByLabelText('Webhook の URL'), SLACK_ADDRESS) - await userEvent.click(dialog.getByRole('button', { name: '追加' })) - - await waitFor(() => - expect(addWebhook).toHaveBeenCalledWith({ - name: '家の Slack', - url: SLACK_ADDRESS, - }), - ) - await waitFor(() => - expect(screen.queryByRole('dialog', { name: '送り先を追加' })).toBeNull(), - ) - }, -} - export const 送り先を追加_Discord: Story = { play: async ({ canvasElement }) => { const dialog = within(await openTheWebhookForm(canvasElement)) @@ -500,6 +527,28 @@ export const 送り先を追加_通知を拒否している: Story = { }, } +export const 送り先を追加する: Story = { + play: async ({ canvasElement }) => { + const dialog = within(await openTheWebhookForm(canvasElement)) + + addWebhook.mockClear() + + await userEvent.type(dialog.getByLabelText('名前'), '家の Slack') + await userEvent.type(dialog.getByLabelText('Webhook の URL'), SLACK_ADDRESS) + await userEvent.click(dialog.getByRole('button', { name: '追加' })) + + await waitFor(() => + expect(addWebhook).toHaveBeenCalledWith({ + name: '家の Slack', + url: SLACK_ADDRESS, + }), + ) + await waitFor(() => + expect(screen.queryByRole('dialog', { name: '送り先を追加' })).toBeNull(), + ) + }, +} + export const 送り先の追加を断られる: Story = { args: { actions: { @@ -688,21 +737,6 @@ export const ルールセットを追加: Story = { }, } -export const ルールセットが上限: Story = { - args: { - screen: { ...NOTIFICATIONS_SCREEN, ruleSets: TWENTY_RULE_SETS }, - }, - play: async ({ canvasElement }) => { - const ruleSets = within(canvasElement).getByRole('heading', { - name: 'ルールセット', - }).parentElement as HTMLElement - - await expect( - within(ruleSets).getByRole('button', { name: '追加' }), - ).toBeDisabled() - }, -} - export const 電話: Story = { parameters: { screen: PHONE, coarse: true }, play: async ({ canvasElement }) => { @@ -768,36 +802,3 @@ export const 電話_ルールセットを変更: Story = { ) }, } - -export const 送り先が多い: Story = { - args: { - screen: { - ...NOTIFICATIONS_SCREEN, - destinations: [ - ...DESTINATIONS, - { - ...HOME_SLACK, - id: 'dest-slack-2', - name: '実家のリビングの Slack のお知らせ用チャンネル', - urlTail: 'c3d4', - enabled: false, - lastResult: { - state: 'givenUp', - at: '2026-11-08T12:03:00Z', - failure: 'rejected', - }, - }, - ], - }, - }, - play: async ({ canvasElement }) => { - const canvas = within(canvasElement) - - await expect( - canvas.getByRole('switch', { - name: '実家のリビングの Slack のお知らせ用チャンネル を有効にする', - }), - ).not.toBeChecked() - await expect(canvas.getByText('届かなかった · 断られた')).toBeVisible() - }, -} From b8bd55384ae3d031823291dc84f8b1a4cd811216 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 03:05:30 +0900 Subject: [PATCH 09/24] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E3=81=AE=20API=20?= =?UTF-8?q?=E3=82=92=20OpenAPI=20=E3=81=AE=E6=96=87=E6=9B=B8=E3=81=A8?= =?UTF-8?q?=E7=94=9F=E6=88=90=E3=81=97=E3=81=9F=E5=9E=8B=E3=81=AB=E5=8F=96?= =?UTF-8?q?=E3=82=8A=E8=BE=BC=E3=82=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- repository/client/carina.json | 1585 +++++++++++++++++++++++++++++++-- repository/client/schema.ts | 920 +++++++++++++++++++ 2 files changed, 2439 insertions(+), 66 deletions(-) diff --git a/repository/client/carina.json b/repository/client/carina.json index 20005aec..984e9436 100644 --- a/repository/client/carina.json +++ b/repository/client/carina.json @@ -5726,6 +5726,789 @@ } } }, + "/api/notifications/destinations": { + "post": { + "tags": [ + "notifications" + ], + "operationId": "createNotificationDestination", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CreateNotificationDestinationRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CreateNotificationDestinationRequest" + } + ] + } + } + } + }, + "responses": { + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationResponder" + } + } + } + } + } + }, + "get": { + "tags": [ + "notifications" + ], + "operationId": "listNotificationDestinations", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationListResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationListResponder" + } + } + } + } + } + } + }, + "/api/notifications/rules": { + "post": { + "tags": [ + "notifications" + ], + "operationId": "createNotificationRule", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CreateNotificationRuleRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CreateNotificationRuleRequest" + } + ] + } + } + } + }, + "responses": { + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleResponder" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleResponder" + } + } + } + } + } + }, + "get": { + "tags": [ + "notifications" + ], + "operationId": "listNotificationRules", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleListResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleListResponder" + } + } + } + } + } + } + }, + "/api/notifications/settings": { + "get": { + "tags": [ + "notifications" + ], + "operationId": "getNotificationSettings", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationSettingsResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationSettingsResponder" + } + } + } + } + } + }, + "put": { + "tags": [ + "notifications" + ], + "operationId": "putNotificationSettings", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/PutNotificationSettingsRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/PutNotificationSettingsRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationSettingsResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationSettingsResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationSettingsResponder" + } + } + } + } + } + } + }, + "/api/notifications/deliveries": { + "get": { + "tags": [ + "notifications" + ], + "operationId": "listNotificationDeliveries", + "parameters": [ + { + "name": "destinationId", + "in": "query", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "perPage", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDeliveryListResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDeliveryListResponder" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDeliveryListResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDeliveryListResponder" + } + } + } + } + } + } + }, + "/api/notifications/destinations/{id}": { + "delete": { + "tags": [ + "notifications" + ], + "operationId": "removeNotificationDestination", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRemovalResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRemovalResponder" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRemovalResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRemovalResponder" + } + } + } + } + } + }, + "patch": { + "tags": [ + "notifications" + ], + "operationId": "reviseNotificationDestination", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ReviseNotificationDestinationRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ReviseNotificationDestinationRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationResponder" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationDestinationResponder" + } + } + } + } + } + } + }, + "/api/notifications/rules/{id}": { + "delete": { + "tags": [ + "notifications" + ], + "operationId": "removeNotificationRule", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRemovalResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRemovalResponder" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRemovalResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRemovalResponder" + } + } + } + } + } + }, + "patch": { + "tags": [ + "notifications" + ], + "operationId": "reviseNotificationRule", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ReviseNotificationRuleRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ReviseNotificationRuleRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleResponder" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationRuleResponder" + } + } + } + } + } + } + }, + "/api/notifications/destinations/{id}/test": { + "post": { + "tags": [ + "notifications" + ], + "operationId": "testNotificationDestination", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNoticeTrialResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNoticeTrialResponder" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNoticeTrialResponder" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNoticeTrialResponder" + } + } + } + }, + "429": { + "description": "Too Many Requests", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNoticeTrialResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNoticeTrialResponder" + } + } + } + } + } + } + }, "/api/migration/record": { "get": { "tags": [ @@ -10361,7 +11144,215 @@ } } }, - "BaseResponderOfLiveChannelListResponder": { + "BaseResponderOfLiveChannelListResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/LiveChannelListResponder" + } + ] + } + } + }, + "BaseResponderOfLiveDepartureTallyResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/LiveDepartureTallyResponder" + } + ] + } + } + }, + "BaseResponderOfMeResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/MeResponder" + } + ] + } + } + }, + "BaseResponderOfMigrationRecordResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/MigrationRecordResponder" + } + ] + } + } + }, + "BaseResponderOfNoticeTrialResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NoticeTrialResponder" + } + ] + } + } + }, + "BaseResponderOfNotificationDeliveryListResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NotificationDeliveryListResponder" + } + ] + } + } + }, + "BaseResponderOfNotificationDestinationListResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NotificationDestinationListResponder" + } + ] + } + } + }, + "BaseResponderOfNotificationDestinationResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NotificationDestinationResponder" + } + ] + } + } + }, + "BaseResponderOfNotificationRemovalResponder": { "required": [ "status", "message", @@ -10381,13 +11372,13 @@ "type": "null" }, { - "$ref": "#/components/schemas/LiveChannelListResponder" + "$ref": "#/components/schemas/NotificationRemovalResponder" } ] } } }, - "BaseResponderOfLiveDepartureTallyResponder": { + "BaseResponderOfNotificationRuleListResponder": { "required": [ "status", "message", @@ -10407,13 +11398,13 @@ "type": "null" }, { - "$ref": "#/components/schemas/LiveDepartureTallyResponder" + "$ref": "#/components/schemas/NotificationRuleListResponder" } ] } } }, - "BaseResponderOfMeResponder": { + "BaseResponderOfNotificationRuleResponder": { "required": [ "status", "message", @@ -10433,13 +11424,13 @@ "type": "null" }, { - "$ref": "#/components/schemas/MeResponder" + "$ref": "#/components/schemas/NotificationRuleResponder" } ] } } }, - "BaseResponderOfMigrationRecordResponder": { + "BaseResponderOfNotificationSettingsResponder": { "required": [ "status", "message", @@ -10459,7 +11450,7 @@ "type": "null" }, { - "$ref": "#/components/schemas/MigrationRecordResponder" + "$ref": "#/components/schemas/NotificationSettingsResponder" } ] } @@ -12800,6 +13791,59 @@ } } }, + "CreateNotificationDestinationRequest": { + "type": "object", + "properties": { + "name": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": [ + "null", + "string" + ] + } + } + }, + "CreateNotificationRuleRequest": { + "type": "object", + "properties": { + "name": { + "type": [ + "null", + "string" + ] + }, + "enabled": { + "type": [ + "null", + "boolean" + ] + }, + "events": { + "type": [ + "null", + "array" + ], + "items": { + "$ref": "#/components/schemas/NoticeKind" + } + }, + "destinations": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string", + "format": "uuid" + } + } + } + }, "CreateReservationRequest": { "type": "object", "properties": { @@ -15617,13 +16661,239 @@ "$ref": "#/components/schemas/MigrationLossResponder" } }, - "items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/MigrationDetailResponder" - } + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MigrationDetailResponder" + } + }, + "total": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "currentPage": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "lastPage": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "perPage": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + }, + "MigrationRefusal": { + "enum": [ + "reallyEmpty", + "fileMissing", + "orphan", + "unidentifiable", + "inexpressible", + "noSuchFeature", + "outOfScope" + ], + "type": "string" + }, + "MigrationRefusalResponder": { + "required": [ + "refusal", + "count" + ], + "type": "object", + "properties": { + "refusal": { + "$ref": "#/components/schemas/MigrationRefusal" + }, + "count": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + }, + "MigrationRunResponder": { + "required": [ + "id", + "source", + "pass", + "startedAt", + "finishedAt", + "rehearsals", + "lastRehearsalFinishedAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "source": { + "type": "string" + }, + "pass": { + "$ref": "#/components/schemas/MigrationPass" + }, + "startedAt": { + "type": "string", + "format": "date-time" + }, + "finishedAt": { + "type": "string", + "format": "date-time" + }, + "rehearsals": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "lastRehearsalFinishedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + } + } + }, + "NoticeFailure": { + "enum": [ + "timedOut", + "rateLimited", + "serverFailed", + "unreachable", + "rejected", + "destinationDisabled", + "unreadable", + "tooOld", + "tlsFailed", + null + ], + "type": [ + "null", + "string" + ] + }, + "NoticeKind": { + "enum": [ + "recordingStarted", + "recordingCompleted", + "recordingTruncated", + "recordingFailed", + "encodeStarted", + "encodeCompleted", + "encodeFailed", + "reservationCompeting", + "reservationMissed", + "programmeMoved", + "qualityIncidentDetected", + "qualityIncidentResolved", + "deviceDisconnected" + ], + "type": "string" + }, + "NoticeTrialResponder": { + "required": [ + "delivered", + "failure" + ], + "type": "object", + "properties": { + "delivered": { + "type": "boolean" + }, + "failure": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NoticeFailure" + } + ] + } + } + }, + "NotificationDeliveryListResponder": { + "required": [ + "perPage", + "items" + ], + "type": "object", + "properties": { + "perPage": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NotificationDeliveryResponder" + } + } + } + }, + "NotificationDeliveryResponder": { + "required": [ + "id", + "kind", + "title", + "occurredAt", + "state", + "attempts", + "queuedAt", + "sentAt", + "nextAttemptAt", + "failure" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "kind": { + "$ref": "#/components/schemas/NoticeKind" + }, + "title": { + "type": "string" + }, + "occurredAt": { + "type": "string", + "format": "date-time" + }, + "state": { + "$ref": "#/components/schemas/NotificationDeliveryState" }, - "total": { + "attempts": { "pattern": "^-?(?:0|[1-9]\\d*)$", "type": [ "integer", @@ -15631,73 +16901,155 @@ ], "format": "int32" }, - "currentPage": { - "pattern": "^-?(?:0|[1-9]\\d*)$", - "type": [ - "integer", - "string" - ], - "format": "int32" + "queuedAt": { + "type": "string", + "format": "date-time" }, - "lastPage": { - "pattern": "^-?(?:0|[1-9]\\d*)$", + "sentAt": { "type": [ - "integer", + "null", "string" ], - "format": "int32" + "format": "date-time" }, - "perPage": { - "pattern": "^-?(?:0|[1-9]\\d*)$", + "nextAttemptAt": { "type": [ - "integer", + "null", "string" ], - "format": "int32" + "format": "date-time" + }, + "failure": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NoticeFailure" + } + ] } } }, - "MigrationRefusal": { + "NotificationDeliveryState": { "enum": [ - "reallyEmpty", - "fileMissing", - "orphan", - "unidentifiable", - "inexpressible", - "noSuchFeature", - "outOfScope" + "queued", + "sent", + "failed", + "givenUp" ], "type": "string" }, - "MigrationRefusalResponder": { + "NotificationDestinationListResponder": { "required": [ - "refusal", - "count" + "items" ], "type": "object", "properties": { - "refusal": { - "$ref": "#/components/schemas/MigrationRefusal" + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NotificationDestinationResponder" + } + } + } + }, + "NotificationDestinationResponder": { + "required": [ + "id", + "name", + "kind", + "tail", + "enabled", + "readable", + "lastResultAt", + "lastFailure", + "createdAt", + "changedAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" }, - "count": { - "pattern": "^-?(?:0|[1-9]\\d*)$", + "name": { + "type": "string" + }, + "kind": { + "$ref": "#/components/schemas/WebhookTarget" + }, + "tail": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "readable": { + "type": "boolean" + }, + "lastResultAt": { "type": [ - "integer", + "null", "string" ], - "format": "int32" + "format": "date-time" + }, + "lastFailure": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NoticeFailure" + } + ] + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "changedAt": { + "type": "string", + "format": "date-time" } } }, - "MigrationRunResponder": { + "NotificationRemovalResponder": { + "required": [ + "id" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + } + } + }, + "NotificationRuleListResponder": { + "required": [ + "items" + ], + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NotificationRuleResponder" + } + } + } + }, + "NotificationRuleResponder": { "required": [ "id", - "source", - "pass", - "startedAt", - "finishedAt", - "rehearsals", - "lastRehearsalFinishedAt" + "name", + "enabled", + "events", + "destinations", + "createdAt", + "changedAt" ], "type": "object", "properties": { @@ -15705,21 +17057,43 @@ "type": "string", "format": "uuid" }, - "source": { + "name": { "type": "string" }, - "pass": { - "$ref": "#/components/schemas/MigrationPass" + "enabled": { + "type": "boolean" }, - "startedAt": { + "events": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NoticeKind" + } + }, + "destinations": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + }, + "createdAt": { "type": "string", "format": "date-time" }, - "finishedAt": { + "changedAt": { "type": "string", "format": "date-time" - }, - "rehearsals": { + } + } + }, + "NotificationSettingsResponder": { + "required": [ + "notifyLeadMinutes", + "publicOriginKnown" + ], + "type": "object", + "properties": { + "notifyLeadMinutes": { "pattern": "^-?(?:0|[1-9]\\d*)$", "type": [ "integer", @@ -15727,12 +17101,8 @@ ], "format": "int32" }, - "lastRehearsalFinishedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" + "publicOriginKnown": { + "type": "boolean" } } }, @@ -16505,6 +17875,20 @@ } } }, + "PutNotificationSettingsRequest": { + "type": "object", + "properties": { + "notifyLeadMinutes": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ], + "format": "int32" + } + } + }, "PutPlaybackPositionRequest": { "required": [ "positionSec" @@ -20173,6 +21557,65 @@ } } }, + "ReviseNotificationDestinationRequest": { + "type": "object", + "properties": { + "name": { + "type": [ + "null", + "string" + ] + }, + "url": { + "type": [ + "null", + "string" + ] + }, + "enabled": { + "type": [ + "null", + "boolean" + ] + } + } + }, + "ReviseNotificationRuleRequest": { + "type": "object", + "properties": { + "name": { + "type": [ + "null", + "string" + ] + }, + "enabled": { + "type": [ + "null", + "boolean" + ] + }, + "events": { + "type": [ + "null", + "array" + ], + "items": { + "$ref": "#/components/schemas/NoticeKind" + } + }, + "destinations": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string", + "format": "uuid" + } + } + } + }, "ReviseQualityThresholdRequest": { "required": [ "value" @@ -23330,6 +24773,13 @@ "format": "int32" } } + }, + "WebhookTarget": { + "enum": [ + "slack", + "discord" + ], + "type": "string" } } }, @@ -23367,6 +24817,9 @@ { "name": "quality" }, + { + "name": "notifications" + }, { "name": "migration" }, diff --git a/repository/client/schema.ts b/repository/client/schema.ts index 49d3ec99..7509e957 100644 --- a/repository/client/schema.ts +++ b/repository/client/schema.ts @@ -1053,6 +1053,118 @@ export interface paths { patch: operations['reviseQualityThreshold'] trace?: never } + '/api/notifications/destinations': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get: operations['listNotificationDestinations'] + put?: never + post: operations['createNotificationDestination'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/notifications/rules': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get: operations['listNotificationRules'] + put?: never + post: operations['createNotificationRule'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/notifications/settings': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get: operations['getNotificationSettings'] + put: operations['putNotificationSettings'] + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/notifications/deliveries': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get: operations['listNotificationDeliveries'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/notifications/destinations/{id}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + post?: never + delete: operations['removeNotificationDestination'] + options?: never + head?: never + patch: operations['reviseNotificationDestination'] + trace?: never + } + '/api/notifications/rules/{id}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + post?: never + delete: operations['removeNotificationRule'] + options?: never + head?: never + patch: operations['reviseNotificationRule'] + trace?: never + } + '/api/notifications/destinations/{id}/test': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + post: operations['testNotificationDestination'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } '/api/migration/record': { parameters: { query?: never @@ -1984,6 +2096,46 @@ export interface components { message: string data: null | components['schemas']['MigrationRecordResponder'] } + BaseResponderOfNoticeTrialResponder: { + status: boolean + message: string + data: null | components['schemas']['NoticeTrialResponder'] + } + BaseResponderOfNotificationDeliveryListResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationDeliveryListResponder'] + } + BaseResponderOfNotificationDestinationListResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationDestinationListResponder'] + } + BaseResponderOfNotificationDestinationResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationDestinationResponder'] + } + BaseResponderOfNotificationRemovalResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationRemovalResponder'] + } + BaseResponderOfNotificationRuleListResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationRuleListResponder'] + } + BaseResponderOfNotificationRuleResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationRuleResponder'] + } + BaseResponderOfNotificationSettingsResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationSettingsResponder'] + } BaseResponderOfOidcConfigRefusedResponder: { status: boolean message: string @@ -2470,6 +2622,16 @@ export interface components { /** Format: int32 */ quantiser?: null | number | string } + CreateNotificationDestinationRequest: { + name?: null | string + url?: null | string + } + CreateNotificationRuleRequest: { + name?: null | string + enabled?: null | boolean + events?: null | components['schemas']['NoticeKind'][] + destinations?: null | string[] + } CreateReservationRequest: { programme?: null | string /** Format: date-time */ @@ -3215,6 +3377,105 @@ export interface components { /** Format: date-time */ lastRehearsalFinishedAt: null | string } + /** @enum {null|string} */ + NoticeFailure: + | 'timedOut' + | 'rateLimited' + | 'serverFailed' + | 'unreachable' + | 'rejected' + | 'destinationDisabled' + | 'unreadable' + | 'tooOld' + | 'tlsFailed' + | null + /** @enum {string} */ + NoticeKind: + | 'recordingStarted' + | 'recordingCompleted' + | 'recordingTruncated' + | 'recordingFailed' + | 'encodeStarted' + | 'encodeCompleted' + | 'encodeFailed' + | 'reservationCompeting' + | 'reservationMissed' + | 'programmeMoved' + | 'qualityIncidentDetected' + | 'qualityIncidentResolved' + | 'deviceDisconnected' + NoticeTrialResponder: { + delivered: boolean + failure: null | components['schemas']['NoticeFailure'] + } + NotificationDeliveryListResponder: { + /** Format: int32 */ + perPage: number | string + items: components['schemas']['NotificationDeliveryResponder'][] + } + NotificationDeliveryResponder: { + /** Format: uuid */ + id: string + kind: components['schemas']['NoticeKind'] + title: string + /** Format: date-time */ + occurredAt: string + state: components['schemas']['NotificationDeliveryState'] + /** Format: int32 */ + attempts: number | string + /** Format: date-time */ + queuedAt: string + /** Format: date-time */ + sentAt: null | string + /** Format: date-time */ + nextAttemptAt: null | string + failure: null | components['schemas']['NoticeFailure'] + } + /** @enum {string} */ + NotificationDeliveryState: 'queued' | 'sent' | 'failed' | 'givenUp' + NotificationDestinationListResponder: { + items: components['schemas']['NotificationDestinationResponder'][] + } + NotificationDestinationResponder: { + /** Format: uuid */ + id: string + name: string + kind: components['schemas']['WebhookTarget'] + tail: string + enabled: boolean + readable: boolean + /** Format: date-time */ + lastResultAt: null | string + lastFailure: null | components['schemas']['NoticeFailure'] + /** Format: date-time */ + createdAt: string + /** Format: date-time */ + changedAt: string + } + NotificationRemovalResponder: { + /** Format: uuid */ + id: string + } + NotificationRuleListResponder: { + items: components['schemas']['NotificationRuleResponder'][] + } + NotificationRuleResponder: { + /** Format: uuid */ + id: string + name: string + enabled: boolean + events: components['schemas']['NoticeKind'][] + destinations: string[] + /** Format: date-time */ + createdAt: string + /** Format: date-time */ + changedAt: string + } + NotificationSettingsResponder: { + /** Format: int32 */ + notifyLeadMinutes: number | string + publicOriginKnown: boolean + } /** @enum {string} */ OidcConfigRefusal: | 'secretRequired' @@ -3397,6 +3658,10 @@ export interface components { /** Format: int32 */ mostCores?: null | number | string } + PutNotificationSettingsRequest: { + /** Format: int32 */ + notifyLeadMinutes?: null | number | string + } PutPlaybackPositionRequest: { /** Format: double */ positionSec: null | number | string @@ -4326,6 +4591,17 @@ export interface components { /** Format: int32 */ quantiser?: null | number | string } + ReviseNotificationDestinationRequest: { + name?: null | string + url?: null | string + enabled?: null | boolean + } + ReviseNotificationRuleRequest: { + name?: null | string + enabled?: null | boolean + events?: null | components['schemas']['NoticeKind'][] + destinations?: null | string[] + } ReviseQualityThresholdRequest: { /** Format: double */ value: null | number | string @@ -5114,6 +5390,8 @@ export interface components { /** Format: int32 */ versionChanges: number | string } + /** @enum {string} */ + WebhookTarget: 'slack' | 'discord' } responses: never parameters: never @@ -9387,6 +9665,648 @@ export interface operations { } } } + listNotificationDestinations: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationListResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationListResponder'] + } + } + } + } + createNotificationDestination: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: { + content: { + 'application/json': + null | components['schemas']['CreateNotificationDestinationRequest'] + 'application/*+json': + null | components['schemas']['CreateNotificationDestinationRequest'] + } + } + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationResponder'] + } + } + } + } + listNotificationRules: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleListResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleListResponder'] + } + } + } + } + createNotificationRule: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: { + content: { + 'application/json': + null | components['schemas']['CreateNotificationRuleRequest'] + 'application/*+json': + null | components['schemas']['CreateNotificationRuleRequest'] + } + } + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleResponder'] + } + } + } + } + getNotificationSettings: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationSettingsResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationSettingsResponder'] + } + } + } + } + putNotificationSettings: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: { + content: { + 'application/json': + null | components['schemas']['PutNotificationSettingsRequest'] + 'application/*+json': + null | components['schemas']['PutNotificationSettingsRequest'] + } + } + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationSettingsResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationSettingsResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationSettingsResponder'] + } + } + } + } + listNotificationDeliveries: { + parameters: { + query?: { + destinationId?: string + perPage?: number | string + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDeliveryListResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDeliveryListResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDeliveryListResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDeliveryListResponder'] + } + } + } + } + removeNotificationDestination: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRemovalResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRemovalResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRemovalResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRemovalResponder'] + } + } + } + } + reviseNotificationDestination: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: { + content: { + 'application/json': + null | components['schemas']['ReviseNotificationDestinationRequest'] + 'application/*+json': + null | components['schemas']['ReviseNotificationDestinationRequest'] + } + } + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationDestinationResponder'] + } + } + } + } + removeNotificationRule: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRemovalResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRemovalResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRemovalResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRemovalResponder'] + } + } + } + } + reviseNotificationRule: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: { + content: { + 'application/json': + null | components['schemas']['ReviseNotificationRuleRequest'] + 'application/*+json': + null | components['schemas']['ReviseNotificationRuleRequest'] + } + } + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationRuleResponder'] + } + } + } + } + testNotificationDestination: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNoticeTrialResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNoticeTrialResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNoticeTrialResponder'] + } + } + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNoticeTrialResponder'] + } + } + /** @description Too Many Requests */ + 429: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNoticeTrialResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNoticeTrialResponder'] + } + } + } + } getMigrationRecord: { parameters: { query?: { From 23686a6b318a6aafb3a5b7f5460cb2ffb440b4f8 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 03:24:20 +0900 Subject: [PATCH 10/24] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E3=81=AE=E7=94=BB?= =?UTF-8?q?=E9=9D=A2=E3=81=AE=E5=9E=8B=E3=82=92=20API=20=E3=81=AE=E5=BD=A2?= =?UTF-8?q?=E3=81=AB=E5=90=88=E3=82=8F=E3=81=9B=E3=80=81=E9=80=81=E3=82=8A?= =?UTF-8?q?=E5=85=88=E3=81=AE=E5=89=8A=E9=99=A4=E3=81=A7=E4=B8=80=E7=B7=92?= =?UTF-8?q?=E3=81=AB=E6=B6=88=E3=81=88=E3=82=8B=E3=83=AB=E3=83=BC=E3=83=AB?= =?UTF-8?q?=E3=82=BB=E3=83=83=E3=83=88=E3=81=AE=E5=90=8D=E5=89=8D=E3=82=92?= =?UTF-8?q?=E5=87=BA=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- .../notifications/add-destination-dialog.tsx | 43 ++-- components/notifications/delivery-log.tsx | 28 ++- components/notifications/destination-list.tsx | 22 +- .../notifications/edit-destination-dialog.tsx | 2 +- .../notifications/notifications-page.tsx | 59 +++-- components/notifications/remove-button.tsx | 5 +- components/notifications/rule-set-dialog.tsx | 6 +- components/notifications/rule-set-list.tsx | 2 +- lib/notifications.ts | 169 +++++++++++---- stories/fixtures/notifications.ts | 101 +++------ stories/screens/Notifications.stories.tsx | 120 +++++++---- tests/lib/notifications.test.ts | 202 +++++++++++++++--- 12 files changed, 497 insertions(+), 262 deletions(-) diff --git a/components/notifications/add-destination-dialog.tsx b/components/notifications/add-destination-dialog.tsx index 35d4bb79..b9ce697f 100644 --- a/components/notifications/add-destination-dialog.tsx +++ b/components/notifications/add-destination-dialog.tsx @@ -48,26 +48,31 @@ export const DENIED_HERE = type Step = 'pick' | 'webhook' | 'browser' -/** `追加` and the dialog it opens: first which kind of destination, then the form for that kind, with a way back to the choice. */ +/** This browser as a destination: what a person calls it, whether it lets notices through, and what adds it. */ +export interface BrowserChoice { + here: string + permission: BrowserPermission + onAdd: (draft: BrowserDraft) => Promise +} + +/** `追加` and the dialog it opens: the form for a webhook, or, where this browser can be a destination too, the choice of kind first with a way back to it. */ export function AddDestinationDialog({ - here, - permission, + browser, onAddWebhook, - onAddBrowser, }: { - here: string - permission: BrowserPermission + browser?: BrowserChoice onAddWebhook: (draft: WebhookDraft) => Promise - onAddBrowser: (draft: BrowserDraft) => Promise }) { + const first: Step = browser ? 'pick' : 'webhook' const [open, setOpen] = useState(false) - const [step, setStep] = useState('pick') + const [step, setStep] = useState(first) + const back = browser ? () => setStep('pick') : undefined const openTo = (next: boolean) => { setOpen(next) if (next) { - setStep('pick') + setStep(first) } } @@ -78,21 +83,23 @@ export function AddDestinationDialog({ 追加 - {step === 'pick' && } + {step === 'pick' && browser && ( + + )} {step === 'webhook' && ( setStep('pick')} + onBack={back} onClose={() => setOpen(false)} onAdd={onAddWebhook} /> )} - {step === 'browser' && ( + {step === 'browser' && browser && ( setStep('pick')} + here={browser.here} + permission={browser.permission} + onBack={back} onClose={() => setOpen(false)} - onAdd={onAddBrowser} + onAdd={browser.onAdd} /> )} @@ -199,7 +206,7 @@ function WebhookForm({ onClose, onAdd, }: { - onBack: () => void + onBack?: () => void onClose: () => void onAdd: (draft: WebhookDraft) => Promise }) { @@ -263,7 +270,7 @@ function BrowserForm({ }: { here: string permission: BrowserPermission - onBack: () => void + onBack?: () => void onClose: () => void onAdd: (draft: BrowserDraft) => Promise }) { diff --git a/components/notifications/delivery-log.tsx b/components/notifications/delivery-log.tsx index 78b75f1b..bfa955c4 100644 --- a/components/notifications/delivery-log.tsx +++ b/components/notifications/delivery-log.tsx @@ -83,11 +83,15 @@ export function DeliveryFilter({ export function DeliveryLog({ deliveries, + destinations, now, }: { deliveries: NotificationDelivery[] + destinations: Pick[] now: number }) { + const names = new Map(destinations.map(({ id, name }) => [id, name])) + return (
            {deliveries.map((delivery) => ( - + ))}
          @@ -113,9 +122,11 @@ export function DeliveryLog({ function DeliveryRow({ delivery, + sentTo, now, }: { delivery: NotificationDelivery + sentTo?: string now: number }) { const said = deliverySaid(delivery) @@ -131,25 +142,22 @@ function DeliveryRow({ - {deliveryMoment(delivery.at, now)} + {deliveryMoment(delivery.occurredAt, now)} - {deliveryClock(delivery.at)} + {deliveryClock(delivery.occurredAt)} - {delivery.destinationName} + {sentTo} - - - {eventLabelOf(delivery.event)} - - {delivery.subject} - + + {eventLabelOf(delivery.kind)} + diff --git a/components/notifications/destination-list.tsx b/components/notifications/destination-list.tsx index 6ba670e9..11d70731 100644 --- a/components/notifications/destination-list.tsx +++ b/components/notifications/destination-list.tsx @@ -5,11 +5,14 @@ import { useState, useTransition } from 'react' import { cn } from '@/lib/utils' import { signedOut } from '@/lib/signed-out' import { + goingToo, lastResultSaid, + ruleSetsGoingWith, tailOf, testSaid, withWhy, type NotificationDestination, + type NotificationRuleSet, type NotificationWrite, type Said, type TestSending, @@ -79,10 +82,12 @@ function refusalOf(result: Exclude) { export function DestinationList({ destinations, + ruleSets, actions, now, }: { destinations: NotificationDestination[] + ruleSets: Pick[] actions: DestinationActions now: number }) { @@ -95,6 +100,9 @@ export function DestinationList({ name, + )} actions={actions} now={now} /> @@ -155,10 +163,13 @@ function ResultLine({ function DestinationRow({ destination, + goingWith, actions, now, }: { destination: NotificationDestination + /** The names of the rule sets that are removed when this destination is. */ + goingWith: string[] actions: DestinationActions now: number }) { @@ -168,7 +179,7 @@ function DestinationRow({ const [editing, setEditing] = useState(false) const [removing, setRemoving] = useState(false) const say = useToast() - const { id, name, kind, urlTail, lastResult } = destination + const { id, name, kind, tail } = destination const webhook = kind !== 'webPush' const toggle = async (next: boolean) => { @@ -209,17 +220,17 @@ function DestinationRow({ {name} - {urlTail && ( + {tail && ( - {tailOf(urlTail)} + {tailOf(tail)} )} actions.onRemoveDestination(id)} diff --git a/components/notifications/edit-destination-dialog.tsx b/components/notifications/edit-destination-dialog.tsx index 01b8d781..f72233e3 100644 --- a/components/notifications/edit-destination-dialog.tsx +++ b/components/notifications/edit-destination-dialog.tsx @@ -133,7 +133,7 @@ function EditDestinationForm({ placeholder="変えないときは空のまま" hint={[ wordFor(KIND_LABEL, destination.kind), - destination.urlTail && `末尾 ${tailOf(destination.urlTail)}`, + destination.tail && `末尾 ${tailOf(destination.tail)}`, ] .filter(Boolean) .join(' · ')} diff --git a/components/notifications/notifications-page.tsx b/components/notifications/notifications-page.tsx index 0aa3b98d..2f7c689f 100644 --- a/components/notifications/notifications-page.tsx +++ b/components/notifications/notifications-page.tsx @@ -4,14 +4,12 @@ import { useState, type ReactNode } from 'react' import { cn } from '@/lib/utils' import { signedOut } from '@/lib/signed-out' -import type { - BrowserPermission, - LeadMinutes, - NotificationDelivery, - NotificationDestination, - NotificationRuleSet, - NotificationSettings, - NotificationWrite, +import { + deliveriesShown, + narrowedTo, + type LeadMinutes, + type NotificationsScreen, + type NotificationWrite, } from '@/lib/notifications' import { Banner } from '@/components/vela/banner' import { PageHeading } from '@/components/vela/section-heading' @@ -19,7 +17,7 @@ import { SettingsGroup } from '@/components/vela/settings-rows' import { useToast } from '@/components/vela/toast' import { AddDestinationDialog, - type BrowserDraft, + type BrowserChoice, type WebhookDraft, } from '@/components/notifications/add-destination-dialog' import { @@ -37,21 +35,10 @@ import { type RuleSetActions, } from '@/components/notifications/rule-set-list' -export interface NotificationsScreen { - settings: NotificationSettings - destinations: NotificationDestination[] - ruleSets: NotificationRuleSet[] - deliveries: NotificationDelivery[] - /** The destination the log is narrowed to; every destination when absent. */ - deliveriesFor?: string -} - export interface NotificationActions extends DestinationActions, RuleSetActions { onAddWebhook: (draft: WebhookDraft) => Promise - onAddBrowser: (draft: BrowserDraft) => Promise onSettleLead: (lead: LeadMinutes) => Promise - onShowDeliveriesFor: (destinationId: string | undefined) => void } export const NO_PUBLIC_ORIGIN = @@ -84,21 +71,22 @@ function Nothing({ children }: { children: string }) { export function NotificationsView({ screen, actions, - here, - permission, + browser, now, }: { screen: NotificationsScreen actions: NotificationActions - /** This browser as a person names it, `Windows の Chrome`. */ - here: string - permission: BrowserPermission + /** This browser as a destination, where it can be one. */ + browser?: BrowserChoice /** The moment the screen was drawn for, which today's times are said against. */ now: number }) { - const { settings, destinations, ruleSets, deliveries } = screen - const [lead, setLead] = useState(settings.leadMinutes) + const { settings, destinations, ruleSets } = screen + const [lead, setLead] = useState(settings.notifyLeadMinutes) const [addingRuleSet, setAddingRuleSet] = useState(false) + const [chosen, setChosen] = useState() + const logFor = narrowedTo(destinations, chosen) + const deliveries = deliveriesShown(screen.deliveries, logFor) const say = useToast() const settleLead = async (next: LeadMinutes) => { @@ -120,7 +108,7 @@ export function NotificationsView({ <> 通知 - {!settings.hasPublicOrigin && ( + {!settings.publicOriginKnown && ( {NO_PUBLIC_ORIGIN} @@ -130,10 +118,8 @@ export function NotificationsView({ } > @@ -142,6 +128,7 @@ export function NotificationsView({ {destinations.length > 0 ? ( @@ -198,8 +185,8 @@ export function NotificationsView({ destinations.length > 0 && ( ) } @@ -207,7 +194,11 @@ export function NotificationsView({ 直近の配送 {deliveries.length > 0 ? ( - + ) : ( 配送の記録はありません )} diff --git a/components/notifications/remove-button.tsx b/components/notifications/remove-button.tsx index 87ca955d..cd2ea216 100644 --- a/components/notifications/remove-button.tsx +++ b/components/notifications/remove-button.tsx @@ -21,10 +21,11 @@ import { Spinner } from '@/components/vela/progress' const SIGNED_OUT = signedOut('削除') -/** The question asked before anything goes: the name of what goes, and that it cannot come back. */ +/** The question asked before anything goes: the name of what goes, what goes with it, and that it cannot come back. */ export function RemoveDialog({ what, name, + also, open, onOpenChange, onRemove, @@ -32,6 +33,7 @@ export function RemoveDialog({ }: { what: '送り先' | 'ルールセット' name: string + also?: string open: boolean onOpenChange: (open: boolean) => void onRemove: () => Promise @@ -71,6 +73,7 @@ export function RemoveDialog({ この{what}を削除します {name} + {also && {also}} 元に戻せません。 diff --git a/components/notifications/rule-set-dialog.tsx b/components/notifications/rule-set-dialog.tsx index badd88f4..a232851c 100644 --- a/components/notifications/rule-set-dialog.tsx +++ b/components/notifications/rule-set-dialog.tsx @@ -35,7 +35,7 @@ const FRESH: RuleSetDraft = { name: '', enabled: true, events: [], - destinationIds: [], + destinations: [], } /** The editor of a rule set: its name, whether it is on, the events it sends, and where it sends them. `削除` stands only for a rule set that already is. */ @@ -89,7 +89,7 @@ function RuleSetForm({ const [name, setName] = useState(from.name) const [enabled, setEnabled] = useState(from.enabled) const [events, setEvents] = useState(from.events) - const [sendTo, setSendTo] = useState(from.destinationIds) + const [sendTo, setSendTo] = useState(from.destinations) const [refusal, setRefusal] = useState() const [pending, startTransition] = useTransition() const ready = nameFits(name) && sendTo.length > 0 && !pending @@ -103,7 +103,7 @@ function RuleSetForm({ name: name.trim(), enabled, events, - destinationIds: sendTo, + destinations: sendTo, }) if (result.state === 'ok') { diff --git a/components/notifications/rule-set-list.tsx b/components/notifications/rule-set-list.tsx index 037f3d57..2777eb55 100644 --- a/components/notifications/rule-set-list.tsx +++ b/components/notifications/rule-set-list.tsx @@ -91,7 +91,7 @@ export function RuleSetList({ { + sendsTo={ruleSet.destinations.flatMap((id) => { const name = nameOf.get(id) return name === undefined ? [] : [name] diff --git a/lib/notifications.ts b/lib/notifications.ts index c2cff1e7..de863c6c 100644 --- a/lib/notifications.ts +++ b/lib/notifications.ts @@ -10,20 +10,27 @@ export type WebhookKind = 'slack' | 'discord' export type DestinationKind = WebhookKind | 'webPush' export type DeliveryFailure = - 'timeout' | 'rateLimited' | 'rejected' | 'tls' | 'unreachable' - -export type DestinationResult = - | { state: 'sent'; at: string } - | { state: 'failed' | 'givenUp'; at: string; failure: DeliveryFailure } + | 'timedOut' + | 'rateLimited' + | 'serverFailed' + | 'unreachable' + | 'rejected' + | 'destinationDisabled' + | 'unreadable' + | 'tooOld' + | 'tlsFailed' /** A place notices are sent to. A webhook's address never comes back from Carina, only its last four characters. */ export interface NotificationDestination { id: string name: string kind: DestinationKind - urlTail?: string + tail?: string enabled: boolean - lastResult?: DestinationResult + /** Whether Carina can still open the address it keeps sealed. */ + readable: boolean + lastResultAt?: string + lastFailure?: DeliveryFailure } export type NotificationEvent = @@ -37,8 +44,8 @@ export type NotificationEvent = | 'reservationCompeting' | 'reservationMissed' | 'programmeMoved' - | 'qualityRaised' - | 'qualityResolved' + | 'qualityIncidentDetected' + | 'qualityIncidentResolved' | 'deviceDisconnected' export interface NotificationRuleSet { @@ -46,20 +53,19 @@ export interface NotificationRuleSet { name: string enabled: boolean events: NotificationEvent[] - destinationIds: string[] + destinations: string[] } export type RuleSetDraft = Omit export type DeliveryState = 'queued' | 'sent' | 'failed' | 'givenUp' +/** One notice on its way to one destination. Its title is the heading Carina gave the notice. */ export interface NotificationDelivery { id: string - at: string - event: NotificationEvent | 'programmeStarting' - subject: string + kind: NotificationEvent + occurredAt: string destinationId: string - destinationName: string state: DeliveryState failure?: DeliveryFailure } @@ -69,8 +75,16 @@ export const LEADS = [0, 1, 3, 5, 10] as const export type LeadMinutes = (typeof LEADS)[number] export interface NotificationSettings { - leadMinutes: LeadMinutes - hasPublicOrigin: boolean + notifyLeadMinutes: LeadMinutes + publicOriginKnown: boolean +} + +export interface NotificationsScreen { + settings: NotificationSettings + destinations: NotificationDestination[] + ruleSets: NotificationRuleSet[] + /** What went to every destination lately, the newest first. */ + deliveries: NotificationDelivery[] } /** A notice that a programme is about to start, set from the guide without recording it. */ @@ -86,8 +100,7 @@ export type NotificationWrite = | { state: 'rejected'; message: string } export type TestSending = - | { state: 'ok'; delivered: true } - | { state: 'ok'; delivered: false; failure: DeliveryFailure } + | { state: 'ok'; delivered: boolean; failure?: DeliveryFailure } | { state: 'unauthenticated' } | { state: 'rejected'; message: string } @@ -102,13 +115,25 @@ export const KIND_LABEL: Record = { } export const FAILURE_LABEL: Record = { - timeout: '時間切れ', + timedOut: '時間切れ', rateLimited: '回数の上限', - rejected: '断られた', - tls: '暗号化の失敗', + serverFailed: '送り先の障害', unreachable: 'つながらない', + rejected: '断られた', + destinationDisabled: '送り先が無効', + unreadable: '開けない', + tooOld: '古くなった', + tlsFailed: '暗号化の失敗', } +const WORTH_ANOTHER_TRY: ReadonlySet = new Set([ + 'timedOut', + 'rateLimited', + 'serverFailed', + 'unreachable', + 'tlsFailed', +]) + const SLACK_HOST = 'hooks.slack.com' const DISCORD_HOSTS = new Set(['discord.com', 'discordapp.com']) @@ -164,8 +189,8 @@ export function registeringAs(kind: WebhookKind): string { return `${KIND_LABEL[kind]} として登録します` } -export function tailOf(urlTail: string): string { - return `…${urlTail}` +export function tailOf(tail: string): string { + return `…${tail}` } export interface EventGroup { @@ -208,8 +233,8 @@ export const EVENT_GROUPS: EventGroup[] = [ name: '品質', prefix: '', events: [ - { event: 'qualityRaised', label: '異常の発生' }, - { event: 'qualityResolved', label: '解消' }, + { event: 'qualityIncidentDetected', label: '異常の発生' }, + { event: 'qualityIncidentResolved', label: '解消' }, ], }, { @@ -235,7 +260,7 @@ export function eventsSummary(events: readonly NotificationEvent[]): string { return said.length === 0 ? NO_EVENTS : said.join(' · ') } -export const EVENT_LABEL: Record = { +export const EVENT_LABEL: Record = { recordingStarted: '録画の開始', recordingCompleted: '録画の完了', recordingTruncated: '録画の欠け', @@ -246,13 +271,12 @@ export const EVENT_LABEL: Record = { reservationCompeting: '予約の競合', reservationMissed: '予約の取り逃し', programmeMoved: '番組の移動', - qualityRaised: '品質の異常の発生', - qualityResolved: '品質の異常の解消', + qualityIncidentDetected: '品質の異常の発生', + qualityIncidentResolved: '品質の異常の解消', deviceDisconnected: '機器の切断', - programmeStarting: '放送開始の通知', } -export function eventLabelOf(event: NotificationDelivery['event']): string { +export function eventLabelOf(event: NotificationEvent): string { return wordFor(EVENT_LABEL, event) } @@ -282,26 +306,43 @@ export interface Said { why?: string } -function failureWord(failure: DeliveryFailure | undefined): string | undefined { +export function failureWord( + failure: DeliveryFailure | undefined, +): string | undefined { return failure === undefined ? undefined : wordFor(FAILURE_LABEL, failure) } -/** How the last notice sent to a destination went: reached it, still being tried, or given up on. */ +/** How the last notice sent to a destination went: reached it, not yet there, or never will be. Nothing while none was sent. */ export function lastResultSaid( - result: DestinationResult, + destination: Pick< + NotificationDestination, + 'readable' | 'lastResultAt' | 'lastFailure' + >, now: number = Date.now(), -): Said { - if (result.state === 'sent') { +): Said | undefined { + const { readable, lastResultAt, lastFailure } = destination + + if (!readable) { + return { verdict: 'err', words: FAILURE_LABEL.unreadable } + } + + if (lastResultAt === undefined) { + return undefined + } + + if (lastFailure === undefined) { return { verdict: 'ok', - words: `届いた ${formatRecentMoment(result.at, now)}`, + words: `届いた ${formatRecentMoment(lastResultAt, now)}`, } } + const retried = WORTH_ANOTHER_TRY.has(lastFailure) + return { - verdict: result.state === 'failed' ? 'warn' : 'err', - words: result.state === 'failed' ? '届いていない' : '届かなかった', - why: failureWord(result.failure), + verdict: retried ? 'warn' : 'err', + words: retried ? '届いていない' : '届かなかった', + why: failureWord(lastFailure), } } @@ -359,6 +400,56 @@ export function nameFits(name: string): boolean { return trimmed.length > 0 && [...trimmed].length <= NAME_LONGEST } +/** The rule sets that go when a destination does: the ones that send to it alone. */ +export function ruleSetsGoingWith< + T extends Pick, +>(destinationId: string, ruleSets: readonly T[]): T[] { + return ruleSets.filter( + ({ destinations }) => + destinations.length > 0 && + destinations.every((one) => one === destinationId), + ) +} + +/** What removing a destination says about the rule sets that go with it; nothing when none does. */ +export function goingToo(names: readonly string[]): string | undefined { + return names.length === 0 + ? undefined + : `ルールセット${names.map((name) => `「${name}」`).join('')}も削除します。` +} + +export const DELIVERIES_SHOWN = 50 + +/** The deliveries of several destinations as one log, the newest first. */ +export function newestFirst( + deliveries: readonly NotificationDelivery[], +): NotificationDelivery[] { + return [...deliveries].sort( + (one, other) => Date.parse(other.occurredAt) - Date.parse(one.occurredAt), + ) +} + +/** The destination the log is narrowed to: the one chosen while it is still held, otherwise none. */ +export function narrowedTo( + destinations: readonly Pick[], + chosen: string | undefined, +): string | undefined { + return destinations.some(({ id }) => id === chosen) ? chosen : undefined +} + +/** The rows the log lists: the newest fifty of every destination, or of the one it is narrowed to. */ +export function deliveriesShown( + deliveries: readonly NotificationDelivery[], + destinationId: string | undefined, +): NotificationDelivery[] { + const asked = + destinationId === undefined + ? deliveries + : deliveries.filter((one) => one.destinationId === destinationId) + + return asked.slice(0, DELIVERIES_SHOWN) +} + /** The destinations a new single notice goes to when nobody chose: every one that is on. */ export function destinationsByDefault( destinations: readonly Pick[], diff --git a/stories/fixtures/notifications.ts b/stories/fixtures/notifications.ts index 6004b32c..ce44b0aa 100644 --- a/stories/fixtures/notifications.ts +++ b/stories/fixtures/notifications.ts @@ -2,8 +2,8 @@ import type { NotificationDelivery, NotificationDestination, NotificationRuleSet, + NotificationsScreen, } from '@/lib/notifications' -import type { NotificationsScreen } from '@/components/notifications/notifications-page' import type { WatchedProgramme } from '@/components/notifications/notify-only-row' export const NOTIFICATIONS_NOW = Date.parse('2026-11-09T12:30:00Z') @@ -12,22 +12,21 @@ export const HOME_SLACK: NotificationDestination = { id: 'dest-slack', name: '家の Slack', kind: 'slack', - urlTail: 'a1b2', + tail: 'a1b2', enabled: true, - lastResult: { state: 'sent', at: '2026-11-09T12:03:00Z' }, + readable: true, + lastResultAt: '2026-11-09T12:03:00Z', } export const DISCORD_ROOM: NotificationDestination = { id: 'dest-discord', name: 'Discord の通知部屋', kind: 'discord', - urlTail: '9f3e', + tail: '9f3e', enabled: true, - lastResult: { - state: 'failed', - at: '2026-11-09T11:58:00Z', - failure: 'timeout', - }, + readable: true, + lastResultAt: '2026-11-09T11:58:00Z', + lastFailure: 'timedOut', } export const IPAD_SAFARI: NotificationDestination = { @@ -35,7 +34,8 @@ export const IPAD_SAFARI: NotificationDestination = { name: 'iPad の Safari', kind: 'webPush', enabled: true, - lastResult: { state: 'sent', at: '2026-11-09T12:03:00Z' }, + readable: true, + lastResultAt: '2026-11-09T12:03:00Z', } export const DESTINATIONS: NotificationDestination[] = [ @@ -54,10 +54,10 @@ export const ONLY_WHEN_TROUBLED: NotificationRuleSet = { 'encodeFailed', 'reservationCompeting', 'reservationMissed', - 'qualityRaised', + 'qualityIncidentDetected', 'deviceDisconnected', ], - destinationIds: [HOME_SLACK.id, IPAD_SAFARI.id], + destinations: [HOME_SLACK.id, IPAD_SAFARI.id], } export const RULE_SETS: NotificationRuleSet[] = [ @@ -67,7 +67,7 @@ export const RULE_SETS: NotificationRuleSet[] = [ name: '録画の記録', enabled: true, events: ['recordingStarted', 'recordingCompleted', 'encodeCompleted'], - destinationIds: [DISCORD_ROOM.id], + destinations: [DISCORD_ROOM.id], }, { id: 'rule-away', @@ -81,86 +81,42 @@ export const RULE_SETS: NotificationRuleSet[] = [ 'encodeStarted', 'encodeCompleted', 'encodeFailed', - 'qualityRaised', - 'qualityResolved', + 'qualityIncidentDetected', + 'qualityIncidentResolved', ], - destinationIds: [HOME_SLACK.id, DISCORD_ROOM.id], + destinations: [HOME_SLACK.id, DISCORD_ROOM.id], }, ] -const HARBOUR_RECIPES = '港町レシピ帖 #15「灯台守のパン」' - function delivery( id: string, - at: string, - event: NotificationDelivery['event'], - subject: string, + occurredAt: string, + kind: NotificationDelivery['kind'], to: NotificationDestination, state: NotificationDelivery['state'] = 'sent', failure?: NotificationDelivery['failure'], ): NotificationDelivery { - return { - id, - at, - event, - subject, - destinationId: to.id, - destinationName: to.name, - state, - failure, - } + return { id, kind, occurredAt, destinationId: to.id, state, failure } } export const DELIVERIES: NotificationDelivery[] = [ - delivery( - 'del-1', - '2026-11-09T12:03:00Z', - 'recordingTruncated', - HARBOUR_RECIPES, - HOME_SLACK, - ), - delivery( - 'del-2', - '2026-11-09T12:03:00Z', - 'recordingTruncated', - HARBOUR_RECIPES, - IPAD_SAFARI, - ), + delivery('del-1', '2026-11-09T12:03:00Z', 'recordingTruncated', HOME_SLACK), + delivery('del-2', '2026-11-09T12:03:00Z', 'recordingTruncated', IPAD_SAFARI), delivery( 'del-3', '2026-11-09T11:58:00Z', 'encodeCompleted', - 'ちびっこ忍者 第12話', DISCORD_ROOM, 'failed', - 'timeout', - ), - delivery( - 'del-4', - '2026-11-09T11:54:00Z', - 'recordingCompleted', - 'ドラマ「ひだまり荘の人々」#18', - DISCORD_ROOM, - ), - delivery( - 'del-5', - '2026-11-09T11:15:00Z', - 'recordingStarted', - HARBOUR_RECIPES, - DISCORD_ROOM, - ), - delivery( - 'del-6', - '2026-11-09T10:27:00Z', - 'programmeStarting', - 'ドキュメント 灯りの仕事', - HOME_SLACK, + 'timedOut', ), + delivery('del-4', '2026-11-09T11:54:00Z', 'recordingCompleted', DISCORD_ROOM), + delivery('del-5', '2026-11-09T11:15:00Z', 'recordingStarted', DISCORD_ROOM), + delivery('del-6', '2026-11-09T10:27:00Z', 'programmeMoved', HOME_SLACK), delivery( 'del-7', '2026-11-09T09:40:00Z', 'reservationCompeting', - '深夜ドラマ「灯台守の娘」#3', HOME_SLACK, 'givenUp', 'rejected', @@ -168,21 +124,20 @@ export const DELIVERIES: NotificationDelivery[] = [ delivery( 'del-8', '2026-11-09T09:12:00Z', - 'qualityRaised', - '中央テレビ · ドロップ率', + 'qualityIncidentDetected', IPAD_SAFARI, ), ] export const NOTIFICATIONS_SCREEN: NotificationsScreen = { - settings: { leadMinutes: 3, hasPublicOrigin: false }, + settings: { notifyLeadMinutes: 3, publicOriginKnown: false }, destinations: DESTINATIONS, ruleSets: RULE_SETS, deliveries: DELIVERIES, } export const EMPTY_NOTIFICATIONS_SCREEN: NotificationsScreen = { - settings: { leadMinutes: 3, hasPublicOrigin: true }, + settings: { notifyLeadMinutes: 3, publicOriginKnown: true }, destinations: [], ruleSets: [], deliveries: [], diff --git a/stories/screens/Notifications.stories.tsx b/stories/screens/Notifications.stories.tsx index e2519e00..d560bec4 100644 --- a/stories/screens/Notifications.stories.tsx +++ b/stories/screens/Notifications.stories.tsx @@ -1,5 +1,4 @@ import type { Meta, StoryObj } from '@storybook/nextjs' -import { useState } from 'react' import { expect, fn, screen, userEvent, waitFor, within } from 'storybook/test' import type { NotificationWrite, TestSending } from '@/lib/notifications' @@ -8,7 +7,10 @@ import { NotificationsView, type NotificationActions, } from '@/components/notifications/notifications-page' -import { DENIED_HERE } from '@/components/notifications/add-destination-dialog' +import { + DENIED_HERE, + type BrowserChoice, +} from '@/components/notifications/add-destination-dialog' import { REFUSED_ADDRESS } from '@/components/notifications/webhook-field' import { inTheSettingsWithNotifications } from '@/stories/frames' import { PHONE } from '@/stories/rows-as-cards' @@ -32,7 +34,15 @@ const REFUSED = 'https://hook.example.jp/carina' const addWebhook = fn(async () => OK) -const addBrowser = fn(async () => OK) +const addBrowser = fn(async () => OK) + +const BROWSER: BrowserChoice = { + here: 'Windows の Chrome', + permission: 'default', + onAdd: addBrowser, +} + +const ON_A_PHONE: BrowserChoice = { ...BROWSER, here: 'iPhone の Safari' } const toggleDestination = fn( async () => OK, @@ -41,7 +51,7 @@ const toggleDestination = fn( const testDestination = fn( async (id): Promise => id === DISCORD_ROOM.id - ? { state: 'ok', delivered: false, failure: 'timeout' } + ? { state: 'ok', delivered: false, failure: 'timedOut' } : { state: 'ok', delivered: true }, ) @@ -63,11 +73,8 @@ const removeRuleSet = fn(async () => OK) const settleLead = fn(async () => OK) -const showDeliveriesFor = fn() - const ACTIONS: NotificationActions = { onAddWebhook: addWebhook, - onAddBrowser: addBrowser, onToggleDestination: toggleDestination, onTestDestination: testDestination, onReviseDestination: reviseDestination, @@ -77,7 +84,6 @@ const ACTIONS: NotificationActions = { onToggleRuleSet: toggleRuleSet, onRemoveRuleSet: removeRuleSet, onSettleLead: settleLead, - onShowDeliveriesFor: showDeliveriesFor, } const meta = { @@ -93,8 +99,7 @@ const meta = { args: { screen: NOTIFICATIONS_SCREEN, actions: ACTIONS, - here: 'Windows の Chrome', - permission: 'default', + browser: BROWSER, now: NOTIFICATIONS_NOW, }, decorators: [inTheSettingsWithNotifications], @@ -116,7 +121,7 @@ async function fromTheMenu( await userEvent.click(await screen.findByRole('menuitem', { name: item })) } -async function openThePicker(canvasElement: HTMLElement) { +async function openTheAdding(canvasElement: HTMLElement) { const canvas = within(canvasElement) const destinations = canvas.getByRole('heading', { name: '送り先' }) .parentElement as HTMLElement @@ -129,7 +134,7 @@ async function openThePicker(canvasElement: HTMLElement) { } async function openTheWebhookForm(canvasElement: HTMLElement) { - const dialog = await openThePicker(canvasElement) + const dialog = await openTheAdding(canvasElement) await userEvent.click( within(dialog).getByRole('button', { name: /Slack・Discord/ }), @@ -139,7 +144,7 @@ async function openTheWebhookForm(canvasElement: HTMLElement) { } async function openTheBrowserForm(canvasElement: HTMLElement) { - const dialog = await openThePicker(canvasElement) + const dialog = await openTheAdding(canvasElement) await userEvent.click( within(dialog).getByRole('button', { name: /このブラウザ/ }), @@ -148,26 +153,6 @@ async function openTheBrowserForm(canvasElement: HTMLElement) { return dialog } -/** The log narrowed to one destination, as the page would answer the URL it is given. */ -function NarrowedLog(args: Story['args']) { - const [only, setOnly] = useState() - - return ( - only === undefined || delivery.destinationId === only, - ), - }} - actions={{ ...ACTIONS, onShowDeliveriesFor: setOnly }} - /> - ) -} - export const 通常: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement) @@ -212,7 +197,7 @@ export const 公開のアドレスがある: Story = { args: { screen: { ...NOTIFICATIONS_SCREEN, - settings: { leadMinutes: 3, hasPublicOrigin: true }, + settings: { notifyLeadMinutes: 3, publicOriginKnown: true }, }, }, play: async ({ canvasElement }) => { @@ -248,13 +233,10 @@ export const 送り先が多い: Story = { ...HOME_SLACK, id: 'dest-slack-2', name: '実家のリビングの Slack のお知らせ用チャンネル', - urlTail: 'c3d4', + tail: 'c3d4', enabled: false, - lastResult: { - state: 'givenUp', - at: '2026-11-08T12:03:00Z', - failure: 'rejected', - }, + lastResultAt: '2026-11-08T12:03:00Z', + lastFailure: 'rejected', }, ], }, @@ -271,6 +253,24 @@ export const 送り先が多い: Story = { }, } +export const 開けない送り先: Story = { + args: { + screen: { + ...NOTIFICATIONS_SCREEN, + destinations: [{ ...HOME_SLACK, readable: false }, DISCORD_ROOM], + }, + }, + play: async ({ canvasElement }) => { + const slack = within( + within(canvasElement) + .getByRole('list', { name: '送り先' }) + .querySelector(`[data-destination="${HOME_SLACK.id}"]`) as HTMLElement, + ) + + await expect(slack.getByText('開けない')).toBeVisible() + }, +} + export const ルールセットが上限: Story = { args: { screen: { ...NOTIFICATIONS_SCREEN, ruleSets: TWENTY_RULE_SETS }, @@ -400,7 +400,6 @@ export const 単発の通知の既定を変える: Story = { } export const 配送を送り先で絞る: Story = { - render: (args) => , play: async ({ canvasElement }) => { const canvas = within(canvasElement) @@ -424,7 +423,7 @@ export const 配送を送り先で絞る: Story = { export const 送り先を追加_種類を選ぶ: Story = { play: async ({ canvasElement }) => { - const dialog = within(await openThePicker(canvasElement)) + const dialog = within(await openTheAdding(canvasElement)) await expect( dialog.getByRole('button', { name: /Slack・Discord の URL に送ります/ }), @@ -435,6 +434,19 @@ export const 送り先を追加_種類を選ぶ: Story = { }, } +export const 送り先を追加_Webhookだけ: Story = { + args: { browser: undefined }, + play: async ({ canvasElement }) => { + const dialog = within(await openTheAdding(canvasElement)) + + await expect(dialog.getByLabelText('Webhook の URL')).toBeVisible() + await expect(dialog.queryByRole('button', { name: '戻る' })).toBeNull() + await expect( + dialog.queryByRole('button', { name: /Slack・Discord/ }), + ).toBeNull() + }, +} + export const 送り先を追加_Slack: Story = { play: async ({ canvasElement }) => { const dialog = within(await openTheWebhookForm(canvasElement)) @@ -516,7 +528,7 @@ export const 送り先を追加_このブラウザ: Story = { } export const 送り先を追加_通知を拒否している: Story = { - args: { permission: 'denied' }, + args: { browser: { ...BROWSER, permission: 'denied' } }, play: async ({ canvasElement }) => { const dialog = within(await openTheBrowserForm(canvasElement)) @@ -627,6 +639,9 @@ export const 送り先を削除: Story = { await expect(asked.getByText('この送り先を削除します')).toBeVisible() await expect(asked.getByText('Discord の通知部屋')).toBeVisible() + await expect( + asked.getByText('ルールセット「録画の記録」も削除します。'), + ).toBeVisible() await userEvent.click(asked.getByRole('button', { name: '削除する' })) @@ -636,6 +651,17 @@ export const 送り先を削除: Story = { }, } +export const 送り先を削除_ほかにも送るルールセット: Story = { + play: async ({ canvasElement }) => { + await fromTheMenu(canvasElement, '家の Slack', '削除') + + const asked = within(await screen.findByRole('alertdialog')) + + await expect(asked.getByText('家の Slack')).toBeVisible() + await expect(asked.queryByText(/も削除します/)).toBeNull() + }, +} + export const ルールセットを変更: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement) @@ -731,7 +757,7 @@ export const ルールセットを追加: Story = { name: '夜中の失敗', enabled: true, events: ['recordingFailed'], - destinationIds: [HOME_SLACK.id], + destinations: [HOME_SLACK.id], }), ) }, @@ -756,9 +782,9 @@ export const 電話: Story = { export const 電話_送り先を追加: Story = { parameters: { screen: PHONE, coarse: true }, - args: { here: 'iPhone の Safari' }, + args: { browser: ON_A_PHONE }, play: async ({ canvasElement }) => { - const dialog = await openThePicker(canvasElement) + const dialog = await openTheAdding(canvasElement) const sheet = dialog.getBoundingClientRect() await expect( @@ -775,7 +801,7 @@ export const 電話_送り先を追加: Story = { export const 電話_このブラウザ: Story = { parameters: { screen: PHONE, coarse: true }, - args: { here: 'iPhone の Safari' }, + args: { browser: ON_A_PHONE }, play: async ({ canvasElement }) => { const dialog = within(await openTheBrowserForm(canvasElement)) diff --git a/tests/lib/notifications.test.ts b/tests/lib/notifications.test.ts index e58b126f..a558a129 100644 --- a/tests/lib/notifications.test.ts +++ b/tests/lib/notifications.test.ts @@ -2,24 +2,32 @@ import assert from 'node:assert/strict' import { test } from 'node:test' import { + deliveriesShown, deliverySaid, destinationsByDefault, eventLabelOf, eventsSummary, + failureWord, + goingToo, isLead, lastResultSaid, leadChipWords, leadLabel, leadToastWords, + narrowedTo, nameFits, + newestFirst, readAddress, registeringAs, ruleSetsFull, + ruleSetsGoingWith, testSaid, toggled, webhookKindOf, withWhy, + type DeliveryFailure, type NotificationDelivery, + type NotificationEvent, } from '@/lib/notifications' test('a Slack address is Slack, and both Discord hosts are Discord under their webhook path', () => { @@ -83,7 +91,7 @@ test('a rule set says its events group by group, each group after its prefix', ( 'encodeFailed', 'reservationCompeting', 'reservationMissed', - 'qualityRaised', + 'qualityIncidentDetected', 'deviceDisconnected', ]), '録画の欠け・失敗 · エンコードの失敗 · 競合・取り逃し · 異常の発生 · 切断', @@ -100,12 +108,9 @@ test('a rule set says its events group by group, each group after its prefix', ( }) test('every event has a label, and one this build does not know is said as such', () => { - assert.equal(eventLabelOf('programmeStarting'), '放送開始の通知') - assert.equal(eventLabelOf('qualityRaised'), '品質の異常の発生') - assert.equal( - eventLabelOf('somethingNew' as NotificationDelivery['event']), - '未知の値', - ) + assert.equal(eventLabelOf('qualityIncidentDetected'), '品質の異常の発生') + assert.equal(eventLabelOf('qualityIncidentResolved'), '品質の異常の解消') + assert.equal(eventLabelOf('somethingNew' as NotificationEvent), '未知の値') }) test('the lead is said as the start itself or minutes before it', () => { @@ -119,43 +124,107 @@ test('the lead is said as the start itself or minutes before it', () => { assert.ok(!isLead(2)) }) -test('the last result of a destination is good, being retried or given up', () => { +test('each of the nine failures Carina names has a word of its own', () => { + const words = [ + 'timedOut', + 'rateLimited', + 'serverFailed', + 'unreachable', + 'rejected', + 'destinationDisabled', + 'unreadable', + 'tooOld', + 'tlsFailed', + ].map((failure) => failureWord(failure as DeliveryFailure)) + + assert.deepEqual(words, [ + '時間切れ', + '回数の上限', + '送り先の障害', + 'つながらない', + '断られた', + '送り先が無効', + '開けない', + '古くなった', + '暗号化の失敗', + ]) + assert.equal(failureWord('somethingNew' as DeliveryFailure), '未知の値') + assert.equal(failureWord(undefined), undefined) +}) + +test('a destination nothing was sent to yet says nothing', () => { + assert.equal(lastResultSaid({ readable: true }), undefined) +}) + +test('the last result of a destination is good, worth another try or over', () => { const now = Date.parse('2026-11-09T12:30:00Z') + const lastResultAt = '2026-11-09T12:03:00Z' + assert.deepEqual(lastResultSaid({ readable: true, lastResultAt }, now), { + verdict: 'ok', + words: '届いた 21:03', + }) + + for (const lastFailure of [ + 'timedOut', + 'rateLimited', + 'serverFailed', + 'unreachable', + 'tlsFailed', + ] as const) { + assert.deepEqual( + lastResultSaid({ readable: true, lastResultAt, lastFailure }, now), + { + verdict: 'warn', + words: '届いていない', + why: failureWord(lastFailure), + }, + lastFailure, + ) + } + + for (const lastFailure of [ + 'rejected', + 'destinationDisabled', + 'unreadable', + 'tooOld', + ] as const) { + assert.deepEqual( + lastResultSaid({ readable: true, lastResultAt, lastFailure }, now), + { + verdict: 'err', + words: '届かなかった', + why: failureWord(lastFailure), + }, + lastFailure, + ) + } +}) + +test('a destination whose address cannot be opened says so before anything else', () => { assert.deepEqual( - lastResultSaid({ state: 'sent', at: '2026-11-09T12:03:00Z' }, now), - { verdict: 'ok', words: '届いた 21:03' }, - ) - assert.deepEqual( - lastResultSaid( - { state: 'failed', at: '2026-11-09T12:03:00Z', failure: 'timeout' }, - now, - ), - { verdict: 'warn', words: '届いていない', why: '時間切れ' }, - ) - assert.deepEqual( - lastResultSaid( - { state: 'givenUp', at: '2026-11-09T12:03:00Z', failure: 'rejected' }, - now, - ), - { verdict: 'err', words: '届かなかった', why: '断られた' }, + lastResultSaid({ + readable: false, + lastResultAt: '2026-11-09T12:03:00Z', + }), + { verdict: 'err', words: '開けない' }, ) }) test('a delivery wears its reason only while it has not arrived', () => { const delivery: NotificationDelivery = { id: 'd', - at: '2026-11-09T12:03:00Z', - event: 'recordingTruncated', - subject: '港町レシピ帖', + kind: 'recordingTruncated', + occurredAt: '2026-11-09T12:03:00Z', destinationId: 'a', - destinationName: '家の Slack', state: 'sent', } assert.deepEqual(deliverySaid(delivery), { verdict: 'ok', words: '届いた' }) assert.equal( - withWhy(deliverySaid({ ...delivery, state: 'failed', failure: 'timeout' })), + withWhy( + deliverySaid({ ...delivery, state: 'failed', failure: 'timedOut' }), + ), '送り直し中 · 時間切れ', ) assert.equal( @@ -180,9 +249,82 @@ test('a delivery wears its reason only while it has not arrived', () => { test('a test send says whether it arrived, and why not when it did not', () => { assert.equal(withWhy(testSaid({ state: 'ok', delivered: true })), '届いた') assert.equal( - withWhy(testSaid({ state: 'ok', delivered: false, failure: 'timeout' })), + withWhy(testSaid({ state: 'ok', delivered: false, failure: 'timedOut' })), '届かなかった · 時間切れ', ) + assert.equal( + withWhy(testSaid({ state: 'ok', delivered: false })), + '届かなかった', + ) +}) + +test('the rule sets that send to one destination alone go with it', () => { + const ruleSets = [ + { name: '困ったときだけ', destinations: ['a', 'b'] }, + { name: '録画の記録', destinations: ['b'] }, + { name: '留守の週', destinations: ['b'] }, + { name: '機器だけ', destinations: ['a'] }, + ] + + assert.deepEqual( + ruleSetsGoingWith('b', ruleSets).map(({ name }) => name), + ['録画の記録', '留守の週'], + ) + assert.deepEqual(ruleSetsGoingWith('c', ruleSets), []) + assert.equal( + goingToo(['録画の記録', '留守の週']), + 'ルールセット「録画の記録」「留守の週」も削除します。', + ) + assert.equal(goingToo([]), undefined) +}) + +function sentAt( + id: string, + occurredAt: string, + destinationId: string, +): NotificationDelivery { + return { + id, + kind: 'recordingStarted', + occurredAt, + destinationId, + state: 'sent', + } +} + +test('the deliveries of several destinations read as one log, the newest first', () => { + const log = newestFirst([ + sentAt('1', '2026-11-09T10:00:00Z', 'a'), + sentAt('2', '2026-11-09T12:00:00.5Z', 'a'), + sentAt('3', '2026-11-09T12:00:00Z', 'b'), + ]) + + assert.deepEqual( + log.map(({ id }) => id), + ['2', '3', '1'], + ) +}) + +test('the log is narrowed to a destination only while that destination is held', () => { + const destinations = [{ id: 'a' }, { id: 'b' }] + + assert.equal(narrowedTo(destinations, 'b'), 'b') + assert.equal(narrowedTo(destinations, undefined), undefined) + assert.equal(narrowedTo(destinations, 'gone'), undefined) +}) + +test('the log lists fifty rows of every destination, or of the one it is narrowed to', () => { + const log = Array.from({ length: 120 }, (_, index) => + sentAt(String(index), '2026-11-09T12:00:00Z', index % 2 === 0 ? 'a' : 'b'), + ) + + assert.deepEqual( + deliveriesShown(log, undefined).map(({ id }) => id), + log.slice(0, 50).map(({ id }) => id), + ) + assert.equal(deliveriesShown(log, 'b').length, 50) + assert.ok(deliveriesShown(log, 'b').every((one) => one.destinationId === 'b')) + assert.deepEqual(deliveriesShown(log, 'gone'), []) }) test('rule sets stop at twenty', () => { From 0ee1b9bcfd173817f24f4f6f7b91712e32ffbb2c Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 03:33:17 +0900 Subject: [PATCH 11/24] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E3=81=AE=E9=80=81?= =?UTF-8?q?=E3=82=8A=E5=85=88=E3=83=BB=E3=83=AB=E3=83=BC=E3=83=AB=E3=82=BB?= =?UTF-8?q?=E3=83=83=E3=83=88=E3=83=BB=E8=A8=AD=E5=AE=9A=E3=83=BB=E9=85=8D?= =?UTF-8?q?=E9=80=81=E3=81=AE=E8=A8=98=E9=8C=B2=E3=82=92=20Carina=20?= =?UTF-8?q?=E3=81=AE=20API=20=E3=81=8B=E3=82=89=E8=AA=AD=E3=81=BF=E6=9B=B8?= =?UTF-8?q?=E3=81=8D=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- .../notifications/add-destination-dialog.tsx | 6 +- components/notifications/destination-list.tsx | 6 +- .../notifications/edit-destination-dialog.tsx | 8 +- .../notifications/notifications-page.tsx | 2 +- lib/notifications.ts | 12 + repository/notifications.ts | 401 +++++++++++ tests/repository/notifications.test.ts | 632 ++++++++++++++++++ tests/storybook/every-test-runs.test.ts | 1 + .../storybook/fields-the-api-answers.test.ts | 19 + 9 files changed, 1070 insertions(+), 17 deletions(-) create mode 100644 repository/notifications.ts create mode 100644 tests/repository/notifications.test.ts diff --git a/components/notifications/add-destination-dialog.tsx b/components/notifications/add-destination-dialog.tsx index b9ce697f..5d41ead2 100644 --- a/components/notifications/add-destination-dialog.tsx +++ b/components/notifications/add-destination-dialog.tsx @@ -9,6 +9,7 @@ import { readAddress, type BrowserPermission, type NotificationWrite, + type WebhookDraft, } from '@/lib/notifications' import { Button } from '@/components/ui/button' import { Dialog } from '@/components/ui/dialog' @@ -30,11 +31,6 @@ import { } from '@/components/notifications/notice-dialog' import { WebhookField } from '@/components/notifications/webhook-field' -export interface WebhookDraft { - name: string - url: string -} - export interface BrowserDraft { name: string } diff --git a/components/notifications/destination-list.tsx b/components/notifications/destination-list.tsx index 11d70731..cd4641e2 100644 --- a/components/notifications/destination-list.tsx +++ b/components/notifications/destination-list.tsx @@ -11,6 +11,7 @@ import { tailOf, testSaid, withWhy, + type DestinationRevision, type NotificationDestination, type NotificationRuleSet, type NotificationWrite, @@ -22,10 +23,7 @@ import { Switch } from '@/components/ui/switch' import { Spinner } from '@/components/vela/progress' import { StatusDot, type StatusTone } from '@/components/vela/status' import { useToast } from '@/components/vela/toast' -import { - EditDestinationDialog, - type DestinationRevision, -} from '@/components/notifications/edit-destination-dialog' +import { EditDestinationDialog } from '@/components/notifications/edit-destination-dialog' import { RemoveDialog } from '@/components/notifications/remove-button' import { KindChip, RowMenu } from '@/components/notifications/row-menu' diff --git a/components/notifications/edit-destination-dialog.tsx b/components/notifications/edit-destination-dialog.tsx index f72233e3..3d886509 100644 --- a/components/notifications/edit-destination-dialog.tsx +++ b/components/notifications/edit-destination-dialog.tsx @@ -8,6 +8,7 @@ import { nameFits, readAddress, tailOf, + type DestinationRevision, type NotificationDestination, type NotificationWrite, } from '@/lib/notifications' @@ -26,13 +27,6 @@ import { } from '@/components/notifications/notice-dialog' import { WebhookField } from '@/components/notifications/webhook-field' -/** What changing a destination sends: its name, whether it is on, and a new address only when one was typed. */ -export interface DestinationRevision { - name: string - enabled: boolean - url?: string -} - const SIGNED_OUT = signedOut('変更') export function EditDestinationDialog({ diff --git a/components/notifications/notifications-page.tsx b/components/notifications/notifications-page.tsx index 2f7c689f..cd2026be 100644 --- a/components/notifications/notifications-page.tsx +++ b/components/notifications/notifications-page.tsx @@ -10,6 +10,7 @@ import { type LeadMinutes, type NotificationsScreen, type NotificationWrite, + type WebhookDraft, } from '@/lib/notifications' import { Banner } from '@/components/vela/banner' import { PageHeading } from '@/components/vela/section-heading' @@ -18,7 +19,6 @@ import { useToast } from '@/components/vela/toast' import { AddDestinationDialog, type BrowserChoice, - type WebhookDraft, } from '@/components/notifications/add-destination-dialog' import { DeliveryFilter, diff --git a/lib/notifications.ts b/lib/notifications.ts index de863c6c..67fb70ae 100644 --- a/lib/notifications.ts +++ b/lib/notifications.ts @@ -58,6 +58,18 @@ export interface NotificationRuleSet { export type RuleSetDraft = Omit +export interface WebhookDraft { + name: string + url: string +} + +/** What changing a destination sends: its name, whether it is on, and a new address only when one was typed. */ +export interface DestinationRevision { + name: string + enabled: boolean + url?: string +} + export type DeliveryState = 'queued' | 'sent' | 'failed' | 'givenUp' /** One notice on its way to one destination. Its title is the heading Carina gave the notice. */ diff --git a/repository/notifications.ts b/repository/notifications.ts new file mode 100644 index 00000000..f94e4111 --- /dev/null +++ b/repository/notifications.ts @@ -0,0 +1,401 @@ +import { + DELIVERIES_SHOWN, + NAME_LONGEST, + RULE_SETS_AT_MOST, + isLead, + newestFirst, +} from '@/lib/notifications' +import type { + DestinationRevision, + LeadMinutes, + NotificationDelivery, + NotificationDestination, + NotificationRuleSet, + NotificationSettings, + NotificationWrite, + NotificationsScreen, + RuleSetDraft, + TestSending, + WebhookDraft, +} from '@/lib/notifications' +import { couldNot } from '@/lib/try-again' +import { carinaClient } from '@/repository/client/carina' +import type { components } from '@/repository/client/schema' +import { toInt } from '@/repository/programmes' +import { whatItSaid } from '@/repository/said' + +type DestinationResponder = + components['schemas']['NotificationDestinationResponder'] +type RuleResponder = components['schemas']['NotificationRuleResponder'] +type DeliveryResponder = components['schemas']['NotificationDeliveryResponder'] +type SettingsResponder = components['schemas']['NotificationSettingsResponder'] + +export interface NotificationAsking { + did: string + fell: string +} + +export const WHEN_ADDING_A_DESTINATION: NotificationAsking = { + did: '追加', + fell: '送り先を追加できませんでした', +} + +export const WHEN_CHANGING_A_DESTINATION: NotificationAsking = { + did: '変更', + fell: '送り先を変更できませんでした', +} + +export const WHEN_REMOVING_A_DESTINATION: NotificationAsking = { + did: '削除', + fell: '送り先を削除できませんでした', +} + +export const WHEN_TRYING_A_DESTINATION: NotificationAsking = { + did: 'テスト送信', + fell: 'テスト送信ができませんでした', +} + +export const WHEN_ADDING_A_RULE_SET: NotificationAsking = { + did: '追加', + fell: 'ルールセットを追加できませんでした', +} + +export const WHEN_CHANGING_A_RULE_SET: NotificationAsking = { + did: '変更', + fell: 'ルールセットを変更できませんでした', +} + +export const WHEN_REMOVING_A_RULE_SET: NotificationAsking = { + did: '削除', + fell: 'ルールセットを削除できませんでした', +} + +export const WHEN_SETTLING_THE_LEAD: NotificationAsking = { + did: '変更', + fell: '単発の通知の既定を変更できませんでした', +} + +const UNREADABLE = '通知の設定を読めませんでした' + +const REFUSAL_SAYINGS: [RegExp, string][] = [ + [/not one a notice can be sent to/i, 'この URL は受け付けられません。'], + [ + /a trial was sent a moment ago/i, + '続けてテスト送信はできません。1 分ほどおいてからお試しください。', + ], + [ + /cannot be opened with the keys/i, + 'この送り先の URL を開けません。URL を入れ直してください。', + ], +] + +const REFUSAL_REASONS: [RegExp, string][] = [ + [ + /no destination is (registered|held) under/i, + 'この送り先は残っていないため、', + ], + [/no set of rules is held under/i, 'このルールセットは残っていないため、'], + [ + /at most \d+ sets of rules are held/i, + `ルールセットは ${RULE_SETS_AT_MOST} 本までのため、`, + ], + [/sends to at least one destination/i, '選んだ送り先が残っていないため、'], + [ + /is named in one to sixty-four characters/i, + `名前が 1 〜 ${NAME_LONGEST} 文字でないため、`, + ], +] + +export function whyItRefused( + asking: NotificationAsking, + said: string | undefined, +): string { + const heard = said ?? '' + const saying = REFUSAL_SAYINGS.find(([reads]) => reads.test(heard)) + + if (saying) { + return saying[1] + } + + const reason = REFUSAL_REASONS.find(([reads]) => reads.test(heard)) + + return reason + ? `${reason[1]}${asking.did}できませんでした。` + : couldNot(asking.fell) +} + +export async function getNotificationsScreen(): Promise { + const [destinations, ruleSets, settings] = await Promise.all([ + fetchDestinations(), + fetchRuleSets(), + fetchSettings(), + ]) + const sentTo = await Promise.all( + destinations.map(({ id }) => fetchDeliveries(id)), + ) + + return { + settings, + destinations, + ruleSets, + deliveries: newestFirst(sentTo.flat()), + } +} + +export async function registerDestination( + draft: WebhookDraft, +): Promise { + const { error, response } = await carinaClient().POST( + '/api/notifications/destinations', + { body: { name: draft.name, url: draft.url } }, + ) + + return toWrite(response, whatItSaid(error), WHEN_ADDING_A_DESTINATION) +} + +export async function reviseDestination( + id: string, + change: DestinationRevision, +): Promise { + const { error, response } = await carinaClient().PATCH( + '/api/notifications/destinations/{id}', + { + params: { path: { id } }, + body: { + name: change.name, + enabled: change.enabled, + url: change.url ?? '', + }, + }, + ) + + return toWrite(response, whatItSaid(error), WHEN_CHANGING_A_DESTINATION) +} + +export async function switchDestination( + id: string, + enabled: boolean, +): Promise { + const { error, response } = await carinaClient().PATCH( + '/api/notifications/destinations/{id}', + { params: { path: { id } }, body: { enabled } }, + ) + + return toWrite(response, whatItSaid(error), WHEN_CHANGING_A_DESTINATION) +} + +export async function removeDestination( + id: string, +): Promise { + const { error, response } = await carinaClient().DELETE( + '/api/notifications/destinations/{id}', + { params: { path: { id } } }, + ) + + return toWrite(response, whatItSaid(error), WHEN_REMOVING_A_DESTINATION) +} + +export async function tryDestination(id: string): Promise { + const { data, error, response } = await carinaClient().POST( + '/api/notifications/destinations/{id}/test', + { params: { path: { id } } }, + ) + const written = toWrite( + response, + whatItSaid(error, data), + WHEN_TRYING_A_DESTINATION, + ) + + if (written.state !== 'ok') { + return written + } + + const trial = data?.data + + return trial + ? { + state: 'ok', + delivered: trial.delivered, + failure: trial.failure ?? undefined, + } + : { state: 'rejected', message: couldNot(WHEN_TRYING_A_DESTINATION.fell) } +} + +export async function defineRuleSet( + draft: RuleSetDraft, +): Promise { + const { error, response } = await carinaClient().POST( + '/api/notifications/rules', + { body: toRuleBody(draft) }, + ) + + return toWrite(response, whatItSaid(error), WHEN_ADDING_A_RULE_SET) +} + +export async function reviseRuleSet( + id: string, + draft: RuleSetDraft, +): Promise { + const { error, response } = await carinaClient().PATCH( + '/api/notifications/rules/{id}', + { params: { path: { id } }, body: toRuleBody(draft) }, + ) + + return toWrite(response, whatItSaid(error), WHEN_CHANGING_A_RULE_SET) +} + +export async function switchRuleSet( + id: string, + enabled: boolean, +): Promise { + const { error, response } = await carinaClient().PATCH( + '/api/notifications/rules/{id}', + { params: { path: { id } }, body: { enabled } }, + ) + + return toWrite(response, whatItSaid(error), WHEN_CHANGING_A_RULE_SET) +} + +export async function removeRuleSet(id: string): Promise { + const { error, response } = await carinaClient().DELETE( + '/api/notifications/rules/{id}', + { params: { path: { id } } }, + ) + + return toWrite(response, whatItSaid(error), WHEN_REMOVING_A_RULE_SET) +} + +export async function settleLead( + lead: LeadMinutes, +): Promise { + const { error, response } = await carinaClient().PUT( + '/api/notifications/settings', + { body: { notifyLeadMinutes: lead } }, + ) + + return toWrite(response, whatItSaid(error), WHEN_SETTLING_THE_LEAD) +} + +function toRuleBody(draft: RuleSetDraft) { + return { + name: draft.name, + enabled: draft.enabled, + events: draft.events, + destinations: draft.destinations, + } +} + +function toWrite( + response: Response, + said: string | undefined, + asking: NotificationAsking, +): NotificationWrite { + if (response.status === 401) { + return { state: 'unauthenticated' } + } + + if (response.ok) { + return { state: 'ok' } + } + + return { + state: 'rejected', + message: whyItRefused(asking, said), + } +} + +async function fetchDestinations(): Promise { + const { data, error } = await carinaClient().GET( + '/api/notifications/destinations', + ) + + if (error || !data?.data) { + throw new Error(whatItSaid(error, data) || UNREADABLE) + } + + return data.data.items.map(toDestination) +} + +async function fetchRuleSets(): Promise { + const { data, error } = await carinaClient().GET('/api/notifications/rules') + + if (error || !data?.data) { + throw new Error(whatItSaid(error, data) || UNREADABLE) + } + + return data.data.items.map(toRuleSet) +} + +async function fetchSettings(): Promise { + const { data, error } = await carinaClient().GET( + '/api/notifications/settings', + ) + + if (error || !data?.data) { + throw new Error(whatItSaid(error, data) || UNREADABLE) + } + + return toSettings(data.data) +} + +async function fetchDeliveries( + destinationId: string, +): Promise { + const { data, error } = await carinaClient().GET( + '/api/notifications/deliveries', + { params: { query: { destinationId, perPage: DELIVERIES_SHOWN } } }, + ) + + if (error || !data?.data) { + throw new Error(whatItSaid(error, data) || UNREADABLE) + } + + return data.data.items + .map(toDelivery) + .map((one) => ({ ...one, destinationId })) +} + +function toDestination(one: DestinationResponder): NotificationDestination { + return { + id: one.id, + name: one.name, + kind: one.kind, + tail: one.tail, + enabled: one.enabled, + readable: one.readable, + lastResultAt: one.lastResultAt ?? undefined, + lastFailure: one.lastFailure ?? undefined, + } +} + +function toRuleSet(one: RuleResponder): NotificationRuleSet { + return { + id: one.id, + name: one.name, + enabled: one.enabled, + events: one.events, + destinations: one.destinations, + } +} + +function toDelivery( + one: DeliveryResponder, +): Omit { + return { + id: one.id, + kind: one.kind, + occurredAt: one.occurredAt, + state: one.state, + failure: one.failure ?? undefined, + } +} + +function toSettings(one: SettingsResponder): NotificationSettings { + const lead = toInt(one.notifyLeadMinutes) + + if (!isLead(lead)) { + throw new Error(UNREADABLE) + } + + return { notifyLeadMinutes: lead, publicOriginKnown: one.publicOriginKnown } +} diff --git a/tests/repository/notifications.test.ts b/tests/repository/notifications.test.ts new file mode 100644 index 00000000..edc2fe84 --- /dev/null +++ b/tests/repository/notifications.test.ts @@ -0,0 +1,632 @@ +import assert from 'node:assert/strict' +import { beforeEach, mock, test } from 'node:test' + +interface Sent { + method: string + path: string + at?: Record + query?: Record + body?: Record +} + +interface Asked { + params?: { + path?: Record + query?: Record + } + body?: Record +} + +const HOME = '0a000000-0000-4000-8000-000000000001' + +const GAMES = '0a000000-0000-4000-8000-000000000002' + +const FAILURES = '0b000000-0000-4000-8000-000000000001' + +const DESTINATION_HOME = { + id: HOME, + name: '見本の送り先 1', + kind: 'slack', + tail: 'a1b2', + enabled: true, + readable: true, + lastResultAt: '2026-01-02T03:04:05Z', + lastFailure: null, + createdAt: '2026-01-01T00:00:00Z', + changedAt: '2026-01-01T00:00:00Z', +} + +const DESTINATION_GAMES = { + ...DESTINATION_HOME, + id: GAMES, + name: '見本の送り先 2', + kind: 'discord', + tail: '9f3e', + enabled: false, + readable: false, + lastFailure: 'timedOut', +} + +const RULE = { + id: FAILURES, + name: '見本のルールセット', + enabled: true, + events: ['recordingFailed', 'encodeFailed'], + destinations: [HOME], + createdAt: '2026-01-01T00:00:00Z', + changedAt: '2026-01-01T00:00:00Z', +} + +function delivery(id: string, occurredAt: string, more: object = {}) { + return { + id, + kind: 'recordingFailed', + title: '見本の見出し', + occurredAt, + state: 'sent', + attempts: 1, + queuedAt: occurredAt, + sentAt: occurredAt, + nextAttemptAt: null, + failure: null, + ...more, + } +} + +const sent: Sent[] = [] + +const store: { + destinations: unknown[] + rules: unknown[] + settings: unknown + deliveries: Record + trial: unknown + readStatus: number + readMessage: string + writeStatus: number + writeMessage: string +} = { + destinations: [], + rules: [], + settings: null, + deliveries: {}, + trial: null, + readStatus: 200, + readMessage: '', + writeStatus: 200, + writeMessage: '', +} + +const answered = (status: number) => ({ status, ok: status < 400 }) + +const envelope = (data: unknown) => ({ + data: { status: true, message: '', data }, + response: answered(200), +}) + +const refusal = (status: number, message: string) => ({ + error: { status: false, message, data: null }, + response: answered(status), +}) + +function written(data: unknown = null) { + return store.writeStatus < 400 + ? { + data: { status: true, message: '', data }, + response: answered(store.writeStatus), + } + : refusal(store.writeStatus, store.writeMessage) +} + +function wrote(method: string) { + return async (path: string, options?: Asked) => { + sent.push({ + method, + path, + at: options?.params?.path, + body: options?.body, + }) + + return written(path.endsWith('/test') ? store.trial : null) + } +} + +const client = () => ({ + GET: async (path: string, options?: Asked) => { + const query = options?.params?.query + sent.push({ method: 'GET', path, query }) + + if (store.readStatus >= 400) { + return refusal(store.readStatus, store.readMessage) + } + + switch (path) { + case '/api/notifications/destinations': + return envelope({ items: store.destinations }) + case '/api/notifications/rules': + return envelope({ items: store.rules }) + case '/api/notifications/settings': + return envelope(store.settings) + case '/api/notifications/deliveries': + return envelope({ + perPage: query?.perPage, + items: store.deliveries[String(query?.destinationId)] ?? [], + }) + default: + throw new Error(`unexpected GET ${path}`) + } + }, + POST: wrote('POST'), + PUT: wrote('PUT'), + PATCH: wrote('PATCH'), + DELETE: wrote('DELETE'), +}) + +mock.module('@/repository/client/carina', { + namedExports: { carinaClient: client, revalidatingCarinaClient: client }, +}) + +const { + WHEN_ADDING_A_DESTINATION, + WHEN_ADDING_A_RULE_SET, + WHEN_CHANGING_A_DESTINATION, + WHEN_CHANGING_A_RULE_SET, + WHEN_TRYING_A_DESTINATION, + defineRuleSet, + getNotificationsScreen, + registerDestination, + removeDestination, + removeRuleSet, + reviseDestination, + reviseRuleSet, + settleLead, + switchDestination, + switchRuleSet, + tryDestination, + whyItRefused, +} = await import('@/repository/notifications') + +beforeEach(() => { + sent.length = 0 + store.destinations = [DESTINATION_HOME, DESTINATION_GAMES] + store.rules = [RULE] + store.settings = { notifyLeadMinutes: 3, publicOriginKnown: true } + store.deliveries = {} + store.trial = { delivered: true, failure: null } + store.readStatus = 200 + store.readMessage = '' + store.writeStatus = 200 + store.writeMessage = '' +}) + +test('the screen is read from the destinations, the rule sets and the settings', async () => { + const screen = await getNotificationsScreen() + + assert.deepEqual(screen.destinations, [ + { + id: HOME, + name: '見本の送り先 1', + kind: 'slack', + tail: 'a1b2', + enabled: true, + readable: true, + lastResultAt: '2026-01-02T03:04:05Z', + lastFailure: undefined, + }, + { + id: GAMES, + name: '見本の送り先 2', + kind: 'discord', + tail: '9f3e', + enabled: false, + readable: false, + lastResultAt: '2026-01-02T03:04:05Z', + lastFailure: 'timedOut', + }, + ]) + assert.deepEqual(screen.ruleSets, [ + { + id: FAILURES, + name: '見本のルールセット', + enabled: true, + events: ['recordingFailed', 'encodeFailed'], + destinations: [HOME], + }, + ]) + assert.deepEqual(screen.settings, { + notifyLeadMinutes: 3, + publicOriginKnown: true, + }) +}) + +test('a destination that has sent nothing yet has no last result', async () => { + store.destinations = [{ ...DESTINATION_HOME, lastResultAt: null }] + + const screen = await getNotificationsScreen() + + assert.equal(screen.destinations[0].lastResultAt, undefined) +}) + +test('the lead arrives as a number even when the API writes it as text', async () => { + store.settings = { notifyLeadMinutes: '10', publicOriginKnown: false } + + const screen = await getNotificationsScreen() + + assert.deepEqual(screen.settings, { + notifyLeadMinutes: 10, + publicOriginKnown: false, + }) +}) + +test('a lead the screen cannot offer is not shown as another one', async () => { + store.settings = { notifyLeadMinutes: 15, publicOriginKnown: true } + + await assert.rejects(getNotificationsScreen(), /通知の設定を読めませんでした/) +}) + +test('the deliveries of every destination are asked for, fifty each', async () => { + await getNotificationsScreen() + + assert.deepEqual( + sent + .filter((one) => one.path === '/api/notifications/deliveries') + .map((one) => one.query), + [ + { destinationId: HOME, perPage: 50 }, + { destinationId: GAMES, perPage: 50 }, + ], + ) +}) + +test('the deliveries come as one list, the newest first, each with the destination it went to', async () => { + store.deliveries = { + [HOME]: [ + delivery('d-1', '2026-01-02T10:00:00Z'), + delivery('d-3', '2026-01-02T08:00:00Z'), + ], + [GAMES]: [ + delivery('d-2', '2026-01-02T09:00:00Z', { + kind: 'encodeFailed', + state: 'givenUp', + failure: 'rejected', + }), + ], + } + + const screen = await getNotificationsScreen() + + assert.deepEqual(screen.deliveries, [ + { + id: 'd-1', + kind: 'recordingFailed', + occurredAt: '2026-01-02T10:00:00Z', + destinationId: HOME, + state: 'sent', + failure: undefined, + }, + { + id: 'd-2', + kind: 'encodeFailed', + occurredAt: '2026-01-02T09:00:00Z', + destinationId: GAMES, + state: 'givenUp', + failure: 'rejected', + }, + { + id: 'd-3', + kind: 'recordingFailed', + occurredAt: '2026-01-02T08:00:00Z', + destinationId: HOME, + state: 'sent', + failure: undefined, + }, + ]) +}) + +test('with no destination, no delivery is asked for', async () => { + store.destinations = [] + store.rules = [] + + const screen = await getNotificationsScreen() + + assert.deepEqual(screen.deliveries, []) + assert.equal( + sent.some((one) => one.path === '/api/notifications/deliveries'), + false, + ) +}) + +test('a screen that cannot be read says so', async () => { + store.readStatus = 500 + + await assert.rejects(getNotificationsScreen(), /通知の設定を読めませんでした/) +}) + +test('a destination is registered by its name and its address', async () => { + store.writeStatus = 201 + + const result = await registerDestination({ + name: '見本の送り先 3', + url: 'https://webhook.example/one', + }) + + assert.deepEqual(result, { state: 'ok' }) + assert.deepEqual(sent, [ + { + method: 'POST', + path: '/api/notifications/destinations', + at: undefined, + body: { name: '見本の送り先 3', url: 'https://webhook.example/one' }, + }, + ]) +}) + +test('a change that leaves the address empty sends it empty, so the address stays', async () => { + await reviseDestination(HOME, { name: '見本の送り先 1', enabled: false }) + + assert.deepEqual(sent, [ + { + method: 'PATCH', + path: '/api/notifications/destinations/{id}', + at: { id: HOME }, + body: { name: '見本の送り先 1', enabled: false, url: '' }, + }, + ]) +}) + +test('a change that writes the address anew sends it', async () => { + await reviseDestination(HOME, { + name: '見本の送り先 1', + enabled: true, + url: 'https://webhook.example/two', + }) + + assert.deepEqual(sent[0].body, { + name: '見本の送り先 1', + enabled: true, + url: 'https://webhook.example/two', + }) +}) + +test('the switch of a destination sends the switch alone', async () => { + await switchDestination(GAMES, true) + + assert.deepEqual(sent, [ + { + method: 'PATCH', + path: '/api/notifications/destinations/{id}', + at: { id: GAMES }, + body: { enabled: true }, + }, + ]) +}) + +test('a destination is removed by its id', async () => { + const result = await removeDestination(HOME) + + assert.deepEqual(result, { state: 'ok' }) + assert.deepEqual(sent, [ + { + method: 'DELETE', + path: '/api/notifications/destinations/{id}', + at: { id: HOME }, + body: undefined, + }, + ]) +}) + +test('a trial that arrived says so', async () => { + const result = await tryDestination(HOME) + + assert.deepEqual(result, { + state: 'ok', + delivered: true, + failure: undefined, + }) + assert.deepEqual(sent, [ + { + method: 'POST', + path: '/api/notifications/destinations/{id}/test', + at: { id: HOME }, + body: undefined, + }, + ]) +}) + +test('a trial that did not arrive carries why', async () => { + store.trial = { delivered: false, failure: 'unreachable' } + + assert.deepEqual(await tryDestination(HOME), { + state: 'ok', + delivered: false, + failure: 'unreachable', + }) +}) + +test('a trial sent too soon after another is refused in words a reader can act on', async () => { + store.writeStatus = 429 + store.writeMessage = + 'A trial was sent a moment ago. One destination is tried once a minute, and five trials are sent a minute in all.' + + assert.deepEqual(await tryDestination(HOME), { + state: 'rejected', + message: '続けてテスト送信はできません。1 分ほどおいてからお試しください。', + }) +}) + +test('a trial to a destination whose address cannot be opened says to write it again', async () => { + store.writeStatus = 409 + store.writeMessage = + 'The address of this destination cannot be opened with the keys this server holds. Write the address again to send to it.' + + assert.deepEqual(await tryDestination(HOME), { + state: 'rejected', + message: 'この送り先の URL を開けません。URL を入れ直してください。', + }) +}) + +test('a rule set is made of its name, its switch, its events and its destinations', async () => { + store.writeStatus = 201 + + const result = await defineRuleSet({ + name: '見本のルールセット 2', + enabled: true, + events: ['recordingCompleted'], + destinations: [HOME, GAMES], + }) + + assert.deepEqual(result, { state: 'ok' }) + assert.deepEqual(sent, [ + { + method: 'POST', + path: '/api/notifications/rules', + at: undefined, + body: { + name: '見本のルールセット 2', + enabled: true, + events: ['recordingCompleted'], + destinations: [HOME, GAMES], + }, + }, + ]) +}) + +test('a rule set is changed, switched and removed by its id', async () => { + await reviseRuleSet(FAILURES, { + name: '見本のルールセット', + enabled: true, + events: [], + destinations: [GAMES], + }) + await switchRuleSet(FAILURES, false) + await removeRuleSet(FAILURES) + + assert.deepEqual(sent, [ + { + method: 'PATCH', + path: '/api/notifications/rules/{id}', + at: { id: FAILURES }, + body: { + name: '見本のルールセット', + enabled: true, + events: [], + destinations: [GAMES], + }, + }, + { + method: 'PATCH', + path: '/api/notifications/rules/{id}', + at: { id: FAILURES }, + body: { enabled: false }, + }, + { + method: 'DELETE', + path: '/api/notifications/rules/{id}', + at: { id: FAILURES }, + body: undefined, + }, + ]) +}) + +test('the lead is put as the minutes chosen', async () => { + const result = await settleLead(5) + + assert.deepEqual(result, { state: 'ok' }) + assert.deepEqual(sent, [ + { + method: 'PUT', + path: '/api/notifications/settings', + at: undefined, + body: { notifyLeadMinutes: 5 }, + }, + ]) +}) + +test('a write from someone signed out says so, whatever was being written', async () => { + store.writeStatus = 401 + + assert.deepEqual(await registerDestination({ name: 'n', url: 'u' }), { + state: 'unauthenticated', + }) + assert.deepEqual(await tryDestination(HOME), { state: 'unauthenticated' }) + assert.deepEqual(await settleLead(0), { state: 'unauthenticated' }) +}) + +test('an address Carina will not send to is refused in the words the form uses', async () => { + store.writeStatus = 400 + store.writeMessage = + 'The address is not one a notice can be sent to: an https webhook of Slack or of Discord. It is not repeated here.' + + assert.deepEqual(await registerDestination({ name: 'n', url: 'u' }), { + state: 'rejected', + message: 'この URL は受け付けられません。', + }) +}) + +test('the twenty-first rule set is refused with the number that are held', async () => { + store.writeStatus = 409 + store.writeMessage = + 'At most 20 sets of rules are held. Remove one to make another.' + + assert.deepEqual( + await defineRuleSet({ + name: 'n', + enabled: true, + events: [], + destinations: [HOME], + }), + { + state: 'rejected', + message: 'ルールセットは 20 本までのため、追加できませんでした。', + }, + ) +}) + +test('what Carina says about a refusal is put in the words of the screen', () => { + assert.equal( + whyItRefused( + WHEN_CHANGING_A_DESTINATION, + 'No destination is registered under that id.', + ), + 'この送り先は残っていないため、変更できませんでした。', + ) + assert.equal( + whyItRefused( + WHEN_TRYING_A_DESTINATION, + 'No destination is registered under that id.', + ), + 'この送り先は残っていないため、テスト送信できませんでした。', + ) + assert.equal( + whyItRefused( + WHEN_CHANGING_A_RULE_SET, + 'No set of rules is held under that id.', + ), + 'このルールセットは残っていないため、変更できませんでした。', + ) + assert.equal( + whyItRefused( + WHEN_ADDING_A_RULE_SET, + 'A set of rules sends to at least one destination, each of them registered.', + ), + '選んだ送り先が残っていないため、追加できませんでした。', + ) + assert.equal( + whyItRefused( + WHEN_ADDING_A_DESTINATION, + 'A destination is named in one to sixty-four characters, none of them a control character.', + ), + '名前が 1 〜 64 文字でないため、追加できませんでした。', + ) + assert.equal( + whyItRefused(WHEN_ADDING_A_DESTINATION, undefined), + '送り先を追加できませんでした。時間をおいてからもう一度お試しください。', + ) + assert.equal( + whyItRefused( + WHEN_ADDING_A_DESTINATION, + 'Something this build never heard.', + ), + '送り先を追加できませんでした。時間をおいてからもう一度お試しください。', + ) +}) diff --git a/tests/storybook/every-test-runs.test.ts b/tests/storybook/every-test-runs.test.ts index 5fe18b37..fab74fc4 100644 --- a/tests/storybook/every-test-runs.test.ts +++ b/tests/storybook/every-test-runs.test.ts @@ -193,6 +193,7 @@ const THE_SUITE = [ 'tests/repository/live-viewers.test.ts', 'tests/repository/live.test.ts', 'tests/repository/migration.test.ts', + 'tests/repository/notifications.test.ts', 'tests/repository/oidc.test.ts', 'tests/repository/playback-sources.test.ts', 'tests/repository/programs.test.ts', diff --git a/tests/storybook/fields-the-api-answers.test.ts b/tests/storybook/fields-the-api-answers.test.ts index 38d196d6..249792a0 100644 --- a/tests/storybook/fields-the-api-answers.test.ts +++ b/tests/storybook/fields-the-api-answers.test.ts @@ -45,6 +45,9 @@ const NOT_READ_ON_PURPOSE: { because: string; fields: string[] }[] = [ 'BaseResponderOfEncodeJobResponder.data', 'BaseResponderOfEncodeProfileResponder.data', 'EncodeRerunResponder.job', + 'BaseResponderOfNotificationDestinationResponder.data', + 'BaseResponderOfNotificationRemovalResponder.data', + 'BaseResponderOfNotificationRuleResponder.data', 'BaseResponderOfQualityThresholdResponder.data', 'BaseResponderOfScanApplicationResponder.data', 'BaseResponderOfScanRefusedResponder.data', @@ -76,6 +79,7 @@ const NOT_READ_ON_PURPOSE: { because: string; fields: string[] }[] = [ 'MigrationRecordResponder.currentPage', 'MigrationRecordResponder.perPage', 'MigrationRecordResponder.total', + 'NotificationDeliveryListResponder.perPage', 'QualityChannelListResponder.currentPage', 'QualityChannelListResponder.lastPage', 'QualityChannelListResponder.perPage', @@ -94,6 +98,21 @@ const NOT_READ_ON_PURPOSE: { because: string; fields: string[] }[] = [ 'ReservationOutcomeListResponder.perPage', ], }, + { + because: + 'a destination says when it last answered and a delivery says when its notice happened and how it ended; when a row was made or changed, and the heading, the attempts and the timetable of one delivery, are drawn nowhere', + fields: [ + 'NotificationDeliveryResponder.attempts', + 'NotificationDeliveryResponder.nextAttemptAt', + 'NotificationDeliveryResponder.queuedAt', + 'NotificationDeliveryResponder.sentAt', + 'NotificationDeliveryResponder.title', + 'NotificationDestinationResponder.changedAt', + 'NotificationDestinationResponder.createdAt', + 'NotificationRuleResponder.changedAt', + 'NotificationRuleResponder.createdAt', + ], + }, { because: 'an id of the very row that was acted on, which the screen was holding before it asked; an id is never put in front of the reader', From 92b3b56aef4e87b24302470e494a307569860d4e Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 03:45:39 +0900 Subject: [PATCH 12/24] =?UTF-8?q?=E8=A8=AD=E5=AE=9A=E3=81=AB=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E3=81=AE=E7=94=BB=E9=9D=A2=E3=82=92=E8=B6=B3=E3=81=97?= =?UTF-8?q?=E3=80=81=E8=A8=AD=E5=AE=9A=E3=81=AE=E4=B8=80=E8=A6=A7=E3=81=AE?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E3=81=AB=E3=81=84=E3=81=A4=E3=82=82=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E3=82=92=E5=87=BA=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- app/(app)/settings/notifications/actions.ts | 124 +++++++++++++++++ app/(app)/settings/notifications/page.tsx | 40 ++++++ components/notifications/delivery-log.tsx | 4 +- components/notifications/destination-list.tsx | 4 +- .../notifications/notifications-page.tsx | 4 +- .../settings-entrance/settings-beside.tsx | 3 - .../settings-entrance-page.tsx | 17 +-- .../settings-entrance/settings-frame.tsx | 4 - lib/phone-bar.ts | 2 +- stories/frames.tsx | 18 --- stories/screens/Notifications.stories.tsx | 4 +- stories/screens/SettingsEntrance.stories.tsx | 4 +- .../settings/notifications/actions.test.ts | 125 ++++++++++++++++++ tests/storybook/every-test-runs.test.ts | 1 + 14 files changed, 306 insertions(+), 48 deletions(-) create mode 100644 app/(app)/settings/notifications/actions.ts create mode 100644 app/(app)/settings/notifications/page.tsx create mode 100644 tests/app/(app)/settings/notifications/actions.test.ts diff --git a/app/(app)/settings/notifications/actions.ts b/app/(app)/settings/notifications/actions.ts new file mode 100644 index 00000000..cb3c7909 --- /dev/null +++ b/app/(app)/settings/notifications/actions.ts @@ -0,0 +1,124 @@ +'use server' + +import { revalidatePath } from 'next/cache' + +import type { + DestinationRevision, + LeadMinutes, + NotificationWrite, + RuleSetDraft, + TestSending, + WebhookDraft, +} from '@/lib/notifications' +import { + defineRuleSet, + registerDestination, + removeDestination, + removeRuleSet, + reviseDestination, + reviseRuleSet, + settleLead, + switchDestination, + switchRuleSet, + tryDestination, +} from '@/repository/notifications' + +const NOTIFICATIONS = '/settings/notifications' + +export async function addDestination( + draft: WebhookDraft, +): Promise { + const result = await registerDestination(draft) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function changeDestination( + id: string, + revision: DestinationRevision, +): Promise { + const result = await reviseDestination(id, revision) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function turnDestination( + id: string, + enabled: boolean, +): Promise { + const result = await switchDestination(id, enabled) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function sendTrial(id: string): Promise { + const result = await tryDestination(id) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function dropDestination(id: string): Promise { + const result = await removeDestination(id) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function addRuleSet( + draft: RuleSetDraft, +): Promise { + const result = await defineRuleSet(draft) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function changeRuleSet( + id: string, + draft: RuleSetDraft, +): Promise { + const result = await reviseRuleSet(id, draft) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function turnRuleSet( + id: string, + enabled: boolean, +): Promise { + const result = await switchRuleSet(id, enabled) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function dropRuleSet(id: string): Promise { + const result = await removeRuleSet(id) + + revalidatePath(NOTIFICATIONS) + + return result +} + +export async function settleTheLead( + lead: LeadMinutes, +): Promise { + const result = await settleLead(lead) + + revalidatePath(NOTIFICATIONS) + + return result +} diff --git a/app/(app)/settings/notifications/page.tsx b/app/(app)/settings/notifications/page.tsx new file mode 100644 index 00000000..7111575a --- /dev/null +++ b/app/(app)/settings/notifications/page.tsx @@ -0,0 +1,40 @@ +import type { Metadata } from 'next' + +import { getNotificationsScreen } from '@/repository/notifications' +import { NotificationsView } from '@/components/notifications/notifications-page' +import { + addDestination, + addRuleSet, + changeDestination, + changeRuleSet, + dropDestination, + dropRuleSet, + sendTrial, + settleTheLead, + turnDestination, + turnRuleSet, +} from './actions' + +export const metadata: Metadata = { title: '通知' } + +export default async function Page() { + const screen = await getNotificationsScreen() + + return ( + + ) +} diff --git a/components/notifications/delivery-log.tsx b/components/notifications/delivery-log.tsx index bfa955c4..1aaf116a 100644 --- a/components/notifications/delivery-log.tsx +++ b/components/notifications/delivery-log.tsx @@ -88,7 +88,7 @@ export function DeliveryLog({ }: { deliveries: NotificationDelivery[] destinations: Pick[] - now: number + now?: number }) { const names = new Map(destinations.map(({ id, name }) => [id, name])) @@ -127,7 +127,7 @@ function DeliveryRow({ }: { delivery: NotificationDelivery sentTo?: string - now: number + now?: number }) { const said = deliverySaid(delivery) diff --git a/components/notifications/destination-list.tsx b/components/notifications/destination-list.tsx index cd4641e2..5e40ac46 100644 --- a/components/notifications/destination-list.tsx +++ b/components/notifications/destination-list.tsx @@ -87,7 +87,7 @@ export function DestinationList({ destinations: NotificationDestination[] ruleSets: Pick[] actions: DestinationActions - now: number + now?: number }) { return (
            () diff --git a/components/notifications/notifications-page.tsx b/components/notifications/notifications-page.tsx index cd2026be..65cd7e7b 100644 --- a/components/notifications/notifications-page.tsx +++ b/components/notifications/notifications-page.tsx @@ -78,8 +78,8 @@ export function NotificationsView({ actions: NotificationActions /** This browser as a destination, where it can be one. */ browser?: BrowserChoice - /** The moment the screen was drawn for, which today's times are said against. */ - now: number + /** The present held still, for a picture. */ + now?: number }) { const { settings, destinations, ruleSets } = screen const [lead, setLead] = useState(settings.notifyLeadMinutes) diff --git a/components/settings-entrance/settings-beside.tsx b/components/settings-entrance/settings-beside.tsx index 2a24bf26..907ba282 100644 --- a/components/settings-entrance/settings-beside.tsx +++ b/components/settings-entrance/settings-beside.tsx @@ -14,12 +14,10 @@ export function SettingsBeside({ status, values, hasMigration, - hasNotifications = false, }: { status: SystemStatus values: SettingsEntranceValues hasMigration: boolean - hasNotifications?: boolean }) { const sideways = usePhoneOnItsSide() const pathname = usePathname() @@ -38,7 +36,6 @@ export function SettingsBeside({ status={status} values={values} hasMigration={hasMigration} - hasNotifications={hasNotifications} current={pathname} /> diff --git a/components/settings-entrance/settings-entrance-page.tsx b/components/settings-entrance/settings-entrance-page.tsx index 0b2cdbf1..a49c03ff 100644 --- a/components/settings-entrance/settings-entrance-page.tsx +++ b/components/settings-entrance/settings-entrance-page.tsx @@ -140,7 +140,6 @@ function groupsOf( status: SystemStatus, values: SettingsEntranceValues, hasMigration: boolean, - hasNotifications: boolean, ): Group[] { const keeping: Item[] = [ { @@ -155,16 +154,13 @@ function groupsOf( icon: QualityIcon, tile: TILE.keeping, }, - ] - - if (hasNotifications) { - keeping.push({ - href: '/settings/notifications' as Route, + { + href: '/settings/notifications', label: '通知', icon: BellIcon, tile: TILE.keeping, - }) - } + }, + ] if (hasMigration) { keeping.push({ @@ -352,15 +348,12 @@ export function SettingsEntranceView({ status, values, hasMigration, - hasNotifications = false, current, withValues = true, }: { status: SystemStatus values: SettingsEntranceValues hasMigration: boolean - /** Whether notifications stand in the list, after the integrity check. Off until their screen exists. */ - hasNotifications?: boolean current?: string /** Each setting's value after its name; the wide screen leaves them to the setting open beside. */ withValues?: boolean @@ -371,7 +364,7 @@ export function SettingsEntranceView({
            {current === undefined &&

            設定

            } - {groupsOf(status, values, hasMigration, hasNotifications).map((group) => ( + {groupsOf(status, values, hasMigration).map((group) => (
            @@ -65,7 +62,6 @@ export function SettingsFrame({ status={status} values={values} hasMigration={hasMigration} - hasNotifications={hasNotifications} /> ( ) -/** The settings frame with notifications in its list, for their stories until their screen is in the app. */ -export const inTheSettingsWithNotifications: Decorator = (Story) => ( - - - - - - - - - -) - export const inTheSettings: Decorator = (Story) => ( diff --git a/stories/screens/Notifications.stories.tsx b/stories/screens/Notifications.stories.tsx index d560bec4..9b7e2c20 100644 --- a/stories/screens/Notifications.stories.tsx +++ b/stories/screens/Notifications.stories.tsx @@ -12,7 +12,7 @@ import { type BrowserChoice, } from '@/components/notifications/add-destination-dialog' import { REFUSED_ADDRESS } from '@/components/notifications/webhook-field' -import { inTheSettingsWithNotifications } from '@/stories/frames' +import { inTheSettings } from '@/stories/frames' import { PHONE } from '@/stories/rows-as-cards' import { DESTINATIONS, @@ -102,7 +102,7 @@ const meta = { browser: BROWSER, now: NOTIFICATIONS_NOW, }, - decorators: [inTheSettingsWithNotifications], + decorators: [inTheSettings], } satisfies Meta export default meta diff --git a/stories/screens/SettingsEntrance.stories.tsx b/stories/screens/SettingsEntrance.stories.tsx index 6ac64ffa..fe4e0aae 100644 --- a/stories/screens/SettingsEntrance.stories.tsx +++ b/stories/screens/SettingsEntrance.stories.tsx @@ -35,7 +35,7 @@ const GROUPS: [string, string[]][] = [ ['観る', ['視聴', '表示']], ['録る', ['エンコード', 'CM・OP・ED の検出', '品質']], ['機器', ['チューナー', 'チャンネル']], - ['管理', ['認証', '整合性チェック', '移行記録']], + ['管理', ['認証', '整合性チェック', '通知', '移行記録']], ] function entranceOf(canvasElement: HTMLElement): HTMLElement { @@ -119,7 +119,7 @@ export const 移行記録が無い: Story = { within(entranceOf(canvasElement)).getByRole('region', { name: '管理' }), ) - await expect(keeping.getAllByRole('link')).toHaveLength(2) + await expect(keeping.getAllByRole('link')).toHaveLength(3) await expect(keeping.queryByText('移行記録')).not.toBeInTheDocument() }, } diff --git a/tests/app/(app)/settings/notifications/actions.test.ts b/tests/app/(app)/settings/notifications/actions.test.ts new file mode 100644 index 00000000..ae823147 --- /dev/null +++ b/tests/app/(app)/settings/notifications/actions.test.ts @@ -0,0 +1,125 @@ +import assert from 'node:assert/strict' +import { registerHooks } from 'node:module' +import { beforeEach, mock, test } from 'node:test' + +const CACHE = 'next/cache' + +registerHooks({ + resolve(specifier, context, next) { + return next(specifier === CACHE ? `${CACHE}.js` : specifier, context) + }, +}) + +const ONE = '0a000000-0000-4000-8000-000000000001' +const PAGE = '/settings/notifications' + +const store: { status: number; said?: string } = { status: 200 } + +const revalidated: string[] = [] + +async function answer() { + const ok = store.status < 400 + + return { + data: ok ? { data: { delivered: true, failure: null } } : undefined, + error: ok ? undefined : { message: store.said }, + response: { status: store.status, ok }, + } +} + +const client = () => ({ + POST: answer, + PATCH: answer, + PUT: answer, + DELETE: answer, +}) + +mock.module('@/repository/client/carina', { + namedExports: { carinaClient: client, revalidatingCarinaClient: client }, +}) + +mock.module(CACHE, { + namedExports: { + revalidatePath: (path: string) => { + revalidated.push(path) + }, + }, +}) + +const { + addDestination, + addRuleSet, + changeDestination, + changeRuleSet, + dropDestination, + dropRuleSet, + sendTrial, + settleTheLead, + turnDestination, + turnRuleSet, +} = await import('@/app/(app)/settings/notifications/actions') + +const RULES = { + name: '見本のルールセット', + enabled: true, + events: [], + destinations: [ONE], +} + +beforeEach(() => { + revalidated.length = 0 + store.status = 200 + store.said = undefined +}) + +test('every change the API took reads the page again', async () => { + const written = await Promise.all([ + addDestination({ + name: '見本の送り先', + url: 'https://webhook.example/one', + }), + changeDestination(ONE, { name: '見本の送り先', enabled: true }), + turnDestination(ONE, false), + dropDestination(ONE), + addRuleSet(RULES), + changeRuleSet(ONE, RULES), + turnRuleSet(ONE, false), + dropRuleSet(ONE), + settleTheLead(3), + ]) + + assert.deepEqual( + written, + written.map(() => ({ state: 'ok' })), + ) + assert.deepEqual( + revalidated, + written.map(() => PAGE), + ) +}) + +test('a trial says whether it arrived and reads the page again', async () => { + assert.deepEqual(await sendTrial(ONE), { + state: 'ok', + delivered: true, + failure: undefined, + }) + assert.deepEqual(revalidated, [PAGE]) +}) + +test('a change about a destination that is gone reads the page again', async () => { + store.status = 404 + store.said = 'No destination is registered under that id.' + + assert.deepEqual(await dropDestination(ONE), { + state: 'rejected', + message: 'この送り先は残っていないため、削除できませんでした。', + }) + assert.deepEqual(revalidated, [PAGE]) +}) + +test('a change from a session that ended says so', async () => { + store.status = 401 + + assert.deepEqual(await turnRuleSet(ONE, true), { state: 'unauthenticated' }) +}) diff --git a/tests/storybook/every-test-runs.test.ts b/tests/storybook/every-test-runs.test.ts index fab74fc4..29c0b790 100644 --- a/tests/storybook/every-test-runs.test.ts +++ b/tests/storybook/every-test-runs.test.ts @@ -7,6 +7,7 @@ import { test } from 'node:test' const TOLD_TO_RUN = ['tests/**/*.test.ts'] const THE_SUITE = [ + 'tests/app/(app)/settings/notifications/actions.test.ts', 'tests/app/(app)/settings/segments/actions.test.ts', 'tests/app/a-fold-comes-with-the-page.test.ts', 'tests/app/the-app-goes-on-the-home-screen.test.ts', From ba957b771dcff2ae2b2e9782f15b19a66cff3a37 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 05:46:53 +0900 Subject: [PATCH 13/24] =?UTF-8?q?=E5=8D=98=E7=99=BA=E3=81=AE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E3=81=AE=20API=20=E3=82=92=20OpenAPI=20=E3=81=AE?= =?UTF-8?q?=E6=96=87=E6=9B=B8=E3=81=A8=E7=94=9F=E6=88=90=E3=81=97=E3=81=9F?= =?UTF-8?q?=E5=9E=8B=E3=81=AB=E5=8F=96=E3=82=8A=E8=BE=BC=E3=82=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- repository/client/carina.json | 467 +++++++++++++++++++++++++++++++++- repository/client/schema.ts | 308 +++++++++++++++++++++- 2 files changed, 768 insertions(+), 7 deletions(-) diff --git a/repository/client/carina.json b/repository/client/carina.json index 984e9436..0559350c 100644 --- a/repository/client/carina.json +++ b/repository/client/carina.json @@ -5726,6 +5726,80 @@ } } }, + "/api/notifications/watches/{id}": { + "delete": { + "tags": [ + "notifications" + ], + "operationId": "cancelNotificationWatch", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + } + } + } + }, "/api/notifications/destinations": { "post": { "tags": [ @@ -5940,6 +6014,128 @@ } } }, + "/api/notifications/watches": { + "post": { + "tags": [ + "notifications" + ], + "operationId": "createNotificationWatch", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CreateNotificationWatchRequest" + } + ] + } + }, + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CreateNotificationWatchRequest" + } + ] + } + } + } + }, + "responses": { + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchResponder" + } + } + } + } + } + }, + "get": { + "tags": [ + "notifications" + ], + "operationId": "listNotificationWatches", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchListResponder" + } + } + } + }, + "401": { + "description": "Unauthenticated. The default-deny middleware answers with an empty body." + }, + "500": { + "description": "The request failed before it could answer for itself. The body carries the usual envelope with no data.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BaseResponderOfNotificationWatchListResponder" + } + } + } + } + } + } + }, "/api/notifications/settings": { "get": { "tags": [ @@ -11456,6 +11652,58 @@ } } }, + "BaseResponderOfNotificationWatchListResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NotificationWatchListResponder" + } + ] + } + } + }, + "BaseResponderOfNotificationWatchResponder": { + "required": [ + "status", + "message", + "data" + ], + "type": "object", + "properties": { + "status": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "data": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NotificationWatchResponder" + } + ] + } + } + }, "BaseResponderOfOidcConfigRefusedResponder": { "required": [ "status", @@ -13829,7 +14077,22 @@ "array" ], "items": { - "$ref": "#/components/schemas/NoticeKind" + "enum": [ + "recordingStarted", + "recordingCompleted", + "recordingTruncated", + "recordingFailed", + "encodeStarted", + "encodeCompleted", + "encodeFailed", + "reservationCompeting", + "reservationMissed", + "programmeMoved", + "qualityIncidentDetected", + "qualityIncidentResolved", + "deviceDisconnected" + ], + "type": "string" } }, "destinations": { @@ -13844,6 +14107,43 @@ } } }, + "CreateNotificationWatchRequest": { + "type": "object", + "properties": { + "programme": { + "type": [ + "null", + "string" + ] + }, + "programmeStartsAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "leadMinutes": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ], + "format": "int32" + }, + "destinations": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string", + "format": "uuid" + } + } + } + }, "CreateReservationRequest": { "type": "object", "properties": { @@ -16812,7 +17112,10 @@ "programmeMoved", "qualityIncidentDetected", "qualityIncidentResolved", - "deviceDisconnected" + "deviceDisconnected", + "programmeStarting", + "watchedProgrammeMoved", + "watchedProgrammeGone" ], "type": "string" }, @@ -17066,7 +17369,22 @@ "events": { "type": "array", "items": { - "$ref": "#/components/schemas/NoticeKind" + "enum": [ + "recordingStarted", + "recordingCompleted", + "recordingTruncated", + "recordingFailed", + "encodeStarted", + "encodeCompleted", + "encodeFailed", + "reservationCompeting", + "reservationMissed", + "programmeMoved", + "qualityIncidentDetected", + "qualityIncidentResolved", + "deviceDisconnected" + ], + "type": "string" } }, "destinations": { @@ -17106,6 +17424,123 @@ } } }, + "NotificationWatchListResponder": { + "required": [ + "items" + ], + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NotificationWatchResponder" + } + } + } + }, + "NotificationWatchResponder": { + "required": [ + "id", + "programmeId", + "networkId", + "serviceId", + "eventId", + "startsAt", + "endsAt", + "programmeName", + "stationName", + "leadMinutes", + "destinations", + "state", + "notifiedAt", + "createdAt", + "changedAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "programmeId": { + "type": "string" + }, + "networkId": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "serviceId": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "eventId": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "startsAt": { + "type": "string", + "format": "date-time" + }, + "endsAt": { + "type": "string", + "format": "date-time" + }, + "programmeName": { + "type": "string" + }, + "stationName": { + "type": [ + "null", + "string" + ] + }, + "leadMinutes": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "destinations": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + }, + "state": { + "$ref": "#/components/schemas/ProgrammeWatchState" + }, + "notifiedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "changedAt": { + "type": "string", + "format": "date-time" + } + } + }, "OidcConfigRefusal": { "enum": [ "secretRequired", @@ -17830,6 +18265,15 @@ ], "type": "string" }, + "ProgrammeWatchState": { + "enum": [ + "waiting", + "notified", + "skipped", + "cancelled" + ], + "type": "string" + }, "PutDataBroadcastSettingsRequest": { "required": [ "postalCode", @@ -21601,7 +22045,22 @@ "array" ], "items": { - "$ref": "#/components/schemas/NoticeKind" + "enum": [ + "recordingStarted", + "recordingCompleted", + "recordingTruncated", + "recordingFailed", + "encodeStarted", + "encodeCompleted", + "encodeFailed", + "reservationCompeting", + "reservationMissed", + "programmeMoved", + "qualityIncidentDetected", + "qualityIncidentResolved", + "deviceDisconnected" + ], + "type": "string" } }, "destinations": { diff --git a/repository/client/schema.ts b/repository/client/schema.ts index 7509e957..60deb404 100644 --- a/repository/client/schema.ts +++ b/repository/client/schema.ts @@ -1053,6 +1053,22 @@ export interface paths { patch: operations['reviseQualityThreshold'] trace?: never } + '/api/notifications/watches/{id}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + post?: never + delete: operations['cancelNotificationWatch'] + options?: never + head?: never + patch?: never + trace?: never + } '/api/notifications/destinations': { parameters: { query?: never @@ -1085,6 +1101,22 @@ export interface paths { patch?: never trace?: never } + '/api/notifications/watches': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get: operations['listNotificationWatches'] + put?: never + post: operations['createNotificationWatch'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } '/api/notifications/settings': { parameters: { query?: never @@ -2136,6 +2168,16 @@ export interface components { message: string data: null | components['schemas']['NotificationSettingsResponder'] } + BaseResponderOfNotificationWatchListResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationWatchListResponder'] + } + BaseResponderOfNotificationWatchResponder: { + status: boolean + message: string + data: null | components['schemas']['NotificationWatchResponder'] + } BaseResponderOfOidcConfigRefusedResponder: { status: boolean message: string @@ -2629,7 +2671,31 @@ export interface components { CreateNotificationRuleRequest: { name?: null | string enabled?: null | boolean - events?: null | components['schemas']['NoticeKind'][] + events?: + | null + | ( + | 'recordingStarted' + | 'recordingCompleted' + | 'recordingTruncated' + | 'recordingFailed' + | 'encodeStarted' + | 'encodeCompleted' + | 'encodeFailed' + | 'reservationCompeting' + | 'reservationMissed' + | 'programmeMoved' + | 'qualityIncidentDetected' + | 'qualityIncidentResolved' + | 'deviceDisconnected' + )[] + destinations?: null | string[] + } + CreateNotificationWatchRequest: { + programme?: null | string + /** Format: date-time */ + programmeStartsAt?: null | string + /** Format: int32 */ + leadMinutes?: null | number | string destinations?: null | string[] } CreateReservationRequest: { @@ -3404,6 +3470,9 @@ export interface components { | 'qualityIncidentDetected' | 'qualityIncidentResolved' | 'deviceDisconnected' + | 'programmeStarting' + | 'watchedProgrammeMoved' + | 'watchedProgrammeGone' NoticeTrialResponder: { delivered: boolean failure: null | components['schemas']['NoticeFailure'] @@ -3464,7 +3533,21 @@ export interface components { id: string name: string enabled: boolean - events: components['schemas']['NoticeKind'][] + events: ( + | 'recordingStarted' + | 'recordingCompleted' + | 'recordingTruncated' + | 'recordingFailed' + | 'encodeStarted' + | 'encodeCompleted' + | 'encodeFailed' + | 'reservationCompeting' + | 'reservationMissed' + | 'programmeMoved' + | 'qualityIncidentDetected' + | 'qualityIncidentResolved' + | 'deviceDisconnected' + )[] destinations: string[] /** Format: date-time */ createdAt: string @@ -3476,6 +3559,36 @@ export interface components { notifyLeadMinutes: number | string publicOriginKnown: boolean } + NotificationWatchListResponder: { + items: components['schemas']['NotificationWatchResponder'][] + } + NotificationWatchResponder: { + /** Format: uuid */ + id: string + programmeId: string + /** Format: int32 */ + networkId: number | string + /** Format: int32 */ + serviceId: number | string + /** Format: int32 */ + eventId: number | string + /** Format: date-time */ + startsAt: string + /** Format: date-time */ + endsAt: string + programmeName: string + stationName: null | string + /** Format: int32 */ + leadMinutes: number | string + destinations: string[] + state: components['schemas']['ProgrammeWatchState'] + /** Format: date-time */ + notifiedAt: null | string + /** Format: date-time */ + createdAt: string + /** Format: date-time */ + changedAt: string + } /** @enum {string} */ OidcConfigRefusal: | 'secretRequired' @@ -3648,6 +3761,8 @@ export interface components { } /** @enum {string} */ ProgrammeSource: 'presentFollowing' | 'scheduleBasic' | 'scheduleExtended' + /** @enum {string} */ + ProgrammeWatchState: 'waiting' | 'notified' | 'skipped' | 'cancelled' PutDataBroadcastSettingsRequest: { postalCode: null | string /** Format: int32 */ @@ -4599,7 +4714,23 @@ export interface components { ReviseNotificationRuleRequest: { name?: null | string enabled?: null | boolean - events?: null | components['schemas']['NoticeKind'][] + events?: + | null + | ( + | 'recordingStarted' + | 'recordingCompleted' + | 'recordingTruncated' + | 'recordingFailed' + | 'encodeStarted' + | 'encodeCompleted' + | 'encodeFailed' + | 'reservationCompeting' + | 'reservationMissed' + | 'programmeMoved' + | 'qualityIncidentDetected' + | 'qualityIncidentResolved' + | 'deviceDisconnected' + )[] destinations?: null | string[] } ReviseQualityThresholdRequest: { @@ -9665,6 +9796,71 @@ export interface operations { } } } + cancelNotificationWatch: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + } + } listNotificationDestinations: { parameters: { query?: never @@ -9850,6 +10046,112 @@ export interface operations { } } } + listNotificationWatches: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchListResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchListResponder'] + } + } + } + } + createNotificationWatch: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: { + content: { + 'application/json': + null | components['schemas']['CreateNotificationWatchRequest'] + 'application/*+json': + null | components['schemas']['CreateNotificationWatchRequest'] + } + } + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + /** @description Bad Request */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + /** @description Unauthenticated. The default-deny middleware answers with an empty body. */ + 401: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + /** @description The request failed before it could answer for itself. The body carries the usual envelope with no data. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BaseResponderOfNotificationWatchResponder'] + } + } + } + } getNotificationSettings: { parameters: { query?: never From d6c301a9d2f71724714db0ac751cd7161c12f9e0 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 06:39:42 +0900 Subject: [PATCH 14/24] =?UTF-8?q?=E5=8D=98=E7=99=BA=E3=81=AE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E3=82=92=20API=20=E3=81=8B=E3=82=89=E8=AA=AD=E3=81=BF?= =?UTF-8?q?=E3=80=81=E9=A0=BC=E3=81=BF=E3=80=81=E5=8F=96=E3=82=8A=E6=B6=88?= =?UTF-8?q?=E3=81=9B=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- app/(app)/guide/actions.ts | 27 ++ lib/notifications.ts | 120 ++++++++- repository/notifications.ts | 163 +++++++++++- repository/programs.fixtures.ts | 6 + repository/programs.ts | 52 ++-- stories/components/ProgramPanel.stories.tsx | 1 + stories/fixtures/notifications.ts | 6 +- tests/app/(app)/guide/actions.test.ts | 99 +++++++ tests/lib/notifications.test.ts | 92 +++++++ tests/repository/notifications.test.ts | 272 +++++++++++++++++++- tests/repository/programs.test.ts | 57 ++++ tests/storybook/every-test-runs.test.ts | 1 + 12 files changed, 869 insertions(+), 27 deletions(-) create mode 100644 tests/app/(app)/guide/actions.test.ts diff --git a/app/(app)/guide/actions.ts b/app/(app)/guide/actions.ts index 80013f4f..2efbcdf8 100644 --- a/app/(app)/guide/actions.ts +++ b/app/(app)/guide/actions.ts @@ -8,6 +8,12 @@ import type { RebuildResult, } from '@/repository/collection' import { collectNow, rebuildEpg } from '@/repository/collection' +import type { + NotificationWrite, + WatchDraft, + WatchWrite, +} from '@/lib/notifications' +import { askForWatch, cancelWatch } from '@/repository/notifications' import type { ProgramExtras } from '@/repository/programs' import { extrasOf } from '@/repository/programs' import type { @@ -97,3 +103,24 @@ export async function readProgramExtras( ): Promise { return extrasOf(kind, date, id, channelId) } + +export async function watchProgramme( + programmeId: string, + draft: WatchDraft, +): Promise { + const result = await askForWatch(programmeId, draft) + + revalidatePath('/guide') + revalidatePath('/reservations') + + return result +} + +export async function unwatchProgramme(id: string): Promise { + const result = await cancelWatch(id) + + revalidatePath('/guide') + revalidatePath('/reservations') + + return result +} diff --git a/lib/notifications.ts b/lib/notifications.ts index 67fb70ae..0f2b5fba 100644 --- a/lib/notifications.ts +++ b/lib/notifications.ts @@ -48,6 +48,13 @@ export type NotificationEvent = | 'qualityIncidentResolved' | 'deviceDisconnected' +/** What a notice can be of: an event a rule set chooses, or what a single notice tells, which no rule set does. */ +export type NoticeKind = + | NotificationEvent + | 'programmeStarting' + | 'watchedProgrammeMoved' + | 'watchedProgrammeGone' + export interface NotificationRuleSet { id: string name: string @@ -75,7 +82,7 @@ export type DeliveryState = 'queued' | 'sent' | 'failed' | 'givenUp' /** One notice on its way to one destination. Its title is the heading Carina gave the notice. */ export interface NotificationDelivery { id: string - kind: NotificationEvent + kind: NoticeKind occurredAt: string destinationId: string state: DeliveryState @@ -103,7 +110,27 @@ export interface NotificationsScreen { export interface ProgrammeWatch { id: string leadMinutes: LeadMinutes - destinationIds: string[] +} + +/** A single notice still waiting for its programme, as the list of reservations shows it. */ +export interface WatchedProgramme extends ProgrammeWatch { + title: string + channelName: string + startAt: string + endAt: string + destinationNames: string[] +} + +/** What a new single notice is asked with. */ +export interface WatchDraft { + leadMinutes: LeadMinutes + destinations: string[] +} + +/** What a new single notice starts from: the lead the settings hold and the destinations that are on. */ +export interface WatchOffer { + leadMinutes: LeadMinutes + destinations: Pick[] } export type NotificationWrite = @@ -111,6 +138,58 @@ export type NotificationWrite = | { state: 'unauthenticated' } | { state: 'rejected'; message: string } +export type WatchWrite = + | { state: 'ok'; watch: ProgrammeWatch } + | { state: 'unauthenticated' } + | { state: 'rejected'; message: string } + +/** One place in a list single notices stand among: what the list held, or a notice. */ +export type AmongWatches = + { own: T; watch?: undefined } | { own?: undefined; watch: WatchedProgramme } + +/** The list with each notice put before the first of its entries that starts later. */ +export function amongWatches( + own: readonly T[], + startOf: (one: T) => string | undefined, + watches: readonly WatchedProgramme[], +): AmongWatches[] { + const waiting = [...watches].sort( + (left, right) => Date.parse(left.startAt) - Date.parse(right.startAt), + ) + const among: AmongWatches[] = [] + let next = 0 + + for (const one of own) { + const start = startOf(one) + + while ( + start !== undefined && + next < waiting.length && + Date.parse(waiting[next].startAt) < Date.parse(start) + ) { + among.push({ watch: waiting[next] }) + next += 1 + } + + among.push({ own: one }) + } + + return [...among, ...waiting.slice(next).map((watch) => ({ watch }))] +} + +/** The single notices a list of reservations shows among its rows, and what takes one back. */ +export interface WaitingNotices { + watches: WatchedProgramme[] + onCancel: (id: string) => Promise +} + +/** What a programme's detail asks and takes back a single notice with; without an offer there is nowhere to send one. */ +export interface Noticing { + offer?: WatchOffer + onWatch: (programmeId: string, draft: WatchDraft) => Promise + onUnwatch: (watchId: string) => Promise +} + export type TestSending = | { state: 'ok'; delivered: boolean; failure?: DeliveryFailure } | { state: 'unauthenticated' } @@ -272,7 +351,7 @@ export function eventsSummary(events: readonly NotificationEvent[]): string { return said.length === 0 ? NO_EVENTS : said.join(' · ') } -export const EVENT_LABEL: Record = { +export const EVENT_LABEL: Record = { recordingStarted: '録画の開始', recordingCompleted: '録画の完了', recordingTruncated: '録画の欠け', @@ -286,9 +365,12 @@ export const EVENT_LABEL: Record = { qualityIncidentDetected: '品質の異常の発生', qualityIncidentResolved: '品質の異常の解消', deviceDisconnected: '機器の切断', + programmeStarting: '放送開始', + watchedProgrammeMoved: '放送時刻の変更', + watchedProgrammeGone: '放送の取り消し', } -export function eventLabelOf(event: NotificationEvent): string { +export function eventLabelOf(event: NoticeKind): string { return wordFor(EVENT_LABEL, event) } @@ -306,6 +388,36 @@ export function leadToastWords(lead: LeadMinutes): string { return lead === 0 ? '開始時に通知します' : `開始の ${lead} 分前に通知します` } +/** The line under a single notice's title in the list of reservations. */ +export function watchLine( + watch: Pick< + WatchedProgramme, + 'channelName' | 'leadMinutes' | 'destinationNames' + >, +): string { + return [ + watch.channelName, + leadLabel(watch.leadMinutes), + watch.destinationNames.join('・'), + ] + .filter(Boolean) + .join(' · ') +} + +/** Whether a programme is still ahead: by the clock on the day shown, by the date on any other. */ +export function yetToStart( + program: { startMin: number }, + nowMin: number | undefined, + day: string, + today: string | undefined, +): boolean { + if (nowMin !== undefined) { + return program.startMin > nowMin + } + + return today !== undefined && day > today +} + export function isLead(value: number): value is LeadMinutes { return (LEADS as readonly number[]).includes(value) } diff --git a/repository/notifications.ts b/repository/notifications.ts index f94e4111..1d1ba28b 100644 --- a/repository/notifications.ts +++ b/repository/notifications.ts @@ -14,14 +14,19 @@ import type { NotificationSettings, NotificationWrite, NotificationsScreen, + ProgrammeWatch, RuleSetDraft, TestSending, + WatchDraft, + WatchOffer, + WatchWrite, + WatchedProgramme, WebhookDraft, } from '@/lib/notifications' import { couldNot } from '@/lib/try-again' import { carinaClient } from '@/repository/client/carina' import type { components } from '@/repository/client/schema' -import { toInt } from '@/repository/programmes' +import { fetchProgramme, toInt } from '@/repository/programmes' import { whatItSaid } from '@/repository/said' type DestinationResponder = @@ -29,6 +34,7 @@ type DestinationResponder = type RuleResponder = components['schemas']['NotificationRuleResponder'] type DeliveryResponder = components['schemas']['NotificationDeliveryResponder'] type SettingsResponder = components['schemas']['NotificationSettingsResponder'] +type WatchResponder = components['schemas']['NotificationWatchResponder'] export interface NotificationAsking { did: string @@ -77,6 +83,29 @@ export const WHEN_SETTLING_THE_LEAD: NotificationAsking = { const UNREADABLE = '通知の設定を読めませんでした' +const NOT_WATCHED = '通知を設定できませんでした' + +const NOT_IN_THE_GUIDE = + 'この番組は番組表にもうないため、通知を設定できませんでした。番組表を読み直してください。' + +const WATCH_REFUSED: Partial> = { + 400: '選んだ送り先が使えなくなったため、通知を設定できませんでした。画面を読み直してください。', + 404: NOT_IN_THE_GUIDE, +} + +const ALREADY_STARTED = + 'この番組はもう始まっているため、通知を設定できませんでした。' + +const ALREADY_WATCHED = + 'この番組の通知はすでに設定してあるか、もう送ったため、設定できませんでした。' + +const UNWATCH_REFUSED: Partial> = { + 404: 'この通知は残っていないため、取り消せませんでした。', + 409: 'この通知はもう済んでいるため、取り消せませんでした。', +} + +const NOT_UNWATCHED = '通知を取り消せませんでした' + const REFUSAL_SAYINGS: [RegExp, string][] = [ [/not one a notice can be sent to/i, 'この URL は受け付けられません。'], [ @@ -276,6 +305,113 @@ export async function settleLead( return toWrite(response, whatItSaid(error), WHEN_SETTLING_THE_LEAD) } +/** The single notices still waiting, by the programme each is for. */ +export async function listWatches(): Promise> { + const waiting = await fetchWaitingWatches() + + return new Map(waiting.map((one) => [one.programmeId, toWatch(one)])) +} + +/** What a new single notice starts from; nothing while no destination is on. */ +export async function getWatchOffer(): Promise { + const [destinations, settings] = await Promise.all([ + fetchDestinations(), + fetchSettings(), + ]) + const on = destinations.filter(({ enabled }) => enabled) + + return on.length > 0 + ? { + leadMinutes: settings.notifyLeadMinutes, + destinations: on.map(({ id, name }) => ({ id, name })), + } + : undefined +} + +export async function listWatchedProgrammes(): Promise { + const [waiting, destinations] = await Promise.all([ + fetchWaitingWatches(), + fetchDestinations(), + ]) + const names = new Map(destinations.map(({ id, name }) => [id, name])) + + return waiting.map((one) => ({ + ...toWatch(one), + title: one.programmeName, + channelName: one.stationName ?? '', + startAt: one.startsAt, + endAt: one.endsAt, + destinationNames: one.destinations + .map((id) => names.get(id)) + .filter((name) => name !== undefined), + })) +} + +export async function askForWatch( + programmeId: string, + draft: WatchDraft, + now: number = Date.now(), +): Promise { + const programme = await fetchProgramme(programmeId) + + if (!programme) { + return { state: 'rejected', message: NOT_IN_THE_GUIDE } + } + + const { data, response } = await carinaClient().POST( + '/api/notifications/watches', + { + body: { + programme: programmeId, + programmeStartsAt: programme.startsAt, + leadMinutes: draft.leadMinutes, + destinations: draft.destinations, + }, + }, + ) + + if (response.status === 401) { + return { state: 'unauthenticated' } + } + + if (response.status === 409) { + return { + state: 'rejected', + message: + Date.parse(programme.startsAt) <= now + ? ALREADY_STARTED + : ALREADY_WATCHED, + } + } + + const made = data?.data + + return response.ok && made + ? { state: 'ok', watch: toWatch(made) } + : { + state: 'rejected', + message: WATCH_REFUSED[response.status] ?? couldNot(NOT_WATCHED), + } +} + +export async function cancelWatch(id: string): Promise { + const { response } = await carinaClient().DELETE( + '/api/notifications/watches/{id}', + { params: { path: { id } } }, + ) + + if (response.status === 401) { + return { state: 'unauthenticated' } + } + + return response.ok + ? { state: 'ok' } + : { + state: 'rejected', + message: UNWATCH_REFUSED[response.status] ?? couldNot(NOT_UNWATCHED), + } +} + function toRuleBody(draft: RuleSetDraft) { return { name: draft.name, @@ -316,6 +452,16 @@ async function fetchDestinations(): Promise { return data.data.items.map(toDestination) } +async function fetchWaitingWatches(): Promise { + const { data, error } = await carinaClient().GET('/api/notifications/watches') + + if (error || !data?.data) { + throw new Error(whatItSaid(error, data) || UNREADABLE) + } + + return data.data.items.filter(({ state }) => state === 'waiting') +} + async function fetchRuleSets(): Promise { const { data, error } = await carinaClient().GET('/api/notifications/rules') @@ -391,11 +537,22 @@ function toDelivery( } function toSettings(one: SettingsResponder): NotificationSettings { - const lead = toInt(one.notifyLeadMinutes) + return { + notifyLeadMinutes: leadOf(one.notifyLeadMinutes), + publicOriginKnown: one.publicOriginKnown, + } +} + +function toWatch(one: WatchResponder): ProgrammeWatch { + return { id: one.id, leadMinutes: leadOf(one.leadMinutes) } +} + +function leadOf(minutes: number | string): LeadMinutes { + const lead = toInt(minutes) if (!isLead(lead)) { throw new Error(UNREADABLE) } - return { notifyLeadMinutes: lead, publicOriginKnown: one.publicOriginKnown } + return lead } diff --git a/repository/programs.fixtures.ts b/repository/programs.fixtures.ts index 67a79e5b..d08e48b7 100644 --- a/repository/programs.fixtures.ts +++ b/repository/programs.fixtures.ts @@ -697,6 +697,7 @@ export const PROGRAM_DETAIL_FIXTURES: Record< durationLabel: '2 時間 25 分', }, day: PROGRAM_DAY, + today: PROGRAM_DAY.date, channel: CHANNEL_FIXTURES[0], }, relayed: { @@ -742,6 +743,7 @@ export const PROGRAM_DETAIL_FIXTURES: Record< durationLabel: '2 時間', }, day: PROGRAM_DAY, + today: PROGRAM_DAY.date, channel: CHANNEL_FIXTURES[0], }, simulcast: { @@ -804,6 +806,7 @@ export const PROGRAM_DETAIL_FIXTURES: Record< durationLabel: '30 分', }, day: PROGRAM_DAY, + today: PROGRAM_DAY.date, channel: CHANNEL_FIXTURES[0], }, undecided: { @@ -828,6 +831,7 @@ export const PROGRAM_DETAIL_FIXTURES: Record< related: [], }, day: PROGRAM_DAY, + today: PROGRAM_DAY.date, channel: CHANNEL_FIXTURES[5], }, multiline: { @@ -858,6 +862,7 @@ export const PROGRAM_DETAIL_FIXTURES: Record< durationLabel: '1 時間 15 分', }, day: PROGRAM_DAY, + today: PROGRAM_DAY.date, channel: CHANNEL_FIXTURES[0], }, minimal: { @@ -879,6 +884,7 @@ export const PROGRAM_DETAIL_FIXTURES: Record< durationLabel: '1 時間', }, day: PROGRAM_DAY, + today: PROGRAM_DAY.date, channel: CHANNEL_FIXTURES[7], }, } diff --git a/repository/programs.ts b/repository/programs.ts index 95b13c7d..917ec155 100644 --- a/repository/programs.ts +++ b/repository/programs.ts @@ -1,6 +1,7 @@ import { cache } from 'react' import type { GuideRelationKind, GuideService } from '@/lib/guide' +import type { ProgrammeWatch } from '@/lib/notifications' import { DAY_STARTS_AT_HOUR, JST_OFFSET_MS, @@ -69,6 +70,7 @@ export interface Program { video?: VideoMode booked?: boolean booking?: ProgramBooking + watch?: ProgrammeWatch endUndecided?: boolean items?: ProgramItem[] related?: RelatedProgram[] @@ -114,10 +116,14 @@ export interface RelatedProgram { export interface ProgramDetail { program: Program day: GuideDay + /** The broadcast day the clock is in, as `day.date` is written. */ + today: string channel?: Channel nowMin?: number } +type Marks = ReadonlyMap | Promise> + const PAST_DAYS = 7 const FUTURE_DAYS = 7 @@ -181,12 +187,11 @@ async function programsOver( kind: ChannelKind, windowStart: Date, minutes: MinuteRange, - bookings: - | ReadonlyMap - | Promise>, + bookings: Marks, + watches: Marks, ): Promise<{ channels: Channel[]; programs: Program[] }> { const at = (min: number) => new Date(windowStart.getTime() + min * 60_000) - const [services, guide, marked] = await Promise.all([ + const [services, guide, marked, told] = await Promise.all([ fetchServiceChannels(), fetchGuide({ type: SYSTEM_OF_KIND[kind], @@ -194,6 +199,7 @@ async function programsOver( to: at(minutes.to), }), bookings, + watches, ]) const shadows = new Set( @@ -218,16 +224,17 @@ async function programsOver( (program): program is Program => program !== null && fallsWithin(minutes, program), ) - .map((program) => booked(program, marked.get(program.id))), + .map((program) => + watched(booked(program, marked.get(program.id)), told.get(program.id)), + ), } } export async function getGuide( rawKind: string | undefined, rawDate: string | undefined, - bookings: - | ReadonlyMap - | Promise> = new Map(), + bookings: Marks = new Map(), + watches: Marks = new Map(), ): Promise { const { kind, days, day, windowStart, now, nowMin } = guideDayOf( rawKind, @@ -238,6 +245,7 @@ export async function getGuide( windowStart, { from: 0, to: WINDOW_HOURS * 60 }, bookings, + watches, ) return { @@ -261,9 +269,8 @@ function cellKeyOf(program: Program): string { export async function getGuideInTwo( rawKind: string | undefined, rawDate: string | undefined, - bookings: - | ReadonlyMap - | Promise> = new Map(), + bookings: Marks = new Map(), + watches: Marks = new Map(), ): Promise<{ guide: GuideResult; rest: Promise }> { const { kind, days, day, windowStart, now, nowMin } = guideDayOf( rawKind, @@ -275,12 +282,14 @@ export async function getGuideInTwo( windowStart, minutesBeforeMeasuringOf(nowMin, windowMin), bookings, + watches, ) const whole = programsOver( kind, windowStart, { from: 0, to: windowMin }, bookings, + watches, ) const rest = Promise.all([opening, whole]).then(([first, all]) => { const drawn = new Set(first.programs.map(cellKeyOf)) @@ -352,11 +361,14 @@ export async function extrasOf( export async function getProgram( id: string, now: Date = new Date(), - bookings: - | ReadonlyMap - | Promise> = new Map(), + bookings: Marks = new Map(), + watches: Marks = new Map(), ): Promise { - const [programme, marked] = await Promise.all([fetchProgramme(id), bookings]) + const [programme, marked, told] = await Promise.all([ + fetchProgramme(id), + bookings, + watches, + ]) if (!programme || programme.isShadow) { return undefined @@ -379,8 +391,12 @@ export async function getProgram( } return { - program: booked(program, marked.get(program.id)), + program: watched( + booked(program, marked.get(program.id)), + told.get(program.id), + ), day, + today: broadcastDateOf(now), channel: serviceOf(services, programme.networkId, programme.serviceId), nowMin: nowMinOf(now, windowStart), } @@ -653,6 +669,10 @@ function booked( return booking ? { ...program, booked: true, booking } : program } +function watched(program: Program, watch: ProgrammeWatch | undefined): Program { + return watch ? { ...program, watch } : program +} + function guideDays(): GuideDay[] { const today = dayOf(new Date()) const days: GuideDay[] = [] diff --git a/stories/components/ProgramPanel.stories.tsx b/stories/components/ProgramPanel.stories.tsx index bfb90552..0fbae9fb 100644 --- a/stories/components/ProgramPanel.stories.tsx +++ b/stories/components/ProgramPanel.stories.tsx @@ -337,6 +337,7 @@ export const 別ページと同じ中身: Story = { program: args.program, channel: args.channel, day: PROGRAM_DAY, + today: PROGRAM_DAY.date, }} onReserve={args.onReserve} onCancel={args.onCancel} diff --git a/stories/fixtures/notifications.ts b/stories/fixtures/notifications.ts index ce44b0aa..83e46fc3 100644 --- a/stories/fixtures/notifications.ts +++ b/stories/fixtures/notifications.ts @@ -3,8 +3,8 @@ import type { NotificationDestination, NotificationRuleSet, NotificationsScreen, + WatchedProgramme, } from '@/lib/notifications' -import type { WatchedProgramme } from '@/components/notifications/notify-only-row' export const NOTIFICATIONS_NOW = Date.parse('2026-11-09T12:30:00Z') @@ -159,7 +159,7 @@ export const WATCHED_DOCUMENTARY: WatchedProgramme = { startAt: '2026-11-09T10:30:00Z', endAt: '2026-11-09T11:15:00Z', leadMinutes: 3, - destinationIds: [HOME_SLACK.id, IPAD_SAFARI.id], + destinationNames: [HOME_SLACK.name, IPAD_SAFARI.name], } export const WATCHED_FOOTBALL: WatchedProgramme = { @@ -169,5 +169,5 @@ export const WATCHED_FOOTBALL: WatchedProgramme = { startAt: '2026-11-09T13:00:00Z', endAt: '2026-11-09T14:30:00Z', leadMinutes: 5, - destinationIds: [HOME_SLACK.id], + destinationNames: [HOME_SLACK.name], } diff --git a/tests/app/(app)/guide/actions.test.ts b/tests/app/(app)/guide/actions.test.ts new file mode 100644 index 00000000..cbbd918a --- /dev/null +++ b/tests/app/(app)/guide/actions.test.ts @@ -0,0 +1,99 @@ +import assert from 'node:assert/strict' +import { registerHooks } from 'node:module' +import { beforeEach, mock, test } from 'node:test' + +import type { WatchDraft } from '@/lib/notifications' + +const CACHE = 'next/cache' + +registerHooks({ + resolve(specifier, context, next) { + return next(specifier === CACHE ? `${CACHE}.js` : specifier, context) + }, +}) + +const DOCUMENTARY = '32736-1024-501' +const WATCH = '0c000000-0000-4000-8000-000000000001' +const HOME = '0a000000-0000-4000-8000-000000000001' + +const store: { status: number } = { status: 200 } + +const revalidated: string[] = [] + +const answered = () => ({ status: store.status, ok: store.status < 400 }) + +const client = () => ({ + GET: async () => ({ + data: { + data: { + id: DOCUMENTARY, + networkId: 32736, + serviceId: 1024, + eventId: 501, + startsAt: '2030-01-02T12:00:00Z', + endsAt: '2030-01-02T12:50:00Z', + isShadow: false, + sounds: 1, + }, + }, + response: { status: 200, ok: true }, + }), + POST: async () => ({ + data: + store.status < 400 ? { data: { id: WATCH, leadMinutes: 5 } } : undefined, + response: answered(), + }), + DELETE: async () => ({ response: answered() }), +}) + +mock.module('@/repository/client/carina', { + namedExports: { carinaClient: client, revalidatingCarinaClient: client }, +}) + +mock.module(CACHE, { + namedExports: { + revalidatePath: (path: string) => { + revalidated.push(path) + }, + }, +}) + +const { unwatchProgramme, watchProgramme } = + await import('@/app/(app)/guide/actions') + +const DRAFT: WatchDraft = { leadMinutes: 5, destinations: [HOME] } + +beforeEach(() => { + revalidated.length = 0 + store.status = 200 +}) + +test('a single notice that was set reads the guide and the reservations again', async () => { + store.status = 201 + + assert.deepEqual(await watchProgramme(DOCUMENTARY, DRAFT), { + state: 'ok', + watch: { id: WATCH, leadMinutes: 5 }, + }) + assert.deepEqual(revalidated, ['/guide', '/reservations']) +}) + +test('a single notice that was refused reads them again too, since what refused it may show there', async () => { + store.status = 409 + + const result = await watchProgramme(DOCUMENTARY, DRAFT) + + assert.equal(result.state, 'rejected') + assert.deepEqual(revalidated, ['/guide', '/reservations']) +}) + +test('taking a single notice back reads the guide and the reservations again', async () => { + assert.deepEqual(await unwatchProgramme(WATCH), { state: 'ok' }) + assert.deepEqual(revalidated, ['/guide', '/reservations']) +}) + +test('a session that ended is said as such', async () => { + store.status = 401 + + assert.deepEqual(await unwatchProgramme(WATCH), { state: 'unauthenticated' }) +}) diff --git a/tests/lib/notifications.test.ts b/tests/lib/notifications.test.ts index a558a129..3a51a352 100644 --- a/tests/lib/notifications.test.ts +++ b/tests/lib/notifications.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict' import { test } from 'node:test' import { + amongWatches, deliveriesShown, deliverySaid, destinationsByDefault, @@ -23,8 +24,10 @@ import { ruleSetsGoingWith, testSaid, toggled, + watchLine, webhookKindOf, withWhy, + yetToStart, type DeliveryFailure, type NotificationDelivery, type NotificationEvent, @@ -354,3 +357,92 @@ test('a choice toggles in and out', () => { assert.deepEqual(toggled(['a', 'b'], 'a'), ['b']) assert.deepEqual(toggled(['b'], 'a'), ['b', 'a']) }) + +test('a single notice says its station, how early and where it goes', () => { + assert.equal( + watchLine({ + channelName: '見本テレビ', + leadMinutes: 3, + destinationNames: ['見本の Slack', '見本の Discord'], + }), + '見本テレビ · 3 分前 · 見本の Slack・見本の Discord', + ) + assert.equal( + watchLine({ channelName: '', leadMinutes: 0, destinationNames: [] }), + '開始時', + ) +}) + +test('a programme on the day shown has yet to start while the clock is before it', () => { + assert.ok(yetToStart({ startMin: 601 }, 600, '2030-01-02', '2030-01-02')) + assert.ok(!yetToStart({ startMin: 600 }, 600, '2030-01-02', '2030-01-02')) + assert.ok(!yetToStart({ startMin: 599 }, 600, '2030-01-02', '2030-01-02')) +}) + +test('a programme on another day has yet to start only when that day is after today', () => { + assert.ok(yetToStart({ startMin: 0 }, undefined, '2030-01-03', '2030-01-02')) + assert.ok(!yetToStart({ startMin: 0 }, undefined, '2030-01-01', '2030-01-02')) + assert.ok(!yetToStart({ startMin: 0 }, undefined, '2030-01-02', '2030-01-02')) + assert.ok(!yetToStart({ startMin: 0 }, undefined, '2030-01-03', undefined)) +}) + +function watchAt(id: string, startAt: string) { + return { + id, + leadMinutes: 3 as const, + title: id, + channelName: 'みなと総合1', + startAt, + endAt: startAt, + destinationNames: [], + } +} + +test('a notice stands before the first entry that starts after it', () => { + const own = [ + { id: 'a', startAt: '2030-01-02T10:00:00Z' }, + { id: 'b', startAt: '2030-01-02T12:00:00Z' }, + ] + const among = amongWatches(own, (one) => one.startAt, [ + watchAt('w2', '2030-01-02T13:00:00Z'), + watchAt('w1', '2030-01-02T11:00:00Z'), + ]) + + assert.deepEqual( + among.map((one) => one.watch?.id ?? one.own?.id), + ['a', 'w1', 'b', 'w2'], + ) +}) + +test('a notice starting with an entry stands after it, and an entry of no start keeps its place', () => { + const own: { id: string; startAt?: string }[] = [ + { id: 'a', startAt: '2030-01-02T10:00:00Z' }, + { id: 'none' }, + { id: 'b', startAt: '2030-01-02T12:00:00Z' }, + ] + const among = amongWatches(own, (one) => one.startAt, [ + watchAt('w', '2030-01-02T10:00:00Z'), + ]) + + assert.deepEqual( + among.map((one) => one.watch?.id ?? one.own?.id), + ['a', 'none', 'w', 'b'], + ) +}) + +test('notices alone make a list of their own', () => { + const among = amongWatches( + [] as { startAt: string }[], + (one) => one.startAt, + [watchAt('w', '2030-01-02T10:00:00Z')], + ) + + assert.equal(among.length, 1) + assert.equal(among[0].watch?.id, 'w') +}) + +test('what a single notice tells has words of its own in the record of what was sent', () => { + assert.equal(eventLabelOf('programmeStarting'), '放送開始') + assert.equal(eventLabelOf('watchedProgrammeMoved'), '放送時刻の変更') + assert.equal(eventLabelOf('watchedProgrammeGone'), '放送の取り消し') +}) diff --git a/tests/repository/notifications.test.ts b/tests/repository/notifications.test.ts index edc2fe84..65de2354 100644 --- a/tests/repository/notifications.test.ts +++ b/tests/repository/notifications.test.ts @@ -73,6 +73,55 @@ function delivery(id: string, occurredAt: string, more: object = {}) { } } +const DOCUMENTARY = '32736-1024-501' + +const PROGRAMME = { + id: DOCUMENTARY, + networkId: 32736, + serviceId: 1024, + eventId: 501, + startsAt: '2030-01-02T12:00:00Z', + endsAt: '2030-01-02T12:50:00Z', + name: '見本の番組 1', + summary: '', + isShadow: false, + hasSubtitles: false, + audio: 'stereo', + sounds: 1, + video: 'hd', + aspect: 'wide', + isArchived: false, +} + +const BEFORE_IT_STARTS = Date.parse('2030-01-02T11:00:00Z') + +const AFTER_IT_STARTED = Date.parse('2030-01-02T12:00:00Z') + +function watch(id: string, more: object = {}) { + return { + id, + programmeId: DOCUMENTARY, + networkId: 32736, + serviceId: 1024, + eventId: 501, + startsAt: '2030-01-02T12:00:00Z', + endsAt: '2030-01-02T12:50:00Z', + programmeName: '見本の番組 1', + stationName: '見本テレビ', + leadMinutes: 3, + destinations: [HOME], + state: 'waiting', + notifiedAt: null, + createdAt: '2030-01-01T00:00:00Z', + changedAt: '2030-01-01T00:00:00Z', + ...more, + } +} + +const WATCH_ONE = '0c000000-0000-4000-8000-000000000001' + +const WATCH_TWO = '0c000000-0000-4000-8000-000000000002' + const sent: Sent[] = [] const store: { @@ -81,6 +130,9 @@ const store: { settings: unknown deliveries: Record trial: unknown + watches: unknown[] + programme: unknown + made: unknown readStatus: number readMessage: string writeStatus: number @@ -91,6 +143,9 @@ const store: { settings: null, deliveries: {}, trial: null, + watches: [], + programme: null, + made: null, readStatus: 200, readMessage: '', writeStatus: 200, @@ -127,8 +182,18 @@ function wrote(method: string) { body: options?.body, }) - return written(path.endsWith('/test') ? store.trial : null) + return written(answerTo(method, path)) + } +} + +function answerTo(method: string, path: string): unknown { + if (path.endsWith('/test')) { + return store.trial } + + return method === 'POST' && path === '/api/notifications/watches' + ? store.made + : null } const client = () => ({ @@ -152,6 +217,12 @@ const client = () => ({ perPage: query?.perPage, items: store.deliveries[String(query?.destinationId)] ?? [], }) + case '/api/notifications/watches': + return envelope({ items: store.watches }) + case '/api/programs/{id}': + return store.programme + ? envelope(store.programme) + : { data: undefined, response: answered(404) } default: throw new Error(`unexpected GET ${path}`) } @@ -172,8 +243,13 @@ const { WHEN_CHANGING_A_DESTINATION, WHEN_CHANGING_A_RULE_SET, WHEN_TRYING_A_DESTINATION, + askForWatch, + cancelWatch, defineRuleSet, getNotificationsScreen, + getWatchOffer, + listWatchedProgrammes, + listWatches, registerDestination, removeDestination, removeRuleSet, @@ -193,6 +269,9 @@ beforeEach(() => { store.settings = { notifyLeadMinutes: 3, publicOriginKnown: true } store.deliveries = {} store.trial = { delivered: true, failure: null } + store.watches = [] + store.programme = PROGRAMME + store.made = watch(WATCH_ONE) store.readStatus = 200 store.readMessage = '' store.writeStatus = 200 @@ -630,3 +709,194 @@ test('what Carina says about a refusal is put in the words of the screen', () => '送り先を追加できませんでした。時間をおいてからもう一度お試しください。', ) }) + +test('the programmes whose start is to be told are the single notices still waiting', async () => { + store.watches = [ + watch(WATCH_ONE, { leadMinutes: '5' }), + watch(WATCH_TWO, { programmeId: '32736-1024-502', state: 'notified' }), + watch(GAMES, { programmeId: '32736-1024-503', state: 'skipped' }), + watch(HOME, { programmeId: '32736-1024-504', state: 'cancelled' }), + ] + + assert.deepEqual( + [...(await listWatches())], + [[DOCUMENTARY, { id: WATCH_ONE, leadMinutes: 5 }]], + ) +}) + +test('single notices that cannot be read are an error, not an empty answer', async () => { + store.readStatus = 500 + store.readMessage = 'boom' + + await assert.rejects(listWatches(), /boom/) + await assert.rejects(listWatchedProgrammes(), /boom/) + await assert.rejects(getWatchOffer(), /boom/) +}) + +test('a new single notice starts from the lead the settings hold and the destinations that are on', async () => { + assert.deepEqual(await getWatchOffer(), { + leadMinutes: 3, + destinations: [{ id: HOME, name: '見本の送り先 1' }], + }) +}) + +test('nothing is offered while no destination is on', async () => { + store.destinations = [DESTINATION_GAMES] + + assert.equal(await getWatchOffer(), undefined) +}) + +test('the waiting notices are listed with the names of the destinations that are still there', async () => { + store.watches = [ + watch(WATCH_ONE, { destinations: [HOME, GAMES, FAILURES] }), + watch(WATCH_TWO, { + programmeId: '32736-1024-502', + stationName: null, + state: 'notified', + }), + ] + + assert.deepEqual(await listWatchedProgrammes(), [ + { + id: WATCH_ONE, + leadMinutes: 3, + title: '見本の番組 1', + channelName: '見本テレビ', + startAt: '2030-01-02T12:00:00Z', + endAt: '2030-01-02T12:50:00Z', + destinationNames: ['見本の送り先 1', '見本の送り先 2'], + }, + ]) +}) + +test('a single notice is asked for with the programme, its start, the lead and the destinations', async () => { + store.writeStatus = 201 + + assert.deepEqual( + await askForWatch( + DOCUMENTARY, + { leadMinutes: 3, destinations: [HOME] }, + BEFORE_IT_STARTS, + ), + { state: 'ok', watch: { id: WATCH_ONE, leadMinutes: 3 } }, + ) + assert.deepEqual(sent.at(-1), { + method: 'POST', + path: '/api/notifications/watches', + at: undefined, + body: { + programme: DOCUMENTARY, + programmeStartsAt: '2030-01-02T12:00:00Z', + leadMinutes: 3, + destinations: [HOME], + }, + }) +}) + +test('a single notice for a programme the guide no longer has is refused before asking', async () => { + store.programme = null + + assert.deepEqual( + await askForWatch(DOCUMENTARY, { leadMinutes: 3, destinations: [HOME] }), + { + state: 'rejected', + message: + 'この番組は番組表にもうないため、通知を設定できませんでした。番組表を読み直してください。', + }, + ) + assert.ok(!sent.some(({ method }) => method === 'POST')) +}) + +test('what refuses a single notice is said by its status and the time, never in the words Carina used', async () => { + const asked = (now: number) => + askForWatch(DOCUMENTARY, { leadMinutes: 3, destinations: [HOME] }, now) + + store.writeMessage = 'The programme has already started.' + + store.writeStatus = 404 + assert.deepEqual(await asked(BEFORE_IT_STARTS), { + state: 'rejected', + message: + 'この番組は番組表にもうないため、通知を設定できませんでした。番組表を読み直してください。', + }) + + store.writeStatus = 400 + assert.deepEqual(await asked(BEFORE_IT_STARTS), { + state: 'rejected', + message: + '選んだ送り先が使えなくなったため、通知を設定できませんでした。画面を読み直してください。', + }) + + store.writeStatus = 409 + assert.deepEqual(await asked(AFTER_IT_STARTED), { + state: 'rejected', + message: 'この番組はもう始まっているため、通知を設定できませんでした。', + }) + assert.deepEqual(await asked(BEFORE_IT_STARTS), { + state: 'rejected', + message: + 'この番組の通知はすでに設定してあるか、もう送ったため、設定できませんでした。', + }) + + store.writeStatus = 500 + assert.deepEqual(await asked(BEFORE_IT_STARTS), { + state: 'rejected', + message: + '通知を設定できませんでした。時間をおいてからもう一度お試しください。', + }) + + store.writeStatus = 401 + assert.deepEqual(await asked(BEFORE_IT_STARTS), { state: 'unauthenticated' }) +}) + +test('a single notice Carina took without saying which is not counted as set', async () => { + store.writeStatus = 201 + store.made = null + + assert.deepEqual( + await askForWatch( + DOCUMENTARY, + { leadMinutes: 3, destinations: [HOME] }, + BEFORE_IT_STARTS, + ), + { + state: 'rejected', + message: + '通知を設定できませんでした。時間をおいてからもう一度お試しください。', + }, + ) +}) + +test('a single notice is taken back by its id', async () => { + assert.deepEqual(await cancelWatch(WATCH_ONE), { state: 'ok' }) + assert.deepEqual(sent.at(-1), { + method: 'DELETE', + path: '/api/notifications/watches/{id}', + at: { id: WATCH_ONE }, + body: undefined, + }) +}) + +test('what refuses taking a single notice back is said by its status', async () => { + store.writeStatus = 404 + assert.deepEqual(await cancelWatch(WATCH_ONE), { + state: 'rejected', + message: 'この通知は残っていないため、取り消せませんでした。', + }) + + store.writeStatus = 409 + assert.deepEqual(await cancelWatch(WATCH_ONE), { + state: 'rejected', + message: 'この通知はもう済んでいるため、取り消せませんでした。', + }) + + store.writeStatus = 503 + assert.deepEqual(await cancelWatch(WATCH_ONE), { + state: 'rejected', + message: + '通知を取り消せませんでした。時間をおいてからもう一度お試しください。', + }) + + store.writeStatus = 401 + assert.deepEqual(await cancelWatch(WATCH_ONE), { state: 'unauthenticated' }) +}) diff --git a/tests/repository/programs.test.ts b/tests/repository/programs.test.ts index 306ffb65..56af7abf 100644 --- a/tests/repository/programs.test.ts +++ b/tests/repository/programs.test.ts @@ -1,6 +1,7 @@ import assert from 'node:assert/strict' import { mock, test } from 'node:test' +import type { ProgrammeWatch } from '@/lib/notifications' import type { ProgramBooking } from '@/repository/programs' const JST_OFFSET_MS = 9 * 60 * 60 * 1000 @@ -842,3 +843,59 @@ test('a programme hands over no field it has nothing to say in', async () => { assert.equal(unsaid in program, false, unsaid) } }) + +test('a programme whose start is to be told carries its single notice, in the guide and at its own address', async () => { + standing() + + const watches = new Map([ + [idOf(CARRIED), { id: 'watch-1', leadMinutes: 5 }], + ]) + const guide = await getGuide( + 'terrestrial', + broadcastDay(STARTS), + new Map(), + Promise.resolve(watches), + ) + const detail = await getProgram( + idOf(CARRIED), + new Date(), + new Map(), + Promise.resolve(watches), + ) + const { guide: opening, rest } = await getGuideInTwo( + 'terrestrial', + broadcastDay(STARTS), + new Map(), + watches, + ) + const inTwo = [...opening.programs, ...(await rest)] + + assert.deepEqual( + guide.programs + .filter((program) => program.watch) + .map((program) => [program.id, program.watch]), + [[idOf(CARRIED), { id: 'watch-1', leadMinutes: 5 }]], + ) + assert.deepEqual( + inTwo.find((program) => program.id === idOf(CARRIED))?.watch, + { id: 'watch-1', leadMinutes: 5 }, + ) + assert.deepEqual(detail?.program.watch, { id: 'watch-1', leadMinutes: 5 }) + assert.equal((await getProgram(idOf(CARRIED)))?.program.watch, undefined) +}) + +test('a programme opened at its own address says which broadcast day today is', async () => { + standing() + + const detail = await getProgram( + idOf(CARRIED), + new Date('2030-03-04T18:59:00Z'), + ) + const afterTheDayTurns = await getProgram( + idOf(CARRIED), + new Date('2030-03-04T19:00:00Z'), + ) + + assert.equal(detail?.today, '2030-03-04') + assert.equal(afterTheDayTurns?.today, '2030-03-05') +}) diff --git a/tests/storybook/every-test-runs.test.ts b/tests/storybook/every-test-runs.test.ts index 29c0b790..d1fe4589 100644 --- a/tests/storybook/every-test-runs.test.ts +++ b/tests/storybook/every-test-runs.test.ts @@ -7,6 +7,7 @@ import { test } from 'node:test' const TOLD_TO_RUN = ['tests/**/*.test.ts'] const THE_SUITE = [ + 'tests/app/(app)/guide/actions.test.ts', 'tests/app/(app)/settings/notifications/actions.test.ts', 'tests/app/(app)/settings/segments/actions.test.ts', 'tests/app/a-fold-comes-with-the-page.test.ts', From f91e6a1588683d6378bf1b500cafc22d6939cac0 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 06:39:44 +0900 Subject: [PATCH 15/24] =?UTF-8?q?=E7=95=AA=E7=B5=84=E8=A9=B3=E7=B4=B0?= =?UTF-8?q?=E3=81=AE=E9=8C=B2=E7=94=BB=E4=BA=88=E7=B4=84=E3=81=AE=E9=9A=A3?= =?UTF-8?q?=E3=81=AB=E6=94=BE=E9=80=81=E9=96=8B=E5=A7=8B=E3=81=AE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E3=82=92=E9=A0=BC=E3=82=80=E3=83=9C=E3=82=BF=E3=83=B3?= =?UTF-8?q?=E3=82=92=E7=BD=AE=E3=81=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- app/(app)/guide/page.tsx | 12 +- .../guide/programs/[programKey]/page.tsx | 18 +- components/guide/guide-page.tsx | 10 + components/guide/program-detail-page.tsx | 5 + components/guide/program-detail.tsx | 41 +++- components/guide/program-panel.tsx | 7 + components/guide/reservation-area.tsx | 8 +- components/notifications/programme-notice.tsx | 227 ++++++++++++------ stories/screens/ProgramDetail.stories.tsx | 122 ++++++++++ 9 files changed, 358 insertions(+), 92 deletions(-) diff --git a/app/(app)/guide/page.tsx b/app/(app)/guide/page.tsx index 74f07a17..cc45ed2c 100644 --- a/app/(app)/guide/page.tsx +++ b/app/(app)/guide/page.tsx @@ -3,6 +3,7 @@ import { cookies } from 'next/headers' import { forTheGrid, getGuideInTwo } from '@/repository/programs' import { listBookings } from '@/repository/reservations' +import { getWatchOffer, listWatches } from '@/repository/notifications' import { coverageDaysOf, epgHealthOf, @@ -29,6 +30,8 @@ import { reserveProgramme, readProgramExtras, reviseProgrammeReservation, + unwatchProgramme, + watchProgramme, } from './actions' export const metadata: Metadata = { title: '番組表' } @@ -40,13 +43,15 @@ export default async function Page({ }) { const params = await searchParams const jar = await cookies() - const [{ guide, rest }, collection] = await Promise.all([ + const [{ guide, rest }, collection, offer] = await Promise.all([ getGuideInTwo( typeof params.kind === 'string' ? params.kind : undefined, typeof params.date === 'string' ? params.date : undefined, listBookings(), + listWatches().catch(() => new Map()), ), getCollectionStatus(), + getWatchOffer().catch(() => undefined), ]) const opening = guide.programs.length > 0 ? guide.programs : await rest const later = @@ -75,6 +80,11 @@ export default async function Page({ onRestore={restoreProgrammeReservation} onRevise={reviseProgrammeReservation} onReadExtras={readProgramExtras} + noticing={{ + offer, + onWatch: watchProgramme, + onUnwatch: unwatchProgramme, + }} subChannelsFolded={flagOf( jar.get(GUIDE_SUB_CHANNELS_FOLDED)?.value, FOLD_SPELLING, diff --git a/app/(app)/guide/programs/[programKey]/page.tsx b/app/(app)/guide/programs/[programKey]/page.tsx index 4b1eb41f..693466c5 100644 --- a/app/(app)/guide/programs/[programKey]/page.tsx +++ b/app/(app)/guide/programs/[programKey]/page.tsx @@ -4,12 +4,15 @@ import { notFound, redirect } from 'next/navigation' import { PROGRAMS_EVENT, RESERVATIONS_EVENT } from '@/repository/events' import { getProgram, primaryProgramKeyOf } from '@/repository/programs' import { listBookings } from '@/repository/reservations' +import { getWatchOffer, listWatches } from '@/repository/notifications' import { RefreshOnSignal } from '@/components/vela/app-signals' import { ProgramDetailView } from '@/components/guide/program-detail-page' import { dropProgrammeReservation, reserveProgramme, reviseProgrammeReservation, + unwatchProgramme, + watchProgramme, } from '@/app/(app)/guide/actions' export async function generateMetadata({ @@ -28,7 +31,15 @@ export default async function Page({ params: Promise<{ programKey: string }> }) { const { programKey } = await params - const detail = await getProgram(programKey, new Date(), listBookings()) + const [detail, offer] = await Promise.all([ + getProgram( + programKey, + new Date(), + listBookings(), + listWatches().catch(() => new Map()), + ), + getWatchOffer().catch(() => undefined), + ]) if (!detail) { const primary = await primaryProgramKeyOf(programKey) @@ -47,6 +58,11 @@ export default async function Page({ onReserve={reserveProgramme} onCancel={dropProgrammeReservation} onRevise={reviseProgrammeReservation} + noticing={{ + offer, + onWatch: watchProgramme, + onUnwatch: unwatchProgramme, + }} /> ) diff --git a/components/guide/guide-page.tsx b/components/guide/guide-page.tsx index 7e5b66e0..4428af9d 100644 --- a/components/guide/guide-page.tsx +++ b/components/guide/guide-page.tsx @@ -14,6 +14,7 @@ import { usePathname, useRouter, useSearchParams } from 'next/navigation' import { addressWith } from '@/lib/path' import { foldedGuideOf, foldsAColumn, isOnAir } from '@/lib/guide' +import { yetToStart, type Noticing } from '@/lib/notifications' import { cn } from '@/lib/utils' import { useSubChannelsFolded } from '@/hooks/useSubChannelsFolded' import { CHANNEL_KINDS } from '@/repository/channels' @@ -80,6 +81,7 @@ export function GuideView({ onRestore, onRevise, onReadExtras, + noticing, subChannelsFolded = false, }: { /** Puts back a reservation the circle took back, from the toast's `元に戻す`. */ @@ -100,6 +102,7 @@ export function GuideView({ id: string, channelId: string, ) => Promise + noticing?: Noticing subChannelsFolded?: boolean }) { const router = useRouter() @@ -248,6 +251,9 @@ export function GuideView({ onRestore={onRestore} /> ) + const today = guide.days.find((day) => day.isToday)?.date + const aheadOf = (program: Program) => + yetToStart(program, guide.nowMin, guide.day.date, today) const detailOf = (program: Program) => { const read = detailed && detailed.id === program.id ? detailed : program @@ -260,6 +266,8 @@ export function GuideView({ channel={listed} dayLabel={guide.day.label} onAir={isOnAir(program, guide.nowMin)} + ahead={aheadOf(program)} + noticing={noticing} onReserve={onReserve} reservation={ read.booking && ( @@ -551,6 +559,8 @@ export function GuideView({ )} dayLabel={guide.day.label} onAir={isOnAir(shown, guide.nowMin)} + ahead={aheadOf(shown)} + noticing={noticing} open={panelOpen} onClose={() => setPanelOpen(false)} onReserve={onReserve} diff --git a/components/guide/program-detail-page.tsx b/components/guide/program-detail-page.tsx index 565a9d1c..e9ce8be2 100644 --- a/components/guide/program-detail-page.tsx +++ b/components/guide/program-detail-page.tsx @@ -1,6 +1,7 @@ import Link from 'next/link' import { isOnAir } from '@/lib/guide' +import { yetToStart, type Noticing } from '@/lib/notifications' import type { ProgramDetail } from '@/repository/programs' import type { ReservationWrite } from '@/repository/reservations' import { Button } from '@/components/ui/button' @@ -15,9 +16,11 @@ export function ProgramDetailView({ onReserve, onCancel, onRevise, + noticing, }: { detail: ProgramDetail onReserve: (programmeId: string) => Promise + noticing?: Noticing } & ProgramBookingActions) { const { program, channel, day, nowMin } = detail @@ -40,6 +43,8 @@ export function ProgramDetailView({ channel={channel} dayLabel={day.label} onAir={isOnAir(program, nowMin)} + ahead={yetToStart(program, nowMin, day.date, detail.today)} + noticing={noticing} onReserve={onReserve} reservation={ program.booking && ( diff --git a/components/guide/program-detail.tsx b/components/guide/program-detail.tsx index ec30de23..65df29fb 100644 --- a/components/guide/program-detail.tsx +++ b/components/guide/program-detail.tsx @@ -9,6 +9,7 @@ import type { RelationKind, } from '@/repository/programs' import type { ReservationWrite } from '@/repository/reservations' +import type { Noticing } from '@/lib/notifications' import { audioSaying, secondSoundSaying, @@ -33,6 +34,10 @@ import { ProgramExtended, } from '@/components/guide/program-description' import { ReservationArea } from '@/components/guide/reservation-area' +import { + NotifyLeadChip, + NotifyStartButton, +} from '@/components/notifications/programme-notice' import { InlineAlert } from '@/components/vela/banner' import { WAITING_LABEL, WaitingRows } from '@/components/vela/waiting' @@ -76,6 +81,8 @@ export function ProgramDetailBody({ onReserve, reservation, extras = 'ready', + ahead = false, + noticing, }: { program: Program channel?: Channel @@ -84,6 +91,9 @@ export function ProgramDetailBody({ onReserve: (programmeId: string) => Promise reservation?: ReactNode extras?: 'ready' | 'waiting' | 'failed' + /** Whether the programme has yet to start, which is when its start can be told. */ + ahead?: boolean + noticing?: Noticing }) { const related = program.related ?? [] const items = program.items ?? [] @@ -97,15 +107,20 @@ export function ProgramDetailBody({ {channel.name} )}
            -

            - {program.dateLabel ?? dayLabel} {program.startLabel} –{' '} - {program.endUndecided ? '終了未定' : program.endLabel} - {program.durationLabel && ( - - {program.durationLabel} - +

            +

            + {program.dateLabel ?? dayLabel} {program.startLabel} –{' '} + {program.endUndecided ? '終了未定' : program.endLabel} + {program.durationLabel && ( + + {program.durationLabel} + + )} +

            + {ahead && program.watch && ( + )} -

            +
            {program.genreLabel} @@ -174,6 +189,16 @@ export function ProgramDetailBody({ booked={reservation} seriesHref={series ? newRuleHref(series) : undefined} onReserve={onReserve} + notice={ + ahead && + noticing && ( + + ) + } first={ onAir && ( + <> + + + + {asking && ( + setAsking(false)} + /> + )} + + + ) } -/** The amber chip a programme wears once its start is to be told, beside its time; pressing it picks how early. */ -export function NotifyLeadChip({ - leadMinutes, - onChangeLead, - defaultOpen, +function AskForm({ + offer, + onAsk, + onClose, }: { - leadMinutes: LeadMinutes - onChangeLead: (lead: LeadMinutes) => void - defaultOpen?: boolean + offer: WatchOffer + onAsk: (draft: WatchDraft) => Promise + onClose: () => void }) { - const [open, setOpen] = useState(defaultOpen ?? false) + const id = useId() + const [lead, setLead] = useState(offer.leadMinutes) + const [sendTo, setSendTo] = useState(() => + offer.destinations.map((destination) => destination.id), + ) + const [refusal, setRefusal] = useState() + const [pending, startTransition] = useTransition() + + const ask = () => { + setRefusal(undefined) + + startTransition(async () => { + const result = await onAsk({ leadMinutes: lead, destinations: sendTo }) + + if (result.state === 'ok') { + onClose() + + return + } + + setRefusal(refusalOf(result)) + }) + } return ( - - - - {leadChipWords(leadMinutes)} - - - + +
            - { - onChangeLead(lead) - setOpen(false) - }} - className="bg-transparent p-0" - /> - - +
            + 何分前 + +
            +
            + 送り先 + + {offer.destinations.map((destination) => ( + setSendTo(toggled(sendTo, destination.id))} + > + {destination.name} + + ))} + +
            + + {refusal && {refusal}} + +
            + + + + + + ) +} + +/** The amber chip a programme wears beside its time once its start is to be told: how early. */ +export function NotifyLeadChip({ leadMinutes }: { leadMinutes: LeadMinutes }) { + return ( + + ) } diff --git a/stories/screens/ProgramDetail.stories.tsx b/stories/screens/ProgramDetail.stories.tsx index 0fffa429..d30305a2 100644 --- a/stories/screens/ProgramDetail.stories.tsx +++ b/stories/screens/ProgramDetail.stories.tsx @@ -2,6 +2,12 @@ import type { Meta, StoryObj } from '@storybook/nextjs' import { expect, fn, screen, userEvent, waitFor, within } from 'storybook/test' import { isOnAir, relationDestinationOf } from '@/lib/guide' +import type { + NotificationWrite, + Noticing, + WatchDraft, + WatchWrite, +} from '@/lib/notifications' import { searchConditionOfQuery, searchTermsOf } from '@/lib/search-condition' import type { ProgramDetail } from '@/repository/programs' import { @@ -11,6 +17,10 @@ import { } from '@/repository/programs.fixtures' import type { ReservationWrite } from '@/repository/reservations' import { ProgramDetailView } from '@/components/guide/program-detail-page' +import { + NOTIFY_START, + STOP_NOTIFYING, +} from '@/components/notifications/programme-notice' import { inTheApp } from '@/stories/frames' import { NARROW_PHONE, PHONE } from '@/stories/rows-as-cards' import { standsOnAGround } from '@/stories/stands-on-a-ground' @@ -628,3 +638,115 @@ export const 狭い電話でも放送中はライブ視聴が先頭: Story = { await liveLeadsOnAPhone(canvasElement, NARROW_PHONE.width) }, } + +const watchIt = fn( + async (_programmeId: string, draft: WatchDraft): Promise => ({ + state: 'ok', + watch: { id: 'watch-asked', leadMinutes: draft.leadMinutes }, + }), +) + +const unwatchIt = fn(async (_watchId: string): Promise => ({ + state: 'ok', +})) + +const NOTICING: Noticing = { + offer: { + leadMinutes: 3, + destinations: [ + { id: 'dest-slack', name: '家の Slack' }, + { id: 'dest-ipad', name: 'iPad の Safari' }, + ], + }, + onWatch: watchIt, + onUnwatch: unwatchIt, +} + +const ahead: ProgramDetail = { + ...standard, + nowMin: standard.program.startMin - 1, +} + +export const 放送前は録画予約の隣で放送開始の通知を頼む: Story = { + args: { detail: ahead, noticing: NOTICING }, + beforeEach: () => { + watchIt.mockClear() + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + const { reserve } = actionsIn(canvasElement) + const ask = canvas.getByRole('button', { name: NOTIFY_START }) + + await sideBySide(reserve!, ask) + await expect(ask).toHaveAttribute('data-variant', 'tone') + await userEvent.click(ask) + + const form = within( + await screen.findByRole('dialog', { name: NOTIFY_START }), + ) + + await userEvent.click(form.getByRole('button', { name: '通知する' })) + await waitFor(() => + expect(watchIt).toHaveBeenCalledWith(standard.program.id, { + leadMinutes: 3, + destinations: ['dest-slack', 'dest-ipad'], + }), + ) + await expect( + await screen.findByText('開始の 3 分前に通知します'), + ).toBeVisible() + }, +} + +export const 放送開始を通知する番組は取り消すボタンになる: Story = { + args: { + detail: { + ...ahead, + program: { + ...ahead.program, + watch: { id: 'watch-told', leadMinutes: 10 }, + }, + }, + noticing: NOTICING, + }, + beforeEach: () => { + unwatchIt.mockClear() + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await expect(canvas.getByText('開始 10 分前に通知')).toBeVisible() + await expect( + canvas.queryByRole('button', { name: NOTIFY_START }), + ).toBeNull() + await userEvent.click(canvas.getByRole('button', { name: STOP_NOTIFYING })) + await waitFor(() => expect(unwatchIt).toHaveBeenCalledWith('watch-told')) + }, +} + +export const 放送中の番組には放送開始の通知を置かない: Story = { + args: { detail: { ...standard, nowMin: NOW_MIN }, noticing: NOTICING }, + play: async ({ canvasElement }) => { + await expect( + within(canvasElement).queryByRole('button', { name: NOTIFY_START }), + ).toBeNull() + }, +} + +export const 電話でも録画予約の隣で放送開始の通知を頼む: Story = { + args: { detail: ahead, noticing: NOTICING }, + parameters: { screen: PHONE }, + play: async ({ canvasElement }) => { + const ask = within(canvasElement).getByRole('button', { + name: NOTIFY_START, + }) + + await expect(ask).toBeVisible() + await expect(ask.getBoundingClientRect().right).toBeLessThanOrEqual( + PHONE.width, + ) + await expect(canvasElement.ownerDocument.documentElement.scrollWidth).toBe( + PHONE.width, + ) + }, +} From 8255089be4be666a657bc245736fa4eea6d49b4c Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 06:39:47 +0900 Subject: [PATCH 16/24] =?UTF-8?q?=E6=94=BE=E9=80=81=E9=96=8B=E5=A7=8B?= =?UTF-8?q?=E3=82=92=E9=80=9A=E7=9F=A5=E3=81=99=E3=82=8B=E7=95=AA=E7=B5=84?= =?UTF-8?q?=E3=81=AF=E7=95=AA=E7=B5=84=E8=A1=A8=E3=81=AE=E6=9C=AD=E3=81=AE?= =?UTF-8?q?=E8=A7=92=E3=81=AB=E3=83=99=E3=83=AB=E3=82=92=E5=87=BA=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- app/globals.css | 24 +++ components/guide/channel-day-list.tsx | 8 + components/guide/guide-grid.tsx | 1 + components/guide/program-cell.tsx | 17 +- stories/screens/Guide.stories.tsx | 250 ++++++++++++++++++++++++++ 5 files changed, 299 insertions(+), 1 deletion(-) diff --git a/app/globals.css b/app/globals.css index 4375c27d..ec9a2c54 100644 --- a/app/globals.css +++ b/app/globals.css @@ -2803,6 +2803,30 @@ } } +/* The bell of a programme whose start is to be told sits in the cell's top + right corner, and in the middle of a cell of one line. */ +@utility guide-cell-bell { + @apply pointer-events-none absolute right-2 text-warn; + top: calc(7rem / 16); + width: calc(15rem / 16); + height: calc(15rem / 16); + + & svg { + stroke-width: 1.9; + } + + @container (height < 2.5rem) { + top: 50%; + width: min(calc(15rem / 16), 80cqh); + height: min(calc(15rem / 16), 80cqh); + translate: 0 -50%; + } + + @container (height < 0.75rem) { + display: none; + } +} + @utility guide-cell-desc { @apply mt-0.5 block text-note text-ink-2; line-height: var(--guide-pitch); diff --git a/components/guide/channel-day-list.tsx b/components/guide/channel-day-list.tsx index 06f0483f..08667dc3 100644 --- a/components/guide/channel-day-list.tsx +++ b/components/guide/channel-day-list.tsx @@ -18,6 +18,8 @@ import { groundOf, } from '@/components/guide/guide-metrics' import { ChevronDownIcon, ChevronUpIcon } from '@/components/vela/icons' +import { WATCHED_SAYS } from '@/components/guide/program-cell' +import { NotifyBell } from '@/components/notifications/programme-notice' import { pressable } from '@/components/vela/tactile' const ROOM_ABOVE_NOW_PX = 48 @@ -255,6 +257,12 @@ export function ChannelDayList({ )} /> {mark && } + {p.watch && ( + + )} {halfWidthOf(p.title)} = PLUS_MIN_DURATION && ( = { booked: RESERVATION_STANDING_TERMS.scheduled.label, @@ -67,7 +70,13 @@ export const ProgramCell = memo(function ProgramCell({ > - + {mark && ( @@ -105,6 +114,12 @@ export const ProgramCell = memo(function ProgramCell({ {mark && {MARK_SAYS[mark]}} + {p.watch && ( + + + )} ) }) diff --git a/stories/screens/Guide.stories.tsx b/stories/screens/Guide.stories.tsx index ddb2c113..83658039 100644 --- a/stories/screens/Guide.stories.tsx +++ b/stories/screens/Guide.stories.tsx @@ -11,6 +11,12 @@ import { NOW_LINE_THICKNESS_PX, } from '@/lib/guide' import { genreWordOf, halfWidthOf } from '@/lib/guide-cell' +import type { + NotificationWrite, + Noticing, + WatchDraft, + WatchWrite, +} from '@/lib/notifications' import { AERIAL_CHANNEL_FIXTURES, CHANNEL_FIXTURES, @@ -44,6 +50,10 @@ import { import { ARRIVAL_SPAN_MS, GUIDE_FACES } from '@/lib/arrival' import { HOUR_REM, hourPxIn } from '@/components/guide/guide-metrics' import { GuideView } from '@/components/guide/guide-page' +import { + NOTIFY_START, + STOP_NOTIFYING, +} from '@/components/notifications/programme-notice' import { inTheApp } from '@/stories/frames' import { FROM_600, NARROW_PHONE, PHONE } from '@/stories/rows-as-cards' @@ -2978,3 +2988,243 @@ export const 電話では上の帯に日付と番組を検索と絞り込みを ).toBe(bar.getByRole('link', { name: '番組を検索' })) }, } + +const watchIt = fn( + async (_programmeId: string, draft: WatchDraft): Promise => ({ + state: 'ok', + watch: { id: 'watch-asked', leadMinutes: draft.leadMinutes }, + }), +) + +const unwatchIt = fn(async (_watchId: string): Promise => ({ + state: 'ok', +})) + +const NOTICING: Noticing = { + offer: { + leadMinutes: 3, + destinations: [ + { id: 'dest-slack', name: '家の Slack' }, + { id: 'dest-ipad', name: 'iPad の Safari' }, + ], + }, + onWatch: watchIt, + onUnwatch: unwatchIt, +} + +const TOLD_WHEN_IT_STARTS = programsOfChannel( + base.programs, + CHANNEL_FIXTURES[0].id, +).find((program) => !program.booking && program.startMin > base.nowMin)! + +const WITH_A_NOTICE = { + ...base, + programs: base.programs.map((program) => + program.id === TOLD_WHEN_IT_STARTS.id + ? { ...program, watch: { id: 'watch-told', leadMinutes: 3 as const } } + : program, + ), +} + +function cellFor(canvasElement: HTMLElement, programmeId: string): HTMLElement { + return canvasElement.querySelectorAll( + '[data-opens="program-panel"]', + )[IN_GRID_ORDER.findIndex((one) => one.id === programmeId)] +} + +async function theBellSitsInTheCorner(cell: HTMLElement): Promise { + const bell = cell.querySelector('[data-slot="notify-bell"]')! + const drawn = bell.getBoundingClientRect() + const room = cell.getBoundingClientRect() + + await expect(bell).toHaveTextContent('放送開始を通知') + await expect(drawn.width).toBeGreaterThan(0) + await expect(drawn.top).toBeGreaterThanOrEqual(room.top) + await expect(drawn.bottom).toBeLessThanOrEqual(room.bottom + 0.5) + await expect(drawn.right).toBeLessThanOrEqual(room.right) + await expect(drawn.left).toBeGreaterThan(room.left + room.width / 2) + await expect(cell.querySelector('[data-booking-mark]')).toBeNull() +} + +export const 放送開始を通知する番組は札の角にベルが付く: Story = { + args: { guide: WITH_A_NOTICE, noticing: NOTICING }, + parameters: { screen: A_LAPTOP }, + beforeEach: () => { + unwatchIt.mockClear() + }, + play: async ({ canvasElement }) => { + await columnsFilled(canvasElement) + + const cell = cellFor(canvasElement, TOLD_WHEN_IT_STARTS.id) + + await expect( + canvasElement.querySelectorAll( + '[data-opens="program-panel"] [data-slot="notify-bell"]', + ), + ).toHaveLength(1) + await theBellSitsInTheCorner(cell) + await expect( + cell.nextElementSibling?.matches('[data-slot="reserve-plus"]') ?? false, + ).toBe(false) + + cell.scrollIntoView({ block: 'center' }) + await userEvent.click(cell) + + const surface = within(await openedPanel(canvasElement)) + + await expect(surface.getByText('開始 3 分前に通知')).toBeVisible() + await userEvent.click(surface.getByRole('button', { name: STOP_NOTIFYING })) + await waitFor(() => expect(unwatchIt).toHaveBeenCalledWith('watch-told')) + }, +} + +export const 番組の詳細から放送開始の通知を頼む: Story = { + args: { guide: base, noticing: NOTICING }, + parameters: { screen: A_LAPTOP }, + beforeEach: () => { + watchIt.mockClear() + }, + play: async ({ canvasElement }) => { + await columnsFilled(canvasElement) + + const cell = cellFor(canvasElement, TOLD_WHEN_IT_STARTS.id) + + cell.scrollIntoView({ block: 'center' }) + await userEvent.click(cell) + + const surface = within(await openedPanel(canvasElement)) + const ask = surface.getByRole('button', { name: NOTIFY_START }) + + await expect( + surface.getByRole('button', { name: '録画予約' }), + ).toBeVisible() + await userEvent.click(ask) + + const form = within( + await screen.findByRole('dialog', { name: NOTIFY_START }), + ) + + await userEvent.click( + within(form.getByRole('group', { name: '何分前' })).getByRole('button', { + name: '5 分前', + }), + ) + await userEvent.click(form.getByRole('button', { name: '通知する' })) + + await waitFor(() => + expect(watchIt).toHaveBeenCalledWith(TOLD_WHEN_IT_STARTS.id, { + leadMinutes: 5, + destinations: ['dest-slack', 'dest-ipad'], + }), + ) + await expect( + await screen.findByText('開始の 5 分前に通知します'), + ).toBeVisible() + }, +} + +export const 始まった番組には放送開始の通知を置かない: Story = { + args: { guide: base, noticing: NOTICING }, + parameters: { screen: A_LAPTOP }, + play: async ({ canvasElement }) => { + await columnsFilled(canvasElement) + + for (const time of ['onAir', 'ended']) { + const cell = canvasElement.querySelector( + `[data-opens="program-panel"][data-time="${time}"]`, + )! + + cell.scrollIntoView({ block: 'center' }) + await userEvent.click(cell) + + const surface = await openedPanel(canvasElement) + + await expect( + within(surface).queryByRole('button', { name: NOTIFY_START }), + ).toBeNull() + + await userEvent.keyboard('{Escape}') + await waitFor(() => + expect( + canvasElement.ownerDocument.querySelector( + '[data-slot="dialog-content"]', + ), + ).toBeNull(), + ) + } + }, +} + +export const 電話では放送開始を通知する番組の行にベルが付く: Story = { + args: { guide: WITH_A_NOTICE, noticing: NOTICING }, + parameters: { screen: PHONE }, + play: async ({ canvasElement }) => { + const list = await phoneList(canvasElement) + const row = list.querySelector( + `[data-programme="${TOLD_WHEN_IT_STARTS.id}"]`, + )! + + await expect( + list.querySelectorAll('[data-slot="notify-bell"]'), + ).toHaveLength(1) + + const bell = row.querySelector('[data-slot="notify-bell"]')! + + await expect(bell).toHaveTextContent('放送開始を通知') + await expect(bell.getBoundingClientRect().width).toBeGreaterThan(0) + + row.scrollIntoView({ block: 'center' }) + await userEvent.click(pressOf(row)) + + await expect( + await within(row).findByRole('button', { name: STOP_NOTIFYING }), + ).toBeVisible() + await expect(within(row).getByText('開始 3 分前に通知')).toBeVisible() + }, +} + +export const 電話の詳細から放送開始の通知を頼む: Story = { + args: { guide: base, noticing: NOTICING }, + parameters: { screen: PHONE }, + beforeEach: () => { + watchIt.mockClear() + }, + play: async ({ canvasElement }) => { + const list = await phoneList(canvasElement) + const row = list.querySelector( + `[data-programme="${TOLD_WHEN_IT_STARTS.id}"]`, + )! + + row.scrollIntoView({ block: 'center' }) + await userEvent.click(pressOf(row)) + await userEvent.click( + await within(row).findByRole('button', { name: NOTIFY_START }), + ) + + const form = within( + await screen.findByRole('dialog', { name: NOTIFY_START }), + ) + + await userEvent.click(form.getByRole('button', { name: '通知する' })) + await waitFor(() => + expect(watchIt).toHaveBeenCalledWith(TOLD_WHEN_IT_STARTS.id, { + leadMinutes: 3, + destinations: ['dest-slack', 'dest-ipad'], + }), + ) + }, +} + +export const 横向きの電話でも札の角にベルが付く: Story = { + args: { guide: WITH_A_NOTICE, noticing: NOTICING }, + parameters: { screen: SIDEWAYS_PHONE, coarse: true }, + play: async ({ canvasElement }) => { + await columnsFilled(canvasElement) + aGridIsShown(canvasElement) + + const cell = cellFor(canvasElement, TOLD_WHEN_IT_STARTS.id) + + cell.scrollIntoView({ block: 'center', inline: 'center' }) + await theBellSitsInTheCorner(cell) + }, +} From 13dee10158c423808586686bcb82d4c48a5cac85 Mon Sep 17 00:00:00 2001 From: fyui001 Date: Wed, 11 Nov 2026 06:39:48 +0900 Subject: [PATCH 17/24] =?UTF-8?q?=E4=BA=88=E7=B4=84=E4=B8=80=E8=A6=A7?= =?UTF-8?q?=E3=81=AB=E6=94=BE=E9=80=81=E9=96=8B=E5=A7=8B=E3=81=AE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E3=81=AE=E8=A1=8C=E3=82=92=E4=B8=A6=E3=81=B9=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- app/(app)/reservations/page.tsx | 6 +- components/notifications/notify-only-row.tsx | 183 +++------- .../reservations/phone-reservations.tsx | 115 ++++++- components/reservations/reservations-page.tsx | 182 ++++++---- .../components/ProgrammeNotice.stories.tsx | 322 +++++++++++------- stories/screens/Reservations.stories.tsx | 226 +++++++++++- 6 files changed, 672 insertions(+), 362 deletions(-) diff --git a/app/(app)/reservations/page.tsx b/app/(app)/reservations/page.tsx index 998ff86a..6e0a1d28 100644 --- a/app/(app)/reservations/page.tsx +++ b/app/(app)/reservations/page.tsx @@ -4,6 +4,7 @@ import { RESERVATIONS_EVENT } from '@/repository/events' import type { EpgDriftKind } from '@/repository/reservations' import { listReservations } from '@/repository/reservations' import { getTuners } from '@/repository/tuners' +import { listWatchedProgrammes } from '@/repository/notifications' import { RefreshOnSignal } from '@/components/vela/app-signals' import { ReservationsView } from '@/components/reservations/reservations-page' import { @@ -15,6 +16,7 @@ import { throwReservationAway, throwReservationsAway, } from '@/app/(app)/reservations/actions' +import { unwatchProgramme } from '@/app/(app)/guide/actions' export const metadata: Metadata = { title: '予約' } @@ -24,12 +26,13 @@ export default async function Page({ searchParams: Promise> }) { const params = await searchParams - const [result, tuners] = await Promise.all([ + const [result, tuners, watches] = await Promise.all([ listReservations({ show: params.show === 'all' ? 'all' : undefined, epg: driftAsked(params.epg), }), getTuners().catch(() => undefined), + listWatchedProgrammes().catch(() => []), ]) return ( @@ -49,6 +52,7 @@ export default async function Page({ onCancelAll: dropReservations, onDiscardAll: throwReservationsAway, }} + notices={{ watches, onCancel: unwatchProgramme }} /> ) diff --git a/components/notifications/notify-only-row.tsx b/components/notifications/notify-only-row.tsx index b13f57a1..c26425c2 100644 --- a/components/notifications/notify-only-row.tsx +++ b/components/notifications/notify-only-row.tsx @@ -1,143 +1,83 @@ 'use client' -import { useId, useState, useTransition } from 'react' +import { useTransition } from 'react' import { cn } from '@/lib/utils' import { signedOut } from '@/lib/signed-out' import { - toggled, - type LeadMinutes, - type NotificationDestination, + watchLine, type NotificationWrite, - type ProgrammeWatch, + type WatchedProgramme, } from '@/lib/notifications' +import { delayOf, rowArrivesIn, rowDelayMs } from '@/lib/arrival' import { Badge } from '@/components/ui/badge' import { IconButton } from '@/components/vela/icon-button' import { CloseIcon } from '@/components/vela/icons' import { useToast } from '@/components/vela/toast' -import { ROW_GROUND, RowTimes } from '@/components/reservations/reservation-row' -import { LeadChoice } from '@/components/notifications/lead-choice' -import { PickChip, PickChips } from '@/components/notifications/pick-chip' +import { + PICKING_GRID, + ROW_GRID, + ROW_GROUND, + ROW_LINE, + RowTimes, +} from '@/components/reservations/reservation-row' import { NotifyBell } from '@/components/notifications/programme-notice' -import { NoticeGroupLabel } from '@/components/notifications/notice-dialog' - -/** A single notice as the reservation list shows it: the programme it is for, and when and where to. */ -export interface WatchedProgramme extends ProgrammeWatch { - title: string - channelName: string - startAt: string - endAt: string -} - -export interface WatchActions { - onChangeLead: (id: string, lead: LeadMinutes) => Promise - onChangeDestinations: ( - id: string, - destinationIds: string[], - ) => Promise - onCancel: (id: string) => Promise -} export const NOTIFY_ONLY = '通知' -const FROM_THE_GUIDE = '手動' +const SIGNED_OUT = signedOut('操作') -const SIGNED_OUT = signedOut('変更') - -/** The row's grid: the times, the bell and the title over where it came from, then the chip and the ×. Narrower times on a phone. */ -const ROW_GRID = - 'grid min-h-[calc(62rem/16)] grid-cols-[calc(76rem/16)_minmax(0,1fr)_auto] items-center gap-x-5 px-2.5 py-2 upright:grid-cols-[calc(50rem/16)_minmax(0,1fr)_auto] upright:gap-x-2 upright:pr-1.5 upright:pl-2.5' +/** What to say once a single notice was asked to be taken back. */ +export function takenBackWords( + result: NotificationWrite, + title: string, +): string { + if (result.state === 'ok') { + return `通知を取り消しました ${title}` + } -const ROW_LINE = - "relative before:absolute before:top-0 before:right-2.5 before:left-[calc(116rem/16)] before:border-t before:border-hair before:content-[''] first:before:hidden data-open:before:opacity-0 [&[data-open]+li]:before:opacity-0 upright:before:left-[calc(70rem/16)]" + return result.state === 'unauthenticated' ? SIGNED_OUT : result.message +} -/** A notice that a programme starts, standing among the reservations: a bell where a reservation has its genre's dot, and `通知` where it has its state. Pressing the title opens how early and where to under it. */ +/** A notice that a programme starts, standing among the reservations: a bell where a reservation has its genre's dot, and `通知` where it has its state. */ export function NotifyOnlyRow({ watch, - destinations, - open, - onToggle, - actions, + nth, + picking = false, + onCancel, }: { watch: WatchedProgramme - destinations: Pick[] - open: boolean - onToggle: () => void - actions: WatchActions + nth: number + /** While reservations are being picked the row keeps their columns, with nothing to check. */ + picking?: boolean + onCancel: (id: string) => Promise }) { - const panel = useId() - const [lead, setLead] = useState(watch.leadMinutes) - const [sendTo, setSendTo] = useState(watch.destinationIds) const [pending, startTransition] = useTransition() const say = useToast() - const refused = (result: NotificationWrite) => { - if (result.state === 'ok') { - return false - } - - say({ - text: result.state === 'unauthenticated' ? SIGNED_OUT : result.message, - }) - - return true - } - - const changeLead = async (next: LeadMinutes) => { - const was = lead - - setLead(next) - - if (refused(await actions.onChangeLead(watch.id, next))) { - setLead(was) - } - } - - const changeSendTo = async (destinationId: string) => { - const was = sendTo - const next = toggled(sendTo, destinationId) - - setSendTo(next) - - if (refused(await actions.onChangeDestinations(watch.id, next))) { - setSendTo(was) - } - } - return (
          • -
            +
            + {picking && - + {NOTIFY_ONLY} startTransition(async () => { - refused(await actions.onCancel(watch.id)) + say({ + text: takenBackWords(await onCancel(watch.id), watch.title), + }) }) } - className="text-ink-3" >
            - {open && ( -
            -
            - 何分前 - void changeLead(next)} - className="w-fit bg-bg [&>button]:h-7 gap-x-0 [&>button]:px-2 [&>button]:text-sub" - /> -
            -
            - - 送り先 - - - {destinations.map((destination) => ( - void changeSendTo(destination.id)} - className={cn( - 'pr-3 pl-2.5 text-[calc(13rem/16)]', - !sendTo.includes(destination.id) && - 'bg-bg enabled:hover:bg-surface-2 dark:bg-bg dark:enabled:hover:bg-surface-2', - )} - > - {destination.name} - - ))} - -
            -
            - )}
          • ) } diff --git a/components/reservations/phone-reservations.tsx b/components/reservations/phone-reservations.tsx index 44fef71d..f5216bb4 100644 --- a/components/reservations/phone-reservations.tsx +++ b/components/reservations/phone-reservations.tsx @@ -8,6 +8,15 @@ import { formatClock } from '@/lib/format' import { calendarDayOf, dayHeadingOf } from '@/lib/library-days' import type { Span } from '@/lib/conflict-line' import type { Reservation, ReservationWrite } from '@/repository/reservations' +import { + amongWatches, + watchLine, + type AmongWatches, + type NotificationWrite, + type WaitingNotices, + type WatchedProgramme, +} from '@/lib/notifications' +import { Badge } from '@/components/ui/badge' import { CloseIcon } from '@/components/vela/icons' import { useToast } from '@/components/vela/toast' import { pressable } from '@/components/vela/tactile' @@ -16,6 +25,11 @@ import { EditReservationDialog } from '@/components/reservations/edit-reservatio import { GenreDot } from '@/components/reservations/genre-dot' import type { ReservationActions } from '@/components/reservations/reservation-row' import { whereFrom } from '@/components/reservations/reservation-row' +import { + NOTIFY_ONLY, + takenBackWords, +} from '@/components/notifications/notify-only-row' +import { NotifyBell } from '@/components/notifications/programme-notice' function clockOf(at: string): string { return formatClock(new Date(at).getTime()) @@ -35,9 +49,70 @@ function spanOf(reservation: Reservation): Span | undefined { return reservation.span } +const ROW_LINE = + "relative before:absolute before:top-0 before:right-3 before:left-[calc(78rem/16)] before:h-px before:bg-hair before:content-[''] first:before:hidden" + +const TAKE_BACK = + 'flex size-11 shrink-0 items-center justify-center self-center rounded-full text-ink-2 outline-none hover:bg-surface-2 focus-visible:shadow-ring [&_svg]:size-[calc(17rem/16)]' + +/** A notice that a programme starts, among the reservations of a phone: a bell for the genre's dot, `通知` at its end, and the × that takes it back. */ +function WatchRow({ + watch, + onCancel, +}: { + watch: WatchedProgramme + onCancel: (id: string) => Promise +}) { + const say = useToast() + const [pending, start] = useTransition() + + return ( +
          • +
            +
            + + + {clockOf(watch.startAt)} + + {clockOf(watch.endAt)} + + + + + {watch.title} + + + {watchLine(watch)} + + + + {NOTIFY_ONLY} + +
            + +
            +
          • + ) +} + /** The reservations on a phone held upright: under the day each starts on, a row each of its start and end, its title, channel and where it came from, a chip only for what needs attention, and the × that takes it back. Pressing the row opens its change under it. */ export function PhoneReservationRows({ reservations, + notices, now, actions, chosenId, @@ -45,6 +120,8 @@ export function PhoneReservationRows({ className, }: { reservations: Reservation[] + /** The notices waiting for a programme to start, shown among the reservations by their start. */ + notices?: WaitingNotices now: Date actions: ReservationActions /** The reservation whose detail stands beside the list, on a phone held on its side: ringed. */ @@ -56,17 +133,21 @@ export function PhoneReservationRows({ const [open, setOpen] = useState() const say = useToast() const [, start] = useTransition() - const days: { day: string; items: Reservation[] }[] = [] + const days: { day: string; items: AmongWatches[] }[] = [] - for (const reservation of reservations) { - const span = spanOf(reservation) - const day = span ? calendarDayOf(span.startAt) : '' + for (const row of amongWatches( + reservations, + (one) => spanOf(one)?.startAt, + notices?.watches ?? [], + )) { + const startAt = row.watch ? row.watch.startAt : spanOf(row.own)?.startAt + const day = startAt ? calendarDayOf(startAt) : '' const last = days.find((one) => one.day === day) if (last) { - last.items.push(reservation) + last.items.push(row) } else { - days.push({ day, items: [reservation] }) + days.push({ day, items: [row] }) } } @@ -112,7 +193,20 @@ export function PhoneReservationRows({ )}
              - {items.map((reservation) => { + {items.map((row) => { + if (row.watch) { + return ( + notices && ( + + ) + ) + } + + const reservation = row.own const span = spanOf(reservation) const opened = open === reservation.id const recording = reservation.standing === 'recording' @@ -127,7 +221,7 @@ export function PhoneReservationRows({ data-keep={reservation.id} data-chosen={reservation.id === chosenId ? '' : undefined} className={cn( - "relative before:absolute before:top-0 before:right-3 before:left-[calc(78rem/16)] before:h-px before:bg-hair before:content-[''] first:before:hidden", + ROW_LINE, reservation.id === chosenId && 'z-[1] rounded-md bg-surface before:hidden [&+li]:before:hidden', opened && @@ -189,10 +283,7 @@ export function PhoneReservationRows({ type="button" aria-label="取り消す" onClick={() => takeBack(reservation)} - className={cn( - 'flex size-11 shrink-0 items-center justify-center self-center rounded-full text-ink-2 outline-none hover:bg-surface-2 focus-visible:shadow-ring [&_svg]:size-[calc(17rem/16)]', - pressable, - )} + className={cn(TAKE_BACK, pressable)} > diff --git a/components/reservations/reservations-page.tsx b/components/reservations/reservations-page.tsx index 9f11bae0..92924a53 100644 --- a/components/reservations/reservations-page.tsx +++ b/components/reservations/reservations-page.tsx @@ -19,6 +19,11 @@ import { import { calendarDayOf, dayHeadingOf } from '@/lib/library-days' import { whatIsLost } from '@/lib/conflict-line' import { linesOf, type ReservationLine } from '@/lib/reservations' +import { + amongWatches, + type AmongWatches, + type WaitingNotices, +} from '@/lib/notifications' import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' import { EmptyState } from '@/components/vela/empty-state' @@ -29,6 +34,7 @@ import { waitsWhile } from '@/components/vela/waiting' import type { ReservationActions } from '@/components/reservations/reservation-row' import { ReservationRow } from '@/components/reservations/reservation-row' import { RelayRow } from '@/components/reservations/relay-row' +import { NotifyOnlyRow } from '@/components/notifications/notify-only-row' import type { ReservationBulkActions } from '@/components/reservations/reservation-selection' import { ReservationSelection } from '@/components/reservations/reservation-selection' import { ReservationTabs } from '@/components/reservations/reservation-tabs' @@ -104,21 +110,21 @@ function startOf(line: ReservationLine): string | undefined { : (line.segments[0].relay?.wholeStartAt ?? line.segments[0].span?.startAt) } -/** The lines in the order given, gathered under the day each starts on; a day keeps the place of its first line. */ -function daysOf( - lines: readonly ReservationLine[], -): { day: string; lines: ReservationLine[] }[] { - const days: { day: string; lines: ReservationLine[] }[] = [] +type ListRow = AmongWatches + +/** The rows in the order given, gathered under the day each starts on; a day keeps the place of its first row. */ +function daysOf(rows: readonly ListRow[]): { day: string; rows: ListRow[] }[] { + const days: { day: string; rows: ListRow[] }[] = [] - for (const line of lines) { - const start = startOf(line) + for (const row of rows) { + const start = row.watch ? row.watch.startAt : startOf(row.own) const day = start ? calendarDayOf(start) : '' const found = days.find((one) => one.day === day) if (found) { - found.lines.push(line) + found.rows.push(row) } else { - days.push({ day, lines: [line] }) + days.push({ day, rows: [row] }) } } @@ -130,15 +136,20 @@ export function ReservationsView({ actions, bulk, tuners, + notices, }: { result: ReservationsResult actions: ReservationActions bulk: ReservationBulkActions /** The tuners as they stand, for the chips under the next recording; left out when they cannot be read. */ tuners?: TunerRow[] + /** The notices waiting for a programme to start; a list narrowed to what drifted from the guide shows none. */ + notices?: WaitingNotices }) { const { items, total, drift, filter } = result const lines = linesOf(items) + const told = filter.epg ? undefined : notices + const anything = items.length > 0 || (told?.watches.length ?? 0) > 0 const [open, setOpen] = useState() const firstConflict = items.find((one) => one.standing === 'conflict')?.id const [relaysOpen, setRelaysOpen] = useState>( @@ -381,12 +392,13 @@ export function ReservationsView({
              {filters}
              - {items.length > 0 && sideways && ( + {anything && sideways && ( )} - {items.length > 0 && ( + {anything && (
              )} - {items.length === 0 &&
              {empty}
              } + {!anything &&
              {empty}
              }
              )} - {items.length === 0 ? ( + {!anything ? ( empty ) : (
              - {daysOf(lines).map(({ day, lines: theirs }) => { - const heading = day ? dayHeadingOf(day, now) : undefined - - return ( -
              - {heading && ( -

              - {heading.near ?? ( - {heading.date} - )} - {heading.near && ( - - {heading.date} - - )} -

              - )} -
                - {theirs.map((line, nth) => { - if (line.kind === 'one') { - return rowOf(line.reservation, nth) - } - - const relayOpen = relaysOpen.has(line.key) - - return [ - toggleRelay(line.key)} - picking={picking} - chosen={ - line.segments.filter((one) => picked.has(one.id)) - .length - } - onSelect={(taken) => - pick( - line.segments.map((one) => one.id), - taken, + {daysOf(amongWatches(lines, startOf, told?.watches ?? [])).map( + ({ day, rows: theirs }) => { + const heading = day ? dayHeadingOf(day, now) : undefined + + return ( +
                + {heading && ( +

                + {heading.near ?? ( + {heading.date} + )} + {heading.near && ( + + {heading.date} + + )} +

                + )} +
                  + {theirs.map((row, nth) => { + if (row.watch) { + return ( + told && ( + ) - } - />, - ...(relayOpen - ? line.segments.map((one, at) => - rowOf(one, at, { - nth: one.relay?.nth ?? at + 1, - of: one.relay?.of ?? line.segments.length, - }), - ) - : []), - ] - })} -
                -
                - ) - })} + ) + } + + const line = row.own + + if (line.kind === 'one') { + return rowOf(line.reservation, nth) + } + + const relayOpen = relaysOpen.has(line.key) + + return [ + toggleRelay(line.key)} + picking={picking} + chosen={ + line.segments.filter((one) => + picked.has(one.id), + ).length + } + onSelect={(taken) => + pick( + line.segments.map((one) => one.id), + taken, + ) + } + />, + ...(relayOpen + ? line.segments.map((one, at) => + rowOf(one, at, { + nth: one.relay?.nth ?? at + 1, + of: one.relay?.of ?? line.segments.length, + }), + ) + : []), + ] + })} +
              +
              + ) + }, + )}
              )}
              diff --git a/stories/components/ProgrammeNotice.stories.tsx b/stories/components/ProgrammeNotice.stories.tsx index cf2561af..8016d4da 100644 --- a/stories/components/ProgrammeNotice.stories.tsx +++ b/stories/components/ProgrammeNotice.stories.tsx @@ -3,9 +3,12 @@ import { useState } from 'react' import { expect, fn, screen, userEvent, waitFor, within } from 'storybook/test' import type { - LeadMinutes, NotificationWrite, + Noticing, ProgrammeWatch, + WatchDraft, + WatchOffer, + WatchWrite, } from '@/lib/notifications' import { NOTIFY_START, @@ -13,65 +16,78 @@ import { NotifyLeadChip, NotifyStartButton, STOP_NOTIFYING, - type WatchWrite, } from '@/components/notifications/programme-notice' import { NOTIFY_ONLY, NotifyOnlyRow, - type WatchActions, } from '@/components/notifications/notify-only-row' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { ListIcon, RecordIcon } from '@/components/vela/icons' import { Toasts } from '@/components/vela/toast' +import { afterTheArrival } from '@/stories/after-the-arrival' import { PHONE } from '@/stories/rows-as-cards' import { DESTINATIONS, - HOME_SLACK, WATCHED_DOCUMENTARY, WATCHED_FOOTBALL, } from '@/stories/fixtures/notifications' const OK: NotificationWrite = { state: 'ok' } -const changeLead = fn(async () => OK) +const PROGRAMME = '40001-4001-52001' -const changeDestinations = fn( - async () => OK, -) +const OFFER: WatchOffer = { + leadMinutes: 3, + destinations: DESTINATIONS.map(({ id, name }) => ({ id, name })), +} -const cancel = fn(async () => OK) +const ALREADY_SET = + 'この番組の通知はすでに設定してあるか、もう送ったため、設定できませんでした。' -const WATCH_ACTIONS: WatchActions = { - onChangeLead: changeLead, - onChangeDestinations: changeDestinations, - onCancel: cancel, -} +const asked = fn<(programmeId: string, draft: WatchDraft) => void>() + +const cancel = fn<(id: string) => Promise>(async () => OK) /** A programme's detail as far as the single notice reaches into it: the time with the chip beside it once set, and the row of actions with the button. */ -function DetailWithTheNotice({ watching }: { watching: boolean }) { +function DetailWithTheNotice({ + watching, + nowhere = false, + refused = false, +}: { + watching: boolean + /** No destination is on, so there is nowhere to send a notice. */ + nowhere?: boolean + /** The notice is turned away when asked. */ + refused?: boolean +}) { const [watch, setWatch] = useState( - watching - ? { id: 'watch-doc', leadMinutes: 3, destinationIds: [HOME_SLACK.id] } - : undefined, + watching ? { id: 'watch-doc', leadMinutes: 3 } : undefined, ) - const onWatch = async (): Promise => { - const made: ProgrammeWatch = { - id: 'watch-doc', - leadMinutes: 3, - destinationIds: [HOME_SLACK.id], - } + const noticing: Noticing = { + offer: nowhere ? undefined : OFFER, + onWatch: async (programmeId, draft): Promise => { + asked(programmeId, draft) - setWatch(made) + if (refused) { + return { state: 'rejected', message: ALREADY_SET } + } - return { state: 'ok', watch: made } - } + const made: ProgrammeWatch = { + id: 'watch-doc', + leadMinutes: draft.leadMinutes, + } - const onUnwatch = async (): Promise => { - setWatch(undefined) + setWatch(made) - return OK + return { state: 'ok', watch: made } + }, + onUnwatch: async () => { + setWatch(undefined) + + return OK + }, } return ( @@ -85,14 +101,7 @@ function DetailWithTheNotice({ watching }: { watching: boolean }) {

              11/09(月) 19:30 – 20:15 45 分 - {watch && ( - - setWatch({ ...watch, leadMinutes: lead }) - } - /> - )} + {watch && }

              @@ -109,9 +118,9 @@ function DetailWithTheNotice({ watching }: { watching: boolean }) { 録画予約

            {hit.description && (
            @@ -67,6 +75,16 @@ export function HitDetail({ programmeId={hit.id} seriesHref={series ? newRuleHref(series) : undefined} onReserve={onReserve} + notice={ + hit.ahead && + noticing && ( + + ) + } /> )}