diff --git a/app/Devnull/Data/Notification.php b/app/Devnull/Data/Notification.php index 3586a1ed..c5031d05 100644 --- a/app/Devnull/Data/Notification.php +++ b/app/Devnull/Data/Notification.php @@ -36,6 +36,10 @@ public function __construct( public ?int $level = null, public ?string $rank = null, public ?string $rankDescription = null, + public ?string $organization = null, + public ?string $timeoutReason = null, + public ?string $timeoutDuration = null, + public ?CarbonImmutable $timeoutEndsAt = null, ) {} /** @@ -53,6 +57,8 @@ public static function fromArray(array $data): self ? (int) $data['unread_count'] > 0 : array_key_exists('read_at', $data) && $data['read_at'] === null; $id = (string) ($data['id'] ?? ''); + $organization = is_array($data['organization'] ?? null) && is_string($data['organization']['handle'] ?? null) ? $data['organization']['handle'] : null; + $timeout = is_array($data['timeout'] ?? null) ? $data['timeout'] : []; return new self( id: $id, @@ -75,6 +81,10 @@ public static function fromArray(array $data): self level: is_int($data['level'] ?? null) ? $data['level'] : null, rank: is_string($data['rank'] ?? null) && $data['rank'] !== '' ? $data['rank'] : null, rankDescription: is_string($data['rank_description'] ?? null) && trim($data['rank_description']) !== '' ? $data['rank_description'] : null, + organization: $organization, + timeoutReason: is_string($timeout['reason'] ?? null) ? $timeout['reason'] : null, + timeoutDuration: is_string($timeout['duration'] ?? null) ? $timeout['duration'] : null, + timeoutEndsAt: Commit::date($timeout['ends_at'] ?? null), ); } @@ -99,11 +109,25 @@ public function isFollow(): bool } /** - * A moderator approved or rejected your commit. Nobody else is named. + * A moderator approved or rejected your commit, or put you in timeout. Nobody else is named. */ public function isModeration(): bool { - return in_array($this->type, ['approved', 'rejected'], true); + return in_array($this->type, ['approved', 'rejected', 'timed_out'], true); + } + + public function isTimeout(): bool + { + return $this->type === 'timed_out'; + } + + /** + * Someone else's commit is what it's about, so the web leads with them: their avatar on the rail, their name and + * handle over what they did, then their words. A reply, a quote, a mention or someone's first commit. + */ + public function isActorsCommit(): bool + { + return in_array($this->type, ['replied', 'quoted', 'mentioned', 'first_commit'], true); } public function isRejection(): bool @@ -140,7 +164,7 @@ public function levelLabel(): ?string */ public function isAboutYourCommit(): bool { - return $this->isStar() || $this->isModeration(); + return in_array($this->type, ['starred', 'approved', 'rejected'], true); } /** @@ -165,11 +189,12 @@ public function isNewSince(?CarbonImmutable $readAt): bool } /** - * The commit a tap opens, as on the web: the notification's own commit. A follow or a level-up opens a profile instead. + * The commit a tap opens, as on the web: the notification's own commit. A follow, a timeout or a level-up opens a + * profile instead. */ public function commitToOpen(): ?string { - return $this->isFollow() || $this->isLevelUp() ? null : $this->commitId; + return $this->isFollow() || $this->isLevelUp() || $this->isTimeout() ? null : $this->commitId; } /** @@ -202,6 +227,28 @@ public function others(): string return $others < 1 ? '' : "and {$others} ".($others === 1 ? 'other' : 'others'); } + /** + * When exactly two people followed you or starred your commit, the web names both: the other one, or null. + */ + public function secondActor(): ?User + { + if (! in_array($this->type, ['followed', 'starred'], true) || $this->actorsCount !== 2) { + return null; + } + + $second = $this->actors[1] ?? null; + + return $second !== null && $second->id !== $this->actor->id ? $second : null; + } + + /** + * Whose commit it is, as the web words it: "your", or the organization's you heard about it for. + */ + private function whose(): string + { + return $this->organization === null ? 'your' : "@{$this->organization}'s"; + } + /** * What happened, as the web words it. For a person it follows their name and their handle or the others. */ @@ -209,12 +256,14 @@ public function sentence(): string { return match ($this->type) { 'followed' => 'followed you', - 'mentioned' => 'mentioned you', - 'starred' => 'starred your commit', - 'quoted' => 'quoted your commit', - 'approved', 'rejected' => "Your commit was {$this->type}", + 'mentioned' => $this->organization === null ? 'mentioned you' : "mentioned @{$this->organization}", + 'starred' => "starred {$this->whose()} commit", + 'quoted' => "quoted {$this->whose()} commit", + 'first_commit' => 'made their first commit', + 'approved', 'rejected' => ($this->organization === null ? 'Your' : $this->whose())." commit was {$this->type}", + 'timed_out' => 'You were put in timeout', 'leveled_up' => $this->levelLabel() === null ? 'You reached a new level' : "You reached level {$this->level}: {$this->rank}", - default => 'replied to your commit', + default => "replied to {$this->whose()} commit", }; } diff --git a/app/Devnull/NotificationFilter.php b/app/Devnull/NotificationFilter.php new file mode 100644 index 00000000..a10f72a8 --- /dev/null +++ b/app/Devnull/NotificationFilter.php @@ -0,0 +1,133 @@ + + */ + public const array Kinds = [ + 'replies' => ['Replies', 'Someone replies to one of your commits.', 'No replies yet. When someone replies to one of your commits, it shows up here.'], + 'quotes' => ['Quotes', 'Someone quotes one of your commits.', 'No quotes yet. When someone quotes one of your commits, it shows up here.'], + 'stars' => ['Stars', 'Someone stars one of your commits.', 'No stars yet. When someone stars one of your commits, it shows up here.'], + 'mentions' => ['Mentions', 'Someone mentions you in a commit.', 'No mentions yet. When someone mentions you in a commit, it shows up here.'], + 'follows' => ['Follows', 'Someone follows you.', 'No followers yet. When someone follows you, it shows up here.'], + 'moderation' => ['Moderation', 'Approved, rejected, and timeout notices.', 'No moderation updates. Approved, rejected, and timeout notices show up here.'], + ]; + + /** + * What the list says with every kind on and nothing in it. + */ + public const string AllEmpty = 'Nothing here yet. Follows, stars, replies, quotes, mentions, level-ups, and moderation updates for your commits will show up here.'; + + /** + * The kinds that are on for this user, in the web's order. Everything is on until they turn something off. + * + * @return list + */ + public function enabled(?string $userId): array + { + $kept = $userId === null ? null : Cache::get($this->key($userId)); + + return is_array($kept) ? self::only($kept) : array_keys(self::Kinds); + } + + /** + * @param list $kinds + */ + public function save(?string $userId, array $kinds): void + { + if ($userId !== null) { + Cache::forever($this->key($userId), self::only($kinds)); + } + } + + /** + * Turns one kind on or off, and says what's on now. + * + * @return list + */ + public function set(?string $userId, string $kind, bool $on): array + { + $enabled = $this->enabled($userId); + $kinds = $on ? [...$enabled, $kind] : array_values(array_diff($enabled, [$kind])); + + $this->save($userId, $kinds); + + return $this->enabled($userId); + } + + /** + * What devnull is asked for, as the web asks: `all`, `none`, or the kinds that are on, comma separated. + * + * @param list $kinds + */ + public static function type(array $kinds): string + { + $kinds = self::only($kinds); + + return match (true) { + count($kinds) === count(self::Kinds) => 'all', + $kinds === [] => 'none', + default => implode(',', $kinds), + }; + } + + /** + * The web's empty state for what's on: its own words for one kind or all of them, and plainer ones otherwise. + * + * @param list $kinds + */ + public static function emptyMessage(array $kinds): string + { + return match (true) { + $kinds === [] => 'All categories are turned off. Enable a category to see notifications.', + count($kinds) === count(self::Kinds) => self::AllEmpty, + count($kinds) === 1 => self::Kinds[$kinds[0]][2], + default => 'No notifications in the selected categories yet.', + }; + } + + /** + * The shell line over the empty state, as the web prints it. + * + * @param list $kinds + */ + public static function command(array $kinds): string + { + return count($kinds) === count(self::Kinds) + ? '$ cat /dev/notifications' + : "\$ cat /dev/notifications | grep -E '".($kinds === [] ? '^$' : implode('|', $kinds))."'"; + } + + /** + * Known kinds only, once each, in the web's order. + * + * @param array $kinds + * @return list + */ + private static function only(array $kinds): array + { + return array_values(array_filter(array_keys(self::Kinds), fn (string $kind): bool => in_array($kind, $kinds, true))); + } + + private function key(string $userId): string + { + return "devnull.notification-kinds.{$userId}"; + } +} diff --git a/app/Icons/Lucide.php b/app/Icons/Lucide.php index b6ea5bb9..23d6d67a 100644 --- a/app/Icons/Lucide.php +++ b/app/Icons/Lucide.php @@ -32,6 +32,7 @@ enum Lucide case ChevronLeft; case ChevronDown; case ChevronsUp; + case Hourglass; case ArrowUpRight; case ArrowUp; case Pin; @@ -126,6 +127,8 @@ public static function forNotification(string $type): self 'mentioned' => self::AtSign, 'approved' => self::Check, 'rejected' => self::X, + 'timed_out' => self::Hourglass, + 'first_commit' => self::GitCommitVertical, default => self::MessageSquareReply, }; } @@ -178,6 +181,7 @@ public function custom(bool $filled = false): string self::ArrowUpRight => 'arrow-up-right', self::ArrowUp => 'arrow-up', self::ChevronsUp => 'chevrons-up', + self::Hourglass => 'hourglass', self::ListOrdered => 'list-ordered', self::Building2 => 'building-2', self::MapPin => 'map-pin', diff --git a/app/NativeComponents/NotificationSettings.php b/app/NativeComponents/NotificationSettings.php new file mode 100644 index 00000000..70e60c6f --- /dev/null +++ b/app/NativeComponents/NotificationSettings.php @@ -0,0 +1,50 @@ + */ + public array $kinds = []; + + public function mount(): void + { + $this->kinds = app(NotificationFilter::class)->enabled($this->me()?->id); + } + + public function navTitle(): string + { + return 'Notification settings'; + } + + public function setKind(string $kind, bool $on): void + { + if (! array_key_exists($kind, NotificationFilter::Kinds)) { + return; + } + + $this->kinds = app(NotificationFilter::class)->set($this->me()?->id, $kind, $on); + } + + public function render(): View + { + return view('native.notification-settings', [ + 'options' => NotificationFilter::Kinds, + ]); + } +} diff --git a/app/NativeComponents/Notifications.php b/app/NativeComponents/Notifications.php index 58b7dd7b..07b77c6b 100644 --- a/app/NativeComponents/Notifications.php +++ b/app/NativeComponents/Notifications.php @@ -8,7 +8,8 @@ use App\Devnull\Exceptions\ApiException; use App\Devnull\Exceptions\KeychainUnavailable; use App\Devnull\Exceptions\Unauthenticated; -use App\Devnull\ShownTabs; +use App\Devnull\NotificationFilter; +use App\Icons\Lucide; use App\NativeComponents\Concerns\DrawsSkeletonFirst; use App\NativeComponents\Concerns\OffersPush; use App\NativeComponents\Concerns\OpensInTab; @@ -19,27 +20,25 @@ use App\NativeComponents\Concerns\WritesInBackground; use Carbon\CarbonImmutable; use Illuminate\View\View; +use Native\Mobile\Edge\Layouts\Builders\NavAction; +use Native\Mobile\Edge\Layouts\Builders\NavBarOptions; use Native\Mobile\Edge\NativeComponent; /** * Follows, stars, replies, quotes, mentions, level-ups, and moderation updates - * for your commits, grouped as the web groups them, on a Rail Gray rail. + * for your commits, grouped as the web groups them, each on its own rail in + * the lane of whoever it's about, ending in a dot, as the web draws them. * - * The web's filters run along the top: All, Replies, Quotes, Stars, Mentions, - * Follows and Moderation, each kept on its own for next time. A group of - * more than one opens in place to list them all, as the web expands it. + * Which kinds show is chosen on the notification settings screen, from the + * button in the title bar, as the web chooses them with its filters: each + * kind on or off on its own, kept per user on this phone. A group of more + * than one opens in place to list them all, as the web expands it. * * It opens on the notifications as they were last time, all read by then, * then asks devnull behind them. devnull marks everything read as it lists - * any of it, and says when, so the groups read since then are the new ones: - * their node is ringed in blue, above the last-visit marker. New ones go in - * at the top quietly, since a group's id moves on as people join it. - * - * The filters are pages you swipe between, as on the Log (see Log), and the - * pager draws the filters along the top and moves them with your finger. The - * filters either side of the one you're on show the first few groups kept - * for them, ready for a swipe. Each has its own list, and a filter you leave - * starts again at the top of a fresh one. + * any of it, and says when, so the groups read since then are the new ones, + * above the last-visit marker. New ones go in at the top quietly, since a + * group's id moves on as people join it. */ class Notifications extends NativeComponent { @@ -58,37 +57,17 @@ class Notifications extends NativeComponent protected bool $forceFullFrames = true; /** - * The web's filters, their labels and what each says when it has nothing. - */ - public const array Types = [ - 'all' => ['All', 'Nothing here yet. Follows, stars, replies, quotes, mentions, level-ups, and moderation updates for your commits will show up here.'], - 'replies' => ['Replies', 'No replies yet. When someone replies to one of your commits, it shows up here.'], - 'quotes' => ['Quotes', 'No quotes yet. When someone quotes one of your commits, it shows up here.'], - 'stars' => ['Stars', 'No stars yet. When someone stars one of your commits, it shows up here.'], - 'mentions' => ['Mentions', 'No mentions yet. When someone mentions you in a commit, it shows up here.'], - 'follows' => ['Follows', 'No followers yet. When someone follows you, it shows up here.'], - 'moderation' => ['Moderation', 'No moderation updates. Approved and rejected commits show up here.'], - ]; - - /** - * How many kept groups a filter beside the one you're on shows, enough to fill the screen while you swipe to it. + * The kinds that are on, as the settings screen keeps them (see NotificationFilter). + * + * @var list */ - public const int PreviewGroups = 6; - - public string $type = 'all'; + public array $kinds = []; /** - * Mounts a fresh list for the filter you're on when it changes, at the top. + * Mounts a fresh list when the kinds change, at the top. */ public int $listKey = 0; - /** - * The list key of each filter you're not on. - * - * @var array - */ - public array $listKeys = []; - /** @var list */ public array $notifications = []; @@ -125,15 +104,27 @@ class Notifications extends NativeComponent public function mount(): void { - $this->type = app(ShownTabs::class)->get($this->me()?->id, 'notifications', array_keys(self::Types), 'all'); + $this->kinds = app(NotificationFilter::class)->enabled($this->me()?->id); $this->checkPushPrompt(); $this->fillInAfterFirstFrame('revalidate'); } + /** + * Back from the settings screen, or another tab: a change to the kinds starts the list again for them. + */ public function onResume(): void { $this->forgetRefreshes(); $this->checkPushPrompt(); + + $kinds = app(NotificationFilter::class)->enabled($this->me()?->id); + + if ($kinds !== $this->kinds) { + $this->showKinds($kinds); + + return; + } + $this->revalidate(); } @@ -143,56 +134,50 @@ public function navTitle(): string } /** - * Shows a filter, from a link such as an empty filter's Show all, and the - * pager follows: its own list, from what was kept for it, then asked again. - * The one you're on goes back to its top. + * The small button in the title bar: the notification settings screen, to choose which kinds show. */ - public function show(string $type): void + public function navigationOptions(): ?NavBarOptions { - if (! array_key_exists($type, self::Types)) { - return; - } - - if ($type === $this->type) { - $this->listKey++; - - return; - } + return NavBarOptions::make() + ->action( + NavAction::make('notification-settings') + ->icon(ios: Lucide::Settings2->ios(), android: Lucide::Settings2->android()) + ->a11yLabel('Notification settings') + ->press('openSettings'), + ); + } - $this->switchTo($type); + public function openSettings(): void + { + $this->openInTab('/settings'); } /** - * The pager settling on a filter, after a swipe or a tap along the top. The one it's already on changes nothing. + * The empty list's Show all notifications, as on the web: every kind on again. */ - public function showPage(int $index): void + public function showAll(): void { - $type = array_keys(self::Types)[$index] ?? null; - - if ($type !== null && $type !== $this->type) { - $this->switchTo($type); - } + app(NotificationFilter::class)->save($this->me()?->id, array_keys(NotificationFilter::Kinds)); + $this->showKinds(app(NotificationFilter::class)->enabled($this->me()?->id)); } /** - * A tap on the filter you're on, which the pager sends instead of moving: back to the top of it. + * What devnull is asked for, from the kinds that are on. */ - public function backToTop(int $index): void + private function typeQuery(): string { - $this->show(array_keys(self::Types)[$index] ?? ''); + return NotificationFilter::type($this->kinds); } /** - * The filter you go to keeps the list its first groups were drawn in, which - * can't have been scrolled, and fills it. The one you leave starts again at - * the top of a fresh one. + * The list for other kinds: a fresh one at the top, from what was kept for them, then asked again. + * + * @param list $kinds */ - private function switchTo(string $type): void + private function showKinds(array $kinds): void { - app(ShownTabs::class)->remember($this->me()?->id, 'notifications', $type); - $this->listKeys[$this->type] = $this->listKey + 1; - $this->listKey = $this->listKeys[$type] ?? 0; - $this->type = $type; + $this->kinds = $kinds; + $this->listKey++; $this->notifications = []; $this->nextCursor = null; $this->loaded = false; @@ -210,7 +195,7 @@ private function switchTo(string $type): void */ public function load(): void { - $type = $this->type; + $type = $this->typeQuery(); $this->refresh('notifications', Client::notificationsQuery($type), fn (array $json) => $this->takeFresh($type, $json), again: true); } @@ -220,7 +205,7 @@ public function load(): void */ protected function revalidate(): void { - $type = $this->type; + $type = $this->typeQuery(); $this->refresh('notifications', Client::notificationsQuery($type), fn (array $json) => $this->takeFresh($type, $json)); foreach (array_keys($this->expanded) as $id) { @@ -239,7 +224,7 @@ public function loadMore(): void return; } - $page = $this->attempt(fn ($devnull) => $devnull->notifications($this->type, $this->nextCursor)); + $page = $this->attempt(fn ($devnull) => $devnull->notifications($this->typeQuery(), $this->nextCursor)); if ($page !== null) { $this->notifications = [...$this->notifications, ...$page->items]; @@ -250,9 +235,11 @@ public function loadMore(): void /** * A tap on a notification opens its commit, the profile of whoever - * followed you, or your own for a level-up. A tap on a group of - * followers lists them in place instead, as its toggle does, rather - * than opening only the latest of them. + * followed you, or your own for a level-up or a timeout. A tap on a + * group of followers lists them in place instead, as its toggle does, + * rather than opening only the latest of them. One star in an opened + * group opens whoever gave it, as the web's does: the group above it + * already opens the commit. */ public function open(string $id): void { @@ -268,7 +255,8 @@ public function open(string $id): void return; } - $commitId = $notification->commitToOpen(); + $isGroupMember = ! in_array($id, array_map(fn (Notification $group): string => $group->id, $this->notifications), true); + $commitId = $notification->isStar() && $isGroupMember ? null : $notification->commitToOpen(); $this->openInTab($commitId !== null ? '/commits/'.$commitId @@ -307,7 +295,7 @@ public function toggleGroup(string $id): void return; } - if (($kept = $this->cached($this->groupPath($id), Client::notificationsQuery($this->type))) !== null) { + if (($kept = $this->cached($this->groupPath($id), Client::notificationsQuery($this->typeQuery()))) !== null) { $this->takeGroup($id, $kept); $this->refreshGroup($id); @@ -331,7 +319,7 @@ public function loadGroup(string $id, bool $older = false): void $this->failedGroups = array_values(array_diff($this->failedGroups, [$id])); try { - $page = app(Client::class)->notificationGroup($id, $this->type, $cursor); + $page = app(Client::class)->notificationGroup($id, $this->typeQuery(), $cursor); } catch (Unauthenticated $exception) { $this->signOut($exception); @@ -391,11 +379,11 @@ private function setFollowed(string $username, bool $following): void private function refreshGroup(string $id): void { - $type = $this->type; + $type = $this->typeQuery(); $this->refresh($this->groupPath($id), Client::notificationsQuery($type), function (array $json) use ($id, $type): void { // Folded away, or another filter, while it was on its way. - if ($type === $this->type && array_key_exists($id, $this->expanded)) { + if ($type === $this->typeQuery() && array_key_exists($id, $this->expanded)) { $this->takeGroup($id, $json); } }, quiet: true); @@ -441,7 +429,7 @@ private function find(string $id): ?Notification private function showKept(): void { - if (($json = $this->cached('notifications', Client::notificationsQuery($this->type))) === null) { + if (($json = $this->cached('notifications', Client::notificationsQuery($this->typeQuery()))) === null) { return; } @@ -461,7 +449,7 @@ private function showKept(): void private function takeFresh(string $type, array $json): void { // An answer for a filter you've left. - if ($type !== $this->type) { + if ($type !== $this->typeQuery()) { return; } @@ -491,72 +479,18 @@ private function takeFresh(string $type, array $json): void public function render(): View { $readAt = $this->readAt === null ? null : CarbonImmutable::parse($this->readAt); - $types = array_keys(self::Types); - $index = (int) array_search($this->type, $types, true); - $from = max(0, $index - 1); - $to = min(count($types) - 1, $index + 1); - - $pages = []; - - foreach (array_slice($types, $from, $to - $from + 1) as $type) { - $pages[] = $type === $this->type - ? $this->page($type, $this->notifications, $this->nextCursor, $this->loaded, $this->error, $readAt, $this->listKey) - : $this->preview($type, $readAt); - } return view('native.notifications', [ 'myColour' => $this->myColour(), - 'types' => self::Types, + 'kinds' => $this->kinds, 'readAt' => $readAt, - 'pages' => $pages, - 'pageIndex' => $index, - 'pagesFrom' => $from, - 'pagesTo' => $to, - ]); - } - - /** - * A filter beside the one you're on: the first few groups kept for it, as it will open. - * - * @return array - */ - private function preview(string $type, ?CarbonImmutable $readAt): array - { - $json = $this->skeletonFrame ? null : $this->cached('notifications', Client::notificationsQuery($type)); - $kept = is_array($json['data'] ?? null) ? $json['data'] : []; - $page = $json === null ? null : Page::fromArray(['data' => array_slice($kept, 0, self::PreviewGroups)] + $json, Notification::fromArray(...)); - - // Groups past the preview are left out, with nothing under them yet. - return $this->page($type, $page->items ?? [], $page?->nextCursor, $page !== null, null, $readAt, $this->listKeys[$type] ?? 0, cut: count($kept) > self::PreviewGroups); - } - - /** - * What a filter's page shows. - * - * @param list $notifications - * @return array - */ - private function page(string $type, array $notifications, ?string $nextCursor, bool $loaded, ?string $error, ?CarbonImmutable $readAt, int $listKey, bool $cut = false): array - { - $showing = $type === $this->type; - - return [ 'end' => match (true) { - $cut || $notifications === [] => null, - $nextCursor !== null => 'more', + $this->notifications === [] => null, + $this->nextCursor !== null => 'more', default => 'oldest', }, - 'type' => $type, - 'showing' => $showing, - 'listKey' => $listKey, - 'notifications' => $notifications, - 'loaded' => $loaded, - 'error' => $error, - 'lastVisitBefore' => self::firstSeen($notifications, $readAt), - 'expanded' => $showing ? $this->expanded : [], - 'expandedCursors' => $showing ? $this->expandedCursors : [], - 'failedGroups' => $showing ? $this->failedGroups : [], - ]; + 'lastVisitBefore' => self::firstSeen($this->notifications, $readAt), + ]); } /** diff --git a/resources/icons/hourglass.svg b/resources/icons/hourglass.svg new file mode 100644 index 00000000..2076a228 --- /dev/null +++ b/resources/icons/hourglass.svg @@ -0,0 +1 @@ + diff --git a/resources/views/native/notification-settings.blade.php b/resources/views/native/notification-settings.blade.php new file mode 100644 index 00000000..b39c4a7c --- /dev/null +++ b/resources/views/native/notification-settings.blade.php @@ -0,0 +1,28 @@ +{{-- + The kinds the Notifications tab shows, laid out like the app's other settings: a heading with a line on what it's + for, then a row per kind with its name, what it covers, and a real switch. Each switch saves when it flips. +--}} + + + + + @include('native.partials.settings-heading', [ + 'title' => 'Show in Notifications', + 'description' => 'Choose which kinds of notification the list shows. Kept on this phone, as the web keeps its filters in your browser.', + ]) + + + @foreach ($options as $kind => [$label, $description]) + + + {{ $label }} + {{ $description }} + + + + @endforeach + + + + + diff --git a/resources/views/native/notifications.blade.php b/resources/views/native/notifications.blade.php index 512cbd34..db18a8bb 100644 --- a/resources/views/native/notifications.blade.php +++ b/resources/views/native/notifications.blade.php @@ -1,39 +1,67 @@ +@use('App\Devnull\Display') +@use('App\Devnull\NotificationFilter') + +{{-- + The inbox, as the web lays it out: one list of the kinds you chose on the settings screen, with a day marker + where the day changes and HEAD@{last visit} under what's new. Each group sits on its own rail in the lane of + whoever it's about, ending in a dot (see partials/notification). + + Keyed per choice of kinds, so a change starts a fresh list at the top. Pull to refresh asks devnull again, and the + end of the list asks for the next page. +--}} @include('native.partials.error') @include('native.partials.refresh-failed') @include('native.partials.push-prompt') - {{-- - The filters as pages you swipe between, as on the Log: the one you're on and one either side, which show the - first few groups kept for them. The web's filters run along the top as the Log's page tabs, each as wide as its - label, in a row that scrolls sideways. The pager draws them, as on the Log: the underline follows your finger, - and the row keeps the filter you're on in view, as the web does. It says which filter it settled on once the - swipe has come to rest, and a tap on the filter you're on takes it back to its top. Keyed so the banners above - coming and going don't make it a new pager. - --}} - - @foreach ($pages as $page) - @include('native.partials.notifications-page', ['page' => $page]) + @if (! $loaded && $error === null) + + + + @endif + + @if ($loaded && $notifications === [] && $error === null) + + {{ NotificationFilter::command($kinds) }} + {{ NotificationFilter::emptyMessage($kinds) }} + @if (count($kinds) !== count(NotificationFilter::Kinds)) + + Show all notifications + + @endif + + @endif + + @foreach ($notifications as $index => $notification) + @php($before = $notifications[$index - 1] ?? null) + @if ($notification->id === $lastVisitBefore) + @include('native.partials.last-visit-marker', ['label' => 'Notifications above are new since your last visit', 'muted' => true]) + @endif + @if ($notification->createdAt && ($before?->createdAt === null || Display::dayKey($before->createdAt) !== Display::dayKey($notification->createdAt))) + @include('native.partials.day-marker', ['label' => Display::dayLabel($notification->createdAt), 'lane' => null]) + @endif + @include('native.partials.notification', [ + 'notification' => $notification, + 'isNew' => $notification->isNewSince($readAt), + 'withoutBottomBorder' => $lastVisitBefore !== null && ($notifications[$index + 1] ?? null)?->id === $lastVisitBefore, + ]) @endforeach - + + @if ($end === 'more') + + + + @elseif ($end === 'oldest') + {{-- The web's footer: a hollow root node in the oldest one's lane, with no line into it. --}} + @include('native.partials.rail-end', ['message' => "That's the oldest notification. There's nothing before it.", 'lane' => end($notifications)->actor->lane(), 'ref' => 'oldest-notification']) + @endif + diff --git a/resources/views/native/partials/last-visit-marker.blade.php b/resources/views/native/partials/last-visit-marker.blade.php index a5290c8e..d9484726 100644 --- a/resources/views/native/partials/last-visit-marker.blade.php +++ b/resources/views/native/partials/last-visit-marker.blade.php @@ -1,7 +1,19 @@ {{-- Between the commits that came in since your last visit and the first one you'd already seen: a muted mono `HEAD@{last visit}` and a dashed hairline, drawn in short dashes since EDGE has no dashed borders. + $muted draws it as the web's inbox does instead: a band in a wash of the muted colour with a little room above and + below, and no line. --}} +@if ($muted ?? false) + + + + + HEAD@{last visit} + + + +@else @@ -18,3 +30,4 @@ @include('native.partials.rail', ['previous' => $lane]) +@endif diff --git a/resources/views/native/partials/notification.blade.php b/resources/views/native/partials/notification.blade.php index 0f89f27f..c0416a99 100644 --- a/resources/views/native/partials/notification.blade.php +++ b/resources/views/native/partials/notification.blade.php @@ -1,67 +1,99 @@ +@use('App\Devnull\Display') +@use('App\Devnull\Lane') +@use('App\Icons\Lucide') + {{-- - A group of notifications on the inbox's Rail Gray rail, as the web draws it. Its node is a 36pt hollow circle - holding the type's icon in the person's lane (a moderator's stays muted), ringed in Commit Blue when it's new - ($isNew). A line of stacked avatars and the time, then the sentence: the person's name, their handle when they act - alone, otherwise "and N others", and what they did. Someone else's words follow at 15pt like a commit; your own - commit sits under a star or a verdict in a muted hairline box. A rejection gives the moderator's reason. A level-up - names nobody either: a chip in your lane with the level and rank, and what the rank means under the sentence. + A group of notifications, as the web's inbox draws it: on its own rail in the lane of whoever it's about, running + from its node down to a dot, like a lone commit on the Log. + + Someone else's commit (a reply, a quote, a mention, a first commit) leads with them: their avatar ringed in their + lane is the node, then their name, handle and the time, what they did in a muted line, and their words. + + Everything else has a 36pt hollow circle in the lane with the kind's icon (a moderator's stays muted), a row of + stacked avatars and the time (or a chip for a verdict or a level-up), then the sentence: the person's name, their + handle when they act alone, both names for two, "and N others" for more, and what they did. Your own commit sits + under a star or a verdict in a muted hairline box. A rejection gives the moderator's reason, a timeout its reason, + how long and when posting resumes, a level-up what the rank means. A group of more than one opens in place from a Commit Blue toggle ("5 stars"), listing each event behind a Rail - Gray guide line, each follower with their own follow back. A group of followers has none of its own, as the web - leaves it out, since it could only follow one of them back, and a tap on it opens the list rather than the latest - follower's profile. + Gray guide line (see notification-group). A group of followers has no follow back of its own, as on the web. No press-* feedback: on iOS it holds any drag that starts on the row, and these rows cover the whole list. The name's run carries font-semibold as well as the font: inside a sentence, NativeUITextRenderer sets each run's weight from font_weight over the face it was given, so the face alone draws regular. --}} -@php($icon = \App\Icons\Lucide::forNotification($notification->type)) -@php($lane = \App\Devnull\Lane::token($notification->actor->lane())) +@php($laneNumber = $notification->actor->lane()) +@php($lane = Lane::token($laneNumber)) +@php($icon = Lucide::forNotification($notification->type)) @php($iconColour = $notification->isModeration() ? 'text-theme-ink-muted' : 'text-theme-'.$lane) @php($open = array_key_exists($notification->id, $expanded)) @php($failed = in_array($notification->id, $failedGroups, true)) @php($noun = $notification->groupNoun()) +@php($second = $notification->secondActor()) +@php($withoutBottomBorder ??= false) +@php($time = Display::relativeTime($notification->createdAt)) - + - - @if ($notification->isLevelUp()) - @if ($notification->levelLabel() !== null) - - {{ $notification->levelLabel() }} + @if ($notification->isActorsCommit()) + + {{ $notification->actor->name }} + {{ $notification->actor->handle() }} + + {{ $time }} + + {{ ucfirst($notification->sentence()) }} + @else + + @if ($notification->isLevelUp()) + @if ($notification->levelLabel() !== null) + + {{ $notification->levelLabel() }} + + @endif + @elseif ($notification->isModeration()) + + {{ $notification->type }} + @else + @include('native.partials.stacked-avatars', ['id' => $notification->id, 'actors' => $notification->actors, 'more' => max(0, $notification->actorsCount - count($notification->actors))]) @endif - @elseif ($notification->isModeration()) - - {{ $notification->type }} - - @else - @include('native.partials.stacked-avatars', ['id' => $notification->id, 'actors' => $notification->actors, 'more' => max(0, $notification->actorsCount - count($notification->actors))]) - @endif - - {{ \App\Devnull\Display::relativeTime($notification->createdAt) }} - @if ($notification->isFollow() && $notification->actorsCount === 1 && $notification->actorIsFollowed !== null) - @include('native.partials.follow-back', ['actor' => $notification->actor, 'isFollowing' => $notification->actorIsFollowed]) - @endif - + + {{ $time }} + @if ($notification->isFollow() && $notification->actorsCount === 1 && $notification->actorIsFollowed !== null) + @include('native.partials.follow-back', ['actor' => $notification->actor, 'isFollowing' => $notification->actorIsFollowed]) + @endif + - @if ($notification->namesNobody()) - {{ $notification->sentence() }}. - @else + @if ($notification->namesNobody()) + {{ $notification->sentence() }}. + @else -@if ($notification->others() === '') +@if ($second !== null) + + + +@elseif ($notification->others() === '') @else @endif + @endif @endif - @if ($notification->body !== null && ! $notification->isFollow()) + @if ($notification->isTimeout() && $notification->timeoutReason !== null) + + + @if ($notification->timeoutEndsAt !== null) + Posting resumes {{ Display::fullDateTime($notification->timeoutEndsAt) }}. + @endif + + @elseif ($notification->body !== null && ! $notification->isFollow() && ! $notification->isTimeout()) @if ($notification->isAboutYourCommit()) {{ $notification->body }} @@ -80,14 +112,14 @@ @if ($notification->reason) reason: {{ $notification->reason }} @endif - Only you can see this update and your rejected commit. + {{ $notification->organization === null ? 'Only you can see this update and your rejected commit.' : "Only @{$notification->organization}'s members can see this update and its rejected commit." }} @endif @if ($notification->isGrouped()) - + {{ $open ? 'Hide '.$noun : $notification->eventCount.' '.$noun }} @@ -97,18 +129,30 @@ @endif @endif - + @unless ($withoutBottomBorder) + + @endunless - {{-- The Rail Gray rail runs the whole inbox, through each node. --}} - @if ($hasPrevious) - + {{-- Its own rail, drawn last so it sits on top: the node, a line in the lane down to a dot 20pt above the bottom. --}} + @if ($notification->isActorsCommit()) + @include('native.partials.rail', [ + 'previous' => null, + 'lane' => $laneNumber, + 'tail' => $laneNumber, + 'node' => 'avatar', + 'user' => $notification->actor, + 'press' => "openActor('{$notification->actor->username}')", + 'endsWithDot' => true, + ]) + @else + + @include('native.partials.rail-node', ['lane' => $laneNumber, 'nodeRef' => 'end-dot-'.$notification->id, 'position' => 'absolute bottom-[11] left-[23]']) + + + + + @endif - - - - - - diff --git a/resources/views/native/partials/notifications-page.blade.php b/resources/views/native/partials/notifications-page.blade.php deleted file mode 100644 index 56669408..00000000 --- a/resources/views/native/partials/notifications-page.blade.php +++ /dev/null @@ -1,69 +0,0 @@ -{{-- - One filter's page in the Notifications pager (see App\NativeComponents\Notifications::page()): the filter you're on, - or the first few groups kept for one beside it, ready for a swipe. - - Each filter has its own list, and one you leave starts again at the top of a fresh one: a list kept while every row - changed under its scroll offset drew blank on iOS. Only the filter you're on asks for its next page, since a page - laid out off screen still shows its rows, and every page keeps pull to refresh, since iOS builds a new list when a - list gains or loses it. ---}} - - - @if (! $page['loaded'] && $page['error'] === null) - - - - @endif - - @if ($page['loaded'] && $page['notifications'] === [] && $page['error'] === null) - - {{ $page['type'] === 'all' ? '$ cat /dev/notifications' : '$ cat /dev/notifications | grep '.$page['type'] }} - {{ $types[$page['type']][1] }} - @if ($page['type'] !== 'all') - - Show all notifications - - @endif - - @endif - - @foreach ($page['notifications'] as $index => $notification) - @php($previous = $page['notifications'][$index - 1] ?? null) - @if ($notification->id === $page['lastVisitBefore']) - @include('native.partials.last-visit-marker', ['lane' => \App\Devnull\Lane::Rail, 'label' => 'Notifications above are new since your last visit']) - @endif - @if ($notification->createdAt && ($previous?->createdAt === null || \App\Devnull\Display::dayKey($previous->createdAt) !== \App\Devnull\Display::dayKey($notification->createdAt))) - @include('native.partials.day-marker', ['label' => \App\Devnull\Display::dayLabel($notification->createdAt), 'lane' => $previous === null ? null : \App\Devnull\Lane::Rail]) - @endif - @include('native.partials.notification', [ - 'notification' => $notification, - 'hasPrevious' => $previous !== null, - 'isNew' => $notification->isNewSince($readAt), - 'expanded' => $page['expanded'], - 'expandedCursors' => $page['expandedCursors'], - 'failedGroups' => $page['failedGroups'], - ]) - @endforeach - - @if ($page['end'] === 'more') - - - - @elseif ($page['end'] === 'oldest') - - - - That's the oldest notification. There's nothing before it. - - @include('native.partials.rail', ['previous' => \App\Devnull\Lane::Rail, 'lane' => \App\Devnull\Lane::Rail, 'node' => 'root']) - - @endif - - diff --git a/resources/views/native/partials/rail-end.blade.php b/resources/views/native/partials/rail-end.blade.php index 5ea2e5a2..dc694c60 100644 --- a/resources/views/native/partials/rail-end.blade.php +++ b/resources/views/native/partials/rail-end.blade.php @@ -1,5 +1,5 @@ {{-- The end of history: a hollow root node on its own, with no tail, and a dry line beside it, as on the web. --}} - + {{ $message }} diff --git a/routes/mobile.php b/routes/mobile.php index 764b9a27..25208b58 100644 --- a/routes/mobile.php +++ b/routes/mobile.php @@ -15,6 +15,7 @@ use App\NativeComponents\NewOrg; use App\NativeComponents\NewRemote; use App\NativeComponents\Notifications; +use App\NativeComponents\NotificationSettings; use App\NativeComponents\Onboarding; use App\NativeComponents\Organization; use App\NativeComponents\OrgMembers; @@ -46,6 +47,7 @@ Route::nativeGroup(TabsLayout::class, function (): void { Route::native('/log', Log::class); Route::native('/notifications', Notifications::class); + Route::native('/notifications/settings', NotificationSettings::class); Route::native('/remotes', Remotes::class); Route::native('/remotes/new', NewRemote::class); Route::native('/remotes/new-org', NewOrg::class); diff --git a/tests/Feature/Screens/LaneButtonsTest.php b/tests/Feature/Screens/LaneButtonsTest.php index 3e966d04..10740266 100644 --- a/tests/Feature/Screens/LaneButtonsTest.php +++ b/tests/Feature/Screens/LaneButtonsTest.php @@ -125,7 +125,7 @@ function laneLog(): TestableComponent ->and(strtolower($pager['props']['dark_tab_indicator_color']))->toBe(strtolower(config("native-ui.theme.dark.lane-{$lane}"))) // Only the underline: the labels stay ink. ->and($pager['props']['tab_active_color'])->toBe(config('native-ui.theme.light.ink')); -})->with(['/log', '/notifications'])->with([2, 5]); +})->with(['/log'])->with([2, 5]); it('draws the underline under your profile\'s tabs in your lane too', function () { signIn(['lane' => 5]); diff --git a/tests/Feature/Screens/NotificationSettingsTest.php b/tests/Feature/Screens/NotificationSettingsTest.php new file mode 100644 index 00000000..c15d7ef2 --- /dev/null +++ b/tests/Feature/Screens/NotificationSettingsTest.php @@ -0,0 +1,76 @@ + 'http://devnull.test']); + signIn(); +}); + +it("has a real switch for each of the web's kinds, all on until you turn one off", function () { + $screen = Native::visit('/notifications/settings') + ->assertNavTitle('Notification settings') + ->assertSee('Show in Notifications'); + + foreach (NotificationFilter::Kinds as $kind => [$label, $description]) { + $switch = nodeByRef($screen, "kind-{$kind}-switch"); + + $screen->assertSee($label)->assertSee($description); + + expect($switch['type'])->toBe('toggle') + ->and($switch['props']['value'] ?? null)->toBeTrue() + ->and($switch['props']['a11y_label'] ?? null)->toBe($label); + } +}); + +it('saves each switch as it flips, for you on this phone, without asking devnull', function () { + Http::fake(); + $me = app(Account::class)->user()->id; + + $screen = Native::visit('/notifications/settings')->toggle('kind-stars-switch', false); + + expect(app(NotificationFilter::class)->enabled($me))->toBe(['replies', 'quotes', 'mentions', 'follows', 'moderation']) + ->and(nodeByRef($screen, 'kind-stars-switch')['props']['value'] ?? null)->toBeFalse(); + + $screen->toggle('kind-replies-switch', false)->toggle('kind-stars-switch', true); + + expect(app(NotificationFilter::class)->enabled($me))->toBe(['quotes', 'stars', 'mentions', 'follows', 'moderation']); + + // Opened again, it shows what was saved. + expect(nodeByRef(Native::visit('/notifications/settings'), 'kind-replies-switch')['props']['value'] ?? null)->toBeFalse(); + + Http::assertNothingSent(); +}); + +it('turns every kind off, which the list then says, and ignores a kind it does not know', function () { + $me = app(Account::class)->user()->id; + $screen = Native::visit('/notifications/settings'); + + foreach (array_keys(NotificationFilter::Kinds) as $kind) { + $screen->toggle("kind-{$kind}-switch", false); + } + + $screen->call('setKind', 'reactions', true); + + expect(app(NotificationFilter::class)->enabled($me))->toBe([]) + ->and(NotificationFilter::type([]))->toBe('none'); +}); + +it('keeps each user their own choice', function () { + $filter = app(NotificationFilter::class); + + $filter->save('someone', ['stars']); + + expect($filter->enabled('someone-else'))->toBe(array_keys(NotificationFilter::Kinds)) + ->and($filter->enabled('someone'))->toBe(['stars']) + ->and($filter->enabled(null))->toBe(array_keys(NotificationFilter::Kinds)); + + // Unknown kinds are dropped, and the rest go back in the web's order. + $filter->save('someone', ['follows', 'nope', 'replies', 'follows']); + + expect($filter->enabled('someone'))->toBe(['replies', 'follows']) + ->and(NotificationFilter::type(['follows', 'replies']))->toBe('replies,follows'); +}); diff --git a/tests/Feature/Screens/NotificationsCacheTest.php b/tests/Feature/Screens/NotificationsCacheTest.php index fc7d5a8f..f69ca04a 100644 --- a/tests/Feature/Screens/NotificationsCacheTest.php +++ b/tests/Feature/Screens/NotificationsCacheTest.php @@ -26,9 +26,9 @@ function serveNotifications(array $groups, int $unread = 0): void 'GET /api/v1/me' => [['data' => userWithCountsJson(), 'unread_notifications_count' => 0]], ]); - // New on this visit, so its node is ringed in Commit Blue. - Native::visit('/notifications')->assertElement('stack', fn (array $node): bool => ($node['ref'] ?? null) === 'node-n-followed' - && ($node['style']['border_color'] ?? $node['style']['borderColor'] ?? null) === config('native-ui.theme.light.primary')); + // New on this visit, so the row says so to a screen reader, as the web's does. + Native::visit('/notifications')->assertElement('pressable', fn (array $node): bool => ($node['ref'] ?? null) === 'notification-n-followed' + && str_starts_with((string) ($node['props']['a11y_label'] ?? ''), 'New. ')); expect(kept('notifications')['data'][0]['unread_count'])->toBe(0) ->and(kept('notifications'))->not->toHaveKey('read_at'); diff --git a/tests/Feature/Screens/NotificationsTest.php b/tests/Feature/Screens/NotificationsTest.php index b160b4ef..04ca4c2e 100644 --- a/tests/Feature/Screens/NotificationsTest.php +++ b/tests/Feature/Screens/NotificationsTest.php @@ -1,7 +1,9 @@ $kinds + */ +function chooseKinds(array $kinds): void +{ + app(NotificationFilter::class)->save(app(Account::class)->user()?->id, $kinds); +} + /** * The colour a node's ring is drawn in. */ @@ -123,6 +135,7 @@ function ringColour(TestableComponent $screen, string $id): ?string notificationJson('quoted', ['id' => 'n-quoted', 'commit' => notificationCommitJson(['id' => 'q1', 'body' => 'Quoting this one.'])]), notificationJson('mentioned', ['actor' => personJson('grace', 'Grace'), 'actors' => [personJson('grace', 'Grace')], 'commit' => notificationCommitJson(['id' => 'm1', 'body' => 'Ask @local_dev about it'])]), notificationJson('followed', ['created_at' => now()->subDays(2)->toIso8601ZuluString(), 'actor' => personJson('linus', 'Linus'), 'actors' => [personJson('linus', 'Linus')]]), + notificationJson('starred', ['actor' => personJson('linus', 'Linus'), 'actors' => [personJson('linus', 'Linus')]]), ])]]); $screen = Native::visit('/notifications') @@ -133,9 +146,10 @@ function ringColour(TestableComponent $screen, string $id): ?string ->assertSee('Ask @local_dev about it') ->assertSee('2d'); - expect(paragraphRuns($screen, 'replied to your commit'))->toBe([['Ada', 'link'], [' '], ['@ada', 'mention'], [' replied to your commit']]) - ->and(paragraphRuns($screen, 'quoted your commit'))->toBe([['Ada', 'link'], [' '], ['@ada', 'mention'], [' quoted your commit']]) - ->and(paragraphRuns($screen, 'mentioned you'))->toBe([['Grace', 'link'], [' '], ['@grace', 'mention'], [' mentioned you']]) + // Someone's own words lead with them, their handle and what they did on a line of its own. + $screen->assertSee('Replied to your commit')->assertSee('Quoted your commit')->assertSee('Mentioned you'); + + expect(paragraphRuns($screen, 'starred your commit'))->toBe([['Linus', 'link'], [' '], ['@linus', 'mention'], [' starred your commit']]) ->and(paragraphRuns($screen, 'followed you'))->toBe([['Linus', 'link'], [' '], ['@linus', 'mention'], [' followed you']]) ->and(stackedAvatars($screen, 'n-followed'))->toBe(['https://avatars.test/linus']); }); @@ -224,7 +238,7 @@ function ringColour(TestableComponent $screen, string $id): ?string ->assertSee('Only you can see this update and your rejected commit.'); }); -it('rings what arrived since your last visit in blue, above the last-visit marker, with day markers between days', function () { +it('draws each group on its own rail in its lane, ending in a dot, with HEAD@{last visit} under the new ones and day markers between days', function () { // At midday, so a notification from a few hours ago is always today's. $this->travelTo(now()->setTime(12, 0)); $this->freezeTime(); @@ -233,22 +247,96 @@ function ringColour(TestableComponent $screen, string $id): ?string fakeApi(['GET /api/v1/notifications' => [inboxJson([ // Marked read just now, by this very listing. - notificationJson('mentioned', ['read_at' => $readAt->toIso8601ZuluString()]), + notificationJson('mentioned', ['read_at' => $readAt->toIso8601ZuluString(), 'actor' => personJson('grace', 'Grace', 5)]), // Read on an earlier visit. - notificationJson('followed', ['read_at' => now()->subDay()->toIso8601ZuluString(), 'created_at' => now()->subDays(3)->toIso8601ZuluString()]), + notificationJson('followed', ['read_at' => now()->subDay()->toIso8601ZuluString(), 'created_at' => now()->subDays(3)->toIso8601ZuluString(), 'actor' => personJson('linus', 'Linus', 4)]), ], readAt: $readAt->toIso8601ZuluString())]]); $screen = Native::visit('/notifications'); - expect(ringColour($screen, 'n-mentioned'))->toBe(config('native-ui.theme.light.primary')) - ->and(ringColour($screen, 'n-followed'))->toBe(config('native-ui.theme.light.rail')); + // A follow's node is a hollow circle in the follower's lane; nothing is ringed in blue for being new. + expect(ringColour($screen, 'n-followed'))->toBe(config('native-ui.theme.light.lane-4')) + // A mention leads with the person who wrote it: their avatar on the rail, ringed in their lane. + ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'node-n-mentioned'))->toBeNull() + ->and(nodeByRef($screen, 'end-dot-n-followed'))->not->toBeNull() + ->and(nodeByRef($screen, 'end-dot'))->not->toBeNull(); $refs = array_values(array_filter(array_map( fn (array $node): ?string => $node['ref'] ?? null, findNodes($screen->tree(), fn (array $node): bool => preg_match('/^(day-|last-visit$|notification-)/', (string) ($node['ref'] ?? '')) === 1), ))); - expect($refs)->toBe(['day-Today', 'notification-n-mentioned', 'last-visit', 'day-'.Display::dayLabel(now()->subDays(3)), 'notification-n-followed']); + expect($refs)->toBe(['day-Today', 'notification-n-mentioned', 'last-visit', 'day-'.Display::dayLabel(now()->subDays(3)), 'notification-n-followed']) + ->and($screen->instance()->readAt)->toBe($readAt->toIso8601ZuluString()); +}); + +it('leads a reply, quote, mention or first commit with whoever wrote it, then what they did, then their words', function (string $type, string $action) { + fakeApi(['GET /api/v1/notifications' => [inboxJson([notificationJson($type, ['actor' => personJson('grace', 'Grace', 5)])])]]); + + $screen = Native::visit('/notifications') + ->assertSee('Grace') + ->assertSee('@grace') + ->assertSee($action) + ->assertSee('3h'); + + expect(nodeByRef($screen, 'action-n-'.$type)['props']['text'] ?? null)->toBe($action); + + $screen->tap('actor-name-n-'.$type)->assertNavigatedTo('/notifications/users/grace'); +})->with([ + ['replied', 'Replied to your commit'], + ['quoted', 'Quoted your commit'], + ['mentioned', 'Mentioned you'], + ['first_commit', 'Made their first commit'], +]); + +it("words what you hear about for an organization as the organization's, as the web does", function () { + $org = ['handle' => 'acme', 'name' => 'Acme', 'avatar_url' => null, 'lane' => 2]; + + fakeApi(['GET /api/v1/notifications' => [inboxJson([ + notificationJson('replied', ['organization' => $org]), + notificationJson('mentioned', ['organization' => $org]), + notificationJson('starred', ['organization' => $org]), + notificationJson('rejected', ['organization' => $org, 'reason' => 'Spam']), + ])]]); + + Native::visit('/notifications') + ->assertSee("Replied to @acme's commit") + ->assertSee('Mentioned @acme') + ->assertSee(" starred @acme's commit") + ->assertSee("@acme's commit was rejected.") + ->assertSee("Only @acme's members can see this update and its rejected commit."); +}); + +it('names both people when two follow you or star your commit', function () { + fakeApi(['GET /api/v1/notifications' => [inboxJson([notificationJson('followed', [ + 'actor' => personJson('grace', 'Grace'), + 'actors' => [personJson('grace', 'Grace'), personJson('linus', 'Linus')], + 'actors_count' => 2, + 'event_count' => 2, + ])])]]); + + $screen = Native::visit('/notifications'); + + expect(paragraphRuns($screen, 'followed you'))->toBe([['Grace', 'link'], [' '], ['and '], ['Linus', 'link'], [' followed you']]); + + $screen->tap('second-actor-n-followed')->assertNavigatedTo('/notifications/users/linus'); +}); + +it('says why and for how long you were put in timeout, and when posting resumes', function () { + fakeApi(['GET /api/v1/notifications' => [inboxJson([notificationJson('timed_out', [ + 'actor' => userJson(), + 'commit' => null, + 'timeout' => ['reason' => 'Spam', 'duration' => '1 day', 'ends_at' => '2026-11-16T10:00:00Z'], + ])])]]); + + $screen = Native::visit('/notifications', platform: 'ios') + ->assertSee('You were put in timeout.') + ->assertSee('Spam') + ->assertSee('1 day') + ->assertSee('Posting resumes') + ->assertElement('icon', fn (array $node): bool => ($node['props']['name'] ?? null) === 'custom:hourglass'); + + $screen->tap('notification-n-timed_out')->assertNavigatedTo('/notifications/users/local_dev'); }); it('opens what the web opens for each kind', function (string $type, string $destination) { @@ -257,6 +345,8 @@ function ringColour(TestableComponent $screen, string $id): ?string Native::visit('/notifications')->tap('notification-n-'.$type)->assertNavigatedTo($destination); })->with([ ['replied', '/notifications/commits/c-replied'], + ['quoted', '/notifications/commits/c-quoted'], + ['first_commit', '/notifications/commits/c-first_commit'], ['starred', '/notifications/commits/c-starred'], ['mentioned', '/notifications/commits/c-mentioned'], ['approved', '/notifications/commits/c-approved'], @@ -265,126 +355,77 @@ function ringColour(TestableComponent $screen, string $id): ?string ['leveled_up', '/notifications/users/local_dev'], ]); -it("has the web's filters, each asked for by its type, with All asked for plainly", function () { - serveApi(function (Request $request) { - parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query); - $type = $query['type'] ?? 'all'; +it('has a small settings button in the title bar that opens the notification settings', function () { + fakeApi(['GET /api/v1/notifications' => [inboxJson([])]]); - return str_starts_with((string) parse_url($request->url(), PHP_URL_PATH), '/api/v1/notifications') - ? Http::response(inboxJson($type === 'stars' ? [notificationJson('starred')] : [notificationJson('followed')], $type)) - : Http::response(['data' => userWithCountsJson(), 'unread_notifications_count' => 0]); - }); + $screen = Native::visit('/notifications', platform: 'ios'); + $actions = array_column(findNodes($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'top_bar_action'), 'props'); - $screen = Native::visit('/notifications')->assertSee('followed you'); + expect($actions)->toHaveCount(1) + ->and($actions[0])->toMatchArray(['id' => 'notification-settings', 'icon' => 'custom:settings-2', 'a11y_label' => 'Notification settings']); - // The pager draws the filters along the top, in a row that scrolls, on All. - expect(nodeByRef($screen, 'notifications-pager')['props'])->toMatchArray([ - 'tabs' => ['All', 'Replies', 'Quotes', 'Stars', 'Mentions', 'Follows', 'Moderation'], - 'tabs_scrollable' => true, - 'page' => 0, - ]); + $screen->call('openSettings')->assertNavigatedTo('/notifications/settings'); +}); - tapFilter($screen, 'stars') - ->assertSet('type', 'stars') - ->assertSee('starred your commit') - ->assertDontSee('followed you'); +it('asks devnull for the kinds that are on, as the web asks: all plainly, some as a list, none as none', function (array $kinds, ?string $query) { + chooseKinds($kinds); + fakeApi(['GET /api/v1/notifications' => [inboxJson([])]]); - $urls = Http::recorded(fn (Request $request): bool => str_contains($request->url(), '/notifications'))->map(fn (array $pair): string => $pair[0]->url())->values()->all(); + Native::visit('/notifications'); - expect($urls)->toContain('http://devnull.test/api/v1/notifications', 'http://devnull.test/api/v1/notifications?type=stars'); -}); + Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/notifications'.($query === null ? '' : '?type='.$query)); +})->with([ + 'all' => [['replies', 'quotes', 'stars', 'mentions', 'follows', 'moderation'], null], + 'some' => [['stars', 'follows'], 'stars%2Cfollows'], + 'one' => [['moderation'], 'moderation'], + 'none' => [[], 'none'], +]); -it("says what each filter shows when it's empty, in the web's words, with a way back to all of them", function (string $type) { +it("says what's empty in the web's words, with a way back to all of them", function (array $kinds, string $command, string $message) { + chooseKinds($kinds); fakeApi(['GET /api/v1/notifications' => [inboxJson([])]]); - $screen = Native::test(Notifications::class)->call('show', $type) - ->assertSee($type === 'all' ? '$ cat /dev/notifications' : '$ cat /dev/notifications | grep '.$type) - ->assertSee(Notifications::Types[$type][1]); + $screen = Native::visit('/notifications')->assertSee($command)->assertSee($message); + + if (count($kinds) === 6) { + $screen->assertDontSee('Show all notifications'); - if ($type !== 'all') { - $screen->assertSee('Show all notifications')->tap('show-all')->assertSet('type', 'all'); + return; } -})->with(array_keys(Notifications::Types)); -it('keeps each filter on its own, and opens one kept before at once', function () { + $screen->tap('show-all')->assertSet('kinds', array_keys(NotificationFilter::Kinds)); + + expect(app(NotificationFilter::class)->enabled('u1'))->toBe(array_keys(NotificationFilter::Kinds)); +})->with([ + 'all' => [['replies', 'quotes', 'stars', 'mentions', 'follows', 'moderation'], '$ cat /dev/notifications', NotificationFilter::AllEmpty], + 'one' => [['stars'], "\$ cat /dev/notifications | grep -E 'stars'", 'No stars yet. When someone stars one of your commits, it shows up here.'], + 'some' => [['replies', 'mentions'], "\$ cat /dev/notifications | grep -E 'replies|mentions'", 'No notifications in the selected categories yet.'], + 'none' => [[], "\$ cat /dev/notifications | grep -E '^$'", 'All categories are turned off. Enable a category to see notifications.'], +]); + +it('starts a fresh list for the new kinds when you come back from the settings, showing what it kept for them first', function () { holdRefreshes(); keep('notifications', inboxJson([notificationJson('followed')]), ['type' => null]); keep('notifications', inboxJson([notificationJson('mentioned')], 'mentions'), ['type' => 'mentions']); serveApi(fn () => Http::response(inboxJson([]))); $screen = Native::visit('/notifications')->assertSee('followed you'); - $requests = count(Http::recorded()); + $list = showingNotifications($screen)['id']; - tapFilter($screen, 'mentions') - ->assertSee('mentioned you') + chooseKinds(['mentions']); + $screen->call('onResume') + ->assertSet('kinds', ['mentions']) + ->assertSee('Mentioned you') ->assertDontSee('followed you'); - expect(showsLoading(showingNotifications($screen)))->toBeFalse() - ->and(count(Http::recorded()))->toBe($requests) - ->and(kept('notifications', ['type' => 'mentions']))->not->toBeNull() - ->and(kept('notifications', ['type' => 'stars']))->toBeNull(); -}); - -it('swipes between the filters both ways under the filters the pager draws, and stops at the ends', function () { - holdRefreshes(); - keep('notifications', inboxJson([notificationJson('followed')]), ['type' => null]); - keep('notifications', inboxJson([notificationJson('replied')], 'replies'), ['type' => 'replies']); - serveApi(fn () => Http::response(inboxJson([]))); - - $screen = Native::visit('/notifications'); - $pager = fn (): array => nodeByRef($screen, 'notifications-pager'); - - // All is first: it and Replies are shipped, nothing before it. The pager says where it is once a swipe has settled. - expect($pager()['props'])->toMatchArray(['horizontal' => true, 'count' => 7, 'page' => 0, 'window_from' => 0, 'window_to' => 1, 'report_on_settle' => true]) - ->and($pager()['props'])->toHaveKey('on_tab_reselect') - ->and(treeShows(nodeByRef($screen, 'notifications-replies'), 'replied'))->toBeTrue(); - - $screen->changeTab('showPage', 1)->assertSet('type', 'replies'); - - expect($pager()['props'])->toMatchArray(['page' => 1, 'window_from' => 0, 'window_to' => 2]) - ->and(treeShows(showingNotifications($screen), 'replied'))->toBeTrue() + expect(showingNotifications($screen)['id'])->not->toBe($list) ->and(showsLoading(showingNotifications($screen)))->toBeFalse(); - $screen->changeTab('showPage', 0)->assertSet('type', 'all'); - - expect($pager()['props']['page'])->toBe(0); - - // Nothing before All, and no wrapping round from Moderation to All. - $screen->changeTab('showPage', -1)->assertSet('type', 'all'); - $screen->changeTab('showPage', 6)->assertSet('type', 'moderation'); - - expect($pager()['props'])->toMatchArray(['page' => 6, 'window_from' => 5, 'window_to' => 6]); - - $screen->changeTab('showPage', 7)->assertSet('type', 'moderation'); -}); - -it('gives each filter its own list, starts the one you leave again in a fresh one, and only lets the one you are on page', function () { - holdRefreshes(); - keep('notifications', inboxJson([notificationJson('followed')]), ['type' => null]); - keep('notifications', inboxJson(array_map(fn (int $n): array => notificationJson('replied', ['id' => "r{$n}"]), range(1, 10)), 'replies', cursor: 'next'), ['type' => 'replies']); - serveApi(fn () => Http::response(inboxJson([]))); - - $screen = Native::visit('/notifications'); - $all = showingNotifications($screen)['id']; - $replies = nodeByRef($screen, 'notifications-replies'); - - // Beside All, Replies shows the first few groups kept for it, with nothing under them yet. - expect(count(findNodes($replies, fn (array $node): bool => str_starts_with((string) ($node['ref'] ?? ''), 'notification-'))))->toBe(Notifications::PreviewGroups) - ->and(showsLoading($replies))->toBeFalse() - ->and($replies['props'])->toHaveKey('on_refresh') - ->and($replies['props'])->not->toHaveKey('on_end_reached') - ->and(showingNotifications($screen)['props'])->toHaveKey('on_end_reached'); + // Nothing changed: the same list, asked again behind it. + $list = showingNotifications($screen)['id']; + $screen->call('onResume'); - $screen->changeTab('showPage', 1); - - // Swiped to, Replies keeps its list and fills it. All, left behind, starts again at the top of a fresh one. - expect(showingNotifications($screen)['id'])->toBe($replies['id']) - ->and(nodeByRef($screen, 'notifications-all')['id'])->not->toBe($all); - - // The filter you're on takes you back to its top. - tapFilter($screen, 'replies'); - - expect(showingNotifications($screen)['id'])->not->toBe($replies['id']); + expect(showingNotifications($screen)['id'])->toBe($list); }); it('opens a group in place, as the web expands it, and folds it away again', function () { @@ -410,14 +451,17 @@ function ringColour(TestableComponent $screen, string $id): ?string expect(array_map(fn ($item): string => $item->id, $screen->instance()->expanded['n-starred']))->toBe(['n-star-2', 'n-star-1']) ->and(childRefs($screen, 'group-items-n-starred'))->toContain('group-item-n-star-2', 'group-item-n-star-1'); - $screen->tap('group-item-n-star-1')->assertNavigatedTo('/notifications/commits/c-starred'); + // One star in the group opens whoever gave it, as the web's does: the group above it already opens the commit. + $screen->tap('group-item-n-star-1')->assertNavigatedTo('/notifications/users/ada'); Native::visit('/notifications')->tap('group-n-starred')->tap('group-n-starred')->assertSee('2 stars')->assertDontSee('Hide stars'); Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/notifications/n-starred/group'); }); -it('opens a group with the filter it was listed under, and pages its older ones', function () { +it('opens a group with the kinds it was listed under, and pages its older ones', function () { + chooseKinds(['follows']); + serveApi(function (Request $request) { $url = $request->url(); @@ -428,7 +472,7 @@ function ringColour(TestableComponent $screen, string $id): ?string }; }); - Native::test(Notifications::class)->call('show', 'follows') + Native::visit('/notifications') ->tap('group-n-followed') ->assertSee('Show older followers') ->tap('group-older-n-followed') diff --git a/tests/Feature/Screens/ShownTabsTest.php b/tests/Feature/Screens/ShownTabsTest.php index d1f04aaf..dd6f5f84 100644 --- a/tests/Feature/Screens/ShownTabsTest.php +++ b/tests/Feature/Screens/ShownTabsTest.php @@ -39,12 +39,12 @@ function shownTabsProfileJson(string $username): array Http::assertNotSent(fn (Request $request): bool => str_starts_with($request->url(), 'http://devnull.test/api/v1/log/following')); }); -it('opens Notifications on the filter you last had open', function () { - Http::fake(['devnull.test/*' => Http::response(['data' => [], 'next_cursor' => null, 'read_at' => null, 'filters' => ['type' => 'all']])]); +it('opens Notifications on the kinds you chose last time', function () { + Http::fake(['devnull.test/*' => Http::response(['data' => [], 'next_cursor' => null, 'read_at' => null, 'filters' => ['type' => 'mentions']])]); - tapFilter(Native::visit('/notifications'), 'mentions')->assertSet('type', 'mentions'); + Native::visit('/notifications/settings')->toggle('kind-replies-switch', false); - Native::visit('/notifications')->assertSet('type', 'mentions'); + Native::visit('/notifications')->assertSet('kinds', ['quotes', 'stars', 'mentions', 'follows', 'moderation']); }); it("opens your own profile on the tab you last had open, but someone else's on their commits", function () { diff --git a/tests/Pest.php b/tests/Pest.php index 41e32e2e..53b9f9a0 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -269,15 +269,6 @@ function tapProfileTab(TestableComponent $screen, string $tab): TestableComponen return $screen->changeTab($screen->get('tab') === $tab ? 'backToTop' : 'showPage', (int) array_search($tab, Profile::Tabs, true)); } -/** - * A tap on one of the notifications filters along the top, which the pager - * draws, as for the Log's tabs (see tapLogTab). - */ -function tapFilter(TestableComponent $screen, string $type): TestableComponent -{ - return $screen->changeTab($screen->get('type') === $type ? 'backToTop' : 'showPage', (int) array_search($type, array_keys(Notifications::Types), true)); -} - /** * Whether a tree shows some text. *