diff --git a/app/(app)/guide/actions.ts b/app/(app)/guide/actions.ts index 80013f4f..4a4a17bf 100644 --- a/app/(app)/guide/actions.ts +++ b/app/(app)/guide/actions.ts @@ -8,6 +8,13 @@ import type { RebuildResult, } from '@/repository/collection' import { collectNow, rebuildEpg } from '@/repository/collection' +import type { + NotificationWrite, + WatchDraft, + WatchWrite, +} from '@/lib/notifications' +import { wasAnswered } from '@/lib/notifications' +import { askForWatch, cancelWatch } from '@/repository/notifications' import type { ProgramExtras } from '@/repository/programs' import { extrasOf } from '@/repository/programs' import type { @@ -97,3 +104,30 @@ 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) + + if (wasAnswered(result)) { + revalidatePath('/guide') + revalidatePath('/reservations') + revalidatePath('/search') + } + + return result +} + +export async function unwatchProgramme(id: string): Promise { + const result = await cancelWatch(id) + + if (wasAnswered(result)) { + revalidatePath('/guide') + revalidatePath('/reservations') + revalidatePath('/search') + } + + return result +} diff --git a/app/(app)/guide/page.tsx b/app/(app)/guide/page.tsx index 74f07a17..4316eb87 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 { readSingleNotices } 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,16 @@ export default async function Page({ }) { const params = await searchParams const jar = await cookies() - const [{ guide, rest }, collection] = await Promise.all([ + const notices = readSingleNotices() + const [{ guide, rest }, collection, offer] = await Promise.all([ getGuideInTwo( typeof params.kind === 'string' ? params.kind : undefined, typeof params.date === 'string' ? params.date : undefined, listBookings(), + notices.watches, ), getCollectionStatus(), + notices.offer, ]) const opening = guide.programs.length > 0 ? guide.programs : await rest const later = @@ -75,6 +81,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..01f49e4c 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 { readSingleNotices } 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,11 @@ export default async function Page({ params: Promise<{ programKey: string }> }) { const { programKey } = await params - const detail = await getProgram(programKey, new Date(), listBookings()) + const notices = readSingleNotices() + const [detail, offer] = await Promise.all([ + getProgram(programKey, new Date(), listBookings(), notices.watches), + notices.offer, + ]) if (!detail) { const primary = await primaryProgramKeyOf(programKey) @@ -47,6 +54,11 @@ export default async function Page({ onReserve={reserveProgramme} onCancel={dropProgrammeReservation} onRevise={reviseProgrammeReservation} + noticing={{ + offer, + onWatch: watchProgramme, + onUnwatch: unwatchProgramme, + }} /> ) 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/app/(app)/search/page.tsx b/app/(app)/search/page.tsx index b971fbcd..0189c609 100644 --- a/app/(app)/search/page.tsx +++ b/app/(app)/search/page.tsx @@ -2,10 +2,13 @@ import type { Metadata } from 'next' import { rawSearchConditionOf } from '@/lib/search-condition' import { searchPrograms } from '@/repository/search' +import { readSingleNotices } from '@/repository/notifications' import { dropProgrammeReservation, reserveProgramme, restoreProgrammeReservation, + unwatchProgramme, + watchProgramme, } from '../guide/actions' import { SearchView } from '@/components/search/search-page' @@ -17,7 +20,11 @@ export default async function Page({ searchParams: Promise> }) { const params = await searchParams - const result = await searchPrograms(rawSearchConditionOf(params)) + const notices = readSingleNotices() + const [result, offer] = await Promise.all([ + searchPrograms(rawSearchConditionOf(params), notices.watches), + notices.offer, + ]) return ( ) } diff --git a/app/(app)/settings/notifications/actions.ts b/app/(app)/settings/notifications/actions.ts new file mode 100644 index 00000000..14861efa --- /dev/null +++ b/app/(app)/settings/notifications/actions.ts @@ -0,0 +1,94 @@ +'use server' + +import { revalidatePath } from 'next/cache' + +import type { + DestinationRevision, + LeadMinutes, + NotificationWrite, + RuleSetDraft, + TestSending, + WebhookDraft, +} from '@/lib/notifications' +import { wasAnswered } from '@/lib/notifications' +import { + defineRuleSet, + registerDestination, + removeDestination, + removeRuleSet, + reviseDestination, + reviseRuleSet, + settleLead, + switchDestination, + switchRuleSet, + tryDestination, +} from '@/repository/notifications' + +const NOTIFICATIONS = '/settings/notifications' + +/** The page is read again once Carina has answered; a write that never reached it leaves the page as it is. */ +function readAgain(result: T): T { + if (wasAnswered(result)) { + revalidatePath(NOTIFICATIONS) + } + + return result +} + +export async function addDestination( + draft: WebhookDraft, +): Promise { + return readAgain(await registerDestination(draft)) +} + +export async function changeDestination( + id: string, + revision: DestinationRevision, +): Promise { + return readAgain(await reviseDestination(id, revision)) +} + +export async function turnDestination( + id: string, + enabled: boolean, +): Promise { + return readAgain(await switchDestination(id, enabled)) +} + +export async function sendTrial(id: string): Promise { + return readAgain(await tryDestination(id)) +} + +export async function dropDestination(id: string): Promise { + return readAgain(await removeDestination(id)) +} + +export async function addRuleSet( + draft: RuleSetDraft, +): Promise { + return readAgain(await defineRuleSet(draft)) +} + +export async function changeRuleSet( + id: string, + draft: RuleSetDraft, +): Promise { + return readAgain(await reviseRuleSet(id, draft)) +} + +export async function turnRuleSet( + id: string, + enabled: boolean, +): Promise { + return readAgain(await switchRuleSet(id, enabled)) +} + +export async function dropRuleSet(id: string): Promise { + return readAgain(await removeRuleSet(id)) +} + +export async function settleTheLead( + lead: LeadMinutes, +): Promise { + return readAgain(await settleLead(lead)) +} 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/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 && ( 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-cell.tsx b/components/guide/program-cell.tsx index 9193b5c7..335a687b 100644 --- a/components/guide/program-cell.tsx +++ b/components/guide/program-cell.tsx @@ -17,6 +17,9 @@ import { remOfMinutes, type CellTime, } from '@/components/guide/guide-metrics' +import { BellIcon } from '@/components/vela/icons' + +export const WATCHED_SAYS = '放送開始を通知' const MARK_SAYS: Record = { 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/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 && ( + + {step === 'pick' && browser && ( + + )} + {step === 'webhook' && ( + setOpen(false)} + onAdd={onAddWebhook} + /> + )} + {step === 'browser' && browser && ( + setOpen(false)} + onAdd={browser.onAdd} + /> + )} + + + ) +} + +function KindPicker({ + here, + onPick, +}: { + here: string + onPick: (step: Step) => void +}) { + return ( + <> + +
    + } + name="Webhook" + says="Slack・Discord の 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..1aaf116a --- /dev/null +++ b/components/notifications/delivery-log.tsx @@ -0,0 +1,170 @@ +'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, + destinations, + now, +}: { + deliveries: NotificationDelivery[] + destinations: Pick[] + now?: number +}) { + const names = new Map(destinations.map(({ id, name }) => [id, name])) + + return ( +
    + +
      + {deliveries.map((delivery) => ( + + ))} +
    +
    + ) +} + +function DeliveryRow({ + delivery, + sentTo, + now, +}: { + delivery: NotificationDelivery + sentTo?: string + now?: number +}) { + const said = deliverySaid(delivery) + + return ( +
  • + + + + {deliveryMoment(delivery.occurredAt, now)} + + + {deliveryClock(delivery.occurredAt)} + + + + + {sentTo} + + + + {eventLabelOf(delivery.kind)} + + + + + {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..75b09ef9 --- /dev/null +++ b/components/notifications/destination-list.tsx @@ -0,0 +1,273 @@ +'use client' + +import { useState, useTransition } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + goingToo, + lastResultSaid, + ruleSetsGoingWith, + tailOf, + testSaid, + withWhy, + type DestinationRevision, + type NotificationDestination, + type NotificationRuleSet, + type NotificationWrite, + type Said, + type TestSending, + type Verdict, +} from '@/lib/notifications' +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 } from '@/components/notifications/edit-destination-dialog' +import { RemoveDialog } from '@/components/notifications/remove-button' +import { KindChip, RowMenu } from '@/components/notifications/row-menu' + +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' + +/** 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] items-center gap-x-2 px-4 py-3', + "upright:min-h-0 upright:gap-x-1 upright:px-3.5 upright:[grid-template-areas:'head_sw_more'_'last_last_last']", +) + +const TWO_LINES = "[grid-template-areas:'head_sw_more'_'last_sw_more']" + +/** A row with nothing to say under its name. */ +const ONE_LINE = "[grid-template-areas:'head_sw_more']" + +const SIGNED_OUT = signedOut('操作') + +function refusalOf(result: Exclude) { + return result.state === 'unauthenticated' ? SIGNED_OUT : result.message +} + +export function DestinationList({ + destinations, + ruleSets, + actions, + now, +}: { + destinations: NotificationDestination[] + ruleSets: Pick[] + actions: DestinationActions + now?: number +}) { + return ( +
      + {destinations.map((destination) => ( + name, + )} + actions={actions} + now={now} + /> + ))} +
    + ) +} + +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 ( + + {testing && } + {!testing && shown && ( + + )} + {(words || said) && ( + {words || (said && withWhy(said))} + )} + {tail && ( + + {(words || said) && '· '} + {tailOf(tail)} + + )} + + ) +} + +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 +}) { + 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, tail } = destination + const webhook = kind !== 'webPush' + const said = lastResultSaid(destination, now) + const bare = !said && !tested && !testing + + 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} + + + {tail && ( + + {tailOf(tail)} + + )} + + + void toggle(next)} + className="mr-1 [grid-area:sw] upright:mr-0.5" + /> + 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 new file mode 100644 index 00000000..68ed0065 --- /dev/null +++ b/components/notifications/edit-destination-dialog.tsx @@ -0,0 +1,162 @@ +'use client' + +import { useId, useState, useTransition } from 'react' + +import { signedOut } from '@/lib/signed-out' +import { + KIND_LABEL, + nameFits, + readAddress, + tailOf, + type DestinationRevision, + type NotificationDestination, + type NotificationWrite, +} from '@/lib/notifications' +import { wordFor } from '@/lib/not-yet-in-this-build' +import { useTellingOfTheGone } from '@/hooks/useTellingOfTheGone' +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' + +const SIGNED_OUT = signedOut('変更') + +export function EditDestinationDialog({ + destination, + open, + onOpenChange, + onRevise, +}: { + destination: NotificationDestination + open: boolean + onOpenChange: (open: boolean) => void + onRevise: ( + id: string, + revision: DestinationRevision, + ) => Promise +}) { + return ( + + + {open && ( + onOpenChange(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 tellOfTheGone = useTellingOfTheGone() + 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 + } + + tellOfTheGone(result) + 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..6465179a --- /dev/null +++ b/components/notifications/notice-dialog.tsx @@ -0,0 +1,97 @@ +'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, in the middle as every dialog has them; stacked the width of the sheet on a phone, the main one on top. */ +export function NoticeDialogFooter({ children }: { children: ReactNode }) { + return ( + + {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..65cd7e7b --- /dev/null +++ b/components/notifications/notifications-page.tsx @@ -0,0 +1,208 @@ +'use client' + +import { useState, type ReactNode } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + deliveriesShown, + narrowedTo, + type LeadMinutes, + type NotificationsScreen, + type NotificationWrite, + type WebhookDraft, +} 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 BrowserChoice, +} 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 NotificationActions + extends DestinationActions, RuleSetActions { + onAddWebhook: (draft: WebhookDraft) => Promise + onSettleLead: (lead: LeadMinutes) => Promise +} + +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, + browser, + now, +}: { + screen: NotificationsScreen + actions: NotificationActions + /** This browser as a destination, where it can be one. */ + browser?: BrowserChoice + /** The present held still, for a picture. */ + now?: number +}) { + 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) => { + 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.publicOriginKnown && ( + + {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..c26425c2 --- /dev/null +++ b/components/notifications/notify-only-row.tsx @@ -0,0 +1,100 @@ +'use client' + +import { useTransition } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + watchLine, + type NotificationWrite, + 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 { + PICKING_GRID, + ROW_GRID, + ROW_GROUND, + ROW_LINE, + RowTimes, +} from '@/components/reservations/reservation-row' +import { NotifyBell } from '@/components/notifications/programme-notice' + +export const NOTIFY_ONLY = '通知' + +const SIGNED_OUT = signedOut('操作') + +/** 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}` + } + + 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. */ +export function NotifyOnlyRow({ + watch, + nth, + picking = false, + onCancel, +}: { + watch: WatchedProgramme + nth: number + /** While reservations are being picked the row keeps their columns, with nothing to check. */ + picking?: boolean + onCancel: (id: string) => Promise +}) { + const [pending, startTransition] = useTransition() + const say = useToast() + + return ( +
  • +
    + {picking &&
    +
  • + ) +} 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..ce863077 --- /dev/null +++ b/components/notifications/programme-notice.tsx @@ -0,0 +1,244 @@ +'use client' + +import { useId, useState, useTransition } from 'react' + +import { cn } from '@/lib/utils' +import { signedOut } from '@/lib/signed-out' +import { + leadChipWords, + leadToastWords, + toggled, + type LeadMinutes, + type NotificationWrite, + type Noticing, + type ProgrammeWatch, + type WatchDraft, + type WatchOffer, + type WatchWrite, +} from '@/lib/notifications' +import { Button } from '@/components/ui/button' +import { Dialog } from '@/components/ui/dialog' +import { InlineAlert } from '@/components/vela/banner' +import { BellIcon, BellOffIcon } from '@/components/vela/icons' +import { useToast } from '@/components/vela/toast' +import { LeadChoice } from '@/components/notifications/lead-choice' +import { + NoticeDialogContent, + NoticeDialogFooter, + NoticeDialogHeader, + NoticeGroupLabel, +} from '@/components/notifications/notice-dialog' +import { PickChip, PickChips } from '@/components/notifications/pick-chip' + +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: opens a small dialog that 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. Nothing where there is neither a notice nor anywhere to send one. */ +export function NotifyStartButton({ + programmeId, + watch, + noticing, + className, +}: { + programmeId: string + watch?: ProgrammeWatch + noticing: Noticing + className?: string +}) { + const [asking, setAsking] = useState(false) + const [pending, startTransition] = useTransition() + const say = useToast() + + const unwatch = (watchId: string) => + startTransition(async () => { + const result = await noticing.onUnwatch(watchId) + + if (result.state !== 'ok') { + say({ text: refusalOf(result) }) + } + }) + + const ask = async (draft: WatchDraft) => { + const result = await noticing.onWatch(programmeId, draft) + + if (result.state === 'ok') { + const asked = result.watch + + say({ + text: leadToastWords(asked.leadMinutes), + action: { label: '取り消す', onPress: () => unwatch(asked.id) }, + }) + } + + return result + } + + if (watch) { + return ( + + ) + } + + if (!noticing.offer) { + return null + } + + return ( + <> + + + + {asking && ( + setAsking(false)} + /> + )} + + + + ) +} + +function AskForm({ + offer, + onAsk, + onClose, +}: { + offer: WatchOffer + onAsk: (draft: WatchDraft) => Promise + onClose: () => void +}) { + 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 ( + <> + +
    +
    + 何分前 + +
    +
    + 送り先 + + {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 ( + + + ) +} + +/** 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..21ec2c80 --- /dev/null +++ b/components/notifications/remove-button.tsx @@ -0,0 +1,138 @@ +'use client' + +import { useState, useTransition } from 'react' + +import { signedOut } from '@/lib/signed-out' +import type { NotificationWrite } from '@/lib/notifications' +import { useTellingOfTheGone } from '@/hooks/useTellingOfTheGone' +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('削除') + +/** 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, + onRemoved, +}: { + what: '送り先' | 'ルールセット' + name: string + also?: string + open: boolean + onOpenChange: (open: boolean) => void + onRemove: () => Promise + onRemoved?: () => void +}) { + const [refusal, setRefusal] = useState() + const [pending, startTransition] = useTransition() + const tellOfTheGone = useTellingOfTheGone() + + const remove = () => + startTransition(async () => { + setRefusal(undefined) + + const result = await onRemove() + + if (result.state === 'ok') { + onOpenChange(false) + onRemoved?.() + + return + } + + tellOfTheGone(result) + setRefusal( + result.state === 'unauthenticated' ? SIGNED_OUT : result.message, + ) + }) + + return ( + { + setRefusal(undefined) + onOpenChange(next) + }} + > + + + この{what}を削除します + + {name} + {also && {also}} + 元に戻せません。 + + + + {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 ( + <> + + + + ) +} 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 new file mode 100644 index 00000000..b8689892 --- /dev/null +++ b/components/notifications/rule-set-dialog.tsx @@ -0,0 +1,221 @@ +'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 { useTellingOfTheGone } from '@/hooks/useTellingOfTheGone' +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: [], + 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. */ +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.destinations) + const [refusal, setRefusal] = useState() + const [pending, startTransition] = useTransition() + const tellOfTheGone = useTellingOfTheGone() + 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, + destinations: sendTo, + }) + + if (result.state === 'ok') { + onClose() + + return + } + + tellOfTheGone(result) + 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}} + +
    + + {ruleSet && onRemove && ( + + )} + + + + + ) +} diff --git a/components/notifications/rule-set-list.tsx b/components/notifications/rule-set-list.tsx new file mode 100644 index 00000000..2777eb55 --- /dev/null +++ b/components/notifications/rule-set-list.tsx @@ -0,0 +1,207 @@ +'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 { useToast } from '@/components/vela/toast' +import { GROUP_ROW } from '@/components/notifications/destination-list' +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 { + onAddRuleSet: (draft: RuleSetDraft) => Promise + onReviseRuleSet: ( + id: string, + draft: RuleSetDraft, + ) => Promise + onToggleRuleSet: (id: string, enabled: boolean) => Promise + onRemoveRuleSet: (id: string) => Promise +} + +const SIGNED_OUT = signedOut('操作') + +/** 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_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. */ +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 [removing, setRemoving] = useState(false) + 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 ( +
  • + + + {name} + + + + {eventsSummary(ruleSet.events)} + + + {sendsTo.map((destination) => ( + + {destination} + + ))} + + + void toggle(next)} + className="mr-1 [grid-area:sw] upright:mr-0.5" + /> + setRemoving(true)} + /> + 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/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/components/search/hit-detail.tsx b/components/search/hit-detail.tsx index 4d9b80da..1cdb3db3 100644 --- a/components/search/hit-detail.tsx +++ b/components/search/hit-detail.tsx @@ -5,6 +5,7 @@ import Link from 'next/link' import { SPAN_DASH } from '@/lib/format' import { newRuleHref, seriesTermsOf } from '@/lib/rules' +import type { Noticing } from '@/lib/notifications' import type { SearchHit } from '@/repository/search' import type { ReservationWrite } from '@/repository/reservations' import { Badge } from '@/components/ui/badge' @@ -14,17 +15,23 @@ import { ChannelMark } from '@/components/vela/channel-mark' import { ChevronRightIcon } from '@/components/vela/icons' import { ReservationArea } from '@/components/guide/reservation-area' import { ProgramDescription } from '@/components/guide/program-description' +import { + NotifyLeadChip, + NotifyStartButton, +} from '@/components/notifications/programme-notice' import { marked } from '@/components/search/hit-parts' -/** A hit beside the list on a phone held on its side: its title, when and where it is on, its genre and description, and the reservation, as the guide's detail lays them; the whole of it is a press away. */ +/** A hit beside the list on a phone held on its side: its title, when and where it is on, its genre and description, the reservation and, while it has not started, the notice of its start, as the guide's detail lays them; the whole of it is a press away. */ export function HitDetail({ hit, words, onReserve, + noticing, }: { hit: SearchHit words: readonly string[] onReserve?: (programmeId: string) => Promise + noticing?: Noticing }) { const series = hit.channelId ? seriesTermsOf(hit.title, hit.channelId) @@ -55,6 +62,7 @@ export function HitDetail({ 予約済み )} + {hit.watch && }
    {hit.description && (
    @@ -67,6 +75,16 @@ export function HitDetail({ programmeId={hit.id} seriesHref={series ? newRuleHref(series) : undefined} onReserve={onReserve} + notice={ + hit.ahead && + noticing && ( + + ) + } /> )} + + +
    + + ) +} + +const meta = { + title: 'Components/番組と局/単発の通知', + component: DetailWithTheNotice, + parameters: { layout: 'centered' }, + args: { watching: false }, + decorators: [ + (Story) => ( + + + + ), + ], +} satisfies Meta + +export default meta + +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() { + 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} +

    + +
    + ))} +
    + ) +} + +/** Two single notices the way the list of reservations shows them among its rows. */ +function ReservationRows() { + return ( +
      + {[WATCHED_DOCUMENTARY, WATCHED_FOOTBALL].map((watch, nth) => ( + + ))} +
    + ) +} + +async function theAskForm() { + return within(await screen.findByRole('dialog', { name: NOTIFY_START })) +} + +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.getByText('開始 3 分前に通知')).toBeVisible() + }, +} + +export const 送り先が無いとボタンは出ない: Story = { + args: { nowhere: true }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await expect(canvas.getByRole('button', { name: '録画予約' })).toBeVisible() + await expect( + canvas.queryByRole('button', { name: NOTIFY_START }), + ).not.toBeInTheDocument() + }, +} + +export const 押すと分と送り先を選ぶ面が開く: Story = { + play: async ({ canvasElement }) => { + await userEvent.click( + within(canvasElement).getByRole('button', { name: NOTIFY_START }), + ) + + const form = await theAskForm() + const leads = within(form.getByRole('group', { name: '何分前' })) + + await expect(leads.getByRole('button', { name: '3 分前' })).toHaveAttribute( + 'aria-pressed', + 'true', + ) + + const to = within(form.getByRole('group', { name: '送り先' })) + + for (const destination of DESTINATIONS) { + await expect( + to.getByRole('button', { name: destination.name }), + ).toHaveAttribute('aria-pressed', 'true') + } + }, +} + +export const 送り先を全部外すと頼めない: Story = { + play: async ({ canvasElement }) => { + await userEvent.click( + within(canvasElement).getByRole('button', { name: NOTIFY_START }), + ) + + const form = await theAskForm() + const to = within(form.getByRole('group', { name: '送り先' })) + + for (const destination of DESTINATIONS) { + await userEvent.click(to.getByRole('button', { name: destination.name })) + } + + await expect(form.getByRole('button', { name: '通知する' })).toBeDisabled() + }, +} + +export const 選んだ分と送り先で頼む: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + asked.mockClear() + + await userEvent.click(canvas.getByRole('button', { name: NOTIFY_START })) + + const form = await theAskForm() + + await userEvent.click( + within(form.getByRole('group', { name: '何分前' })).getByRole('button', { + name: '10 分前', + }), + ) + await userEvent.click( + within(form.getByRole('group', { name: '送り先' })).getByRole('button', { + name: 'Discord の通知部屋', + }), + ) + await userEvent.click(form.getByRole('button', { name: '通知する' })) + + await waitFor(() => + expect(asked).toHaveBeenCalledWith(PROGRAMME, { + leadMinutes: 10, + destinations: ['dest-slack', 'dest-ipad'], + }), + ) + await expect( + await screen.findByText('開始の 10 分前に通知します'), + ).toBeVisible() + await expect(canvas.getByText('開始 10 分前に通知')).toBeVisible() + await expect( + canvas.getByRole('button', { name: STOP_NOTIFYING }), + ).toBeVisible() + }, +} + +export const 知らせから取り消す: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('button', { name: NOTIFY_START })) + await userEvent.click( + (await theAskForm()).getByRole('button', { name: '通知する' }), + ) + + await expect( + await screen.findByText('開始の 3 分前に通知します'), + ).toBeVisible() + + await userEvent.click(screen.getByRole('button', { name: '取り消す' })) + + await waitFor(() => + expect(canvas.getByRole('button', { name: NOTIFY_START })).toBeVisible(), + ) + await expect( + canvas.queryByText('開始 3 分前に通知'), + ).not.toBeInTheDocument() + }, +} + +export const 断られると面の中に理由が出る: Story = { + args: { refused: true }, + play: async ({ canvasElement }) => { + await userEvent.click( + within(canvasElement).getByRole('button', { name: NOTIFY_START }), + ) + + const form = await theAskForm() + + await userEvent.click(form.getByRole('button', { name: '通知する' })) + + await expect(await form.findByText(ALREADY_SET)).toBeVisible() + await expect(form.getByRole('button', { name: '通知する' })).toBeEnabled() + }, +} + +export const 取り消すボタンで取り消す: Story = { + args: { watching: true }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('button', { name: STOP_NOTIFYING })) + + await waitFor(() => + expect(canvas.getByRole('button', { name: NOTIFY_START })).toBeVisible(), + ) + }, +} + +export const 番組表のベル: Story = { + render: () => , + play: async ({ canvasElement }) => { + await expect( + within(canvasElement).getAllByText('放送開始を通知'), + ).toHaveLength(2) + }, +} + +export const 予約一覧の行: Story = { + render: () => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await afterTheArrival(canvasElement) + await expect(canvas.getAllByText(NOTIFY_ONLY)).toHaveLength(2) + await expect( + canvas.getByText('みなと総合1 · 3 分前 · 家の Slack・iPad の Safari'), + ).toBeVisible() + await expect( + canvas.getByText('第一テレビ · 5 分前 · 家の Slack'), + ).toBeVisible() + }, +} + +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), + ) + await expect( + await screen.findByText( + '通知を取り消しました サッカー中継 湾岸カップ 準決勝', + ), + ).toBeVisible() + }, +} + +export const 予約一覧の行_電話: Story = { + parameters: { screen: PHONE, coarse: true, layout: 'fullscreen' }, + render: () => , + play: async ({ canvasElement }) => { + await expect(within(canvasElement).getAllByText(NOTIFY_ONLY)).toHaveLength( + 2, + ) + }, +} + +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() + }, +} + +export const 電話で頼む面: Story = { + parameters: { screen: PHONE, coarse: true, layout: 'fullscreen' }, + play: async ({ canvasElement }) => { + await userEvent.click( + within(canvasElement).getByRole('button', { name: NOTIFY_START }), + ) + + await expect( + (await theAskForm()).getByRole('button', { name: '通知する' }), + ).toBeEnabled() + }, +} diff --git a/stories/fixtures/notifications.ts b/stories/fixtures/notifications.ts new file mode 100644 index 00000000..83e46fc3 --- /dev/null +++ b/stories/fixtures/notifications.ts @@ -0,0 +1,173 @@ +import type { + NotificationDelivery, + NotificationDestination, + NotificationRuleSet, + NotificationsScreen, + WatchedProgramme, +} from '@/lib/notifications' + +export const NOTIFICATIONS_NOW = Date.parse('2026-11-09T12:30:00Z') + +export const HOME_SLACK: NotificationDestination = { + id: 'dest-slack', + name: '家の Slack', + kind: 'slack', + tail: 'a1b2', + enabled: true, + readable: true, + lastResultAt: '2026-11-09T12:03:00Z', +} + +export const DISCORD_ROOM: NotificationDestination = { + id: 'dest-discord', + name: 'Discord の通知部屋', + kind: 'discord', + tail: '9f3e', + enabled: true, + readable: true, + lastResultAt: '2026-11-09T11:58:00Z', + lastFailure: 'timedOut', +} + +export const IPAD_SAFARI: NotificationDestination = { + id: 'dest-ipad', + name: 'iPad の Safari', + kind: 'webPush', + enabled: true, + readable: true, + lastResultAt: '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', + 'qualityIncidentDetected', + 'deviceDisconnected', + ], + destinations: [HOME_SLACK.id, IPAD_SAFARI.id], +} + +export const RULE_SETS: NotificationRuleSet[] = [ + ONLY_WHEN_TROUBLED, + { + id: 'rule-record', + name: '録画の記録', + enabled: true, + events: ['recordingStarted', 'recordingCompleted', 'encodeCompleted'], + destinations: [DISCORD_ROOM.id], + }, + { + id: 'rule-away', + name: '留守の週', + enabled: false, + events: [ + 'recordingStarted', + 'recordingCompleted', + 'recordingTruncated', + 'recordingFailed', + 'encodeStarted', + 'encodeCompleted', + 'encodeFailed', + 'qualityIncidentDetected', + 'qualityIncidentResolved', + ], + destinations: [HOME_SLACK.id, DISCORD_ROOM.id], + }, +] + +function delivery( + id: string, + occurredAt: string, + kind: NotificationDelivery['kind'], + to: NotificationDestination, + state: NotificationDelivery['state'] = 'sent', + failure?: NotificationDelivery['failure'], +): NotificationDelivery { + return { id, kind, occurredAt, destinationId: to.id, state, failure } +} + +export const DELIVERIES: NotificationDelivery[] = [ + 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', + DISCORD_ROOM, + 'failed', + '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', + HOME_SLACK, + 'givenUp', + 'rejected', + ), + delivery( + 'del-8', + '2026-11-09T09:12:00Z', + 'qualityIncidentDetected', + IPAD_SAFARI, + ), +] + +export const NOTIFICATIONS_SCREEN: NotificationsScreen = { + settings: { notifyLeadMinutes: 3, publicOriginKnown: false }, + destinations: DESTINATIONS, + ruleSets: RULE_SETS, + deliveries: DELIVERIES, +} + +export const EMPTY_NOTIFICATIONS_SCREEN: NotificationsScreen = { + settings: { notifyLeadMinutes: 3, publicOriginKnown: 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, + destinationNames: [HOME_SLACK.name, IPAD_SAFARI.name], +} + +export const WATCHED_FOOTBALL: WatchedProgramme = { + id: 'watch-football', + title: 'サッカー中継 湾岸カップ 準決勝', + channelName: '第一テレビ', + startAt: '2026-11-09T13:00:00Z', + endAt: '2026-11-09T14:30:00Z', + leadMinutes: 5, + destinationNames: [HOME_SLACK.name], +} diff --git a/stories/foundations/Icons.stories.tsx b/stories/foundations/Icons.stories.tsx index 3c73c511..059fd6e7 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/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) + }, +} diff --git a/stories/screens/Notifications.stories.tsx b/stories/screens/Notifications.stories.tsx new file mode 100644 index 00000000..3c6cf383 --- /dev/null +++ b/stories/screens/Notifications.stories.tsx @@ -0,0 +1,1311 @@ +import { useState, type ComponentProps } from 'react' +import type { Meta, StoryObj } from '@storybook/nextjs' +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, + type BrowserChoice, +} 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 BROWSER: BrowserChoice = { + here: 'Windows の Chrome', + permission: 'default', + onAdd: addBrowser, +} + +const ON_A_PHONE: BrowserChoice = { ...BROWSER, here: 'iPhone の Safari' } + +const toggleDestination = fn( + async () => OK, +) + +const testDestination = fn( + async (id): Promise => + id === DISCORD_ROOM.id + ? { state: 'ok', delivered: false, failure: 'timedOut' } + : { 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 ACTIONS: NotificationActions = { + onAddWebhook: addWebhook, + onToggleDestination: toggleDestination, + onTestDestination: testDestination, + onReviseDestination: reviseDestination, + onRemoveDestination: removeDestination, + onAddRuleSet: addRuleSet, + onReviseRuleSet: reviseRuleSet, + onToggleRuleSet: toggleRuleSet, + onRemoveRuleSet: removeRuleSet, + onSettleLead: settleLead, +} + +const meta = { + title: 'Screens/設定/管理/通知', + component: NotificationsView, + parameters: { + nextjs: { + appDirectory: true, + navigation: { pathname: '/settings/notifications' }, + }, + layout: 'fullscreen', + }, + args: { + screen: NOTIFICATIONS_SCREEN, + actions: ACTIONS, + browser: BROWSER, + now: NOTIFICATIONS_NOW, + }, + decorators: [inTheSettings], +} satisfies 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 openTheAdding(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 openTheAdding(canvasElement) + + await userEvent.click( + within(dialog).getByRole('button', { name: /Slack・Discord/ }), + ) + + return dialog +} + +async function openTheBrowserForm(canvasElement: HTMLElement) { + const dialog = await openTheAdding(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: /テスト送信|変更|削除/ }), + ).toBeNull() + await expect( + destinations + .getAllByText(/^(Slack|Discord|Web Push)$/) + .map((chip) => chip.dataset.kind), + ).toEqual(['slack', 'discord', 'webPush']) + 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: { notifyLeadMinutes: 3, publicOriginKnown: 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 = { + args: { + screen: { + ...NOTIFICATIONS_SCREEN, + destinations: [ + ...DESTINATIONS, + { + ...HOME_SLACK, + id: 'dest-slack-2', + name: '実家のリビングの Slack のお知らせ用チャンネル', + tail: 'c3d4', + enabled: false, + lastResultAt: '2026-11-08T12:03:00Z', + lastFailure: '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, + 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 }, + }, + 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) + + 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( + 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( + within(canvasElement).getByRole('button', { + name: 'iPad の Safari の操作', + }), + ) + + const menu = within(await screen.findByRole('menu')) + + await expect( + menu.getAllByRole('menuitem').map((item) => item.textContent), + ).toEqual(['テスト送信', '削除']) + }, +} + +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()) + }, +} + +const NOT_REACHED_REVISING = + '送り先を変更できませんでした。時間をおいてからもう一度お試しください。' + +const NOT_REACHED_REMOVING = + '送り先を削除できませんでした。時間をおいてからもう一度お試しください。' + +const LEAD_NOT_SETTLED = + '単発の通知の既定を変更できませんでした。時間をおいてからもう一度お試しください。' + +const TESTED_TOO_SOON = + '続けてテスト送信はできません。1 分ほどおいてからお試しください。' + +const RULE_SETS_FULL = 'ルールセットは 20 本までのため、追加できませんでした。' + +const CHOSEN_DESTINATION_GONE = + '選んだ送り先が残っていないため、変更できませんでした。' + +const RULE_SET_NOT_REMOVED = + 'ルールセットを削除できませんでした。時間をおいてからもう一度お試しください。' + +/** An action that turns away whatever it is asked, in these words. */ +function turnedAway(message: string) { + return async (): Promise => ({ + state: 'rejected', + message, + }) +} + +async function aToastSays(words: string) { + const said = await screen.findByText(words) + + await expect(said.closest('[data-slot="toast"]')).toBeVisible() +} + +export const 送り先の切り替えを断られる: Story = { + args: { + actions: { + ...ACTIONS, + onToggleDestination: turnedAway(NOT_REACHED_REVISING), + }, + }, + play: async ({ canvasElement }) => { + const slack = within(canvasElement).getByRole('switch', { + name: '家の Slack を有効にする', + }) + + await expect(slack).toBeChecked() + + await userEvent.click(slack) + + await aToastSays(NOT_REACHED_REVISING) + await waitFor(() => expect(slack).toBeChecked()) + }, +} + +export const 単発の通知の既定を断られる: Story = { + args: { + actions: { ...ACTIONS, onSettleLead: turnedAway(LEAD_NOT_SETTLED) }, + }, + play: async ({ canvasElement }) => { + const lead = within( + within(canvasElement).getByRole('group', { name: '単発の通知の既定' }), + ) + + await userEvent.click(lead.getByRole('button', { name: '5 分前' })) + + await aToastSays(LEAD_NOT_SETTLED) + await waitFor(() => + expect(lead.getByRole('button', { name: '3 分前' })).toHaveAttribute( + 'aria-pressed', + 'true', + ), + ) + await expect(lead.getByRole('button', { name: '5 分前' })).toHaveAttribute( + 'aria-pressed', + 'false', + ) + }, +} + +export const テスト送信を断られる: Story = { + args: { + actions: { + ...ACTIONS, + onTestDestination: async () => ({ + state: 'rejected', + message: TESTED_TOO_SOON, + }), + }, + }, + play: async ({ canvasElement }) => { + await fromTheMenu(canvasElement, '家の Slack', 'テスト送信') + + await aToastSays(TESTED_TOO_SOON) + await expect( + within( + within(canvasElement).getByRole('list', { name: '送り先' }), + ).queryByText(/^テスト送信 · /), + ).toBeNull() + }, +} + +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', + ) + }, +} + +export const 配送を送り先で絞る: Story = { + 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 openTheAdding(canvasElement)) + + await expect( + dialog.getByRole('button', { name: /Slack・Discord の URL に送ります/ }), + ).toBeVisible() + await expect( + dialog.getByText('Windows の Chrome に通知を出します'), + ).toBeVisible() + }, +} + +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)) + 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 送り先を追加_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: { browser: { ...BROWSER, 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 = { + 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: { + ...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() + await expect(dialog.getByLabelText('名前')).toHaveValue('家の Slack') + await expect(dialog.getByLabelText('Webhook の URL')).toHaveValue( + SLACK_ADDRESS, + ) + await expect(dialog.getByRole('button', { name: '追加' })).toBeEnabled() + }, +} + +export const 送り先を変更: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await fromTheMenu(canvasElement, '家の 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 fromTheMenu(canvasElement, '家の 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 = { + args: { + actions: { + ...ACTIONS, + onReviseDestination: turnedAway('この URL は受け付けられません。'), + }, + }, + play: async ({ canvasElement }) => { + await fromTheMenu(canvasElement, '家の Slack', '変更') + + const dialog = within( + await screen.findByRole('dialog', { name: '送り先を変更' }), + ) + + await userEvent.type(dialog.getByLabelText('名前'), '(居間)') + await userEvent.type( + dialog.getByLabelText('Webhook の URL'), + DISCORD_ADDRESS, + ) + await userEvent.click(dialog.getByRole('switch', { name: '有効' })) + await userEvent.click(dialog.getByRole('button', { name: '保存' })) + + await expect( + await dialog.findByText('この URL は受け付けられません。'), + ).toBeVisible() + await expect(dialog.getByLabelText('名前')).toHaveValue('家の Slack(居間)') + await expect(dialog.getByLabelText('Webhook の URL')).toHaveValue( + DISCORD_ADDRESS, + ) + await expect(dialog.getByRole('switch', { name: '有効' })).not.toBeChecked() + await expect(dialog.getByRole('button', { name: '保存' })).toBeEnabled() + }, +} + +export const 送り先の削除を断られる: Story = { + args: { + actions: { + ...ACTIONS, + onRemoveDestination: turnedAway(NOT_REACHED_REMOVING), + }, + }, + play: async ({ canvasElement }) => { + await fromTheMenu(canvasElement, 'Discord の通知部屋', '削除') + + const asked = within(await screen.findByRole('alertdialog')) + + await userEvent.click(asked.getByRole('button', { name: '削除する' })) + + await expect(await asked.findByText(NOT_REACHED_REMOVING)).toBeVisible() + await expect(asked.getByRole('button', { name: '削除する' })).toBeEnabled() + + await userEvent.click(asked.getByRole('button', { name: 'キャンセル' })) + + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()) + await expect( + within(canvasElement).getByRole('button', { + name: 'Discord の通知部屋 の操作', + }), + ).toBeVisible() + }, +} + +export const 送り先を削除: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + removeDestination.mockClear() + + await fromTheMenu(canvasElement, 'Discord の通知部屋', '削除') + + const asked = within(await screen.findByRole('alertdialog')) + + await expect(asked.getByText('この送り先を削除します')).toBeVisible() + await expect(asked.getByText('Discord の通知部屋')).toBeVisible() + await expect( + asked.getByText('ルールセット「録画の記録」も削除します。'), + ).toBeVisible() + + await userEvent.click(asked.getByRole('button', { name: '削除する' })) + + await waitFor(() => + expect(removeDestination).toHaveBeenCalledWith(DISCORD_ROOM.id), + ) + }, +} + +const DESTINATION_GONE = 'この送り先は残っていないため、変更できませんでした。' + +const DESTINATION_GONE_REMOVING = + 'この送り先は残っていないため、削除できませんでした。' + +const RULE_SET_GONE = + 'このルールセットは残っていないため、変更できませんでした。' + +const RULE_SET_GONE_REMOVING = + 'このルールセットは残っていないため、削除できませんでした。' + +/** The page as it is when what is changed or removed was removed on another screen: the write is refused and the row leaves the page. */ +function RemovedElsewhere(props: ComponentProps) { + const [held, setHeld] = useState(props.screen) + + const refusedAs = + (message: string) => + async (id: string): Promise => { + setHeld((was) => ({ + ...was, + destinations: was.destinations.filter((one) => one.id !== id), + ruleSets: was.ruleSets.filter((one) => one.id !== id), + })) + + return { state: 'rejected', message, gone: true } + } + + return ( + + ) +} + +/** The refusal stands whole in the toast, the dialog that asked having left. */ +async function theToastSays(words: string) { + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()) + + const said = await screen.findByText(words) + + await expect(said.closest('[data-slot="toast"]')).toBeVisible() + await expect(said.scrollWidth).toBeLessThanOrEqual(said.clientWidth) +} + +export const よそで消された送り先を保存する: Story = { + render: (args) => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await fromTheMenu(canvasElement, '家の Slack', '変更') + + const dialog = within( + await screen.findByRole('dialog', { name: '送り先を変更' }), + ) + + await userEvent.type(dialog.getByLabelText('名前'), '(居間)') + await userEvent.click(dialog.getByRole('button', { name: '保存' })) + + await theToastSays(DESTINATION_GONE) + await expect( + within(canvas.getByRole('list', { name: '送り先' })).getAllByRole( + 'listitem', + ), + ).toHaveLength(2) + }, +} + +export const よそで消された送り先を削除する: Story = { + render: (args) => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await fromTheMenu(canvasElement, 'Discord の通知部屋', '削除') + await userEvent.click( + within(await screen.findByRole('alertdialog')).getByRole('button', { + name: '削除する', + }), + ) + + await theToastSays(DESTINATION_GONE_REMOVING) + await expect( + canvas.queryByRole('button', { name: 'Discord の通知部屋 の操作' }), + ).toBeNull() + }, +} + +export const よそで消されたルールセットを保存する: Story = { + render: (args) => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await fromTheMenu(canvasElement, '困ったときだけ', '変更') + + const dialog = within( + await screen.findByRole('dialog', { name: 'ルールセットを変更' }), + ) + + await userEvent.click( + within(dialog.getByRole('group', { name: '録画' })).getByRole('button', { + name: '開始', + }), + ) + await userEvent.click(dialog.getByRole('button', { name: '保存' })) + + await theToastSays(RULE_SET_GONE) + await expect( + canvas.queryByRole('button', { name: '困ったときだけ の操作' }), + ).toBeNull() + }, +} + +export const よそで消されたルールセットを削除する: Story = { + render: (args) => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await fromTheMenu(canvasElement, '困ったときだけ', '変更') + + const dialog = within( + await screen.findByRole('dialog', { name: 'ルールセットを変更' }), + ) + + await userEvent.click( + dialog.getByRole('button', { name: '困ったときだけ を削除' }), + ) + await userEvent.click( + within(await screen.findByRole('alertdialog')).getByRole('button', { + name: '削除する', + }), + ) + + await theToastSays(RULE_SET_GONE_REMOVING) + await expect( + canvas.queryByRole('button', { name: '困ったときだけ の操作' }), + ).toBeNull() + }, +} + +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) + + await fromTheMenu(canvasElement, '困ったときだけ', '変更') + + 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 fromTheMenu(canvasElement, '困ったときだけ', '変更') + + 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 = { + args: { + actions: { + ...ACTIONS, + onReviseRuleSet: turnedAway(CHOSEN_DESTINATION_GONE), + }, + }, + play: async ({ canvasElement }) => { + await fromTheMenu(canvasElement, '困ったときだけ', '変更') + + const dialog = within( + await screen.findByRole('dialog', { name: 'ルールセットを変更' }), + ) + const recording = within(dialog.getByRole('group', { name: '録画' })) + const to = within(dialog.getByRole('group', { name: '送り先' })) + + await userEvent.type(dialog.getByLabelText('名前'), '(夜)') + await userEvent.click(recording.getByRole('button', { name: '開始' })) + await userEvent.click( + to.getByRole('button', { name: 'Discord の通知部屋' }), + ) + await userEvent.click(dialog.getByRole('button', { name: '保存' })) + + await expect(await dialog.findByText(CHOSEN_DESTINATION_GONE)).toBeVisible() + await expect(dialog.getByLabelText('名前')).toHaveValue( + '困ったときだけ(夜)', + ) + await expect( + recording.getByRole('button', { name: '開始' }), + ).toHaveAttribute('aria-pressed', 'true') + await expect( + to.getByRole('button', { name: 'Discord の通知部屋' }), + ).toHaveAttribute('aria-pressed', 'true') + await expect(dialog.getByRole('button', { name: '保存' })).toBeEnabled() + }, +} + +export const ルールセットの削除を断られる: Story = { + args: { + actions: { + ...ACTIONS, + onRemoveRuleSet: turnedAway(RULE_SET_NOT_REMOVED), + }, + }, + play: async ({ canvasElement }) => { + await fromTheMenu(canvasElement, '困ったときだけ', '変更') + + const dialog = within( + await screen.findByRole('dialog', { name: 'ルールセットを変更' }), + ) + + await userEvent.click( + dialog.getByRole('button', { name: '困ったときだけ を削除' }), + ) + + const asked = within(await screen.findByRole('alertdialog')) + + await userEvent.click(asked.getByRole('button', { name: '削除する' })) + + await expect(await asked.findByText(RULE_SET_NOT_REMOVED)).toBeVisible() + + await userEvent.click(asked.getByRole('button', { name: 'キャンセル' })) + + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()) + await expect( + within( + await screen.findByRole('dialog', { name: 'ルールセットを変更' }), + ).getByLabelText('名前'), + ).toHaveValue('困ったときだけ') + }, +} + +export const ルールセットの追加を断られる: Story = { + args: { + actions: { ...ACTIONS, onAddRuleSet: turnedAway(RULE_SETS_FULL) }, + }, + play: async ({ canvasElement }) => { + const ruleSets = within(canvasElement).getByRole('heading', { + name: 'ルールセット', + }).parentElement as HTMLElement + + await userEvent.click( + within(ruleSets).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 userEvent.type(dialog.getByLabelText('名前'), '夜中の失敗') + await userEvent.click(recording.getByRole('button', { name: '失敗' })) + await userEvent.click(to.getByRole('button', { name: '家の Slack' })) + await userEvent.click(dialog.getByRole('button', { name: '保存' })) + + await expect(await dialog.findByText(RULE_SETS_FULL)).toBeVisible() + await expect(dialog.getByLabelText('名前')).toHaveValue('夜中の失敗') + await expect( + recording.getByRole('button', { name: '失敗' }), + ).toHaveAttribute('aria-pressed', 'true') + await expect( + to.getByRole('button', { name: '家の Slack' }), + ).toHaveAttribute('aria-pressed', 'true') + }, +} + +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'], + destinations: [HOME_SLACK.id], + }), + ) + }, +} + +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.getByRole('button', { name: '困ったときだけ の操作' }), + ).toBeVisible() + }, +} + +export const 電話_送り先を追加: Story = { + parameters: { screen: PHONE, coarse: true }, + args: { browser: ON_A_PHONE }, + play: async ({ canvasElement }) => { + const dialog = await openTheAdding(canvasElement) + const sheet = dialog.getBoundingClientRect() + + await expect( + within(dialog).getByText('iPhone の Safari に通知を出します'), + ).toBeVisible() + await waitFor(() => + expect(Math.round(dialog.getBoundingClientRect().bottom)).toBe( + window.innerHeight, + ), + ) + await expect(Math.round(sheet.width)).toBe(window.innerWidth) + }, +} + +export const 電話_このブラウザ: Story = { + parameters: { screen: PHONE, coarse: true }, + args: { browser: ON_A_PHONE }, + 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 }) => { + await fromTheMenu(canvasElement, '録画の記録', '変更') + + const dialog = await screen.findByRole('dialog', { + name: 'ルールセットを変更', + }) + + await expect(within(dialog).getByLabelText('名前')).toHaveValue( + '録画の記録', + ) + await waitFor(() => + expect(Math.round(dialog.getBoundingClientRect().bottom)).toBe( + window.innerHeight, + ), + ) + }, +} + +const NEVER_SENT = { + ...HOME_SLACK, + id: 'dest-slack-new', + name: '新しい Slack', + tail: 'e5f6', + lastResultAt: undefined, + lastFailure: undefined, +} + +function neverSentRow(canvasElement: HTMLElement): HTMLElement { + return within(canvasElement) + .getByRole('list', { name: '送り先' }) + .querySelector(`[data-destination="${NEVER_SENT.id}"]`) as HTMLElement +} + +export const まだ送っていない送り先は名前が行の中央に立つ: Story = { + args: { + screen: { + ...NOTIFICATIONS_SCREEN, + destinations: [...DESTINATIONS, NEVER_SENT], + }, + }, + play: async ({ canvasElement }) => { + const row = neverSentRow(canvasElement) + const room = row.getBoundingClientRect() + const name = within(row).getByText(NEVER_SENT.name).getBoundingClientRect() + const flip = within(row).getByRole('switch').getBoundingClientRect() + + await expect( + Math.abs(name.top + name.height / 2 - (room.top + room.height / 2)), + ).toBeLessThanOrEqual(1) + await expect( + Math.abs(flip.top + flip.height / 2 - (room.top + room.height / 2)), + ).toBeLessThanOrEqual(1) + await expect(within(row).getAllByText('…e5f6')[0]).toBeVisible() + await expect(row.querySelector('[aria-live]')).not.toBeVisible() + }, +} + +export const 電話_まだ送っていない送り先: Story = { + args: { + screen: { + ...NOTIFICATIONS_SCREEN, + destinations: [...DESTINATIONS, NEVER_SENT], + }, + }, + parameters: { screen: PHONE, coarse: true }, + play: async ({ canvasElement }) => { + const row = neverSentRow(canvasElement) + const under = row.querySelector('[aria-live]')! + + await expect(under).toBeVisible() + await expect(under).toHaveTextContent('…e5f6') + await expect(under.querySelector('[data-slot="status-dot"]')).toBeNull() + }, +} diff --git a/stories/screens/ProgramDetail.stories.tsx b/stories/screens/ProgramDetail.stories.tsx index 0fffa429..322c7ab0 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,151 @@ 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')) + }, +} + +const NOTICE_GONE = 'この通知は残っていないため、取り消せませんでした。' + +export const 通知の取り消しを断られるとボタンは取り消すのまま残る: Story = { + args: { + detail: { + ...ahead, + program: { + ...ahead.program, + watch: { id: 'watch-told', leadMinutes: 10 }, + }, + }, + noticing: { + ...NOTICING, + onUnwatch: async (): Promise => ({ + state: 'rejected', + message: NOTICE_GONE, + }), + }, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await userEvent.click(canvas.getByRole('button', { name: STOP_NOTIFYING })) + + const said = await screen.findByText(NOTICE_GONE) + + await expect(said.closest('[data-slot="toast"]')).toBeVisible() + await waitFor(() => + expect( + canvas.getByRole('button', { name: STOP_NOTIFYING }), + ).toBeEnabled(), + ) + await expect(canvas.getByText('開始 10 分前に通知')).toBeVisible() + }, +} + +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, + ) + }, +} diff --git a/stories/screens/Reservations.stories.tsx b/stories/screens/Reservations.stories.tsx index a1ae7650..1a806fae 100644 --- a/stories/screens/Reservations.stories.tsx +++ b/stories/screens/Reservations.stories.tsx @@ -1,6 +1,11 @@ import type { Meta, StoryObj } from '@storybook/nextjs' -import { expect, screen, userEvent, waitFor, within } from 'storybook/test' +import { expect, fn, screen, userEvent, waitFor, within } from 'storybook/test' +import type { + NotificationWrite, + WaitingNotices, + WatchedProgramme, +} from '@/lib/notifications' import type { Reservation, ReservationBatch, @@ -19,6 +24,7 @@ import { SETTLED_RESERVATION_FIXTURES, } from '@/stories/fixtures/reservations' import { ReservationsView } from '@/components/reservations/reservations-page' +import { NOTIFY_ONLY } from '@/components/notifications/notify-only-row' import { afterTheArrival } from '@/stories/after-the-arrival' import { tipIn } from '@/stories/pills-in-a-column' import { inTheApp } from '@/stories/frames' @@ -1487,3 +1493,255 @@ export const 横向きの電話は予約の一覧と競合を左右に置き押 ) }, } + +const HARBOUR_AT_NIGHT: WatchedProgramme = { + id: 'watch-harbour', + title: 'ドキュメント 灯りの仕事「夜の港、最後の便まで」', + channelName: 'みなと総合1', + startAt: '2026-08-08T13:30:00.000Z', + endAt: '2026-08-08T14:15:00.000Z', + leadMinutes: 3, + destinationNames: ['家の Slack', 'iPad の Safari'], +} + +const BAY_CUP: WatchedProgramme = { + id: 'watch-cup', + title: 'サッカー中継 湾岸カップ 準決勝', + channelName: '第一テレビ', + startAt: '2026-08-09T10:00:00.000Z', + endAt: '2026-08-09T11:30:00.000Z', + leadMinutes: 0, + destinationNames: ['家の Slack'], +} + +const takenBack = fn<(id: string) => Promise>(async () => ({ + state: 'ok', +})) + +const NOTICES: WaitingNotices = { + watches: [BAY_CUP, HARBOUR_AT_NIGHT], + onCancel: takenBack, +} + +function watchRow(within_: HTMLElement, watch: WatchedProgramme): HTMLElement { + const row = within_.querySelector(`li[data-watch="${watch.id}"]`) + + if (!row) { + throw new Error(`${watch.title} has no row of its own`) + } + + return row +} + +function startsOf(list: HTMLElement): string[] { + return [...list.querySelectorAll('li')] + .filter((row) => row.parentElement?.closest('li') === null) + .map((row) => /\d{2}:\d{2}/.exec(row.textContent ?? '')?.[0] ?? '') +} + +export const 放送開始の通知は予約のあいだに開始の順で並ぶ: Story = { + args: { result: shown(RESERVATION_FIXTURES), notices: NOTICES }, + play: async ({ canvasElement }) => { + await afterTheArrival(canvasElement) + + const list = listOf(canvasElement) + const row = watchRow(list, HARBOUR_AT_NIGHT) + + await expect(list.querySelectorAll('li[data-watch]')).toHaveLength(2) + await expect(within(row).getByText(NOTIFY_ONLY)).toBeVisible() + await expect( + within(row).getByText( + 'みなと総合1 · 3 分前 · 家の Slack・iPad の Safari', + ), + ).toBeVisible() + await expect( + within(watchRow(list, BAY_CUP)).getByText( + '第一テレビ · 開始時 · 家の Slack', + ), + ).toBeVisible() + await expect(row.querySelector('[data-slot="row-chips"]')).toBeNull() + + const starts = startsOf(row.parentElement!) + const at = starts.indexOf('22:30') + + await expect(at).toBeGreaterThan(0) + await expect(starts[at - 1] <= '22:30').toBe(true) + await expect(starts[at + 1] >= '22:30').toBe(true) + + const middles = [...row.firstElementChild!.children].map((one) => { + const box = one.getBoundingClientRect() + + return Math.round(box.top + box.height / 2) + }) + + await expect(Math.max(...middles) - Math.min(...middles)).toBeLessThan(3) + }, +} + +export const 放送開始の通知は行のばつで取り消す: Story = { + args: { result: shown(RESERVATION_FIXTURES), notices: NOTICES }, + play: async ({ canvasElement }) => { + await afterTheArrival(canvasElement) + + takenBack.mockClear() + + await userEvent.click( + within(watchRow(listOf(canvasElement), BAY_CUP)).getByRole('button', { + name: `${BAY_CUP.title} の通知を取り消す`, + }), + ) + + await waitFor(() => expect(takenBack).toHaveBeenCalledWith(BAY_CUP.id)) + await expect( + await screen.findByText(`通知を取り消しました ${BAY_CUP.title}`), + ).toBeVisible() + }, +} + +const NOTICE_ALREADY_SENT = + 'この通知はもう済んでいるため、取り消せませんでした。' + +export const 放送開始の通知の取り消しを断られる: Story = { + args: { + result: shown(RESERVATION_FIXTURES), + notices: { + ...NOTICES, + onCancel: async () => ({ + state: 'rejected', + message: NOTICE_ALREADY_SENT, + }), + }, + }, + play: async ({ canvasElement }) => { + await afterTheArrival(canvasElement) + + const cancel = within(watchRow(listOf(canvasElement), BAY_CUP)).getByRole( + 'button', + { name: `${BAY_CUP.title} の通知を取り消す` }, + ) + + await userEvent.click(cancel) + + const said = await screen.findByText(NOTICE_ALREADY_SENT) + + await expect(said.closest('[data-slot="toast"]')).toBeVisible() + await waitFor(() => expect(cancel).toBeEnabled()) + await expect( + listOf(canvasElement).querySelectorAll('li[data-watch]'), + ).toHaveLength(2) + }, +} + +export const 放送開始の通知は選ぶ対象にならない: Story = { + args: { result: shown(RESERVATION_FIXTURES), notices: NOTICES }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await afterTheArrival(canvasElement) + await startPicking(canvas) + + const list = listOf(canvasElement) + const row = watchRow(list, HARBOUR_AT_NIGHT) + + await expect(within(row).queryByRole('checkbox')).toBeNull() + + const booked = list.querySelector('li[data-reservation]')! + const timeOf = (one: HTMLElement) => + [...one.querySelectorAll('*')] + .find((part) => /^\d{2}:\d{2}/.test(part.textContent ?? ''))! + .getBoundingClientRect().left + + await expect(Math.abs(timeOf(row) - timeOf(booked))).toBeLessThan(2) + }, +} + +export const 予約が無くても放送開始の通知は並ぶ: Story = { + args: { result: shown([]), notices: NOTICES }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement) + + await afterTheArrival(canvasElement) + + await expect( + canvas.queryByRole('heading', { name: '予約がありません' }), + ).toBeNull() + await expect( + listOf(canvasElement).querySelectorAll('li[data-watch]'), + ).toHaveLength(2) + await expect(canvas.queryByRole('button', { name: '選ぶ' })).toBeNull() + }, +} + +export const 番組変更だけに絞ると放送開始の通知は出ない: Story = { + args: { + result: shown( + EPG_DRIFT_FIXTURES.filter((one) => one.epg?.diverged), + { + total: EPG_DRIFT_FIXTURES.length, + drift: { diverged: 2, missing: 1 }, + filter: { epg: 'diverged' }, + }, + ), + notices: NOTICES, + }, + play: async ({ canvasElement }) => { + await afterTheArrival(canvasElement) + + await expect( + listOf(canvasElement).querySelectorAll('li[data-watch]'), + ).toHaveLength(0) + }, +} + +export const 電話の幅でも放送開始の通知は予約のあいだに並ぶ: Story = { + args: { result: shown(RESERVATION_FIXTURES), notices: NOTICES }, + parameters: { screen: PHONE, coarse: true }, + play: async ({ canvasElement }) => { + await afterTheArrival(canvasElement) + + const list = await waitFor(() => phoneList(canvasElement)) + const row = watchRow(list, HARBOUR_AT_NIGHT) + + await expect(list.querySelectorAll('li[data-watch]')).toHaveLength(2) + await expect(within(row).getByText(NOTIFY_ONLY)).toBeVisible() + await expect(row.previousElementSibling).not.toBeNull() + await expect(row.nextElementSibling).not.toBeNull() + await expect(row.getBoundingClientRect().right).toBeLessThanOrEqual( + window.innerWidth, + ) + + const takeBack = within(row).getByRole('button', { + name: `${HARBOUR_AT_NIGHT.title} の通知を取り消す`, + }) + + await expect(takeBack.getBoundingClientRect().width).toBeGreaterThanOrEqual( + 44, + ) + + takenBack.mockClear() + await userEvent.click(takeBack) + await waitFor(() => + expect(takenBack).toHaveBeenCalledWith(HARBOUR_AT_NIGHT.id), + ) + }, +} + +export const 横向きの電話でも放送開始の通知は一覧に並ぶ: Story = { + args: { result: shown(RESERVATION_FIXTURES), notices: NOTICES }, + parameters: { screen: { width: 844, height: 390 }, coarse: true }, + play: async ({ canvasElement }) => { + const pane = await waitFor(() => { + const found = + canvasElement.querySelector('[data-pane="list"]') + + expect(found).not.toBeNull() + + return found! + }) + + await expect(pane.querySelectorAll('li[data-watch]')).toHaveLength(2) + await expect( + within(watchRow(pane, BAY_CUP)).getByText(NOTIFY_ONLY), + ).toBeVisible() + }, +} diff --git a/stories/screens/Search.stories.tsx b/stories/screens/Search.stories.tsx index df9c747f..39bde411 100644 --- a/stories/screens/Search.stories.tsx +++ b/stories/screens/Search.stories.tsx @@ -5,6 +5,7 @@ import { getRouter } from '@storybook/nextjs/navigation.mock' import { expect, fireEvent, + fn, screen, userEvent, waitFor, @@ -13,10 +14,17 @@ import { import type { SearchCondition, + SearchHit, SearchHits, SearchResult, } from '@/repository/search' import type { GuideChannel } from '@/repository/programs' +import type { + NotificationWrite, + Noticing, + WatchDraft, + WatchWrite, +} from '@/lib/notifications' import { SEARCH_MOST_CHANNELS, narrowsAnything, @@ -28,6 +36,10 @@ import { SEARCH_HIT_FIXTURES, } from '@/repository/search.fixtures' import { SearchView } from '@/components/search/search-page' +import { + NOTIFY_START, + STOP_NOTIFYING, +} from '@/components/notifications/programme-notice' import { afterTheArrival } from '@/stories/after-the-arrival' import { standsOnAGround } from '@/stories/stands-on-a-ground' import { inTheApp } from '@/stories/frames' @@ -1600,3 +1612,131 @@ export const 横向きの電話は結果と詳細を左右に置き条件の札 ).not.toBeVisible() }, } + +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 CINEMA_AHEAD: SearchHit = { ...SEARCH_HIT_FIXTURES[1], ahead: true } + +const AQUARIUM_TOLD: SearchHit = { + ...SEARCH_HIT_FIXTURES[2], + ahead: true, + watch: { id: 'watch-told', leadMinutes: 10 }, +} + +const STARTED: SearchHit = { + ...SEARCH_HIT_FIXTURES[1], + id: '131-1310-40011', + title: '夕方の灯台だより', + startLabel: '17:00', + endLabel: '17:30', +} + +/** The detail beside the list once the row at a place in it is chosen. */ +async function besideTheRow( + canvasElement: HTMLElement, + at: number, +): Promise { + const beside = await within(canvasElement).findByRole('region', { + name: '番組の詳細', + }) + const rows = canvasElement.querySelectorAll( + '[data-pane="list"] li[data-programme]', + ) + + await userEvent.click(within(rows[at]).getAllByRole('button')[0]) + await waitFor(() => expect(rows[at]).toHaveAttribute('data-chosen')) + + return beside +} + +export const 横向きの電話の詳細でも録画予約の隣で放送開始の通知を頼む: Story = { + args: { + result: { + condition, + channels, + outcome: searched({ + hits: [STARTED, CINEMA_AHEAD, AQUARIUM_TOLD], + total: 3, + page: 1, + lastPage: 1, + perPage: 20, + rangeFrom: 1, + rangeTo: 3, + }), + }, + noticing: NOTICING, + }, + parameters: { screen: { width: 844, height: 390 }, coarse: true }, + beforeEach: () => { + watchIt.mockClear() + unwatchIt.mockClear() + }, + play: async ({ canvasElement }) => { + const first = within(await besideTheRow(canvasElement, 1)) + const reserve = first.getByRole('button', { name: '録画予約' }) + const ask = first.getByRole('button', { name: NOTIFY_START }) + + await expect(Math.round(ask.getBoundingClientRect().top)).toBe( + Math.round(reserve.getBoundingClientRect().top), + ) + await expect(ask.getBoundingClientRect().left).toBeGreaterThan( + reserve.getBoundingClientRect().right, + ) + await expect(canvasElement.ownerDocument.documentElement.scrollWidth).toBe( + 844, + ) + 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(CINEMA_AHEAD.id, { + leadMinutes: 3, + destinations: ['dest-slack', 'dest-ipad'], + }), + ) + await expect( + await screen.findByText('開始の 3 分前に通知します'), + ).toBeVisible() + + const told = within(await besideTheRow(canvasElement, 2)) + + await expect(told.getByText('開始 10 分前に通知')).toBeVisible() + await expect(told.queryByRole('button', { name: NOTIFY_START })).toBeNull() + await userEvent.click(told.getByRole('button', { name: STOP_NOTIFYING })) + await waitFor(() => expect(unwatchIt).toHaveBeenCalledWith('watch-told')) + + const started = within(await besideTheRow(canvasElement, 0)) + + await expect( + started.getByRole('button', { name: '録画予約' }), + ).toBeVisible() + await expect( + started.queryByRole('button', { name: NOTIFY_START }), + ).toBeNull() + }, +} 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)/guide/actions.test.ts b/tests/app/(app)/guide/actions.test.ts new file mode 100644 index 00000000..91985915 --- /dev/null +++ b/tests/app/(app)/guide/actions.test.ts @@ -0,0 +1,153 @@ +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 NAVIGATION = 'next/navigation' + +const STOOD_IN = 'vela-stand-in:next/navigation' + +const CACHE = 'next/cache' + +registerHooks({ + resolve(specifier, context, next) { + if (specifier === CACHE) { + return next(`${CACHE}.js`, context) + } + + return specifier === NAVIGATION + ? { url: STOOD_IN, shortCircuit: true } + : next(specifier, context) + }, + load(url, context, next) { + return url === STOOD_IN + ? { + format: 'module', + source: 'export const unstable_rethrow = () => {}', + shortCircuit: true, + } + : next(url, context) + }, +}) + +const DOCUMENTARY = '32736-1024-501' +const WATCH = '0c000000-0000-4000-8000-000000000001' +const HOME = '0a000000-0000-4000-8000-000000000001' + +const store: { status: number; down: boolean } = { status: 200, down: false } + +const revalidated: string[] = [] + +const answered = () => ({ status: store.status, ok: store.status < 400 }) + +function reach(): void { + if (store.down) { + throw new Error('the API is not there') + } +} + +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 () => { + reach() + + return { + data: + store.status < 400 + ? { data: { id: WATCH, leadMinutes: 5 } } + : undefined, + response: answered(), + } + }, + DELETE: async () => { + reach() + + return { 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 + store.down = false +}) + +test('a single notice that was set reads the guide, the reservations and the search again', async () => { + store.status = 201 + + assert.deepEqual(await watchProgramme(DOCUMENTARY, DRAFT), { + state: 'ok', + watch: { id: WATCH, leadMinutes: 5 }, + }) + assert.deepEqual(revalidated, ['/guide', '/reservations', '/search']) +}) + +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', '/search']) +}) + +test('taking a single notice back reads the guide, the reservations and the search again', async () => { + assert.deepEqual(await unwatchProgramme(WATCH), { state: 'ok' }) + assert.deepEqual(revalidated, ['/guide', '/reservations', '/search']) +}) + +test('a session that ended is said as such', async () => { + store.status = 401 + + assert.deepEqual(await unwatchProgramme(WATCH), { state: 'unauthenticated' }) +}) + +test('a single notice whose asking or taking back never reached the API leaves the pages as they are', async () => { + store.down = true + + assert.deepEqual(await watchProgramme(DOCUMENTARY, DRAFT), { + state: 'rejected', + message: + '通知を設定できませんでした。時間をおいてからもう一度お試しください。', + unreached: true, + }) + assert.deepEqual(await unwatchProgramme(WATCH), { + state: 'rejected', + message: + '通知を取り消せませんでした。時間をおいてからもう一度お試しください。', + unreached: true, + }) + assert.deepEqual(revalidated, []) +}) 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..ab979586 --- /dev/null +++ b/tests/app/(app)/settings/notifications/actions.test.ts @@ -0,0 +1,185 @@ +import assert from 'node:assert/strict' +import { registerHooks } from 'node:module' +import { beforeEach, mock, test } from 'node:test' + +const NAVIGATION = 'next/navigation' + +const STOOD_IN = 'vela-stand-in:next/navigation' + +const CACHE = 'next/cache' + +registerHooks({ + resolve(specifier, context, next) { + if (specifier === CACHE) { + return next(`${CACHE}.js`, context) + } + + return specifier === NAVIGATION + ? { url: STOOD_IN, shortCircuit: true } + : next(specifier, context) + }, + load(url, context, next) { + return url === STOOD_IN + ? { + format: 'module', + source: 'export const unstable_rethrow = () => {}', + shortCircuit: true, + } + : next(url, context) + }, +}) + +const ONE = '0a000000-0000-4000-8000-000000000001' +const PAGE = '/settings/notifications' + +const store: { status: number; said?: string; down: boolean } = { + status: 200, + down: false, +} + +const revalidated: string[] = [] + +async function answer() { + if (store.down) { + throw new Error('the API is not there') + } + + 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 + store.down = false +}) + +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: 'この送り先は残っていないため、削除できませんでした。', + gone: true, + }) + 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' }) +}) + +test('a change that never reached the API leaves the page as it is, and says what could not be done', async () => { + store.down = true + + const written = await Promise.all([ + addDestination({ + name: '見本の送り先', + url: 'https://webhook.example/one', + }), + changeDestination(ONE, { name: '見本の送り先', enabled: true }), + turnDestination(ONE, false), + sendTrial(ONE), + dropDestination(ONE), + addRuleSet(RULES), + changeRuleSet(ONE, RULES), + turnRuleSet(ONE, false), + dropRuleSet(ONE), + settleTheLead(3), + ]) + + assert.deepEqual( + written.map(({ state }) => state), + written.map(() => 'rejected'), + ) + assert.deepEqual(written[2], { + state: 'rejected', + message: + '送り先を変更できませんでした。時間をおいてからもう一度お試しください。', + unreached: true, + }) + assert.deepEqual(revalidated, []) +}) 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..f12dcd9c --- /dev/null +++ b/tests/lib/notifications.test.ts @@ -0,0 +1,462 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' + +import { + amongWatches, + deliveriesShown, + deliverySaid, + destinationsByDefault, + eventLabelOf, + eventsSummary, + failureWord, + goingToo, + isLead, + lastResultSaid, + leadChipWords, + leadLabel, + leadToastWords, + narrowedTo, + nameFits, + newestFirst, + readAddress, + registeringAs, + ruleSetsFull, + ruleSetsGoingWith, + saidOfTheGone, + testSaid, + toggled, + watchLine, + webhookKindOf, + withWhy, + yetToStart, + 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', () => { + 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.1.2.3]/api/webhooks/1', + 'https://discord.com/channels/1234', + 'https://hook.example.jp/carina', + ]) { + assert.equal(webhookKindOf(refused), undefined, refused) + } +}) + +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 として登録します') +}) + +test('a rule set says its events group by group, each group after its prefix', () => { + assert.equal( + eventsSummary([ + 'recordingTruncated', + 'recordingFailed', + 'encodeFailed', + 'reservationCompeting', + 'reservationMissed', + 'qualityIncidentDetected', + '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('qualityIncidentDetected'), '品質の異常の発生') + assert.equal(eventLabelOf('qualityIncidentResolved'), '品質の異常の解消') + assert.equal(eventLabelOf('somethingNew' as NotificationEvent), '未知の値') +}) + +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('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({ + 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', + kind: 'recordingTruncated', + occurredAt: '2026-11-09T12:03:00Z', + destinationId: 'a', + state: 'sent', + } + + assert.deepEqual(deliverySaid(delivery), { verdict: 'ok', words: '届いた' }) + assert.equal( + withWhy( + deliverySaid({ ...delivery, state: 'failed', failure: 'timedOut' }), + ), + '送り直し中 · 時間切れ', + ) + 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: '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', () => { + 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']) +}) + +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'), '放送の取り消し') +}) + +test('a refusal for what is no longer there is said where it outlives the row, any other stays where it was asked', () => { + assert.equal( + saidOfTheGone({ state: 'rejected', message: '残っていない', gone: true }), + '残っていない', + ) + assert.equal( + saidOfTheGone({ state: 'rejected', message: '受け付けられない' }), + undefined, + ) + assert.equal(saidOfTheGone({ state: 'unauthenticated' }), undefined) + assert.equal(saidOfTheGone({ state: 'ok' }), undefined) +}) diff --git a/tests/repository/notifications.test.ts b/tests/repository/notifications.test.ts new file mode 100644 index 00000000..80e6c6d1 --- /dev/null +++ b/tests/repository/notifications.test.ts @@ -0,0 +1,1111 @@ +import assert from 'node:assert/strict' +import { registerHooks } from 'node:module' +import { beforeEach, mock, test } from 'node:test' + +const NAVIGATION = 'next/navigation' + +const STOOD_IN = 'vela-stand-in:next/navigation' + +registerHooks({ + resolve(specifier, context, next) { + return specifier === NAVIGATION + ? { url: STOOD_IN, shortCircuit: true } + : next(specifier, context) + }, + load(url, context, next) { + return url === STOOD_IN + ? { + format: 'module', + source: 'export const unstable_rethrow = () => {}', + shortCircuit: true, + } + : next(url, context) + }, +}) + +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 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: { + destinations: unknown[] + rules: unknown[] + settings: unknown + deliveries: Record + trial: unknown + watches: unknown[] + programme: unknown + made: unknown + readStatus: number + readMessage: string + writeStatus: number + writeMessage: string + down: 'nothing' | 'writes' | 'everything' + unread: string +} = { + destinations: [], + rules: [], + settings: null, + deliveries: {}, + trial: null, + watches: [], + programme: null, + made: null, + readStatus: 200, + readMessage: '', + writeStatus: 200, + writeMessage: '', + down: 'nothing', + unread: '', +} + +const NOT_THERE = 'the API is not there' + +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, + }) + + if (store.down !== 'nothing') { + throw new Error(NOT_THERE) + } + + 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 = () => ({ + GET: async (path: string, options?: Asked) => { + const query = options?.params?.query + sent.push({ method: 'GET', path, query }) + + if (store.down === 'everything') { + throw new Error(NOT_THERE) + } + + if (store.unread === path) { + return refusal(503, '') + } + + 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)] ?? [], + }) + 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}`) + } + }, + 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, + askForWatch, + cancelWatch, + defineRuleSet, + getNotificationsScreen, + getWatchOffer, + listWatchedProgrammes, + listWatches, + readSingleNotices, + 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.watches = [] + store.programme = PROGRAMME + store.made = watch(WATCH_ONE) + store.readStatus = 200 + store.readMessage = '' + store.writeStatus = 200 + store.writeMessage = '' + store.down = 'nothing' + store.unread = '' +}) + +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('a change or a removal of what is no longer there says so, and that it is gone', async () => { + store.writeStatus = 404 + store.writeMessage = 'No destination is registered under that id.' + + const gone = { + state: 'rejected', + message: 'この送り先は残っていないため、変更できませんでした。', + gone: true, + } + + assert.deepEqual( + await reviseDestination(HOME, { name: 'n', enabled: true }), + gone, + ) + assert.deepEqual(await switchDestination(HOME, false), gone) + assert.deepEqual(await removeDestination(HOME), { + ...gone, + message: 'この送り先は残っていないため、削除できませんでした。', + }) + + store.writeMessage = 'No set of rules is held under that id.' + + assert.deepEqual( + await reviseRuleSet(FAILURES, { + name: 'n', + enabled: true, + events: [], + destinations: [HOME], + }), + { + ...gone, + message: 'このルールセットは残っていないため、変更できませんでした。', + }, + ) + assert.deepEqual(await removeRuleSet(FAILURES), { + ...gone, + message: 'このルールセットは残っていないため、削除できませんでした。', + }) +}) + +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.', + ), + '送り先を追加できませんでした。時間をおいてからもう一度お試しください。', + ) +}) + +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' }) +}) + +test('a write that never reached Carina is refused in the words of what was asked, never thrown', async () => { + store.down = 'everything' + + const later = '時間をおいてからもう一度お試しください。' + const refused = (what: string) => ({ + state: 'rejected', + message: `${what}。${later}`, + unreached: true, + }) + const rule = { + name: '見本のルールセット', + enabled: true, + events: ['recordingFailed' as const], + destinations: [HOME], + } + + assert.deepEqual( + await registerDestination({ name: 'n', url: 'u' }), + refused('送り先を追加できませんでした'), + ) + assert.deepEqual( + await reviseDestination(HOME, { name: 'n', enabled: true }), + refused('送り先を変更できませんでした'), + ) + assert.deepEqual( + await switchDestination(HOME, false), + refused('送り先を変更できませんでした'), + ) + assert.deepEqual( + await removeDestination(HOME), + refused('送り先を削除できませんでした'), + ) + assert.deepEqual( + await tryDestination(HOME), + refused('テスト送信ができませんでした'), + ) + assert.deepEqual( + await defineRuleSet(rule), + refused('ルールセットを追加できませんでした'), + ) + assert.deepEqual( + await reviseRuleSet(FAILURES, rule), + refused('ルールセットを変更できませんでした'), + ) + assert.deepEqual( + await switchRuleSet(FAILURES, false), + refused('ルールセットを変更できませんでした'), + ) + assert.deepEqual( + await removeRuleSet(FAILURES), + refused('ルールセットを削除できませんでした'), + ) + assert.deepEqual( + await settleLead(0), + refused('単発の通知の既定を変更できませんでした'), + ) + assert.deepEqual( + await askForWatch(DOCUMENTARY, { leadMinutes: 3, destinations: [HOME] }), + refused('通知を設定できませんでした'), + ) + assert.deepEqual( + await cancelWatch(WATCH_ONE), + refused('通知を取り消せませんでした'), + ) +}) + +test('a single notice whose asking never arrived is refused the same way, the programme having been read', async () => { + store.down = 'writes' + + assert.deepEqual( + await askForWatch( + DOCUMENTARY, + { leadMinutes: 3, destinations: [HOME] }, + BEFORE_IT_STARTS, + ), + { + state: 'rejected', + message: + '通知を設定できませんでした。時間をおいてからもう一度お試しください。', + unreached: true, + }, + ) + assert.equal(sent.at(-1)?.method, 'POST') +}) + +test('what is read stays an error while Carina is not there', async () => { + store.down = 'everything' + + await assert.rejects(getNotificationsScreen(), /the API is not there/) + await assert.rejects(listWatches(), /the API is not there/) + await assert.rejects(getWatchOffer(), /the API is not there/) + await assert.rejects(listWatchedProgrammes(), /the API is not there/) +}) + +test('the single notices are read as those waiting and what a new one starts from', async () => { + store.watches = [watch(WATCH_ONE)] + + const { watches, offer } = readSingleNotices() + + assert.deepEqual([...(await watches).keys()], [DOCUMENTARY]) + assert.deepEqual(await offer, { + leadMinutes: 3, + destinations: [{ id: HOME, name: '見本の送り先 1' }], + }) +}) + +test('while the notices waiting cannot be read none is marked, and no new one is offered, since one may already be set', async () => { + store.watches = [watch(WATCH_ONE)] + store.unread = '/api/notifications/watches' + + const { watches, offer } = readSingleNotices() + + assert.equal((await watches).size, 0) + assert.equal(await offer, undefined) +}) + +test('while what a new one starts from cannot be read, the notices waiting are still marked', async () => { + store.watches = [watch(WATCH_ONE)] + store.unread = '/api/notifications/settings' + + const { watches, offer } = readSingleNotices() + + assert.deepEqual([...(await watches).keys()], [DOCUMENTARY]) + assert.equal(await offer, undefined) +}) 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/repository/search.test.ts b/tests/repository/search.test.ts index d404c34d..b685ade4 100644 --- a/tests/repository/search.test.ts +++ b/tests/repository/search.test.ts @@ -581,3 +581,43 @@ test('a reservation that is no longer standing marks nothing', async () => { [undefined], ) }) + +test('a hit that has not started says so and carries the notice asked of it, and one that has started carries neither', async () => { + standing() + + const hourAhead = (hours: number): string => + new Date(Date.now() + hours * 60 * 60 * 1000).toISOString() + + store.page = { + items: [ + programme(131, 1310, 40001, '空から見る港町の夏', hourAhead(3)), + programme(131, 1310, 40002, '真夜中の水槽通信', hourAhead(5)), + programme(131, 1310, 40003, '朝の灯台だより', hourAhead(-1)), + ], + total: 3, + currentPage: 1, + lastPage: 1, + perPage: 20, + } + + const result = await searchPrograms( + { q: '観測所' }, + Promise.resolve( + new Map([ + ['131-1310-40001', { id: 'watch-1', leadMinutes: 5 as const }], + ['131-1310-40003', { id: 'watch-3', leadMinutes: 0 as const }], + ]), + ), + ) + + assert.deepEqual( + result.outcome.state === 'searched' + ? result.outcome.found.hits.map((hit) => [hit.id, hit.ahead, hit.watch]) + : [], + [ + ['131-1310-40001', true, { id: 'watch-1', leadMinutes: 5 }], + ['131-1310-40002', true, undefined], + ['131-1310-40003', undefined, undefined], + ], + ) +}) diff --git a/tests/storybook/every-test-runs.test.ts b/tests/storybook/every-test-runs.test.ts index 9219a852..d1fe4589 100644 --- a/tests/storybook/every-test-runs.test.ts +++ b/tests/storybook/every-test-runs.test.ts @@ -7,6 +7,8 @@ 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', 'tests/app/the-app-goes-on-the-home-screen.test.ts', @@ -133,6 +135,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', @@ -192,6 +195,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',