diff --git a/app/Devnull/Account.php b/app/Devnull/Account.php index 22917423..d97f9944 100644 --- a/app/Devnull/Account.php +++ b/app/Devnull/Account.php @@ -36,6 +36,13 @@ final class Account private const string TermsKey = 'devnull.terms-to-accept'; + private const string GuildsKey = 'devnull.guilds-available'; + + /** + * Whether this launch shows the Guilds tab, once it's been asked (see guildsTabShown()). + */ + private static ?bool $guildsTabShown = null; + public function user(): ?User { $attributes = Cache::get(self::CacheKey); @@ -93,6 +100,43 @@ public function rememberUnreadNotifications(int $count): void Cache::forever(self::UnreadKey, max(0, $count)); } + /** + * Are guilds on for the current user? Guilds can be set to admin-only, + * which was used before public release. Handling the unlikely scenario + * where they get switched off again (at least temporarily) so we don't + * need an app update to handle it. They'll just be hidden in the app. + */ + public function guildsAvailable(): ?bool + { + $available = Cache::get(self::GuildsKey); + + return is_bool($available) ? $available : null; + } + + public function rememberGuildsAvailable(bool $available): void + { + Cache::forever(self::GuildsKey, $available); + } + + /** + * Whether this launch shows the Guilds tab: unless guilds were known to be + * off when it was first asked. iOS can't add or remove a tab mid-session, + * so guilds switching on or off shows from the next launch. + */ + public function guildsTabShown(): bool + { + return self::$guildsTabShown ??= $this->guildsAvailable() !== false; + } + + /** + * Forgets whether this launch shows the Guilds tab, so the next look + * decides it again, as a fresh launch would. + */ + public static function forgetGuildsTabShown(): void + { + self::$guildsTabShown = null; + } + /** * Your pastéis for today while pastéis mode is on, as devnull last said or * as this phone has counted them since, or null while the mode is off. @@ -215,8 +259,9 @@ public function rememberTermsToAccept(?string $version): void } /** - * Signs this phone out: who it was, the badges, its pastéis and Remotes, your timezone, the terms you owe, every - * answer, image and voice note kept for a quick start, and your unsent drafts and recordings. + * Signs this phone out: who it was, the badges, its pastéis and Remotes, whether it has guilds and shows their + * tab, your timezone, the terms you owe, every answer, image and voice note kept for a quick start, and your unsent + * drafts and recordings. Signing out leaves the tabs for onboarding, so the next account's tabs are decided afresh. */ public function forget(): void { @@ -233,6 +278,8 @@ public function forget(): void Cache::forget(self::ProfileKey); Cache::forget(self::PinWarningKey); Cache::forget(self::TimezoneKey); + Cache::forget(self::GuildsKey); Cache::forget(self::TermsKey); + self::forgetGuildsTabShown(); } } diff --git a/app/Devnull/Client.php b/app/Devnull/Client.php index b6538ae5..a289f69a 100644 --- a/app/Devnull/Client.php +++ b/app/Devnull/Client.php @@ -7,6 +7,7 @@ use App\Devnull\Data\Connection; use App\Devnull\Data\CurrentUser; use App\Devnull\Data\DraftImage; +use App\Devnull\Data\Guild; use App\Devnull\Data\IncomingCall; use App\Devnull\Data\MessageVoice; use App\Devnull\Data\Notification; @@ -454,6 +455,22 @@ public function starred(?string $cursor = null): Page return Page::fromArray($this->get('starred', ['cursor' => $cursor]), Commit::fromArray(...)); } + /** + * This is a list of Guilds from the web. It might be: + * - Biggest first, 24 per page. + * - Guilds matching $term in a name, #handle or description + * + * They're paged by number, which a Page carries as a cursor. + * + * @return Page + */ + public function guilds(string $term = '', ?string $page = null): Page + { + $guilds = Page::fromArray($this->get('guilds', ['q' => $term === '' ? null : $term, 'page' => $page]), Guild::fromArray(...)); + + return new Page(array_values(array_filter($guilds->items)), $guilds->nextCursor); + } + /** * 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/CommitMenu.php b/app/Devnull/CommitMenu.php index d566caf9..6fc7cacf 100644 --- a/app/Devnull/CommitMenu.php +++ b/app/Devnull/CommitMenu.php @@ -11,7 +11,8 @@ /** * What More holds, on the right of a commit's action row (see * partials/commit-actions): Share link on every commit; Pin to profile or - * Unpin from profile on your own published commit, not a reply; then, after a + * Unpin from profile on your own published commit, not a reply nor one posted + * in a guild, which devnull won't pin to a profile; then, after a * divider, Report commit on someone else's published commit, or Delete commit * on your own. Each item names the commit, so a tap never rebuilds anything * from an attribute (see ShowsCommits). @@ -28,7 +29,7 @@ public static function items(Commit $commit, ?User $viewer): array $items[] = self::item($commit, 'share', 'Share link', Lucide::Link, 'shareCommit'); - if ($isOwn && $commit->isApproved() && $commit->parentId === null) { + if ($isOwn && $commit->isApproved() && $commit->parentId === null && $commit->guild === null) { $items[] = self::item($commit, 'pin', $commit->isPinned ? 'Unpin from profile' : 'Pin to profile', Lucide::Pin, 'togglePin'); } diff --git a/app/Devnull/Data/Commit.php b/app/Devnull/Data/Commit.php index 6d19fdde..e7b87ada 100644 --- a/app/Devnull/Data/Commit.php +++ b/app/Devnull/Data/Commit.php @@ -20,6 +20,9 @@ * * A Nata Nu//ers high score carries its signed run in a fenced block, which * shows as a card ($scoreCard) instead of as code. + * + * A commit posted straight to a guild's board knows that guild ($guild), which + * keeps it out of general logs. */ final readonly class Commit { @@ -82,6 +85,7 @@ public function __construct( public ?ReplyPreview $replyPreview = null, public int $pasteisCount = 0, public ?ScoreCard $scoreCard = null, + public ?Guild $guild = null, ) {} /** @@ -149,6 +153,7 @@ public static function fromArray(array $data): self replyPreview: is_array($data['reply_preview'] ?? null) ? ReplyPreview::fromArray($data['reply_preview']) : null, pasteisCount: max(0, (int) ($data['pasteis_count'] ?? 0)), scoreCard: $scoreCard, + guild: self::guild($data), ); } @@ -382,6 +387,18 @@ public static function date(mixed $value): ?CarbonImmutable } } + /** + * The guild this commit was posted in. It might be known + * because devnull sent the guild with the commit, or it + * might be known only by its handle. + * + * @param array $data + */ + private static function guild(array $data): ?Guild + { + return Guild::fromArray(is_array($data['guild'] ?? null) ? $data['guild'] : ['handle' => $data['guild_handle'] ?? null]); + } + private static function positiveInt(mixed $value): ?int { return is_int($value) && $value > 0 ? $value : null; diff --git a/app/Devnull/Data/Guild.php b/app/Devnull/Data/Guild.php new file mode 100644 index 00000000..48afbad8 --- /dev/null +++ b/app/Devnull/Data/Guild.php @@ -0,0 +1,95 @@ + $data + */ + public static function fromArray(array $data): ?self + { + $handle = $data['handle'] ?? null; + + if (! is_string($handle) || $handle === '') { + return null; + } + + $name = $data['name'] ?? null; + + return new self( + handle: $handle, + name: is_string($name) && $name !== '' ? $name : '#'.$handle, + description: is_string($data['description'] ?? null) ? $data['description'] : '', + emoji: is_string($data['emoji'] ?? null) ? $data['emoji'] : '', + memberCount: max(0, (int) ($data['member_count'] ?? 0)), + isJoined: ($data['is_joined'] ?? false) === true, + isMuted: ($data['is_muted'] ?? false) === true, + isPaused: ($data['is_paused'] ?? false) === true, + htmlUrl: is_string($data['html_url'] ?? null) ? $data['html_url'] : null, + iconUrl: is_string($data['icon_url'] ?? null) && $data['icon_url'] !== '' ? $data['icon_url'] : null, + ); + } + + /** + * Its hashtag, as commits write it and search takes it. + */ + public function hashtag(): string + { + return '#'.$this->handle; + } + + /** + * What an image element gets for the icon, or null when it can't be drawn: + * there is no icon, or its signed link has expired and no copy was + * downloaded while it was good. A link with no expiry counts as good. + */ + public function iconSrc(): ?string + { + if ($this->iconUrl === null) { + return null; + } + + parse_str((string) parse_url($this->iconUrl, PHP_URL_QUERY), $query); + $expires = $query['expires'] ?? null; + + if (is_numeric($expires) && (int) $expires <= time() && ! ImageCache::has($this->iconUrl)) { + return null; + } + + return ImageCache::src($this->iconUrl); + } +} diff --git a/app/Devnull/ImageCache.php b/app/Devnull/ImageCache.php index cd41cd70..a6c16e77 100644 --- a/app/Devnull/ImageCache.php +++ b/app/Devnull/ImageCache.php @@ -6,8 +6,8 @@ use Illuminate\Support\Facades\File; /** - * Remote images kept on the device: avatars, commit images and link preview - * images. NativePHP's image element streams a remote URL every time it comes + * Remote images kept on the device: avatars, guild icons, commit images and link + * preview images. NativePHP's image element streams a remote URL every time it comes * into view, but draws a file on the device from memory, so an image is * downloaded once in the background (see DownloadImages) and drawn from its * file until it's older than config('devnull.image_cache_hours'). @@ -63,6 +63,14 @@ public static function src(?string $url): ?string return app(self::class)->sources[$url] ??= self::freshPath($url) ?? $url; } + /** + * Whether a fresh downloaded copy of this URL's image is on the device. + */ + public static function has(string $url): bool + { + return self::isRemote($url) && self::freshPath($url) !== null; + } + /** * Downloads, in the background, the images in an answer from devnull that * aren't on the device yet. @@ -132,7 +140,7 @@ public static function clear(): void /** * Every image URL in an answer, wherever it's nested: people's avatars, - * commits' images and link previews' images. + * guilds' icons, commits' images and link previews' images. * * @param array $json * @return list @@ -142,7 +150,7 @@ public static function urlsIn(array $json): array $urls = []; foreach ($json as $key => $value) { - if (in_array($key, ['avatar_url', 'image_url'], true) && self::isRemote($value)) { + if (in_array($key, ['avatar_url', 'image_url', 'icon_url'], true) && self::isRemote($value)) { $urls[] = $value; } elseif ($key === 'images' && is_array($value)) { foreach ($value as $image) { diff --git a/app/Devnull/ResponseCache.php b/app/Devnull/ResponseCache.php index fadaa8a0..dc8af583 100644 --- a/app/Devnull/ResponseCache.php +++ b/app/Devnull/ResponseCache.php @@ -52,6 +52,7 @@ final class ResponseCache '#^remotes/@[^/]+/messages$#', '#^remotes/orgs/[^/]+/messages$#', '#^scheduled-commits$#', + '#^guilds$#', ]; /** @@ -113,7 +114,8 @@ final class ResponseCache public static function caches(string $path, array $query = []): bool { // A cursor's page, a numbered page, and a Remotes thread's messages before or after one, aren't the first page. - if (array_intersect_key(self::normalise($query), array_flip(['cursor', 'page', 'before', 'after'])) !== []) { + // A search (q) isn't kept either: each term would push a kept page out, and screens open on the unsearched list. + if (array_intersect_key(self::normalise($query), array_flip(['cursor', 'page', 'before', 'after', 'q'])) !== []) { return false; } diff --git a/app/NativeComponents/Concerns/RefreshesInBackground.php b/app/NativeComponents/Concerns/RefreshesInBackground.php index 600f5c37..df453463 100644 --- a/app/NativeComponents/Concerns/RefreshesInBackground.php +++ b/app/NativeComponents/Concerns/RefreshesInBackground.php @@ -83,13 +83,15 @@ protected function cached(string $path, array $query = []): ?array * Asks devnull for a GET in the background and hands $apply the JSON when it * lands. A refresh of the same thing already on its way isn't sent twice, * unless $again says it must be. A $quiet one never says it failed on the - * screen. It only tells $failed, for a caller that has something else to - * do then. One $withImages brings the answer's images down before it - * lands, rather than after in a task of their own (see FetchInBackground). + * screen. It only tells $failed, with devnull's status (0 when devnull didn't + * answer), for a caller that has something else to do then, such as + * telling a 404 from a dropped connection. One $withImages brings the + * answer's images down before it lands, rather than after in a task of + * their own (see FetchInBackground). * * @param array $query * @param Closure(array): void $apply - * @param (Closure(): void)|null $failed + * @param (Closure(int): void)|null $failed */ protected function refresh(string $path, array $query, Closure $apply, bool $again = false, bool $quiet = false, ?Closure $failed = null, bool $withImages = false, bool $retried = false): void { @@ -103,7 +105,7 @@ protected function refresh(string $path, array $query, Closure $apply, bool $aga $request = app(Client::class)->signedGet($path, $query); } catch (KeychainUnavailable $exception) { if ($quiet) { - $failed?->__invoke(); + $failed?->__invoke(0); } else { $this->couldNotRefresh($exception->getMessage()); } @@ -132,7 +134,7 @@ protected function refresh(string $path, array $query, Closure $apply, bool $aga unset($this->refreshing[$key]); if ($quiet) { - $failed?->__invoke(); + $failed?->__invoke(0); } else { $this->couldNotRefresh('fatal: '.$exception->getMessage()); } @@ -218,7 +220,7 @@ protected function forgetRefreshes(): void * @param array{status?: int, json?: mixed, retry_after?: string, from_devnull?: bool} $result * @param array $query * @param Closure(array): void $apply - * @param (Closure(): void)|null $failed + * @param (Closure(int): void)|null $failed */ private function settleRefresh(array $result, string $path, array $query, Closure $apply, bool $quiet, ?Closure $failed = null, bool $withImages = false): void { @@ -246,7 +248,7 @@ private function settleRefresh(array $result, string $path, array $query, Closur } if ($quiet) { - $failed?->__invoke(); + $failed?->__invoke(($result['from_devnull'] ?? false) === true ? $status : 0); return; } diff --git a/app/NativeComponents/Concerns/ShowsCommits.php b/app/NativeComponents/Concerns/ShowsCommits.php index 05407927..cb2564e8 100644 --- a/app/NativeComponents/Concerns/ShowsCommits.php +++ b/app/NativeComponents/Concerns/ShowsCommits.php @@ -538,7 +538,7 @@ private function canReactTo(Commit $commit): bool private function canPin(Commit $commit): bool { - return ! $commit->isDeleted() && $commit->isApproved() && $commit->parentId === null && $commit->author->id === $this->me()?->id; + return ! $commit->isDeleted() && $commit->isApproved() && $commit->parentId === null && $commit->guild === null && $commit->author->id === $this->me()?->id; } private function canDelete(Commit $commit): bool diff --git a/app/NativeComponents/Guilds.php b/app/NativeComponents/Guilds.php new file mode 100644 index 00000000..6fcb04f3 --- /dev/null +++ b/app/NativeComponents/Guilds.php @@ -0,0 +1,203 @@ + */ + public array $guilds = []; + + /** + * The number of the next page + */ + public ?string $nextPage = null; + + /** + * Whether the list has had guilds to show. Until then it shows skeleton rows. + */ + public bool $loaded = false; + + /** + * Guilds are switched off for you: devnull answered the directory with a 404. + */ + public bool $unavailable = false; + + public function mount(): void + { + $this->showKept(); + $this->revalidate(); + } + + public function onResume(): void + { + $this->forgetRefreshes(); + $this->revalidate(); + } + + public function navTitle(): string + { + return 'Guilds'; + } + + /** + * Pull to refresh. + */ + public function load(): void + { + $this->ask(again: true); + } + + /** + * The field's term changed. + */ + public function updatedTerm(): void + { + $this->ask(); + } + + /** + * The keyboard's search key, with the field's text, which a debounced binding may not have caught up with yet. + */ + public function search(?string $submitted = null): void + { + $this->term = $submitted ?? $this->term; + $this->ask(again: true); + } + + /** + * Browse all guilds: the whole directory, from the top. + */ + public function browseAll(): void + { + $this->term = ''; + $this->ask(again: true); + } + + public function openGuild(string $handle): void + { + $this->openHashtag('#'.$handle); + } + + public function loadMore(): void + { + if ($this->nextPage === null) { + return; + } + + $page = $this->attempt(fn ($devnull) => $devnull->guilds($this->searchTerm(), $this->nextPage)); + + if ($page !== null) { + $shown = array_flip(array_map(fn (Guild $guild): string => $guild->handle, $this->guilds)); + $this->guilds = [...$this->guilds, ...array_values(array_filter($page->items, fn (Guild $guild): bool => ! isset($shown[$guild->handle])))]; + $this->nextPage = $page->nextCursor; + } + } + + protected function revalidate(): void + { + $this->ask(); + } + + protected function showsContent(): bool + { + return $this->loaded; + } + + /** + * 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 + { + if ($exception->status !== 404) { + return false; + } + + $this->unavailable = true; + $this->loaded = true; + app(Account::class)->rememberGuildsAvailable(false); + $this->guilds = []; + $this->nextPage = null; + + return true; + } + + /** + * Asks devnull for the first page of guilds for the term in the field. + */ + private function ask(bool $again = false): void + { + $term = $this->searchTerm(); + + $this->refresh('guilds', ['q' => $term === '' ? null : $term], function (array $json) use ($term): void { + if ($this->searchTerm() !== $term) { + return; + } + + $this->take($json); + }, again: $again); + } + + private function showKept(): void + { + if (($json = $this->cached('guilds')) !== null) { + $this->take($json); + } + } + + /** + * @param array $json + */ + private function take(array $json): void + { + $page = Page::fromArray($json, Guild::fromArray(...)); + + $this->guilds = array_values(array_filter($page->items)); + $this->nextPage = $page->nextCursor; + $this->loaded = true; + $this->unavailable = false; + app(Account::class)->rememberGuildsAvailable(true); + } + + /** + * We trim the search term, just like it's trimmed on the web app. + */ + private function searchTerm(): string + { + return trim($this->term); + } + + public function render(): View + { + return view('native.guilds'); + } +} diff --git a/app/NativeComponents/Layouts/TabsLayout.php b/app/NativeComponents/Layouts/TabsLayout.php index 4b7ce13d..61608cdd 100644 --- a/app/NativeComponents/Layouts/TabsLayout.php +++ b/app/NativeComponents/Layouts/TabsLayout.php @@ -15,17 +15,20 @@ use Native\Mobile\Edge\NativeComponent; /** - * The top-level sections: Log, Notifications, Remotes and your Profile, with - * the icons of the web's nav, picked out in the colour you chose for your lane. - * Notifications and Remotes wear a badge with the unread count devnull last - * gave. Starred opens from your own profile. + * The top-level sections: Log, Notifications, Guilds, Remotes and your + * Profile, with the icons of the web's nav, picked out in the colour you chose + * for your lane. Notifications and Remotes wear a badge with the unread count + * devnull last gave. Starred opens from your own profile. Guilds is left out + * for a launch that began with devnull having said they're off for you (see + * Account::guildsTabShown()). */ class TabsLayout extends NativeLayout { /** - * Each tab's URI. Commits and profiles open beneath the one they were tapped in. + * Each tab's URI, Guilds among them even in a launch that leaves its tab + * out. Commits and profiles open beneath the one they were tapped in. */ - public const array Tabs = ['/log', '/notifications', '/remotes', '/profile']; + public const array Tabs = ['/log', '/notifications', '/guilds', '/remotes', '/profile']; /** * The icon and "/dev/null" wordmark as the web's MobileHeader draws them, 105 x 28pt. @@ -80,11 +83,17 @@ public function tabBar(NativeComponent $screen): ?TabBar self::badge($notifications, app(Account::class)->unreadNotifications()); self::badge($remotes, app(Account::class)->unreadRemotes()); - return TabBar::make() + $tabBar = TabBar::make() ->activeColor(self::accent()) ->labelVisibility('labeled') ->add(Tab::link('Log', '/log', ios: Lucide::GitCommitVertical->ios(), android: Lucide::GitCommitVertical->android())) - ->add($notifications) + ->add($notifications); + + if (app(Account::class)->guildsTabShown()) { + $tabBar->add(Tab::link('Guilds', '/guilds', ios: Lucide::UsersRound->ios(), android: Lucide::UsersRound->android())); + } + + return $tabBar ->add($remotes) ->add(Tab::link('Profile', '/profile', ios: Lucide::UserRound->ios(), android: Lucide::UserRound->android())); } diff --git a/app/NativeComponents/Log.php b/app/NativeComponents/Log.php index 050e79e2..3fbafc26 100644 --- a/app/NativeComponents/Log.php +++ b/app/NativeComponents/Log.php @@ -326,7 +326,7 @@ public function navTitle(): string } /** - * Search, as the web's phone header has it, then a new commit. + * Search, as the web's phone header has it, then a new commit. Guilds have their own tab. */ public function navigationOptions(): ?NavBarOptions { @@ -509,6 +509,30 @@ protected function revalidate(): void : $this->takeFresh($log, $json)); $this->refreshThreads(); $this->refreshUnreadNotifications(); + $this->refreshGuildsAvailability(); + } + + /** + * Asks devnull whether guilds are on for you until it has said they are, + * for the tabs of the next launch (see Account::guildsTabShown()). This + * launch's tabs are settled before asking, so the answer can't move them. + * Only a 404 says guilds are off: no connection, or devnull failing, + * leaves what was known, so a phone offline at launch still shows the tab. + */ + private function refreshGuildsAvailability(): void + { + $account = app(Account::class); + $account->guildsTabShown(); + + if ($account->guildsAvailable() === true) { + return; + } + + $this->refresh('guilds', [], fn () => $account->rememberGuildsAvailable(true), quiet: true, failed: function (int $status) use ($account): void { + if ($status === 404) { + $account->rememberGuildsAvailable(false); + } + }); } /** diff --git a/app/NativeComponents/Search.php b/app/NativeComponents/Search.php index c82ff53d..86b9e3f1 100644 --- a/app/NativeComponents/Search.php +++ b/app/NativeComponents/Search.php @@ -292,6 +292,7 @@ public function render(): View 'stashed' => app(Stash::class)->names($viewer?->id), 'myColour' => $this->myColour(), 'rows' => Timeline::ranked([], $this->commits), + 'hidesGuildBadge' => true, ]); } } diff --git a/resources/views/native/guilds.blade.php b/resources/views/native/guilds.blade.php new file mode 100644 index 00000000..05f5b848 --- /dev/null +++ b/resources/views/native/guilds.blade.php @@ -0,0 +1,73 @@ + + @include('native.partials.error') + @include('native.partials.refresh-failed') + + + @if ($unavailable) + @include('native.partials.empty', [ + 'command' => 'fatal: guilds are not available', + 'message' => "Guilds aren't open to you yet.", + ]) + @else + {{-- + What the web's Guilds page says above the list, then its search. + The hairline is in the same row, as on Starred. + + The web also says "Join to see their commits in Following.", but we'll hold + off on adding that in the app until users of the app are able to join a guild. + We can't add guild joining until the upstream APIs are merged and available. + --}} + + + Public groups, biggest first. + + + + + + + Search names, #handles, and descriptions. + + + + + @if (! $loaded && $error === null) + @foreach (range(1, 3) as $skeleton) + @include('native.partials.rail-loading', ['ref' => 'loading-'.$skeleton, 'label' => 'Loading guilds']) + @endforeach + @endif + + @if ($loaded && $guilds === [] && $error === null) + @if (trim($term) === '') + @include('native.partials.empty', [ + 'command' => 'fatal: no guilds yet', + 'message' => 'No guilds yet.', + ]) + @else + @include('native.partials.empty', [ + 'command' => 'fatal: no guilds match', + 'message' => 'No guilds found. Try another keyword.', + 'link' => 'Browse all guilds', + 'press' => 'browseAll', + ]) + @endif + @endif + + @foreach ($guilds as $guild) + @include('native.partials.guild-row') + @endforeach + + @if ($nextPage !== null) + @include('native.partials.rail-loading', ['ref' => 'loading-more', 'label' => 'Loading more guilds']) + @endif + @endif + + diff --git a/resources/views/native/partials/commit-row-content.blade.php b/resources/views/native/partials/commit-row-content.blade.php index 553ac21e..80528b31 100644 --- a/resources/views/native/partials/commit-row-content.blade.php +++ b/resources/views/native/partials/commit-row-content.blade.php @@ -11,6 +11,8 @@ which tapped says when in your timezone, its hash, and its replies behind a toggle in its action row. The commits around it ($muted) step back: smaller and in muted ink, with a smaller avatar and action row. They still open their own pages. + A commit posted straight to a guild's board says so under its header (see guild-badge), except in search. + A commit you just made that devnull doesn't have yet is staged: dimmed, with the staged chip and no actions, until the real one takes its place (see SyncsOutbox). @@ -53,6 +55,10 @@ @endunless + @if ($commit->guild !== null && ! ($hidesGuildBadge ?? false)) + @include('native.partials.guild-badge') + @endif + @if ($commit->parent?->isDeleted()) diff --git a/resources/views/native/partials/guild-badge.blade.php b/resources/views/native/partials/guild-badge.blade.php new file mode 100644 index 00000000..c99b4651 --- /dev/null +++ b/resources/views/native/partials/guild-badge.blade.php @@ -0,0 +1,18 @@ +{{-- + The web shows a message under commits that are posted straight to a guild's board, + 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. +--}} +@php($guild = $commit->guild) + + posted in + + @include('native.partials.guild-mark', ['guild' => $guild, 'size' => 14, 'ref' => 'guild-pill-mark-'.$commit->id]) + {{ $guild->name }} + + · not shown in general logs + diff --git a/resources/views/native/partials/guild-mark.blade.php b/resources/views/native/partials/guild-mark.blade.php new file mode 100644 index 00000000..82651ed0 --- /dev/null +++ b/resources/views/native/partials/guild-mark.blade.php @@ -0,0 +1,14 @@ +{{-- + A guild's mark: its uploaded icon while devnull's signed link to it is good, or a copy is on the device + (see Guild::iconSrc). A guild with an uploaded icon the app can't load shows a plain people glyph, never + the emoji it stores underneath, which its moderator didn't choose and the web doesn't show. Otherwise its + emoji, otherwise nothing. The mark sits beside the guild's name, so it has no alt text of its own. +--}} +@php($iconSrc = $guild->iconSrc()) +@if ($iconSrc !== null) + +@elseif ($guild->iconUrl !== null) + +@elseif ($guild->emoji !== '') + {{ $guild->emoji }} +@endif diff --git a/resources/views/native/partials/guild-row.blade.php b/resources/views/native/partials/guild-row.blade.php new file mode 100644 index 00000000..388b2f87 --- /dev/null +++ b/resources/views/native/partials/guild-row.blade.php @@ -0,0 +1,20 @@ +{{-- + 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. +--}} +@php($members = \App\Devnull\Display::count($guild->memberCount, 'member', 'members')) + + + @include('native.partials.guild-mark', ['guild' => $guild, 'size' => 40, 'ref' => 'guild-mark-'.$guild->handle]) + + + {{ $guild->name }} + {{ $guild->hashtag() }} + @if ($guild->description !== '') + {{ $guild->description }} + @endif + {{ $members }} + + diff --git a/routes/mobile.php b/routes/mobile.php index 764b9a27..2c98e10b 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\Guilds; use App\NativeComponents\Launch; use App\NativeComponents\Layouts\TabsLayout; use App\NativeComponents\Log; @@ -49,6 +50,7 @@ Route::native('/remotes', Remotes::class); Route::native('/remotes/new', NewRemote::class); Route::native('/remotes/new-org', NewOrg::class); + Route::native('/guilds', Guilds::class); Route::native('/profile', Profile::class); Route::native('/profile/device', ThisDevice::class); Route::native('/profile/starred', Starred::class); @@ -69,5 +71,6 @@ Route::native("{$tab}/orgs/{org}/members/add", AddOrgMembers::class); Route::native("{$tab}/scheduled", ScheduledCommits::class); Route::native("{$tab}/search", Search::class); + Route::native("{$tab}/guilds", Guilds::class); } }); diff --git a/tests/Feature/Devnull/ResponseCacheTest.php b/tests/Feature/Devnull/ResponseCacheTest.php index 7ba55066..afd3fd86 100644 --- a/tests/Feature/Devnull/ResponseCacheTest.php +++ b/tests/Feature/Devnull/ResponseCacheTest.php @@ -439,3 +439,13 @@ ->and(ResponseCache::caches('remotes', ['before' => 'conv-1']))->toBeFalse() ->and(ResponseCache::caches('remotes/reactions'))->toBeFalse(); }); + +it('keeps the guild directory, but not a search of it, so typing a search never pushes kept pages out', function () { + expect(ResponseCache::caches('guilds'))->toBeTrue() + ->and(ResponseCache::caches('guilds', ['q' => 'rust']))->toBeFalse() + ->and(ResponseCache::caches('guilds', ['page' => '2']))->toBeFalse(); + + $this->cache->put('guilds', ['q' => 'rust'], ['data' => []]); + + expect($this->cache->get('guilds', ['q' => 'rust']))->toBeNull(); +}); diff --git a/tests/Feature/ImageCacheTest.php b/tests/Feature/ImageCacheTest.php index 2d41b058..d5004889 100644 --- a/tests/Feature/ImageCacheTest.php +++ b/tests/Feature/ImageCacheTest.php @@ -2,6 +2,7 @@ use App\Devnull\Account; use App\Devnull\Client; +use App\Devnull\Data\Guild; use App\Devnull\DownloadImages; use App\Devnull\FetchInBackground; use App\Devnull\ImageCache; @@ -76,6 +77,38 @@ function imagesQueued(): array )->not->toContain('https://example.com'); }); +it('collects guild icons to download', function () { + $url = 'https://x/icon?expires=1'; + + expect(ImageCache::urlsIn(['data' => [['guild' => ['icon_url' => $url]]]]))->toContain($url); +}); + +it('knows whether a fresh downloaded copy exists', function () { + $url = 'https://x/icon?expires=1'; + + expect(ImageCache::has($url))->toBeFalse() + ->and(ImageCache::has('/on/the/device.png'))->toBeFalse(); + + cachedImage($url, hoursAgo: 1); + + expect(ImageCache::has($url))->toBeTrue(); +}); + +it('shows a guild\'s icon until its link expires, then its emoji', function () { + $icon = fn (string $query): Guild => Guild::fromArray(['handle' => 'rust', 'icon_url' => 'https://devnull.test/api/v1/guilds/rust/icon'.$query]); + $live = '?expires='.(time() + 3600).'&signature=x'; + $expired = '?expires='.(time() - 60).'&signature=x'; + + expect($icon($live)->iconSrc())->toBe($icon($live)->iconUrl) + ->and($icon('?v=1')->iconSrc())->toBe($icon('?v=1')->iconUrl) + ->and(Guild::fromArray(['handle' => 'go'])->iconSrc())->toBeNull() + ->and($icon($expired)->iconSrc())->toBeNull(); + + $path = cachedImage($icon($expired)->iconUrl, hoursAgo: 1); + + expect($icon($expired)->iconSrc())->toBe($path); +}); + it('draws an image from the device while it is younger than a day, and from its URL otherwise', function () { $url = 'https://avatars.githubusercontent.com/u/2?v=4'; diff --git a/tests/Feature/Screens/CommitCardTest.php b/tests/Feature/Screens/CommitCardTest.php index 067cf306..8c249773 100644 --- a/tests/Feature/Screens/CommitCardTest.php +++ b/tests/Feature/Screens/CommitCardTest.php @@ -231,3 +231,43 @@ function logOf(array $commits): TestableComponent Native::visit('/log/commits/c1')->assertSee('The very end.')->assertDontSee('Show more'); }); + +it('says which guild a commit was posted in, as the web does', function () { + $screen = logOf([['id' => 'g1', 'guild_handle' => 'rust', 'guild' => ['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀', 'icon_url' => null]]]) + ->assertSee('posted in') + ->assertSee('Rust') + ->assertSee('· not shown in general logs'); + + expect(rendersRef($screen, 'guild-badge-g1'))->toBeTrue() + ->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('says nothing about guilds on a commit that was not posted in one', function () { + $screen = logOf([['id' => 'c1']]); + + expect(rendersRef($screen, 'guild-badge-c1'))->toBeFalse(); + $screen->assertDontSee('posted in'); +}); + +it('shows the uploaded icon of the guild a commit was posted in', function () { + $url = 'https://dev-null.sh/api/v1/guilds/php/icon?expires='.(time() + 3600).'&signature=x'; + $screen = logOf([['id' => 'g1', 'guild_handle' => 'php', 'guild' => ['handle' => 'php', 'name' => 'PHP', 'emoji' => '💻', 'icon_url' => $url]]]); + + expect(nodeByRef($screen, 'guild-pill-mark-g1')['type'])->toBe('image') + ->and(nodeByRef($screen, 'guild-pill-mark-g1')['props']['src'])->toBe($url); + $screen->assertDontSee('💻'); +}); + +it('shows the emoji of the guild a commit was posted in when it has no uploaded icon', function () { + $screen = logOf([['id' => 'g1', 'guild_handle' => 'rust', 'guild' => ['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀', 'icon_url' => null]]]); + + expect(nodeByRef($screen, 'guild-pill-mark-g1')['props']['text'] ?? null)->toBe('🦀'); +}); diff --git a/tests/Feature/Screens/CommitMenuTest.php b/tests/Feature/Screens/CommitMenuTest.php index c07a7170..aedf1ae3 100644 --- a/tests/Feature/Screens/CommitMenuTest.php +++ b/tests/Feature/Screens/CommitMenuTest.php @@ -229,3 +229,21 @@ Http::assertNotSent(fn (Request $request): bool => str_ends_with($request->url(), '/pin')); }); + +it('leaves Pin to profile off your own commit posted in a guild, which devnull refuses to pin', function () { + serveApi(fn () => Http::response(pageJson([ + commitJson(['id' => 'g1', 'guild_handle' => 'rust', 'guild' => ['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀', 'icon_url' => null]]), + ]))); + + $screen = Native::visit('/log', platform: 'ios'); + + expect(menuItems($screen, 'more-g1'))->toBe([ + ['share-g1', 'Share link', 'custom:link'], + 'divider', + ['delete-g1', 'Delete commit', 'custom:trash-2'], + ]); + + $screen->call('togglePin', 'g1'); + + Http::assertNotSent(fn (Request $request): bool => str_ends_with($request->url(), '/pin')); +}); diff --git a/tests/Feature/Screens/GuildsTest.php b/tests/Feature/Screens/GuildsTest.php new file mode 100644 index 00000000..ea5df6d9 --- /dev/null +++ b/tests/Feature/Screens/GuildsTest.php @@ -0,0 +1,307 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * A guild as the directory lists it. + * + * @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 page of the directory, paged by number as the web pages it. + * + * @param list> $guilds + * @return array + */ +function guildsPage(array $guilds, ?int $nextPage = null, string $term = ''): array +{ + $path = 'http://devnull.test/api/v1/guilds'; + $query = $term === '' ? '' : 'q='.rawurlencode($term).'&'; + + return [ + 'data' => $guilds, + 'links' => ['first' => $path.'?'.$query.'page=1', 'last' => null, 'prev' => null, 'next' => $nextPage === null ? null : $path.'?'.$query.'page='.$nextPage], + 'meta' => ['current_page' => $nextPage === null ? 1 : $nextPage - 1, 'path' => $path, 'per_page' => 24], + ]; +} + +/** @return list */ +function shownGuilds(TestableComponent $screen): array +{ + return array_map(fn ($guild): string => $guild->handle, $screen->instance()->guilds); +} + +/** + * Answers the directory by search term: $pages maps a term ('' for none) to its answer. + * + * @param array> $pages + */ +function serveGuilds(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') { + return Http::response(['message' => 'No fake.'], 404); + } + + $key = ($query['q'] ?? '').(isset($query['page']) ? '#'.$query['page'] : ''); + + return Http::response($pages[$key] ?? guildsPage([])); + }); +} + +it('lists guilds biggest first with the web wording', function (string $platform) { + serveGuilds(['' => guildsPage([ + guildJson(['handle' => 'rust', 'name' => 'Rust', 'member_count' => 12]), + guildJson(['handle' => 'go', 'name' => 'Go', 'member_count' => 1, 'description' => 'Gophers.']), + ])]); + + $screen = finishRefreshes(Native::visit('/profile/guilds', platform: $platform)) + ->assertNavTitle('Guilds') + ->assertTabActive('Profile') + ->assertSee('Public groups, biggest first.') + ->assertSee('Search names, #handles, and descriptions.') + ->assertSee('Rust') + ->assertSee('#rust') + ->assertSee('12 members') + ->assertSee('Gophers.') + ->assertSee('1 member'); + + expect(shownGuilds($screen))->toBe(['rust', 'go']) + ->and(nodeByRef($screen, 'guild-rust')['props']['a11y_label'])->toBe('Rust, #rust, 12 members') + ->and(nodeByRef($screen, 'guild-search-field')['props']['placeholder'])->toBe('Search guilds'); +})->with(['ios', 'android']); + +it('opens the hashtag search for a tapped guild', 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']); +}); + +it('opens the hashtag search 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'); + + $search = $screen->follow(); + + expect($search->instance())->toBeInstanceOf(Search::class); + $search->assertTabActive('Guilds'); +}); + +it('searches with the term and keeps it when loading more', function () { + serveGuilds([ + '' => guildsPage([guildJson(['handle' => 'go'])]), + 'rust' => guildsPage([guildJson(['handle' => 'rust'])], nextPage: 2, term: 'rust'), + 'rust#2' => guildsPage([guildJson(['handle' => 'rustaceans'])], term: 'rust'), + ]); + + $screen = finishRefreshes(Native::visit('/profile/guilds')); + $screen->input('term', 'rust'); + finishRefreshes($screen); + + expect(shownGuilds($screen))->toBe(['rust']); + + $screen->call('loadMore'); + + expect(shownGuilds($screen))->toBe(['rust', 'rustaceans']); + Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/api/v1/guilds?q=rust&page=2')); +}); + +it('ignores an answer for a term the field has moved on from', function () { + holdRefreshes(); + serveGuilds([ + '' => guildsPage([guildJson(['handle' => 'go'])]), + 'ru' => guildsPage([guildJson(['handle' => 'ruby'])], term: 'ru'), + 'rust' => guildsPage([guildJson(['handle' => 'rust'])], term: 'rust'), + ]); + + $screen = finishRefreshes(Native::visit('/profile/guilds')); + $screen->input('term', 'ru'); + $screen->input('term', 'rust'); + + // The answer for "ru" lands last. + finishRefreshes($screen, newestFirst: true); + + expect(shownGuilds($screen))->toBe(['rust']); +}); + +it('drops guilds already shown when the next page repeats one', function () { + serveGuilds([ + '' => guildsPage([guildJson(['handle' => 'rust']), guildJson(['handle' => 'go'])], nextPage: 2), + '#2' => guildsPage([guildJson(['handle' => 'go']), guildJson(['handle' => 'zig'])]), + ]); + + $screen = finishRefreshes(Native::visit('/profile/guilds')); + $screen->call('loadMore'); + + expect(shownGuilds($screen))->toBe(['rust', 'go', 'zig']); +}); + +it('says when no guild matches, with a way back to all of them', function () { + serveGuilds([ + '' => guildsPage([guildJson(['handle' => 'rust'])]), + 'cobol' => guildsPage([], term: 'cobol'), + ]); + + $screen = finishRefreshes(Native::visit('/profile/guilds')); + $screen->input('term', 'cobol'); + finishRefreshes($screen) + ->assertSee('No guilds found. Try another keyword.') + ->assertSee('Browse all guilds'); + + $screen->press('browseAll'); + finishRefreshes($screen)->assertSet('term', ''); + + expect(shownGuilds($screen))->toBe(['rust']); +}); + +it('says there are no guilds yet on an empty directory', function () { + serveGuilds(['' => guildsPage([])]); + + finishRefreshes(Native::visit('/profile/guilds')) + ->assertSee('No guilds yet.') + ->assertDontSee('Browse all guilds'); +}); + +it('says guilds are not available when devnull answers 404, without an error', function () { + serveApi(['GET /api/v1/guilds' => [['message' => 'Not Found'], 404]]); + + $screen = finishRefreshes(Native::visit('/profile/guilds')) + ->assertSee('fatal: guilds are not available') + ->assertSee("Guilds aren't open to you yet.") + ->assertSet('unavailable', true) + ->assertSet('error', null); + + expect(rendersRef($screen, 'guild-search-field'))->toBeFalse(); +}); + +it('opens on the guilds kept last time and refreshes behind them', function () { + holdRefreshes(); + keep('guilds', guildsPage([guildJson(['handle' => 'rust'])])); + serveGuilds(['' => guildsPage([guildJson(['handle' => 'go']), guildJson(['handle' => 'rust'])])]); + + $screen = Native::visit('/profile/guilds'); + + expect(shownGuilds($screen))->toBe(['rust']); + + finishRefreshes($screen); + + expect(shownGuilds($screen))->toBe(['go', 'rust']); +}); + +it('is the Guilds screen', function () { + expect(Native::visit('/log/guilds')->instance())->toBeInstanceOf(Guilds::class); +}); + +it('shows a guild\'s uploaded icon in the directory', function () { + $url = 'https://dev-null.sh/api/v1/guilds/php/icon?expires='.(time() + 3600).'&signature=x'; + serveGuilds(['' => guildsPage([ + guildJson(['handle' => 'php', 'name' => 'PHP', 'emoji' => '💻', 'icon_url' => $url]), + guildJson(['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀']), + ])]); + + $screen = finishRefreshes(Native::visit('/profile/guilds')); + + expect(nodeByRef($screen, 'guild-mark-php')['type'])->toBe('image') + ->and(nodeByRef($screen, 'guild-mark-php')['props']['src'])->toBe($url) + ->and(nodeByRef($screen, 'guild-mark-rust')['props']['text'] ?? null)->toBe('🦀'); + $screen->assertDontSee('💻'); +}); + +it('shows the people glyph, never the stored emoji, for an uploaded icon it cannot load', function () { + config(['devnull.image_cache_hours' => 24]); + $expired = 'https://dev-null.sh/api/v1/guilds/php/icon?expires='.(time() - 60).'&signature=x'; + serveGuilds(['' => guildsPage([ + guildJson(['handle' => 'php', 'name' => 'PHP', 'emoji' => '💻', 'icon_url' => $expired]), + ])]); + + $screen = finishRefreshes(Native::visit('/profile/guilds')); + + expect(nodeByRef($screen, 'guild-mark-php')['type'])->toBe('icon'); + $screen->assertDontSee('💻'); +}); + +it('hides the Guilds tab from the next launch once devnull says guilds are off for you', function () { + serveApi(function (Request $request) { + return parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds' + ? Http::response(['message' => 'Not Found'], 404) + : Http::response(pageJson([])); + }); + + finishRefreshes(Native::visit('/guilds'))->assertSet('unavailable', true); + + Account::forgetGuildsTabShown(); + + expect(tabsShown(finishRefreshes(Native::visit('/log'))))->not->toHaveKey('Guilds'); +}); + +it('brings the Guilds tab back at the next launch once guilds are on for you again', function () { + app(Account::class)->rememberGuildsAvailable(false); + serveApi(function (Request $request) { + return parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds' + ? Http::response(guildsPage([guildJson()])) + : Http::response(pageJson([])); + }); + + $log = finishRefreshes(Native::visit('/log')); + + expect(app(Account::class)->guildsAvailable())->toBeTrue() + ->and(tabsShown($log))->not->toHaveKey('Guilds'); + + Account::forgetGuildsTabShown(); + + expect(tabsShown(finishRefreshes(Native::visit('/log'))))->toHaveKey('Guilds'); +}); + +it('forgets whether guilds were off when you sign out', function () { + app(Account::class)->rememberGuildsAvailable(false); + app(Account::class)->forget(); + + expect(app(Account::class)->guildsAvailable())->toBeNull(); +}); + +it('decides the Guilds tab afresh for whoever signs in next', function () { + expect(app(Account::class)->guildsTabShown())->toBeTrue(); + + app(Account::class)->forget(); + app(Account::class)->rememberGuildsAvailable(false); + + expect(app(Account::class)->guildsTabShown())->toBeFalse(); +}); diff --git a/tests/Feature/Screens/LogCacheTest.php b/tests/Feature/Screens/LogCacheTest.php index 1839334b..1d405ee5 100644 --- a/tests/Feature/Screens/LogCacheTest.php +++ b/tests/Feature/Screens/LogCacheTest.php @@ -120,8 +120,8 @@ function shownCommitIds(TestableComponent $screen): array expect(shownCommitIds($screen))->toBe(['c3', 'c2', 'c1']) ->and(count(Http::recorded()))->toBe($requests) - // The log, you for the unread badge, who to follow, and your settings for your timezone. - ->and(refreshesSent($screen))->toBe(4) + // The log, you for the unread badge, whether guilds are on, who to follow, and your settings for your timezone. + ->and(refreshesSent($screen))->toBe(5) // A new list key is how the log gets back to the top. ->and($screen->get('listKey'))->toBe($listKey + 1); }); diff --git a/tests/Feature/Screens/LogTest.php b/tests/Feature/Screens/LogTest.php index c0222442..eef79241 100644 --- a/tests/Feature/Screens/LogTest.php +++ b/tests/Feature/Screens/LogTest.php @@ -792,3 +792,45 @@ // Other screens keep their text titles. expect($titleView(Native::visit('/notifications')->assertNavTitle('Notifications')))->toBeNull(); }); + +/** + * Answers GET guilds with what $guilds gives, and the Log's own requests with an empty page. + */ +function serveGuildsProbe(Closure $guilds): void +{ + serveApi(fn (Request $request) => parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds' ? $guilds() : Http::response(pageJson([]))); +} + +it('leaves guilds to their tab, with Search and New commit in its bar', function () { + serveApi(fn (Request $request) => Http::response(pageJson([]))); + + $screen = finishRefreshes(Native::visit('/log')); + + expect(hasTopBarAction($screen, 'guilds'))->toBeFalse() + ->and(hasTopBarAction($screen, 'search'))->toBeTrue() + ->and(hasTopBarAction($screen, 'compose'))->toBeTrue(); +}); + +it('asks devnull whether guilds are on until it knows, for the next launch\'s tabs', function (Closure $serve, ?bool $remembered) { + $serve(); + + finishRefreshes(Native::visit('/log')); + + expect(app(Account::class)->guildsAvailable())->toBe($remembered); +})->with([ + 'on' => [fn () => serveGuildsProbe(fn () => Http::response(pageJson([]))), true], + 'off' => [fn () => serveGuildsProbe(fn () => Http::response(['message' => 'Not Found'], 404)), false], + 'a 404 devnull did not send' => [fn () => serveGuildsProbe(fn () => Http::response('Example: Hotel Wi-Fi sign-in', 404)), null], + 'devnull failing' => [fn () => serveGuildsProbe(fn () => Http::response(['message' => 'Server Error'], 500)), null], + // No connection at launch must not hide the tab next time. + 'no connection' => [fn () => fakeOffline(), null], +]); + +it('stops asking whether guilds are on once it knows they are', function () { + app(Account::class)->rememberGuildsAvailable(true); + serveApi(fn (Request $request) => Http::response(pageJson([]))); + + finishRefreshes(Native::visit('/log')); + + Http::assertNotSent(fn (Request $request): bool => parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds'); +}); diff --git a/tests/Feature/Screens/SearchTest.php b/tests/Feature/Screens/SearchTest.php index c9ad12a8..a1921e9a 100644 --- a/tests/Feature/Screens/SearchTest.php +++ b/tests/Feature/Screens/SearchTest.php @@ -208,3 +208,12 @@ function searchedFor(string $kind): array expect(treeShows(nodeByRef($screen, 'person-grace'), 'Following'))->toBeFalse(); }); + +it('leaves out the guild a result was posted in, as the web does', function () { + serveSearch(commits: [commitJson(['id' => 'g1', 'body' => 'Board post about #rust', 'guild_handle' => 'rust', 'guild' => ['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀', 'icon_url' => null]])]); + + $screen = Native::visit('/log/search', ['query' => '#rust'])->assertSee('Board post about'); + + expect(rendersRef($screen, 'guild-badge-g1'))->toBeFalse(); + $screen->assertDontSee('not shown in general logs'); +}); diff --git a/tests/Feature/Screens/TabsTest.php b/tests/Feature/Screens/TabsTest.php index 98b46526..37bb370e 100644 --- a/tests/Feature/Screens/TabsTest.php +++ b/tests/Feature/Screens/TabsTest.php @@ -1,5 +1,8 @@ all(); } -it('has Log, Notifications, Remotes and Profile tabs with the Lucide icons of the web nav', function (string $platform) { +it('has Log, Notifications, Guilds, Remotes and Profile tabs with the Lucide icons of the web nav', function (string $platform) { Http::fake(['devnull.test/*' => Http::response(pageJson([]))]); // The same drawings on both platforms. A custom icon has no Material font variant. expect(tabIcons(Native::visit('/log', platform: $platform)))->toBe([ 'Log' => ['custom:git-commit-vertical', null], 'Notifications' => ['custom:bell', null], + 'Guilds' => ['custom:users-round', null], 'Remotes' => ['custom:messages-square', null], 'Profile' => ['custom:user-round', null], ]); })->with(['ios', 'android']); +it('shows the Guilds tab unless devnull said guilds were off before launch', function (?bool $available, array $tabs) { + if ($available !== null) { + app(Account::class)->rememberGuildsAvailable($available); + } + Http::fake(['devnull.test/*' => Http::response(pageJson([]))]); + + expect(tabsShown(Native::visit('/log')))->toBe($tabs); +})->with([ + 'not known yet' => [null, ['Log' => '/log', 'Notifications' => '/notifications', 'Guilds' => '/guilds', 'Remotes' => '/remotes', 'Profile' => '/profile']], + 'on' => [true, ['Log' => '/log', 'Notifications' => '/notifications', 'Guilds' => '/guilds', 'Remotes' => '/remotes', 'Profile' => '/profile']], + 'off' => [false, ['Log' => '/log', 'Notifications' => '/notifications', 'Remotes' => '/remotes', 'Profile' => '/profile']], +]); + +it('keeps the tabs it launched with', function () { + app(Account::class)->rememberGuildsAvailable(true); + serveApi(fn (Request $request) => parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds' + ? Http::response(['message' => 'Not Found'], 404) + : Http::response(pageJson([]))); + + expect(tabsShown(Native::visit('/log')))->toHaveKey('Guilds'); + + finishRefreshes(Native::visit('/guilds'))->assertSet('unavailable', true); + + expect(app(Account::class)->guildsAvailable())->toBeFalse() + ->and(tabsShown(finishRefreshes(Native::visit('/log'))))->toHaveKey('Guilds'); +}); + +it('keeps the Guilds tab for the launch in which devnull first says guilds are off', function () { + serveApi(fn (Request $request) => parse_url($request->url(), PHP_URL_PATH) === '/api/v1/guilds' + ? Http::response(['message' => 'Not Found'], 404) + : Http::response(pageJson([]))); + + $log = finishRefreshes(Native::visit('/log')); + + expect(app(Account::class)->guildsAvailable())->toBeFalse() + ->and(tabsShown($log))->toHaveKey('Guilds'); +}); + +it('opens the guild directory as the Guilds tab', function () { + Http::fake(['devnull.test/*' => Http::response(pageJson([]))]); + + $screen = Native::visit('/guilds')->assertTabActive('Guilds'); + + expect($screen->instance())->toBeInstanceOf(Guilds::class); +}); + it('picks out the tab you are on in the colour you chose for your lane', function (int $lane) { signIn(['lane' => $lane]); Http::fake(['devnull.test/*' => Http::response(pageJson([]))]); diff --git a/tests/Pest.php b/tests/Pest.php index 41e32e2e..684feac1 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -701,6 +701,26 @@ function findNode(array $node, callable $matches): ?array return null; } +/** + * The tabs along the bottom, in order, as label => URL. + * + * @return array + */ +function tabsShown(TestableComponent $screen): array +{ + return collect(findNodes($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'bottom_nav_item')) + ->mapWithKeys(fn (array $tab): array => [$tab['props']['label'] => $tab['props']['url']]) + ->all(); +} + +/** + * Whether the screen's top bar has the action with this id. + */ +function hasTopBarAction(TestableComponent $screen, string $id): bool +{ + return findNode($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'top_bar_action' && ($node['props']['id'] ?? null) === $id) !== null; +} + /** * Whether anything with this ref was rendered. */ diff --git a/tests/TestCase.php b/tests/TestCase.php index 80975918..70ff97f6 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,6 +2,7 @@ namespace Tests; +use App\Devnull\Account; use App\Devnull\Timezone; use Illuminate\Foundation\Testing\LazilyRefreshDatabase; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; @@ -22,6 +23,8 @@ abstract class TestCase extends BaseTestCase * first frame. A test that wants to see the frame before it calls * holdRefreshes() (see Pest.php). * + * Each test is a fresh launch, so the Guilds tab is decided afresh. + * * The phone's timezone is unknown, so times show in UTC whatever this * machine's is, until a test puts the phone somewhere (see phoneIn()). */ @@ -29,6 +32,7 @@ protected function setUp(): void { parent::setUp(); + Account::forgetGuildsTabShown(); AsyncTask::fake(); $this->app->instance(Timezone::class, new Timezone(localtime: '/nonexistent')); } diff --git a/tests/Unit/Devnull/CommitCardDataTest.php b/tests/Unit/Devnull/CommitCardDataTest.php index 2addc22c..3a213756 100644 --- a/tests/Unit/Devnull/CommitCardDataTest.php +++ b/tests/Unit/Devnull/CommitCardDataTest.php @@ -180,3 +180,17 @@ function pollJson(array $overrides = []): array ->and(Achievements::fromArray(null))->toBeNull() ->and(Achievements::fromArray(['level' => 9, 'rank' => 'root', 'xp' => 9000, 'next_level_xp' => null, 'ranks' => []])->nextRankLabel())->toBe('Maximum rank (UID 0)'); }); + +it('knows the guild a commit was posted in', function () { + $commit = Commit::fromArray(cardJson(['guild_handle' => 'rust', 'guild' => ['handle' => 'rust', 'name' => 'Rust', 'emoji' => '🦀', 'icon_url' => null]])); + + expect($commit->guild?->name)->toBe('Rust') + ->and($commit->guild?->emoji)->toBe('🦀') + ->and($commit->withStar(true)->guild?->handle)->toBe('rust'); +}); + +it('names the guild by its hashtag when only the handle came', function () { + expect(Commit::fromArray(cardJson(['guild_handle' => 'rust', 'guild' => null]))->guild?->name)->toBe('#rust') + ->and(Commit::fromArray(cardJson())->guild)->toBeNull() + ->and(Commit::fromArray(cardJson(['guild_handle' => '', 'guild' => ['name' => 'Rust']]))->guild)->toBeNull(); +}); diff --git a/tests/Unit/Devnull/GuildTest.php b/tests/Unit/Devnull/GuildTest.php new file mode 100644 index 00000000..b3331cd7 --- /dev/null +++ b/tests/Unit/Devnull/GuildTest.php @@ -0,0 +1,44 @@ + 'rust', + 'name' => 'Rust', + 'description' => 'Crabs.', + 'emoji' => '🦀', + 'icon_url' => 'https://dev-null.sh/guilds/rust/icon?v=1', + 'member_count' => 12, + 'is_joined' => true, + 'is_muted' => false, + 'is_paused' => false, + 'html_url' => 'https://dev-null.sh/guilds/rust', + ]); + + expect($guild->handle)->toBe('rust') + ->and($guild->name)->toBe('Rust') + ->and($guild->description)->toBe('Crabs.') + ->and($guild->emoji)->toBe('🦀') + ->and($guild->memberCount)->toBe(12) + ->and($guild->isJoined)->toBeTrue() + ->and($guild->isPaused)->toBeFalse() + ->and($guild->htmlUrl)->toBe('https://dev-null.sh/guilds/rust') + ->and($guild->hashtag())->toBe('#rust'); +}); + +it('names a guild by its hashtag when the name is missing, and rejects one without a handle', function () { + expect(Guild::fromArray(['handle' => 'rust'])->name)->toBe('#rust') + ->and(Guild::fromArray(['handle' => 'rust', 'name' => ''])->name)->toBe('#rust') + ->and(Guild::fromArray(['name' => 'Rust']))->toBeNull() + ->and(Guild::fromArray(['handle' => '', 'name' => 'Rust']))->toBeNull() + ->and(Guild::fromArray(['handle' => 'rust', 'member_count' => -3])->memberCount)->toBe(0); +}); + +it('keeps the icon url devnull sent', function () { + $url = 'https://devnull.test/api/v1/guilds/rust/icon?expires='.(time() + 3600).'&signature=x'; + + expect(Guild::fromArray(['handle' => 'rust', 'icon_url' => $url])->iconUrl)->toBe($url) + ->and(Guild::fromArray(['handle' => 'go', 'icon_url' => ''])->iconUrl)->toBeNull() + ->and(Guild::fromArray(['handle' => 'php'])->iconUrl)->toBeNull(); +});