From c1fe912766384907585918b94845eb319a6c2c48 Mon Sep 17 00:00:00 2001 From: Shane Smith Date: Sat, 21 Nov 2026 11:14:49 +1030 Subject: [PATCH] [Guilds] Open a guild's page, with pinned commit at the top --- app/Devnull/Client.php | 11 + app/Devnull/Data/GuildBoard.php | 39 +++ app/Devnull/ResponseCache.php | 1 + app/Devnull/SiteLink.php | 18 +- .../Concerns/HoldsNewCommits.php | 14 +- app/NativeComponents/Concerns/OpensGuilds.php | 16 + .../Concerns/RefreshesInBackground.php | 7 +- .../Concerns/ShowsCommits.php | 1 + app/NativeComponents/Connections.php | 2 +- app/NativeComponents/Guild.php | 323 ++++++++++++++++++ app/NativeComponents/Guilds.php | 15 +- app/NativeComponents/Profile.php | 2 +- app/NativeComponents/Remotes.php | 2 +- resources/views/native/guild.blade.php | 74 ++++ .../native/partials/guild-badge.blade.php | 7 +- .../native/partials/guild-header.blade.php | 31 ++ .../views/native/partials/guild-row.blade.php | 3 +- routes/mobile.php | 8 +- tests/Feature/Devnull/ClientCacheTest.php | 20 ++ tests/Feature/Devnull/ResponseCacheTest.php | 5 + tests/Feature/Devnull/SiteLinkTest.php | 13 + tests/Feature/Screens/CommitCardTest.php | 10 +- tests/Feature/Screens/GuildTest.php | 294 ++++++++++++++++ tests/Feature/Screens/GuildsTest.php | 46 +-- tests/Feature/Screens/LogTest.php | 9 + tests/Pest.php | 42 +++ tests/Unit/Devnull/GuildBoardTest.php | 23 ++ 27 files changed, 966 insertions(+), 70 deletions(-) create mode 100644 app/Devnull/Data/GuildBoard.php create mode 100644 app/NativeComponents/Concerns/OpensGuilds.php create mode 100644 app/NativeComponents/Guild.php create mode 100644 resources/views/native/guild.blade.php create mode 100644 resources/views/native/partials/guild-header.blade.php create mode 100644 tests/Feature/Screens/GuildTest.php create mode 100644 tests/Unit/Devnull/GuildBoardTest.php diff --git a/app/Devnull/Client.php b/app/Devnull/Client.php index a289f69a..7337c382 100644 --- a/app/Devnull/Client.php +++ b/app/Devnull/Client.php @@ -8,6 +8,7 @@ use App\Devnull\Data\CurrentUser; use App\Devnull\Data\DraftImage; use App\Devnull\Data\Guild; +use App\Devnull\Data\GuildBoard; use App\Devnull\Data\IncomingCall; use App\Devnull\Data\MessageVoice; use App\Devnull\Data\Notification; @@ -471,6 +472,16 @@ public function guilds(string $term = '', ?string $page = null): Page return new Page(array_values(array_filter($guilds->items)), $guilds->nextCursor); } + /** + * A guild's bulletin board: its latest commits and the one pinned to the top. Null when the answer carries + * no guild. A handle devnull has no guild by is a 404, which throws, as does guilds being switched off for + * you. Page 1 is asked for with no page number, so it's kept. + */ + public function guild(string $handle, ?string $page = null): ?GuildBoard + { + return GuildBoard::fromArray($this->get('guilds/'.rawurlencode($handle), ['page' => $page])); + } + /** * A page of your Remotes inbox, newest first, for the web's Open, Fetched * or Stashed tab, continuing before a conversation. diff --git a/app/Devnull/Data/GuildBoard.php b/app/Devnull/Data/GuildBoard.php new file mode 100644 index 00000000..95db96c4 --- /dev/null +++ b/app/Devnull/Data/GuildBoard.php @@ -0,0 +1,39 @@ + $commits + */ + public function __construct( + public Guild $guild, + public Page $commits, + public ?Commit $pinned, + ) {} + + /** + * @param array $json + */ + public static function fromArray(array $json): ?self + { + $guild = is_array($json['guild'] ?? null) ? Guild::fromArray($json['guild']) : null; + + if ($guild === null) { + return null; + } + + return new self( + guild: $guild, + commits: Page::fromArray($json, Commit::fromArray(...)), + pinned: is_array($json['pinned_commit'] ?? null) ? Commit::fromArray($json['pinned_commit']) : null, + ); + } +} diff --git a/app/Devnull/ResponseCache.php b/app/Devnull/ResponseCache.php index dc8af583..8ee68c26 100644 --- a/app/Devnull/ResponseCache.php +++ b/app/Devnull/ResponseCache.php @@ -53,6 +53,7 @@ final class ResponseCache '#^remotes/orgs/[^/]+/messages$#', '#^scheduled-commits$#', '#^guilds$#', + '#^guilds/[^/]+$#', ]; /** diff --git a/app/Devnull/SiteLink.php b/app/Devnull/SiteLink.php index 6aa1acd3..474fba79 100644 --- a/app/Devnull/SiteLink.php +++ b/app/Devnull/SiteLink.php @@ -17,7 +17,8 @@ final class SiteLink { /** * The web's pages the app has a screen for, and that screen. {user} is a - * GitHub username, {id} a commit's or an org's id, and {photo} anything. + * GitHub username, {id} a commit's or an org's id, {handle} a guild's, + * and {photo} anything. */ private const array Screens = [ '/@{user}' => '/users/{user}', @@ -26,6 +27,8 @@ final class SiteLink '/@{user}/commits/{id}/photos/{photo}' => '/commits/{id}', '/remotes/@{user}' => '/conversations/{user}', '/remotes/orgs/{id}' => '/orgs/{id}', + '/guilds' => '/guilds', + '/guilds/{handle}' => '/guilds/{handle}', ]; /** @@ -38,6 +41,11 @@ final class SiteLink */ private const string Username = '[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}'; + /** + * A guild's handle once decoded, as the web allows one (CreateGuildRequest). + */ + private const string Handle = '/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD'; + /** * A UUID in either case. */ @@ -59,9 +67,16 @@ public static function screen(?string $url): ?string foreach (self::Screens as $page => $screen) { if (preg_match(self::pattern($page), $path, $matches) === 1) { + $handle = rawurldecode($matches['handle'] ?? ''); + + if (isset($matches['handle']) && (mb_strlen($handle) > 60 || preg_match(self::Handle, $handle) !== 1)) { + continue; + } + return strtr($screen, [ '{user}' => $matches['user'] ?? '', '{connections}' => $matches['connections'] ?? '', + '{handle}' => $handle, '{id}' => strtolower($matches['id'] ?? ''), ]); } @@ -119,6 +134,7 @@ private static function pattern(string $page): string return '#^'.strtr($page, [ '{user}' => '(?'.self::Username.')', '{connections}' => '(?'.implode('|', Connections::Types).')', + '{handle}' => '(?[^/]+)', '{id}' => '(?'.self::Id.')', '{photo}' => '[^/]+', ]).'/?\z#'; diff --git a/app/NativeComponents/Concerns/HoldsNewCommits.php b/app/NativeComponents/Concerns/HoldsNewCommits.php index 25e2ef68..3f211cbb 100644 --- a/app/NativeComponents/Concerns/HoldsNewCommits.php +++ b/app/NativeComponents/Concerns/HoldsNewCommits.php @@ -74,12 +74,24 @@ public function showNewCommits(): void */ public function newCommitsLabel(): string { - $count = max(count($this->newCommits), $this->newCommitsCount ?? 0); + $count = max(count($this->waitingCommits()), $this->newCommitsCount ?? 0); $more = $this->newCommitsCount === null && $this->newCommitsReplaceList && $this->newCommitsCursor !== null; return $count.($more ? '+' : '').' '.($count === 1 ? 'new commit' : 'new commits'); } + /** + * The new commits the pill counts. A screen that already shows one of + * them elsewhere, as a guild's board shows its pinned commit on top, + * leaves that one out (see Guild). + * + * @return list + */ + protected function waitingCommits(): array + { + return $this->newCommits; + } + /** * Lays a fresh first page over the list. Newer commits wait for the pill * unless $showNewer says you asked for them. diff --git a/app/NativeComponents/Concerns/OpensGuilds.php b/app/NativeComponents/Concerns/OpensGuilds.php new file mode 100644 index 00000000..553562c0 --- /dev/null +++ b/app/NativeComponents/Concerns/OpensGuilds.php @@ -0,0 +1,16 @@ +openInTab('/guilds/'.$handle); + } +} diff --git a/app/NativeComponents/Concerns/RefreshesInBackground.php b/app/NativeComponents/Concerns/RefreshesInBackground.php index df453463..3f4b4e80 100644 --- a/app/NativeComponents/Concerns/RefreshesInBackground.php +++ b/app/NativeComponents/Concerns/RefreshesInBackground.php @@ -200,9 +200,10 @@ protected function refreshSettings(): void /** * A screen that has its own way of saying devnull refused it, such as a * profile across a block, says so here and returns true. Anything else - * prints the error. + * prints the error. $path is what was asked for, as a screen may ask + * for more than its own page, such as an opened thread's replies. */ - protected function refused(ApiException $exception): bool + protected function refused(ApiException $exception, string $path): bool { return false; } @@ -269,7 +270,7 @@ private function settleRefresh(array $result, string $path, array $query, Closur if (in_array($status, [403, 404, 410], true)) { app(ResponseCache::class)->forget($path, $query); - if (! $this->refused($exception)) { + if (! $this->refused($exception, $path)) { $this->error = $exception->firstError(); } diff --git a/app/NativeComponents/Concerns/ShowsCommits.php b/app/NativeComponents/Concerns/ShowsCommits.php index cb2564e8..587bc8c7 100644 --- a/app/NativeComponents/Concerns/ShowsCommits.php +++ b/app/NativeComponents/Concerns/ShowsCommits.php @@ -43,6 +43,7 @@ trait ShowsCommits { use OpensCommitSheet; + use OpensGuilds; use OpensHashtags; use OpensStargazers; use VotesOnPolls; diff --git a/app/NativeComponents/Connections.php b/app/NativeComponents/Connections.php index 519b3384..73d39652 100644 --- a/app/NativeComponents/Connections.php +++ b/app/NativeComponents/Connections.php @@ -161,7 +161,7 @@ protected function showsContent(): bool /** * A list across a block says so as the profile does, whatever devnull's message says. */ - protected function refused(ApiException $exception): bool + protected function refused(ApiException $exception, string $path): bool { if (! $exception->is(ErrorCode::UserBlocked) && ! $exception->is(ErrorCode::UserUnavailable)) { return false; diff --git a/app/NativeComponents/Guild.php b/app/NativeComponents/Guild.php new file mode 100644 index 00000000..33b8d1d6 --- /dev/null +++ b/app/NativeComponents/Guild.php @@ -0,0 +1,323 @@ +fillInAfterFirstFrame('revalidate'); + } + + /** + * Back from a commit or a profile: take any change made there from the cache at once, then ask devnull. + */ + public function onResume(): void + { + $this->forgetRefreshes(); + $this->showKept(); + $this->revalidate(); + } + + public function navTitle(): string + { + return $this->guild->name ?? '#'.$this->handle(); + } + + public function navigationOptions(): ?NavBarOptions + { + return NavBarOptions::make()->action( + NavAction::make('share') + ->icon(ios: Lucide::Share->ios(), android: Lucide::Share2->android()) + ->a11yLabel('Share guild') + ->press('share'), + ); + } + + /** + * Pull to refresh. You're at the top, so new commits go straight in. + */ + public function load(): void + { + $this->refreshBoard(showNewer: true); + } + + /** + * The next page of the board, less the commits already showing. + */ + public function loadMore(): void + { + if ($this->nextCursor === null) { + return; + } + + $board = $this->attempt(fn (Client $devnull): ?GuildBoard => $devnull->guild($this->handle(), $this->nextCursor)); + + if ($board === null) { + return; + } + + $shown = array_flip(array_map(fn (Commit $commit): string => $commit->id, $this->commits)); + $this->commits = [...$this->commits, ...array_values(array_filter($board->commits->items, fn (Commit $commit): bool => ! isset($shown[$commit->id])))]; + $this->nextCursor = $board->commits->nextCursor; + } + + /** + * The bar's Share: the system share sheet, with the guild's page on the web. + */ + public function share(): void + { + Share::url('', '', $this->guild?->htmlUrl ?? rtrim((string) config('devnull.url'), '/').'/guilds/'.rawurlencode($this->handle())); + } + + public function render(): View + { + $this->rowCache ??= new RowCache; + $this->rowCache->startFrame(); + + $pinned = $this->pinnedCommit(); + $boardCommits = array_values(array_filter($this->commits, fn (Commit $commit): bool => $commit->id !== $this->pinnedId)); + + return view('native.guild', [ + 'handle' => $this->handle(), + 'myColour' => $this->myColour(), + 'newCommitsLabel' => $this->newCommitsLabel(), + 'hasNewCommits' => $this->waitingCommits() !== [], + 'viewer' => $this->me(), + 'stashed' => app(Stash::class)->names($this->me()?->id), + 'pasteis' => app(Account::class)->pasteis(), + 'rowCache' => $this->rowCache, + // The pinned commit has its label for a heading, so no day of its own. + 'pinnedRows' => $pinned === null ? [] : array_values(array_filter(Timeline::feed([$pinned]), fn (TimelineRow $row): bool => ! $row->isDayMarker())), + 'rows' => Timeline::feed($boardCommits), + 'isEmpty' => $pinned === null && $boardCommits === [], + // Everything on the board was posted in this guild, so none of it says so. + 'hidesGuildBadge' => true, + ]); + } + + protected function revalidate(): void + { + $this->refreshBoard(); + } + + /** + * The pinned commit already shows on top, so a new one that's pinned isn't new to you. + * + * @return list + */ + protected function waitingCommits(): array + { + return array_values(array_filter($this->newCommits, fn (Commit $commit): bool => $commit->id !== $this->pinnedId)); + } + + protected function showsContent(): bool + { + return $this->guild !== null; + } + + /** + * @return iterable + */ + protected function shownCommits(): iterable + { + return [...$this->commits, ...($this->pinned === null ? [] : [$this->pinned]), ...$this->threadCommits()]; + } + + protected function updateShownCommits(Closure $update): void + { + $this->commits = array_map($update, $this->commits); + $this->pinned = $this->pinned === null ? null : $update($this->pinned); + $this->threads = array_map(fn (array $replies): array => array_map($update, $replies), $this->threads); + } + + /** + * A 404 for the board is a guild devnull no longer has, unless it has no + * guilds for you at all. Only the directory can tell, so it's asked, and + * only its 404 says guilds are off. Until it answers, the page waits, and + * if it can't answer, the page says it couldn't load. + * + * An opened thread devnull refuses, such as one under a commit by someone + * you blocked, closes, and leaves the board alone. + */ + protected function refused(ApiException $exception, string $path): bool + { + if ($path === 'guilds' && $exception->status === 404) { + $this->unavailable = true; + app(Account::class)->rememberGuildsAvailable(false); + + return true; + } + + if ($path !== $this->boardPath()) { + if (preg_match('#^commits/(?[^/]+)/replies$#', $path, $matches) !== 1) { + return false; + } + + $this->closeThread($matches['id']); + + return true; + } + + if ($exception->status !== 404) { + return false; + } + + $this->guild = null; + $this->pinned = null; + $this->pinnedId = null; + $this->commits = []; + $this->threads = []; + $this->nextCursor = null; + $this->forgetNewCommits(); + + $this->refresh('guilds', [], function (): void { + $this->missing = true; + app(Account::class)->rememberGuildsAvailable(true); + }); + + return true; + } + + private function refreshBoard(bool $showNewer = false): void + { + $this->refresh($this->boardPath(), [], fn (array $json) => $this->takeBoard($json, $showNewer), again: $showNewer); + $this->refreshThreads(); + } + + private function showKept(): void + { + if (($json = $this->cached($this->boardPath())) !== null) { + $this->takeBoard($json); + } + } + + /** + * @param array $json + */ + private function takeBoard(array $json, bool $showNewer = false): void + { + $board = GuildBoard::fromArray($json); + + // An answer with no guild in it, like a maintenance page, leaves what's showing alone. + if ($board === null) { + return; + } + + $this->layFreshCommits($json, $showNewer || $this->guild === null); + $this->guild = $board->guild; + $this->pinned = $board->pinned; + $this->pinnedId = $board->pinned?->id; + $this->missing = false; + $this->unavailable = false; + } + + /** + * The pinned commit as the board last sent it, or as devnull sent it on its own when its page isn't loaded. + */ + private function pinnedCommit(): ?Commit + { + foreach ($this->commits as $commit) { + if ($commit->id === $this->pinnedId) { + return $commit; + } + } + + return $this->pinned; + } + + private function boardPath(): string + { + return 'guilds/'.rawurlencode($this->handle()); + } + + private function handle(): string + { + return (string) $this->param('handle'); + } +} diff --git a/app/NativeComponents/Guilds.php b/app/NativeComponents/Guilds.php index 6fcb04f3..0ef323c0 100644 --- a/app/NativeComponents/Guilds.php +++ b/app/NativeComponents/Guilds.php @@ -6,7 +6,7 @@ use App\Devnull\Data\Guild; use App\Devnull\Data\Page; use App\Devnull\Exceptions\ApiException; -use App\NativeComponents\Concerns\OpensHashtags; +use App\NativeComponents\Concerns\OpensGuilds; use App\NativeComponents\Concerns\OpensInTab; use App\NativeComponents\Concerns\RefreshesInBackground; use App\NativeComponents\Concerns\TalksToDevnull; @@ -20,13 +20,11 @@ * The web pages through them with Previous and Next; but in the native app * we instead are using infinite scrolling to load more guilds. * - * Due to pending APIs not being merged yet, we can't support a dedicated guild - * page yet. Instead, tapping a guild hashtag will open search for commits that - * contain that hashtag (see OpensHashtags). + * Tapping a guild opens its own screen, its board (see Guild and OpensGuilds). */ class Guilds extends NativeComponent { - use OpensHashtags; + use OpensGuilds; use OpensInTab; use RefreshesInBackground; use TalksToDevnull; @@ -102,11 +100,6 @@ public function browseAll(): void $this->ask(again: true); } - public function openGuild(string $handle): void - { - $this->openHashtag('#'.$handle); - } - public function loadMore(): void { if ($this->nextPage === null) { @@ -136,7 +129,7 @@ protected function showsContent(): bool * A 404 for the directory means guilds are switched off for the * current user (unlikely to happen now that it's available to public). */ - protected function refused(ApiException $exception): bool + protected function refused(ApiException $exception, string $path): bool { if ($exception->status !== 404) { return false; diff --git a/app/NativeComponents/Profile.php b/app/NativeComponents/Profile.php index d4c1e690..0a03a1c7 100644 --- a/app/NativeComponents/Profile.php +++ b/app/NativeComponents/Profile.php @@ -692,7 +692,7 @@ protected function showsContent(): bool * you blocked with it, for the page's name and avatar. A handle no user has may be an organization's, which shares * its link on the web, so until devnull has sent anything for it, the organization's screen takes this one's place. */ - protected function refused(ApiException $exception): bool + protected function refused(ApiException $exception, string $path): bool { if ($exception->status === 404 && ! $this->commitsLoaded && ($this->profile === null || $this->sketched)) { $this->replace($this->tabRoot().'/organizations/'.rawurlencode($this->username)); diff --git a/app/NativeComponents/Remotes.php b/app/NativeComponents/Remotes.php index 982d55c5..ae341683 100644 --- a/app/NativeComponents/Remotes.php +++ b/app/NativeComponents/Remotes.php @@ -240,7 +240,7 @@ protected function showsContent(): bool /** * devnull answers a 404 while you have Remotes off, as the web does. */ - protected function refused(ApiException $exception): bool + protected function refused(ApiException $exception, string $path): bool { if ($exception->status !== 404) { return false; diff --git a/resources/views/native/guild.blade.php b/resources/views/native/guild.blade.php new file mode 100644 index 00000000..5ec9ba99 --- /dev/null +++ b/resources/views/native/guild.blade.php @@ -0,0 +1,74 @@ +{{-- + A guild's page (see App\NativeComponents\Guild): its header, then its bulletin board, the pinned commit on top under + its label, then the rest newest first, more coming in as you scroll. One list, as the directory is, so the header + scrolls away with the board. +--}} + + @include('native.partials.error') + @include('native.partials.refresh-failed') + @include('native.partials.commit-sheet') + @include('native.partials.live-stream-sheet') + @include('native.partials.stargazers-sheet') + + {{-- + The new commits pill lies over the top of the board, as the pinned bar lies over a Remotes thread. The stack and + the pill's slot are always there, so the pill coming or going never adds a node beside the list. + --}} + + + @if ($unavailable) + @include('native.partials.empty', [ + 'command' => 'fatal: guilds are not available', + 'message' => "Guilds aren't open to you yet.", + ]) + @elseif ($missing) + @include('native.partials.empty', [ + 'command' => 'fatal: no such guild #'.$handle, + 'message' => 'This guild is no longer available.', + ]) + @elseif ($guild !== null) + @include('native.partials.guild-header') + + + Bulletin board · Latest commits + + + @if ($pinnedRows !== []) + + + Pinned to board + + @include('native.partials.feed', ['rows' => $pinnedRows, 'threads' => $threads, 'rowCache' => $rowCache]) + @endif + + @if ($isEmpty) + @include('native.partials.empty', [ + 'command' => '$ git log --grep=#'.$handle, + 'message' => 'No commits yet. Post to the board or include #'.$handle.' in a commit.', + ]) + @else + @include('native.partials.feed', ['rows' => $rows, 'threads' => $threads, 'rowCache' => $rowCache]) + + @if ($nextCursor !== null) + @include('native.partials.rail-loading') + @endif + @endif + @elseif ($error === null) + + + + @endif + + + + @include('native.partials.new-commits-pill', ['label' => $newCommitsLabel, 'press' => 'showNewCommits', 'shown' => $hasNewCommits]) + + + diff --git a/resources/views/native/partials/guild-badge.blade.php b/resources/views/native/partials/guild-badge.blade.php index c99b4651..83f32786 100644 --- a/resources/views/native/partials/guild-badge.blade.php +++ b/resources/views/native/partials/guild-badge.blade.php @@ -3,14 +3,13 @@ which looks like this: "posted in #guild · not shown in general logs". It says this because these posts stay out of profiles and feeds. - If the user taps on the pill for the guild's hashtag (see OpensHashtags), we open a - search for that hashtag. Once guild pages exist in the app, this can open the dedicated - guild page instead. + Tapping the pill opens the guild's own screen (see OpensGuilds). A guild's own board + leaves the badge off its commits, since they're all posted there (see Guild). --}} @php($guild = $commit->guild) posted in - + @include('native.partials.guild-mark', ['guild' => $guild, 'size' => 14, 'ref' => 'guild-pill-mark-'.$commit->id]) {{ $guild->name }} diff --git a/resources/views/native/partials/guild-header.blade.php b/resources/views/native/partials/guild-header.blade.php new file mode 100644 index 00000000..6ea637d7 --- /dev/null +++ b/resources/views/native/partials/guild-header.blade.php @@ -0,0 +1,31 @@ +{{-- + A guild's header, at the top of its board (see guild.blade.php), in the web's words: its icon or emoji (see + guild-mark), its name, "#handle · Public guild · N members", what it's about, then how to post there, or that it's + paused while it has no moderator. +--}} +@php($members = \App\Devnull\Display::count($guild->memberCount, 'member', 'members')) + + + + @include('native.partials.guild-mark', ['guild' => $guild, 'size' => 64, 'ref' => 'guild-header-mark']) + + + + {{ $guild->name }} + + {{ $guild->hashtag() }} + · + {{ $guild->isPaused ? 'Public guild · Paused' : 'Public guild' }} + · + {{ $members }} + + + + @if ($guild->description !== '') + {{ $guild->description }} + @endif + + {{ $guild->isPaused ? 'This guild is paused until it has a moderator. Its board and members are preserved.' : 'Include '.$guild->hashtag().' in any commit to post here.' }} + + + diff --git a/resources/views/native/partials/guild-row.blade.php b/resources/views/native/partials/guild-row.blade.php index 388b2f87..98f18ff9 100644 --- a/resources/views/native/partials/guild-row.blade.php +++ b/resources/views/native/partials/guild-row.blade.php @@ -1,8 +1,7 @@ {{-- A guild in the directory, as the web's card shows it: its uploaded icon, or its emoji (see guild-mark). - Tapped, it searches for the hashtag. Once we are able to add support for actual guild - pages, tapping it will instead open that guild page. + Tapped, it opens the guild's screen (see OpensGuilds). --}} @php($members = \App\Devnull\Display::count($guild->memberCount, 'member', 'members')) diff --git a/routes/mobile.php b/routes/mobile.php index 2c98e10b..a0c78122 100644 --- a/routes/mobile.php +++ b/routes/mobile.php @@ -8,6 +8,7 @@ use App\NativeComponents\CommitDetail; use App\NativeComponents\Connections; use App\NativeComponents\Conversation; +use App\NativeComponents\Guild; use App\NativeComponents\Guilds; use App\NativeComponents\Launch; use App\NativeComponents\Layouts\TabsLayout; @@ -55,9 +56,9 @@ Route::native('/profile/device', ThisDevice::class); Route::native('/profile/starred', Starred::class); - // Commits, profiles, their followers, the people you mute and block, and - // Remotes threads and your scheduled commits open beneath the tab they were - // tapped in, so that tab's own navigation stack pushes them (see + // Commits, profiles, their followers, the people you mute and block, + // Remotes threads, your scheduled commits and guilds open beneath the tab + // they were tapped in, so that tab's own navigation stack pushes them (see // Concerns\OpensInTab). foreach (TabsLayout::Tabs as $tab) { Route::native("{$tab}/commits/{id}", CommitDetail::class); @@ -72,5 +73,6 @@ Route::native("{$tab}/scheduled", ScheduledCommits::class); Route::native("{$tab}/search", Search::class); Route::native("{$tab}/guilds", Guilds::class); + Route::native("{$tab}/guilds/{handle}", Guild::class); } }); diff --git a/tests/Feature/Devnull/ClientCacheTest.php b/tests/Feature/Devnull/ClientCacheTest.php index dba1838d..35ec9801 100644 --- a/tests/Feature/Devnull/ClientCacheTest.php +++ b/tests/Feature/Devnull/ClientCacheTest.php @@ -425,3 +425,23 @@ ->and($request->body)->toContain('{"body":"","scheduled_at":"2026-10-20T08:00:00+00:00","image_descriptions":["A cabin."]}') ->and($request->body)->toContain('name="images[]"; filename="image-1.png"'); }); + +it('asks for a guild board with no page on the first, and keeps only that', function () { + serveApi(['GET /api/v1/guilds/rust' => [boardJson()]]); + + $this->devnull->guild('rust'); + $this->devnull->guild('rust', '2'); + + expect(array_map(fn (array $call): string => $call[0]->url(), Http::recorded()->all()))->toBe([ + 'http://devnull.test/api/v1/guilds/rust', + 'http://devnull.test/api/v1/guilds/rust?page=2', + ]) + ->and(kept('guilds/rust')['guild']['handle'])->toBe('rust') + ->and(kept('guilds/rust', ['page' => '2']))->toBeNull(); +}); + +it('is nothing for a guild devnull answers without', function () { + serveApi(['GET /api/v1/guilds/rust' => [['data' => []]]]); + + expect($this->devnull->guild('rust'))->toBeNull(); +}); diff --git a/tests/Feature/Devnull/ResponseCacheTest.php b/tests/Feature/Devnull/ResponseCacheTest.php index afd3fd86..a6b848f1 100644 --- a/tests/Feature/Devnull/ResponseCacheTest.php +++ b/tests/Feature/Devnull/ResponseCacheTest.php @@ -449,3 +449,8 @@ expect($this->cache->get('guilds', ['q' => 'rust']))->toBeNull(); }); + +it('keeps a guild board, first page only', function () { + expect(ResponseCache::caches('guilds/rust'))->toBeTrue() + ->and(ResponseCache::caches('guilds/rust', ['page' => '2']))->toBeFalse(); +}); diff --git a/tests/Feature/Devnull/SiteLinkTest.php b/tests/Feature/Devnull/SiteLinkTest.php index b50d528c..648a6f5c 100644 --- a/tests/Feature/Devnull/SiteLinkTest.php +++ b/tests/Feature/Devnull/SiteLinkTest.php @@ -23,6 +23,12 @@ 'a query and a fragment' => ['https://dev-null.sh/@ada/commits/01a14a9d-7971-73ea-8f35-135fe5149ca8/?ref=share#replies', '/commits/01a14a9d-7971-73ea-8f35-135fe5149ca8'], 'a Remotes conversation' => ['https://dev-null.sh/remotes/@ada', '/conversations/ada'], 'an org' => ['https://dev-null.sh/remotes/orgs/0199E5C4-0000-7000-8000-000000000002', '/orgs/0199e5c4-0000-7000-8000-000000000002'], + 'the guilds directory' => ['https://dev-null.sh/guilds', '/guilds'], + 'a guild' => ['https://dev-null.sh/guilds/rust', '/guilds/rust'], + 'a guild with an underscore' => ['https://dev-null.sh/guilds/rust_lang/', '/guilds/rust_lang'], + 'a guild with a letter beyond ASCII' => ['https://dev-null.sh/guilds/café', '/guilds/café'], + 'a guild as a browser sends it, percent-encoded' => ['https://dev-null.sh/guilds/caf%C3%A9', '/guilds/café'], + 'a guild with digits and an underscore' => ['https://dev-null.sh/guilds/rust_2024', '/guilds/rust_2024'], 'the host the app talks to' => ['http://devnull.test/@ada', '/users/ada'], ]); @@ -30,6 +36,13 @@ expect(SiteLink::screen($url))->toBeNull(); })->with([ 'nothing' => [null], + "a percent-encoded guild's icon" => ['https://dev-null.sh/guilds/caf%C3%A9/icon?v=1'], + 'a handle with a hyphen' => ['https://dev-null.sh/guilds/rust-lang'], + 'a handle that is not valid UTF-8' => ['https://dev-null.sh/guilds/caf%E9'], + 'a handle longer than the web allows' => ['https://dev-null.sh/guilds/'.str_repeat('a', 61)], + "a guild's icon" => ['https://dev-null.sh/guilds/rust/icon?v=1700000000000'], + 'a page beneath a guild' => ['https://dev-null.sh/guilds/rust/members/extra'], + 'a handle that starts with a digit' => ['https://dev-null.sh/guilds/1rust'], 'a host ending like dev/null' => ['https://dev-null.sh.evil.com/@ada'], 'a subdomain' => ['https://api.dev-null.sh/@ada'], 'another site' => ['https://evil.com/@ada'], diff --git a/tests/Feature/Screens/CommitCardTest.php b/tests/Feature/Screens/CommitCardTest.php index 5a01b14e..42201e5f 100644 --- a/tests/Feature/Screens/CommitCardTest.php +++ b/tests/Feature/Screens/CommitCardTest.php @@ -271,12 +271,10 @@ function logOf(array $commits): TestableComponent ->and(nodeByRef($screen, 'guild-pill-g1')['props']['a11y_label'])->toBe('Rust, #rust'); }); -it('searches for the guild hashtag from the guild a commit was posted in', function () { - $screen = logOf([['id' => 'g1', 'guild_handle' => 'rust', 'guild' => ['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀', 'icon_url' => null]]]); - - $screen->press("openHashtag('#rust')")->assertNavigatedTo('/log/search'); - - expect($screen->instance()->getNavigationIntent()->data)->toBe(['query' => '#rust']); +it('opens the guild a commit was posted in', function () { + logOf([['id' => 'g1', 'guild_handle' => 'rust', 'guild' => ['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀', 'icon_url' => null]]]) + ->tap('guild-pill-g1') + ->assertNavigatedTo('/log/guilds/rust'); }); it('says nothing about guilds on a commit that was not posted in one', function () { diff --git a/tests/Feature/Screens/GuildTest.php b/tests/Feature/Screens/GuildTest.php new file mode 100644 index 00000000..81ed7c15 --- /dev/null +++ b/tests/Feature/Screens/GuildTest.php @@ -0,0 +1,294 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * Answers #rust's board by page number: $pages maps '' (the first page, asked for with no number) and '2', '3'… to + * their answers. Anything else is a 404. + * + * @param array> $pages + */ +function serveBoard(array $pages): void +{ + serveApi(function (Request $request) use ($pages) { + parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query); + + if (parse_url($request->url(), PHP_URL_PATH) !== '/api/v1/guilds/rust' || ! isset($pages[$query['page'] ?? ''])) { + return Http::response(['message' => 'Not Found'], 404); + } + + return Http::response($pages[$query['page'] ?? '']); + }); +} + +/** + * A board page of commits by id, newest first, with no pin unless one is given. + * + * @param list $ids + * @param array $overrides + * @return array + */ +function boardOf(array $ids, ?int $nextPage = null, array $overrides = []): array +{ + return boardJson([ + 'data' => array_map(fn (string $id): array => commitJson(['id' => $id]), $ids), + 'pinned_commit' => null, + 'links' => ['next' => $nextPage === null ? null : 'http://devnull.test/api/v1/guilds/rust?page='.$nextPage], + ...$overrides, + ]); +} + +/** + * The commits the board shows, top to bottom, by id. + * + * @return list + */ +function boardShows(TestableComponent $screen): array +{ + $rows = findNodes($screen->tree(), fn (array $node): bool => preg_match('/^commit-c\d+$/', $node['ref'] ?? '') === 1); + + return array_map(fn (array $node): string => substr($node['ref'], strlen('commit-')), $rows); +} + +/** + * The words of the header's line under the name, as one line. + */ +function guildMeta(TestableComponent $screen): string +{ + $texts = findNodes(nodeByRef($screen, 'guild-meta'), fn (array $node): bool => ($node['type'] ?? null) === 'text'); + + return implode(' ', array_map(fn (array $node): string => (string) ($node['text'] ?? $node['props']['text'] ?? ''), $texts)); +} + +it('shows the guild\'s header as the web does', function () { + serveBoard(['' => boardOf(['c1'], overrides: ['guild' => guildJson(['name' => 'Rustaceans', 'member_count' => 2, 'description' => 'Crabs welcome.'])])]); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust')) + ->assertNavTitle('Rustaceans') + ->assertSee('Rustaceans') + ->assertSee('Crabs welcome.') + ->assertSee('Include #rust in any commit to post here.') + ->assertSee('Bulletin board · Latest commits') + ->assertDontSee('This guild is paused until it has a moderator. Its board and members are preserved.'); + + expect(guildMeta($screen))->toBe('#rust · Public guild · 2 members'); + + serveBoard(['' => boardOf(['c1'], overrides: ['guild' => guildJson(['member_count' => 1, 'is_paused' => true])])]); + + $paused = finishRefreshes(Native::visit('/log/guilds/rust')) + ->assertSee('This guild is paused until it has a moderator. Its board and members are preserved.') + ->assertDontSee('Include #rust in any commit to post here.'); + + expect(guildMeta($paused))->toBe('#rust · Public guild · Paused · 1 member'); +}); + +it('opens a guilds directory link on top of the board, with a way back', function () { + serveBoard(['' => boardOf(['c1'], overrides: ['data' => [commitJson(['id' => 'c1', 'body' => 'See https://dev-null.sh/guilds'])]])]); + + finishRefreshes(Native::visit('/guilds/guilds/rust')) + ->press("openLink('c1', 0)") + ->assertNavigatedTo('/guilds/guilds') + ->assertNativeNotCalled('Browser.OpenInApp'); +}); + +it('shares the guild\'s page on the web', function () { + serveBoard(['' => boardOf(['c1'])]); + + finishRefreshes(Native::visit('/log/guilds/rust')) + ->press('share') + ->assertNativeCalled('Share.Url', fn (array $params): bool => $params['url'] === 'http://devnull.test/guilds/rust'); +}); + +it('shows the pinned commit first, once', function () { + serveBoard(['' => boardOf(['c1', 'c2', 'c3'], overrides: ['pinned_commit' => commitJson(['id' => 'c2'])])]); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust')); + + expect(boardShows($screen))->toBe(['c2', 'c1', 'c3']) + ->and(treeShows(nodeByRef($screen, 'pinned-label'), 'Pinned to board'))->toBeTrue() + ->and($screen->get('pinnedId'))->toBe('c2'); +}); + +it('leaves the posted in badge off its own board', function () { + serveBoard(['' => boardOf([], overrides: ['data' => [commitJson(['id' => 'c1', 'guild_handle' => 'rust', 'guild' => ['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀', 'icon_url' => null]])]])]); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust')); + + expect(boardShows($screen))->toBe(['c1']) + ->and(rendersRef($screen, 'guild-badge-c1'))->toBeFalse(); +}); + +it('loads the next page without repeating a commit', function () { + serveBoard([ + '' => boardOf(['c5', 'c4', 'c3'], nextPage: 2), + '2' => boardOf(['c3', 'c2'], nextPage: 3), + '3' => boardOf(['c1']), + ]); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust'))->call('loadMore'); + + expect(boardShows($screen))->toBe(['c5', 'c4', 'c3', 'c2']); + + $screen->call('loadMore'); + + expect(boardShows($screen))->toBe(['c5', 'c4', 'c3', 'c2', 'c1']) + ->and($screen->get('nextCursor'))->toBeNull(); + Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/guilds/rust?page=2'); +}); + +it('shows the pinned commit once when a later page carries it too', function () { + serveBoard([ + '' => boardOf(['c5', 'c4'], nextPage: 2, overrides: ['pinned_commit' => commitJson(['id' => 'c2'])]), + '2' => boardOf(['c3', 'c2', 'c1'], overrides: ['pinned_commit' => commitJson(['id' => 'c2'])]), + ]); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust')); + + expect(boardShows($screen))->toBe(['c2', 'c5', 'c4']); + + $screen->call('loadMore'); + + expect(boardShows($screen))->toBe(['c2', 'c5', 'c4', 'c3', 'c1']); +}); + +it('says when the board is empty', function () { + serveBoard(['' => boardOf([])]); + + finishRefreshes(Native::visit('/log/guilds/rust')) + ->assertSee('Include #rust in any commit to post here.') + ->assertSee('No commits yet.') + ->assertSee('Post to the board or include #rust in a commit.'); +}); + +it('says when the guild is gone', function () { + serveApi(function (Request $request) { + return parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds' + ? Http::response(['data' => [guildJson(['handle' => 'go'])], 'links' => ['next' => null]]) + : Http::response(['message' => 'Not Found'], 404); + }); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust')) + ->assertSee('This guild is no longer available.') + ->assertDontSee('fatal: guilds are not available') + ->assertSet('missing', true) + ->assertSet('unavailable', false); + + expect($screen->get('error'))->toBeNull() + ->and(app(Account::class)->guildsAvailable())->toBeTrue(); +}); + +it('shows guilds switched off when guilds are gone too', function () { + serveApi(fn () => Http::response(['message' => 'Not Found'], 404)); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust')) + ->assertSee('fatal: guilds are not available') + ->assertSee("Guilds aren't open to you yet.") + ->assertDontSee('This guild is no longer available.') + ->assertSet('unavailable', true); + + expect($screen->get('error'))->toBeNull() + ->and(app(Account::class)->guildsAvailable())->toBeFalse(); +}); + +it('says it could not load, not that the guild is gone, when the directory check fails', function (int $status) { + serveApi(function (Request $request) use ($status) { + return parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds' + ? ($status === 0 ? throw new ConnectionException('cURL error 6') : Http::response(['message' => 'Server Error'], $status)) + : Http::response(['message' => 'Not Found'], 404); + }); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust')) + ->assertDontSee('This guild is no longer available.') + ->assertSet('missing', false) + ->assertSet('unavailable', false); + + expect($screen->get('error'))->not->toBeNull() + ->and(app(Account::class)->guildsAvailable())->toBeNull(); +})->with(['no connection' => 0, 'devnull failing' => 500]); + +it('signs out when the key stops working during the directory check', function () { + serveApi(function (Request $request) { + return parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds' + ? Http::response(['message' => 'This SSH key is not on the GitHub account of a devnull user.'], 401) + : Http::response(['message' => 'Not Found'], 404); + }); + + finishRefreshes(Native::visit('/log/guilds/rust'))->assertReplacedWith('/onboarding'); + + expect(app(Account::class)->user())->toBeNull(); +}); + +it('keeps the board when an opened thread is gone', function () { + $board = boardOf([], overrides: [ + 'guild' => guildJson(['name' => 'Rustaceans']), + 'data' => [commitJson(['id' => 'c1', 'replies_count' => 1]), commitJson(['id' => 'c2'])], + ]); + $repliesGone = false; + serveApi(function (Request $request) use ($board, &$repliesGone) { + return match (parse_url($request->url(), PHP_URL_PATH)) { + '/api/v1/guilds/rust' => Http::response($board), + '/api/v1/commits/c1/replies' => $repliesGone + ? Http::response(['message' => "This commit isn't available.", 'code' => 'commit_unavailable'], 404) + : Http::response(pageJson([commitJson(['id' => 'r1', 'parent_id' => 'c1'])])), + default => Http::response(['message' => 'Not Found'], 404), + }; + }); + $screen = finishRefreshes(Native::visit('/log/guilds/rust'))->call('toggleReplies', 'c1'); + $repliesGone = true; + + finishRefreshes($screen->call('load')); + + $screen->assertSee('Rustaceans') + ->assertSet('missing', false) + ->assertSet('unavailable', false); + expect(boardShows($screen))->toBe(['c1', 'c2']) + ->and($screen->get('error'))->toBeNull() + ->and(rendersRef($screen, 'thread-reply-r1'))->toBeFalse(); + Http::assertNotSent(fn (Request $request): bool => parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds'); +}); + +it('leaves the pinned commit out of the new commits pill', function () { + keep('guilds/rust', boardOf(['c1'])); + serveBoard(['' => boardOf(['c9', 'c8', 'c1'], overrides: ['pinned_commit' => commitJson(['id' => 'c9'])])]); + + $screen = finishRefreshes(Native::visit('/log/guilds/rust')) + ->assertSee('1 new commit') + ->assertDontSee('2 new commits'); + + expect(boardShows($screen))->toBe(['c9', 'c1']); + + $screen->tap('new-commits'); + + expect(boardShows($screen))->toBe(['c9', 'c8', 'c1']); + + keep('guilds/rust', boardOf(['c1'])); + serveBoard(['' => boardOf(['c9', 'c1'], overrides: ['pinned_commit' => commitJson(['id' => 'c9'])])]); + + $pinnedOnly = finishRefreshes(Native::visit('/log/guilds/rust')); + + expect(boardShows($pinnedOnly))->toBe(['c9', 'c1']) + ->and(rendersRef($pinnedOnly, 'new-commits'))->toBeFalse(); +}); + +it('opens a guild whose handle is a route word', function (string $handle) { + // The Guilds tab is /guilds, so its own /guilds/search, /guilds/safety… belong to other screens. + serveApi(fn (Request $request) => parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds/'.$handle + ? Http::response(boardOf(['c1'], overrides: ['guild' => guildJson(['handle' => $handle, 'name' => 'Not a screen'])])) + : Http::response(pageJson([]))); + + $guild = finishRefreshes(Native::visit('/guilds')->call('openGuild', $handle)->assertNavigatedTo("/guilds/guilds/{$handle}")->follow()); + + expect($guild->instance())->toBeInstanceOf(Guild::class); + $guild->assertNavTitle('Not a screen'); +})->with(['search', 'safety', 'scheduled', 'guilds']); diff --git a/tests/Feature/Screens/GuildsTest.php b/tests/Feature/Screens/GuildsTest.php index ea5df6d9..e7e18c2f 100644 --- a/tests/Feature/Screens/GuildsTest.php +++ b/tests/Feature/Screens/GuildsTest.php @@ -1,8 +1,8 @@ $overrides - * @return array - */ -function guildJson(array $overrides = []): array -{ - $handle = $overrides['handle'] ?? 'rust'; - - return [ - 'handle' => $handle, - 'name' => ucfirst($handle), - 'description' => "All about {$handle}.", - 'emoji' => '💻', - 'icon_url' => null, - 'member_count' => 3, - 'is_joined' => false, - 'is_muted' => false, - 'is_paused' => false, - 'html_url' => "http://devnull.test/guilds/{$handle}", - ...$overrides, - ]; -} - /** * A page of the directory, paged by number as the web pages it. * @@ -104,25 +79,24 @@ function serveGuilds(array $pages): void ->and(nodeByRef($screen, 'guild-search-field')['props']['placeholder'])->toBe('Search guilds'); })->with(['ios', 'android']); -it('opens the hashtag search for a tapped guild', function () { +it('opens a tapped guild in the tab it was tapped in', function () { serveGuilds(['' => guildsPage([guildJson(['handle' => 'rust'])])]); - $screen = finishRefreshes(Native::visit('/profile/guilds')); - $screen->press("openGuild('rust')")->assertNavigatedTo('/profile/search'); - - expect($screen->instance()->getNavigationIntent()->data)->toBe(['query' => '#rust']); + finishRefreshes(Native::visit('/log/guilds')) + ->tap('guild-rust') + ->assertNavigatedTo('/log/guilds/rust'); }); -it('opens the hashtag search on the Guilds tab\'s own stack from the tab', function () { +it('opens a guild on the Guilds tab\'s own stack from the tab', function () { serveGuilds(['' => guildsPage([guildJson(['handle' => 'rust'])])]); $screen = finishRefreshes(Native::visit('/guilds')); - $screen->press("openGuild('rust')")->assertNavigatedTo('/guilds/search'); + $screen->press("openGuild('rust')")->assertNavigatedTo('/guilds/guilds/rust'); - $search = $screen->follow(); + $guild = $screen->follow(); - expect($search->instance())->toBeInstanceOf(Search::class); - $search->assertTabActive('Guilds'); + expect($guild->instance())->toBeInstanceOf(Guild::class); + $guild->assertTabActive('Guilds'); }); it('searches with the term and keeps it when loading more', function () { diff --git a/tests/Feature/Screens/LogTest.php b/tests/Feature/Screens/LogTest.php index eef79241..e4019710 100644 --- a/tests/Feature/Screens/LogTest.php +++ b/tests/Feature/Screens/LogTest.php @@ -317,6 +317,15 @@ ->assertNativeNotCalled('Browser.OpenInApp'); }); +it('opens a guild directory linked in a commit on top of the tab it was tapped in', function () { + Http::fake(['devnull.test/*' => Http::response(pageJson([commitJson(['id' => 'c1', 'body' => 'All guilds: https://dev-null.sh/guilds'])]))]); + + Native::visit('/log') + ->press("openLink('c1', 0)") + ->assertNavigatedTo('/log/guilds') + ->assertNativeNotCalled('Browser.OpenInApp'); +}); + it('shows a link preview as a compact row and opens it in the browser', function () { Http::fake(['devnull.test/*' => Http::response(pageJson([commitJson([ 'id' => 'c1', diff --git a/tests/Pest.php b/tests/Pest.php index 684feac1..9e9e9aae 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -470,6 +470,48 @@ function currentUserTermsJson(bool $accepted, ?string $acceptedAt = '2026-10-05T return currentUserJson(['terms_version' => $version, 'terms_accepted_at' => $acceptedAt, 'terms_accepted' => $accepted]); } +/** + * A guild as devnull sends it: a row of the directory, or the `guild` of a board. + * + * @param array $overrides + * @return array + */ +function guildJson(array $overrides = []): array +{ + $handle = $overrides['handle'] ?? 'rust'; + + return [ + 'handle' => $handle, + 'name' => ucfirst($handle), + 'description' => "All about {$handle}.", + 'emoji' => '💻', + 'icon_url' => null, + 'member_count' => 3, + 'is_joined' => false, + 'is_muted' => false, + 'is_paused' => false, + 'html_url' => "http://devnull.test/guilds/{$handle}", + ...$overrides, + ]; +} + +/** + * A guild board answer, as `GET /guilds/{handle}` sends it. + * + * @param array $overrides + * @return array + */ +function boardJson(array $overrides = []): array +{ + return [ + 'guild' => guildJson(), + 'data' => [commitJson(['id' => 'c1']), commitJson(['id' => 'c2'])], + 'pinned_commit' => commitJson(['id' => 'c2']), + 'links' => ['next' => 'https://dev-null.sh/api/v1/guilds/rust?page=2'], + ...$overrides, + ]; +} + /** * A commit as the API sends it to a signed request. The short hash and the link * follow the id and the author, and the body's segments follow the body, unless diff --git a/tests/Unit/Devnull/GuildBoardTest.php b/tests/Unit/Devnull/GuildBoardTest.php new file mode 100644 index 00000000..2d1d2716 --- /dev/null +++ b/tests/Unit/Devnull/GuildBoardTest.php @@ -0,0 +1,23 @@ +guild->handle)->toBe('rust') + ->and($board->commits->items)->toHaveCount(2) + ->and($board->commits->nextCursor)->toBe('2') + ->and($board->pinned->id)->toBe('c2'); +}); + +it('has no pinned commit and no next page when the answer says so', function () { + $board = GuildBoard::fromArray(boardJson(['pinned_commit' => null, 'links' => []])); + + expect($board->pinned)->toBeNull() + ->and($board->commits->nextCursor)->toBeNull(); +}); + +it('is nothing when the guild is missing', function () { + expect(GuildBoard::fromArray(boardJson(['guild' => null])))->toBeNull(); +});