diff --git a/app/Devnull/Account.php b/app/Devnull/Account.php index 22917423..2163391d 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,31 @@ 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(...)))) : []; + } + + /** + * 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 +260,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..a2b74bea 100644 --- a/app/Devnull/Client.php +++ b/app/Devnull/Client.php @@ -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/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/PostAs.php b/app/Devnull/PostAs.php new file mode 100644 index 00000000..03902d77 --- /dev/null +++ b/app/Devnull/PostAs.php @@ -0,0 +1,106 @@ + + */ + 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, the one posting now ticked. $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(fn (User $identity): TopBarAction => NavAction::make('post-as-'.$identity->username) + ->label($identity->name.' (@'.$identity->username.')') + ->icon(...self::icon($identity, $author)) + ->press($method."('".($identity->isOrganization ? $identity->username : '')."')") + ->toElement() + ->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()); + } + + /** + * A tick beside whoever posts now, and what each is beside the rest, as the menu has no room for avatars. + * + * @return array{ios: string, android: string} + */ + private static function icon(User $identity, ?User $author): array + { + $posting = $author === null ? ! $identity->isOrganization : $identity->isOrganization && $identity->username === $author->username; + $icon = match (true) { + $posting => Lucide::Check, + $identity->isOrganization => Lucide::Building2, + default => Lucide::UserRound, + }; + + return ['ios' => $icon->ios(), 'android' => $icon->android()]; + } +} 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..23435b1b 100644 --- a/app/NativeComponents/CommitDetail.php +++ b/app/NativeComponents/CommitDetail.php @@ -14,6 +14,7 @@ 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\Stash; @@ -71,6 +72,9 @@ * 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). */ class CommitDetail extends NativeComponent { @@ -180,6 +184,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. */ @@ -465,6 +474,7 @@ public function sendReply(): void 'images' => PendingWrite::imagePayload($this->replyImages), 'stash' => $this->replyStashName(), 'composer' => 'bar', + ...PendingWrite::authorPayload(PostAs::author($this->replyAuthor)), ]); if ($write === null) { @@ -482,6 +492,14 @@ public function sendReply(): void $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). @@ -708,6 +726,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(); diff --git a/app/NativeComponents/Concerns/OpensCommitSheet.php b/app/NativeComponents/Concerns/OpensCommitSheet.php index 19ac3922..4bcc9cf4 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) { @@ -549,10 +570,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 +582,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 +600,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 +648,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 +659,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/RefreshesInBackground.php b/app/NativeComponents/Concerns/RefreshesInBackground.php index 600f5c37..a64a3a82 100644 --- a/app/NativeComponents/Concerns/RefreshesInBackground.php +++ b/app/NativeComponents/Concerns/RefreshesInBackground.php @@ -155,6 +155,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); } 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/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/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/views/native/commit-detail.blade.php b/resources/views/native/commit-detail.blade.php index 3667a822..f2645514 100644 --- a/resources/views/native/commit-detail.blade.php +++ b/resources/views/native/commit-detail.blade.php @@ -136,9 +136,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()) @@ -167,6 +170,7 @@ @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], @@ -180,6 +184,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/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/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/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/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/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/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/PostAsTest.php b/tests/Feature/Screens/PostAsTest.php new file mode 100644 index 00000000..2b195312 --- /dev/null +++ b/tests/Feature/Screens/PostAsTest.php @@ -0,0 +1,357 @@ + '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('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'); +});