diff --git a/app/Devnull/Account.php b/app/Devnull/Account.php index 22917423..d7d7b1ee 100644 --- a/app/Devnull/Account.php +++ b/app/Devnull/Account.php @@ -36,6 +36,8 @@ final class Account private const string TermsKey = 'devnull.terms-to-accept'; + private const string GuildsKey = 'devnull.guilds-available'; + public function user(): ?User { $attributes = Cache::get(self::CacheKey); @@ -93,6 +95,24 @@ 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); + } + /** * 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. @@ -233,6 +253,7 @@ public function forget(): void Cache::forget(self::ProfileKey); Cache::forget(self::PinWarningKey); Cache::forget(self::TimezoneKey); + Cache::forget(self::GuildsKey); Cache::forget(self::TermsKey); } } 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..a1f594c3 --- /dev/null +++ b/app/Devnull/Data/Guild.php @@ -0,0 +1,94 @@ + $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 the emoji should + * show: 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/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/Log.php b/app/NativeComponents/Log.php index 050e79e2..448b9b8a 100644 --- a/app/NativeComponents/Log.php +++ b/app/NativeComponents/Log.php @@ -326,11 +326,23 @@ public function navTitle(): string } /** - * Search, as the web's phone header has it, then a new commit. + * The guilds, then search, then a new commit. + * If devnull reports guild feature as disabled, we hide it here. */ public function navigationOptions(): ?NavBarOptions { - return NavBarOptions::make() + $options = NavBarOptions::make(); + + if (app(Account::class)->guildsAvailable() !== false) { + $options->action( + NavAction::make('guilds') + ->icon(ios: Lucide::UsersRound->ios(), android: Lucide::UsersRound->android()) + ->a11yLabel('Guilds') + ->press('openGuilds'), + ); + } + + return $options ->action( NavAction::make('search') ->icon(ios: Lucide::Search->ios(), android: Lucide::Search->android()) @@ -345,6 +357,20 @@ public function navigationOptions(): ?NavBarOptions ); } + /** + * The guild directory opens on the Log's own stack, beside search. + * + * Once we can support dedicated guild pages in the mobile app, it may + * be worth promoting it to the bottom row as a fifth icon instead. + * + * At the moment it mostly acts as a restricted guild-only search, so + * this is the most logical place for it. + */ + public function openGuilds(): void + { + $this->openInTab('/guilds'); + } + /** * Search opens on the Log's own stack, so back comes here. */ @@ -509,6 +535,21 @@ protected function revalidate(): void : $this->takeFresh($log, $json)); $this->refreshThreads(); $this->refreshUnreadNotifications(); + $this->refreshGuildsAvailability(); + } + + /** + * If guilds are switched off at some point, we keep checking to make + * sure we notice when they get switched back on again. That ensures + * the Guilds button comes back. + */ + private function refreshGuildsAvailability(): void + { + if (app(Account::class)->guildsAvailable() !== false) { + return; + } + + $this->refresh('guilds', [], fn () => app(Account::class)->rememberGuildsAvailable(true), quiet: true); } /** 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..ee3b4d5a --- /dev/null +++ b/resources/views/native/partials/guild-mark.blade.php @@ -0,0 +1,11 @@ +{{-- + 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), otherwise its emoji, otherwise nothing. The icon sits beside the guild's name, so + it has no alt text of its own. +--}} +@php($iconSrc = $guild->iconSrc()) +@if ($iconSrc !== 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..ee8e0fe4 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; @@ -69,5 +70,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..66bdaafb --- /dev/null +++ b/tests/Feature/Screens/GuildsTest.php @@ -0,0 +1,287 @@ + '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('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('opens from the Log bar, before Search, on the Log stack', function (string $platform) { + serveApi(fn (Request $request) => Http::response(pageJson([]))); + + $screen = finishRefreshes(Native::visit('/log', platform: $platform)); + $guilds = findNode($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'top_bar_action' && ($node['props']['id'] ?? null) === 'guilds'); + + expect($guilds['props'] ?? null)->toMatchArray(['icon' => 'custom:users-round', 'a11y_label' => 'Guilds']); + + $screen->press('openGuilds')->assertNavigatedTo('/log/guilds'); +})->with(['ios', 'android']); + +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('hides the Log bar icon 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('/log/guilds'))->assertSet('unavailable', true); + + $log = finishRefreshes(Native::visit('/log')); + + expect(findNode($log->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'top_bar_action' && ($node['props']['id'] ?? null) === 'guilds'))->toBeNull(); +}); + +it('brings the Log bar icon back 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(findNode($log->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'top_bar_action' && ($node['props']['id'] ?? null) === 'guilds'))->not->toBeNull(); +}); + +it('asks nothing extra from the Log while guilds are not known to be off', function () { + 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'); +}); + +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(); +}); diff --git a/tests/Feature/Screens/SearchTest.php b/tests/Feature/Screens/SearchTest.php index c9ad12a8..acb9a31b 100644 --- a/tests/Feature/Screens/SearchTest.php +++ b/tests/Feature/Screens/SearchTest.php @@ -66,8 +66,8 @@ function searchedFor(string $kind): array $screen = finishRefreshes(Native::visit('/log', platform: $platform)); $actions = array_column(findNodes($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'top_bar_action'), 'props'); - expect(array_column($actions, 'id'))->toBe(['search', 'compose']) - ->and($actions[0])->toMatchArray(['icon' => 'custom:search', 'a11y_label' => 'Search']); + expect(array_column($actions, 'id'))->toBe(['guilds', 'search', 'compose']) + ->and($actions[1])->toMatchArray(['icon' => 'custom:search', 'a11y_label' => 'Search']); $screen->press('openSearch')->assertNavigatedTo('/log/search'); })->with(['ios', 'android']); @@ -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/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(); +});