diff --git a/app/Devnull/Account.php b/app/Devnull/Account.php index 22917423..07f3b10a 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 OrganizationsKey = 'devnull.organizations'; + public function user(): ?User { $attributes = Cache::get(self::CacheKey); @@ -215,7 +217,39 @@ 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 + * The GitHub organizations you can post as, as devnull last said, oldest membership first. None until it has. + * + * @return list + */ + public function organizations(): array + { + $kept = Cache::get(self::OrganizationsKey); + + return is_array($kept) ? array_values(array_map(User::fromArray(...), array_filter($kept, is_array(...)))) : []; + } + + /** + * Which commits are yours: your own and your organizations' (see Ownership). + */ + public function ownership(): Ownership + { + return Ownership::of($this->user(), $this->organizations()); + } + + /** + * Remembers the organizations you can post as. With null, from a devnull too old to say, it keeps what it had. + * + * @param list|null $organizations + */ + public function rememberOrganizations(?array $organizations): void + { + if ($organizations !== null) { + Cache::forever(self::OrganizationsKey, array_map(fn (User $organization): array => $organization->toArray(), $organizations)); + } + } + + /** + * Signs this phone out: who it was, the badges, its pastéis and Remotes, your organizations, your timezone, the terms you owe, every * answer, image and voice note kept for a quick start, and your unsent drafts and recordings. */ public function forget(): void @@ -234,5 +268,6 @@ public function forget(): void Cache::forget(self::PinWarningKey); Cache::forget(self::TimezoneKey); Cache::forget(self::TermsKey); + Cache::forget(self::OrganizationsKey); } } diff --git a/app/Devnull/Client.php b/app/Devnull/Client.php index b6538ae5..4753ee35 100644 --- a/app/Devnull/Client.php +++ b/app/Devnull/Client.php @@ -110,10 +110,10 @@ public const string IssuesPath = 'issues'; /** - * How many replies the app asks for at a time. devnull sends 50 a page - * unless it's asked for fewer, and the app never asks for more than this. + * How many replies the app asks for at a time, in a feed's thread and on + * a commit's page. devnull sends 50 a page unless it's asked for fewer. */ - public const int RepliesPerPage = 5; + public const int RepliesPerPage = 10; /** * Where the signed-in account's timezone is saved, or unset, with whether their profile shows their local time. @@ -301,13 +301,15 @@ public function replies(string $id, ?string $cursor = null): Page /** * Commits, as a reply to $parentId or quoting $quotedCommitId, as the web's * composer, reply box and Quote do. devnull takes one or the other, not both. - * A new commit or a quote may start a poll (see PollDraft::payload()). + * A new commit or a quote may start a poll (see PollDraft::payload()). With + * $author, the handle of an organization you're a member of, it goes out as + * that organization, as the web's Post as picks (see PostAs). * * @param array{options: list, duration: int}|null $poll */ - public function createCommit(string $body, ?string $parentId = null, ?string $quotedCommitId = null, ?array $poll = null): Commit + public function createCommit(string $body, ?string $parentId = null, ?string $quotedCommitId = null, ?array $poll = null, ?string $author = null): Commit { - $commit = $this->data($this->send('POST', 'commits', payload: self::commitPayload($body, $parentId, $quotedCommitId, poll: $poll))); + $commit = $this->data($this->send('POST', 'commits', payload: self::commitPayload($body, $parentId, $quotedCommitId, $poll, $author))); $this->cache->commitAdded($commit); return Commit::fromArray($commit); @@ -319,9 +321,9 @@ public function createCommit(string $body, ?string $parentId = null, ?string $qu * * @param array{options: list, duration: int}|null $poll */ - public function signedCommit(string $body, ?string $parentId = null, ?string $quotedCommitId = null, ?array $poll = null): SignedRequest + public function signedCommit(string $body, ?string $parentId = null, ?string $quotedCommitId = null, ?array $poll = null, ?string $author = null): SignedRequest { - return $this->signedWrite('POST', 'commits', self::commitPayload($body, $parentId, $quotedCommitId, poll: $poll)); + return $this->signedWrite('POST', 'commits', self::commitPayload($body, $parentId, $quotedCommitId, $poll, $author)); } /** @@ -331,9 +333,9 @@ public function signedCommit(string $body, ?string $parentId = null, ?string $qu * * @param list $images */ - public function signedCommitWithImages(string $body, array $images, ?string $parentId = null, ?string $quotedCommitId = null): SignedRequest + public function signedCommitWithImages(string $body, array $images, ?string $parentId = null, ?string $quotedCommitId = null, ?string $author = null): SignedRequest { - return $this->signedWithImages('commits', self::commitPayload($body, $parentId, $quotedCommitId), $images); + return $this->signedWithImages('commits', self::commitPayload($body, $parentId, $quotedCommitId, author: $author), $images); } /** @@ -360,14 +362,15 @@ public function signedMessage(string $threadPath, string $body, string $clientId * Signs a commit to be submitted at $at, as the web's Schedule commit * does, for the background to send. Only you see it until then. With * photos it goes as multipart, as a commit with photos does, and a poll - * goes in its JSON. + * goes in its JSON. With $author it goes out as that organization when it's + * due, as long as you're still in it then. * * @param list $images * @param array|null $poll */ - public function signedScheduledCommit(string $body, CarbonInterface $at, array $images = [], ?array $poll = null): SignedRequest + public function signedScheduledCommit(string $body, CarbonInterface $at, array $images = [], ?array $poll = null, ?string $author = null): SignedRequest { - $payload = array_filter(['body' => $body, 'scheduled_at' => self::scheduleTime($at), 'poll' => $poll], fn (mixed $value): bool => $value !== null); + $payload = array_filter(['body' => $body, 'scheduled_at' => self::scheduleTime($at), 'poll' => $poll, 'author' => $author], fn (mixed $value): bool => $value !== null); return $images === [] ? $this->signedWrite('POST', self::ScheduledCommitsPath, $payload) @@ -976,13 +979,14 @@ private function send(string $method, string $path, array $query = [], ?array $p * @param array{options: list, duration: int}|null $poll * @return array */ - private static function commitPayload(string $body, ?string $parentId, ?string $quotedCommitId, ?array $poll = null): array + private static function commitPayload(string $body, ?string $parentId, ?string $quotedCommitId, ?array $poll = null, ?string $author = null): array { return array_filter([ 'body' => $body, 'parent_id' => $parentId, 'quoted_commit_id' => $quotedCommitId, 'poll' => $poll, + 'author' => $author, ], fn (mixed $value): bool => $value !== null); } diff --git a/app/Devnull/CommitMenu.php b/app/Devnull/CommitMenu.php index d566caf9..89a2b1e2 100644 --- a/app/Devnull/CommitMenu.php +++ b/app/Devnull/CommitMenu.php @@ -3,7 +3,6 @@ namespace App\Devnull; use App\Devnull\Data\Commit; -use App\Devnull\Data\User; use App\Icons\Lucide; use Native\Mobile\Edge\Elements\TopBarAction; use Native\Mobile\Edge\Layouts\Builders\NavAction; @@ -13,26 +12,28 @@ * 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 * 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). + * on yours. An organization's commit is yours while you're a member, whoever + * posted it (see Ownership), so every member gets Delete, as on the web. Only + * a person has a profile to pin to, so it never gets Pin. Each item names the + * commit, so a tap never rebuilds anything from an attribute (see ShowsCommits). */ final class CommitMenu { /** * @return list */ - public static function items(Commit $commit, ?User $viewer): array + public static function items(Commit $commit, Ownership $ownership): array { - $isOwn = $viewer !== null && $commit->author->id === $viewer->id; + $isOwn = $ownership->owns($commit); $items = []; $items[] = self::item($commit, 'share', 'Share link', Lucide::Link, 'shareCommit'); - if ($isOwn && $commit->isApproved() && $commit->parentId === null) { + if ($ownership->isYourOwn($commit) && $commit->isApproved() && $commit->parentId === null) { $items[] = self::item($commit, 'pin', $commit->isPinned ? 'Unpin from profile' : 'Pin to profile', Lucide::Pin, 'togglePin'); } - if ($viewer !== null && ! $isOwn && $commit->isApproved()) { + if ($ownership->isSignedIn() && ! $isOwn && $commit->isApproved()) { $items[] = NavAction::divider(); $items[] = self::item($commit, 'report', 'Report commit', Lucide::Flag, 'reportCommit'); } elseif ($isOwn) { diff --git a/app/Devnull/Data/Commit.php b/app/Devnull/Data/Commit.php index 941f4ce3..4a2f608d 100644 --- a/app/Devnull/Data/Commit.php +++ b/app/Devnull/Data/Commit.php @@ -4,6 +4,7 @@ use App\Devnull\Display; use App\Devnull\Lane; +use App\Devnull\Ownership; use Carbon\CarbonImmutable; use Closure; use Throwable; @@ -20,6 +21,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. + * + * $continuationId is the reply that carries on a thread its author writes as + * replies to themselves, when devnull says which (see SelfThread). */ final readonly class Commit { @@ -75,6 +79,7 @@ public function __construct( public ?ReplyPreview $replyPreview = null, public int $pasteisCount = 0, public ?ScoreCard $scoreCard = null, + public ?string $continuationId = null, ) {} /** @@ -142,6 +147,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, + continuationId: is_string($data['continuation_id'] ?? null) && $data['continuation_id'] !== '' ? $data['continuation_id'] : null, ); } @@ -163,6 +169,14 @@ public function withMorePasteis(int $change): self return new self(...[...get_object_vars($this), 'pasteisCount' => max(0, $this->pasteisCount + $change)]); } + /** + * This commit with the count of replies its own page gives, for a copy that came without one. + */ + public function withRepliesCount(int $repliesCount): self + { + return new self(...[...get_object_vars($this), 'repliesCount' => max(0, $repliesCount)]); + } + public function withPinned(bool $isPinned): self { return new self(...[...get_object_vars($this), 'isPinned' => $isPinned]); @@ -327,15 +341,15 @@ public function isApproved(): bool } /** - * Whether $viewer may vote on the commit's poll, as the web decides it: someone else's published commit, whose - * poll is open and hasn't had their vote yet. + * Whether you may vote on the commit's poll, as the web decides it: a published commit that isn't yours or your + * organization's (see Ownership), whose poll is open and hasn't had your vote yet. */ - public function canBeVotedOnBy(?User $viewer): bool + public function canBeVotedOnBy(Ownership $ownership): bool { - return $viewer !== null + return $ownership->isSignedIn() && $this->poll !== null && $this->isApproved() - && $this->author->id !== $viewer->id + && ! $ownership->owns($this) && $this->poll->closesAt !== null && ! $this->poll->hasVoted && ! $this->poll->showsResults() diff --git a/app/Devnull/Data/CurrentUser.php b/app/Devnull/Data/CurrentUser.php index 9fead8f8..32b1701d 100644 --- a/app/Devnull/Data/CurrentUser.php +++ b/app/Devnull/Data/CurrentUser.php @@ -19,9 +19,16 @@ * And the terms: the version in force, which is the moment it took effect, when * you last accepted them, and whether that was this version. A devnull too old * to say leaves all three null. + * + * And the GitHub organizations you're a member of, admin or not, oldest + * membership first, which you can post as, as the web's Post as menu lists + * them. A devnull too old to say leaves it null. */ final readonly class CurrentUser { + /** + * @param list|null $organizations + */ public function __construct( public User $user, public int $unreadNotificationsCount = 0, @@ -37,6 +44,7 @@ public function __construct( public ?string $termsVersion = null, public ?CarbonImmutable $termsAcceptedAt = null, public ?bool $termsAccepted = null, + public ?array $organizations = null, ) {} /** @@ -69,9 +77,23 @@ public static function fromArray(array $json): self termsVersion: is_string($data['terms_version'] ?? null) && $data['terms_version'] !== '' ? $data['terms_version'] : null, termsAcceptedAt: Commit::date($data['terms_accepted_at'] ?? null), termsAccepted: is_bool($data['terms_accepted'] ?? null) ? $data['terms_accepted'] : null, + organizations: is_array($data['organizations'] ?? null) ? self::organizations($data['organizations']) : null, ); } + /** + * The organizations you can post as, each drawn as an organization whatever the answer said. + * + * @param array $organizations + * @return list + */ + private static function organizations(array $organizations): array + { + $users = array_map(fn (array $organization): User => User::fromArray([...$organization, 'type' => 'organization']), array_values(array_filter($organizations, is_array(...)))); + + return array_values(array_filter($users, fn (User $organization): bool => $organization->username !== '')); + } + /** * The version of the terms devnull is waiting for you to accept, exactly as it sent it, or null when you have. */ diff --git a/app/Devnull/Data/ScheduledCommit.php b/app/Devnull/Data/ScheduledCommit.php index 31280b98..dcdf0b0e 100644 --- a/app/Devnull/Data/ScheduledCommit.php +++ b/app/Devnull/Data/ScheduledCommit.php @@ -10,7 +10,8 @@ * page, which only you see. Until it's submitted it has its body, the options * of its poll, and how many images it carries. Once submitted, those are its * commit's, and its status is that commit's: pending review, approved, - * rejected, or deleted. + * rejected, or deleted. $author is the organization it goes out as, or null + * when it goes out as you. */ final readonly class ScheduledCommit { @@ -39,6 +40,7 @@ public function __construct( public CarbonImmutable $scheduledAt, public ?CarbonImmutable $submittedAt, public string $status, + public ?User $author = null, ) {} /** @@ -62,6 +64,7 @@ public static function fromArray(array $data): self scheduledAt: Commit::date($data['scheduled_at'] ?? null) ?? CarbonImmutable::now(), submittedAt: Commit::date($data['submitted_at'] ?? null), status: is_string($status) && ($status === 'scheduled' || array_key_exists($status, self::Labels)) ? $status : 'scheduled', + author: is_array($data['author'] ?? null) ? User::fromArray([...$data['author'], 'type' => 'organization']) : null, ); } diff --git a/app/Devnull/Display.php b/app/Devnull/Display.php index a6aeb0bb..b61ff32c 100644 --- a/app/Devnull/Display.php +++ b/app/Devnull/Display.php @@ -27,6 +27,14 @@ final class Display public const int ReplyBarDescriptionHeight = 100; + /** + * The people to mention above a field (see partials/mention-suggestions): a row's height, and how many rows show + * before the rest scroll inside the list. + */ + public const int MentionRowHeight = 44; + + public const int MentionRowsShown = 6; + /** * A bar holding partials/composer-box with one line of draft, as drawn on an iPhone: the bar's padding, then the * field over the row of tools and the send button. @@ -44,6 +52,12 @@ final class Display */ public const int ComposerGlassTint = 40; + /** + * How opaque, in percent, the glass under a composer bar gets on iOS once it has faded in (glass/N, see + * composerBarGlass()). Full glass over a dark screen reads as a heavy slab. + */ + public const int ComposerGlassOpacity = 80; + /** * About how many characters fit on a line of the box's field, which runs the width of the box. */ @@ -56,12 +70,6 @@ final class Display */ public const int HomeIndicatorHeight = 34; - /** - * How far below the top of a reply's row its elbow comes level with the - * middle of the reply's avatar. - */ - public const int ElbowLevel = 22; - /** * How long ago a commit was made, as the web prints it beside the commit: * "now", "5m", "3h", "2d", then the date, in the same time zone as dayLabel(). @@ -300,12 +308,13 @@ public static function fadesInBar(): bool * The classes for a composer's native:bottom-bar. On iOS that's Liquid Glass: what scrolls under the bar shows * through it, blurred. A patched mobile-air draws the glass behind the whole bar, under the home indicator too, * and fades it in over the bar's top ComposerFadeHeight points, so it has no hard top edge. EDGE's own glass on - * an element can't be faded, and stops short of the home indicator. Android has no glass, so the bar stays the - * surface there. + * an element can't be faded, and stops short of the home indicator. The glass stops at ComposerGlassOpacity + * percent (glass/N), so a little of the screen under the bar shows through. Android has no glass, so the bar + * stays the surface there. */ public static function composerBarGlass(): string { - return self::fadesInBar() ? 'glass' : ''; + return self::fadesInBar() ? 'glass/'.self::ComposerGlassOpacity : ''; } /** diff --git a/app/Devnull/LastVisit.php b/app/Devnull/LastVisit.php index f88e01b2..4a951c89 100644 --- a/app/Devnull/LastVisit.php +++ b/app/Devnull/LastVisit.php @@ -36,13 +36,13 @@ public function remember(string $userId, string $log, array $commits): void /** * The commit the marker goes above, or null for a first visit, when nothing is - * new, or when the only new commits are your own. + * new, or when the only new commits are yours or your organizations' (see Ownership). * * @param list $commits newest first */ - public static function firstSeenId(array $commits, ?string $seenAt, ?string $userId): ?string + public static function firstSeenId(array $commits, ?string $seenAt, Ownership $ownership): ?string { - if ($seenAt === null || $userId === null) { + if ($seenAt === null || ! $ownership->isSignedIn()) { return null; } @@ -58,7 +58,7 @@ public static function firstSeenId(array $commits, ?string $seenAt, ?string $use } foreach (array_slice($commits, 0, $index) as $newer) { - if ($newer->author->id !== $userId) { + if (! $ownership->owns($newer)) { return $commit->id; } } diff --git a/app/Devnull/Ownership.php b/app/Devnull/Ownership.php new file mode 100644 index 00000000..99f52478 --- /dev/null +++ b/app/Devnull/Ownership.php @@ -0,0 +1,72 @@ + $organizationIds + */ + public function __construct( + public ?string $userId = null, + public array $organizationIds = [], + ) {} + + /** + * @param list $organizations + */ + public static function of(?User $user, array $organizations = []): self + { + $userId = $user === null || $user->id === '' ? null : $user->id; + + if ($userId === null) { + return new self; + } + + return new self($userId, array_values(array_filter( + array_map(fn (User $organization): string => $organization->id, $organizations), + fn (string $id): bool => $id !== '' && $id !== $userId, + ))); + } + + public function isSignedIn(): bool + { + return $this->userId !== null; + } + + /** + * Whether the commit is yours: by you, or by an organization you're in. + */ + public function owns(Commit $commit): bool + { + $author = $commit->author->id; + + return $this->userId !== null && $author !== '' && ($author === $this->userId || in_array($author, $this->organizationIds, true)); + } + + /** + * Whether you made the commit as yourself, not as an organization. + */ + public function isYourOwn(Commit $commit): bool + { + return $this->userId !== null && $commit->author->id === $this->userId; + } +} diff --git a/app/Devnull/Pop.php b/app/Devnull/Pop.php new file mode 100644 index 00000000..dc9e86f3 --- /dev/null +++ b/app/Devnull/Pop.php @@ -0,0 +1,39 @@ + ['scale' => 1.0, 'rotate' => 0.0, 'duration' => 150, 'easing' => 'ease-out'], + self::Up => ['scale' => $star ? 1.35 : 1.25, 'rotate' => $star ? -12.0 : 0.0, 'duration' => 150, 'easing' => 'ease-out'], + self::Down => ['scale' => 1.0, 'rotate' => 0.0, 'duration' => $star ? 320 : 180, 'easing' => $star ? 'spring' : 'ease-out'], + default => ['scale' => null, 'rotate' => null, 'duration' => null, 'easing' => null], + }; + } +} diff --git a/app/Devnull/PostAs.php b/app/Devnull/PostAs.php new file mode 100644 index 00000000..d57f5fb7 --- /dev/null +++ b/app/Devnull/PostAs.php @@ -0,0 +1,105 @@ + + */ + public static function organizations(): array + { + return app(Account::class)->organizations(); + } + + /** + * The organization the commit goes out as, or null when it goes out as you. + */ + public static function author(?string $picked): ?User + { + if ($picked === null || $picked === '') { + return null; + } + + foreach (self::organizations() as $organization) { + if (strcasecmp($organization->username, $picked) === 0) { + return $organization; + } + } + + return null; + } + + /** + * Whether the composer shows whom it posts as: you're in an organization, or picked one you've left since. + */ + public static function offered(?string $picked): bool + { + return self::organizations() !== [] || ($picked !== null && $picked !== ''); + } + + /** + * The menu: you first, then your organizations, each with their avatar, round for you and a rounded square for + * an organization, as elsewhere in the app, and the one posting now ticked. Until an avatar loads, or if it + * can't, a person or building icon stands in. $method is called with the handle picked, or '' for you. + * + * @return list + */ + public static function menu(User $me, ?User $author, string $method): array + { + return array_map(function (User $identity) use ($author, $method): TopBarAction { + $icon = $identity->isOrganization ? Lucide::Building2 : Lucide::UserRound; + + return NavAction::make('post-as-'.$identity->username) + ->label($identity->name.' (@'.$identity->username.')') + ->icon(ios: $icon->ios(), android: $icon->android()) + ->image(ImageCache::src($identity->avatarUrl)) + ->press($method."('".($identity->isOrganization ? $identity->username : '')."')") + ->toElement() + ->setProp('image_shape', $identity->isOrganization ? 'rounded' : 'circle') + ->setProp('checked', self::posting($identity, $author)) + ->ref('post-as-'.$identity->username); + }, [$me, ...self::organizations()]); + } + + /** + * What the composer's avatar says to a screen reader. + */ + public static function label(User $me, ?User $author): string + { + return 'Posting as @'.($author ?? $me)->username.'. Choose who to post as'; + } + + /** + * The lane the composer's main button is drawn in: yours, or the organization's. + */ + public static function colour(User $me, ?User $author): string + { + return Lane::token(($author ?? $me)->lane()); + } + + /** + * Whether the menu ticks this one: whoever posts now. + */ + private static function posting(User $identity, ?User $author): bool + { + return $author === null ? ! $identity->isOrganization : $identity->isOrganization && $identity->username === $author->username; + } +} diff --git a/app/Devnull/ResponseCache.php b/app/Devnull/ResponseCache.php index fadaa8a0..cc37bb14 100644 --- a/app/Devnull/ResponseCache.php +++ b/app/Devnull/ResponseCache.php @@ -396,7 +396,9 @@ public function pastelGiven(array $json): void /** * You committed. A commit goes on top of your logs and your profile; a reply - * goes under its parent and counts there, and on top of your replies. + * goes under its parent and counts there, and on top of your replies. One + * you posted as an organization is the organization's, so it stays off + * your profile and its counts, as devnull keeps it. * * @param array $commit */ @@ -409,14 +411,17 @@ public function commitAdded(array $commit): void } $parentId = is_string($commit['parent_id'] ?? null) ? $commit['parent_id'] : null; + $onYourProfile = ! self::isOrganizations($commit); if ($parentId === null) { // Trending is ranked, so a new commit has no place at the top of it. - foreach (['log/following', 'log/latest', "users/{$me}/commits"] as $path) { + foreach (['log/following', 'log/latest', ...($onYourProfile ? ["users/{$me}/commits"] : [])] as $path) { $this->patch($path, [], fn (array $json): array => self::prepend($json, $commit)); } - $this->patch("users/{$me}", [], fn (array $json): array => self::count($json, 'commits_count', 1)); + if ($onYourProfile) { + $this->patch("users/{$me}", [], fn (array $json): array => self::count($json, 'commits_count', 1)); + } return; } @@ -425,7 +430,10 @@ public function commitAdded(array $commit): void $this->patch("commits/{$parentId}/replies", [], fn (array $json): array => ($json['meta']['next_cursor'] ?? null) === null ? [...$json, 'data' => [...self::without($json['data'] ?? [], $commit['id']), $commit]] : $json); - $this->patch("users/{$me}/commits", ['replies' => '1'], fn (array $json): array => self::prepend($json, $commit)); + if ($onYourProfile) { + $this->patch("users/{$me}/commits", ['replies' => '1'], fn (array $json): array => self::prepend($json, $commit)); + } + $this->patchCommit($parentId, fn (array $parent): array => self::withNewestReply([...$parent, 'replies_count' => (int) ($parent['replies_count'] ?? 0) + 1], $commit)); } @@ -450,11 +458,14 @@ private static function withNewestReply(array $parent, array $reply): array } /** - * You deleted a commit: it leaves every list, its page goes, and its parent counts one reply fewer. + * You deleted a commit: it leaves every list, its page goes, and its parent + * counts one reply fewer. Your profile counts one commit fewer, unless it + * was an organization's you're in (see Ownership). */ public function commitDeleted(string $id): void { - $parentId = $this->findCommit($id)['parent_id'] ?? null; + $found = $this->findCommit($id); + $parentId = $found['parent_id'] ?? null; $this->rememberDeletion($id); @@ -465,11 +476,21 @@ public function commitDeleted(string $id): void if (is_string($parentId) && $parentId !== '') { $this->patchCommit($parentId, fn (array $parent): array => [...$parent, 'replies_count' => max(0, (int) ($parent['replies_count'] ?? 0) - 1)]); - } elseif (($me = $this->username()) !== null) { + } elseif (($me = $this->username()) !== null && ($found === null || ! self::isOrganizations($found))) { $this->patch("users/{$me}", [], fn (array $json): array => self::count($json, 'commits_count', -1)); } } + /** + * Whether a kept commit is an organization's. + * + * @param array $commit + */ + private static function isOrganizations(array $commit): bool + { + return is_array($commit['author'] ?? null) && ($commit['author']['type'] ?? null) === 'organization'; + } + /** * You followed or unfollowed someone: their profile and your following * count change, and every list of people kept with whether you follow them. diff --git a/app/Devnull/RowInputs.php b/app/Devnull/RowInputs.php index 0659a309..323d2265 100644 --- a/app/Devnull/RowInputs.php +++ b/app/Devnull/RowInputs.php @@ -25,16 +25,21 @@ final class RowInputs public static function for(Commit $commit, array $scope): array { $viewer = $scope['viewer'] ?? app(Account::class)->user(); + $ownership = $scope['ownership'] ?? app(Account::class)->ownership(); return [ 'viewer' => $viewer?->id, + 'organizations' => $ownership->organizationIds, 'pasteis' => $scope['pasteis'] ?? app(Account::class)->pasteis(), 'stashed' => $scope['stashed'] ?? [], 'unfolded' => $scope['unfolded'] ?? [], 'expandable' => isset($scope['threads']), - 'opened' => array_key_exists($commit->id, $scope['threads'] ?? []), + 'opened' => array_key_exists($commit->id, $scope['threads'] ?? []) && ! in_array($commit->id, $scope['closingThreads'] ?? [], true), + 'faded' => in_array($commit->id, $scope['fadedRows'] ?? [], true), + // A reply whose replies, opened in place, showed its author carried it on gets "Show thread". + 'continued' => in_array($commit->id, $scope['threadsContinued'] ?? [], true), + 'popping' => [$scope['popping']['star-'.$commit->id] ?? null, $scope['popping']['pastel-'.$commit->id] ?? null], 'tombstones' => $scope['tombstones'] ?? false, - 'tombstoneReplies' => array_key_exists($commit->id, $scope['tombstoneReplies'] ?? []), 'shown' => [self::changing($commit), $commit->quotedCommit === null ? null : self::changing($commit->quotedCommit)], 'poll' => [$scope['pollChoices'][$commit->id] ?? null, in_array($commit->id, $scope['voting'] ?? [], true)], ]; diff --git a/app/Devnull/SelfThread.php b/app/Devnull/SelfThread.php new file mode 100644 index 00000000..56278e10 --- /dev/null +++ b/app/Devnull/SelfThread.php @@ -0,0 +1,176 @@ + $parts The commits carrying the thread on below the commit, in order, at most the limit. + * @param bool $hasMore Whether another part follows the last of $parts. + * @param bool $hasEnded Whether it's known that no part follows the last of $parts. + * @param string|null $waiting The commit whose replies the walk needs to go on. + */ + public function __construct( + public array $parts = [], + public bool $hasMore = false, + public bool $hasEnded = false, + public ?string $waiting = null, + ) {} + + /** + * The reply among $replies that carries $commit's thread on, if it's one of them. + * + * @param iterable $replies + */ + public static function next(Commit $commit, iterable $replies): ?Commit + { + if ($commit->isDeleted() || $commit->isStaged() || $commit->author->id === '') { + return null; + } + + $earliest = null; + + foreach ($replies as $reply) { + if ($commit->continuationId !== null) { + if ($reply->id === $commit->continuationId) { + return $reply; + } + + continue; + } + + if ($reply->parentId !== $commit->id || $reply->isDeleted() || $reply->isStaged() || $reply->author->id !== $commit->author->id) { + continue; + } + + if ($earliest === null || self::isEarlier($reply, $earliest)) { + $earliest = $reply; + } + } + + return $earliest; + } + + /** + * $replies without the one that carries $commit's thread on, which shows as the next part of it instead. + * + * @param list $replies + * @return list + */ + public static function others(Commit $commit, array $replies): array + { + $next = self::next($commit, $replies); + + return $next === null ? $replies : array_values(array_filter($replies, fn (Commit $reply): bool => $reply->id !== $next->id)); + } + + /** + * Walks down from $commit through the parts that carry its thread on, as far as $limit and the replies that + * have come allow. + * + * @param Closure(Commit): (list|null) $repliesOf A commit's first page of replies, or null until it comes. + */ + public static function below(Commit $commit, Closure $repliesOf, int $limit = self::PerPage): self + { + $parts = []; + $above = $commit; + + while (true) { + $replies = $repliesOf($above); + + if ($replies === null) { + return new self($parts, waiting: $above->id); + } + + $next = self::next($above, $replies); + + if ($next === null || in_array($next, $parts, true) || $next->id === $commit->id) { + return new self($parts, hasEnded: true); + } + + if (count($parts) >= $limit) { + return new self($parts, hasMore: true); + } + + $parts[] = $next; + $above = $next; + } + } + + /** + * How many of the commits just above $commit, of $ancestors (oldest first), are earlier parts of its thread, + * and whose replies are needed to look further up. Only the author's own commits can be; each one is a part + * when its earliest reply from them is the one below it. + * + * @param list $ancestors + * @param Closure(Commit): (list|null) $repliesOf + * @return array{0: int, 1: string|null} + */ + public static function above(array $ancestors, Commit $commit, Closure $repliesOf): array + { + $count = 0; + $below = $commit; + + foreach (array_reverse($ancestors) as $ancestor) { + if ($below->isDeleted() || $ancestor->isDeleted() || $ancestor->author->id !== $below->author->id || $below->parentId !== $ancestor->id) { + break; + } + + $replies = $repliesOf($ancestor); + + if ($replies === null) { + return [$count, $ancestor->id]; + } + + if (self::next($ancestor, $replies)?->id !== $below->id) { + break; + } + + $count++; + $below = $ancestor; + } + + return [$count, null]; + } + + /** + * The place in its thread of the commit at $position, as the web's ThreadPositionBadge writes it: "3/7", with + * a "+" when more of the thread follows than has been read. Null for a commit that isn't part of one. + */ + public static function position(int $position, int $size, bool $isOpenEnded): ?string + { + return $size > 1 && $position >= 1 ? $position.'/'.$size.($isOpenEnded ? '+' : '') : null; + } + + private static function isEarlier(Commit $reply, Commit $than): bool + { + if ($reply->createdAt === null || $than->createdAt === null || $reply->createdAt->equalTo($than->createdAt)) { + return strcmp($reply->id, $than->id) < 0; + } + + return $reply->createdAt->lessThan($than->createdAt); + } +} diff --git a/app/Devnull/ThreadRows.php b/app/Devnull/ThreadRows.php new file mode 100644 index 00000000..6d26c2b5 --- /dev/null +++ b/app/Devnull/ThreadRows.php @@ -0,0 +1,234 @@ +> $threads Open threads, by the id of the commit or reply they answer. + * @param array $cursors Where each open thread with more carries on. + * @param array $shown How many of each open thread's replies show. + * @param int|string|null $railLane The commit's rail running on past its thread, when its author's run carries on below. + * @param int $opensInPlace How deep a reply's replies button opens its replies in place rather than its page. + * @param bool $onPage On a commit page: replies muted, deleted ones open theirs in place, and no hairline under them by default. + * @param string|null $morePress What the commit's own "Show more" presses, when it isn't showMoreReplies. + * @param bool|null $hairline Whether the last row closes the thread with a hairline: in a feed it does, and on a + * commit page only when another commit's row comes next. + * @return list, reply: Commit|null}> + */ + public static function under( + Commit $commit, + array $threads, + array $cursors, + array $shown, + int|string|null $railLane = null, + int $opensInPlace = 1, + bool $onPage = false, + ?string $morePress = null, + ?bool $hairline = null, + ): array { + $thread = fn (string $id): array => array_slice($threads[$id] ?? [], 0, $shown[$id] ?? null); + $hasMore = fn (string $id): bool => isset($cursors[$id]) || count($thread($id)) < count($threads[$id] ?? []); + + $rows = []; + self::branch($rows, $commit, 1, [], $thread, $hasMore, [ + 'railLane' => $railLane, + 'opensInPlace' => $opensInPlace, + 'onPage' => $onPage, + 'morePress' => $morePress, + 'hairline' => $hairline ?? ! $onPage, + ]); + + if ($rows === []) { + return []; + } + + $last = array_key_last($rows); + $rows[$last]['data']['last'] = true; + + return $rows; + } + + /** + * How far in replies at $depth start, past the commit's text. + */ + public static function indent(int $depth): int + { + return (min($depth, self::MaxIndentDepth) - 1) * self::Step; + } + + /** + * The x of the line down from the avatars of replies at $depth, or the commit's rail above them all. + */ + private static function lineAt(int $depth): float + { + return $depth === 0 ? 31.5 : 75.5 + self::indent($depth); + } + + /** + * The rows of $parent's replies at $depth, and theirs under each. + * + * @param list> $rows + * @param list $spines Lines from further up running on past these rows. + * @param Closure(string): list $thread + * @param Closure(string): bool $hasMore + * @param array{railLane: int|string|null, opensInPlace: int, onPage: bool, morePress: string|null, hairline: bool} $options + */ + private static function branch(array &$rows, Commit $parent, int $depth, array $spines, Closure $thread, Closure $hasMore, array $options): void + { + $replies = $thread($parent->id); + + if ($replies === []) { + return; + } + + $more = $hasMore($parent->id); + $indent = self::indent($depth); + $hangs = $depth === self::MaxIndentDepth; + $flattened = $depth > self::MaxIndentDepth; + $parentLine = self::lineAt($depth - 1); + $onPage = $options['onPage']; + + foreach ($replies as $index => $reply) { + $nested = $reply->isDeleted() && ! $onPage ? [] : $thread($reply->id); + $followed = $index < count($replies) - 1 || $more; + $top = ! $onPage && $depth === 1 && $index === 0 ? self::FirstReplyTop : 10; + + $rows[] = self::reply($reply, [ + 'lane' => $parent->lane(), + 'previousLane' => $index === 0 || $hangs ? null : $replies[$index - 1]->lane(), + 'hasNext' => ! $hangs && ! $flattened && ($followed || $nested !== []), + 'links' => ! $flattened, + 'railLane' => $options['railLane'], + 'indent' => $indent, + 'top' => $top, + // At the deepest step the line of the reply answered runs on under the elbow to the next one. + 'spines' => [...$spines, ...($hangs && $followed ? [['left' => $parentLine, 'lane' => $parent->lane(), 'top' => $top + 12]] : [])], + 'replyingTo' => $flattened ? self::replyingTo($reply, $parent) : null, + 'repliesInPlace' => $depth <= $options['opensInPlace'], + 'muted' => $onPage, + 'tombstones' => $onPage, + 'hairline' => $options['hairline'], + ]); + + // The line that has to run on past this reply's own replies, to the next reply at this depth. + $through = match (true) { + ! $followed || $flattened => [], + $hangs => [['left' => $parentLine, 'lane' => $parent->lane()]], + default => [['left' => self::lineAt($depth), 'lane' => $reply->lane()]], + }; + + self::branch($rows, $reply, $depth + 1, [...$spines, ...$through], $thread, $hasMore, $options); + } + + if ($more) { + $rows[] = self::more($parent, [ + 'lane' => $replies[array_key_last($replies)]->lane(), + 'parentLane' => $parent->lane(), + 'hangs' => $hangs, + 'links' => ! $flattened, + 'railLane' => $options['railLane'], + 'indent' => $indent, + 'spines' => $spines, + 'to' => $flattened && ! $parent->isDeleted() ? $parent->author->handle() : null, + 'hairline' => $options['hairline'], + ...($depth === 1 && $options['morePress'] !== null ? ['press' => $options['morePress']] : []), + ]); + } + } + + /** + * "replying to @handle", or "quoting" when the reply quotes what it answers, as the web marks a flattened reply. + */ + private static function replyingTo(Commit $reply, Commit $parent): string + { + return ($reply->quotedCommitId === $parent->id ? 'quoting ' : 'replying to ').($parent->isDeleted() ? '[deleted]' : $parent->author->handle()); + } + + /** + * @param array $data + * @return array{key: string, partial: string, data: array, reply: Commit} + */ + private static function reply(Commit $reply, array $data): array + { + return [ + 'key' => 'thread-reply-'.$reply->id, + 'partial' => 'native.partials.thread-reply', + 'data' => ['reply' => $reply, 'last' => false, 'fades' => true, ...$data], + 'reply' => $reply, + ]; + } + + /** + * "Show more" at the foot of a thread, on a line down in the lane of the reply above it. + * + * @param array $data + * @return array{key: string, partial: string, data: array, reply: null} + */ + private static function more(Commit $parent, array $data): array + { + return [ + 'key' => 'thread-more-'.$parent->id, + 'partial' => 'native.partials.thread-more-row', + 'data' => ['threadId' => $parent->id, 'last' => false, ...$data], + 'reply' => null, + ]; + } +} diff --git a/app/Icons/Lucide.php b/app/Icons/Lucide.php index 3df5fa55..24bcab8f 100644 --- a/app/Icons/Lucide.php +++ b/app/Icons/Lucide.php @@ -36,6 +36,7 @@ enum Lucide case ArrowUp; case Pin; case ListOrdered; + case ListTree; /** lucide-react 1.57 draws Building2 as building-complex, so that is the drawing in building-2.svg. */ case Building2; case MapPin; @@ -177,6 +178,7 @@ public function custom(bool $filled = false): string self::ArrowUp => 'arrow-up', self::ChevronsUp => 'chevrons-up', self::ListOrdered => 'list-ordered', + self::ListTree => 'list-tree', self::Building2 => 'building-2', self::MapPin => 'map-pin', self::CalendarDays => 'calendar-days', diff --git a/app/Models/PendingWrite.php b/app/Models/PendingWrite.php index 917bc654..74fb060b 100644 --- a/app/Models/PendingWrite.php +++ b/app/Models/PendingWrite.php @@ -19,8 +19,8 @@ * $target is what it's about: the commit starred, or the Remotes thread a * message goes to. $payload is what's sent, and for a commit what the * composer needs to have it back: its body, what it replies to or quotes, - * its poll, its photos with their descriptions, and the draft it was - * stashed under. + * its poll, its photos with their descriptions, the draft it was stashed + * under, and the organization it goes out as, if not as you. * * It's queued until it goes, sending while it's on its way, and failed once * devnull turned it down, when a commit stays for you to edit and a message @@ -132,6 +132,34 @@ public function quotedCommitId(): ?string return is_string($this->payload['quoted_commit_id'] ?? null) ? $this->payload['quoted_commit_id'] : null; } + /** + * The handle of the organization a commit goes out as, or null when it goes out as you. + */ + public function author(): ?string + { + return is_string($this->payload['author'] ?? null) && $this->payload['author'] !== '' ? $this->payload['author'] : null; + } + + /** + * The organization a commit goes out as, as the composer knew it, for the staged commit to show it, or null. + */ + public function authorProfile(): ?User + { + $profile = $this->payload['author_profile'] ?? null; + + return $this->author() !== null && is_array($profile) ? User::fromArray([...$profile, 'type' => 'organization']) : null; + } + + /** + * The payload's part for who a commit goes out as: nothing for you, and an organization's handle and profile. + * + * @return array{author?: string, author_profile?: array} + */ + public static function authorPayload(?User $organization): array + { + return $organization === null ? [] : ['author' => $organization->username, 'author_profile' => $organization->toArray()]; + } + /** * The commit's poll as devnull takes it, or null with none. * @@ -200,12 +228,15 @@ public static function imagePayload(array $images): array } /** - * The commit a commit on its way stands in as, by you, at once: what you - * wrote and its photos, marked staged, as the web's git words go, until - * devnull has it and the real one takes its place. + * The commit a commit on its way stands in as, at once: by you, or by the + * organization it goes out as, with what you wrote and its photos, marked + * staged, as the web's git words go, until devnull has it and the real one + * takes its place. */ - public function stagedCommit(User $author): Commit + public function stagedCommit(User $me): Commit { + $author = $this->authorProfile() ?? $me; + return new Commit( id: self::StagedPrefix.$this->client_id, body: $this->body(), diff --git a/app/NativeComponents/CommitDetail.php b/app/NativeComponents/CommitDetail.php index 169606fd..44239e01 100644 --- a/app/NativeComponents/CommitDetail.php +++ b/app/NativeComponents/CommitDetail.php @@ -14,13 +14,17 @@ use App\Devnull\Display; use App\Devnull\DraftImages; use App\Devnull\Outbox; +use App\Devnull\PostAs; use App\Devnull\ResponseCache; use App\Devnull\RowCache; +use App\Devnull\SelfThread; use App\Devnull\Stash; +use App\Devnull\ThreadRows; use App\Devnull\Timeline; use App\Devnull\Toasts; use App\Icons\Lucide; use App\Models\PendingWrite; +use App\NativeComponents\Concerns\ExpandsThreads; use App\NativeComponents\Concerns\OpensInTab; use App\NativeComponents\Concerns\OpensLiveStream; use App\NativeComponents\Concerns\RedrawsOnAppearanceChange; @@ -42,9 +46,18 @@ * The commit opens near the top, under the commit it replies to, with the * ones before that behind "↑ N earlier commits" and its replies behind * "› N replies", each opened in place. Opened from a "› N replies" button - * ($data['replies']), its replies already show. They come five at a time + * ($data['replies']), its replies already show. They come ten at a time * (see Client::RepliesPerPage), and "Show more" under the last asks for the - * next five, as it does under a deleted reply's replies opened in place. + * next ten. + * + * Each reply's own replies open in place under it, and theirs under them, as + * deep as they go, as the web's commit page does (see ExpandsThreads and + * App\Devnull\ThreadRows). So do the commits above the commit, less the one + * on the line down to it, which already shows (see ancestorThreads()). + * + * Tapping a commit in the tree, above the commit, below it or among the + * replies at any depth, moves this page to it rather than pushing another + * (see refocus()). Back still leaves the page. * * It opens on the commit as it was last time, or opened from a row, on what * the row knew of it, then asks devnull for the rest behind it and fills it in. @@ -67,18 +80,37 @@ * * A reply goes at once: the bar empties and the reply shows staged under the * commit while it goes to devnull from the outbox (see SyncsOutbox), then the - * real one takes its place. If devnull turns it down, it leaves, and what you + * real one takes its place. The page scrolls to it as it shows, and stays + * there when the real one comes (see scrollToRow()). If devnull turns it down, it leaves, and what you * wrote is back in the bar, or in the sheet with its photos. Edit, on the * toast of a reply or a quote turned down after you'd left, opens its commit * here with it ($data['edit']). + * + * A member of a GitHub organization can reply as it, from the avatar at the + * start of the bar's row, as the web's reply composer does (see PostAs). + * + * A thread its author wrote as replies to themselves reads in order, as on + * the web (see SelfThread): the parts after the commit follow it on its rail, + * each with its place in the thread, ten at a time with "Show more of this + * thread", and the next part isn't among the commit's replies. The replies of + * the last part show under it. The earlier parts are the ancestors above it, + * and wear their places too. Each step needs the replies of the commit above + * it, which are asked for one after another ($partReplies). */ class CommitDetail extends NativeComponent { + use ExpandsThreads { + toggleReplies as private toggleThread; + showMoreReplies as private showMoreThreadReplies; + } use OpensInTab; use OpensLiveStream; use RedrawsOnAppearanceChange; use RefreshesInBackground; use ShowsCommits { + openCommit as private openCommitPage; + openReplies as private openRepliesPage; + replyTo as private replyOnPage; reopenFailedCommit as private reopenFailedCommitInSheet; editFailedCommit as private editFailedCommitInSheet; mentionFields as private sheetMentionFields; @@ -96,6 +128,13 @@ class CommitDetail extends NativeComponent /** @var list */ public array $ancestors = []; + /** + * The commits above whose own page was asked for their count since the page last asked devnull again. + * + * @var list + */ + protected array $countedAncestors = []; + /** * The parts of its series after the commit, in order. * @@ -106,6 +145,26 @@ class CommitDetail extends NativeComponent /** @var list */ public array $replies = []; + /** + * The first page of replies of the commits around this one in its author's thread, by id, which say which + * reply carries it on (see SelfThread). + * + * @var array> + */ + public array $partReplies = []; + + /** + * The commits in $partReplies with more replies than their first page. + * + * @var list + */ + public array $partsWithMore = []; + + /** + * How many parts of the author's thread show after the commit. + */ + public int $threadLimit = SelfThread::PerPage; + public ?string $repliesCursor = null; /** @@ -157,20 +216,6 @@ class CommitDetail extends NativeComponent */ public bool $repliesLoaded = false; - /** - * The replies of deleted replies that were opened in place, by the deleted reply's id. - * - * @var array> - */ - public array $tombstoneReplies = []; - - /** - * Where the next page of each deleted reply's replies starts, by the deleted reply's id, or null when they're all shown. - * - * @var array - */ - public array $tombstoneCursors = []; - public string $reply = ''; /** @@ -180,6 +225,11 @@ class CommitDetail extends NativeComponent */ public array $replyImages = []; + /** + * The handle of the organization the reply bar posts as, or null for you (see PostAs). + */ + public ?string $replyAuthor = null; + /** * Whether the reply was stashed when the page opened, which the bar marks until you empty it or drop it. */ @@ -206,6 +256,30 @@ class CommitDetail extends NativeComponent */ public int $scrollKey = 0; + /** + * Which of the scroll view's rows it brings into view: the commit's, once tapping another commit in the tree + * moved the page to it (see refocus()), or the reply you just sent (see scrollToRow()). Null until one of those, + * so the page opens at the top as it always has. + */ + public ?int $scrollTarget = null; + + /** + * Counts the moves refocus() and scrollToRow() made. The scroll view takes it as its auto-scroll-token, so asking for the same row + * as last time (going back to the top twice) scrolls again rather than doing nothing. + */ + public int $scrollRequest = 0; + + /** + * The key of the row scrollToRow() brought into view last, so a reply you sent can be followed when devnull's + * takes its place (see showCommitWent()). + */ + private ?string $scrolledToRow = null; + + /** + * The commit the page opened on, before tapping others in its tree moved it (see refocus()). + */ + public string $openedId = ''; + /** * The replies from the last frame, so a render only builds the replies that changed, as the Log does its rows. */ @@ -222,6 +296,7 @@ class CommitDetail extends NativeComponent public function mount(): void { + $this->openedId = $this->id; $this->focusReply = $this->data('reply', false) === true; $this->repliesShown = $this->data('replies', false) === true; $draft = app(Stash::class)->get($this->me()?->id, $this->replyStashName()); @@ -275,26 +350,20 @@ public function load(): void protected function revalidate(): void { - $this->refresh($this->threadPath(), [], fn (array $json) => $this->takeThread($json)); + $this->countedAncestors = []; + $this->refresh($this->threadPath(), [], fn (array $json) => $this->takeCommitThread($json)); $this->refresh($this->threadPath().'/replies', [], fn (array $json) => $this->takeReplies($json)); $this->refresh($this->threadPath().'/related', [], fn (array $json) => $this->takeRelated($json), quiet: true, failed: function (): void { $this->related = []; app(ResponseCache::class)->forget($this->threadPath().'/related'); }); - foreach (array_keys($this->tombstoneReplies) as $id) { - $id = (string) $id; - - $this->refresh('commits/'.rawurlencode($id).'/replies', [], function (array $json) use ($id): void { - if (array_key_exists($id, $this->tombstoneReplies)) { - [$this->tombstoneReplies[$id], $this->tombstoneCursors[$id]] = self::withFirstPage( - $this->tombstoneReplies[$id], - $this->tombstoneCursors[$id] ?? null, - Page::fromArray($json, Commit::fromArray(...)), - ); - } - }); + foreach (array_keys($this->partReplies) as $id) { + $this->refreshPartReplies((string) $id); } + + $this->refreshThreads(); + $this->countAncestorReplies(); } protected function showsContent(): bool @@ -308,6 +377,7 @@ protected function showsContent(): bool public function showEarlier(): void { $this->earlierShown = true; + $this->countAncestorReplies(); } /** @@ -318,15 +388,328 @@ public function showEarlier(): void public function replyTapped(): void { $this->earlierShown = false; + $this->scrollTarget = null; $this->scrollKey++; } /** - * "› N replies" under the commit opens them in place, and "Hide replies" folds them away. + * A commit in the tree this page shows moves the page to it, rather than + * pushing another commit page (see refocus()). Anything else opens its page. + */ + public function openCommit(string $id): void + { + if (! $this->refocus($id)) { + $this->openCommitPage($id); + } + } + + /** + * "Show more" under the last part of a thread, or "› N replies" on a commit in the tree: the page moves to it with + * its replies showing. + */ + public function openReplies(string $id): void + { + if (! $this->refocus($id)) { + $this->openRepliesPage($id); + } + } + + /** + * Reply on a commit in the tree moves the page to it, with the reply bar answering it and its keyboard up. + */ + public function replyTo(string $id): void + { + if ($id === $this->id) { + $this->focusReply = true; + + return; + } + + if ($this->refocus($id)) { + $this->focusReply = true; + + return; + } + + $this->replyOnPage($id); + } + + /** + * Moves the page to a commit already in its tree: an ancestor, a part of + * the author's thread or series, or a reply at any depth. It becomes the + * commit the page is about, with what's above it as its ancestors and its + * replies showing below, all from what the page already has, so nothing + * goes blank, and devnull is asked for the rest behind it. The commits + * above it start with their replies folded, showing only "› N replies", + * as when the page opens on a reply. Moving up, the commit the page was on + * keeps its replies, and so do the commits between, so the commit you + * move to shows the way back down to where you came from opened under it. + * + * The page stays one screen: Back still leaves it, as Simon asked, rather + * than stepping back through the commits it moved to. The scroll view + * brings the commit into view, with every ancestor showing above it. + * + * False, changing nothing, for a commit that isn't in the tree, or one + * that's staged or deleted, which has no page of its own. + */ + private function refocus(string $id): bool + { + if ($this->commit === null || $id === $this->id) { + return false; + } + + $target = $this->treeCommit($id); + $ancestors = $target === null || $target->isStaged() || $target->isDeleted() ? null : $this->ancestorsInTree($target); + + if ($ancestors === null) { + return false; + } + + $line = [...$this->ancestors, $this->commit]; + $below = array_slice($line, count($ancestors) + 1); + + // What the page was on keeps its replies, opened in place, when it ends up below the commit the page moves to. + if ($this->repliesShown && $this->repliesLoaded && $this->replies !== []) { + $this->threads[$this->id] = array_values(array_filter($this->replies, fn (Commit $reply): bool => ! $reply->isStaged())); + $this->keepCursor($this->id, $this->repliesCursor); + unset($this->threadShown[$this->id]); + } + + // Moving up, the commits between keep their replies open, so the one the page was on shows under them. + foreach ($below as $between) { + if ($between->id !== $this->id && ! array_key_exists($between->id, $this->threads) && ($kept = $this->cached('commits/'.rawurlencode($between->id).'/replies')) !== null) { + $this->takeThread($between->id, $kept); + } + } + + $this->id = $id; + $this->commit = $target; + $this->ancestors = $ancestors; + $this->series = []; + $this->related = []; + $this->relatedShown = false; + $this->threadLimit = SelfThread::PerPage; + $this->takeOwnReplies($id); + + // The commits above it fold their replies, the commit the page was on among them when the page moved down. + foreach ($this->ancestors as $ancestor) { + $this->closeThread($ancestor->id); + } + + if (($thread = $this->cached($this->threadPath())) !== null) { + $this->takeCommitThread($thread); + } + + $this->takeRelated($this->cached($this->threadPath().'/related') ?? []); + $this->repliesShown = true; + $this->earlierShown = true; + $this->takeReplyDraft(); + $this->error = null; + + // The commit's row is the one after its ancestors, whose replies are folded. A new token asks again even when + // that's the row the scroll view went to last time. The scroll view keeps its key, so its rows slide to their + // new places. Opening an ancestor's replies later leaves the target be, so it doesn't scroll. + $this->scrollTarget = count($this->ancestors); + $this->scrollRequest++; + $this->forgetRefreshes(); + $this->revalidate(); + $this->followThread(); + + return true; + } + + /** + * The commit's own replies, as the page knows them: opened in place, read for its author's thread, or kept from + * before. Until one of those, they show as loading. + */ + private function takeOwnReplies(string $id): void + { + $this->replies = []; + $this->repliesCursor = null; + $this->repliesLoaded = false; + + if (array_key_exists($id, $this->threads)) { + $this->replies = $this->threads[$id]; + $this->repliesCursor = $this->threadCursors[$id] ?? null; + $this->repliesLoaded = true; + unset($this->threads[$id], $this->threadCursors[$id], $this->threadShown[$id]); + $this->pagedThreads = array_values(array_diff($this->pagedThreads, [$id])); + } elseif (($kept = $this->cached($this->threadPath().'/replies')) !== null) { + $this->takeReplies($kept); + + return; + } elseif (array_key_exists($id, $this->partReplies)) { + $this->replies = $this->partReplies[$id]; + $this->repliesLoaded = true; + } + + $this->keepStagedReplies(); + } + + /** + * The reply bar takes up the draft kept for the commit the page is on now. + */ + private function takeReplyDraft(): void + { + $draft = app(Stash::class)->get($this->me()?->id, $this->replyStashName()); + $this->reply = $draft->body; + $this->replyImages = $draft->images; + $this->replyRestored = ! $draft->isEmpty(); + $this->replyAuthor = null; + $this->replyPreviewing = false; + $this->replyPreview = null; + $this->focusReply = false; + } + + /** + * A commit the page draws in its tree, by id: around the commit, in its author's thread, or among the replies. + */ + private function treeCommit(string $id): ?Commit + { + $lastPart = $this->commit === null ? null : $this->selfThread()->parts; + $tree = [ + ...$this->ancestors, + ...$this->series, + ...($lastPart ?? []), + ...$this->replies, + ...$this->threadCommits(), + ...array_merge([], ...array_values($this->partReplies)), + ]; + + foreach ($tree as $commit) { + if ($commit->id === $id) { + return $commit; + } + } + + return null; + } + + /** + * What's above $target in the tree, in order: the page's line of ancestors as far as the one it hangs from, then + * the replies, parts or series between. Null when it doesn't hang from that line. + * + * @return list|null + */ + private function ancestorsInTree(Commit $target): ?array + { + $line = [...$this->ancestors, ...($this->commit === null ? [] : [$this->commit])]; + $lineIds = array_map(fn (Commit $commit): string => $commit->id, $line); + $at = array_search($target->id, $lineIds, true); + + if ($at !== false) { + return array_slice($line, 0, $at); + } + + $between = []; + $parentId = $target->parentId; + + while ($parentId !== null && ! in_array($parentId, $lineIds, true)) { + $parent = $this->treeCommit($parentId); + + if ($parent === null || in_array($parent, $between, true)) { + return null; + } + + array_unshift($between, $parent); + $parentId = $parent->parentId; + } + + if ($parentId === null) { + return null; + } + + return [...array_slice($line, 0, array_search($parentId, $lineIds, true) + 1), ...$between]; + } + + /** + * The replies of each commit above the commit, as its "› N replies" opens them in place under it, the same as a + * reply's (see ExpandsThreads), and how many that button counts. The commit under it on the page, when that's + * one of its replies, is left out of both: it's already showing, on the line down to the commit. The web leaves + * out only the part of a self-thread that carries it on (see SelfThread), so there the rest of the line would + * show twice. devnull's count already leaves that part out. + * + * @param list $above + * @return array, reply: Commit|null}>}> + */ + private function ancestorThreads(array $above): array + { + if ($this->commit === null) { + return []; + } + + $line = [...$above, $this->commit]; + $threads = []; + + foreach ($above as $index => $ancestor) { + $next = $line[$index + 1]; + $onLine = $next->parentId === $ancestor->id && $ancestor->continuationId !== $next->id; + $replies = array_values(array_filter($this->threads[$ancestor->id] ?? [], fn (Commit $reply): bool => $reply->id !== $next->id)); + + $threads[$ancestor->id] = [ + 'count' => max(0, $ancestor->repliesCount - ($onLine ? 1 : 0)), + 'rows' => $ancestor->isDeleted() || $replies === [] ? [] : ThreadRows::under( + $ancestor, + [...$this->threads, $ancestor->id => $replies], + $this->threadCursors, + $this->threadShown, + $ancestor->lane(), + opensInPlace: PHP_INT_MAX, + onPage: true, + // The next commit on the line follows them, so they end on the hairline the ancestor's row gave up. + hairline: true, + ), + ]; + } + + return $threads; + } + + /** + * The commits on the page's line, above the commit and the commit itself, draw rows of their own, so closing the + * replies they're among leaves their own replies open. */ - public function toggleReplies(): void + protected function drawsOnItsOwn(string $id): bool { - $this->repliesShown = ! $this->repliesShown; + return $id === $this->id || in_array($id, array_map(fn (Commit $ancestor): string => $ancestor->id, $this->ancestors), true); + } + + /** + * "› N replies" under the commit opens them in place, and "Hide replies" folds them away. Under a reply, at any + * depth, or a commit above the commit, it opens that one's replies in place under it (see ExpandsThreads). + */ + public function toggleReplies(string $id = ''): void + { + if ($id === '' || $id === $this->id) { + $this->repliesShown = ! $this->repliesShown; + + return; + } + + $this->toggleThread($id); + } + + /** + * "Show more" under a reply's replies opened in place. The commit's own go on from loadMoreReplies(). + */ + public function showMoreReplies(string $id): void + { + if ($id === $this->id) { + $this->loadMoreReplies(); + + return; + } + + $this->showMoreThreadReplies($id); + } + + /** + * "Show more of this thread": the next ten parts of the author's thread, as on the web. + */ + public function showMoreThread(): void + { + $this->threadLimit += SelfThread::PerPage; + $this->followThread(); } /** @@ -394,39 +777,6 @@ public function toggleRelated(): void Beat::dispatch(self::RelatedFade)->finished($closed)->failed($closed); } - /** - * A deleted reply has no page of its own, so its replies open in place below it. - */ - public function toggleTombstone(string $id): void - { - if (array_key_exists($id, $this->tombstoneReplies)) { - unset($this->tombstoneReplies[$id], $this->tombstoneCursors[$id]); - - return; - } - - $this->loadTombstoneReplies($id); - } - - /** - * "Show more" under a deleted reply's replies: its next five, in place. - */ - public function loadMoreTombstoneReplies(string $id): void - { - $cursor = $this->tombstoneCursors[$id] ?? null; - - if ($cursor === null) { - return; - } - - $page = $this->attempt(fn ($devnull) => $devnull->replies($id, $cursor)); - - if ($page !== null && array_key_exists($id, $this->tombstoneReplies)) { - $this->tombstoneReplies[$id] = [...$this->tombstoneReplies[$id], ...$page->items]; - $this->tombstoneCursors[$id] = $page->nextCursor; - } - } - public function loadMoreReplies(): void { if ($this->repliesCursor === null) { @@ -442,6 +792,7 @@ public function loadMoreReplies(): void $this->replies = [...array_values(array_filter($this->replies, fn (Commit $reply): bool => ! isset($loaded[$reply->id]))), ...$page->items]; $this->repliesCursor = $page->nextCursor; $this->keepStagedReplies(); + $this->followThread(); } } @@ -465,6 +816,7 @@ public function sendReply(): void 'images' => PendingWrite::imagePayload($this->replyImages), 'stash' => $this->replyStashName(), 'composer' => 'bar', + ...PendingWrite::authorPayload(PostAs::author($this->replyAuthor)), ]); if ($write === null) { @@ -479,9 +831,18 @@ public function sendReply(): void $this->updatedReply(); $this->repliesShown = true; $this->keepStagedReplies(); + $this->scrollToRow('thread-reply-'.PendingWrite::stagedId($write->client_id)); $this->sendFromOutbox($write); } + /** + * Post as, from the reply bar's avatar: an organization's handle, or '' for you. + */ + public function postAsInReply(string $handle = ''): void + { + $this->replyAuthor = PostAs::author($handle)?->username; + } + /** * The reply bar suggests whom devnull suggests for a reply to this commit, the people in its thread first, as * the web's reply composer asks, and so does the composer sheet over it (see SuggestsMentions). @@ -536,6 +897,7 @@ protected function showCommitted(Commit $commit): void $this->replyRestored = false; $this->repliesShown = true; $this->keepStagedReplies(); + $this->scrollToRow('thread-reply-'.$commit->id); } /** @@ -546,6 +908,32 @@ protected function showCommitWent(PendingWrite $write, Commit $commit): void $staged = PendingWrite::stagedId($write->client_id); $this->replies = array_map(fn (Commit $reply): Commit => $reply->id === $staged ? $commit : $reply, $this->replies); + $this->followThread(); + $this->followSentReply('thread-reply-'.$staged, $commit); + } + + /** + * The page scrolled to a reply you sent, staged, and devnull's reply has taken its place. That's the same row, + * so the scroll view is left be. Only when the reply has moved, as the next part of your thread below the + * commit's replies, does the page follow it there. + */ + private function followSentReply(string $stagedKey, Commit $commit): void + { + if ($this->scrolledToRow !== $stagedKey) { + return; + } + + $keys = array_column($this->pageRows($this->viewData()), 'key'); + $at = array_search('thread-reply-'.$commit->id, $keys, true); + $at = $at === false ? array_search('commit-'.$commit->id, $keys, true) : $at; + + if ($at === false || $at === $this->scrollTarget) { + $this->scrolledToRow = null; + + return; + } + + $this->scrollToRow($keys[$at]); } /** @@ -661,6 +1049,16 @@ protected function commitSheetGone(string $view): void */ protected function showDeleted(string $id): void { + // The page moved here from a commit above it, so it goes back there rather than leaving. + $parent = $this->ancestors === [] ? null : end($this->ancestors); + + if ($id === $this->id && $id !== $this->openedId && $parent !== null && $this->refocus($parent->id)) { + $this->threads = array_map(fn (array $replies): array => array_values(array_filter($replies, fn (Commit $reply): bool => $reply->id !== $id)), $this->threads); + $this->replies = array_values(array_filter($this->replies, fn (Commit $reply): bool => $reply->id !== $id)); + + return; + } + if ($id === $this->id) { $this->back(); @@ -676,8 +1074,9 @@ protected function updateShownCommits(Closure $update): void $this->ancestors = array_map($update, $this->ancestors); $this->series = array_map($update, $this->series); $this->replies = array_map($update, $this->replies); + $this->partReplies = array_map(fn (array $replies): array => array_map($update, $replies), $this->partReplies); $this->related = array_map($update, $this->related); - $this->tombstoneReplies = array_map(fn (array $replies): array => array_map($update, $replies), $this->tombstoneReplies); + $this->threads = array_map(fn (array $replies): array => array_map($update, $replies), $this->threads); } /** @@ -685,7 +1084,7 @@ protected function updateShownCommits(Closure $update): void */ protected function shownCommits(): iterable { - return [...($this->commit === null ? [] : [$this->commit]), ...$this->ancestors, ...$this->series, ...$this->replies, ...$this->related, ...array_merge([], ...array_values($this->tombstoneReplies))]; + return [...($this->commit === null ? [] : [$this->commit]), ...$this->ancestors, ...$this->series, ...$this->replies, ...array_merge([], ...array_values($this->partReplies)), ...$this->related, ...$this->threadCommits()]; } /** @@ -708,6 +1107,7 @@ private function takeFailedReply(PendingWrite $write): void { $this->reply = $write->body(); $this->replyImages = $write->images(); + $this->replyAuthor = $write->author(); $this->replyRestored = true; $this->focusReply = true; $this->updatedReply(); @@ -735,7 +1135,7 @@ private function keepStagedReplies(): void private function showKept(): void { if (($thread = $this->cached($this->threadPath())) !== null) { - $this->takeThread($thread); + $this->takeCommitThread($thread); } elseif ($this->commit === null && ($commit = $this->data('commit')) instanceof Commit && $commit->id === $this->id) { $this->commit = $commit; $this->ancestors = $commit->parent === null ? [] : [$commit->parent]; @@ -747,6 +1147,7 @@ private function showKept(): void $this->takeRelated($this->cached($this->threadPath().'/related') ?? []); $this->keepStagedReplies(); + $this->followThread(); } /** @@ -760,13 +1161,66 @@ private function takeRelated(array $json): void /** * @param array $json */ - private function takeThread(array $json): void + private function takeCommitThread(array $json): void { $thread = CommitThread::fromArray($json); $this->commit = $thread->commit; $this->ancestors = $thread->ancestors; $this->series = $thread->series; + $this->countAncestorReplies(); + $this->followThread(); + } + + /** + * The commits above the commit that show: its parent, or every one once "↑ N earlier commits" opened them. + * + * @return list + */ + private function shownAncestors(): array + { + return $this->earlierShown ? $this->ancestors : array_slice($this->ancestors, -1); + } + + /** + * devnull sends the commits above the commit without their counts, so on their own a commit above never shows + * its "› N replies". Each one showing takes its count from its own page instead: kept from before at once, and + * asked for behind. That also keeps its page, so tapping it moves there with nothing blank. + */ + private function countAncestorReplies(): void + { + foreach ($this->shownAncestors() as $ancestor) { + if ($ancestor->isStaged() || $ancestor->isDeleted()) { + continue; + } + + $id = $ancestor->id; + $path = 'commits/'.rawurlencode($id); + + if (($kept = $this->cached($path)) !== null) { + $this->takeAncestorCount($id, $kept); + } + + // The commit's page landing draws its ancestors again, and they were asked for once already. + if (! in_array($id, $this->countedAncestors, true)) { + $this->countedAncestors[] = $id; + $this->refresh($path, [], fn (array $json) => $this->takeAncestorCount($id, $json), quiet: true); + } + } + } + + /** + * @param array $json + */ + private function takeAncestorCount(string $id, array $json): void + { + $page = CommitThread::fromArray($json)->commit; + + if ($page->id !== $id) { + return; + } + + $this->ancestors = array_map(fn (Commit $ancestor): Commit => $ancestor->id === $id ? $ancestor->withRepliesCount($page->repliesCount) : $ancestor, $this->ancestors); } /** @@ -779,6 +1233,74 @@ private function takeReplies(array $json): void [$this->replies, $this->repliesCursor] = self::withFirstPage($this->replies, $this->repliesCursor, Page::fromArray($json, Commit::fromArray(...))); $this->repliesLoaded = true; $this->keepStagedReplies(); + $this->followThread(); + } + + /** + * Asks for the replies the author's thread needs next, above the commit and below it, each when the one + * before has come (see SelfThread). A page kept from before shows at once and refreshes behind. + */ + private function followThread(): void + { + if ($this->commit === null) { + return; + } + + $waiting = [ + $this->selfThread()->waiting, + SelfThread::above($this->ancestors, $this->commit, $this->repliesOf())[1], + ]; + + foreach (array_unique(array_filter($waiting, fn (?string $id): bool => $id !== null && $id !== $this->id)) as $id) { + $kept = $this->cached('commits/'.rawurlencode($id).'/replies'); + $this->refreshPartReplies($id); + + if ($kept !== null) { + $this->takePartReplies($id, $kept); + } + } + } + + private function refreshPartReplies(string $id): void + { + $this->refresh('commits/'.rawurlencode($id).'/replies', [], fn (array $json) => $this->takePartReplies($id, $json)); + } + + /** + * @param array $json + */ + private function takePartReplies(string $id, array $json): void + { + $page = Page::fromArray($json, Commit::fromArray(...)); + $this->partReplies[$id] = $page->items; + $this->partsWithMore = array_values(array_diff($this->partsWithMore, [$id])); + + if ($page->hasMore()) { + $this->partsWithMore[] = $id; + } + + $this->followThread(); + } + + /** + * The first page of a commit's replies as far as the page has them, or null until they come. The commit's + * own are the ones showing, less any still on their way. + * + * @return Closure(Commit): (list|null) + */ + private function repliesOf(): Closure + { + return fn (Commit $commit): ?array => $commit->id === $this->id + ? ($this->repliesLoaded ? array_values(array_filter($this->replies, fn (Commit $reply): bool => ! $reply->isStaged())) : null) + : ($this->partReplies[$commit->id] ?? null); + } + + /** + * The parts of the author's thread after the commit, as far as they've been read. + */ + private function selfThread(): SelfThread + { + return $this->commit === null ? new SelfThread : SelfThread::below($this->commit, $this->repliesOf(), $this->threadLimit); } /** @@ -815,43 +1337,177 @@ private function threadPath(): string return 'commits/'.rawurlencode($this->id); } - private function loadTombstoneReplies(string $id): void + /** + * Whether the commit is yours, or an organization's you're in, which puts Delete in the nav bar (see Ownership). + */ + public function isOwn(): bool { - $page = $this->attempt(fn ($devnull) => $devnull->replies($id)); - - if ($page !== null) { - $this->tombstoneReplies[$id] = $page->items; - $this->tombstoneCursors[$id] = $page->nextCursor; - } + return $this->commit !== null && $this->ownership()->owns($this->commit); } - public function isOwn(): bool + public function render(): View { - return $this->commit !== null && $this->commit->author->username === $this->me()?->username; + $this->replyRows ??= new RowCache; + $this->replyRows->startFrame(); + $data = $this->viewData(); + + return view('native.commit-detail', [...$data, 'replyRows' => $this->replyRows, 'pageRows' => $this->pageRows($data)]); } - public function render(): View + /** + * What the page's view draws from, besides the component's own properties. + * + * @return array + */ + private function viewData(): array { $earlier = $this->earlierShown ? [] : array_slice($this->ancestors, 0, -1); - $above = $this->earlierShown ? $this->ancestors : array_slice($this->ancestors, -1); + $above = $this->shownAncestors(); $viewer = $this->me(); - $this->replyRows ??= new RowCache; - $this->replyRows->startFrame(); + $thread = $this->selfThread(); + $parts = $thread->parts; + $partsAbove = $this->commit === null ? 0 : SelfThread::above($this->ancestors, $this->commit, $this->repliesOf())[0]; + $lastPart = $thread->hasEnded && $parts !== [] ? end($parts) : null; + $replies = $this->commit === null ? $this->replies : SelfThread::others($this->commit, $this->replies); - return view('native.commit-detail', [ - 'replyRows' => $this->replyRows, + return [ 'myColour' => $this->myColour(), 'viewer' => $viewer, + 'ownership' => $this->ownership(), 'stashed' => app(Stash::class)->names($viewer?->id), 'pasteis' => app(Account::class)->pasteis(), 'rows' => $this->commit === null ? [] : Timeline::thread( - [...$above, $this->commit, ...$this->series], + [...$above, $this->commit, ...$this->series, ...$parts], laneAbove: $earlier === [] ? null : end($earlier)->lane(), ), 'relatedRows' => Timeline::thread($this->related), + 'ancestorThreads' => $this->ancestorThreads($above), 'earlierCount' => $this->commit === null ? 0 : count($earlier), 'earlierLane' => $earlier === [] ? null : end($earlier)->lane(), - 'replyCount' => max($this->commit->repliesCount ?? 0, count($this->replies)), - ]); + 'replyCount' => max($this->commit->repliesCount ?? 0, count($replies)), + 'replies' => $replies, + 'threadParts' => array_map(fn (Commit $part): string => $part->id, $parts), + 'threadMore' => $thread->hasMore, + 'threadPositions' => $this->threadPositions($thread, $partsAbove), + 'lastPart' => $lastPart, + 'lastPartReplies' => $lastPart === null ? [] : array_slice($this->partReplies[$lastPart->id] ?? [], 0, Client::RepliesPerPage), + 'lastPartMore' => $lastPart !== null && (count($this->partReplies[$lastPart->id] ?? []) > Client::RepliesPerPage || in_array($lastPart->id, $this->partsWithMore, true)), + ]; + } + + /** + * The scroll view's rows from the top down to the end of the thread, in the order the view draws them, each one + * child of the scroll view: "↑ N earlier commits", then each commit with what hangs under it, its replies opened + * in place and theirs (see App\Devnull\ThreadRows). The view draws exactly these, so a row's place here is its + * place among the scroll view's children, which auto-scroll-to counts in (see scrollToRow()). What comes after + * the thread, the related commits and the room for the reply bar, the view draws on its own. + * + * @param array $data What viewData() gave. + * @return list, reply: Commit|null}> + */ + private function pageRows(array $data): array + { + $commit = $this->commit; + $rows = $data['rows']; + $replies = $data['replies']; + $lastPart = $data['lastPart']; + $noReplies = $commit !== null && $data['replyCount'] === 0 && $this->repliesLoaded && $this->series === [] && $data['threadParts'] === []; + $relatedBelow = $commit !== null && $this->related !== [] && ! $noReplies; + $pageRows = []; + + if ($data['earlierCount'] > 0) { + $pageRows[] = ['key' => 'earlier-commits', 'partial' => 'native.partials.earlier-commits', 'data' => ['count' => $data['earlierCount'], 'lane' => $data['earlierLane']], 'reply' => null]; + } + + foreach ($rows as $index => $row) { + $last = $index === array_key_last($rows); + $isFocused = $row->commit->id === $commit?->id; + $isLastPart = $lastPart !== null && $row->commit->id === $lastPart->id; + $hasThread = $isFocused && $this->repliesShown && $replies !== []; + $partThread = $isLastPart && $data['lastPartReplies'] !== []; + $aboveThread = $data['ancestorThreads'][$row->commit->id] ?? null; + $aboveOpen = ($aboveThread['rows'] ?? []) !== []; + + $pageRows[] = ['key' => 'commit-'.$row->commit->id, 'partial' => 'native.partials.commit-row', 'reply' => null, 'data' => [ + 'commit' => $row->commit, + 'previousLane' => $row->previousLane, + 'continuesRun' => $row->continuesRun, + 'continuesNext' => $isFocused || $aboveOpen ? ! $last : null, + 'threadBelow' => $hasThread || $partThread || $aboveOpen, + 'repliesBelow' => $partThread, + 'focused' => $isFocused, + 'muted' => ! $isFocused, + 'seriesExpanded' => true, + 'withTail' => ! $last || $data['threadMore'], + 'hairline' => ! ($last && $relatedBelow && ! $data['threadMore']), + 'threadPosition' => $data['threadPositions'][$row->commit->id] ?? null, + 'showsThread' => false, + 'expandable' => $aboveThread !== null, + 'repliesCount' => $aboveThread['count'] ?? null, + ]]; + + if ($isFocused && $this->repliesShown && $replies === [] && ! $this->repliesLoaded && $this->error === null) { + $pageRows[] = ['key' => 'loading-replies', 'partial' => null, 'data' => [], 'reply' => null]; + } + + // The replies, and theirs opened in place under them as deep as they go. A commit above the commit opens + // its replies in place under it too, all but the one on the line down to the commit, which already shows + // (see ancestorThreads()). Replies with another commit's row after them end on the hairline the row above + // them gave up; at the foot of the page they end on none. + array_push($pageRows, ...match (true) { + $aboveThread !== null => $aboveThread['rows'], + $hasThread => ThreadRows::under($commit, [...$this->threads, $commit->id => $replies], array_filter([...$this->threadCursors, $commit->id => $this->repliesCursor]), $this->threadShown, $last ? null : $commit->lane(), opensInPlace: PHP_INT_MAX, onPage: true, morePress: 'loadMoreReplies', hairline: ! $last), + $partThread => ThreadRows::under($lastPart, [...$this->threads, $lastPart->id => $data['lastPartReplies']], array_filter([...$this->threadCursors, $lastPart->id => $data['lastPartMore'] ? 'more' : null]), $this->threadShown, opensInPlace: PHP_INT_MAX, onPage: true, morePress: "openReplies('{$lastPart->id}')"), + default => [], + }); + } + + return $pageRows; + } + + /** + * Brings the row keyed $key into view, animated, under a new token so it goes even when that's the row it went to + * last time. Nothing happens for a row the page doesn't draw. + */ + private function scrollToRow(string $key): void + { + $at = array_search($key, array_column($this->pageRows($this->viewData()), 'key'), true); + + if ($at === false) { + return; + } + + $this->scrollTarget = $at; + $this->scrollRequest++; + $this->scrolledToRow = $key; + } + + /** + * Each commit's place in its author's thread, by id, as the web marks them: the earlier parts above the + * commit, the commit, and the parts after it. None when the commit isn't part of a thread. + * + * A part known to follow the last one read counts, and a thread not read to its end gets the web's "+". + * + * @return array + */ + private function threadPositions(SelfThread $below, int $partsAbove): array + { + if ($this->commit === null) { + return []; + } + + $thread = [...array_slice($this->ancestors, count($this->ancestors) - $partsAbove, $partsAbove), $this->commit, ...$below->parts]; + $size = count($thread) + ($below->hasMore ? 1 : 0); + $positions = []; + + foreach ($thread as $index => $commit) { + $label = SelfThread::position($index + 1, $size, ! $below->hasEnded); + + if ($label !== null) { + $positions[$commit->id] = $label; + } + } + + return $positions; } } diff --git a/app/NativeComponents/Concerns/ExpandsThreads.php b/app/NativeComponents/Concerns/ExpandsThreads.php index 2a5763ce..cbd8830d 100644 --- a/app/NativeComponents/Concerns/ExpandsThreads.php +++ b/app/NativeComponents/Concerns/ExpandsThreads.php @@ -2,52 +2,98 @@ namespace App\NativeComponents\Concerns; +use App\Devnull\Beat; +use App\Devnull\Client; use App\Devnull\Data\Commit; use App\Devnull\Data\Page; +use App\Devnull\SelfThread; +use App\Devnull\ThreadRows; /** - * "› N replies" under a commit in a feed opens its replies in place, the way - * the web's thread toggle does, and "Hide replies" closes them again. One - * level deep: a reply's own replies open its page. + * Replies in a feed stay hidden until you ask for them. "N replies", on its + * own line under a commit's actions, opens its replies in place, oldest first, + * ten at a time (Client::RepliesPerPage), with "Show more" under the last for + * the next ten. Tapped again ("Hide replies") it closes them. devnull's API + * sends 50 replies a page whatever `limit` asks for, so the replies it sent + * are kept and shown ten at a time ($threadShown), and the next page is only + * asked for once they're all showing. * - * The app asks for replies oldest first, five at a time (see - * Client::RepliesPerPage). A thread opened in place shows its first five, - * and "Show more" under them opens the rest on the commit's page, with its - * replies showing. + * A reply opened in place has the same button under its own actions, which + * opens its replies in place too, one step in. In a feed a reply that deep + * opens its replies on its page. On a commit page every reply opens its + * replies in place, as deep as they go (see CommitDetail and + * App\Devnull\ThreadRows). Every thread is kept by the id of the commit or + * reply it answers, so a reply's replies sit in $threads beside its commit's. * - * Under a commit devnull sends with its newest reply, "Show more" opens the - * rest in place, newest first as on the web, so they're turned round here, - * and a thread longer than a page opens the commit's page instead. + * EDGE can't animate a row coming into a list or going out of it, so replies + * fade: a page that opens is drawn see-through ($fadedRows) and drawn again + * as it should be once a Beat comes back, which every row in a thread + * animates to. Closing fades its rows out the same way, then takes them out. * * A thread opened before opens at once from the cache, and refreshes behind. + * + * The reply that carries on a thread its author wrote as replies to + * themselves isn't one of the replies, as on the web: it's the next part of + * that thread, which the commit's "Show thread" opens (see SelfThread). + * devnull's count of the replies already leaves it out. */ trait ExpandsThreads { /** - * The replies of each commit opened in place, by the commit's id. + * The replies opened in place, by the id of the commit or reply they answer. * * @var array> */ public array $threads = []; /** - * Threads opened from a preview with "Show more", which read newest first. + * Where the next page of each open thread starts, by the same id, for those with more. + * + * @var array + */ + public array $threadCursors = []; + + /** + * How many of each open thread's replies show, by the same id. + * + * @var array + */ + public array $threadShown = []; + + /** + * Open threads that have had a page after their first. + * + * @var list + */ + public array $pagedThreads = []; + + /** + * Rows drawn see-through: a page about to fade in, or a thread fading out. + * A reply's row goes by its id, a thread's "Show more" by "more-" and the + * thread's id. + * + * @var list + */ + public array $fadedRows = []; + + /** + * Threads fading out, still drawn until they've faded. * * @var list */ - public array $newestFirst = []; + public array $closingThreads = []; /** - * Threads opened in place with more replies than they show. + * Commits whose replies, opened, showed that their author carried them on as a thread, so they show "Show thread". * * @var list */ - public array $threadsWithMore = []; + public array $threadsContinued = []; public function toggleReplies(string $id): void { if (array_key_exists($id, $this->threads)) { - $this->closeThread($id); + $this->fadeOut($id); return; } @@ -56,37 +102,96 @@ public function toggleReplies(string $id): void if ($kept === null) { $this->loadThread($id); - - return; + } else { + $this->takeThread($id, $kept); + $this->refreshThread($id); } - $this->takeThread($id, $kept); - $this->refreshThread($id); + if (array_key_exists($id, $this->threads)) { + $this->threadShown[$id] = min(Client::RepliesPerPage, count($this->threads[$id])); + $this->fadeIn($this->rowsOf($id, $this->shownReplies($id))); + } } /** - * "Show more" under the newest reply: the rest of the thread, in place. + * "Show more" under an open thread: its next page, under what's showing. */ public function showMoreReplies(string $id): void { - if (array_key_exists($id, $this->threads)) { + if (! $this->isOpenThread($id)) { return; } - if (! in_array($id, $this->newestFirst, true)) { - $this->newestFirst[] = $id; + $shown = $this->threadShown[$id] ?? count($this->threads[$id]); + + if ($shown >= count($this->threads[$id]) && ! $this->loadNextPage($id)) { + return; } - $kept = $this->cached('commits/'.$id.'/replies'); + $this->threadShown[$id] = min($shown + Client::RepliesPerPage, count($this->threads[$id])); + $this->fadeIn($this->rowsOf($id, array_slice($this->threads[$id], $shown, $this->threadShown[$id] - $shown))); + } - if ($kept === null) { - $this->loadThread($id); + /** + * The replies of an open thread that show. + * + * @return list + */ + public function shownReplies(string $id): array + { + return array_slice($this->threads[$id] ?? [], 0, $this->threadShown[$id] ?? null); + } - return; + /** + * Whether an open thread has replies past those that show, kept or still to ask for. + */ + public function hasMoreReplies(string $id): bool + { + return isset($this->threadCursors[$id]) || count($this->shownReplies($id)) < count($this->threads[$id] ?? []); + } + + /** + * Asks for the page after an open thread's replies, under them. False when there's none or it didn't come. + */ + private function loadNextPage(string $id): bool + { + $cursor = $this->threadCursors[$id] ?? null; + + if ($cursor === null) { + return false; } - $this->takeThread($id, $kept); - $this->refreshThread($id); + $page = $this->attempt(fn ($devnull) => $devnull->replies($id, $cursor)); + + if ($page === null || ! $this->isOpenThread($id)) { + return false; + } + + $loaded = array_flip(array_map(fn (Commit $reply): string => $reply->id, $this->threads[$id])); + $added = array_values(array_filter($page->items, fn (Commit $reply): bool => ! isset($loaded[$reply->id]))); + + $this->threads[$id] = [...$this->threads[$id], ...$added]; + $this->keepCursor($id, $page->nextCursor); + $this->pagedThreads = array_values(array_unique([...$this->pagedThreads, $id])); + + return $added !== []; + } + + /** + * Whether a thread shows, and isn't on its way out. + */ + public function isOpenThread(string $id): bool + { + return array_key_exists($id, $this->threads) && ! in_array($id, $this->closingThreads, true); + } + + /** + * Closes every thread at once, for a list that starts again. + */ + protected function forgetThreads(): void + { + $this->threads = $this->threadCursors = $this->threadShown = $this->pagedThreads = []; + $this->fadedRows = $this->closingThreads = []; } /** @@ -103,7 +208,7 @@ private function refreshThread(string $id): void { $this->refresh('commits/'.$id.'/replies', [], function (array $json) use ($id): void { // Closed while it was on its way. - if (array_key_exists($id, $this->threads)) { + if ($this->isOpenThread($id)) { $this->takeThread($id, $json); } }); @@ -118,10 +223,15 @@ private function takeThread(string $id, array $json): void } /** + * A thread's first page, over what it showed. Pages loaded after the first + * stay, past what it holds, with their own cursor. + * * @param Page $page */ private function openThread(string $id, Page $page): void { + $page = $this->withoutContinuation($id, $page); + // A thread whose last reply went closes, so its commit gets its hairline back. if ($page->items === []) { $this->closeThread($id); @@ -129,33 +239,144 @@ private function openThread(string $id, Page $page): void return; } - if (! in_array($id, $this->newestFirst, true)) { - $this->threads[$id] = $page->items; - $this->threadsWithMore = array_values(array_diff($this->threadsWithMore, [$id])); + // With only the first page loaded, the fresh one is the whole thread: a reply that's gone goes. + if (in_array($id, $this->pagedThreads, true)) { + $fresh = array_flip(array_map(fn (Commit $reply): string => $reply->id, $page->items)); + $later = array_values(array_filter(array_slice($this->threads[$id], count($page->items)), fn (Commit $reply): bool => ! isset($fresh[$reply->id]))); + $this->threads[$id] = [...$page->items, ...$later]; + + return; + } + + $this->threads[$id] = $page->items; + $this->keepCursor($id, $page->nextCursor); + } + + private function keepCursor(string $id, ?string $cursor): void + { + unset($this->threadCursors[$id]); + + if ($cursor !== null) { + $this->threadCursors[$id] = $cursor; + } + } - if ($page->hasMore()) { - $this->threadsWithMore[] = $id; + /** + * Takes a thread out, and the replies opened in it. + */ + private function closeThread(string $id): void + { + foreach ($this->threads[$id] ?? [] as $reply) { + if (! $this->drawsOnItsOwn($reply->id)) { + $this->closeThread($reply->id); } + } + unset($this->threads[$id], $this->threadCursors[$id], $this->threadShown[$id]); + $this->pagedThreads = array_values(array_diff($this->pagedThreads, [$id])); + $this->closingThreads = array_values(array_diff($this->closingThreads, [$id])); + } + + /** + * Draws rows see-through for a frame, then as they are, which they fade to. + * + * @param list $rows + */ + private function fadeIn(array $rows): void + { + if ($rows === []) { return; } - // More than a page: the newest replies aren't on it, so the commit's page shows them. - if ($page->hasMore()) { - $this->closeThread($id); - $this->newestFirst = array_values(array_diff($this->newestFirst, [$id])); - $this->openReplies($id); + $this->fadedRows = array_values(array_unique([...$this->fadedRows, ...$rows])); + + $shown = fn () => $this->fadedRows = array_values(array_diff($this->fadedRows, $rows)); + Beat::dispatch(Beat::Step)->finished($shown)->failed($shown); + } + + /** + * Fades a thread's rows out, and the replies opened in it, then takes them out. + */ + private function fadeOut(string $id): void + { + if (in_array($id, $this->closingThreads, true)) { return; } - $this->threads[$id] = array_reverse($page->items); + $rows = $this->rowsInside($id); + $this->closingThreads[] = $id; + $this->fadedRows = array_values(array_unique([...$this->fadedRows, ...$rows])); + + $closed = function () use ($id, $rows): void { + $this->closeThread($id); + $this->fadedRows = array_values(array_diff($this->fadedRows, $rows)); + }; + + Beat::dispatch(ThreadRows::Fade)->finished($closed)->failed($closed); } - private function closeThread(string $id): void + /** + * The page without the reply that carries the commit's thread on, which marks the commit as carried on instead. + * + * @param Page $page + * @return Page + */ + private function withoutContinuation(string $id, Page $page): Page + { + $commit = $this->shownCommit($id); + $next = $commit === null ? null : SelfThread::next($commit, $page->items); + + if ($next === null) { + return $page; + } + + if (! in_array($id, $this->threadsContinued, true)) { + $this->threadsContinued[] = $id; + } + + return new Page(SelfThread::others($commit, $page->items), $page->nextCursor); + } + + /** + * The rows of $replies in a thread, and its "Show more" when it has more. + * + * @param list $replies + * @return list + */ + private function rowsOf(string $id, array $replies): array + { + return [ + ...array_map(fn (Commit $reply): string => $reply->id, $replies), + ...($this->hasMoreReplies($id) ? ['more-'.$id] : []), + ]; + } + + /** + * Every row a thread draws, the replies opened inside it included. + * + * @return list + */ + private function rowsInside(string $id): array + { + $rows = $this->rowsOf($id, $this->shownReplies($id)); + + foreach ($this->shownReplies($id) as $reply) { + if (array_key_exists($reply->id, $this->threads) && ! $this->drawsOnItsOwn($reply->id)) { + $rows = [...$rows, ...$this->rowsInside($reply->id)]; + } + } + + return $rows; + } + + /** + * Whether the screen draws a reply in a row of its own rather than in the thread it's in, so its own replies + * stay open when that thread closes. A commit page draws the commits on its line that way (see CommitDetail). + */ + protected function drawsOnItsOwn(string $id): bool { - unset($this->threads[$id]); - $this->threadsWithMore = array_values(array_diff($this->threadsWithMore, [$id])); + return false; } /** diff --git a/app/NativeComponents/Concerns/HoldsNewCommits.php b/app/NativeComponents/Concerns/HoldsNewCommits.php index 25e2ef68..dd5e42fb 100644 --- a/app/NativeComponents/Concerns/HoldsNewCommits.php +++ b/app/NativeComponents/Concerns/HoldsNewCommits.php @@ -111,7 +111,7 @@ protected function putNewCommitsOnTop(): void $shown = (new FreshPage($this->commits, $this->nextCursor, $this->newCommits, $this->newCommitsReplaceList, $this->newCommitsCursor))->withNewer(); if ($this->newCommitsReplaceList) { - $this->threads = []; + $this->forgetThreads(); $this->replacedList(); } diff --git a/app/NativeComponents/Concerns/OpensCommitSheet.php b/app/NativeComponents/Concerns/OpensCommitSheet.php index 19ac3922..06df216a 100644 --- a/app/NativeComponents/Concerns/OpensCommitSheet.php +++ b/app/NativeComponents/Concerns/OpensCommitSheet.php @@ -9,6 +9,7 @@ use App\Devnull\Data\StashedDraft; use App\Devnull\DraftImages; use App\Devnull\Outbox; +use App\Devnull\PostAs; use App\Devnull\ReportReason; use App\Devnull\ResponseCache; use App\Devnull\SignedRequest; @@ -56,6 +57,11 @@ * web's does: devnull's people for a new commit, a reply or a quote (see * SuggestsMentions). * + * A member of a GitHub organization can post as it instead, from the avatar + * over the field, as the web's Post as menu does, in a new commit, a quote or + * a reply (see PostAs). It starts as you each time, as the web's does, and + * the commit shows staged as the organization while it goes. + * * The sheet keeps its commit while it slides away, so it doesn't empty on the * way down, and lets go of it once iOS says it's gone, however it was closed. */ @@ -104,6 +110,11 @@ trait OpensCommitSheet */ public string $sheetBody = ''; + /** + * The handle of the organization the sheet posts as, or null for you (see PostAs). + */ + public ?string $sheetAuthor = null; + /** * Whether the sheet opened on a stashed draft, which it marks until you empty it or drop it. */ @@ -249,6 +260,15 @@ public function composeInSheet(): void $this->restoreSheetDraft(); } + /** + * Post as, from the sheet's avatar: an organization's handle, or '' for you. + */ + public function postAsInSheet(string $handle = ''): void + { + $this->sheetAuthor = PostAs::author($handle)?->username; + $this->sheetError = null; + } + /** * The web's clock button, in a new commit's composer: it opens "Submit at" under the field, with no time picked, * or closes it, and the commit goes now again. Its photos or its poll go with it either way, as on the web. @@ -335,6 +355,7 @@ public function commitFromSheet(): void 'images' => PendingWrite::imagePayload($this->sheetImages), 'stash' => $stashName, 'composer' => $this->sheetView, + ...PendingWrite::authorPayload(PostAs::author($this->sheetAuthor)), ]); if ($write === null) { @@ -519,18 +540,24 @@ private function openFailedCommit(PendingWrite $write): bool return $this->sheetOpen && $this->sheetStashName() === $write->stashName(); } + /** + * A published commit, or one of yours still waiting for approval, as the web's Quote shows. + */ private function canQuote(Commit $commit): bool { - $viewer = $this->me(); + $ownership = $this->ownership(); - return $viewer !== null && ! $commit->isDeleted() && ! $commit->isStaged() && ($commit->isApproved() || $commit->author->id === $viewer->id); + return $ownership->isSignedIn() && ! $commit->isDeleted() && ! $commit->isStaged() && ($commit->isApproved() || $ownership->owns($commit)); } + /** + * Someone else's published commit: never yours or an organization's you're in, which devnull won't take a report of. + */ private function canReport(Commit $commit): bool { - $viewer = $this->me(); + $ownership = $this->ownership(); - return $viewer !== null && ! $commit->isDeleted() && $commit->isApproved() && $commit->author->id !== $viewer->id; + return $ownership->isSignedIn() && ! $commit->isDeleted() && $commit->isApproved() && ! $ownership->owns($commit); } /** @@ -549,10 +576,11 @@ private function scheduleFromSheet(string $body, string $stashName): void $images = $this->sheetImages; $poll = $this->sheetPollPayload(); + $author = PostAs::author($this->sheetAuthor)?->username; $this->sendingSchedule = true; $this->sheetError = null; - $this->sendInBackground(fn (Client $devnull): SignedRequest => $devnull->signedScheduledCommit($body, $at, $images, $poll), function () use ($me, $stashName, $images): void { + $this->sendInBackground(fn (Client $devnull): SignedRequest => $devnull->signedScheduledCommit($body, $at, $images, $poll, $author), function () use ($me, $stashName, $images): void { $this->sendingSchedule = false; app(ResponseCache::class)->forget(Client::ScheduledCommitsPath); app(Stash::class)->put($me->id, $stashName, new StashedDraft); @@ -560,9 +588,13 @@ private function scheduleFromSheet(string $body, string $stashName): void $this->sheetImages = []; $this->closeCommitSheet(); Toasts::say(self::Scheduled); - }, function (string $message): void { + }, function (string $message) use ($author): void { $this->sendingSchedule = false; $this->sheetError = $message; + + if ($author !== null && method_exists($this, 'refreshUnreadNotifications')) { + $this->refreshUnreadNotifications(); + } }, timeout: $images === [] ? 30 : 120); } @@ -574,6 +606,7 @@ private function forgetCommitSheet(): void $this->reportReason = ''; $this->reportDetails = ''; $this->sheetBody = ''; + $this->sheetAuthor = null; $this->sheetRestored = false; $this->sheetError = null; $this->forgetMention('sheetBody'); @@ -621,9 +654,10 @@ protected function stashSheetDraft(): void } /** - * The sheet starts from its stashed draft, with its photos and poll. A - * commit devnull turned down that was written under it comes back whole, - * and leaves the outbox: from here it's a draft again. + * The sheet starts from its stashed draft, with its photos and poll, as + * you. A commit devnull turned down that was written under it comes back + * whole, as the organization it was to go out as, and leaves the outbox: + * from here it's a draft again. */ private function restoreSheetDraft(): void { @@ -631,6 +665,7 @@ private function restoreSheetDraft(): void $failed = $name === null ? null : app(Outbox::class)->failedDraft($name); if ($failed !== null) { + $this->sheetAuthor = $failed->author(); $this->takeFailedCommit($failed); } diff --git a/app/NativeComponents/Concerns/OpensStargazers.php b/app/NativeComponents/Concerns/OpensStargazers.php index 84024cf4..5ec6fe7f 100644 --- a/app/NativeComponents/Concerns/OpensStargazers.php +++ b/app/NativeComponents/Concerns/OpensStargazers.php @@ -12,6 +12,11 @@ * opening their profile. As on the web, only you see who starred your * commits, and it asks devnull again each time it opens, so stars given in * the meantime show. + * + * An organization's commit is every member's (see Ownership), so its star + * opens the sheet too. The web lists who starred it to any member, but the + * API only to the member who posted it, and to anyone else it says the list + * isn't there. The sheet says so then, rather than offering Try again. */ trait OpensStargazers { @@ -37,6 +42,11 @@ trait OpensStargazers */ public bool $stargazersFailed = false; + /** + * Whether devnull only shows who starred this organization's commit to the member who posted it. + */ + public bool $stargazersForPoster = false; + /** * The load the sheet is waiting for. An answer to an earlier one, sent * before the sheet closed or opened again, is left alone. @@ -47,7 +57,7 @@ public function openStargazers(string $id): void { $commit = $this->shownCommit($id); - if ($commit === null || $commit->isDeleted() || $commit->starsCount === 0 || $commit->author->id !== $this->me()?->id) { + if ($commit === null || $commit->isDeleted() || $commit->starsCount === 0 || ! $this->ownership()->owns($commit)) { return; } @@ -81,10 +91,11 @@ public function loadStargazers(): void $this->stargazers = [...$this->stargazers, ...$page->items]; $this->stargazersCursor = $page->nextCursor; $this->loadingStargazers = false; - }, again: true, quiet: true, failed: function () use ($load): void { + }, again: true, quiet: true, failed: function (int $status = 0) use ($load): void { if ($load === $this->stargazersLoad) { $this->loadingStargazers = false; - $this->stargazersFailed = true; + $this->stargazersForPoster = $status === 404 && $this->shownCommit((string) $this->stargazersOf)?->author->isOrganization === true; + $this->stargazersFailed = ! $this->stargazersForPoster; } }); } @@ -113,5 +124,6 @@ public function stargazersClosed(): void $this->stargazersCursor = null; $this->loadingStargazers = false; $this->stargazersFailed = false; + $this->stargazersForPoster = false; } } diff --git a/app/NativeComponents/Concerns/PopsReactions.php b/app/NativeComponents/Concerns/PopsReactions.php new file mode 100644 index 00000000..3683ebd5 --- /dev/null +++ b/app/NativeComponents/Concerns/PopsReactions.php @@ -0,0 +1,59 @@ + + */ + public array $popping = []; + + protected function pop(string $button): void + { + $this->popping[$button] = Pop::Ready; + + $this->popStep($button, Pop::Ready, Pop::Up, Beat::Step, fn () => $this->popStep($button, Pop::Up, Pop::Down, 150, fn () => $this->popStep($button, Pop::Down, null, 400))); + } + + /** + * Moves $button from $from to $to after $wait milliseconds, unless a tap since started it again. + */ + private function popStep(string $button, string $from, ?string $to, int $wait, ?\Closure $then = null): void + { + $step = function () use ($button, $from, $to, $then): void { + if (($this->popping[$button] ?? null) !== $from) { + return; + } + + if ($to === null) { + unset($this->popping[$button]); + + return; + } + + $this->popping[$button] = $to; + + if ($then !== null) { + $then(); + } + }; + + Beat::dispatch($wait)->finished($step)->failed($step); + } +} diff --git a/app/NativeComponents/Concerns/RefreshesInBackground.php b/app/NativeComponents/Concerns/RefreshesInBackground.php index 600f5c37..732d4f8a 100644 --- a/app/NativeComponents/Concerns/RefreshesInBackground.php +++ b/app/NativeComponents/Concerns/RefreshesInBackground.php @@ -84,12 +84,13 @@ protected function cached(string $path, array $query = []): ?array * 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). + * do then, with devnull's status code, or 0 when it never answered. 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 +104,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 +133,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()); } @@ -155,6 +156,7 @@ protected function refreshUnreadNotifications(): void app(Account::class)->remember($current->user); app(Account::class)->rememberPasteis($current->pasteis()); app(Account::class)->rememberRemotes($current->remotes); + app(Account::class)->rememberOrganizations($current->organizations); $this->takeTerms($current); } @@ -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($status); return; } diff --git a/app/NativeComponents/Concerns/ShowsCommits.php b/app/NativeComponents/Concerns/ShowsCommits.php index 05407927..b58711fa 100644 --- a/app/NativeComponents/Concerns/ShowsCommits.php +++ b/app/NativeComponents/Concerns/ShowsCommits.php @@ -39,12 +39,16 @@ * * A commit can be tapped where a row nests it too: the commit a row quotes, * and the replies a feed shows under a commit. + * + * A commit is yours when you made it or an organization you're in did, as + * devnull decides it (see Ownership). */ trait ShowsCommits { use OpensCommitSheet; use OpensHashtags; use OpensStargazers; + use PopsReactions; use VotesOnPolls; use WritesInBackground; @@ -210,8 +214,8 @@ public function showTime(string $id): void * star goes to devnull from the outbox (see SyncsOutbox). The commit takes * the count devnull sends back, or the star comes back off it if devnull * says no. Like the web, only someone else's published commit can be - * starred, as devnull turns down a star on your own (whose star opens who - * starred it instead, see OpensStargazers). + * starred, as devnull turns down a star on your own or your organization's + * (whose star opens who starred it instead, see OpensStargazers). */ public function toggleStar(string $id): void { @@ -223,12 +227,18 @@ public function toggleStar(string $id): void $this->showStar($id, ! $commit->starred); $this->queueStar($id, ! $commit->starred); + + // The web only pops a star going on. + if (! $commit->starred) { + $this->pop('star-'.$id); + } } /** * Gives the commit a pastel, as the web's pastel button does in pastéis * mode: one per tap, from the ten you get each day, on someone else's - * published commit. Its count goes up and your allowance down at once, + * published commit, never an organization's, which has no pastel at all, + * as on the web. Its count goes up and your allowance down at once, * and the pastel goes from the background, so you can keep tapping. When * devnull turns one down, it comes back, and a toast says why in the web's * words. With none left, the toast says so without asking devnull. @@ -238,7 +248,7 @@ public function givePastel(string $id): void $commit = $this->shownCommit($id); $pasteis = app(Account::class)->pasteis(); - if ($commit === null || $pasteis === null || ! $this->canReactTo($commit)) { + if ($commit === null || $pasteis === null || ! $this->canGivePastel($commit)) { return; } @@ -250,6 +260,7 @@ public function givePastel(string $id): void app(Account::class)->rememberPasteis($pasteis->afterGiving()); $this->changeShownCommit($id, fn (Commit $shown): Commit => $shown->withMorePasteis(1)); + $this->pop('pastel-'.$id); $this->writeInBackground('POST', Client::pastelPath($id), null, fn (array $json) => $this->pastelGiven($id, $json), function (string $message, ?ApiException $exception = null) use ($id): void { $this->pastelTurnedDown($id, $exception); @@ -258,8 +269,9 @@ public function givePastel(string $id): void /** * Pin to profile or Unpin from profile, in your own published commit's - * More menu. Once devnull answers, a toast says so in the web's words, and - * a pin takes the place of the one before (see showPinned()). + * More menu. Not an organization's: devnull pins to its author's profile, + * which only a person has. Once devnull answers, a toast says so in the + * web's words, and a pin takes the place of the one before (see showPinned()). */ public function togglePin(string $id): void { @@ -398,7 +410,8 @@ public function shareCommit(string $id): void } /** - * Delete commit, in your own commit's More menu, asks first, as the web does. + * Delete commit, in the More menu of your own commit or an organization's + * you're in, asks first, as the web does. */ public function confirmDelete(string $id): void { @@ -473,6 +486,11 @@ private function pastelGiven(string $id, array $json): void /** * Deletes your commit on devnull, which takes it out of every list kept on * this phone, then the screen lets it go (see showDeleted()). + * + * An organization's commit is only yours while you're in it. When devnull + * turns its delete down, the screen says why in devnull's words, and asks + * GET /me which organizations you're still in, so the commit stops + * offering Delete if you've left. */ public function deleteCommit(string $id): void { @@ -491,6 +509,8 @@ public function deleteCommit(string $id): void if ($deleted === true) { Toasts::say('rm '.$commit->shortHash.' → /dev/null', short: true); $this->showDeleted($id); + } elseif ($this->error !== null && $commit->author->isOrganization && method_exists($this, 'refreshUnreadNotifications')) { + $this->refreshUnreadNotifications(); } } @@ -533,17 +553,22 @@ private function pastelTurnedDown(string $id, ?ApiException $exception): void private function canReactTo(Commit $commit): bool { - return ! $commit->isDeleted() && $commit->isApproved() && $commit->author->id !== $this->me()?->id; + return ! $commit->isDeleted() && $commit->isApproved() && ! $this->ownership()->owns($commit); + } + + private function canGivePastel(Commit $commit): bool + { + return $this->canReactTo($commit) && ! $commit->author->isOrganization; } 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 && $this->ownership()->isYourOwn($commit); } private function canDelete(Commit $commit): bool { - return ! $commit->isDeleted() && ! $commit->isStaged() && $commit->author->id === $this->me()?->id; + return ! $commit->isDeleted() && ! $commit->isStaged() && $this->ownership()->owns($commit); } /** diff --git a/app/NativeComponents/Concerns/SuggestsMentions.php b/app/NativeComponents/Concerns/SuggestsMentions.php index 9166bcf4..4dd2f05e 100644 --- a/app/NativeComponents/Concerns/SuggestsMentions.php +++ b/app/NativeComponents/Concerns/SuggestsMentions.php @@ -31,8 +31,6 @@ trait SuggestsMentions */ public const string MentionBeforeCaret = '/(?:^|[^\p{L}\p{N}_.\/@-])@([A-Za-z0-9][A-Za-z0-9-]{0,38}|)$/u'; - public const int MaxMentionSuggestions = 6; - /** * The "@handle" the caret is after: the field it's in, where its "@" is, in code points, what follows it, and the * field's text when the caret was there. Null while there's none. @@ -199,7 +197,8 @@ private static function mentionEnd(array $mention, string $text): ?int } /** - * An org's members to suggest for what's typed after the "@", best first. + * An org's members to suggest for what's typed after the "@", best first. All of them: past six the list scrolls + * (see partials/mention-suggestions), as the reply bar's does. * * @param list $members * @return list @@ -236,6 +235,6 @@ private static function rankMembers(array $members, string $query, ?User $viewer usort($ranked, fn (array $a, array $b): int => [$a['tier'], ! $a['followed'], $a['user']->username] <=> [$b['tier'], ! $b['followed'], $b['user']->username]); - return array_column(array_slice($ranked, 0, self::MaxMentionSuggestions), 'user'); + return array_column($ranked, 'user'); } } diff --git a/app/NativeComponents/Concerns/SyncsOutbox.php b/app/NativeComponents/Concerns/SyncsOutbox.php index 52b9a63e..eeb43c7a 100644 --- a/app/NativeComponents/Concerns/SyncsOutbox.php +++ b/app/NativeComponents/Concerns/SyncsOutbox.php @@ -42,11 +42,11 @@ * - A star comes back off the commit, here and in every kept copy, and the * toast offers Retry. * - A commit or a reply leaves the screen, and its draft goes back where you - * wrote it: the text in its stash, and the photos and poll with the failed - * write in the outbox, for the composer to take when it opens. The screen - * that owns the composer opens it again with the lot. Anywhere else the - * toast offers Edit, which opens it here when it can, or the commit the - * reply or quote was for. + * wrote it: the text in its stash, and the photos, poll and organization + * it was to go out as with the failed write in the outbox, for the + * composer to take when it opens. The screen that owns the composer opens + * it again with the lot. Anywhere else the toast offers Edit, which opens + * it here when it can, or the commit the reply or quote was for. * - A message stays in its thread as rejected, with its Retry, and the toast * offers Retry too. Its photos or voice note stay on the phone with it * until it goes. @@ -310,6 +310,7 @@ private function turnDownCommit(PendingWrite $write, string $error, bool $reopen } $this->showCommitTurnedDown($write); + $this->checkOrganizations($write); if ($reopen && $this->reopenFailedCommit($write)) { Toasts::failed($error); @@ -320,6 +321,18 @@ private function turnDownCommit(PendingWrite $write, string $error, bool $reopen Toasts::failed($error, ['label' => 'Edit', 'id' => 'edit', 'data' => ['write' => $write->id]]); } + /** + * A commit that was to go out as an organization asks devnull which ones + * you're still in, since leaving it is a reason devnull turns one down. Its + * composer then posts as you, as the web's does (see PostAs). + */ + private function checkOrganizations(PendingWrite $write): void + { + if ($write->author() !== null && method_exists($this, 'refreshUnreadNotifications')) { + $this->refreshUnreadNotifications(); + } + } + /** * Signs a write as devnull takes it, here on the UI thread. */ @@ -333,8 +346,8 @@ private function signWrite(PendingWrite $write): SignedRequest PendingWrite::Unstar => $devnull->signedWrite('DELETE', $commit), PendingWrite::Message => $devnull->signedMessage((string) $write->target, $write->body(), $write->client_id, $write->replyToId(), $write->images(), $write->voice()), default => $write->images() === [] - ? $devnull->signedCommit($write->body(), $write->parentId(), $write->quotedCommitId(), $write->poll()) - : $devnull->signedCommitWithImages($write->body(), $write->images(), $write->parentId(), $write->quotedCommitId()), + ? $devnull->signedCommit($write->body(), $write->parentId(), $write->quotedCommitId(), $write->poll(), $write->author()) + : $devnull->signedCommitWithImages($write->body(), $write->images(), $write->parentId(), $write->quotedCommitId(), $write->author()), }; } diff --git a/app/NativeComponents/Concerns/TalksToDevnull.php b/app/NativeComponents/Concerns/TalksToDevnull.php index 246acbde..43d3b6a5 100644 --- a/app/NativeComponents/Concerns/TalksToDevnull.php +++ b/app/NativeComponents/Concerns/TalksToDevnull.php @@ -9,6 +9,7 @@ use App\Devnull\Exceptions\KeychainUnavailable; use App\Devnull\Exceptions\Unauthenticated; use App\Devnull\Lane; +use App\Devnull\Ownership; use Closure; /** @@ -62,6 +63,14 @@ protected function me(): ?User return app(Account::class)->user(); } + /** + * Which commits are yours: your own and your organizations' (see Ownership). + */ + protected function ownership(): Ownership + { + return app(Account::class)->ownership(); + } + /** * The theme token for your lane, which the main buttons and the pager tab * underlines are drawn in. diff --git a/app/NativeComponents/Concerns/VotesOnPolls.php b/app/NativeComponents/Concerns/VotesOnPolls.php index 0d6e38a9..d9c78538 100644 --- a/app/NativeComponents/Concerns/VotesOnPolls.php +++ b/app/NativeComponents/Concerns/VotesOnPolls.php @@ -35,7 +35,7 @@ public function choosePollOption(string $id, string $optionId): void { $commit = $this->shownCommit($id); - if ($commit === null || ! $commit->canBeVotedOnBy($this->me()) || ! in_array($optionId, array_map(fn ($option): string => $option->id, $commit->poll?->options ?? []), true)) { + if ($commit === null || ! $commit->canBeVotedOnBy($this->ownership()) || ! in_array($optionId, array_map(fn ($option): string => $option->id, $commit->poll?->options ?? []), true)) { return; } @@ -47,7 +47,7 @@ public function voteOnPoll(string $id): void $commit = $this->shownCommit($id); $choice = $this->pollChoices[$id] ?? null; - if ($commit === null || $choice === null || in_array($id, $this->voting, true) || ! $commit->canBeVotedOnBy($this->me())) { + if ($commit === null || $choice === null || in_array($id, $this->voting, true) || ! $commit->canBeVotedOnBy($this->ownership())) { return; } diff --git a/app/NativeComponents/Log.php b/app/NativeComponents/Log.php index 050e79e2..5d3dc681 100644 --- a/app/NativeComponents/Log.php +++ b/app/NativeComponents/Log.php @@ -6,9 +6,9 @@ use App\Devnull\Data\Commit; use App\Devnull\Data\Page; use App\Devnull\Data\TimelineRow; -use App\Devnull\Data\User; use App\Devnull\Display; use App\Devnull\LastVisit; +use App\Devnull\Ownership; use App\Devnull\ResponseCache; use App\Devnull\RowCache; use App\Devnull\RowWindow; @@ -412,7 +412,7 @@ private function switchTo(string $log): void private function openAfresh(): void { $this->commits = []; - $this->threads = []; + $this->forgetThreads(); $this->latestCommits = []; $this->suggestions = []; $this->rankedSince = null; @@ -959,7 +959,7 @@ private function takeRanking(string $log, array $json, bool $prefetch = true): v $this->commits = $page->items; $this->nextCursor = $page->nextCursor; $this->latestCommits = []; - $this->threads = []; + $this->forgetThreads(); $this->rankedSince = is_string($json['newest_commit_id'] ?? null) ? $json['newest_commit_id'] : null; $this->forgetNewCommits(); $this->keepStagedOnTop(); @@ -1169,6 +1169,7 @@ public function render(): Element private function frame(): View { $viewer = $this->me(); + $ownership = $this->ownership(); foreach (self::Logs as $log) { $this->rowCache($log)->startFrame(); @@ -1184,14 +1185,15 @@ private function frame(): View 'loaded' => $this->loaded, 'lastVisitAt' => $this->lastVisitAt, 'error' => $this->error, - ], $viewer, $this->listKey) - : $this->page($log, $this->previewState($log), $viewer, $this->listKeys[$log] ?? 0), self::Logs); + ], $ownership, $this->listKey) + : $this->page($log, $this->previewState($log), $ownership, $this->listKeys[$log] ?? 0), self::Logs); $showing = $pages[array_search($this->log, self::Logs, true)]; return view('native.log', [ 'myColour' => $this->myColour(), 'viewer' => $viewer, + 'ownership' => $ownership, 'pasteis' => app(Account::class)->pasteis(), 'stashed' => app(Stash::class)->names($viewer?->id), 'newCommitsLabel' => $this->newCommitsLabel(), @@ -1208,7 +1210,7 @@ private function frame(): View * @param array $state * @return array */ - private function page(string $log, array $state, ?User $viewer, int $listKey): array + private function page(string $log, array $state, Ownership $ownership, int $listKey): array { /** @var list $commits */ $commits = $state['commits']; @@ -1216,7 +1218,7 @@ private function page(string $log, array $state, ?User $viewer, int $listKey): a $latestCommits = $state['latestCommits']; // Only the log you're on has who to follow: the others show their first few commits. $showsWhoToFollow = $log === $this->log && $this->showsWhoToFollow(); - $rows = $this->timeline($log, $latestCommits, $commits, $log === self::Ranked ? null : LastVisit::firstSeenId($commits, $state['lastVisitAt'], $viewer?->id), $showsWhoToFollow); + $rows = $this->timeline($log, $latestCommits, $commits, $log === self::Ranked ? null : LastVisit::firstSeenId($commits, $state['lastVisitAt'], $ownership), $showsWhoToFollow); return [ 'log' => $log, diff --git a/app/NativeComponents/Notifications.php b/app/NativeComponents/Notifications.php index 58b7dd7b..f22944de 100644 --- a/app/NativeComponents/Notifications.php +++ b/app/NativeComponents/Notifications.php @@ -270,13 +270,16 @@ public function open(string $id): void $commitId = $notification->commitToOpen(); - $this->openInTab($commitId !== null - ? '/commits/'.$commitId - : '/users/'.$notification->actor->username); + $this->openInTab(match (true) { + $commitId !== null => '/commits/'.$commitId, + $notification->actor->isOrganization => '/organizations/'.rawurlencode($notification->actor->username), + default => '/users/'.$notification->actor->username, + }); } /** - * Names and avatars open their profile independently of the notification's commit. + * Names and avatars open their profile independently of the notification's commit: an organization's page for + * one that replied, quoted or mentioned you. */ public function openActor(string $username): void { @@ -287,7 +290,9 @@ public function openActor(string $username): void foreach ([$notification->actor, ...$notification->actors] as $actor) { if ($username !== '' && $actor->username === $username) { - $this->openInTab('/users/'.$actor->username, ['user' => $actor]); + $actor->isOrganization + ? $this->openInTab('/organizations/'.rawurlencode($actor->username)) + : $this->openInTab('/users/'.$actor->username, ['user' => $actor]); return; } diff --git a/app/NativeComponents/Onboarding.php b/app/NativeComponents/Onboarding.php index 2b3cef0a..77914150 100644 --- a/app/NativeComponents/Onboarding.php +++ b/app/NativeComponents/Onboarding.php @@ -272,6 +272,7 @@ private function signInWithExistingKey(): void app(Account::class)->rememberUnreadNotifications($current->unreadNotificationsCount); app(Account::class)->rememberPasteis($current->pasteis()); app(Account::class)->rememberRemotes($current->remotes); + app(Account::class)->rememberOrganizations($current->organizations); app(Account::class)->rememberTermsToAccept($current->termsToAccept()); $this->keepProfile($current->user); $this->replace($current->termsToAccept() === null ? '/log' : AcceptTerms::Path); diff --git a/app/NativeComponents/Organization.php b/app/NativeComponents/Organization.php index c2f3718c..b680a512 100644 --- a/app/NativeComponents/Organization.php +++ b/app/NativeComponents/Organization.php @@ -254,6 +254,7 @@ public function render(): View 'myColour' => $this->myColour(), 'newCommitsLabel' => $this->newCommitsLabel(), 'viewer' => $this->me(), + 'ownership' => $this->ownership(), 'stashed' => app(Stash::class)->names($this->me()?->id), 'pages' => $pages, 'pageIndex' => array_search($this->tab, self::Tabs, true), @@ -296,7 +297,7 @@ private function switchTo(string $tab): void $this->tab = $tab; $this->listKey = $this->listKeys[$tab] ?? 0; $this->commits = []; - $this->threads = []; + $this->forgetThreads(); $this->nextCursor = null; $this->commitsLoaded = false; $this->commitsFailed = false; diff --git a/app/NativeComponents/Profile.php b/app/NativeComponents/Profile.php index d4c1e690..02a29a98 100644 --- a/app/NativeComponents/Profile.php +++ b/app/NativeComponents/Profile.php @@ -300,7 +300,7 @@ private function switchTo(string $tab): void $this->tab = $tab; $this->listKey = $this->listKeys[$tab] ?? 0; $this->commits = []; - $this->threads = []; + $this->forgetThreads(); $this->nextCursor = null; $this->commitsLoaded = false; $this->forgetNewCommits(); @@ -732,7 +732,7 @@ private function showBlocked(): void private function forgetShownCommits(): void { $this->commits = []; - $this->threads = []; + $this->forgetThreads(); $this->nextCursor = null; $this->forgetNewCommits(); } @@ -899,6 +899,7 @@ public function render(): View 'canRemote' => $this->canRemote(), 'newCommitsLabel' => $this->newCommitsLabel(), 'viewer' => $this->me(), + 'ownership' => $this->ownership(), 'stashed' => app(Stash::class)->names($this->me()?->id), 'pages' => $pages, 'pageIndex' => array_search($this->tab, self::Tabs, true), diff --git a/app/NativeComponents/Search.php b/app/NativeComponents/Search.php index c82ff53d..d05cd1a9 100644 --- a/app/NativeComponents/Search.php +++ b/app/NativeComponents/Search.php @@ -289,6 +289,7 @@ public function render(): View 'searchesCommits' => $this->searchesCommits($term), 'rowCache' => $this->rowCache, 'viewer' => $viewer, + 'ownership' => $this->ownership(), 'stashed' => app(Stash::class)->names($viewer?->id), 'myColour' => $this->myColour(), 'rows' => Timeline::ranked([], $this->commits), diff --git a/app/NativeComponents/Starred.php b/app/NativeComponents/Starred.php index fb69e42c..98fd4021 100644 --- a/app/NativeComponents/Starred.php +++ b/app/NativeComponents/Starred.php @@ -265,6 +265,7 @@ public function render(): View return view('native.starred', [ 'rowCache' => $this->rowCache, 'viewer' => $viewer, + 'ownership' => $this->ownership(), 'stashed' => app(Stash::class)->names($viewer?->id), 'myColour' => $this->myColour(), 'rows' => Timeline::feed($this->commits), diff --git a/app/NativeComponents/ThisDevice.php b/app/NativeComponents/ThisDevice.php index 25c2c46c..dd17af64 100644 --- a/app/NativeComponents/ThisDevice.php +++ b/app/NativeComponents/ThisDevice.php @@ -989,6 +989,7 @@ private function takeMe(array $json): void app(Account::class)->rememberUnreadNotifications($current->unreadNotificationsCount); app(Account::class)->rememberPasteis($current->pasteis()); app(Account::class)->rememberRemotes($current->remotes); + app(Account::class)->rememberOrganizations($current->organizations); app(ResponseCache::class)->meChanged($json); $this->takeTerms($current); } diff --git a/resources/icons/list-tree.svg b/resources/icons/list-tree.svg new file mode 100644 index 00000000..27294fa1 --- /dev/null +++ b/resources/icons/list-tree.svg @@ -0,0 +1 @@ + diff --git a/resources/views/native/commit-detail.blade.php b/resources/views/native/commit-detail.blade.php index b1c2f5f4..f1aaa51f 100644 --- a/resources/views/native/commit-detail.blade.php +++ b/resources/views/native/commit-detail.blade.php @@ -7,8 +7,16 @@ {{-- The stack around the page holds the fade over its foot, just above the reply bar (see partials/composer-fade). --}} - - + {{-- + Each row is a child of the scroll view itself, so it can bring one into view: the commit the page is on, after + tapping another commit in the tree moves the page to it (see CommitDetail::refocus() and $scrollTarget). Every + move animates (auto-scroll-animated), and $scrollRequest as the token makes asking for the same row again scroll + again. With animate-layout the rows the page keeps slide to their new places, and the ones it adds or drops + fade. That needs the scroll view's key, and each row's, to stay the same across the move: the focused commit + is keyed commit-, as the commits above it are. These need NativePHP/mobile-air#736 and + NativePHP/mobile-ui#225; without them the move jumps and a repeat of the same row doesn't scroll. + --}} + @if (! $commit && $error === null) @@ -21,89 +29,46 @@ behind "↑ N earlier commits", since EDGE can't open the page scrolled down to the commit. Opened, the ancestors, the commit and the rest of its series share one rail, so someone replying to themselves shows their avatar once. The replies hang under it on the thread's dashed lines, with the rail ending in a dot - above them, five at a time with "Show more" under the last. A part of a series with more parts after it + above them, ten at a time with "Show more" under the last. A part of a series with more parts after it has its replies right under it, beside the rail running on, and the later parts follow. Everything - around the commit is muted, and still opens its own page. A deleted reply's own replies open in place, - one level in, five at a time too, since a deleted commit has no page. - --}} - @if ($earlierCount > 0) - @include('native.partials.earlier-commits', ['count' => $earlierCount, 'lane' => $earlierLane]) - @endif + around the commit is muted, and the commits above it open their other replies in place under them, as the + commit does, from their "N replies", which starts folded, even after the page moves. Tapping any commit in the tree moves the page to it rather than pushing + another (see CommitDetail::refocus()). Every reply's own replies open in place under + it, ten at a time too, as deep as they go, as on the web: they step in up to the web's depth and line up + under the deepest step past it, saying who they answer (see App\Devnull\ThreadRows). + A thread its author wrote as replies to themselves carries on below the commit, on the same rail, as + the web reads it (see SelfThread): each part wears its place ("2/5"), ten show at a time with "Show + more of this thread" under them, and the replies of the last part hang under it as the commit's do. + --}} {{-- - Related commits start with a full-width line of their own (see partials/related-commits). The last row - above them leaves out its hairline, which runs from the text's edge, so the two don't stack up into a - line and a half. Replies end with no hairline on a commit page, and "No replies yet" keeps the commit's. + The rows down to the end of the thread come from CommitDetail::pageRows(), each one child of the scroll + view, in the order it lists them, so the place it gives a row is the row auto-scroll-to brings into + view: the reply you just sent, say (see CommitDetail::scrollToRow()). A row drawn here and not there + would put every row below it one out. Related commits start with a full-width line of their own (see + partials/related-commits), so the last row above them leaves out its hairline, which runs from the + text's edge, and the two don't stack up into a line and a half. Replies end with no hairline on a + commit page, and "No replies yet" keeps the commit's. --}} - @php($noReplies = $commit && $replyCount === 0 && $repliesLoaded && $series === []) - @php($relatedBelow = $commit && $related !== [] && ! $noReplies) + @php($noReplies = $commit && $replyCount === 0 && $repliesLoaded && $series === [] && $threadParts === []) - @foreach ($rows as $row) - @php($isFocused = $row->commit->id === $commit?->id) - @php($hasThread = $isFocused && $repliesShown && $replies !== []) - @include('native.partials.commit-row', [ - 'commit' => $row->commit, - 'previousLane' => $row->previousLane, - 'continuesRun' => $row->continuesRun, - 'continuesNext' => $isFocused ? ! $loop->last : null, - 'threadBelow' => $hasThread, - 'focused' => $isFocused, - 'muted' => ! $isFocused, - 'seriesExpanded' => true, - 'withTail' => ! $loop->last, - 'hairline' => ! ($loop->last && $relatedBelow), - ]) - @if ($isFocused && $repliesShown && $replies === [] && ! $repliesLoaded && $error === null) + @foreach ($pageRows as $pageRow) + @if ($pageRow['key'] === 'loading-replies') - @endif - @if ($hasThread) - @php($railLane = $loop->last ? null : $commit->lane()) - @foreach ($replies as $index => $threadReply) - @php($nested = $tombstoneReplies[$threadReply->id] ?? []) - @php($nestedMore = ($tombstoneCursors[$threadReply->id] ?? null) !== null) - @php($hasNext = ! $loop->last || $repliesCursor !== null) - @php($replyRow = [ - 'reply' => $threadReply, - 'lane' => $commit->lane(), - 'previousLane' => $index === 0 ? null : $replies[$index - 1]->lane(), - 'hasNext' => $hasNext, - 'railLane' => $railLane, - 'tombstones' => true, - 'muted' => true, - 'thread' => $commit, - 'more' => $loop->last && $nested === [] && $repliesCursor !== null ? 'loadMoreReplies' : null, - 'last' => $loop->last && $nested === [], - ]) - @php($rowScope = array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1])) - @php($replyRows->include('reply-'.$threadReply->id, \App\Devnull\RowInputs::for($threadReply, $rowScope), 'native.partials.thread-reply', $replyRow, $rowScope)) - @foreach ($nested as $nestedIndex => $nestedReply) - @php($nestedRow = [ - 'reply' => $nestedReply, - 'lane' => \App\Devnull\Lane::Rail, - 'previousLane' => $nestedIndex === 0 ? null : $nested[$nestedIndex - 1]->lane(), - 'hasNext' => ! $loop->last || $nestedMore, - 'railLane' => $railLane, - 'indent' => 32, - 'spine' => $hasNext ? $threadReply->lane() : null, - 'muted' => true, - 'thread' => $nestedMore ? $threadReply : $commit, - 'more' => match (true) { - ! $loop->last => null, - $nestedMore => "loadMoreTombstoneReplies('{$threadReply->id}')", - $loop->parent->last && $repliesCursor !== null => 'loadMoreReplies', - default => null, - }, - 'last' => $loop->last && $loop->parent->last, - ]) - @php($rowScope = array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1])) - @php($replyRows->include('reply-'.$nestedReply->id, \App\Devnull\RowInputs::for($nestedReply, $rowScope), 'native.partials.thread-reply', $nestedRow, $rowScope)) - @endforeach - @endforeach + @elseif ($pageRow['reply'] === null) + @include($pageRow['partial'], $pageRow['data']) + @else + @php($rowScope = array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1])) + @php($replyRows->include('reply-'.$pageRow['reply']->id, \App\Devnull\RowInputs::for($pageRow['reply'], $rowScope), $pageRow['partial'], $pageRow['data'], $rowScope)) @endif @endforeach + @if ($threadMore && $threadParts !== []) + @include('native.partials.thread-continues', ['lane' => $rows[array_key_last($rows)]->commit->lane()]) + @endif + @if ($noReplies) No replies yet. @@ -122,7 +87,6 @@ @if ($commit) @endif - @if ($commit && ! \App\Devnull\Display::fadesInBar()) @@ -145,9 +109,12 @@ the draft away whenever there's anything in it, after the web's stash@{0} when the draft came back from the stash, then how long the reply is near the limit. - A "post as" avatar, for people in a GitHub organization, goes at the start of the row as composer-box's - $lead. + A member of a GitHub organization has the web's Post as at the start of the row, as composer-box's $lead: + the avatar of whoever the reply goes out as, lined up with the field's text, which opens the menu (see + PostAs). The send button is then filled with that one's lane. --}} + @php($replyPostingMe = app(\App\Devnull\Account::class)->user()) + @php($replyPostsAs = $replyPostingMe !== null && \App\Devnull\PostAs::offered($replyAuthor)) @if (\App\Devnull\Display::fadesInBar()) @@ -170,12 +137,13 @@ @include('native.partials.composer-photos', ['photos' => $replyImages, 'photoRef' => 'reply-photo']) @endif - + @php($hasDraft = trim($reply) !== '' || $replyImages !== []) @php($photosFull = count($replyImages) >= \App\Devnull\DraftImages::MaxImages) @include('native.partials.composer-box', [ 'ref' => 'reply', 'field' => $replyPreviewing ? 'native.partials.reply-preview' : 'native.partials.reply-field', + 'lead' => $replyPostsAs ? [['native.partials.post-as', ['ref' => 'reply-post-as', 'me' => $replyPostingMe, 'picked' => $replyAuthor, 'method' => 'postAsInReply', 'size' => 28, 'inset' => 'pl-3']]] : [], 'tools' => [ ['ref' => 'reply-add-photos', 'icon' => \App\Icons\Lucide::ImagePlus, 'label' => $photosFull ? 'A reply can have up to 3 photos' : 'Add photos', 'menu' => $photosFull ? null : \App\Devnull\ComposerMenu::photoItems(), 'disabled' => $photosFull], ['ref' => 'reply-preview', 'icon' => \App\Icons\Lucide::Eye, 'label' => $replyPreviewing ? 'Edit' : 'Preview', 'press' => 'toggleReplyPreview', 'active' => $replyPreviewing], @@ -189,6 +157,7 @@ 'label' => 'Reply', 'press' => 'sendReply', 'disabled' => ! \App\Devnull\Data\Draft::canCommit($reply, $replyImages), + 'colour' => $replyPostingMe === null ? $myColour : \App\Devnull\PostAs::colour($replyPostingMe, \App\Devnull\PostAs::author($replyAuthor)), ], ]) diff --git a/resources/views/native/conversation.blade.php b/resources/views/native/conversation.blade.php index e5642545..5191385f 100644 --- a/resources/views/native/conversation.blade.php +++ b/resources/views/native/conversation.blade.php @@ -124,7 +124,7 @@ The box keeps its row, and the row its place among the bar's, so the field inside never moves. A voice note takes the field's place, and the +'s, while it's recorded and waits to be pushed. --}} - + @include('native.partials.composer-box', [ 'ref' => 'message', 'field' => $recorder === null ? 'native.partials.message-field' : 'native.partials.voice-recorder', diff --git a/resources/views/native/partials/commit-actions.blade.php b/resources/views/native/partials/commit-actions.blade.php index 5c86cf74..b8371dc7 100644 --- a/resources/views/native/partials/commit-actions.blade.php +++ b/resources/views/native/partials/commit-actions.blade.php @@ -1,29 +1,33 @@ {{-- The action row under a commit, in the web's order. On the left: the star and its count, in pastéis mode the pastel - and its count, Quote, Reply, and in Commit Blue "› N replies" when the row has no thread under it already. On the - right: More. + and its count, Quote and Reply, each with its label. On the right: More. Under the row, on a line of its own, the + replies button: "› N replies" in Commit Blue, or "Hide replies" with the chevron turned down while they show. Share link, Report and Delete live in More, which opens the platform's own menu (a UIMenu on iOS, a dropdown on Android, see CommitMenu for what's in it). Tapping More only opens the menu. - Reply opens the commit with its reply composer focused. In a feed ($expandable) the replies link opens the thread in - place, as on the web; elsewhere it opens the commit with its replies showing. Like the web, someone else's commit - that isn't approved gets no star or Quote. devnull doesn't let you star your own commits, so on those the star is - the count, which opens who starred it (see OpensStargazers), or a faint star until there are any, as on the web. + Reply opens the commit with its reply composer focused. In a feed ($expandable) the replies button opens the replies + in place, as on the web (see Concerns\ExpandsThreads); elsewhere it opens the commit with its replies showing. Like + the web, someone else's commit that isn't approved gets no star or Quote. devnull doesn't let you star your own + commits, so on those the star is the count, which opens who starred it (see OpensStargazers), or a faint star until + there are any, as on the web. An organization's commit is yours while you're a member of it, whoever posted it + ($ownership, see Ownership). Quote opens a sheet to write the quote in, over the commit being quoted (see commit-sheet). The pastel is the web's: the pastel de nata and how many the commit was given, always, even 0. On someone else's published commit it gives one more per tap; on your own, or one that isn't published, it's just the count. It - only shows in pastéis mode ($pasteis). + only shows in pastéis mode ($pasteis), and never on an organization's commit, which takes no pastéis, as the web + leaves it off. A star you give and a pastel pop as they do on the web (see PopsReactions). A commit with a quote or a reply you started and didn't send marks that button, as the web does with stash@{0} - beside its label. That doesn't fit the row, so here it's a dot after the icon or label, inside the button's 44pt. + beside its label. That doesn't fit the row, so here it's a dot after the label, inside the button. The screen passes the names of the drafts it has kept ($stashed, see App\Devnull\Stash). - Each action is at least 44pt wide and 36pt tall to tap, as Apple asks, with the row pulled in by the extra height so - the commit keeps its rhythm. EDGE makes a pressable's whole box tappable, so the box is the target. Off the log, - "› N replies" sits beside Reply, and both won't fit on a phone with their labels, so Reply is just its icon there. + Each action is at least 44pt wide and 36pt tall to tap, as Apple asks. The row has no negative vertical margins: + Android draws a negative margin as an offset and keeps the space, so the row sat 6pt lower there than on iOS, and + with it everything placed against it. $endDot draws the end of the commit's rail, a lane dot, inside the row at the + rail's x, so it's level with the actions whatever is above or below them (see commit-row-content). A button is the pressable itself, laid out as a row, with no row inside it, since a list builds and measures every node of a row as it scrolls in. More keeps its column: a pressable with a menu draws its content as the menu's @@ -32,34 +36,43 @@ A commit page opens its replies under its commit in place: it passes what the toggle presses ($repliesToggle), whether they're open ($repliesOpen) and how many there are ($repliesCount). $compact draws the row smaller, for the commits around the one a page is about. + + Wherever the button opens the replies in place, in a feed or on a commit page, its chevron turns down while they + show and back as they close, over the time a feed's thread takes to fade (ThreadRows::Fade). The chevron carries + the animation shut as well as open: iOS only animates a change on a node that already had it. --}} @php($withReply ??= true) @php($withReplies ??= true) @php($withQuote ??= true) @php($compact ??= false) @php($expandable ??= isset($threads)) -@php($isOpen = $repliesOpen ?? ($expandable && array_key_exists($commit->id, $threads))) +@php($isOpen = $repliesOpen ?? ($expandable && array_key_exists($commit->id, $threads) && ! in_array($commit->id, $closingThreads ?? [], true))) @php($repliesPress = $repliesToggle ?? ($expandable ? "toggleReplies('{$commit->id}')" : "openReplies('{$commit->id}')")) +@php($opensInPlace = $expandable || isset($repliesToggle)) @php($repliesCount ??= $commit->repliesCount) @php($iconSize = $compact ? 14 : 16) @php($labelSize = $compact ? 'text-xs' : 'text-[13px]') @php($viewer ??= app(\App\Devnull\Account::class)->user()) +@php($ownership ??= app(\App\Devnull\Account::class)->ownership()) @php($stashed ??= []) @php($hasQuoteStash = in_array('quote-'.$commit->id, $stashed, true)) @php($hasReplyStash = in_array('reply-'.$commit->id, $stashed, true)) -@php($isOwn = $commit->author->id === $viewer?->id) +@php($isOwn = $ownership->owns($commit)) @php($canQuote = $commit->isApproved() || $isOwn) -@php($hasThread = $expandable && $commit->replyPreview !== null) -@php($showsReplies = $withReplies && ! $hasThread && $repliesCount > 0) +@php($showsReplies = $withReplies && ! $commit->isDeleted() && $repliesCount > 0) +@php($endDot ??= null) +@php($starPop = \App\Devnull\Pop::transform($popping['star-'.$commit->id] ?? null, 'star')) +@php($pastelPop = \App\Devnull\Pop::transform($popping['pastel-'.$commit->id] ?? null, 'pastel')) @php($pasteis ??= app(\App\Devnull\Account::class)->pasteis()) -@php($canGivePastel = $pasteis !== null && $viewer !== null && ! $isOwn && $commit->isApproved()) +@php($showsPastel = $pasteis !== null && ! $commit->author->isOrganization) +@php($canGivePastel = $showsPastel && $viewer !== null && ! $isOwn && $commit->isApproved()) @php($pastelLabel = \App\Devnull\Display::count($commit->pasteisCount, 'pastel', 'pastéis')) @php($pastelSize = $compact ? 18 : 20) @php($starLabel = ($commit->starred ? 'Unstar commit' : 'Star commit').($commit->starsCount > 0 ? ', '.\App\Devnull\Display::count($commit->starsCount, 'star', 'stars') : '')) - + @if ($commit->isApproved() && ! $isOwn && $viewer !== null && ! $commit->isDeleted()) - + @if ($commit->starsCount > 0) {{ \App\Devnull\Display::compactCount($commit->starsCount) }} @endif @@ -77,10 +90,10 @@ @if ($canGivePastel) - + {{ \App\Devnull\Display::compactCount($commit->pasteisCount) }} - @elseif ($pasteis !== null) + @elseif ($showsPastel) {{ \App\Devnull\Display::compactCount($commit->pasteisCount) }} @@ -88,43 +101,42 @@ @endif @if ($withQuote && $canQuote) - + + Quote @if ($hasQuoteStash) - + @endif @endif @if ($withReply) - + - @unless ($showsReplies) - Reply - @endunless + Reply @if ($hasReplyStash) @endif @endif - @if ($showsReplies) - - @if ($isOpen) - - Hide replies - @else - - {{ \App\Devnull\Display::count($repliesCount, 'reply', 'replies') }} - @endif - - @endif - - + + + @if ($endDot !== null) + {{-- The end of the rail, at its x: the row starts 8pt into the 64pt gutter's edge, and the dot is 18pt round. --}} + @include('native.partials.rail-node', ['lane' => $endDot, 'nodeRef' => 'end-dot', 'position' => 'absolute top-[9] -left-[33]']) + @endif + +@if ($showsReplies) + + + {{ $isOpen ? 'Hide replies' : \App\Devnull\Display::count($repliesCount, 'reply', 'replies') }} + +@endif diff --git a/resources/views/native/partials/commit-poll.blade.php b/resources/views/native/partials/commit-poll.blade.php index 9df5bc5a..ea6028ae 100644 --- a/resources/views/native/partials/commit-poll.blade.php +++ b/resources/views/native/partials/commit-poll.blade.php @@ -4,14 +4,14 @@ its percentage in mono on the right, and "4 votes · 3h left" under them all. Without results, the options are plain boxes over the time left. - On someone else's published commit whose poll is open and has no vote of yours yet, you vote as on the web: tap an - option to pick it, its box in Commit Blue on Blue Wash with its radio filled, then Vote, beside the time left, - since votes are final (see VotesOnPolls). Vote spins while it goes, and the poll then shows its results. $static - is the quote card's copy, which never votes. + On a published commit that isn't yours or your organization's, whose poll is open and has no vote of yours yet, you + vote as on the web: tap an option to pick it, its box in Commit Blue on Blue Wash with its radio filled, then Vote, + beside the time left, since votes are final (see VotesOnPolls). Vote spins while it goes, and the poll then shows + its results. $static is the quote card's copy, which never votes. --}} @php($poll = $commit->poll) @php($static ??= false) -@php($canVote = ! $static && $commit->canBeVotedOnBy($viewer ?? app(\App\Devnull\Account::class)->user())) +@php($canVote = ! $static && $commit->canBeVotedOnBy($ownership ?? app(\App\Devnull\Account::class)->ownership())) @php($choice = $pollChoices[$commit->id] ?? null) @php($isVoting = in_array($commit->id, $voting ?? [], true)) diff --git a/resources/views/native/partials/commit-row-content.blade.php b/resources/views/native/partials/commit-row-content.blade.php index 553ac21e..382e6c66 100644 --- a/resources/views/native/partials/commit-row-content.blade.php +++ b/resources/views/native/partials/commit-row-content.blade.php @@ -4,19 +4,33 @@ after it links to them, as the web's "2 more commits in this series" does. $withTail runs the rail on below. In a feed, $continuesNext says whether the author's run goes on in the next row. The rail then runs on, or for a - commit alone in its run ends in a dot of its own, and with replies under the row ($threadBelow) a dashed line in - the lane carries on down to them, as the web draws it. + commit alone in its run ends in a dot of its own, level with the action row, and with replies open under the row + ($threadBelow) a dashed line in the lane carries on down from the dot to them, as the web draws it. The dot is drawn + inside the action row (see commit-actions), so it's level with it whatever the body, images or replies line above + and below. Only the rail's lines are placed from the row's bottom, to meet it, and every height under the action + row is fixed here, so they meet it on both platforms. On a commit page the commit it's about ($focused) is the main thing: a larger name and body in full ink, its time, - 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: + which tapped says when in your timezone, its hash at the top right, 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 in a thread its author wrote as replies to themselves wears its place in it ($threadPosition, "2/5"), and + one its author carried on that way links to that thread ($showsThread), as the web's "Show thread" does (see + SelfThread). $repliesBelow says its replies show under the row, so its action row leaves out "› N replies". + 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). A list builds and measures every node of a row as it scrolls in, so the content is one column: the rail's 64pt gutter is its left margin, and the hairline under it is its bottom border. A border draws inside the box, so the bottom padding takes the hairline's 1pt to keep the row as tall as it was. + + In a feed the row is as tall with its replies open as shut. The replies are rows of their own, and when a row + whose top is off screen changes height, an iOS list can hold the row below it still and move this one instead, + so its photo jumped by the difference. With the replies open the row keeps its bottom padding, the hairline's 1pt + included, and only the hairline goes. The first reply takes that padding off its own top (see ThreadRows), so the + thread looks the same. A commit page's scroll view holds its top, so there the commit it's about ($focused) lets + its replies come straight up under it. --}} @php($author = $commit->author) @php($muted ??= false) @@ -25,12 +39,19 @@ @php($withTail ??= ! $focused) @php($continuesNext ??= null) @php($threadBelow ??= false) +@php($threadPosition ??= null) +@php($showsThread ??= $commit->continuationId !== null) +@php($repliesBelow ??= false) @php($inFeed = $continuesNext !== null) @php($endsWithDot = $inFeed && ! $continuesRun && ! $continuesNext) @php($laterParts = $seriesExpanded ? 0 : $commit->laterSeriesParts()) @php($hasHairline = $hairline && ! $threadBelow) @php($inset = $focused ? 16 : 12) -@php($padding = 'pt-['.$inset.']'.($threadBelow ? '' : ' pb-['.($hasHairline ? $inset + 1 : $inset).']')) +{{-- The action row's 36pt reaches 6pt into the inset below it, as its buttons are taller than their icons. --}} +@php($bottom = $threadBelow && $focused ? 0 : $inset - 6 + ($hairline ? 1 : 0)) +@php($padding = 'pt-['.$inset.']'.($bottom > 0 ? ' pb-['.$bottom.']' : '')) +@php($repliesLine = ! $commit->isStaged() && ! $commit->isDeleted() && ($focused || ! $repliesBelow) && ($focused ? ($replyCount ?? $commit->repliesCount) : $commit->repliesCount) > 0 ? 40 : 0) +@php($dotInActions = $endsWithDot && ! $commit->isStaged()) @php($metaSize = $muted ? 'text-xs' : 'text-[13px]') @@ -48,9 +69,17 @@ @if ($commit->isSeriesPart()) @include('native.partials.series-position') @endif + @if ($threadPosition !== null) + @include('native.partials.thread-position') + @endif @unless ($commit->isApproved()) @include('native.partials.status-chip', ['status' => $commit->status]) @endunless + @if ($focused) + {{-- Its short hash, at the top right of the row, as the web has it at the right of the page's header. --}} + + {{ $commit->shortHash }} + @endif @if ($commit->parent?->isDeleted()) @@ -75,8 +104,8 @@ @endif - @if ($focused) - {{ $commit->shortHash }} + @if ($showsThread && ! $focused) + @include('native.partials.show-thread') @endif @if ($commit->isStaged()) @@ -86,9 +115,10 @@ 'repliesToggle' => 'toggleReplies', 'repliesOpen' => $repliesShown ?? false, 'repliesCount' => $replyCount ?? $commit->repliesCount, + 'endDot' => $dotInActions ? $commit->lane() : null, ]) @else - @include('native.partials.commit-actions', ['compact' => $muted]) + @include('native.partials.commit-actions', ['compact' => $muted, 'withReplies' => ! $repliesBelow, 'endDot' => $dotInActions ? $commit->lane() : null]) @endif @@ -97,6 +127,10 @@ 'lane' => $commit->lane(), 'tail' => ($inFeed ? $continuesNext || ! $continuesRun : $withTail) ? $commit->lane() : null, 'endsWithDot' => $endsWithDot, + // The middle of the action row, where the rail's end dot is, above the row's bottom: its padding, the replies + // line under the actions (4pt gap and 36pt) and half the row. + 'endDotAt' => $bottom + $repliesLine + 18, + 'dotInActions' => $dotInActions, 'replyTail' => $threadBelow && ! ($inFeed && $continuesNext), 'node' => $continuesRun ? 'dot' : 'avatar', 'avatarSize' => $muted ? 36 : 48, diff --git a/resources/views/native/partials/commit-row.blade.php b/resources/views/native/partials/commit-row.blade.php index 209350f2..528a20d1 100644 --- a/resources/views/native/partials/commit-row.blade.php +++ b/resources/views/native/partials/commit-row.blade.php @@ -13,7 +13,7 @@ @if ($commit->isDeleted()) @include('native.partials.commit-tombstone') @elseif ($focused) - + @include('native.partials.commit-row-content') @else diff --git a/resources/views/native/partials/commit-sheet.blade.php b/resources/views/native/partials/commit-sheet.blade.php index d30a12ee..1af931c2 100644 --- a/resources/views/native/partials/commit-sheet.blade.php +++ b/resources/views/native/partials/commit-sheet.blade.php @@ -19,6 +19,10 @@ field, its placeholder in it, and Open issue (the same check) in Commit's place in the bar. Opened, the sheet says so, with View issue and Done. + A member of a GitHub organization sees who the commit goes out as above the field, as the web's composer shows its + avatar: theirs, or the organization's, with its name and handle. A tap opens Post as (see PostAs). Commit is then + filled with the organization's lane. An issue always comes from you, so it hides there. + A commit's page opens its reply here too, as "Reply to @handle", with the commit being answered as a static card over the field, for the photos and the preview its reply bar has no room for. Commit says Reply there. @@ -51,6 +55,8 @@ @php($quoting = $sheetView === 'quote') @php($replying = $sheetView === 'reply') @php($issueCommand = $sheetIssue === null ? null : \App\Devnull\IssueCommand::from($sheetIssue)) + @php($postingMe = app(\App\Devnull\Account::class)->user()) + @php($postsAs = $postingMe !== null && ! $issueCommand && \App\Devnull\PostAs::offered($sheetAuthor)) @php($canCommit = \App\Devnull\Data\Draft::canCommit($sheetBody, $sheetImages, $replying ? null : $sheetPoll)) @@ -60,12 +66,18 @@ @include('native.partials.sheet-bar-button', ['ref' => 'sheet-open-issue', 'icon' => \App\Icons\Lucide::Check, 'label' => 'Open issue', 'main' => true, 'loading' => $openingIssue, 'press' => $openingIssue || ! \App\Devnull\IssueCommand::fits($sheetBody) ? null : 'openIssueFromSheet']) @else @php($schedulingThis = $scheduling && $sheetView === 'compose') - @include('native.partials.sheet-bar-button', ['ref' => 'sheet-commit', 'icon' => \App\Icons\Lucide::Check, 'label' => match (true) { $schedulingThis => 'Schedule commit', $replying => 'Reply', default => 'Commit' }, 'main' => true, 'loading' => $sendingSchedule, 'press' => $sendingSchedule || ! $canCommit || ($schedulingThis && ! $hasScheduledTime) ? null : 'commitFromSheet']) + @include('native.partials.sheet-bar-button', ['ref' => 'sheet-commit', 'icon' => \App\Icons\Lucide::Check, 'label' => match (true) { $schedulingThis => 'Schedule commit', $replying => 'Reply', default => 'Commit' }, 'main' => true, 'mainColour' => $postingMe === null ? $myColour : \App\Devnull\PostAs::colour($postingMe, \App\Devnull\PostAs::author($sheetAuthor)), 'loading' => $sendingSchedule, 'press' => $sendingSchedule || ! $canCommit || ($schedulingThis && ! $hasScheduledTime) ? null : 'commitFromSheet']) @endif + @if ($postsAs) + + @include('native.partials.post-as', ['ref' => 'sheet-post-as', 'me' => $postingMe, 'picked' => $sheetAuthor, 'method' => 'postAsInSheet', 'size' => 36, 'withName' => true]) + + @endif + @if ($sheetError) {{ $sheetError }} @endif diff --git a/resources/views/native/partials/composer-box.blade.php b/resources/views/native/partials/composer-box.blade.php index 5cb53133..c706afc0 100644 --- a/resources/views/native/partials/composer-box.blade.php +++ b/resources/views/native/partials/composer-box.blade.php @@ -11,12 +11,13 @@ row, ahead of the tools, and for the end, left of the send button, such as the count of a long draft. $send is send-button's: its ref, label, method, and whether it can send yet. - The field's text lines up with the tools' icons under it. + The field's text lines up with the tools' icons under it. The field sits a little nearer the fade above it than + the row under it: the row around the box has no top padding, and the field row leaves 8pt under the field. --}} @php($lead ??= []) @php($trail ??= []) - + @include($field) diff --git a/resources/views/native/partials/dashed-ring.blade.php b/resources/views/native/partials/dashed-ring.blade.php index 97d43a19..67e9bf36 100644 --- a/resources/views/native/partials/dashed-ring.blade.php +++ b/resources/views/native/partials/dashed-ring.blade.php @@ -1,4 +1,6 @@ {{-- - A 2pt ring in dashes of $lane's colour, as the web's `border-2 border-dashed rounded-full`, $size across. + A 2pt ring in dashes of $lane's colour, as the web's `border-2 border-dashed rounded-full`, $size across. $rounded + makes it a rounded square instead, around an organization. --}} - +@php($rounded ??= 'rounded-full') + diff --git a/resources/views/native/partials/feed.blade.php b/resources/views/native/partials/feed.blade.php index c85258e0..5a9ebb31 100644 --- a/resources/views/native/partials/feed.blade.php +++ b/resources/views/native/partials/feed.blade.php @@ -1,9 +1,10 @@ {{-- A feed's rows from App\Devnull\Timeline: day markers, the last-visit marker, who to follow ($whoToFollow, see - partials/who-to-follow) and commits on the rail. Under a commit hangs its thread, inside its row's hairline, as on - the web: the newest reply devnull previews, with "Show more" when there are others, or the replies opened in place, - with "Show more" to the commit's page when there are more than they show. The commit's rail runs on past them when - its author's run goes on below. + partials/who-to-follow) and commits on the rail. A commit's replies stay hidden until its replies button opens them + in place (see Concerns\ExpandsThreads). Then its thread hangs under it, inside its row's hairline, a page at a time + with "Show more" under the last, and a reply's own replies opened under it one step in (see App\Devnull\ThreadRows). + The commit's rail runs on past them when its author's run goes on below. A commit its author carried on in replies to + themselves shows "Show thread". Given a $rowCache (see App\Devnull\RowCache), commits and replies that haven't changed since the last frame are drawn from it rather than built again. Given a $rowWindow (see App\Devnull\RowWindow), rows far from the screen @@ -42,20 +43,15 @@ @else @php $feedCommit = $row->commit; - $opened = $threads[$feedCommit->id] ?? null; - $threadReplies = $opened ?? ($feedCommit->isDeleted() ? [] : $feedCommit->replyPreview?->replies ?? []); - $feedDraws = $rowWindow?->place($feedIndex, 1 + count($threadReplies)) ?? true; - $hasMoreReplies = $opened === null - ? ! $feedCommit->isDeleted() && ($feedCommit->replyPreview?->hasMore ?? false) - : in_array($feedCommit->id, $threadsWithMore ?? [], true); - $morePress = $opened === null ? "showMoreReplies('{$feedCommit->id}')" : "openReplies('{$feedCommit->id}')"; - $railLane = $row->continuesNext ? $feedCommit->lane() : null; + $threadRows = $feedCommit->isDeleted() ? [] : \App\Devnull\ThreadRows::under($feedCommit, $threads ?? [], $threadCursors ?? [], $threadShown ?? [], $row->continuesNext ? $feedCommit->lane() : null); + $feedDraws = $rowWindow?->place($feedIndex, 1 + count($threadRows)) ?? true; $commitRow = [ 'commit' => $feedCommit, 'previousLane' => $row->previousLane, 'continuesRun' => $row->continuesRun, 'continuesNext' => $row->continuesNext, - 'threadBelow' => $threadReplies !== [], + 'threadBelow' => $threadRows !== [], + 'showsThread' => $feedCommit->continuationId !== null || in_array($feedCommit->id, $threadsContinued ?? [], true), ]; @endphp @if (! $feedDraws) @@ -70,29 +66,17 @@ $rowCache->include('commit-'.$feedCommit->id, \App\Devnull\RowInputs::for($feedCommit, $rowScope), 'native.partials.commit-row', $commitRow, $rowScope); @endphp @endif - @foreach ($threadReplies as $index => $threadReply) - @php - $replyRow = [ - 'reply' => $threadReply, - 'lane' => $feedCommit->lane(), - 'previousLane' => $index === 0 ? null : $threadReplies[$index - 1]->lane(), - 'hasNext' => ! $loop->last || $hasMoreReplies, - 'railLane' => $railLane, - 'thread' => $feedCommit, - 'more' => $loop->last && $hasMoreReplies ? $morePress : null, - 'last' => $loop->last, - ]; - @endphp + @foreach ($threadRows as $threadRow) @if (! $feedDraws) @php - $rowWindow->placeholder('thread-reply-'.$threadReply->id); + $rowWindow->placeholder($threadRow['key']); @endphp - @elseif ($rowCache === null) - @include('native.partials.thread-reply', $replyRow) + @elseif ($rowCache === null || $threadRow['reply'] === null) + @include($threadRow['partial'], $threadRow['data']) @else @php $rowScope = array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]); - $rowCache->include('reply-'.$threadReply->id, \App\Devnull\RowInputs::for($threadReply, $rowScope), 'native.partials.thread-reply', $replyRow, $rowScope); + $rowCache->include('reply-'.$threadRow['reply']->id, \App\Devnull\RowInputs::for($threadRow['reply'], $rowScope), $threadRow['partial'], $threadRow['data'], $rowScope); @endphp @endif @endforeach diff --git a/resources/views/native/partials/mention-suggestions.blade.php b/resources/views/native/partials/mention-suggestions.blade.php index 1f0a4e29..93dbf174 100644 --- a/resources/views/native/partials/mention-suggestions.blade.php +++ b/resources/views/native/partials/mention-suggestions.blade.php @@ -4,15 +4,27 @@ colour. $heading, when there is one, heads them: Members for a bare "@" in an org thread. A tap puts "@handle " in the field in place of what was typed. Above a bar's field on iOS they sit on glass of their own, like the reply strip; $class says otherwise. + + At most six rows show (Display::MentionRowsShown). Past that the rows scroll inside a list that tall, so the list + never pushes the field and the bar's buttons down under the keyboard. Fewer, and it's only as tall as its rows. + Each row is then exactly a row's height (Display::MentionRowHeight), so six fill the list. The rows sit inside the + list's own column, so the slot around it, and the field's row beside that, stay where they are. A caller that + scrolls the list itself (the composer sheet sizes and scrolls its own) passes 'scrolls' => false, and every row is + drawn as tall as it is, with no scroll view inside. --}} @if (($mention['field'] ?? null) === $field && ($mentionPeople !== [] || $mentionOrganizations !== [])) @if ($heading ?? null) {{ $heading }} @endif - @foreach ([...array_map(fn ($user) => [$user, true], $mentionPeople), ...array_map(fn ($user) => [$user, false], $mentionOrganizations)] as [$user, $person]) + @php($mentionRows = [...array_map(fn ($user) => [$user, true], $mentionPeople), ...array_map(fn ($user) => [$user, false], $mentionOrganizations)]) + @php($mentionScrolls = ($scrolls ?? true) && count($mentionRows) > \App\Devnull\Display::MentionRowsShown) + @if ($mentionScrolls) + + @endif + @foreach ($mentionRows as [$user, $person]) - + @include('native.partials.avatar', ['user' => $user, 'size' => 28]) {{ $user->name }} @@ -26,5 +38,8 @@ @endforeach + @if ($mentionScrolls) + + @endif @endif diff --git a/resources/views/native/partials/post-as.blade.php b/resources/views/native/partials/post-as.blade.php new file mode 100644 index 00000000..b22f86a8 --- /dev/null +++ b/resources/views/native/partials/post-as.blade.php @@ -0,0 +1,30 @@ +{{-- + Who a composer posts as (see PostAs): the avatar of whoever it is now, round for you and a rounded square for an + organization, with a small chevron on its corner, as the web's Post as button draws it. A tap opens the menu of you + and your organizations, which calls $method with the handle picked, or '' for you. With $withName, their name and + handle follow the avatar, for the sheet, which has the room. $inset pads it inside its tap target, so a bar can line + the avatar up with its field. + + $picked is the handle the composer holds. An organization you've left since posts as you, so your avatar shows. +--}} +@php($size ??= 32) +@php($withName ??= false) +@php($inset ??= '') +@php($author = \App\Devnull\PostAs::author($picked)) +@php($identity = $author ?? $me) + + + + @include('native.partials.avatar', ['user' => $identity, 'size' => $size]) + + + + + @if ($withName) + + {{ $identity->name }} + {{ $identity->handle() }} + + @endif + + diff --git a/resources/views/native/partials/rail-avatar.blade.php b/resources/views/native/partials/rail-avatar.blade.php index e5055af0..d000bc54 100644 --- a/resources/views/native/partials/rail-avatar.blade.php +++ b/resources/views/native/partials/rail-avatar.blade.php @@ -13,8 +13,8 @@ @php($position ??= '') @php($live = ! $staged && $user->isLive()) @if ($staged) - - @include('native.partials.dashed-ring', ['size' => 48, 'lane' => $lane]) + + @include('native.partials.dashed-ring', ['size' => 48, 'lane' => $lane, 'rounded' => $user->isOrganization ? 'rounded-lg' : 'rounded-full']) @include('native.partials.avatar', ['user' => $user, 'size' => 40]) diff --git a/resources/views/native/partials/rail.blade.php b/resources/views/native/partials/rail.blade.php index f64abf05..3af56dbd 100644 --- a/resources/views/native/partials/rail.blade.php +++ b/resources/views/native/partials/rail.blade.php @@ -10,7 +10,8 @@ 'tombstone' a dashed Rail Gray ring where a deleted commit's avatar was 'skeleton' a wash disc, for a row still loading null no node; a $previous segment then runs the full height of the row - $endsWithDot stops the $tail 20pt above the bottom at a lane dot, as the web ends a commit that's alone in its run. + $endsWithDot stops the $tail at a lane dot $endDotAt above the bottom (its middle), as the web ends a commit that's + alone in its run. A commit row draws that dot in its action row ($dotInActions), so the rail only runs to it. $replyTail runs a dashed line in the lane on down from the node, or from that dot, to the replies under the row. $avatarSize draws the avatar's ring smaller than its 48pt, centred in the same place. --}} @@ -23,7 +24,8 @@ @php($replyTail ??= false) @php($avatarSize ??= 48) @php($center = 32) -@php($endDot = 20) +@php($endDotAt ??= 20) +@php($dotInActions ??= false) @php($segment = fn (int|string $lane): string => 'bg-theme-'.\App\Devnull\Lane::token($lane)) @if ($node === null) @@ -41,18 +43,19 @@ @endforeach @elseif ($tail !== null) - {{-- `bottom-0`, never `bottom-[0]`: EDGE reads an arbitrary zero inset as no inset, which leaves the tail no height. --}} - + {{-- `bottom-0`, never `bottom-[0]`: EDGE reads an arbitrary zero inset as no inset, which leaves the tail no height. + Ending at a dot, it stops 2pt into the dot's ring, which is in the same lane, so no gap shows. --}} + @endif @if ($replyTail && $endsWithDot) - @include('native.partials.dashed-line', ['position' => 'bottom-0 h-['.$endDot.']', 'left' => 31.5, 'lane' => $lane]) + @include('native.partials.dashed-line', ['position' => 'bottom-0 h-['.($endDotAt - 9).']', 'left' => 31.5, 'lane' => $lane]) @elseif ($replyTail) @include('native.partials.dashed-line', ['position' => 'top-['.($node === 'dot' ? $center - 9 : $center).'] bottom-0', 'left' => 31.5, 'lane' => $lane]) @endif - @if ($endsWithDot && $tail !== null) - @include('native.partials.rail-node', ['lane' => $tail, 'nodeRef' => 'end-dot', 'position' => 'absolute bottom-['.($endDot - 9).'] left-[23]']) + @if ($endsWithDot && $tail !== null && ! $dotInActions) + @include('native.partials.rail-node', ['lane' => $tail, 'nodeRef' => 'end-dot', 'position' => 'absolute bottom-['.($endDotAt - 9).'] left-[23]']) @endif {{-- The node itself takes its place on the rail, or the pressable around it does: no wrapper just to position it. --}} diff --git a/resources/views/native/partials/related-commits.blade.php b/resources/views/native/partials/related-commits.blade.php index 452eaedf..af215186 100644 --- a/resources/views/native/partials/related-commits.blade.php +++ b/resources/views/native/partials/related-commits.blade.php @@ -28,6 +28,7 @@ 'seriesExpanded' => false, 'threadBelow' => false, 'withTail' => ! $loop->last, + 'expandable' => false, ]) @endforeach diff --git a/resources/views/native/partials/send-button.blade.php b/resources/views/native/partials/send-button.blade.php index 00123656..d38068c1 100644 --- a/resources/views/native/partials/send-button.blade.php +++ b/resources/views/native/partials/send-button.blade.php @@ -2,10 +2,12 @@ A composer's send button: a 32pt circle in your colour with an up arrow, as the Claude and Messages apps send. It names what it does for screen readers ($label: Push, Reply). While there's nothing to send ($disabled) it's a muted circle, and not a button, as a disabled button would be. Its 36pt tap target fits the composer-tool row. + $colour fills it with another lane than yours, such as the organization a reply goes out as (see PostAs). --}} @php($disabled ??= false) -@php($circle = 'rounded-full '.($disabled ? 'bg-theme-surface-variant' : 'bg-theme-'.$myColour)) -@php($arrow = $disabled ? 'text-theme-ink-muted' : 'text-theme-on-'.$myColour) +@php($colour ??= $myColour) +@php($circle = 'rounded-full '.($disabled ? 'bg-theme-surface-variant' : 'bg-theme-'.$colour)) +@php($arrow = $disabled ? 'text-theme-ink-muted' : 'text-theme-on-'.$colour) @if ($disabled) diff --git a/resources/views/native/partials/sheet-bar-button.blade.php b/resources/views/native/partials/sheet-bar-button.blade.php index a554285b..1dac031a 100644 --- a/resources/views/native/partials/sheet-bar-button.blade.php +++ b/resources/views/native/partials/sheet-bar-button.blade.php @@ -1,16 +1,18 @@ {{-- A round button in a sheet's bar, as Apple draws a sheet's cross and check: the same 44pt circle on both platforms. - It's glass on iOS and a tonal circle on Android, or filled with your colour as the bar's main button ($main). + It's glass on iOS and a tonal circle on Android, or filled with your colour as the bar's main button ($main), or + with $mainColour's, the lane of the organization a composer posts as. Without $press it's drawn muted, and not as a button, as a disabled button would be. Its action checks again anyway. $loading swaps the icon for a spinner in the same circle. --}} @php($main ??= false) +@php($mainColour ??= $myColour) @php($loading ??= false) @php($hint ??= null) @php($filled = $main && ($press !== null || $loading)) -@php($circle = 'rounded-full '.($filled ? 'bg-theme-'.$myColour : 'android:bg-theme-surface-variant ios:glass'.($press === null ? '' : ':interactive'))) -@php($iconColour = $filled ? 'text-theme-on-'.$myColour : ($press === null ? 'text-theme-ink-muted' : 'text-theme-ink')) +@php($circle = 'rounded-full '.($filled ? 'bg-theme-'.$mainColour : 'android:bg-theme-surface-variant ios:glass'.($press === null ? '' : ':interactive'))) +@php($iconColour = $filled ? 'text-theme-on-'.$mainColour : ($press === null ? 'text-theme-ink-muted' : 'text-theme-ink')) @if ($press !== null) diff --git a/resources/views/native/partials/show-thread.blade.php b/resources/views/native/partials/show-thread.blade.php new file mode 100644 index 00000000..6a3e4aa6 --- /dev/null +++ b/resources/views/native/partials/show-thread.blade.php @@ -0,0 +1,8 @@ +{{-- + "Show thread" under a commit its author carried on in replies to themselves, as the web's ShowThreadLink: it opens + the commit's page, where the thread reads in order (see SelfThread). +--}} + + + Show thread + diff --git a/resources/views/native/partials/stargazers-sheet.blade.php b/resources/views/native/partials/stargazers-sheet.blade.php index f20394b8..1d3d9253 100644 --- a/resources/views/native/partials/stargazers-sheet.blade.php +++ b/resources/views/native/partials/stargazers-sheet.blade.php @@ -3,6 +3,9 @@ then each of them, newest first, with their avatar, name and handle. A tap opens them. While a page loads, skeleton rows stand in for up to three of them. When one doesn't load, the web's line says so, with Try again, and while there are more, Show more. Nothing is drawn until the sheet opens. + + On an organization's commit that a different member posted, devnull's API won't list who starred it, though the + web does, so the sheet says that instead ($stargazersForPoster). --}} @if ($stargazersOf !== null) @@ -34,7 +37,9 @@ @endif - @if ($stargazersFailed) + @if ($stargazersForPoster) + Only the member who posted this commit can see who starred it here. + @elseif ($stargazersFailed) fatal: could not load stars Try again diff --git a/resources/views/native/partials/thread-continues.blade.php b/resources/views/native/partials/thread-continues.blade.php new file mode 100644 index 00000000..efe83068 --- /dev/null +++ b/resources/views/native/partials/thread-continues.blade.php @@ -0,0 +1,24 @@ +{{-- + "Show more of this thread" under the last part of an author's thread a commit page shows, as the web's: a tap shows + the next ten parts (see SelfThread). It mirrors "↑ N earlier commits" above the commit: the last part's rail comes + down solid to a hollow node in its lane, and a dashed Rail Gray line runs on below it to what's still to come. +--}} +@php($colour = 'bg-theme-'.\App\Devnull\Lane::token($lane)) + + + + + + + Show more of this thread + + + + + + + @include('native.partials.rail-node', ['lane' => $lane, 'filled' => false]) + + @include('native.partials.dashed-line', ['position' => 'top-[31] bottom-0', 'left' => 31.5, 'lane' => \App\Devnull\Lane::Rail]) + + diff --git a/resources/views/native/partials/thread-elbow.blade.php b/resources/views/native/partials/thread-elbow.blade.php index 063ab961..f53f9afe 100644 --- a/resources/views/native/partials/thread-elbow.blade.php +++ b/resources/views/native/partials/thread-elbow.blade.php @@ -1,8 +1,9 @@ {{-- Where a thread leaves the rail, as the web's thread elbow from #121: a dashed line in the commit's lane down from - the rail ($from), round a 12pt corner, and across to the first reply's avatar ($to), level with its middle. A - nested reply's elbow leaves the spine of the reply above it the same way. It stops 1pt short of the avatar. + the rail ($from), round a 12pt corner, and across to the first reply's avatar ($to), level with its middle ($level + below the top of the reply's row). A nested reply's elbow leaves the spine of the reply above it the same way. It + stops 1pt short of the avatar. --}} @php($from ??= 31.5) @php($to ??= 64) - + diff --git a/resources/views/native/partials/thread-links.blade.php b/resources/views/native/partials/thread-links.blade.php index 858869c5..9f547262 100644 --- a/resources/views/native/partials/thread-links.blade.php +++ b/resources/views/native/partials/thread-links.blade.php @@ -1,22 +1,28 @@ {{-- - The lines beside a reply in a feed's thread (see thread-reply), drawn last in its row so they sit on top: the - commit's rail running on past, the elbow or the link from the reply above, and the line on down to the next one. + The lines beside a reply in a thread (see thread-reply and App\Devnull\ThreadRows), drawn last in its row so they + sit on top: the commit's rail running on past, the lines from further up running on past ($spines, each from its + `top` or the row's top), the elbow or the link from the reply above, and the line on down to the next one. A + flattened reply, past the web's depth, has no links of its own ($links). --}} +@php($spines ??= []) +@php($links ??= true) @if ($railLane !== null) @include('native.partials.rail', ['previous' => $railLane]) @endif -@if ($spine !== null) - @include('native.partials.dashed-line', ['position' => 'top-0 bottom-0', 'left' => 75.5, 'lane' => $spine]) -@endif +@foreach ($spines as $spineLine) + @include('native.partials.dashed-line', ['position' => (isset($spineLine['top']) ? 'top-['.$spineLine['top'].']' : 'top-0').' bottom-0', 'left' => $spineLine['left'], 'lane' => $spineLine['lane']]) +@endforeach -@if ($previousLane === null) - @include('native.partials.thread-elbow', ['lane' => $lane, 'from' => $indent > 0 ? 75.5 : 31.5, 'to' => 64 + $indent]) -@else - @include('native.partials.dashed-line', ['position' => 'top-0 h-[6]', 'left' => $avatarLine - 0.5, 'lane' => $previousLane]) -@endif +@if ($links) + @if ($previousLane === null) + @include('native.partials.thread-elbow', ['lane' => $lane, 'from' => $indent > 0 ? 43.5 + $indent : 31.5, 'to' => 64 + $indent, 'level' => $top + 12]) + @else + @include('native.partials.dashed-line', ['position' => 'top-0 h-['.($top - 4).']', 'left' => $avatarLine - 0.5, 'lane' => $previousLane]) + @endif -@if ($hasNext) - {{-- Down to the next reply, or to the top of Show more's dot: 12pt under it, its padding and the hairline below. --}} - @include('native.partials.dashed-line', ['position' => 'top-[38] '.($more !== null ? 'bottom-[34]' : 'bottom-0'), 'left' => $avatarLine - 0.5, 'lane' => $reply->lane()]) + @if ($hasNext) + {{-- From 4pt under the avatar down to the next row, which carries it on. --}} + @include('native.partials.dashed-line', ['position' => 'top-['.($top + 28).'] bottom-0', 'left' => $avatarLine - 0.5, 'lane' => $reply->lane()]) + @endif @endif diff --git a/resources/views/native/partials/thread-more-row.blade.php b/resources/views/native/partials/thread-more-row.blade.php new file mode 100644 index 00000000..4b77ced3 --- /dev/null +++ b/resources/views/native/partials/thread-more-row.blade.php @@ -0,0 +1,51 @@ +{{-- + "Show more" at the foot of a thread opened in place (see App\Devnull\ThreadRows), as a row of its own: a muted rail + dot where the next avatar would be, on the dashed line down from the reply above ($lane), and the words. Tapped, + the thread's next page opens under what's showing, or whatever $press says. $indent puts it as far in as the + replies above it, and $spines carry the lines from further up on past it. + + At the web's deepest step the dot hangs on an elbow from the line of the reply the thread answers ($hangs, in + $parentLane), as those replies do. Past it there are no lines ($links), and it says whose replies these are ($to). + + It's 44pt tall, as tall as the list's shortest row, so the list never pads it out under its hairline. The dot sits + in its middle, so the line from above stops at the top of the dot, 13pt down. In a feed the $last closes the + commit's row with its hairline; on a commit page ($hairline false) nothing does. +--}} +@php($indent ??= 0) +@php($spines ??= []) +@php($railLane ??= null) +@php($hangs ??= false) +@php($links ??= true) +@php($to ??= null) +@php($hairline ??= true) +@php($press ??= "showMoreReplies('{$threadId}')") +@php($faded = in_array('more-'.$threadId, $fadedRows ?? [], true)) + + + + + + + + + + + @if ($to === null) + Show more + @else + Show more to {{ $to }} + @endif + + + @if ($railLane !== null) + @include('native.partials.rail', ['previous' => $railLane]) + @endif + @foreach ($spines as $spineLine) + @include('native.partials.dashed-line', ['position' => (isset($spineLine['top']) ? 'top-['.$spineLine['top'].']' : 'top-0').' bottom-0', 'left' => $spineLine['left'], 'lane' => $spineLine['lane']]) + @endforeach + @if ($links && $hangs) + @include('native.partials.thread-elbow', ['lane' => $parentLane, 'from' => 43.5 + $indent, 'to' => 64 + $indent, 'level' => 22]) + @elseif ($links) + @include('native.partials.dashed-line', ['position' => 'top-0 h-[13]', 'left' => 75.5 + $indent, 'lane' => $lane]) + @endif + diff --git a/resources/views/native/partials/thread-more.blade.php b/resources/views/native/partials/thread-more.blade.php deleted file mode 100644 index 6ed4afba..00000000 --- a/resources/views/native/partials/thread-more.blade.php +++ /dev/null @@ -1,17 +0,0 @@ -{{-- - "Show more" at the foot of a thread, as the web's: a muted rail dot where the next avatar would be, and the words. - It sits inside the last reply's row, under the reply, so the rail beside it never breaks: a row of its own is - shorter than the list's shortest, and the list pads it out under its hairline. ---}} - - - - - - - - - - Show more - - diff --git a/resources/views/native/partials/thread-position.blade.php b/resources/views/native/partials/thread-position.blade.php new file mode 100644 index 00000000..0a9bb7dd --- /dev/null +++ b/resources/views/native/partials/thread-position.blade.php @@ -0,0 +1,4 @@ +{{-- A commit's place in its author's thread, like the web's ThreadPositionBadge: "2/5" in mono on a muted wash. --}} + + {{ $threadPosition }} + diff --git a/resources/views/native/partials/thread-reply.blade.php b/resources/views/native/partials/thread-reply.blade.php index 6a1d0a7c..9e225242 100644 --- a/resources/views/native/partials/thread-reply.blade.php +++ b/resources/views/native/partials/thread-reply.blade.php @@ -1,37 +1,56 @@ {{-- - A reply in the thread under a commit in a feed, like a reply in the web's thread: a 24pt avatar lined up with the - commit's text, the name and time, the body and its actions. The thread hangs off the rail in dashes of each - author's lane, as upstream's #121 draws it: the first reply on an elbow from the rail ($lane is the commit's), each - later one on a short link from the reply above ($previousLane), and a line on down from its avatar when another - reply, or "Show more", follows ($hasNext). $railLane runs the commit's own rail on past, solid, when its author's - run goes on below the thread. A deleted reply keeps its place with a dashed ring. In a feed the $last closes the - commit's row with its hairline. On a commit page nothing follows the thread, so there's no hairline. + A reply in a thread opened in place (see App\Devnull\ThreadRows), like a reply in the web's thread: a 24pt avatar + lined up with the commit's text, or $indent further in, the name and time, the body and its actions. The thread + hangs off the rail in dashes of each author's lane, as upstream's #121 draws it: the first reply on an elbow from + the line of what it answers ($lane is that one's), each later one on a short link from the reply above + ($previousLane), and a line on down from its avatar when another reply, its own replies, or "Show more", follows + ($hasNext). $spines carry lines from further up on past it, and $railLane runs the commit's own rail on past, + solid, when its author's run goes on below the thread (see thread-links). A deleted reply keeps its place with a + dashed ring. In a feed the $last closes the commit's row with its hairline. On a commit page it has one only when + another commit's row comes next ($hairline): under the replies of a commit above the commit, say, but not at the + foot of the page. - On a commit page a deleted reply's own replies open in place ($tombstones), since it has no page of their own, - one level in ($indent 32), hanging off a dashed spine from its ring as the web nests them. $spine carries the - thread's line on past a nested reply when the deleted one has another reply after it. + Past the web's depth a reply is flattened: it lines up under the reply it answers, with no lines of its own + ($links), and says who it answers on a line under its name ($replyingTo), as the web does. - The last reply carries the thread's "Show more" when there's more ($more, what it presses), with the line from its - avatar running down to it. + On a commit page a deleted reply's own replies open in place too ($tombstones), with "N replies" under its ring. + + $top is the space above the avatar, 10pt, less for the first reply in a feed, which sits under the commit row's + bottom padding (see ThreadRows::FirstReplyTop). The lines beside it are placed from the avatar, so they move with it. A commit page draws its replies $muted, smaller and in muted ink, so the commit they answer stays the main thing. + A reply its author carried on in replies to themselves links to that thread, as on the web (see show-thread): when + devnull says so, or once its replies opened in place showed it ($threadsContinued, see Concerns\ExpandsThreads). + A reply you just sent that devnull doesn't have yet is staged: dimmed, with the staged chip and no actions. + + A reply's replies button opens them under it ($repliesInPlace): on a commit page at every depth, in a feed only for + the commit's own replies, and a reply's replies there open its page. Tapping the reply itself opens its page. The + rows fade in as they open and out as they close ($fades): drawn see-through and nudged up while they're in + $fadedRows (see Concerns\ExpandsThreads), and eased to where they belong. Only what's beside the rail fades, so + the commit's rail running past never blinks. --}} @php($previousLane ??= null) @php($muted ??= false) +@php($hairline ??= ! $muted) @php($railLane ??= null) @php($indent ??= 0) -@php($spine ??= null) +@php($spines ??= []) +@php($links ??= true) +@php($replyingTo ??= null) @php($tombstones ??= false) -@php($more ??= null) @php($avatarLine = 76 + $indent) +@php($repliesInPlace ??= false) +@php($fades ??= false) +@php($top ??= 10) +@php($faded = $fades && in_array($reply->id, $fadedRows ?? [], true)) @if ($reply->isDeleted()) - @php($opened = $tombstones && array_key_exists($reply->id, $tombstoneReplies ?? [])) + @php($opened = $tombstones && array_key_exists($reply->id, $threads ?? []) && ! in_array($reply->id, $closingThreads ?? [], true)) - - + + @include('native.partials.dashed-ring', ['size' => 24, 'lane' => \App\Devnull\Lane::Rail]) @@ -40,7 +59,7 @@ [deleted] This commit was deleted. @if ($tombstones && $reply->repliesCount > 0) - + {{ $opened ? 'Hide replies' : \App\Devnull\Display::count($reply->repliesCount, 'reply', 'replies') }} @@ -49,26 +68,19 @@ @endif - @if ($more !== null) - @include('native.partials.thread-more', ['commit' => $thread ?? $reply]) - @endif - @if ($last && ! $muted) + @if ($last && $hairline) @endif @include('native.partials.thread-links') - @if ($opened && ($tombstoneReplies[$reply->id] ?? []) !== []) - {{-- The spine its own replies hang off, down from its ring. --}} - @include('native.partials.dashed-line', ['position' => 'top-[38] bottom-0', 'left' => $avatarLine - 0.5, 'lane' => \App\Devnull\Lane::Rail]) - @endif @else @php($commit = $reply) - - + + @include('native.partials.rail-avatar', ['user' => $reply->author, 'lane' => $reply->lane(), 'size' => 24, 'staged' => false]) @@ -81,17 +93,23 @@ @include('native.partials.status-chip', ['status' => $reply->status]) @endunless + @if ($replyingTo !== null) + + + {{ $replyingTo }} + + @endif @include('native.partials.commit-body', ['size' => $muted ? 'text-sm' : 'text-[15px]']) @include('native.partials.commit-media', ['withEmbeds' => false]) + @if ($reply->continuationId !== null || in_array($reply->id, $threadsContinued ?? [], true)) + @include('native.partials.show-thread') + @endif @unless ($reply->isStaged()) - @include('native.partials.commit-actions', ['expandable' => false, 'withQuote' => false, 'compact' => $muted]) + @include('native.partials.commit-actions', ['expandable' => $repliesInPlace, 'withQuote' => false, 'compact' => $muted]) @endunless - @if ($more !== null) - @include('native.partials.thread-more', ['commit' => $thread ?? $reply]) - @endif - @if ($last && ! $muted) + @if ($last && $hairline) @endif diff --git a/resources/views/native/scheduled-commits.blade.php b/resources/views/native/scheduled-commits.blade.php index 06f07ac1..3dbf2dda 100644 --- a/resources/views/native/scheduled-commits.blade.php +++ b/resources/views/native/scheduled-commits.blade.php @@ -47,6 +47,13 @@ {{ $item->label($now) }} {{ Display::scheduleTime($item->scheduledAt, $timezone) }} + @if ($item->author) + {{-- The organization it goes out as, as the web's list shows it under the time. --}} + + @include('native.partials.avatar', ['user' => $item->author, 'size' => 16]) + As {{ $item->author->handle() }} + + @endif @if ($item->isWaiting()) @php($when = Display::scheduleTime($item->scheduledAt, $timezone)) diff --git a/tests/Feature/Screens/CommitCardTest.php b/tests/Feature/Screens/CommitCardTest.php index 067cf306..966269ce 100644 --- a/tests/Feature/Screens/CommitCardTest.php +++ b/tests/Feature/Screens/CommitCardTest.php @@ -105,10 +105,12 @@ function logOf(array $commits): TestableComponent expect($target($ref))->toMatchArray(['min_width' => 44.0, 'height' => 36.0]); } + // The row takes its full 36pt, with no negative margins above or below, which Android draws as an offset and keeps + // the space of. The padding under it takes back the 6pt its buttons reach past their icons. expect($target('reply-to-c1')['height'])->toBe(36.0) ->and($target('replies-c1')['height'])->toBe(36.0) - // 6pt more above and below than the 24pt the row used to be, so it's pulled in by that much. - ->and(array_slice(nodeByRef($screen, 'actions-c1')['layout']['margin'], 0, 3))->toBe([-6.0, 0.0, -6.0]); + ->and(nodeByRef($screen, 'actions-c1')['layout']['height'])->toBe(36.0) + ->and(array_slice(nodeByRef($screen, 'actions-c1')['layout']['margin'] ?? [0.0, 0.0, 0.0], 0, 3))->toBe([0.0, 0.0, 0.0]); }); it('builds a row from as few views as it can, as a list builds and measures each of them while it scrolls', function () { @@ -122,7 +124,8 @@ function logOf(array $commits): TestableComponent ->and($content['layout']['margin'])->toBe([0.0, 0.0, 0.0, 64.0]) ->and($content['props']['border_b'])->toBe(1.0) ->and(array_column(nodeByRef($screen, 'star-c1')['children'], 'type'))->toBe(['icon', 'text']) - ->and(count(findNodes($row, fn (): bool => true)))->toBeLessThanOrEqual(35); + // Quote's label, and the end of the rail drawn in the action row, came to two more. + ->and(count(findNodes($row, fn (): bool => true)))->toBeLessThanOrEqual(37); }); it("draws a poll you haven't voted on as plain options, with nothing to tap, since the app can't vote yet", function () { diff --git a/tests/Feature/Screens/CommitDetailCacheTest.php b/tests/Feature/Screens/CommitDetailCacheTest.php index b864b63e..afc3e075 100644 --- a/tests/Feature/Screens/CommitDetailCacheTest.php +++ b/tests/Feature/Screens/CommitDetailCacheTest.php @@ -48,7 +48,8 @@ function serveThread(): void finishRefreshes($screen)->assertSee('A compiler'); - expect(count(Http::recorded()))->toBe(3); + // The commit, its replies, what's related, and c0's own page for how many replies it has. + expect(count(Http::recorded()))->toBe(4); }); it('opens from a row on what the row knew, then fills in the replies and what it replies to', function () { @@ -140,10 +141,10 @@ function serveThread(): void 'GET /api/v1/commits/d1/replies' => [pageJson([replyJson(['id' => 'r9', 'parent_id' => 'd1', 'body' => 'Under a deleted reply'])])], ]); - $screen = Native::visit('/log/commits/c1')->tap('replies-c1')->call('toggleTombstone', 'd1')->assertSee('Under a deleted reply'); + $screen = Native::visit('/log/commits/c1')->tap('replies-c1')->call('toggleReplies', 'd1')->assertSee('Under a deleted reply'); $screen->call('load'); - Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/d1/replies?limit=5'); + Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/d1/replies?limit=10'); $screen->assertSee('Under a deleted reply'); }); diff --git a/tests/Feature/Screens/CommitDetailTest.php b/tests/Feature/Screens/CommitDetailTest.php index 8b692e51..1da6b224 100644 --- a/tests/Feature/Screens/CommitDetailTest.php +++ b/tests/Feature/Screens/CommitDetailTest.php @@ -9,6 +9,7 @@ use Illuminate\Support\Facades\Http; use Native\Mobile\Events\Alert\ButtonPressed; use Native\Mobile\Testing\Native; +use Tests\Support\GlassOpacity; beforeEach(function () { config(['devnull.url' => 'http://devnull.test']); @@ -50,19 +51,19 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): ->assertSee('Reply to @local_dev'); // The commit comes after the one it replies to, and the row standing in for what that replies to. - expect(childRefs($screen, 'thread-page'))->toBe(['earlier-commits', 'commit-c1', 'focused-commit', 'reply-bar-clearance']); + expect(childRefs($screen, 'thread-scroll'))->toBe(['earlier-commits', 'commit-c1', 'focused-commit', 'reply-bar-clearance']); $screen->tap('earlier-commits') ->assertSee('The root commit') ->assertDontSee('1 earlier commit'); - expect(childRefs($screen, 'thread-page'))->toBe(['commit-c0', 'commit-c1', 'focused-commit', 'reply-bar-clearance']); + expect(childRefs($screen, 'thread-scroll'))->toBe(['commit-c0', 'commit-c1', 'focused-commit', 'reply-bar-clearance']); $screen->tap('replies-c2') ->assertSee('First reply') ->assertSee('Hide replies'); - expect(childRefs($screen, 'thread-page'))->toBe(['commit-c0', 'commit-c1', 'focused-commit', 'thread-reply-r1', 'reply-bar-clearance']); + expect(childRefs($screen, 'thread-scroll'))->toBe(['commit-c0', 'commit-c1', 'focused-commit', 'thread-reply-r1', 'reply-bar-clearance']); $screen->tap('replies-c2') ->assertDontSee('First reply') @@ -83,7 +84,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): ->assertSee('The parent commit') ->assertDontSee('The root commit'); - expect(childRefs($screen, 'thread-page'))->toBe(['earlier-commits', 'commit-c1', 'focused-commit', 'reply-bar-clearance']) + expect(childRefs($screen, 'thread-scroll'))->toBe(['earlier-commits', 'commit-c1', 'focused-commit', 'reply-bar-clearance']) ->and(nodeByRef($screen, 'thread-scroll')['id'])->not->toBe($before); }); @@ -286,7 +287,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): ->and(findNode($screen->tree(), fn (array $node): bool => str_starts_with((string) ($node['ref'] ?? ''), 'thread-end-')))->toBeNull(); }); -it('shows the short hash under the focused commit, without the full date', function () { +it('shows the short hash at the top right of the focused commit, without the full date', function () { fakeThread(['created_at' => '2026-10-14T20:13:05Z']); $screen = Native::visit('/log/commits/c2') @@ -294,8 +295,13 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): ->assertDontSee('+0000'); $hash = nodeByRef($screen, 'focused-hash'); + // The row with the name, the handle and the time, with a spacer pushing the hash to its end. + $nameRow = findNode(nodeByRef($screen, 'focused-commit'), fn (array $node): bool => ($node['type'] ?? null) === 'row' && in_array('focused-time', array_map(fn (array $child): ?string => $child['ref'] ?? null, $node['children'] ?? []), true)); + $children = $nameRow['children'] ?? []; - expect($hash['text'] ?? $hash['props']['text'] ?? null)->toBe('c2'); + expect($hash['text'] ?? $hash['props']['text'] ?? null)->toBe('c2') + ->and($children[array_key_last($children)]['ref'] ?? null)->toBe('focused-hash') + ->and($children[count($children) - 2]['type'] ?? null)->toBe('spacer'); }); it('says when the commit was made, in your timezone, when its time is tapped, as the web does on hover', function (?string $chosen, string $toast) { @@ -346,7 +352,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): $staged = $screen->instance()->replies[1]->id; - expect(childRefs($screen, 'thread-page'))->toBe(['focused-commit', 'thread-reply-r1', "thread-reply-{$staged}", 'reply-bar-clearance']) + expect(childRefs($screen, 'thread-scroll'))->toBe(['focused-commit', 'thread-reply-r1', "thread-reply-{$staged}", 'reply-bar-clearance']) ->and(PendingWrite::query()->count())->toBe(1); finishRefreshes($screen) @@ -354,7 +360,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): ->assertSee('pending') ->assertDontSee('staged'); - expect(childRefs($screen, 'thread-page'))->toBe(['focused-commit', 'thread-reply-r1', 'thread-reply-r9', 'reply-bar-clearance']) + expect(childRefs($screen, 'thread-scroll'))->toBe(['focused-commit', 'thread-reply-r1', 'thread-reply-r9', 'reply-bar-clearance']) ->and(PendingWrite::query()->count())->toBe(0) ->and(collect(Http::recorded())->filter(fn (array $sent): bool => $sent[0]->method() === 'POST'))->toHaveCount(1); }); @@ -382,7 +388,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): ->call('loadMoreReplies') ->assertSet('repliesCursor', null); - expect(childRefs($screen, 'thread-page'))->toBe(['focused-commit', 'thread-reply-r1', 'thread-reply-r2', 'thread-reply-r9', 'reply-bar-clearance']); + expect(childRefs($screen, 'thread-scroll'))->toBe(['focused-commit', 'thread-reply-r1', 'thread-reply-r2', 'thread-reply-r9', 'reply-bar-clearance']); }); it('marks a reply waiting for approval as pending on its row', function () { @@ -503,63 +509,83 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): }); it('opens ancestors, replies and profiles', function () { - fakeThread(replies: [replyJson(['id' => 'r1'])]); + fakeThread(replies: [replyJson(['id' => 'r1', 'parent_id' => 'c2'])]); - Native::visit('/log/commits/c2')->tap('earlier-commits')->tap('commit-c1')->assertNavigatedTo('/log/commits/c1'); - Native::visit('/log/commits/c2')->tap('replies-c2')->tap('thread-reply-r1')->assertNavigatedTo('/log/commits/r1'); + // Commits in the tree move the page to them, and anything else opens its own page. + Native::visit('/log/commits/c2')->tap('earlier-commits')->tap('commit-c1')->assertNoNavigation()->assertSet('id', 'c1'); + Native::visit('/log/commits/c2')->tap('replies-c2')->tap('thread-reply-r1')->assertNoNavigation()->assertSet('id', 'r1'); Native::visit('/log/commits/c2')->call('openProfile', 'ada')->assertNavigatedTo('/log/users/ada'); }); +it("turns the replies button's chevron down while the replies show, as the Log does, and back as they close", function (string $platform) { + fakeThread(['replies_count' => 1], replies: [replyJson(['id' => 'r1', 'parent_id' => 'c2', 'body' => 'First reply', 'replies_count' => 1])]); + + $screen = Native::visit('/log/commits/c2', platform: $platform); + $chevron = fn (string $ref): array => findNode(nodeByRef($screen, $ref), fn (array $node): bool => ($node['type'] ?? null) === 'icon'); + + // Shut, it points right, and already carries the animation, so the turn animates on iOS. + expect($chevron('replies-c2')['props'])->toMatchArray(['name' => 'custom:chevron-right', 'rotate' => 0.0, 'animate-duration' => 220.0]); + + $screen->tap('replies-c2')->assertSee('First reply')->assertSee('Hide replies'); + expect($chevron('replies-c2')['props'])->toMatchArray(['name' => 'custom:chevron-right', 'rotate' => 90.0, 'animate-duration' => 220.0]); + + $screen->tap('replies-c2')->assertDontSee('First reply')->assertSee('1 reply'); + expect($chevron('replies-c2')['props'])->toMatchArray(['name' => 'custom:chevron-right', 'rotate' => 0.0, 'animate-duration' => 220.0]); + + // A reply's button opens its replies in place too, so its chevron turns the same way. + $screen->tap('replies-c2'); + expect($chevron('replies-r1')['props'])->toMatchArray(['rotate' => 0.0, 'animate-duration' => 220.0]); +})->with(['ios', 'android']); + it('opens with its replies showing from a replies button', function () { fakeThread(['replies_count' => 1], replies: [replyJson(['id' => 'r1', 'parent_id' => 'c2', 'body' => 'First reply', 'replies_count' => 1])], extra: [ 'GET /api/v1/commits/r1' => [commitPageJson(replyJson(['id' => 'r1', 'parent_id' => 'c2', 'body' => 'First reply', 'replies_count' => 1]))], - 'GET /api/v1/commits/r1/replies' => [pageJson([replyJson(['id' => 'r2', 'parent_id' => 'r1', 'body' => 'Answering the reply'])])], + // Someone other than r1's author, whose reply to themselves would carry r1 on as a thread instead. + 'GET /api/v1/commits/r1/replies' => [pageJson([replyJson(['id' => 'r2', 'parent_id' => 'r1', 'body' => 'Answering the reply', 'author' => userJson(['id' => 'u3', 'handle' => 'grace', 'name' => 'Grace'])])])], ]); Native::visit('/log/commits/c2', ['replies' => true]) ->assertSee('First reply') ->assertSee('Hide replies'); - // A reply's replies don't open in place on a commit page, so its button opens its page with them showing. + // A reply's replies open in place under it, as on the web, rather than on its page. Native::visit('/log/commits/c2') ->tap('replies-c2') ->tap('replies-r1') - ->assertNavigatedTo('/log/commits/r1') - ->follow() - ->assertSee('Answering the reply') - ->assertSee('Hide replies'); + ->assertNoNavigation() + ->assertSee('Answering the reply'); }); -it('asks for the replies five at a time, and the next five from Show more', function () { +it('asks for the replies a page at a time, and the next page from Show more', function () { $replies = fn (int ...$numbers): array => array_map(fn (int $n): array => replyJson(['id' => "r{$n}", 'parent_id' => 'c2', 'body' => "Reply {$n}"]), $numbers); Http::fake(fn (Request $request) => match (parse_url($request->url(), PHP_URL_PATH)) { '/api/v1/commits/c2/replies' => Http::response(str_contains($request->url(), 'cursor=page2') - ? pageJson($replies(6)) - : pageJson($replies(1, 2, 3, 4, 5), 'page2', 'http://devnull.test/api/v1/commits/c2/replies')), + ? pageJson($replies(11)) + : pageJson($replies(...range(1, 10)), 'page2', 'http://devnull.test/api/v1/commits/c2/replies')), '/api/v1/commits/c2/related' => Http::response(['data' => []]), - default => Http::response(commitPageJson(commitJson(['id' => 'c2', 'body' => 'The focused commit', 'replies_count' => 6]))), + default => Http::response(commitPageJson(commitJson(['id' => 'c2', 'body' => 'The focused commit', 'replies_count' => 11]))), }); $screen = Native::visit('/log/commits/c2', ['replies' => true]) - ->assertSee('Reply 5') - ->assertDontSee('Reply 6') + ->assertSee('Reply 10') + ->assertDontSee('Reply 11') ->tap('more-replies-c2') - ->assertSee('Reply 6') + ->assertSee('Reply 11') ->assertDontSee('Show more'); $asked = collect(Http::recorded())->map(fn (array $sent): string => $sent[0]->url())->filter(fn (string $url): bool => str_contains($url, '/replies')); expect($asked)->toHaveCount(2) - ->and($asked->every(fn (string $url): bool => str_contains($url, 'limit=5')))->toBeTrue(); + ->and($asked->every(fn (string $url): bool => str_contains($url, 'limit=10')))->toBeTrue(); - // Asking again for the first five keeps the one loaded after them. + // Asking again for the first page keeps the one loaded after it. $screen->call('load') - ->assertSee('Reply 6') + ->assertSee('Reply 11') ->assertDontSee('Show more'); }); -it('opens the replies of a deleted reply five at a time too', function () { +it('opens the replies of a deleted reply a page at a time too', function () { $nested = fn (int ...$numbers): array => array_map(fn (int $n): array => replyJson(['id' => "n{$n}", 'parent_id' => 'r1', 'body' => "Nested {$n}"]), $numbers); Http::fake(fn (Request $request) => match (parse_url($request->url(), PHP_URL_PATH)) { @@ -585,7 +611,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): ->assertSee('Nested 6') ->assertMissingElement('pressable', $more); - Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/r1/replies?cursor=page2&limit=5'); + Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/r1/replies?cursor=page2&limit=10'); }); it('keeps deleted ancestors on the rail as tombstones', function () { @@ -644,7 +670,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): // One level in, on an elbow off the deleted reply's spine. expect(findNode(nodeByRef($screen, 'thread-reply-r3'), fn (array $node): bool => ($node['ref'] ?? null) === 'thread-elbow'))->not->toBeNull(); - $screen->tap('thread-reply-r3')->assertNavigatedTo('/log/commits/r3'); + $screen->tap('thread-reply-r3')->assertNoNavigation()->assertSet('id', 'r3'); Native::visit('/log/commits/c2') ->tap('replies-c2') @@ -772,7 +798,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): expect(app(Account::class)->user())->toBeNull(); }); -it('reloads when you come back from a reply you deleted', function () { +it('moves back to the parent when you delete a reply the page moved to', function () { $replyDeleted = false; Http::fake(function (Request $request) use (&$replyDeleted) { @@ -789,15 +815,15 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): }; }); - $reply = Native::visit('/log/commits/c2') + // The page moved to the reply, so deleting it moves the page back to its parent, asked for again. + Native::visit('/log/commits/c2') ->tap('replies-c2') ->assertSee('Soon gone') ->tap('thread-reply-r1') - ->follow() + ->assertSet('id', 'r1') ->call('deleteCommit', 'r1') - ->assertWentBack(); - - $reply->goBack() + ->assertNoNavigation() + ->assertSet('id', 'c2') ->assertSee('Parent') ->assertDontSee('Soon gone') ->assertSee('No replies yet.'); @@ -842,7 +868,7 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): it('stars the focused commit and its replies in place', function () { $grace = userJson(['id' => 'u3', 'handle' => 'grace', 'name' => 'Grace']); - fakeThread(['author' => $grace], replies: [replyJson(['id' => 'r1', 'parent_id' => 'c2', 'author' => $grace])], extra: [ + fakeThread(['author' => $grace], replies: [replyJson(['id' => 'r1', 'parent_id' => 'c2'])], extra: [ 'POST /api/v1/commits/c2/star' => [['data' => commitJson(['id' => 'c2', 'stars_count' => 1, 'starred' => true])]], 'POST /api/v1/commits/r1/star' => [['data' => commitJson(['id' => 'r1', 'starred' => true])]], ]); @@ -868,6 +894,10 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): it('puts the reply bar on glass on iOS and the surface on Android, with no line, and fades the page out above it', function (string $platform) { fakeThread(); + if ($platform === 'ios') { + GlassOpacity::skipUnlessSupported(); + } + $screen = Native::visit('/log/commits/c2', platform: $platform); $bottomBar = findNode($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'bottom_bar'); $bar = $bottomBar['children'][0]; @@ -901,12 +931,33 @@ function fakeThread(array $commit = [], array $replies = [], array $extra = []): } })->with(['ios', 'android']); +it('keeps the reply field closer to the fade than to the row of tools under it', function (string $platform) { + fakeThread(); + + $screen = Native::visit('/log/commits/c2', platform: $platform); + + // [top, right, bottom, left]. The row has no top padding, so the field starts 4pt under the fade, and the field + // row leaves 8pt between the field and the tools. + expect(nodeByRef($screen, 'reply-row')['layout']['padding'])->toEqual([0, 16, 8, 16]) + ->and(nodeByRef($screen, 'reply-field-row')['layout']['padding'])->toEqual([4, 12, 8, 16]); +})->with(['ios', 'android']); + +it('fades the glass under the reply bar to 80% on iOS only', function (string $platform) { + GlassOpacity::skipUnlessSupported(); + fakeThread(); + + $screen = Native::visit('/log/commits/c2', platform: $platform); + $bottomBar = findNode($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'bottom_bar'); + + expect($bottomBar['props']['glass_opacity'] ?? null)->toBe($platform === 'ios' ? Display::ComposerGlassOpacity / 100 : null); +})->with(['ios', 'android']); + it('ends the page above the reply bar, and further as the draft grows', function () { fakeThread(replies: [replyJson(['id' => 'r1', 'parent_id' => 'c2', 'body' => 'The last reply'])]); $screen = Native::visit('/log/commits/c2', platform: 'ios'); $scroller = findNode($screen->tree(), fn (array $node): bool => ($node['type'] ?? null) === 'scroll_view'); - $page = $scroller['children'][0]['children']; + $page = $scroller['children']; // The clearance is the last thing on the page, under the last reply: the fade, the bar and the home indicator. $bar = 24 + Display::ComposerFadeHeight + Display::ComposerBoxBarHeight + 34; diff --git a/tests/Feature/Screens/CommitMentionsTest.php b/tests/Feature/Screens/CommitMentionsTest.php index 4d35f14f..b728402d 100644 --- a/tests/Feature/Screens/CommitMentionsTest.php +++ b/tests/Feature/Screens/CommitMentionsTest.php @@ -95,6 +95,31 @@ function mentionsComposer(bool $quoting = false): TestableComponent ->assertMissingElement('column', fn (array $node): bool => ($node['ref'] ?? null) === 'mention-suggestions'); }); +it('holds the reply bar\'s suggestions to six rows and scrolls the rest inside the list', function () { + $people = array_map(fn (int $n): array => userJson(['id' => "u{$n}", 'handle' => "ada{$n}", 'name' => "Ada {$n}"]), range(1, 7)); + $screen = mentionsCommitPage([['data' => $people, 'organizations' => [['handle' => 'adaptive', 'name' => 'Adaptive', 'avatar_url' => null]]]]) + ->input('reply-input', '@ada', 4); + + // Eight rows, so they sit in a list six rows tall, which scrolls. The slot and the field's row around it stay put. + $list = nodeByRef($screen, 'mention-scroll'); + + expect(childRefs($screen, 'mention-suggestions'))->toBe(['mention-scroll']) + ->and($list['type'])->toBe('scroll_view') + ->and($list['layout']['height'] ?? null)->toEqual(6 * 44) + ->and(childRefs($screen, 'mention-scroll'))->toBe([...array_map(fn (int $n): string => "mention-ada{$n}", range(1, 7)), 'mention-adaptive']) + ->and(childRefs($screen, 'reply-rows'))->toBe(['reply-mention-slot', 'reply-photos-slot', 'reply-row']); + + $screen->tap('mention-ada7')->assertSet('reply', '@ada7 '); +}); + +it('leaves six suggestions or fewer as tall as their rows, with no list to scroll', function () { + $people = array_map(fn (int $n): array => userJson(['id' => "u{$n}", 'handle' => "ada{$n}", 'name' => "Ada {$n}"]), range(1, 6)); + $screen = mentionsCommitPage([['data' => $people]])->input('reply-input', '@ada', 4); + + expect(childRefs($screen, 'mention-suggestions'))->toBe(array_map(fn (int $n): string => "mention-ada{$n}", range(1, 6))) + ->and(rendersRef($screen, 'mention-scroll'))->toBeFalse(); +}); + it('puts the person picked in the reply where the @ was, with the caret after them', function () { $screen = mentionsCommitPage() ->input('reply-input', 'cc @adfor review', 6) diff --git a/tests/Feature/Screens/CommitMenuTest.php b/tests/Feature/Screens/CommitMenuTest.php index c07a7170..53ba2936 100644 --- a/tests/Feature/Screens/CommitMenuTest.php +++ b/tests/Feature/Screens/CommitMenuTest.php @@ -130,7 +130,7 @@ $deleted = true; }), 'GET /api/v1/commits/c2' => Http::response(commitPageJson(commitJson(['id' => 'c2', 'body' => 'Ada asks', 'replies_count' => $deleted ? 0 : 1, 'author' => userJson(['id' => 'u2', 'handle' => 'ada'])]))), - 'GET /api/v1/commits/c2/replies' => Http::response(pageJson($deleted ? [] : [replyJson(['id' => 'r1', 'parent_id' => 'c2', 'body' => 'Soon gone'])])), + 'GET /api/v1/commits/c2/replies' => Http::response(pageJson($deleted ? [] : [replyJson(['id' => 'r1', 'parent_id' => 'c2', 'body' => 'Soon gone', 'author' => userJson()])])), default => Http::response(['message' => 'No fake.'], 404), }; }); diff --git a/tests/Feature/Screens/ConversationTest.php b/tests/Feature/Screens/ConversationTest.php index 4a22b9cc..40806fa2 100644 --- a/tests/Feature/Screens/ConversationTest.php +++ b/tests/Feature/Screens/ConversationTest.php @@ -1281,7 +1281,7 @@ function orgWithMembers(array $people): array ->assertMissingElement('column', fn (array $node): bool => ($node['ref'] ?? null) === 'mention-suggestions'); }); -it('filters org members as the web ranks them: exact handle, handle prefix, name prefix, then the rest, followed first, six at most', function () { +it('filters org members as the web ranks them: exact handle, handle prefix, name prefix, then the rest, followed first, all of them in a list that scrolls past six', function () { serveOrgThread(orgWithMembers([ ['grace', 'Grace Hopper'], ['tobias', 'Ada Tobias'], @@ -1295,7 +1295,8 @@ function orgWithMembers(array $people): array $screen = finishRefreshes(Native::visit('/remotes/orgs/org-1'))->input('message-input', '@ADA', 4); - expect(childRefs($screen, 'mention-suggestions'))->toBe(['mention-ada', 'mention-adams', 'mention-adamant', 'mention-tobias', 'mention-bada', 'mention-cada']); + expect(childRefs($screen, 'mention-scroll'))->toBe(['mention-ada', 'mention-adams', 'mention-adamant', 'mention-tobias', 'mention-bada', 'mention-cada', 'mention-dada']) + ->and(nodeByRef($screen, 'mention-scroll')['layout']['height'])->toEqual(Display::MentionRowsShown * Display::MentionRowHeight); }); it('never suggests you, or a member devnull says not to, and suggests nothing in a thread with one person', function () { diff --git a/tests/Feature/Screens/DraftStashTest.php b/tests/Feature/Screens/DraftStashTest.php index a346e29d..b112a26d 100644 --- a/tests/Feature/Screens/DraftStashTest.php +++ b/tests/Feature/Screens/DraftStashTest.php @@ -273,7 +273,7 @@ function stashLabel(TestableComponent $screen, string $ref): array $screen = Native::visit('/log', platform: 'ios'); // The dots sit inside the buttons, so the row has the same actions as without them. - expect(array_values(array_filter(childRefs($screen, 'actions-c2'))))->toBe(['star-c2', 'pastel-c2', 'quote-c2', 'reply-to-c2', 'replies-c2', 'more-c2']) + expect(array_values(array_filter(childRefs($screen, 'actions-c2'))))->toBe(['star-c2', 'pastel-c2', 'quote-c2', 'reply-to-c2', 'more-c2']) ->and(array_values(array_filter(childRefs($screen, 'actions-c1'))))->toBe(['star-c1', 'pastel-c1', 'quote-c1', 'reply-to-c1', 'more-c1']) ->and(showsRef($screen, 'quote-stash-c2'))->toBeTrue() ->and(showsRef($screen, 'reply-stash-c2'))->toBeTrue() diff --git a/tests/Feature/Screens/LogTest.php b/tests/Feature/Screens/LogTest.php index c0222442..ffc354b0 100644 --- a/tests/Feature/Screens/LogTest.php +++ b/tests/Feature/Screens/LogTest.php @@ -437,7 +437,7 @@ ], ]); -it('puts the web action row under each commit: the star, Quote, Reply and replies, then More', function () { +it('puts the web action row under each commit: the star, Quote, Reply, then More, with the replies on a line below', function () { $ada = userJson(['id' => 'u2', 'handle' => 'ada']); Http::fake(['devnull.test/*' => Http::response(pageJson([ @@ -458,8 +458,9 @@ // Someone else's pending commit can't be starred or quoted, so the web leaves them off. ->assertMissingElement('pressable', fn (array $node): bool => in_array($node['ref'] ?? null, ['star-c0', 'quote-c0'], true)); - // The web's order: star, Quote, Reply and replies on the left, then More for Share link and Report. - expect(array_values(array_filter(childRefs($screen, 'actions-c2'))))->toBe(['star-c2', 'quote-c2', 'reply-to-c2', 'replies-c2', 'more-c2']) + // The web's order: star, Quote and Reply on the left, then More for Share link and Report. The replies are under them. + expect(array_values(array_filter(childRefs($screen, 'actions-c2'))))->toBe(['star-c2', 'quote-c2', 'reply-to-c2', 'more-c2']) + ->and(findNode(nodeByRef($screen, 'actions-c2'), fn (array $node): bool => ($node['ref'] ?? null) === 'replies-c2'))->toBeNull() // Nor can it be reported, so all its menu has is the link. ->and(menuItems($screen, 'more-c0'))->toBe([['share-c0', 'Share link', 'custom:link']]); @@ -475,6 +476,8 @@ ->and($icon('reply-to-c1')['props']['name'] ?? null)->toBe('custom:message-square-reply') ->and($icon('replies-c2')['props']['name'] ?? null)->toBe('custom:chevron-right') ->and($text('replies-c2', '1 reply')['props']['color'] ?? null)->toBe($primary) + ->and($text('quote-c1', 'Quote'))->not->toBeNull() + ->and($text('reply-to-c1', 'Reply'))->not->toBeNull() ->and($icon('more-c1')['props']['name'] ?? null)->toBe('custom:ellipsis') ->and($icon('more-c1')['props']['color'] ?? null)->toBe($muted); @@ -607,7 +610,11 @@ ->assertSee('This commit was deleted.') ->assertSee('Hide replies'); - expect(findNode(nodeByRef($screen, 'replies-c2'), fn (array $node): bool => ($node['type'] ?? null) === 'icon')['props']['name'] ?? null)->toBe('custom:chevron-down'); + // The chevron turns down, which the phone animates. + $chevron = findNode(nodeByRef($screen, 'replies-c2'), fn (array $node): bool => ($node['type'] ?? null) === 'icon'); + expect($chevron['props']['name'] ?? null)->toBe('custom:chevron-right') + ->and($chevron['props']['rotate'] ?? null)->toBe(90.0) + ->and($chevron['props']['animate-duration'] ?? null)->toBeGreaterThan(0.0); // Its replies get the same actions, and open their own page. $screen->tap('star-r1'); @@ -618,24 +625,29 @@ Native::visit('/log')->tap('replies-c2')->tap('thread-reply-r1')->assertNavigatedTo('/log/commits/r1'); }); -it('opens five replies of a thread in place, and the rest on its commit page from Show more', function () { - fakeApi([ - 'GET /api/v1/log/following' => [pageJson([commitJson(['id' => 'c2', 'replies_count' => 7])])], - 'GET /api/v1/commits/c2/replies' => [pageJson(array_map(fn (int $n): array => replyJson(['id' => "r{$n}", 'parent_id' => 'c2', 'body' => "Reply {$n}"]), range(1, 5)), 'page2', 'http://devnull.test/api/v1/commits/c2/replies')], - 'GET /api/v1/commits/c2' => [commitPageJson(commitJson(['id' => 'c2', 'replies_count' => 7]))], - ]); +it('opens ten replies of a thread in place, and the next ten under them from Show more', function () { + $replies = fn (int $from, int $to): array => array_map(fn (int $n): array => replyJson(['id' => "r{$n}", 'parent_id' => 'c2', 'body' => "Reply {$n}"]), range($from, $to)); + + Http::fake(fn (Request $request) => Http::response(match (true) { + str_contains($request->url(), '/log/following') => pageJson([commitJson(['id' => 'c2', 'replies_count' => 13])]), + str_contains($request->url(), 'cursor=page2') => pageJson($replies(11, 13), path: 'http://devnull.test/api/v1/commits/c2/replies'), + default => pageJson($replies(1, 10), 'page2', 'http://devnull.test/api/v1/commits/c2/replies'), + })); - Native::visit('/log', platform: 'ios') + $screen = Native::visit('/log', platform: 'ios') ->tap('replies-c2') ->assertNoNavigation() - ->assertSee('Reply 5') + ->assertSee('Reply 10') + ->assertDontSee('Reply 11') ->tap('more-replies-c2') - ->assertNavigatedTo('/log/commits/c2') - ->follow() - ->assertSet('repliesShown', true) - ->assertSee('Reply 5'); + ->assertNoNavigation() + ->assertSee('Reply 13') + ->assertDontSee('Show more'); + + expect(array_map(fn ($reply): string => $reply->id, $screen->instance()->threads['c2']))->toBe(array_map(fn (int $n): string => "r{$n}", range(1, 13))); - Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/c2/replies?limit=5'); + Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/c2/replies?limit=10'); + Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/c2/replies?cursor=page2&limit=10'); }); it('closes a thread whose replies have all gone', function () { diff --git a/tests/Feature/Screens/LogThreadTest.php b/tests/Feature/Screens/LogThreadTest.php new file mode 100644 index 00000000..de2badd5 --- /dev/null +++ b/tests/Feature/Screens/LogThreadTest.php @@ -0,0 +1,457 @@ + 'http://devnull.test']); + signIn(); +}); + +function grace(): array +{ + return userJson(['id' => 'u3', 'handle' => 'grace', 'name' => 'Grace', 'lane' => 4]); +} + +function threadAda(): array +{ + return userJson(['id' => 'u2', 'handle' => 'ada', 'name' => 'Ada', 'lane' => 1]); +} + +/** + * A commit by Ada in a list, with $replies replies, and the newest one devnull previews under it. + * + * @param array $overrides + * @return array + */ +function threadedJson(int $replies = 1, array $overrides = []): array +{ + return commitJson([ + 'id' => 'c1', + 'body' => 'Ship it?', + 'replies_count' => $replies, + 'author' => threadAda(), + 'reply_preview' => ['data' => [replyJson(['id' => 'r9', 'parent_id' => 'c1', 'body' => 'The newest reply', 'author' => grace()])], 'next_cursor' => null], + ...$overrides, + ]); +} + +/** + * $count replies to $parentId, r1 to rN unless $prefix says otherwise. + * + * @return list> + */ +function repliesJson(string $parentId, int $count, string $prefix = 'r', int $from = 1, array $overrides = []): array +{ + return array_map(fn (int $n): array => replyJson(['id' => "{$prefix}{$n}", 'parent_id' => $parentId, 'body' => "Reply {$prefix}{$n}", 'author' => grace(), ...$overrides]), range($from, $from + $count - 1)); +} + +/** + * The colours of the dashed lines in a node, in order. + * + * @return list + */ +function dashColours(array $node): array +{ + return array_values(array_unique(array_map( + fn (array $line): string => $line['style']['border_color'] ?? '', + findNodes($node, fn (array $child): bool => ($child['props']['border_style'] ?? null) === 1), + ))); +} + +function refNode(array $node, string $ref): ?array +{ + return findNode($node, fn (array $child): bool => ($child['ref'] ?? null) === $ref); +} + +it('keeps replies hidden under a commit, with the replies button on its own line under the actions', function () { + Http::fake(['devnull.test/*' => Http::response(pageJson([threadedJson(3)]))]); + + $screen = Native::visit('/log', platform: 'ios') + ->assertSee('Ship it?') + ->assertDontSee('The newest reply') + ->assertSee('3 replies'); + + expect(refNode(nodeByRef($screen, 'actions-c1'), 'replies-c1'))->toBeNull() + ->and(refNode(nodeByRef($screen, 'commit-c1'), 'replies-c1'))->not->toBeNull() + ->and(findNode($screen->tree(), fn (array $node): bool => str_starts_with($node['ref'] ?? '', 'thread-reply-')))->toBeNull(); +}); + +it('opens the replies under a commit from its replies button, on a dashed elbow in its lane', function () { + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([threadedJson(2)])], + 'GET /api/v1/commits/c1/replies' => [pageJson(repliesJson('c1', 2))], + ]); + + $screen = Native::visit('/log', platform: 'ios') + ->tap('replies-c1') + ->assertNoNavigation() + ->assertSee('Reply r1') + ->assertSee('Reply r2') + ->assertSee('Hide replies'); + + $reply = nodeByRef($screen, 'thread-reply-r1'); + $elbow = refNode($reply, 'thread-elbow'); + + expect($elbow)->not->toBeNull() + ->and(dashColours($elbow))->toBe([config('native-ui.theme.light.lane-1')]) + ->and($elbow['props'])->toMatchArray(['border_l' => 1.0, 'border_b' => 1.0, 'border_t' => 0.0, 'border_r' => 0.0, 'radius_bl' => 12.0]) + // Level with the middle of the avatar, which sits 3pt down, under the commit row's 7pt of bottom padding. + ->and($elbow['layout'])->toMatchArray(['width' => 31.5, 'height' => 15.5, 'position' => [0.0, 0.0, 0.0, 31.5]]) + // A reply's own actions: the star and Reply, but no Quote. + ->and(refNode($reply, 'reply-to-r1'))->not->toBeNull() + ->and(refNode($reply, 'quote-r1'))->toBeNull() + // The second hangs on a short link in the lane of the reply above it. + ->and(dashColours(nodeByRef($screen, 'thread-reply-r2')))->toContain(config('native-ui.theme.light.lane-4')) + ->and(refNode(nodeByRef($screen, 'thread-reply-r2'), 'thread-elbow'))->toBeNull() + // The last closes the commit's row with its hairline. + ->and(refNode($screen->tree(), 'thread-end-r2'))->not->toBeNull(); + + $screen->tap('thread-reply-r1')->assertNavigatedTo('/log/commits/r1'); +}); + +it('frames a reply avatar in its own lane without shifting the thread', function (string $platform) { + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([threadedJson()])], + 'GET /api/v1/commits/c1/replies' => [pageJson(repliesJson('c1', 1))], + ]); + + $screen = Native::visit('/log', platform: $platform)->tap('replies-c1'); + $ring = findNode(nodeByRef($screen, 'thread-reply-r1'), fn (array $node): bool => ($node['style']['border_color'] ?? null) === config('native-ui.theme.light.lane-4') + && ($node['layout']['width'] ?? null) === 24.0 + && ($node['layout']['height'] ?? null) === 24.0); + + expect($ring)->not->toBeNull() + ->and($ring['style']['border_radius'])->toBeGreaterThanOrEqual(12.0) + ->and($ring['style'])->toMatchArray(['border_width' => 1.0, 'bg_color' => config('native-ui.theme.light.surface')]) + ->and($ring['children'])->toHaveCount(1) + ->and($ring['children'][0]['layout'])->toMatchArray(['width' => 20.0, 'height' => 20.0]); +})->with(['ios', 'android']); + +it('shows ten replies at a time when devnull sends more, and asks for the next page once they all show', function () { + Http::fake(fn (Request $request) => Http::response(match (true) { + str_contains($request->url(), '/log/following') => pageJson([threadedJson(25)]), + // devnull sends 50 a page whatever limit asks for. + str_contains($request->url(), 'cursor=page2') => pageJson(repliesJson('c1', 12, from: 14), path: 'http://devnull.test/api/v1/commits/c1/replies'), + default => pageJson(repliesJson('c1', 13), 'page2', 'http://devnull.test/api/v1/commits/c1/replies'), + })); + + $screen = Native::visit('/log', platform: 'ios') + ->tap('replies-c1') + ->assertSee('Reply r10') + ->assertDontSee('Reply r11') + ->assertSee('Show more'); + + $screen->tap('more-replies-c1')->assertSee('Reply r13')->assertDontSee('Reply r14')->assertNoNavigation(); + expect(sentTo('GET', 'commits/c1/replies'))->toHaveCount(1); + + $screen->tap('more-replies-c1')->assertSee('Reply r23')->assertDontSee('Reply r24'); + $screen->tap('more-replies-c1')->assertSee('Reply r25')->assertDontSee('Show more'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/c1/replies?limit=10'); + Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/c1/replies?cursor=page2&limit=10'); +}); + +it("opens a reply's own replies in place, one step in, hanging off the line from its avatar", function () { + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([threadedJson(2)])], + 'GET /api/v1/commits/c1/replies' => [pageJson([ + replyJson(['id' => 'r1', 'parent_id' => 'c1', 'body' => 'First', 'replies_count' => 12, 'author' => grace()]), + replyJson(['id' => 'r2', 'parent_id' => 'c1', 'body' => 'Second', 'author' => replierJson()]), + ])], + 'GET /api/v1/commits/r1/replies' => [pageJson(repliesJson('r1', 12, 'n', overrides: ['author' => threadAda(), 'replies_count' => 2]))], + ]); + + $screen = Native::visit('/log', platform: 'ios')->tap('replies-c1'); + + // Its replies button is under its actions too. + expect(refNode(nodeByRef($screen, 'actions-r1'), 'replies-r1'))->toBeNull() + ->and(refNode(nodeByRef($screen, 'thread-reply-r1'), 'replies-r1'))->not->toBeNull(); + + $screen->tap('replies-r1') + ->assertNoNavigation() + ->assertSee('Reply n10') + ->assertDontSee('Reply n11'); + + // In order: r1, its replies, its Show more, then r2. + $refs = array_values(array_filter(array_map(fn (array $node): ?string => $node['ref'] ?? null, findNodes($screen->tree(), fn (array $node): bool => preg_match('/^(thread-reply-|more-replies-)/', $node['ref'] ?? '') === 1)))); + expect($refs)->toBe(['thread-reply-r1', ...array_map(fn (int $n): string => "thread-reply-n{$n}", range(1, 10)), 'more-replies-r1', 'thread-reply-r2']); + + $nested = nodeByRef($screen, 'thread-reply-n1'); + $elbow = refNode($nested, 'thread-elbow'); + $spine = fn (array $node): ?array => findNode($node, fn (array $line): bool => ($line['props']['border_style'] ?? null) === 1 && ($line['layout']['position'][3] ?? null) === 75.5 && ! isset($line['layout']['height'])); + + // Its elbow leaves the line down from r1's avatar, in r1's lane, and that line runs on past it to r2. + expect($elbow['layout']['position'][3] ?? null)->toBe(75.5) + ->and(dashColours($elbow))->toBe([config('native-ui.theme.light.lane-4')]) + ->and($spine($nested))->not->toBeNull(); + + // One step in, a reply's replies open its page instead. + $screen->tap('replies-n1')->assertNavigatedTo('/log/commits/n1'); + expect($screen->navigationIntent()->data['replies'])->toBeTrue(); +}); + +it("closes a commit's thread, and the replies opened inside it, from Hide replies", function () { + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([threadedJson(1)])], + 'GET /api/v1/commits/c1/replies' => [pageJson([replyJson(['id' => 'r1', 'parent_id' => 'c1', 'replies_count' => 1, 'author' => grace()])])], + 'GET /api/v1/commits/r1/replies' => [pageJson(repliesJson('r1', 1, 'n', overrides: ['author' => threadAda()]))], + ]); + + $screen = Native::visit('/log', platform: 'ios')->tap('replies-c1')->tap('replies-r1')->assertSee('Reply n1'); + + $screen->tap('replies-c1')->assertDontSee('Reply n1')->assertSee('1 reply'); + + expect($screen->instance()->threads)->toBe([]) + ->and($screen->instance()->fadedRows)->toBe([]); +}); + +it('fades a thread in as it opens and out as it closes', function () { + holdRefreshes(); + keep('log/following', pageJson([threadedJson(1)])); + keep('commits/c1/replies', pageJson(repliesJson('c1', 1))); + serveApi(fn () => Http::response(pageJson([]))); + + $screen = Native::visit('/log', platform: 'ios'); + $content = fn (): array => nodeByRef($screen, 'thread-reply-r1')['children'][0]['children'][1]; + + // Drawn see-through and nudged up first, with the animation it eases in by. + $screen->tap('replies-c1'); + expect($content()['style']['opacity'] ?? null)->toBe(0.0) + ->and($content()['props']['translate-y'] ?? null)->toBe(-8.0) + ->and($content()['props']['animate-duration'] ?? null)->toBe(220.0); + + finishBeats($screen); + expect($content()['style']['opacity'] ?? 1.0)->toBe(1.0) + ->and($content()['props']['translate-y'] ?? null)->toBe(0.0); + + // Closing fades it out, and it goes once that's done. + $screen->tap('replies-c1')->assertSee('1 reply'); + expect($content()['style']['opacity'] ?? null)->toBe(0.0); + + finishBeats($screen); + expect(refNode($screen->tree(), 'thread-reply-r1'))->toBeNull(); +}); + +it('keeps a thread under a commit you star, and stars a reply in it in place', function () { + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([threadedJson(1)])], + 'GET /api/v1/commits/c1/replies' => [pageJson(repliesJson('c1', 1))], + 'POST /api/v1/commits/c1/star' => [['data' => commitJson(['id' => 'c1', 'stars_count' => 1, 'starred' => true])]], + 'POST /api/v1/commits/r1/star' => [['data' => commitJson(['id' => 'r1', 'stars_count' => 1, 'starred' => true, 'author' => grace()])]], + ]); + + $screen = Native::visit('/log', platform: 'ios')->tap('replies-c1')->tap('star-c1')->tap('star-r1'); + + $screen->assertSee('Reply r1'); + expect($screen->instance()->commits[0]->starred)->toBeTrue() + ->and($screen->instance()->threads['c1'][0]->starred)->toBeTrue(); +}); + +it('pops a star you give, as the web does, and leaves it as it was', function () { + holdRefreshes(); + keep('log/following', pageJson([commitJson(['id' => 'c1', 'author' => threadAda(), 'starred' => false])])); + serveApi(fn () => Http::response(['data' => commitJson(['id' => 'c1', 'starred' => true, 'stars_count' => 1, 'author' => threadAda()])])); + + $screen = Native::visit('/log', platform: 'ios'); + $star = fn (): array => findNode(nodeByRef($screen, 'star-c1'), fn (array $node): bool => ($node['type'] ?? null) === 'icon'); + + expect($star()['props'])->not->toHaveKey('scale'); + + $screen->tap('star-c1'); + expect($screen->instance()->popping)->toBe(['star-c1' => Pop::Ready]) + ->and($star()['props'])->toMatchArray(['scale' => 1.0, 'animate-duration' => 150.0]); + + finishBeats($screen, 1); + expect($star()['props'])->toMatchArray(['scale' => 1.35, 'rotate' => -12.0]); + + finishBeats($screen, 1); + expect($star()['props'])->toMatchArray(['scale' => 1.0, 'rotate' => 0.0, 'animate-easing' => 'spring']); + + finishBeats($screen); + expect($screen->instance()->popping)->toBe([]) + ->and($star()['props'])->not->toHaveKey('scale'); +}); + +it("doesn't pop a star you take back, as the web doesn't", function () { + holdRefreshes(); + keep('log/following', pageJson([commitJson(['id' => 'c1', 'author' => threadAda(), 'starred' => true, 'stars_count' => 1])])); + serveApi(fn () => Http::response(['data' => commitJson(['id' => 'c1', 'starred' => false, 'stars_count' => 0, 'author' => threadAda()])])); + + $screen = Native::visit('/log', platform: 'ios')->tap('star-c1'); + + expect($screen->instance()->popping)->toBe([]); +}); + +it("runs the commit's rail on past its thread when the author's run carries on below", function () { + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([threadedJson(1, ['id' => 'c2']), commitJson(['id' => 'c1', 'author' => threadAda()])])], + 'GET /api/v1/commits/c2/replies' => [pageJson(repliesJson('c2', 1))], + ]); + + $screen = Native::visit('/log', platform: 'ios')->tap('replies-c2'); + $lane = config('native-ui.theme.light.lane-1'); + $solidRail = fn (array $node): bool => ($node['layout']['width'] ?? null) === 2.0 && ($node['style']['bg_color'] ?? null) === $lane; + + expect(findNode(nodeByRef($screen, 'thread-reply-r1'), $solidRail))->not->toBeNull() + ->and(refNode(nodeByRef($screen, 'commit-c2'), 'end-dot'))->toBeNull() + ->and(railNode($screen, 'commit-c1'))->toBe('dot'); +}); + +it('ends a commit alone in its run with a dot inside its action row, level with the actions', function (string $platform) { + Http::fake(['devnull.test/*' => Http::response(pageJson([ + commitJson(['id' => 'c3', 'author' => threadAda()]), + commitJson(['id' => 'c2', 'author' => threadAda()]), + commitJson(['id' => 'c1', 'author' => grace(), 'replies_count' => 4]), + commitJson(['id' => 'c0', 'author' => threadAda(), 'body' => str_repeat('A long body that wraps. ', 20)]), + ]))]); + + $screen = Native::visit('/log', platform: $platform); + + expect(railNode($screen, 'commit-c3'))->toBe('avatar') + ->and(railNode($screen, 'commit-c2'))->toBe('dot') + ->and(refNode(nodeByRef($screen, 'commit-c3'), 'end-dot'))->toBeNull() + ->and(refNode(nodeByRef($screen, 'commit-c2'), 'end-dot'))->toBeNull(); + + foreach (['c1', 'c0'] as $id) { + $dot = refNode(nodeByRef($screen, "actions-{$id}"), 'end-dot'); + + // Centred in the 36pt row, at the rail's x: the row starts 56pt in, the dot's middle is at 32. + expect($dot)->not->toBeNull() + ->and($dot['layout'])->toMatchArray(['width' => 18.0, 'height' => 18.0]) + ->and($dot['layout']['position'][0])->toBe(9.0) + ->and($dot['layout']['position'][3])->toBe(-33.0) + ->and(nodeByRef($screen, "actions-{$id}")['layout']['height'])->toBe(36.0); + } +})->with(['ios', 'android']); + +it('stops the rail at the end dot, past the replies line, and carries it on in dashes once the replies open', function () { + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([commitJson(['id' => 'c1', 'author' => grace(), 'replies_count' => 1])])], + 'GET /api/v1/commits/c1/replies' => [pageJson(repliesJson('c1', 1, overrides: ['author' => threadAda()]))], + ]); + + $screen = Native::visit('/log', platform: 'ios'); + $lane = config('native-ui.theme.light.lane-4'); + $tail = fn (): ?array => findNode(nodeByRef($screen, 'commit-c1'), fn (array $node): bool => ($node['layout']['width'] ?? null) === 2.0 && ($node['style']['bg_color'] ?? null) === $lane); + + // Closed: 7pt padding with the hairline, the replies line (4pt gap and 36pt) and half the action row (18pt) put + // the dot's middle 65pt up, and the rail stops 2pt into its ring, 9pt above that. + expect($tail()['layout']['position'][2])->toBe(72.0); + + $screen->tap('replies-c1'); + + // Open: the same 7pt padding without the hairline, so the dot stays put, and the dashes run on from the dot's foot + // to the row's, where the first reply's elbow takes over. + $dashes = findNode(nodeByRef($screen, 'commit-c1'), fn (array $node): bool => ($node['props']['border_style'] ?? null) === 1 && ($node['layout']['position'][2] ?? null) === 0.0); + + expect($tail()['layout']['position'][2])->toBe(72.0) + ->and($dashes['layout']['height'] ?? null)->toBe(56.0) + ->and(refNode(nodeByRef($screen, 'thread-reply-r1'), 'thread-elbow')['layout']['position'][0])->toBe(0.0); +}); + +it("keeps a commit's row the same height with its replies shut, opening, open and closing, so the list never moves it", function (string $platform) { + holdRefreshes(); + keep('log/following', pageJson([commitJson(['id' => 'c1', 'author' => grace(), 'replies_count' => 2])])); + keep('commits/c1/replies', pageJson(repliesJson('c1', 2, overrides: ['author' => threadAda()]))); + serveApi(fn () => Http::response(pageJson([]))); + + $screen = Native::visit('/log', platform: $platform); + $content = fn (): array => nodeByRef($screen, 'commit-c1')['children'][0]; + $heights = fn (): array => [ + $content()['layout'], + nodeByRef($screen, 'actions-c1')['layout'], + nodeByRef($screen, 'replies-c1')['layout'], + ]; + $hairline = fn (): ?float => $content()['props']['border_b'] ?? null; + + $shut = $heights(); + + // 12pt above, and under the replies line the 6pt the action row leaves and the hairline's 1pt. + expect($shut[0]['padding'])->toEqual([12, 16, 7, 0]) + ->and($hairline())->toBe(1.0); + + $screen->tap('replies-c1'); + expect($heights())->toBe($shut); + + finishBeats($screen); + expect($heights())->toBe($shut) + ->and($hairline())->toBeNull() + // The first reply takes the 7pt off its 10pt top, so the thread sits where it did; the next keeps its 10pt. + ->and(nodeByRef($screen, 'thread-reply-r1')['children'][0]['children'][1]['children'][0]['layout']['padding'][0])->toEqual(3) + ->and(nodeByRef($screen, 'thread-reply-r2')['children'][0]['children'][1]['children'][0]['layout']['padding'][0])->toEqual(10); + + $screen->tap('replies-c1')->assertSee('2 replies'); + expect($heights())->toBe($shut); + + finishBeats($screen); + expect(refNode($screen->tree(), 'thread-reply-r1'))->toBeNull() + ->and($heights())->toBe($shut) + ->and($hairline())->toBe(1.0); +})->with(['ios', 'android']); + +it('drops a reply that went from an open thread when the log refreshes, and keeps the pages loaded after the first', function () { + $gone = false; + + Http::fake(function (Request $request) use (&$gone) { + return Http::response(match (true) { + str_contains($request->url(), '/log/following') => pageJson([threadedJson(12)]), + str_contains($request->url(), 'cursor=page2') => pageJson(repliesJson('c1', 2, from: 11), path: 'http://devnull.test/api/v1/commits/c1/replies'), + default => pageJson(array_values(array_filter(repliesJson('c1', 10), fn (array $reply): bool => ! ($gone && $reply['id'] === 'r3'))), 'page2', 'http://devnull.test/api/v1/commits/c1/replies'), + }); + }); + + $screen = Native::visit('/log', platform: 'ios')->tap('replies-c1')->tap('more-replies-c1')->assertSee('Reply r12'); + + $gone = true; + $screen->call('load'); + + expect(array_map(fn ($reply): string => $reply->id, $screen->instance()->threads['c1']))->toBe(['r1', 'r2', ...array_map(fn (int $n): string => "r{$n}", range(4, 12))]); +}); + +it('opens a thread at once from the replies kept last time, and refreshes it behind', function () { + holdRefreshes(); + keep('log/following', pageJson([threadedJson(2)])); + keep('commits/c1/replies', pageJson([replyJson(['id' => 'r1', 'parent_id' => 'c1', 'body' => 'First kept']), replyJson(['id' => 'r2', 'parent_id' => 'c1'])])); + serveApi(fn () => Http::response(pageJson([]))); + + $screen = Native::visit('/log', platform: 'ios'); + $requests = count(Http::recorded()); + + $screen->tap('replies-c1')->assertSee('First kept'); + + expect(count(Http::recorded()))->toBe($requests) + ->and(refreshesSent($screen))->toBeGreaterThan(1); +}); + +/** + * Runs the Beats a screen is waiting on, $times rounds of them or until none are left. + */ +function finishBeats(TestableComponent $screen, int $times = PHP_INT_MAX): TestableComponent +{ + $done = []; + + for ($round = 0; $round < $times; $round++) { + $beats = array_filter($screen->bridge()->callsTo('AsyncTask.Dispatch'), function (array $call) use (&$done): bool { + $payload = AsyncTaskTransport::readPayload($call['params']['id']); + + return ! isset($done[$call['params']['id']]) && $payload !== null && str_contains($payload, 'App\\Devnull\\Beat'); + }); + + if ($beats === []) { + break; + } + + foreach ($beats as $call) { + $done[$call['params']['id']] = true; + $screen->emitNative(AsyncTaskFinished::class, ['id' => $call['params']['id'], 'result' => true]); + } + } + + return $screen; +} diff --git a/tests/Feature/Screens/LogWindowTest.php b/tests/Feature/Screens/LogWindowTest.php index 539f02ba..98546ae2 100644 --- a/tests/Feature/Screens/LogWindowTest.php +++ b/tests/Feature/Screens/LogWindowTest.php @@ -7,16 +7,25 @@ config(['devnull.url' => 'http://devnull.test']); signIn(); - // A day marker and 300 commits, with a reply under c220, then the row loading the next page. + // A day marker and 300 commits, with a reply under c220 (opened by visit()), then the row loading the next page. fakeApi([ + 'GET /api/v1/commits/c220/replies' => [pageJson([replyJson(['id' => 'r220', 'parent_id' => 'c220'])])], 'GET /api/v1/log/following' => [pageJson(array_map(fn (int $n): array => commitJson([ 'id' => "c{$n}", 'body' => "Commit {$n}", - ...($n === 220 ? ['replies_count' => 1, 'reply_preview' => ['data' => [replyJson(['id' => 'r220', 'parent_id' => 'c220'])], 'next_cursor' => null]] : []), + ...($n === 220 ? ['replies_count' => 1] : []), ]), range(0, 299)), nextCursor: 'more')], ]); }); +/** + * The log, with c220's reply opened under it. + */ +function visitWithThread(): TestableComponent +{ + return Native::visit('/log')->call('toggleReplies', 'c220'); +} + /** * Each row of the log's list as its ref, or "placeholder". * @@ -41,7 +50,7 @@ function windowRowIds(TestableComponent $screen): array } it('draws the first rows and those near the top, and puts placeholders in the rest', function () { - $rows = windowRows(Native::visit('/log')); + $rows = windowRows(visitWithThread()); // The first 151 rows of the timeline: the day marker and c0 to c149. expect($rows)->toHaveCount(303) @@ -53,7 +62,7 @@ function windowRowIds(TestableComponent $screen): array }); it('draws the rows around the ones on screen as you scroll, each keeping its place in the list', function () { - $screen = Native::visit('/log'); + $screen = visitWithThread(); $ids = windowRowIds($screen); // On screen: c229 to c234, which come after c220 and its reply. Drawn: the first ten rows of the timeline, and @@ -71,21 +80,21 @@ function windowRowIds(TestableComponent $screen): array it('draws more rows above the screen once you scroll back up and stop', function () { // Down to c229, then back up to c199: drawn from 150 above c199 (c49). - $rows = windowRows(Native::visit('/log')->call('showRows', 231, 236)->call('showRows', 200, 205)->call('scrollEnded', 200, 205)); + $rows = windowRows(visitWithThread()->call('showRows', 231, 236)->call('showRows', 200, 205)->call('scrollEnded', 200, 205)); expect($rows[49])->toBe('placeholder') ->and($rows[50])->toBe('commit-c49'); }); it('only asks the log you are on where it is scrolled to, and when it stops', function () { - $screen = Native::visit('/log'); + $screen = visitWithThread(); expect(showingLog($screen)['props'])->toHaveKeys(['on_visible_range', 'on_scroll_end']) ->and(nodeByRef($screen, 'log-latest')['props'] ?? [])->not->toHaveKey('on_visible_range')->not->toHaveKey('on_scroll_end'); }); it('draws the top again when the log goes back to the top of a new list', function () { - $screen = Native::visit('/log')->call('showRows', 231, 236)->call('show', 'following'); + $screen = visitWithThread()->call('showRows', 231, 236)->call('show', 'following'); $rows = windowRows($screen); expect($rows[21])->toBe('commit-c20') diff --git a/tests/Feature/Screens/MentionSuggestionsTest.php b/tests/Feature/Screens/MentionSuggestionsTest.php new file mode 100644 index 00000000..04a7eb65 --- /dev/null +++ b/tests/Feature/Screens/MentionSuggestionsTest.php @@ -0,0 +1,54 @@ + 'body', 'start' => 0, 'query' => 'ada', 'text' => '@ada']; + + /** @var list */ + public array $mentionPeople = []; + + /** @var list */ + public array $mentionOrganizations = []; + + /** @var array */ + public array $options = []; + + public function mount(int $rows = 8, array $options = []): void + { + $this->mentionPeople = array_map(fn (int $n): User => User::fromArray(userJson(['id' => "u{$n}", 'handle' => "ada{$n}", 'name' => "Ada {$n}"])), range(1, $rows)); + $this->options = $options; + } + + public function pickMention(string $field, string $username): void {} + + public function render(): View + { + return view('fixtures::mention-suggestions', ['options' => $this->options]); + } +} + +beforeEach(fn () => view()->addNamespace('fixtures', base_path('tests/Fixtures/views'))); + +it('scrolls more than six rows inside the list by default', function () { + $screen = Native::test(MentionSuggestionsFixture::class, ['rows' => 8]); + + expect(childRefs($screen, 'mention-suggestions'))->toBe(['mention-scroll']) + ->and(nodeByRef($screen, 'mention-scroll')['type'])->toBe('scroll_view'); +}); + +it('draws every row with no scroll view inside when the caller scrolls the list itself', function () { + $screen = Native::test(MentionSuggestionsFixture::class, ['rows' => 8, 'options' => ['scrolls' => false]]); + + expect(rendersRef($screen, 'mention-scroll'))->toBeFalse() + ->and(childRefs($screen, 'mention-suggestions'))->toBe(array_map(fn (int $n): string => "mention-ada{$n}", range(1, 8))) + ->and(nodeByRef($screen, 'mention-ada8')['children'][0]['layout']['height'] ?? null)->toBeNull(); +}); diff --git a/tests/Feature/Screens/NestedRepliesTest.php b/tests/Feature/Screens/NestedRepliesTest.php new file mode 100644 index 00000000..57fa618e --- /dev/null +++ b/tests/Feature/Screens/NestedRepliesTest.php @@ -0,0 +1,342 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * A commit page for c2 whose replies chain five deep: r1 answers c2, r2 answers r1, and so on, each from someone + * other than the one they answer, so none of them carries a thread on. + */ +function fakeDeepThread(): void +{ + $handles = ['grace', 'linus', 'alan', 'edsger', 'ken']; + $reply = fn (int $depth): array => replyJson([ + 'id' => "r{$depth}", + 'parent_id' => $depth === 1 ? 'c2' : 'r'.($depth - 1), + 'body' => "Reply at depth {$depth}", + 'replies_count' => $depth < 5 ? 1 : 0, + 'author' => userJson(['handle' => $handles[$depth - 1], 'name' => ucfirst($handles[$depth - 1]), 'lane' => $depth]), + ]); + + Http::fake(function (Request $request) use ($reply) { + $path = parse_url($request->url(), PHP_URL_PATH); + + return match (true) { + $path === '/api/v1/commits/c2' => Http::response(commitPageJson(commitJson(['id' => 'c2', 'body' => 'The focused commit', 'replies_count' => 1]))), + $path === '/api/v1/commits/c2/related' => Http::response(['data' => []]), + $path === '/api/v1/commits/c2/replies' => Http::response(pageJson([$reply(1)])), + (bool) preg_match('#^/api/v1/commits/r(\d)/replies$#', $path, $match) => Http::response(pageJson((int) $match[1] < 5 ? [$reply((int) $match[1] + 1)] : [])), + default => Http::response(['message' => 'No fake.'], 404), + }; + }); +} + +it('opens replies of replies in place on a commit page, as deep as they go, without leaving the page', function () { + fakeDeepThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true])->assertSee('Reply at depth 1'); + + foreach (range(1, 4) as $depth) { + $screen->tap("replies-r{$depth}")->assertSee('Reply at depth '.($depth + 1)); + } + + $screen->assertNoNavigation()->assertSee('Reply at depth 5'); + + // Hiding a reply's replies takes the ones opened under them away too. + $screen->tap('replies-r2')->assertDontSee('Reply at depth 3'); + finishRefreshes($screen)->assertDontSee('Reply at depth 5'); + + // Tapping a reply itself moves the page to it. + $screen->tap('thread-reply-r2')->assertNoNavigation()->assertSet('id', 'r2'); +}); + +it('steps replies in up to the third level, and lines deeper ones up under it saying who they answer', function () { + fakeDeepThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true]); + + foreach (range(1, 4) as $depth) { + $screen->tap("replies-r{$depth}"); + } + + // The left padding of the row the reply's avatar sits in, past the commit's 64pt gutter. + $indent = fn (string $id): float => (float) (findNode(nodeByRef($screen, "thread-reply-{$id}"), fn (array $node): bool => ($node['type'] ?? null) === 'row' && isset($node['layout']['padding']))['layout']['padding'][3] ?? 0); + $elbow = fn (string $id): bool => findNode(nodeByRef($screen, "thread-reply-{$id}"), fn (array $node): bool => ($node['ref'] ?? null) === 'thread-elbow') !== null; + + expect([$indent('r1'), $indent('r2'), $indent('r3'), $indent('r4'), $indent('r5')])->toEqual([0, 32, 64, 64, 64]) + ->and([$elbow('r1'), $elbow('r2'), $elbow('r3'), $elbow('r4'), $elbow('r5')])->toBe([true, true, true, false, false]) + ->and(rendersRef($screen, 'replying-to-r3'))->toBeFalse(); + + $screen->assertSee('replying to @alan')->assertSee('replying to @edsger'); +}); + +it('moves the page to a reply in its tree rather than pushing another, keeping what was open', function () { + fakeDeepThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true]); + + foreach (range(1, 3) as $depth) { + $screen->tap("replies-r{$depth}"); + } + + $screen->tap('thread-reply-r3') + ->assertNoNavigation() + ->assertSet('id', 'r3') + ->assertSet('scrollTarget', 3); + + // The reply is the commit the page is on, under the commits above it, with its replies showing at once. + expect(childRefs($screen, 'thread-scroll'))->toBe(['commit-c2', 'commit-r1', 'commit-r2', 'focused-commit', 'thread-reply-r4', 'reply-bar-clearance']) + ->and(nodeByRef($screen, 'thread-scroll')['props']['auto_scroll_to'])->toBe(3); + + // Back up at the top, the reply the page was on is still open under its parents. + $screen->tap('commit-c2') + ->assertNoNavigation() + ->assertSet('id', 'c2') + ->assertSet('scrollTarget', 0) + ->assertSee('Reply at depth 4'); + + expect(childRefs($screen, 'thread-scroll'))->toBe(['focused-commit', 'thread-reply-r1', 'thread-reply-r2', 'thread-reply-r3', 'thread-reply-r4', 'reply-bar-clearance']); +}); + +it('answers a reply in the tree from the bar, on the same page', function () { + fakeDeepThread(); + + Native::visit('/log/commits/c2', ['replies' => true]) + ->call('replyTo', 'r1') + ->assertNoNavigation() + ->assertSet('id', 'r1') + ->assertSet('focusReply', true); +}); + +it('still pushes a page for a commit outside the tree', function () { + fakeDeepThread(); + + Native::visit('/log/commits/c2', ['replies' => true]) + ->call('openCommit', 'q9') + ->assertNavigatedTo('/log/commits/q9'); +}); + +it('opens at the top with no scroll asked for until the page moves', function () { + fakeDeepThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true]); + + expect(nodeByRef($screen, 'thread-scroll')['props'] ?? [])->not->toHaveKey('auto_scroll_to'); +}); + +it('keeps the commit row and the scroll view the same nodes when the page moves', function () { + fakeDeepThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true]); + $screen->tap('replies-r1'); + $screen->tap('thread-reply-r2'); + $scroller = nodeByRef($screen, 'thread-scroll')['id']; + $ancestor = nodeByRef($screen, 'commit-c2')['id']; + + // The commit the page moves to keeps the node it had above the focus, so its row slides into place. The scroll + // view keeps its node too: a new one would make every row in it new. + $screen->tap('commit-c2')->assertSet('id', 'c2'); + + expect(nodeByRef($screen, 'focused-commit')['id'])->toBe($ancestor) + ->and(nodeByRef($screen, 'thread-scroll')['id'])->toBe($scroller); +}); + +it('animates the move and asks again for a row it went to before', function () { + LayoutAnimation::skipUnlessSupported(); + fakeDeepThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true]); + $props = fn (): array => nodeByRef($screen, 'thread-scroll')['props']; + + expect($props())->toHaveKey('animate_layout', true) + ->and($props())->toHaveKey('auto_scroll_animated', true) + ->and($props())->toHaveKey('auto_scroll_token', '0'); + + $screen->tap('replies-r1'); + $screen->tap('thread-reply-r1')->assertSet('scrollTarget', 1); + $screen->tap('commit-c2')->assertSet('scrollTarget', 0); + $first = $props()['auto_scroll_token']; + $screen->tap('thread-reply-r1'); + $screen->tap('commit-c2')->assertSet('scrollTarget', 0); + + // The same row as two moves ago, under a new token, so the scroll view goes back to it. + expect($props()['auto_scroll_to'])->toBe(0) + ->and($props()['auto_scroll_token'])->not->toBe($first); +}); + +/** + * A commit page for c2, which answers c1. c1 has another reply, x1, and x1 has one of its own, x2. c2 has one reply, r1. + */ +function fakeAncestorThread(): void +{ + $person = fn (string $handle, int $lane): array => userJson(['handle' => $handle, 'name' => ucfirst($handle), 'lane' => $lane]); + $c1 = commitJson(['id' => 'c1', 'body' => 'The commit above', 'replies_count' => 2, 'author' => $person('ada', 1)]); + $c2 = commitJson(['id' => 'c2', 'parent_id' => 'c1', 'body' => 'The focused commit', 'replies_count' => 1, 'author' => $person('grace', 2)]); + $x1 = replyJson(['id' => 'x1', 'parent_id' => 'c1', 'body' => 'Another reply above', 'replies_count' => 1, 'author' => $person('linus', 4)]); + $x2 = replyJson(['id' => 'x2', 'parent_id' => 'x1', 'body' => 'A reply to the other reply', 'author' => $person('alan', 5)]); + $r1 = replyJson(['id' => 'r1', 'parent_id' => 'c2', 'body' => 'A reply below', 'author' => $person('ken', 6)]); + + Http::fake(function (Request $request) use ($c1, $c2, $x1, $x2, $r1) { + $path = parse_url($request->url(), PHP_URL_PATH); + + return match ($path) { + '/api/v1/commits/c2' => Http::response(commitPageJson($c2, [$c1])), + '/api/v1/commits/c1' => Http::response(commitPageJson($c1)), + '/api/v1/commits/r1' => Http::response(commitPageJson($r1, [$c1, $c2])), + '/api/v1/commits/c1/related', '/api/v1/commits/c2/related', '/api/v1/commits/r1/related' => Http::response(['data' => []]), + '/api/v1/commits/c1/replies' => Http::response(pageJson([$c2, $x1])), + '/api/v1/commits/c2/replies' => Http::response(pageJson([$r1])), + '/api/v1/commits/x1/replies' => Http::response(pageJson([$x2])), + '/api/v1/commits/r1/replies', '/api/v1/commits/x2/replies' => Http::response(pageJson([])), + default => Http::response(['message' => 'No fake.'], 404), + }; + }); +} + +it('opens the replies of a commit above the commit in place, leaving out the one on the way down', function () { + fakeAncestorThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true]); + + // c1 has two replies, and one of them is the commit the page is on, so its button counts the other. + expect(nodeByRef($screen, 'replies-c1')['props']['a11y_label'] ?? null)->toBe('1 reply'); + + $screen->tap('replies-c1')->assertNoNavigation()->assertSee('Another reply above'); + + // The other reply opens under c1, and the commit the page is on shows once, as the commit. + expect(childRefs($screen, 'thread-scroll'))->toBe(['commit-c1', 'thread-reply-x1', 'focused-commit', 'thread-reply-r1', 'reply-bar-clearance']) + // c1 gives up its hairline to its replies, and the last of them ends on it above the commit. The commit's own + // replies end the page, so they end on none. + ->and(rendersRef($screen, 'thread-end-x1'))->toBeTrue() + ->and(rendersRef($screen, 'thread-end-r1'))->toBeFalse(); + + // Its replies open in place too, at any depth, and the hairline moves down under the last of them. + $screen->tap('replies-x1')->assertNoNavigation()->assertSee('A reply to the other reply'); + + expect(rendersRef($screen, 'thread-end-x2'))->toBeTrue() + ->and(rendersRef($screen, 'thread-end-x1'))->toBeFalse(); + + $screen->tap('replies-c1'); + finishRefreshes($screen)->assertDontSee('Another reply above')->assertDontSee('A reply to the other reply'); + + expect(childRefs($screen, 'thread-scroll'))->toBe(['commit-c1', 'focused-commit', 'thread-reply-r1', 'reply-bar-clearance']); +}); + +it('folds the replies of the commits above when the page moves down to a reply', function () { + fakeAncestorThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true]); + $screen->tap('replies-c1')->assertSee('Another reply above'); + $screen->tap('thread-reply-r1')->assertSet('id', 'r1')->assertSet('scrollTarget', 2)->assertDontSee('Another reply above'); + + // c1 is back to its button, still leaving out c2 on the way down. r1 has no replies, so "No replies yet" follows it. + expect(childRefs($screen, 'thread-scroll'))->toBe(['commit-c1', 'commit-c2', 'focused-commit', null, 'reply-bar-clearance']) + ->and(nodeByRef($screen, 'replies-c1')['props']['a11y_label'] ?? null)->toBe('1 reply') + ->and(rendersRef($screen, 'replies-c2'))->toBeFalse(); + + // Opening them again later doesn't scroll the page. + $screen->tap('replies-c1')->assertSee('Another reply above')->assertSet('scrollTarget', 2); +}); + +it('folds the replies of the commit the page was on when it moves down to one of them, and opens them again moving back up', function () { + fakeAncestorThread(); + + $screen = Native::visit('/log/commits/c1', ['replies' => true])->assertSee('Another reply above'); + $screen->tap('thread-reply-c2')->assertNoNavigation()->assertSet('id', 'c2')->assertDontSee('Another reply above'); + + expect(childRefs($screen, 'thread-scroll'))->toBe(['commit-c1', 'focused-commit', 'thread-reply-r1', 'reply-bar-clearance']) + ->and(nodeByRef($screen, 'replies-c1')['props']['a11y_label'] ?? null)->toBe('1 reply'); + + // Back up on c1, its replies show as the commit's do, with c2's still open under it. + $screen->tap('commit-c1')->assertSet('id', 'c1')->assertSee('Another reply above')->assertSee('A reply below'); +}); + +it('opens on a reply with the replies of the commits above it folded', function () { + fakeAncestorThread(); + + $screen = Native::visit('/log/commits/r1')->call('showEarlier')->assertDontSee('Another reply above'); + + expect(nodeByRef($screen, 'replies-c1')['props']['a11y_label'] ?? null)->toBe('1 reply') + ->and(rendersRef($screen, 'replies-c2'))->toBeFalse() + ->and($screen->get('threads'))->toBe([]); +}); + +it('keeps the replies of the commits on the line open when the replies of one above them close', function () { + fakeDeepThread(); + + $screen = Native::visit('/log/commits/c2', ['replies' => true]); + $screen->tap('replies-r1'); + $screen->tap('replies-r2'); + $screen->tap('thread-reply-r3')->assertSet('id', 'r3'); + + // The commits above r3 fold their replies. Each has one, the one on the way down, so none of them has a button. + expect($screen->get('threads'))->toBe([]) + ->and(rendersRef($screen, 'replies-c2'))->toBeFalse() + ->and(rendersRef($screen, 'replies-r1'))->toBeFalse(); + + // Opened again, closing c2's replies leaves r1's be, since r1 draws a row of its own. + $screen->call('toggleReplies', 'c2'); + $screen->call('toggleReplies', 'r1'); + expect($screen->get('threads'))->toHaveKeys(['c2', 'r1']); + + $screen->call('toggleReplies', 'c2'); + finishRefreshes($screen); + + expect($screen->get('threads'))->toHaveKey('r1')->not->toHaveKey('c2'); +}); + +/** + * c3 answers c2, which answers c1, shaped like devnull's API: the ancestors on c3's page come without their counts, + * since CommitAncestorsQuery doesn't load them. Only a commit's own page says how many replies it has. c2 has two + * besides c3, and c1 has one besides c2. Neither page was opened before. + */ +function fakeUncountedAncestors(): void +{ + $person = fn (string $handle, int $lane): array => userJson(['handle' => $handle, 'name' => ucfirst($handle), 'lane' => $lane]); + $uncounted = fn (array $commit): array => array_diff_key($commit, array_flip(['replies_count', 'stars_count'])); + $c1 = commitJson(['id' => 'c1', 'body' => 'The first commit', 'replies_count' => 2, 'author' => $person('ada', 1)]); + $c2 = commitJson(['id' => 'c2', 'parent_id' => 'c1', 'body' => 'The commit above', 'replies_count' => 3, 'author' => $person('grace', 2)]); + $c3 = commitJson(['id' => 'c3', 'parent_id' => 'c2', 'body' => 'The focused commit', 'author' => $person('ken', 3)]); + $y1 = replyJson(['id' => 'y1', 'parent_id' => 'c1', 'body' => 'Another reply to the first', 'author' => $person('linus', 4)]); + $x1 = replyJson(['id' => 'x1', 'parent_id' => 'c2', 'body' => 'Another reply above', 'author' => $person('alan', 5)]); + $x2 = replyJson(['id' => 'x2', 'parent_id' => 'c2', 'body' => 'One more reply above', 'author' => $person('edsger', 6)]); + + Http::fake(function (Request $request) use ($uncounted, $c1, $c2, $c3, $x1, $x2, $y1) { + return match (parse_url($request->url(), PHP_URL_PATH)) { + '/api/v1/commits/c3' => Http::response(commitPageJson($c3, [$uncounted($c1), $uncounted($c2)])), + '/api/v1/commits/c2' => Http::response(commitPageJson($c2, [$uncounted($c1)])), + '/api/v1/commits/c1' => Http::response(commitPageJson($c1)), + '/api/v1/commits/c1/related', '/api/v1/commits/c2/related', '/api/v1/commits/c3/related' => Http::response(['data' => []]), + '/api/v1/commits/c1/replies' => Http::response(pageJson([$c2, $y1])), + '/api/v1/commits/c2/replies' => Http::response(pageJson([$c3, $x1, $x2])), + '/api/v1/commits/c3/replies', '/api/v1/commits/x1/replies', '/api/v1/commits/x2/replies', '/api/v1/commits/y1/replies' => Http::response(pageJson([])), + default => Http::response(['message' => 'No fake.'], 404), + }; + }); +} + +it('shows the folded replies of a commit above that was never opened, from that commit\'s own page', function () { + fakeUncountedAncestors(); + + $screen = finishRefreshes(Native::visit('/log/commits/c3')); + + // c2's page says it has three replies, and c3 is one of them, on the way down. + expect(nodeByRef($screen, 'replies-c2')['props']['a11y_label'] ?? null)->toBe('2 replies') + ->and($screen->get('threads'))->toBe([]); + + $screen->tap('replies-c2')->assertNoNavigation()->assertSee('Another reply above')->assertSee('One more reply above'); + + // The earlier commits get theirs once they show. + expect(rendersRef($screen, 'replies-c1'))->toBeFalse(); + + finishRefreshes($screen->call('showEarlier')); + + expect(nodeByRef($screen, 'replies-c1')['props']['a11y_label'] ?? null)->toBe('1 reply'); +}); diff --git a/tests/Feature/Screens/NotificationsTest.php b/tests/Feature/Screens/NotificationsTest.php index b160b4ef..06cef232 100644 --- a/tests/Feature/Screens/NotificationsTest.php +++ b/tests/Feature/Screens/NotificationsTest.php @@ -84,6 +84,13 @@ function ringColour(TestableComponent $screen, string $id): ?string Native::visit('/notifications')->tap('group-n-starred')->tap('group-actor-older')->assertNavigatedTo('/notifications/users/linus'); }); +it('opens the page of an organization that replied to you, from its name', function () { + $organization = [...personJson('dev-null-sh', '/dev/null'), 'type' => 'organization']; + fakeApi(['GET /api/v1/notifications' => [inboxJson([notificationJson('replied', ['actor' => $organization, 'actors' => [$organization]])])]]); + + Native::visit('/notifications')->tap('actor-name-n-replied')->assertNavigatedTo('/notifications/organizations/dev-null-sh'); +}); + it('does not navigate to an actor absent from the displayed notifications', function () { fakeApi(['GET /api/v1/notifications' => [inboxJson([])]]); Native::visit('/notifications')->call('openActor', 'nobody')->assertNoNavigation(); diff --git a/tests/Feature/Screens/OrganizationCommitsTest.php b/tests/Feature/Screens/OrganizationCommitsTest.php new file mode 100644 index 00000000..d540573e --- /dev/null +++ b/tests/Feature/Screens/OrganizationCommitsTest.php @@ -0,0 +1,256 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * NativePHP as `GET /me` lists an organization you're in. + * + * @return array + */ +function nativephpMembershipJson(): array +{ + return [ + 'type' => 'organization', + 'id' => 'o-nativephp', + 'role' => 'member', + 'handle' => 'nativephp', + 'name' => 'NativePHP', + 'avatar_url' => 'https://avatars.githubusercontent.com/u/7?v=4', + 'github_url' => 'https://github.com/nativephp', + 'html_url' => 'http://devnull.test/@nativephp', + 'lane' => 5, + ]; +} + +/** + * A commit from NativePHP, posted by whichever member it was: devnull never says who. + * + * @param array $overrides + * @return array + */ +function nativephpCommitJson(array $overrides = []): array +{ + return commitJson(['author' => ['type' => 'organization', 'id' => 'o-nativephp', 'handle' => 'nativephp', 'name' => 'NativePHP', 'lane' => 5], ...$overrides]); +} + +/** + * Makes you a member of NativePHP, as the last `GET /me` said. + */ +function joinNativephp(): void +{ + app(Account::class)->rememberOrganizations(CurrentUser::fromArray(currentUserJson(['organizations' => [nativephpMembershipJson()]]))->organizations); +} + +/** + * The Log showing NativePHP's commit c1, with the API answering $routes besides. + * + * @param array $commit + * @param array $routes + */ +function nativephpCommitOnLog(array $commit = [], array $routes = []): TestableComponent +{ + serveApi([ + 'GET /api/v1/log/following' => [pageJson([nativephpCommitJson(['id' => 'c1', 'body' => 'NativePHP ships', ...$commit])])], + ...$routes, + ]); + + return Native::visit('/log', platform: 'ios'); +} + +it('treats an organization\'s commit as yours when you\'re a member, whoever posted it', function () { + joinNativephp(); + app(Account::class)->rememberPasteis(new Pasteis(Pasteis::Daily, CarbonImmutable::now()->addDay())); + + $screen = nativephpCommitOnLog(['stars_count' => 2]); + + // Delete, as for your own, but no Pin: devnull pins to a person's profile. No Report, as devnull won't take one. + expect(menuItems($screen, 'more-c1'))->toBe([ + ['share-c1', 'Share link', 'custom:link'], + 'divider', + ['delete-c1', 'Delete commit', 'custom:trash-2'], + ]) + // You can't star it, so its star is the count, as on your own. + ->and(rendersRef($screen, 'star-c1'))->toBeFalse() + ->and(nodeByRef($screen, 'star-count-c1')['props']['a11y_label'])->toBe('2 stars, show who starred') + // An organization's commit takes no pastéis from anyone, so the web shows none. + ->and(rendersRef($screen, 'pastel-c1'))->toBeFalse() + ->and(rendersRef($screen, 'pastel-count-c1'))->toBeFalse(); + + $screen->call('toggleStar', 'c1') + ->call('givePastel', 'c1') + ->call('reportCommit', 'c1') + ->call('togglePin', 'c1') + ->assertSet('sheetOpen', false); + + Http::assertNotSent(fn (Request $request): bool => $request->method() !== 'GET'); +}); + +it('lets a member delete an organization\'s commit they didn\'t post', function () { + joinNativephp(); + $deleted = false; + + serveApi(function (Request $request) use (&$deleted) { + return match ($request->method().' '.parse_url($request->url(), PHP_URL_PATH)) { + 'DELETE /api/v1/commits/c1' => tap(Http::response(null, 204), function () use (&$deleted): void { + $deleted = true; + }), + 'GET /api/v1/log/following' => Http::response(pageJson([ + ...($deleted ? [] : [nativephpCommitJson(['id' => 'c1', 'body' => 'Delete me'])]), + commitJson(['id' => 'c2', 'body' => 'Keep me']), + ])), + default => Http::response(currentUserJson(['organizations' => [nativephpMembershipJson()]])), + }; + }); + + Native::visit('/log', platform: 'ios') + ->tap('delete-c1') + ->assertNativeCalled('Dialog.Alert', fn (array $params): bool => $params['title'] === 'Delete this commit?') + ->emitNative(ButtonPressed::class, ['index' => 1, 'label' => 'Delete', 'id' => 'delete-commit']) + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => str_starts_with($params['message'], 'rm ')) + ->assertDontSee('Delete me') + ->assertSee('Keep me'); + + Http::assertSent(fn (Request $request): bool => $request->method() === 'DELETE' && $request->url() === 'http://devnull.test/api/v1/commits/c1'); +}); + +it('puts Delete in the nav bar of an organization\'s commit page for a member', function () { + joinNativephp(); + fakeApi(['GET /api/v1/commits/c1' => [commitPageJson(nativephpCommitJson(['id' => 'c1']))]]); + + Native::visit('/log/commits/c1', platform: 'ios') + ->assertElement('top_bar_action', fn (array $node): bool => ($node['props']['id'] ?? null) === 'delete'); +}); + +it('offers someone outside the organization a star, the pastel and Report, never Delete', function () { + app(Account::class)->rememberPasteis(new Pasteis(Pasteis::Daily, CarbonImmutable::now()->addDay())); + + $screen = nativephpCommitOnLog(); + + expect(menuItems($screen, 'more-c1'))->toBe([ + ['share-c1', 'Share link', 'custom:link'], + 'divider', + ['report-c1', 'Report commit', 'custom:flag'], + ]) + ->and(rendersRef($screen, 'star-c1'))->toBeTrue() + // Still no pastel: it would go to whoever posted it. + ->and(rendersRef($screen, 'pastel-c1'))->toBeFalse() + ->and(rendersRef($screen, 'pastel-count-c1'))->toBeFalse(); + + $screen->call('confirmDelete', 'c1')->call('deleteCommit', 'c1'); + + Http::assertNotSent(fn (Request $request): bool => $request->method() === 'DELETE'); +}); + +it('lets a member quote an organization\'s commit still waiting for approval, as the web does', function () { + $screen = nativephpCommitOnLog(['status' => 'pending']); + + expect(rendersRef($screen, 'quote-c1'))->toBeFalse(); + + joinNativephp(); + $screen = nativephpCommitOnLog(['status' => 'pending']); + + expect(rendersRef($screen, 'quote-c1'))->toBeTrue(); + + $screen->call('quoteCommit', 'c1')->assertSet('sheetOpen', true); +}); + +it('doesn\'t let a member vote on an organization\'s poll', function () { + $poll = [ + 'id' => 'poll1', + 'closes_at' => now()->addDay()->toIso8601ZuluString(), + 'is_closed' => false, + 'has_voted' => false, + 'total_votes' => null, + 'options' => [ + ['id' => 'o1', 'label' => 'Tabs', 'votes_count' => null, 'voted' => false, 'percentage' => null], + ['id' => 'o2', 'label' => 'Spaces', 'votes_count' => null, 'voted' => false, 'percentage' => null], + ], + ]; + + expect(rendersRef(nativephpCommitOnLog(['poll' => $poll]), 'poll-vote-c1'))->toBeTrue(); + + joinNativephp(); + $screen = nativephpCommitOnLog(['poll' => $poll]); + + expect(rendersRef($screen, 'poll-vote-c1'))->toBeFalse(); + + $screen->call('choosePollOption', 'c1', 'o1')->call('voteOnPoll', 'c1'); + + Http::assertNotSent(fn (Request $request): bool => str_ends_with($request->url(), Client::pollVotesPath('c1'))); +}); + +it('says devnull\'s no when you\'ve left the organization, and stops offering Delete once /me says so', function () { + joinNativephp(); + $left = false; + + serveApi(function (Request $request) use (&$left) { + return match ($request->method().' '.parse_url($request->url(), PHP_URL_PATH)) { + 'DELETE /api/v1/commits/c1' => tap(Http::response(['message' => 'This action is unauthorized.'], 403), function () use (&$left): void { + $left = true; + }), + 'GET /api/v1/log/following' => Http::response(pageJson([nativephpCommitJson(['id' => 'c1', 'body' => 'NativePHP ships'])])), + default => Http::response(currentUserJson(['organizations' => $left ? [] : [nativephpMembershipJson()]])), + }; + }); + + $screen = Native::visit('/log', platform: 'ios'); + $asked = count(sentTo('GET', 'me')); + + $screen->tap('delete-c1') + ->emitNative(ButtonPressed::class, ['index' => 1, 'label' => 'Delete', 'id' => 'delete-commit']) + ->assertSee('This action is unauthorized.') + ->assertSee('NativePHP ships'); + + expect(sentTo('GET', 'me'))->toHaveCount($asked + 1) + ->and(app(Account::class)->organizations())->toBe([]) + ->and(menuItems($screen, 'more-c1'))->toBe([ + ['share-c1', 'Share link', 'custom:link'], + 'divider', + ['report-c1', 'Report commit', 'custom:flag'], + ]); +}); + +it('lists who starred an organization\'s commit, or says only the member who posted it can', function () { + joinNativephp(); + + nativephpCommitOnLog(['stars_count' => 1], ['GET /api/v1/commits/c1/stars' => [pageJson([userJson(['id' => 'u-grace', 'handle' => 'grace', 'name' => 'Grace Hopper'])], path: 'http://devnull.test/api/v1/commits/c1/stars')]]) + ->tap('star-count-c1') + ->assertSee('Grace Hopper') + ->assertDontSee('Only the member who posted this commit can see who starred it here.'); + + // The API answers someone who didn't post it as though the list isn't there, where the web shows it them. + nativephpCommitOnLog(['stars_count' => 1], ['GET /api/v1/commits/c1/stars' => [['message' => 'Not found.'], 404]]) + ->tap('star-count-c1') + ->assertSee('Only the member who posted this commit can see who starred it here.') + ->assertDontSee('fatal: could not load stars') + ->assertDontSee('Try again'); +}); + +it('keeps an organization\'s commits off your profile\'s count, posted or deleted', function () { + keep('users/local_dev', ['data' => userWithCountsJson(commits: 3)]); + keep('users/local_dev/commits', pageJson([commitJson(['id' => 'c0'])])); + keep('log/following', pageJson([nativephpCommitJson(['id' => 'c1']), commitJson(['id' => 'c0'])])); + fakeApi(['DELETE /api/v1/commits/c1' => [null, 204]]); + + app(ResponseCache::class)->commitAdded(nativephpCommitJson(['id' => 'c2'])); + app(Client::class)->deleteCommit('c1'); + + expect(kept('users/local_dev')['data']['commits_count'])->toBe(3) + ->and(array_column(kept('users/local_dev/commits')['data'], 'id'))->toBe(['c0']) + ->and(array_column(kept('log/following')['data'], 'id'))->toBe(['c2', 'c0']); +}); diff --git a/tests/Feature/Screens/PasteisTest.php b/tests/Feature/Screens/PasteisTest.php index 6f580305..01f879f2 100644 --- a/tests/Feature/Screens/PasteisTest.php +++ b/tests/Feature/Screens/PasteisTest.php @@ -85,7 +85,7 @@ function textInside(TestableComponent $screen, string $ref): ?string $screen = Native::visit('/log', platform: 'ios')->assertSee('3 replies'); - expect(array_values(array_filter(childRefs($screen, 'actions-c2'))))->toBe(['star-c2', 'quote-c2', 'reply-to-c2', 'replies-c2', 'more-c2']) + expect(array_values(array_filter(childRefs($screen, 'actions-c2'))))->toBe(['star-c2', 'quote-c2', 'reply-to-c2', 'more-c2', 'end-dot']) ->and(findNode($screen->tree(), fn (array $node): bool => str_starts_with((string) ($node['ref'] ?? ''), 'pastel')))->toBeNull() ->and(findNode($screen->tree(), fn (array $node): bool => ($node['props']['src'] ?? null) === Pasteis::Image))->toBeNull(); @@ -103,7 +103,7 @@ function textInside(TestableComponent $screen, string $ref): ?string $screen = Native::visit('/log', platform: 'ios'); - expect(array_values(array_filter(childRefs($screen, 'actions-c2'))))->toBe(['star-c2', 'pastel-c2', 'quote-c2', 'reply-to-c2', 'replies-c2', 'more-c2']) + expect(array_values(array_filter(childRefs($screen, 'actions-c2'))))->toBe(['star-c2', 'pastel-c2', 'quote-c2', 'reply-to-c2', 'more-c2']) ->and(nodeByRef($screen, 'pastel-c2')['props']['a11y_label'])->toBe('Give a pastel, 3 pastéis, 7 left today') ->and(nodeByRef($screen, 'pastel-c1')['props']['a11y_label'])->toBe('Give a pastel, 0 pastéis, 7 left today') // The web shows the count even when it's 0. @@ -278,13 +278,14 @@ function textInside(TestableComponent $screen, string $ref): ?string it('gives pastéis to replies in a thread and on a commit page', function () { pasteisOn(); - $reply = commitJson(['id' => 'r1', 'parent_id' => 'c1', 'pasteis_count' => 1, 'author' => pastelAuthor()]); + $reply = commitJson(['id' => 'r1', 'parent_id' => 'c1', 'pasteis_count' => 1, 'author' => replierJson()]); fakeApi([ - 'GET /api/v1/log/following' => [pageJson([commitJson(['id' => 'c1', 'replies_count' => 1, 'author' => pastelAuthor(), 'reply_preview' => ['data' => [$reply], 'next_cursor' => null]])])], + 'GET /api/v1/log/following' => [pageJson([commitJson(['id' => 'c1', 'replies_count' => 1, 'author' => pastelAuthor()])])], + 'GET /api/v1/commits/c1/replies' => [pageJson([$reply])], 'POST /api/v1/commits/r1/pasteis' => [pastelAnswer([...$reply, 'pasteis_count' => 2], remaining: 9)], ]); - $screen = Native::visit('/log', platform: 'ios')->tap('pastel-r1'); + $screen = Native::visit('/log', platform: 'ios')->tap('replies-c1')->tap('pastel-r1'); expect(pasteisSent())->toBe(['r1']) ->and(textInside($screen, 'pastel-r1'))->toBe('2'); diff --git a/tests/Feature/Screens/PostAsTest.php b/tests/Feature/Screens/PostAsTest.php new file mode 100644 index 00000000..21550679 --- /dev/null +++ b/tests/Feature/Screens/PostAsTest.php @@ -0,0 +1,388 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * An organization as `GET /me` lists one you're a member of. + * + * @param array $overrides + * @return array + */ +function memberOrganizationJson(array $overrides = []): array +{ + return [ + 'type' => 'organization', + 'id' => '0199e5c4-0000-7000-8000-0000000000aa', + 'role' => 'admin', + 'handle' => 'dev-null-sh', + 'name' => '/dev/null', + 'avatar_url' => 'https://avatars.githubusercontent.com/u/9?v=4', + 'bio' => null, + 'location' => null, + 'website' => null, + 'github_url' => 'https://github.com/dev-null-sh', + 'html_url' => 'http://devnull.test/@dev-null-sh', + 'lane' => null, + ...$overrides, + ]; +} + +/** + * Makes you a member of these organizations, as the last `GET /me` said. + * + * @param list> $organizations + */ +function memberOf(array $organizations): void +{ + app(Account::class)->rememberOrganizations(CurrentUser::fromArray(currentUserJson(['organizations' => $organizations]))->organizations); +} + +/** + * The Log with its composer open in the sheet, devnull answering a new commit with $answer. + * + * @param array{0: mixed, 1?: int}|null $answer + * @param array $extra + */ +function composeOnLogAs(?array $answer = null, array $extra = []): TestableComponent +{ + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([commitJson(['id' => 'c1', 'body' => 'An older commit', 'author' => userJson(['id' => 'u2', 'handle' => 'ada'])])])], + 'POST /api/v1/commits' => $answer ?? [['data' => commitJson(['id' => '0199e5c4-2222-7000-8000-00000000cafe', 'body' => 'From the org.', 'author' => memberOrganizationJson()])], 201], + ...$extra, + ]); + + return Native::visit('/log', platform: 'ios')->press('composeInSheet'); +} + +/** + * The JSON of the commits sent to devnull. + * + * @return list> + */ +function commitsSent(): array +{ + return collect(Http::recorded()) + ->filter(fn (array $sent): bool => $sent[0]->method() === 'POST' && str_ends_with(parse_url($sent[0]->url(), PHP_URL_PATH), '/commits')) + ->map(fn (array $sent): array => json_decode($sent[0]->body(), true)) + ->values() + ->all(); +} + +it('reads the organizations you can post as from GET /me, oldest membership first', function () { + $current = CurrentUser::fromArray(currentUserJson(['organizations' => [ + memberOrganizationJson(), + memberOrganizationJson(['id' => 'o2', 'handle' => 'nativephp', 'name' => 'NativePHP', 'role' => 'member', 'lane' => 5, 'type' => 'user']), + ['handle' => ''], + ]])); + + expect(array_map(fn (User $organization): array => [$organization->username, $organization->isOrganization, $organization->lane()], $current->organizations)) + ->toBe([['dev-null-sh', true, 'primary'], ['nativephp', true, 5]]) + ->and(CurrentUser::fromArray(currentUserJson())->organizations)->toBeNull(); +}); + +it('keeps the organizations GET /me lists, and what it had when devnull is too old to say', function () { + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([])], + 'GET /api/v1/me' => [currentUserJson(['organizations' => [memberOrganizationJson()]])], + ]); + + Native::visit('/log'); + + expect(array_map(fn (User $organization): string => $organization->username, app(Account::class)->organizations()))->toBe(['dev-null-sh']); + + app(Account::class)->rememberOrganizations(null); + + expect(app(Account::class)->organizations())->toHaveCount(1); + + app(Account::class)->forget(); + + expect(app(Account::class)->organizations())->toBe([]); +}); + +it('shows no Post as to someone in no organization, as the web hides it', function () { + composeOnLogAs() + ->assertSee('New commit') + ->assertMissingElement('pressable', fn (array $node): bool => ($node['ref'] ?? null) === 'sheet-post-as'); +}); + +it('draws each account in the Post as menu with its avatar, round for you, square for an organization, and ticks who posts now', function () { + memberOf([memberOrganizationJson(), memberOrganizationJson(['id' => 'o2', 'handle' => 'nativephp', 'name' => 'NativePHP', 'role' => 'member', 'avatar_url' => null])]); + + $screen = composeOnLogAs(); + + $rows = fn (): array => array_map(fn (array $item): array => [ + $item['ref'], + $item['props']['image'] ?? null, + $item['props']['image_shape'], + $item['props']['checked'], + $item['props']['icon'], + ], array_values(array_filter(nodeByRef($screen, 'sheet-post-as')['children'], fn (array $child): bool => $child['type'] === 'top_bar_action'))); + + $me = app(Account::class)->user(); + $person = Lucide::UserRound->ios(); + $building = Lucide::Building2->ios(); + + expect($me->avatarUrl)->not->toBeNull() + ->and($rows())->toBe([ + ['post-as-local_dev', $me->avatarUrl, 'circle', true, $person], + ['post-as-dev-null-sh', 'https://avatars.githubusercontent.com/u/9?v=4', 'rounded', false, $building], + // No avatar: the building stands in. + ['post-as-nativephp', null, 'rounded', false, $building], + ]); + + $screen->call('postAsInSheet', 'dev-null-sh'); + + expect(array_column($rows(), 3))->toBe([false, true, false]); +}); + +it('starts the composer as you, and lists you and your organizations under Post as', function () { + memberOf([memberOrganizationJson(), memberOrganizationJson(['id' => 'o2', 'handle' => 'nativephp', 'name' => 'NativePHP', 'role' => 'member', 'lane' => 5])]); + + $screen = composeOnLogAs(); + + expect(nodeByRef($screen, 'sheet-post-as-name')['props']['text'])->toBe('Local Dev') + ->and(nodeByRef($screen, 'sheet-post-as-handle')['props']['text'])->toBe('@local_dev') + ->and(nodeByRef($screen, 'sheet-post-as')['props']['a11y_label'])->toBe('Posting as @local_dev. Choose who to post as') + ->and(array_map(fn (array $item): array => [$item[0], $item[1]], menuItems($screen, 'sheet-post-as')))->toBe([ + ['post-as-local_dev', 'Local Dev (@local_dev)'], + ['post-as-dev-null-sh', '/dev/null (@dev-null-sh)'], + ['post-as-nativephp', 'NativePHP (@nativephp)'], + ]); + + $screen->call('postAsInSheet', 'nativephp'); + + expect(nodeByRef($screen, 'sheet-post-as-name')['props']['text'])->toBe('NativePHP') + ->and(nodeByRef($screen, 'sheet-post-as-handle')['props']['text'])->toBe('@nativephp') + ->and(nodeByRef($screen, 'sheet-post-as')['props']['a11y_label'])->toBe('Posting as @nativephp. Choose who to post as'); + + $screen->input('sheet-body', 'a'); + $organizationFill = sheetButtonCircle($screen, 'sheet-commit')['style']['bg_color']; + + // Commit is filled with the organization's lane rather than yours. + $screen->call('postAsInSheet', ''); + + expect(sheetButtonCircle($screen, 'sheet-commit')['style']['bg_color'])->not->toBe($organizationFill); +}); + +it('commits as the organization picked, and shows it staged as the organization', function () { + memberOf([memberOrganizationJson()]); + holdRefreshes(); + + $screen = composeOnLogAs() + ->call('postAsInSheet', 'dev-null-sh') + ->input('sheet-body', 'From the org.') + ->tap('sheet-commit'); + + $staged = $screen->instance()->commits[0]; + + expect($staged->isStaged())->toBeTrue() + ->and($staged->author->username)->toBe('dev-null-sh') + ->and($staged->author->isOrganization)->toBeTrue() + ->and(PendingWrite::query()->sole()->author())->toBe('dev-null-sh'); + + finishRefreshes($screen); + + expect(commitsSent())->toBe([['body' => 'From the org.', 'author' => 'dev-null-sh']]) + ->and($screen->instance()->commits[0]->author->username)->toBe('dev-null-sh'); +}); + +it('commits as you again once you pick yourself, and ignores an organization you are not in', function () { + memberOf([memberOrganizationJson()]); + + composeOnLogAs() + ->call('postAsInSheet', 'laravel') + ->assertSet('sheetAuthor', null) + ->call('postAsInSheet', 'dev-null-sh') + ->call('postAsInSheet', '') + ->input('sheet-body', 'From me.') + ->tap('sheet-commit'); + + expect(commitsSent())->toBe([['body' => 'From me.']]); +}); + +it('quotes as the organization picked', function () { + memberOf([memberOrganizationJson()]); + fakeApi([ + 'GET /api/v1/log/following' => [pageJson([commitJson(['id' => 'c1', 'body' => 'Quote me', 'author' => userJson(['id' => 'u2', 'handle' => 'ada'])])])], + 'POST /api/v1/commits' => [['data' => commitJson(['id' => 'q1', 'body' => 'Our take', 'quoted_commit_id' => 'c1', 'author' => memberOrganizationJson()])], 201], + ]); + + $screen = Native::visit('/log', platform: 'ios')->call('quoteCommit', 'c1'); + + expect(rendersRef($screen, 'sheet-post-as'))->toBeTrue(); + + $screen->call('postAsInSheet', 'dev-null-sh')->input('sheet-body', 'Our take')->tap('sheet-commit'); + + expect(commitsSent())->toBe([['body' => 'Our take', 'quoted_commit_id' => 'c1', 'author' => 'dev-null-sh']]); +}); + +it('replies from the commit page as the organization picked in the bar', function () { + memberOf([memberOrganizationJson()]); + fakeApi([ + 'GET /api/v1/commits/c2' => [commitPageJson(commitJson(['id' => 'c2', 'body' => 'The focused commit']))], + 'GET /api/v1/commits/c2/replies' => [pageJson([])], + 'GET /api/v1/commits/c2/related' => [['data' => []]], + 'POST /api/v1/commits' => [['data' => replyJson(['id' => 'r9', 'parent_id' => 'c2', 'body' => 'From the org', 'author' => memberOrganizationJson()])], 201], + ]); + + $screen = Native::visit('/log/commits/c2'); + + // It leads the row under the field, ahead of the photo button. + expect(array_slice(childRefs($screen, 'reply-actions'), 0, 2))->toBe(['reply-post-as', 'reply-add-photos']) + ->and(array_column(menuItems($screen, 'reply-post-as'), 0))->toBe(['post-as-local_dev', 'post-as-dev-null-sh']); + + $screen->call('postAsInReply', 'dev-null-sh') + ->input('reply-input', 'From the org') + ->tap('send-reply') + ->assertSee('From the org'); + + expect(commitsSent())->toBe([['body' => 'From the org', 'parent_id' => 'c2', 'author' => 'dev-null-sh']]) + ->and($screen->instance()->replies[0]->author->username)->toBe('dev-null-sh'); +}); + +it("fills the reply bar's send button with the lane of the organization it replies as", function () { + memberOf([memberOrganizationJson(['handle' => 'nativephp', 'name' => 'NativePHP', 'lane' => 5])]); + fakeApi([ + 'GET /api/v1/commits/c2' => [commitPageJson(commitJson(['id' => 'c2', 'body' => 'The focused commit']))], + 'GET /api/v1/commits/c2/replies' => [pageJson([])], + 'GET /api/v1/commits/c2/related' => [['data' => []]], + ]); + + $screen = Native::visit('/log/commits/c2')->input('reply-input', 'Agreed'); + $mine = nodeByRef($screen, 'send-reply-circle')['style']['bg_color']; + + $screen->call('postAsInReply', 'nativephp'); + + expect(strtolower(nodeByRef($screen, 'send-reply-circle')['style']['bg_color']))->toBe(strtolower(config('native-ui.theme.light.lane-5'))) + ->and(nodeByRef($screen, 'reply-post-as')['props']['a11y_label'])->toBe('Posting as @nativephp. Choose who to post as'); + + $screen->call('postAsInReply', ''); + + expect(nodeByRef($screen, 'send-reply-circle')['style']['bg_color'])->toBe($mine); +}); + +it('replies as the organization picked in the bar with photos', function () { + memberOf([memberOrganizationJson()]); + fakeApi([ + 'GET /api/v1/commits/c2' => [commitPageJson(commitJson(['id' => 'c2', 'body' => 'The focused commit']))], + 'GET /api/v1/commits/c2/replies' => [pageJson([])], + 'GET /api/v1/commits/c2/related' => [['data' => []]], + 'POST /api/v1/commits' => [['data' => replyJson(['id' => 'r9', 'parent_id' => 'c2', 'body' => 'Look', 'author' => memberOrganizationJson()])], 201], + ]); + + $screen = photosPicked(Native::visit('/log/commits/c2')->call('postAsInReply', 'dev-null-sh')->input('reply-input', 'Look'), [testPhoto()]) + ->tap('send-reply') + ->assertSee('Look'); + + Http::assertSent(fn (Request $request): bool => $request->method() === 'POST' + && multipartParts($request)[0]['contents'] === '{"body":"Look","parent_id":"c2","author":"dev-null-sh"}' + && multipartParts($request)[1]['name'] === 'images[]'); + + expect($screen->instance()->replies[0]->author->username)->toBe('dev-null-sh'); +}); + +it('posts as the organization picked in a reply sheet, which starts as you, apart from the bar', function () { + memberOf([memberOrganizationJson()]); + fakeApi([ + 'GET /api/v1/commits/c2' => [commitPageJson(commitJson(['id' => 'c2', 'body' => 'The focused commit']))], + 'GET /api/v1/commits/c2/replies' => [pageJson([])], + 'GET /api/v1/commits/c2/related' => [['data' => []]], + 'POST /api/v1/commits' => [['data' => replyJson(['id' => 'r9', 'parent_id' => 'c2', 'body' => 'Sheet reply'])], 201], + ]); + + // The bar no longer opens the sheet, but a reply written there before it took over comes back to it if devnull + // turned it down. + $screen = Native::visit('/log/commits/c2', platform: 'ios') + ->call('postAsInReply', 'dev-null-sh') + ->call('replyInSheet', 'c2') + ->assertSet('sheetAuthor', null); + + expect(rendersRef($screen, 'sheet-post-as'))->toBeTrue(); + + $screen->call('postAsInSheet', 'dev-null-sh')->input('sheet-body', 'Sheet reply')->tap('sheet-commit'); + + expect(commitsSent())->toBe([['body' => 'Sheet reply', 'parent_id' => 'c2', 'author' => 'dev-null-sh']]); +}); + +it('puts a commit turned down for leaving the organization back in the sheet, asks devnull again, and then posts as you', function () { + memberOf([memberOrganizationJson()]); + $refused = 'You can only post as an organization you are a member of.'; + $routes = [ + 'GET /api/v1/log/following' => [pageJson([commitJson(['id' => 'c1'])])], + 'GET /api/v1/me' => [currentUserJson(['organizations' => [memberOrganizationJson()]])], + ]; + serveApi($routes); + + $screen = Native::visit('/log', platform: 'ios') + ->press('composeInSheet') + ->call('postAsInSheet', 'dev-null-sh') + ->input('sheet-body', 'From the org.'); + + // You were taken out of the organization since the app last asked. + serveApi([ + ...$routes, + 'POST /api/v1/commits' => [['message' => $refused, 'errors' => ['author' => [$refused]]], 422], + 'GET /api/v1/me' => [currentUserJson(['organizations' => []])], + ]); + + $screen->tap('sheet-commit') + ->assertNativeCalled('ToastKit.Show', fn (array $params): bool => $params['message'] === $refused && $params['variant'] === 'error'); + + expect(commitsSent())->toBe([['body' => 'From the org.', 'author' => 'dev-null-sh']]) + ->and(app(Account::class)->organizations())->toBe([]); + + // The sheet opens on the draft again, as the organization picked, which now posts as you. + $screen->dismissSheet('sheet'); + + expect($screen->instance()) + ->sheetOpen->toBeTrue() + ->sheetBody->toBe('From the org.') + ->sheetAuthor->toBe('dev-null-sh'); + expect(nodeByRef($screen, 'sheet-post-as-handle')['props']['text'])->toBe('@local_dev') + ->and(menuItems($screen, 'sheet-post-as'))->toHaveCount(1); + + serveApi([...$routes, 'POST /api/v1/commits' => [['data' => commitJson(['id' => 'c9', 'body' => 'From the org.'])], 201]]); + $screen->tap('sheet-commit'); + + expect(commitsSent())->toBe([['body' => 'From the org.', 'author' => 'dev-null-sh'], ['body' => 'From the org.']]); +}); + +it('schedules a commit as the organization picked, and lists it as the organization', function () { + phoneIn('Europe/Lisbon'); + $this->travelTo(CarbonImmutable::parse('2026-10-19 15:30:00', 'UTC')); + memberOf([memberOrganizationJson()]); + + composeOnLogAs(extra: [ + 'POST /api/v1/scheduled-commits' => [['data' => scheduledCommitJson(['author' => memberOrganizationJson()])], 201], + 'GET /api/v1/scheduled-commits' => [scheduledPageJson([scheduledCommitJson(['author' => memberOrganizationJson()]), scheduledCommitJson(['id' => 's2'])])], + ]) + ->call('postAsInSheet', 'dev-null-sh') + ->input('sheet-body', 'Shipping this tomorrow.') + ->tap('sheet-schedule') + ->pickDateTime('scheduled-at', '2026-10-20T09:00') + ->tap('sheet-commit'); + + Http::assertSent(fn (Request $request): bool => $request->method() === 'POST' + && str_ends_with($request->url(), '/scheduled-commits') + && $request['author'] === 'dev-null-sh'); + + $list = Native::visit('/log/scheduled'); + + expect(rendersRef($list, 'scheduled-author-0199e5c4-3333-7000-8000-00000000da7e'))->toBeTrue() + ->and(rendersRef($list, 'scheduled-author-s2'))->toBeFalse(); + $list->assertSee('As @dev-null-sh'); +}); diff --git a/tests/Feature/Screens/ProfileTest.php b/tests/Feature/Screens/ProfileTest.php index eea451e5..02e88cbb 100644 --- a/tests/Feature/Screens/ProfileTest.php +++ b/tests/Feature/Screens/ProfileTest.php @@ -58,7 +58,7 @@ function adaCommitJson(array $overrides = []): array ->assertSee("That's @ada's root commit."); }); -it("shows Reply as just its icon beside a commit's replies, so the row still fits a phone", function () { +it("labels Reply, with a commit's replies on their own line under the actions", function () { fakeApi([ 'GET /api/v1/users/ada' => [profileJson()], 'GET /api/v1/users/ada/commits' => [pageJson([ @@ -71,8 +71,9 @@ function adaCommitJson(array $overrides = []): array $labels = fn (string $ref): array => findNodes(nodeByRef($screen, $ref), fn (array $node): bool => ($node['type'] ?? null) === 'text'); expect(nodeByRef($screen, 'reply-to-c1')['props']['a11y_label'])->toBe('Reply') - ->and($labels('reply-to-c1'))->toBe([]) - ->and($labels('reply-to-c2'))->toHaveCount(1); + ->and($labels('reply-to-c1'))->toHaveCount(1) + ->and($labels('reply-to-c2'))->toHaveCount(1) + ->and(findNode(nodeByRef($screen, 'actions-c1'), fn (array $node): bool => ($node['ref'] ?? null) === 'replies-c1'))->toBeNull(); }); it('lists what GitHub says about them under the bio, as the web does', function () { diff --git a/tests/Feature/Screens/RelatedCommitsTest.php b/tests/Feature/Screens/RelatedCommitsTest.php index d493ad73..b3f9a350 100644 --- a/tests/Feature/Screens/RelatedCommitsTest.php +++ b/tests/Feature/Screens/RelatedCommitsTest.php @@ -85,7 +85,7 @@ function openRelated(TestableComponent $screen): TestableComponent ->assertSee('Next match') ->assertSee('Third match'); - expect(childRefs($screen, 'thread-page'))->toBe(['focused-commit', 'thread-reply-r1', 'related-commits', 'reply-bar-clearance']) + expect(childRefs($screen, 'thread-scroll'))->toBe(['focused-commit', 'thread-reply-r1', 'related-commits', 'reply-bar-clearance']) ->and(childRefs($screen, 'related-commits'))->toBe(['related-commits-toggle', 'related-c9', 'related-c3', 'related-c7']) ->and(childRefs($screen, 'related-c9'))->toBe(['commit-c9']) ->and(railNode($screen, 'commit-c9'))->toBe('avatar') @@ -255,13 +255,13 @@ function openRelated(TestableComponent $screen): TestableComponent $relatedLine = fn (): float => (float) (nodeByRef($screen, 'related-commits')['props']['border_t'] ?? 0); // Shut, the commit sits right on the section, whose line is the only one. - expect(childRefs($screen, 'thread-page'))->toBe(['focused-commit', 'related-commits', 'reply-bar-clearance']) + expect(childRefs($screen, 'thread-scroll'))->toBe(['focused-commit', 'related-commits', 'reply-bar-clearance']) ->and($commitLine())->toBe(0.0) ->and($relatedLine())->toBe(1.0); // Open, the last reply ends with no hairline of its own, so the section's line is still the only one. $screen->tap('replies-c1')->assertSee('A reply'); - expect(childRefs($screen, 'thread-page'))->toBe(['focused-commit', 'thread-reply-r1', 'related-commits', 'reply-bar-clearance']) + expect(childRefs($screen, 'thread-scroll'))->toBe(['focused-commit', 'thread-reply-r1', 'related-commits', 'reply-bar-clearance']) ->and($commitLine())->toBe(0.0) ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'thread-end-r1'))->toBeNull() ->and($relatedLine())->toBe(1.0); diff --git a/tests/Feature/Screens/RemotesComposerTest.php b/tests/Feature/Screens/RemotesComposerTest.php index 637ed790..6e3e0079 100644 --- a/tests/Feature/Screens/RemotesComposerTest.php +++ b/tests/Feature/Screens/RemotesComposerTest.php @@ -10,6 +10,7 @@ use Native\Mobile\Facades\System; use Native\Mobile\Testing\Native; use Native\Mobile\Testing\TestableComponent; +use Tests\Support\GlassOpacity; const ComposerViewerId = '0199e5c4-0000-7000-8000-000000000001'; @@ -285,7 +286,22 @@ function threadWithAda(string $platform = 'ios'): TestableComponent ->and(nodeByRef($screen, 'push')['props']['a11y_label'] ?? nodeByRef($screen, 'push')['a11y_label'] ?? null)->toBe('Push'); })->with(['ios', 'android']); +it('keeps the field closer to the fade than to the + and Push under it', function (string $platform) { + serveThreadWithAda([remoteMessageJson(['id' => 1])], ['read_through_id' => 1]); + + $screen = threadWithAda($platform); + + // [top, right, bottom, left]. As on a commit's reply bar: no top padding on the row, so the field starts 4pt + // under the fade, and 8pt between the field and the row under it. + expect(nodeByRef($screen, 'message-row')['layout']['padding'])->toEqual([0, 16, 8, 16]) + ->and(nodeByRef($screen, 'message-field-row')['layout']['padding'])->toEqual([4, 12, 8, 16]); +})->with(['ios', 'android']); + it('puts the bar on glass on iOS and the surface on Android, with no box or line, and fades the thread out above it', function (string $platform) { + if ($platform === 'ios') { + GlassOpacity::skipUnlessSupported(); + } + serveThreadWithAda([remoteMessageJson(['id' => 1])], ['read_through_id' => 1]); $screen = threadWithAda($platform); @@ -306,6 +322,7 @@ function threadWithAda(string $platform = 'ios'): TestableComponent // top, ending at the glass's tint, and its rows carry the tint, in either appearance. The bar itself has no // background, which iOS would paint behind the fade. expect($bottomBar['props']['glass'] ?? null)->toBe(1) + ->and($bottomBar['props']['glass_opacity'] ?? null)->toBe(Display::ComposerGlassOpacity / 100) ->and(childRefs($screen, 'composer-bar'))->toBe(['composer-fade', 'composer-rows']) ->and($bar['style']['bg_color'] ?? null)->toBeNull() ->and(nodeByRef($screen, 'composer-rows')['style']['bg_color'] ?? null)->toBe('#66'.$surface) @@ -315,6 +332,7 @@ function threadWithAda(string $platform = 'ios'): TestableComponent } else { // No glass on Android. The thread stops at the bar, so the fade lies over its foot, and the bar is the surface. expect($bottomBar['props']['glass'] ?? null)->toBeNull() + ->and($bottomBar['props']['glass_opacity'] ?? null)->toBeNull() ->and(childRefs($screen, 'composer-bar'))->toBe(['composer-rows']) ->and($bar['style']['bg_color'] ?? null)->toBe(config('native-ui.theme.light.surface')) ->and(nodeByRef($screen, 'composer-rows')['style']['bg_color'] ?? null)->toBe(config('native-ui.theme.light.surface')) diff --git a/tests/Feature/Screens/ReplyPreviewTest.php b/tests/Feature/Screens/ReplyPreviewTest.php deleted file mode 100644 index ca38f205..00000000 --- a/tests/Feature/Screens/ReplyPreviewTest.php +++ /dev/null @@ -1,252 +0,0 @@ - 'http://devnull.test']); - signIn(); -}); - -function grace(): array -{ - return userJson(['id' => 'u3', 'handle' => 'grace', 'name' => 'Grace', 'lane' => 4]); -} - -/** - * A commit by Ada in a list, with the newest reply devnull previews under it. - * - * @param list> $replies - * @param array $overrides - * @return array - */ -function previewedJson(array $replies, bool $more = false, array $overrides = []): array -{ - return commitJson([ - 'id' => 'c1', - 'body' => 'Ship it?', - 'replies_count' => count($replies) + ($more ? 2 : 0), - 'author' => userJson(['id' => 'u2', 'handle' => 'ada', 'name' => 'Ada', 'lane' => 1]), - 'reply_preview' => ['data' => $replies, 'next_cursor' => $more ? 'eyJjcmVhdGVkX2F0IjoiMjAyNiJ9' : null], - ...$overrides, - ]); -} - -/** - * The colours of the dashed lines in a node, in order. - * - * @return list - */ -function dashColours(array $node): array -{ - return array_values(array_unique(array_map( - fn (array $line): string => $line['style']['border_color'] ?? '', - findNodes($node, fn (array $child): bool => ($child['props']['border_style'] ?? null) === 1), - ))); -} - -it('hangs the newest reply under a commit, on a dashed elbow in its lane, instead of a replies toggle', function () { - Http::fake(['devnull.test/*' => Http::response(pageJson([previewedJson([ - replyJson(['id' => 'r9', 'parent_id' => 'c1', 'body' => 'The newest reply', 'author' => grace()]), - ])]))]); - - $screen = Native::visit('/log', platform: 'ios') - ->assertSee('Ship it?') - ->assertSee('The newest reply') - ->assertDontSee('1 reply') - ->assertDontSee('Show more'); - - $reply = nodeByRef($screen, 'thread-reply-r9'); - $elbow = findNode($reply, fn (array $node): bool => ($node['ref'] ?? null) === 'thread-elbow'); - - expect($elbow)->not->toBeNull() - ->and(dashColours($elbow))->toBe([config('native-ui.theme.light.lane-1')]) - // One dashed border down from the rail, round a 12pt corner and across to 1pt short of the avatar. - ->and($elbow['props'])->toMatchArray(['border_l' => 1.0, 'border_b' => 1.0, 'border_t' => 0.0, 'border_r' => 0.0, 'radius_bl' => 12.0]) - ->and($elbow['layout'])->toMatchArray(['width' => 31.5, 'height' => 22.5, 'position' => [0.0, 0.0, 0.0, 31.5]]) - // A reply's own actions: the star and Reply, but no Quote. - ->and(findNode($reply, fn (array $node): bool => ($node['ref'] ?? null) === 'reply-to-r9'))->not->toBeNull() - ->and(findNode($reply, fn (array $node): bool => ($node['ref'] ?? null) === 'quote-r9'))->toBeNull(); - - // The commit ends its rail in a dot, and the dashes carry on from it to the reply. - expect(findNode(nodeByRef($screen, 'commit-c1'), fn (array $node): bool => ($node['ref'] ?? null) === 'end-dot'))->not->toBeNull(); - - $screen->tap('thread-reply-r9')->assertNavigatedTo('/log/commits/r9'); -}); - -it('frames a reply avatar in its own lane without shifting the thread', function (string $platform) { - Http::fake(['devnull.test/*' => Http::response(pageJson([previewedJson([ - replyJson(['id' => 'r9', 'parent_id' => 'c1', 'author' => grace()]), - ])]))]); - - $screen = Native::visit('/log', platform: $platform); - $reply = nodeByRef($screen, 'thread-reply-r9'); - $ring = findNode($reply, fn (array $node): bool => ($node['style']['border_color'] ?? null) === config('native-ui.theme.light.lane-4') - && ($node['layout']['width'] ?? null) === 24.0 - && ($node['layout']['height'] ?? null) === 24.0); - - expect($ring)->not->toBeNull() - ->and($ring['style']['border_radius'])->toBeGreaterThanOrEqual(12.0) - ->and($ring['style'])->toMatchArray(['border_width' => 1.0, 'bg_color' => config('native-ui.theme.light.surface')]) - ->and($ring['children'])->toHaveCount(1) - ->and($ring['children'][0]['layout'])->toMatchArray(['width' => 20.0, 'height' => 20.0]); -})->with(['ios', 'android']); - -it('opens the rest of the thread in place, newest first, from Show more', function () { - fakeApi([ - 'GET /api/v1/log/following' => [pageJson([previewedJson([replyJson(['id' => 'r3', 'parent_id' => 'c1', 'body' => 'Third', 'author' => grace()])], more: true)])], - 'GET /api/v1/commits/c1/replies' => [pageJson([ - replyJson(['id' => 'r1', 'parent_id' => 'c1', 'body' => 'First']), - replyJson(['id' => 'r2', 'parent_id' => 'c1', 'body' => 'Second', 'author' => grace()]), - replyJson(['id' => 'r3', 'parent_id' => 'c1', 'body' => 'Third', 'author' => grace()]), - ])], - ]); - - $screen = Native::visit('/log', platform: 'ios') - ->assertSee('Third') - ->assertDontSee('Second') - ->assertSee('Show more'); - - $screen->tap('more-replies-c1') - ->assertNoNavigation() - ->assertSee('First') - ->assertSee('Second') - ->assertDontSee('Show more'); - - expect(array_map(fn ($reply): string => $reply->id, $screen->instance()->threads['c1']))->toBe(['r3', 'r2', 'r1']); - - // Each reply after the first hangs on a short link in the lane of the reply above it. - expect(dashColours(nodeByRef($screen, 'thread-reply-r2')))->toContain(config('native-ui.theme.light.lane-4')) - ->and(findNode(nodeByRef($screen, 'thread-reply-r2'), fn (array $node): bool => ($node['ref'] ?? null) === 'thread-elbow'))->toBeNull(); - - Http::assertSent(fn (Request $request): bool => $request->url() === 'http://devnull.test/api/v1/commits/c1/replies?limit=5'); -}); - -it('opens Show more at once from the thread kept last time, and refreshes it behind', function () { - holdRefreshes(); - keep('log/following', pageJson([previewedJson([replyJson(['id' => 'r2', 'parent_id' => 'c1', 'body' => 'Second'])], more: true)])); - keep('commits/c1/replies', pageJson([replyJson(['id' => 'r1', 'parent_id' => 'c1', 'body' => 'First kept']), replyJson(['id' => 'r2', 'parent_id' => 'c1', 'body' => 'Second'])])); - serveApi(fn () => Http::response(pageJson([]))); - - $screen = Native::visit('/log', platform: 'ios'); - $requests = count(Http::recorded()); - - $screen->tap('more-replies-c1')->assertSee('First kept'); - - expect(count(Http::recorded()))->toBe($requests) - ->and(refreshesSent($screen))->toBeGreaterThan(1); -}); - -it('opens the commit with its replies showing instead when its thread is longer than a page', function () { - fakeApi([ - 'GET /api/v1/log/following' => [pageJson([previewedJson([replyJson(['id' => 'r60', 'parent_id' => 'c1'])], more: true)])], - 'GET /api/v1/commits/c1/replies' => [pageJson(array_map(fn (int $n): array => replyJson(['id' => "r{$n}", 'parent_id' => 'c1']), range(1, 5)), 'page2')], - 'GET /api/v1/commits/c1' => [commitPageJson(previewedJson([], more: true))], - ]); - - Native::visit('/log', platform: 'ios') - ->tap('more-replies-c1') - ->assertNavigatedTo('/log/commits/c1') - ->follow() - ->assertSet('repliesShown', true); -}); - -it('stars a reply in the thread in place', function () { - fakeApi([ - 'GET /api/v1/log/following' => [pageJson([previewedJson([replyJson(['id' => 'r1', 'parent_id' => 'c1', 'author' => grace(), 'stars_count' => 0])])])], - 'POST /api/v1/commits/r1/star' => [['data' => commitJson(['id' => 'r1', 'stars_count' => 1, 'starred' => true, 'author' => grace()])]], - ]); - - $screen = Native::visit('/log')->tap('star-r1'); - - expect($screen->instance()->commits[0]->replyPreview->replies[0]->starred)->toBeTrue() - ->and($screen->instance()->commits[0]->replyPreview->replies[0]->starsCount)->toBe(1); -}); - -it('keeps the thread under a commit you star below a quote of it, and unstars it on the next tap', function () { - $quoted = previewedJson([]); - unset($quoted['reply_preview']); - - fakeApi([ - 'GET /api/v1/log/following' => [pageJson([ - commitJson(['id' => 'q1', 'body' => 'Look at this', 'quoted_commit_id' => 'c1', 'quoted_commit' => $quoted]), - previewedJson([replyJson(['id' => 'r9', 'parent_id' => 'c1', 'body' => 'The newest reply', 'author' => grace()])]), - ])], - 'POST /api/v1/commits/c1/star' => [['data' => commitJson(['id' => 'c1', 'stars_count' => 1, 'starred' => true])]], - 'DELETE /api/v1/commits/c1/star' => [['data' => commitJson(['id' => 'c1', 'stars_count' => 0, 'starred' => false])]], - ]); - $screen = Native::visit('/log', platform: 'ios'); - - $screen->tap('star-c1')->assertSee('The newest reply'); - $starred = $screen->instance()->commits[1]->starred; - $screen->tap('star-c1'); - - expect($starred)->toBeTrue() - ->and($screen->instance()->commits[1]->starred)->toBeFalse() - ->and(sentTo('DELETE', 'commits/c1/star'))->toHaveCount(1); -}); - -it('keeps the thread under a commit you star that is also the reply previewed under its parent', function () { - fakeApi([ - 'GET /api/v1/log/following' => [pageJson([])], - 'GET /api/v1/log/latest' => [pageJson([ - previewedJson([replyJson(['id' => 'c1', 'parent_id' => 'p1', 'body' => 'Ship it?', 'replies_count' => 1, 'author' => userJson(['id' => 'u2', 'handle' => 'ada', 'name' => 'Ada', 'lane' => 1])])], overrides: ['id' => 'p1', 'body' => 'Should we ship?']), - previewedJson([replyJson(['id' => 'r9', 'parent_id' => 'c1', 'body' => 'The newest reply', 'author' => grace()])], overrides: ['parent_id' => 'p1']), - ], path: 'http://devnull.test/api/v1/log/latest')], - 'POST /api/v1/commits/c1/star' => [['data' => commitJson(['id' => 'c1', 'stars_count' => 1, 'starred' => true])]], - ]); - $screen = tapLogTab(Native::visit('/log', platform: 'ios'), 'latest'); - - $screen->call('toggleStar', 'c1'); - - $screen->assertSee('The newest reply'); - expect($screen->instance()->commits[0]->replyPreview->replies[0]->starred)->toBeTrue() - ->and($screen->instance()->commits[1]->starred)->toBeTrue(); -}); - -it("runs the commit's rail on past its thread when the author's run carries on below", function () { - $ada = userJson(['id' => 'u2', 'handle' => 'ada', 'name' => 'Ada', 'lane' => 1]); - - Http::fake(['devnull.test/*' => Http::response(pageJson([ - previewedJson([replyJson(['id' => 'r1', 'parent_id' => 'c1', 'author' => grace()])], overrides: ['id' => 'c2', 'author' => $ada]), - commitJson(['id' => 'c1', 'author' => $ada]), - ]))]); - - $screen = Native::visit('/log', platform: 'ios'); - $lane = config('native-ui.theme.light.lane-1'); - $solidRail = fn (array $node): bool => ($node['layout']['width'] ?? null) === 2.0 && ($node['style']['bg_color'] ?? null) === $lane; - - expect(findNode(nodeByRef($screen, 'thread-reply-r1'), $solidRail))->not->toBeNull() - ->and(findNode(nodeByRef($screen, 'commit-c2'), fn (array $node): bool => ($node['ref'] ?? null) === 'end-dot'))->toBeNull() - ->and(railNode($screen, 'commit-c1'))->toBe('dot'); -}); - -it('ends a commit alone in its run with a dot, and joins a run of one author', function () { - $ada = userJson(['id' => 'u2', 'handle' => 'ada', 'lane' => 1]); - - Http::fake(['devnull.test/*' => Http::response(pageJson([ - commitJson(['id' => 'c3', 'author' => $ada]), - commitJson(['id' => 'c2', 'author' => $ada]), - commitJson(['id' => 'c1', 'author' => grace()]), - ]))]); - - $screen = Native::visit('/log', platform: 'ios'); - $endDot = fn (string $ref): bool => findNode(nodeByRef($screen, $ref), fn (array $node): bool => ($node['ref'] ?? null) === 'end-dot') !== null; - - expect(railNode($screen, 'commit-c3'))->toBe('avatar') - ->and(railNode($screen, 'commit-c2'))->toBe('dot') - ->and($endDot('commit-c3'))->toBeFalse() - ->and($endDot('commit-c2'))->toBeFalse() - ->and($endDot('commit-c1'))->toBeTrue(); -}); - -it("closes a commit's row in the log with a hairline after its last previewed reply", function () { - Http::fake(['devnull.test/*' => Http::response(pageJson([previewedJson([ - replyJson(['id' => 'r9', 'parent_id' => 'c1', 'body' => 'The newest reply', 'author' => grace()]), - ])]))]); - - $screen = Native::visit('/log', platform: 'ios'); - - expect(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'thread-end-r9'))->not->toBeNull(); -}); diff --git a/tests/Feature/Screens/RowCacheScreensTest.php b/tests/Feature/Screens/RowCacheScreensTest.php index 902cbd0d..d7c547cd 100644 --- a/tests/Feature/Screens/RowCacheScreensTest.php +++ b/tests/Feature/Screens/RowCacheScreensTest.php @@ -88,10 +88,10 @@ function expectKeptRowsMatchFreshOnes(TestableComponent $screen, string $class, }); $screen = Native::visit('/log/commits/c2')->tap('replies-c2')->assertSee('Second reply'); - // The commits above the replies read what the screen shows of the thread, so they're built every time. The last - // reply of a page changes when the next page comes, since it no longer carries "more". + // The commits above the replies read what the screen shows of the thread, so they're built every time. "Show + // more" is a row of its own, so the last reply of a page stays as it was when the next page comes. expect(rowsBuiltBy(fn () => $screen->call('navTitle')))->toBe(['c2']) - ->and(rowsBuiltBy(fn () => $screen->call('loadMoreReplies')->assertSee('Third reply')))->toBe(['c2', 'r2', 'r3']); + ->and(rowsBuiltBy(fn () => $screen->call('loadMoreReplies')->assertSee('Third reply')))->toBe(['c2', 'r3']); expectKeptRowsMatchFreshOnes($screen, CommitDetail::class, 'replyRows', null); }); diff --git a/tests/Feature/Screens/ScrollToReplyTest.php b/tests/Feature/Screens/ScrollToReplyTest.php new file mode 100644 index 00000000..be04ecf7 --- /dev/null +++ b/tests/Feature/Screens/ScrollToReplyTest.php @@ -0,0 +1,129 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * A commit page for c2, under c1 and c0, with a first page of ten replies and more after them. r1 has a reply of + * its own, n1. Everything is kept from before, so the page shows it at once and holds its refreshes, the reply + * you post among them, until the test lets them go. + * + * @param array $commit + */ +function fakeLongThread(array $commit = [], array $posted = []): void +{ + holdRefreshes(); + + $grace = userJson(['handle' => 'grace', 'name' => 'Grace']); + $c0 = commitJson(['id' => 'c0', 'body' => 'The root commit', 'author' => userJson(['handle' => 'ada', 'name' => 'Ada'])]); + $c1 = commitJson(['id' => 'c1', 'parent_id' => 'c0', 'body' => 'The parent commit', 'author' => userJson(['handle' => 'linus', 'name' => 'Linus'])]); + $c2 = commitJson(['id' => 'c2', 'parent_id' => 'c1', 'body' => 'The focused commit', 'replies_count' => 11, 'author' => $grace, ...$commit]); + $replies = array_map(fn (int $n): array => replyJson(['id' => "r{$n}", 'parent_id' => 'c2', 'body' => "Reply {$n}", 'replies_count' => $n === 1 ? 1 : 0]), range(1, 10)); + $repliesPage = pageJson($replies, 'page2', 'http://devnull.test/api/v1/commits/c2/replies'); + $nested = pageJson([replyJson(['id' => 'n1', 'parent_id' => 'r1', 'body' => 'A reply to the first reply', 'author' => userJson(['handle' => 'alan', 'name' => 'Alan'])])]); + + keep('commits/c2', commitPageJson($c2, [$c0, $c1])); + keep('commits/c2/replies', $repliesPage); + keep('commits/r1/replies', $nested); + + fakeApi([ + 'GET /api/v1/commits/c2' => [commitPageJson($c2, [$c0, $c1])], + 'GET /api/v1/commits/c2/replies' => [$repliesPage], + 'GET /api/v1/commits/c2/related' => [['data' => []]], + 'GET /api/v1/commits/r1/replies' => [$nested], + 'POST /api/v1/commits' => [['data' => commitJson(['id' => 'r99', 'parent_id' => 'c2', 'body' => 'My fresh reply', ...$posted])], 201], + ]); +} + +/** + * Where the scroll view is asked to go: the ref of the child at auto-scroll-to, and the request it's under, which + * the scroll view takes as its auto-scroll-token where mobile-ui has it. + * + * @return array{0: string|null, 1: int} + */ +function scrolledTo(TestableComponent $screen): array +{ + $index = nodeByRef($screen, 'thread-scroll')['props']['auto_scroll_to'] ?? -1; + + return [childRefs($screen, 'thread-scroll')[$index] ?? null, $screen->instance()->scrollRequest]; +} + +function stagedReplyId(TestableComponent $screen): string +{ + /** @var CommitDetail $page */ + $page = $screen->instance(); + + return collect($page->replies)->first(fn ($reply): bool => $reply->isStaged())->id; +} + +it('scrolls to a reply sent from the bar, under the commits above and past ten replies', function () { + fakeLongThread(); + + $screen = Native::visit('/log/commits/c2')->assertSet('scrollRequest', 0); + + $screen->input('reply-input', 'My fresh reply')->tap('send-reply')->assertSet('repliesShown', true); + + $staged = stagedReplyId($screen); + $children = childRefs($screen, 'thread-scroll'); + + expect($children)->toBe([ + 'earlier-commits', 'commit-c1', 'focused-commit', + ...array_map(fn (int $n): string => "thread-reply-r{$n}", range(1, 10)), + "thread-reply-{$staged}", null, 'reply-bar-clearance', + ]) + ->and($screen->instance()->scrollTarget)->toBe(array_search("thread-reply-{$staged}", $children, true)) + ->and(scrolledTo($screen))->toBe(["thread-reply-{$staged}", 1]); + + // devnull's reply takes the staged one's place, on the same row, and the page doesn't scroll again. + finishRefreshes($screen)->assertDontSee('staged'); + + expect(scrolledTo($screen))->toBe(['thread-reply-r99', 1]); +}); + +it('scrolls to a reply sent from the sheet, past replies opened in place under the ones before it', function () { + fakeLongThread(); + + $screen = Native::visit('/log/commits/c2') + ->tap('earlier-commits') + ->tap('replies-c2') + ->tap('replies-r1'); + + finishRefreshes($screen) + ->assertSee('A reply to the first reply') + ->assertSet('scrollRequest', 0); + + $screen->call('replyInSheet', 'c2')->input('sheet-body', 'My fresh reply')->tap('sheet-commit'); + + $staged = stagedReplyId($screen); + $children = childRefs($screen, 'thread-scroll'); + + expect(array_slice($children, 0, 5))->toBe(['commit-c0', 'commit-c1', 'focused-commit', 'thread-reply-r1', 'thread-reply-n1']) + ->and(scrolledTo($screen))->toBe(["thread-reply-{$staged}", 1]) + ->and($screen->instance()->scrollTarget)->toBe(14); + + finishRefreshes($screen); + + expect(scrolledTo($screen))->toBe(['thread-reply-r99', 1]); +}); + +it('follows a reply to your own commit when devnull has it carry your thread on', function () { + // The commit is yours, and so is the reply, so once devnull has it, it's the next part of your thread, below the + // commit's replies, rather than one of them. + fakeLongThread(commit: ['author' => userJson()]); + + $screen = Native::visit('/log/commits/c2'); + $screen->input('reply-input', 'My fresh reply')->tap('send-reply'); + + expect(scrolledTo($screen))->toBe(['thread-reply-'.stagedReplyId($screen), 1]); + + finishRefreshes($screen); + + // It moved a row down, past "Show more" under the replies, so the page goes after it. + expect(scrolledTo($screen))->toBe(['commit-r99', 2]); +}); diff --git a/tests/Feature/Screens/SelfThreadTest.php b/tests/Feature/Screens/SelfThreadTest.php new file mode 100644 index 00000000..b78153cc --- /dev/null +++ b/tests/Feature/Screens/SelfThreadTest.php @@ -0,0 +1,204 @@ + 'http://devnull.test']); + signIn(); +}); + +/** + * One of Ada's commits, $minutes ago, replying to $parent. + * + * @param array $overrides + * @return array + */ +function adaJson(string $id, ?string $parent = null, int $minutes = 30, array $overrides = []): array +{ + return commitJson([ + 'id' => $id, + 'parent_id' => $parent, + 'body' => "Ada's {$id}", + 'author' => userJson(['handle' => 'ada', 'name' => 'Ada', 'lane' => 2]), + 'created_at' => now()->subMinutes($minutes)->toIso8601ZuluString(), + ...$overrides, + ]); +} + +/** + * Serves a commit page and the replies of every commit in $replies, by id, and 404s anything else. + * + * @param array $commit + * @param list> $ancestors + * @param array>> $replies + */ +function serveSelfThread(array $commit, array $ancestors, array $replies): void +{ + Http::fake(function (Request $request) use ($commit, $ancestors, $replies) { + $path = (string) parse_url($request->url(), PHP_URL_PATH); + + if ($path === '/api/v1/commits/'.$commit['id']) { + return Http::response(commitPageJson($commit, $ancestors)); + } + + if (preg_match('#^/api/v1/commits/([^/]+)/replies$#', $path, $match) === 1 && array_key_exists($match[1], $replies)) { + return Http::response(pageJson($replies[$match[1]])); + } + + if (str_ends_with($path, '/related')) { + return Http::response(['data' => []]); + } + + return Http::response(['message' => 'No fake.'], 404); + }); +} + +/** + * The refs of the rows down a commit page, top to bottom. + * + * @return list + */ +function selfThreadRows(TestableComponent $screen): array +{ + return array_values(array_filter(childRefs($screen, 'thread-scroll'), fn (?string $ref): bool => $ref !== 'reply-bar-clearance')); +} + +/** + * The text of a commit's place in its thread. + */ +function threadPositionOf(TestableComponent $screen, string $id): string +{ + $text = findNode(nodeByRef($screen, 'thread-position-'.$id), fn (array $node): bool => ($node['type'] ?? null) === 'text'); + + return $text['props']['text'] ?? ''; +} + +it("reads an author's replies to themselves in order under the commit, as the web's thread", function () { + serveSelfThread(adaJson('c1', overrides: ['replies_count' => 2]), [], [ + 'c1' => [ + replyJson(['id' => 'r1', 'parent_id' => 'c1', 'body' => 'Grace answers', 'created_at' => now()->subMinutes(28)->toIso8601ZuluString()]), + adaJson('p2', 'c1', 25), + adaJson('later', 'c1', 5, ['body' => 'Ada again, later']), + ], + 'p2' => [replyJson(['id' => 'x1', 'parent_id' => 'p2', 'body' => 'Under part two']), adaJson('p3', 'p2', 20)], + 'p3' => [replyJson(['id' => 'y1', 'parent_id' => 'p3', 'body' => 'Under the last part'])], + ]); + + $screen = Native::visit('/log/commits/c1') + ->assertSee("Ada's p2") + ->assertSee("Ada's p3") + ->assertSee('Under the last part') + ->assertDontSee('Under part two') + ->assertDontSee('Grace answers') + ->assertDontSee('No replies yet.'); + + expect(selfThreadRows($screen))->toBe(['focused-commit', 'commit-p2', 'commit-p3', 'thread-reply-y1']) + ->and(threadPositionOf($screen, 'c1'))->toBe('1/3') + ->and(threadPositionOf($screen, 'p2'))->toBe('2/3') + ->and(threadPositionOf($screen, 'p3'))->toBe('3/3') + ->and(railNode($screen, 'commit-p2'))->toBe('dot') + // The last part's replies show under it, so its action row doesn't offer them again. + ->and(findNode(nodeByRef($screen, 'commit-p3'), fn (array $node): bool => ($node['ref'] ?? null) === 'replies-p3'))->toBeNull(); + + // The commit's own replies leave out the part that carries it on, and keep its later replies to itself. + $screen->tap('replies-c1')->assertSee('Grace answers')->assertSee('Ada again, later'); + + expect(selfThreadRows($screen))->toBe(['focused-commit', 'thread-reply-r1', 'thread-reply-later', 'commit-p2', 'commit-p3', 'thread-reply-y1']); +}); + +it('marks the earlier parts above a commit in the middle of its thread', function () { + serveSelfThread(adaJson('p2', 'c1', 20), [adaJson('c1', minutes: 30)], [ + 'c1' => [adaJson('p2', 'c1', 20)], + 'p2' => [], + ]); + + $screen = Native::visit('/log/commits/p2'); + + expect(threadPositionOf($screen, 'c1'))->toBe('1/2') + ->and(threadPositionOf($screen, 'p2'))->toBe('2/2'); +}); + +it("doesn't mark a commit its author replied to some other way first", function () { + serveSelfThread(adaJson('p2', 'c1', 10), [adaJson('c1', minutes: 30)], [ + 'c1' => [adaJson('first', 'c1', 20), adaJson('p2', 'c1', 10)], + 'p2' => [], + ]); + + $screen = Native::visit('/log/commits/p2')->assertSee("Ada's c1"); + + expect(findNode($screen->tree(), fn (array $node): bool => str_starts_with((string) ($node['ref'] ?? ''), 'thread-position-')))->toBeNull(); +}); + +it('shows ten parts at a time, and the rest from Show more of this thread', function () { + $replies = ['c1' => [adaJson('p2', 'c1', 29)]]; + + foreach (range(2, 11) as $part) { + $replies['p'.$part] = [adaJson('p'.($part + 1), 'p'.$part, 29 - $part)]; + } + + $replies['p12'] = []; + serveSelfThread(adaJson('c1', minutes: 30), [], $replies); + + $screen = Native::visit('/log/commits/c1') + ->assertSee("Ada's p11") + ->assertDontSee("Ada's p12"); + + expect(threadPositionOf($screen, 'c1'))->toBe('1/12+'); + + $screen->tap('more-thread')->assertSee("Ada's p12"); + + expect(threadPositionOf($screen, 'c1'))->toBe('1/12') + ->and(threadPositionOf($screen, 'p12'))->toBe('12/12') + ->and(findNode($screen->tree(), fn (array $node): bool => ($node['ref'] ?? null) === 'more-thread'))->toBeNull(); +}); + +it("leaves the author's next part out of a thread opened on the Log, and links to the thread instead", function () { + Http::fake(fn (Request $request) => match (parse_url($request->url(), PHP_URL_PATH)) { + '/api/v1/log/following' => Http::response(pageJson([adaJson('c1', overrides: ['replies_count' => 1])])), + '/api/v1/commits/c1/replies' => Http::response(pageJson([adaJson('p2', 'c1', 25), replyJson(['id' => 'r1', 'parent_id' => 'c1', 'body' => 'Grace answers'])])), + default => Http::response(['message' => 'No fake.'], 404), + }); + + $screen = Native::visit('/log')->assertDontSee('Show thread')->tap('replies-c1') + ->assertSee('Grace answers') + ->assertDontSee("Ada's p2") + ->assertSee('Show thread'); + + expect(array_map(fn ($reply): string => $reply->id, $screen->instance()->threads['c1']))->toBe(['r1']); + + $screen->tap('show-thread-c1')->assertNavigatedTo('/log/commits/c1'); +}); + +it("leaves a reply's next part out of its replies opened in place on the Log, and links that reply to its thread", function () { + $grace = userJson(['handle' => 'grace', 'name' => 'Grace', 'lane' => 4]); + + Http::fake(fn (Request $request) => match (parse_url($request->url(), PHP_URL_PATH)) { + '/api/v1/log/following' => Http::response(pageJson([adaJson('c1', overrides: ['replies_count' => 1])])), + '/api/v1/commits/c1/replies' => Http::response(pageJson([replyJson(['id' => 'r1', 'parent_id' => 'c1', 'body' => 'Grace answers', 'author' => $grace, 'replies_count' => 2])])), + '/api/v1/commits/r1/replies' => Http::response(pageJson([ + replyJson(['id' => 'g2', 'parent_id' => 'r1', 'body' => 'Grace carries on', 'author' => $grace, 'created_at' => now()->subMinutes(4)->toIso8601ZuluString()]), + replyJson(['id' => 'n1', 'parent_id' => 'r1', 'body' => 'Someone else answers Grace']), + ])), + default => Http::response(['message' => 'No fake.'], 404), + }); + + $screen = Native::visit('/log')->tap('replies-c1')->assertSee('Grace answers')->assertDontSee('Show thread') + ->tap('replies-r1') + ->assertSee('Someone else answers Grace') + ->assertDontSee('Grace carries on') + ->assertSee('Show thread'); + + expect(array_map(fn ($reply): string => $reply->id, $screen->instance()->threads['r1']))->toBe(['n1']) + ->and($screen->instance()->threadsContinued)->toBe(['r1']); + + $screen->tap('show-thread-r1')->assertNavigatedTo('/log/commits/r1'); +}); + +it('links to the thread when devnull says which reply carries it on', function () { + Http::fake(['devnull.test/api/v1/log/following*' => Http::response(pageJson([adaJson('c1', overrides: ['continuation_id' => 'p2'])]))]); + + Native::visit('/log')->assertSee('Show thread')->tap('show-thread-c1')->assertNavigatedTo('/log/commits/c1'); +}); diff --git a/tests/Feature/Screens/SeriesTest.php b/tests/Feature/Screens/SeriesTest.php index ad0ff31a..07829c2b 100644 --- a/tests/Feature/Screens/SeriesTest.php +++ b/tests/Feature/Screens/SeriesTest.php @@ -131,7 +131,8 @@ function railRunsOn(TestableComponent $screen, string $ref): bool ->and(railRunsOn($screen, 'focused-commit'))->toBeTrue() ->and(railRunsOn($screen, 'commit-p3'))->toBeFalse(); - $screen->tap('commit-p3')->assertNavigatedTo('/log/commits/p3'); + // A part in the tree moves the page to it rather than pushing another. + $screen->tap('commit-p3')->assertNoNavigation()->assertSet('id', 'p3'); }); it('puts a part\'s replies under it, above the later parts, as on the web', function () { @@ -154,7 +155,10 @@ function railRunsOn(TestableComponent $screen, string $ref): bool ->assertSee('Agreed') ->assertDontSee('2 replies'); - expect(threadRows($screen))->toBe(['focused-commit', 'thread-reply-r1', 'thread-reply-r2', 'commit-p2', 'commit-p3']); + expect(threadRows($screen))->toBe(['focused-commit', 'thread-reply-r1', 'thread-reply-r2', 'commit-p2', 'commit-p3']) + // The focused part gave up its hairline to its replies, and the later parts follow, so the last reply ends on it. + ->and(rendersRef($screen, 'thread-end-r2'))->toBeTrue() + ->and(rendersRef($screen, 'thread-end-r1'))->toBeFalse(); }); it('keeps replies at the foot of the last part\'s page', function () { @@ -167,7 +171,9 @@ function railRunsOn(TestableComponent $screen, string $ref): bool ->assertSee('The end'); expect(threadRows($screen))->toBe(['commit-p1', 'commit-p2', 'focused-commit', 'thread-reply-r1']) - ->and(railRunsOn($screen, 'focused-commit'))->toBeFalse(); + ->and(railRunsOn($screen, 'focused-commit'))->toBeFalse() + // Nothing follows the replies at the foot of the page, so they end on no hairline. + ->and(rendersRef($screen, 'thread-end-r1'))->toBeFalse(); }); it('keeps a deleted part in its place in the series', function () { diff --git a/tests/Fixtures/views/mention-suggestions.blade.php b/tests/Fixtures/views/mention-suggestions.blade.php new file mode 100644 index 00000000..d29b0fbf --- /dev/null +++ b/tests/Fixtures/views/mention-suggestions.blade.php @@ -0,0 +1,4 @@ +{{-- The mention list alone, for MentionSuggestionsTest: the partial with whatever options the test passes. --}} + + @include('native.partials.mention-suggestions', ['field' => 'body', ...$options]) + diff --git a/tests/Pest.php b/tests/Pest.php index d1bf556c..42366d00 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -409,7 +409,8 @@ function userJson(array $overrides = []): array $username = $overrides['handle'] ?? 'local_dev'; return [ - 'id' => '0199e5c4-0000-7000-8000-000000000001', + // Someone else, named by a handle of their own, is someone else to the app too. + 'id' => $username === 'local_dev' ? '0199e5c4-0000-7000-8000-000000000001' : 'user-'.$username, 'handle' => $username, 'name' => 'Local Dev', 'avatar_url' => 'https://avatars.githubusercontent.com/u/1?v=4', @@ -426,6 +427,17 @@ function userJson(array $overrides = []): array ]; } +/** + * Someone replying to a commit, who isn't its author. + * + * @param array $overrides + * @return array + */ +function replierJson(array $overrides = []): array +{ + return userJson(['id' => '0199e5c4-0000-7000-8000-0000000000aa', 'handle' => 'replier', 'name' => 'Re Plier', 'lane' => 5, ...$overrides]); +} + /** * A user with their counts, as `/me`, a profile and a key sync send them. * @@ -525,14 +537,16 @@ function commitPageJson(array $commit, array $ancestors = [], array $series = [] /** * A reply as `GET /commits/{id}/replies` sends it: like any commit, but without - * stars_count or starred, which that list doesn't load. + * stars_count or starred, which that list doesn't load. It comes from someone + * other than the commit's author unless a test says who, since a reply of + * theirs carries their own thread on (see SelfThread). * * @param array $overrides * @return array */ function replyJson(array $overrides = []): array { - return array_diff_key(commitJson($overrides), array_flip(['stars_count', 'starred'])); + return array_diff_key(commitJson(['author' => replierJson(), ...$overrides]), array_flip(['stars_count', 'starred'])); } /** diff --git a/tests/Support/GlassOpacity.php b/tests/Support/GlassOpacity.php new file mode 100644 index 00000000..4acf0dac --- /dev/null +++ b/tests/Support/GlassOpacity.php @@ -0,0 +1,24 @@ +markTestSkipped('Needs a mobile-air that reads glass/N (NativePHP/mobile-air#735)'); + } + } +} diff --git a/tests/Support/LayoutAnimation.php b/tests/Support/LayoutAnimation.php new file mode 100644 index 00000000..155686c8 --- /dev/null +++ b/tests/Support/LayoutAnimation.php @@ -0,0 +1,25 @@ +markTestSkipped('Needs a mobile-air with layout animation (NativePHP/mobile-air#736)'); + } + } +} diff --git a/tests/Unit/Devnull/SelfThreadTest.php b/tests/Unit/Devnull/SelfThreadTest.php new file mode 100644 index 00000000..5f9cc7e6 --- /dev/null +++ b/tests/Unit/Devnull/SelfThreadTest.php @@ -0,0 +1,105 @@ + $overrides + */ +function threadCommit(string $id, string $handle = 'ada', ?string $parent = null, int $minutes = 10, array $overrides = []): Commit +{ + return Commit::fromArray(commitJson([ + 'id' => $id, + 'parent_id' => $parent, + 'author' => userJson(['handle' => $handle]), + 'created_at' => now()->subMinutes($minutes)->toIso8601ZuluString(), + ...$overrides, + ])); +} + +/** + * @param array> $replies + * @return Closure(Commit): (list|null) + */ +function repliesFrom(array $replies): Closure +{ + return fn (Commit $commit): ?array => $replies[$commit->id] ?? null; +} + +it("carries a commit on with its author's earliest reply to it", function () { + $commit = threadCommit('c1', minutes: 30); + $replies = [ + threadCommit('r1', 'grace', 'c1', 25), + threadCommit('p3', 'ada', 'c1', 10), + threadCommit('p2', 'ada', 'c1', 20), + ]; + + expect(SelfThread::next($commit, $replies)?->id)->toBe('p2') + ->and(array_map(fn (Commit $reply): string => $reply->id, SelfThread::others($commit, $replies)))->toBe(['r1', 'p3']); +}); + +it('never carries a commit on with a deleted reply, a quote, or a reply still on its way', function () { + $commit = threadCommit('c1', minutes: 30); + + expect(SelfThread::next($commit, [ + Commit::fromArray(['id' => 'gone', 'parent_id' => 'c1', 'deleted_at' => now()->toIso8601ZuluString()]), + threadCommit('quote', 'ada', null, 20, ['quoted_commit_id' => 'c1']), + threadCommit('staged', 'ada', 'c1', 1, ['status' => Commit::Staged]), + threadCommit('r1', 'grace', 'c1', 15), + ]))->toBeNull(); +}); + +it("takes devnull's word for which reply carries the thread on", function () { + $commit = threadCommit('c1', minutes: 30, overrides: ['continuation_id' => 'p3']); + + expect(SelfThread::next($commit, [threadCommit('p2', 'ada', 'c1', 20), threadCommit('p3', 'ada', 'c1', 10)])?->id)->toBe('p3'); +}); + +it('walks down the parts as far as their replies have come', function () { + $c1 = threadCommit('c1', minutes: 30); + $p2 = threadCommit('p2', 'ada', 'c1', 20); + $p3 = threadCommit('p3', 'ada', 'p2', 10); + + $waiting = SelfThread::below($c1, repliesFrom(['c1' => [$p2]])); + $ended = SelfThread::below($c1, repliesFrom(['c1' => [$p2], 'p2' => [$p3], 'p3' => [threadCommit('r1', 'grace', 'p3', 5)]])); + + expect(array_map(fn (Commit $part): string => $part->id, $waiting->parts))->toBe(['p2']) + ->and($waiting->waiting)->toBe('p2') + ->and($waiting->hasEnded)->toBeFalse() + ->and(array_map(fn (Commit $part): string => $part->id, $ended->parts))->toBe(['p2', 'p3']) + ->and($ended->hasEnded)->toBeTrue() + ->and($ended->waiting)->toBeNull(); +}); + +it('stops at the limit and says another part follows', function () { + $c1 = threadCommit('c1', minutes: 30); + $p2 = threadCommit('p2', 'ada', 'c1', 20); + $p3 = threadCommit('p3', 'ada', 'p2', 10); + + $thread = SelfThread::below($c1, repliesFrom(['c1' => [$p2], 'p2' => [$p3]]), limit: 1); + + expect(array_map(fn (Commit $part): string => $part->id, $thread->parts))->toBe(['p2']) + ->and($thread->hasMore)->toBeTrue() + ->and($thread->hasEnded)->toBeFalse(); +}); + +it('counts the earlier parts above a commit, only while each is the one its author carried on', function () { + $c1 = threadCommit('c1', minutes: 30); + $p2 = threadCommit('p2', 'ada', 'c1', 20); + $p3 = threadCommit('p3', 'ada', 'p2', 10); + $other = threadCommit('o1', 'ada', 'p2', 15); + + expect(SelfThread::above([$c1, $p2], $p3, repliesFrom(['c1' => [$p2], 'p2' => [$p3]])))->toBe([2, null]) + ->and(SelfThread::above([$c1, $p2], $p3, repliesFrom(['p2' => [$p3]])))->toBe([1, 'c1']) + // Ada's earliest reply to p2 is o1, so p3 isn't part of the thread. + ->and(SelfThread::above([$c1, $p2], $p3, repliesFrom(['p2' => [$other, $p3]])))->toBe([0, null]) + ->and(SelfThread::above([threadCommit('g1', 'grace')], threadCommit('p9', 'ada', 'g1'), repliesFrom([])))->toBe([0, null]); +}); + +it("writes a commit's place in its thread as the web does", function () { + expect(SelfThread::position(2, 5, false))->toBe('2/5') + ->and(SelfThread::position(1, 12, true))->toBe('1/12+') + ->and(SelfThread::position(1, 1, false))->toBeNull(); +}); diff --git a/tests/Unit/Devnull/ThreadRowsTest.php b/tests/Unit/Devnull/ThreadRowsTest.php new file mode 100644 index 00000000..dfad7144 --- /dev/null +++ b/tests/Unit/Devnull/ThreadRowsTest.php @@ -0,0 +1,86 @@ + $id, 'parent_id' => $parent, 'author' => userJson(['handle' => $handle, 'lane' => strlen($handle)]), ...$overrides])); +} + +/** + * The rows of a chain five replies deep under c1, with a second reply at the deepest step (r3b), each opened. + * + * @return array> + */ +function deepRows(int $opensInPlace = PHP_INT_MAX): array +{ + $commit = Commit::fromArray(commitJson(['id' => 'c1', 'author' => userJson(['handle' => 'ada'])])); + $threads = [ + 'c1' => [nestedReply('r1', 'c1', 'grace')], + 'r1' => [nestedReply('r2', 'r1', 'linus')], + 'r2' => [nestedReply('r3', 'r2', 'alan'), nestedReply('r3b', 'r2', 'barbara')], + 'r3' => [nestedReply('r4', 'r3', 'edsger', ['quoted_commit_id' => 'r3'])], + 'r4' => [nestedReply('r5', 'r4', 'ken')], + ]; + + $rows = ThreadRows::under($commit, $threads, ['r4' => 'next'], [], opensInPlace: $opensInPlace, onPage: true); + + return array_column(array_map(fn (array $row): array => [$row['key'], $row['data']], $rows), 1, 0); +} + +it('steps replies in up to the web\'s depth of three, and lines deeper ones up under the third', function () { + $rows = deepRows(); + + expect(array_keys($rows))->toBe(['thread-reply-r1', 'thread-reply-r2', 'thread-reply-r3', 'thread-reply-r4', 'thread-reply-r5', 'thread-more-r4', 'thread-reply-r3b']) + ->and(array_map(fn (array $row): int => $row['indent'], $rows))->toBe([ + 'thread-reply-r1' => 0, + 'thread-reply-r2' => 32, + 'thread-reply-r3' => 64, + 'thread-reply-r4' => 64, + 'thread-reply-r5' => 64, + 'thread-more-r4' => 64, + 'thread-reply-r3b' => 64, + ]); +}); + +it('says who a flattened reply answers, and draws it no lines of its own', function () { + $rows = deepRows(); + + expect($rows['thread-reply-r3']['replyingTo'])->toBeNull() + ->and($rows['thread-reply-r3']['links'])->toBeTrue() + ->and($rows['thread-reply-r4']['replyingTo'])->toBe('quoting @alan') + ->and($rows['thread-reply-r5']['replyingTo'])->toBe('replying to @edsger') + ->and($rows['thread-reply-r4']['links'])->toBeFalse() + ->and($rows['thread-reply-r4']['hasNext'])->toBeFalse() + ->and($rows['thread-more-r4']['links'])->toBeFalse() + ->and($rows['thread-more-r4']['to'])->toBe('@edsger'); +}); + +it('hangs each reply at the deepest step on its own elbow, with the line of the reply it answers running on past', function () { + $rows = deepRows(); + $lane = $rows['thread-reply-r3b']['lane']; + + // r3 and r3b both answer r2, so both hang on elbows off r2's line, which runs past r3's own replies to r3b. + expect($rows['thread-reply-r3']['previousLane'])->toBeNull() + ->and($rows['thread-reply-r3b']['previousLane'])->toBeNull() + ->and($rows['thread-reply-r3']['hasNext'])->toBeFalse() + ->and($rows['thread-reply-r3']['spines'])->toBe([['left' => 107.5, 'lane' => $lane, 'top' => 22]]) + ->and($rows['thread-reply-r4']['spines'])->toBe([['left' => 107.5, 'lane' => $lane]]) + ->and($rows['thread-more-r4']['spines'])->toBe([['left' => 107.5, 'lane' => $lane]]) + ->and($rows['thread-reply-r3b']['spines'])->toBe([]) + // Above that the replies chain from avatar to avatar as before. + ->and($rows['thread-reply-r2']['hasNext'])->toBeTrue() + ->and($rows['thread-reply-r3b']['last'])->toBeTrue(); +}); + +it('opens replies in place as deep as the caller allows', function () { + $inPlace = fn (array $rows): array => array_map(fn (array $row): bool => $row['repliesInPlace'], array_filter($rows, fn (array $row): bool => isset($row['repliesInPlace']))); + + expect($inPlace(deepRows()))->each->toBeTrue() + ->and($inPlace(deepRows(opensInPlace: 1))) + ->toBe(['thread-reply-r1' => true, 'thread-reply-r2' => false, 'thread-reply-r3' => false, 'thread-reply-r4' => false, 'thread-reply-r5' => false, 'thread-reply-r3b' => false]); +}); diff --git a/tests/Unit/Devnull/TimelineTest.php b/tests/Unit/Devnull/TimelineTest.php index b21edb2a..c68a082b 100644 --- a/tests/Unit/Devnull/TimelineTest.php +++ b/tests/Unit/Devnull/TimelineTest.php @@ -3,6 +3,7 @@ use App\Devnull\Data\Commit; use App\Devnull\Data\TimelineRow; use App\Devnull\LastVisit; +use App\Devnull\Ownership; use App\Devnull\Timeline; use Carbon\CarbonImmutable; @@ -166,14 +167,18 @@ function describeRows(array $rows): array timelineCommit('c1', 'grace', '2026-10-15T09:00:00Z'), ]; - expect(LastVisit::firstSeenId($commits, '2026-10-15T10:00:00+00:00', 'ada'))->toBe('c2') - ->and(LastVisit::firstSeenId($commits, '2026-10-15T09:30:00+00:00', 'ada'))->toBe('c1') + $ada = new Ownership('ada'); + + expect(LastVisit::firstSeenId($commits, '2026-10-15T10:00:00+00:00', $ada))->toBe('c2') + ->and(LastVisit::firstSeenId($commits, '2026-10-15T09:30:00+00:00', $ada))->toBe('c1') // Nothing new. - ->and(LastVisit::firstSeenId($commits, '2026-10-15T11:00:00+00:00', 'ada'))->toBeNull() + ->and(LastVisit::firstSeenId($commits, '2026-10-15T11:00:00+00:00', $ada))->toBeNull() // Only your own commit is new. - ->and(LastVisit::firstSeenId($commits, '2026-10-15T10:00:00+00:00', 'grace'))->toBeNull() + ->and(LastVisit::firstSeenId($commits, '2026-10-15T10:00:00+00:00', new Ownership('grace')))->toBeNull() + // Only a commit from an organization you're in is new, as the web counts it. + ->and(LastVisit::firstSeenId($commits, '2026-10-15T10:00:00+00:00', new Ownership('linus', ['grace'])))->toBeNull() // Everything is new, so there's nothing to mark. - ->and(LastVisit::firstSeenId($commits, '2026-10-15T08:00:00+00:00', 'ada'))->toBeNull() + ->and(LastVisit::firstSeenId($commits, '2026-10-15T08:00:00+00:00', $ada))->toBeNull() // A first visit. - ->and(LastVisit::firstSeenId($commits, null, 'ada'))->toBeNull(); + ->and(LastVisit::firstSeenId($commits, null, $ada))->toBeNull(); });