From e082ad509ab65df393b040cf3f37ca3e1d89cea1 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Tue, 17 Nov 2026 00:57:13 +0000 Subject: [PATCH 1/3] Post as an organization you're in, as the web does The web lets a member of a GitHub organization post a commit, a quote or a reply as that organization. The app now does too. - GET /me's organizations are kept on the phone (Account), and refreshed whenever /me is. - The composer sheet shows who the commit goes out as above the field. A tap opens a menu of you and your organizations. The reply bar on a commit's page has the same avatar at its start, and hands its choice to the reply sheet and back. - The choice goes to devnull as `author`, which the API already takes, and rides in the outbox, so a staged commit shows the organization as its author. Commit and Reply use the organization's lane. - A scheduled commit goes out as the organization too, and the Scheduled list says "As @handle" as the web's does. - If devnull turns a commit down (you left the organization, or it's rate limited), the usual toast says why and the draft comes back with the organization still picked. The app asks /me again, and a composer whose organization is gone posts as you. - Tapping an organization in Notifications opens its page. Co-Authored-By: Claude Opus 5.5 --- app/Devnull/Account.php | 29 +- app/Devnull/Client.php | 26 +- app/Devnull/Data/CurrentUser.php | 22 ++ app/Devnull/Data/ScheduledCommit.php | 5 +- app/Devnull/PostAs.php | 106 ++++++ app/Models/PendingWrite.php | 43 ++- app/NativeComponents/CommitDetail.php | 38 +++ .../Concerns/OpensCommitSheet.php | 56 +++- .../Concerns/RefreshesInBackground.php | 1 + app/NativeComponents/Concerns/SyncsOutbox.php | 27 +- app/NativeComponents/Notifications.php | 15 +- app/NativeComponents/Onboarding.php | 1 + app/NativeComponents/ThisDevice.php | 1 + .../views/native/commit-detail.blade.php | 9 +- .../native/partials/commit-sheet.blade.php | 14 +- .../native/partials/dashed-ring.blade.php | 6 +- .../views/native/partials/post-as.blade.php | 28 ++ .../native/partials/rail-avatar.blade.php | 4 +- .../partials/sheet-bar-button.blade.php | 8 +- .../views/native/scheduled-commits.blade.php | 7 + tests/Feature/Screens/NotificationsTest.php | 7 + tests/Feature/Screens/PostAsTest.php | 312 ++++++++++++++++++ 22 files changed, 721 insertions(+), 44 deletions(-) create mode 100644 app/Devnull/PostAs.php create mode 100644 resources/views/native/partials/post-as.blade.php create mode 100644 tests/Feature/Screens/PostAsTest.php 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 f20c88a3..322153b7 100644 --- a/app/NativeComponents/CommitDetail.php +++ b/app/NativeComponents/CommitDetail.php @@ -13,6 +13,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; @@ -62,6 +63,10 @@ * 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, as the web's reply composer does (see PostAs). The sheet + * takes the choice with the draft, and gives it back. */ class CommitDetail extends NativeComponent { @@ -129,6 +134,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. */ @@ -349,6 +359,7 @@ public function sendReply(): void 'images' => PendingWrite::imagePayload($this->replyImages), 'stash' => $this->replyStashName(), 'composer' => 'bar', + ...PendingWrite::authorPayload(PostAs::author($this->replyAuthor)), ]); if ($write === null) { @@ -364,6 +375,32 @@ 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 in the sheet starts as whoever the bar posts as. + */ + protected function sheetAuthorFor(string $view): ?string + { + return $view === 'reply' && $this->sheetCommit?->id === $this->id ? $this->replyAuthor : null; + } + + /** + * A choice made in the reply's sheet goes back to the bar with the draft. + */ + protected function sheetAuthorChanged(): void + { + if ($this->sheetView === 'reply' && $this->sheetCommit?->id === $this->id) { + $this->replyAuthor = $this->sheetAuthor; + } + } + /** * 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). @@ -535,6 +572,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..cae605a7 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,24 @@ 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; + $this->sheetAuthorChanged(); + } + + /** + * The sheet's author changed. A screen whose own composer handed it the draft keeps the choice too. + */ + protected function sheetAuthorChanged(): void + { + // + } + /** * 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 +364,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 +579,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 +591,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 +609,7 @@ private function forgetCommitSheet(): void $this->reportReason = ''; $this->reportDetails = ''; $this->sheetBody = ''; + $this->sheetAuthor = null; $this->sheetRestored = false; $this->sheetError = null; $this->forgetMention('sheetBody'); @@ -621,16 +657,20 @@ protected function stashSheetDraft(): void } /** - * The sheet starts from its stashed draft, with its photos and poll. A + * The sheet starts from its stashed draft, with its photos and poll, as + * you, or as the screen's own composer had it (see sheetAuthorFor()). A * commit devnull turned down that was written under it comes back whole, - * and leaves the outbox: from here it's a draft again. + * as the organization it was to go out as, and leaves the outbox: from + * here it's a draft again. */ private function restoreSheetDraft(): void { $name = $this->sheetStashName(); $failed = $name === null ? null : app(Outbox::class)->failedDraft($name); + $this->sheetAuthor = $this->sheetAuthorFor($this->sheetView); if ($failed !== null) { + $this->sheetAuthor = $failed->author(); $this->takeFailedCommit($failed); } @@ -643,6 +683,14 @@ private function restoreSheetDraft(): void $this->sheetRestored = ! $draft->isEmpty(); } + /** + * Who the sheet starts out posting as for $view: you, unless the screen's own composer handed it a choice. + */ + protected function sheetAuthorFor(string $view): ?string + { + return null; + } + private function takeFailedCommit(PendingWrite $write): void { $poll = $write->poll(); 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 c633a3d0..d73c27f8 100644 --- a/resources/views/native/commit-detail.blade.php +++ b/resources/views/native/commit-detail.blade.php @@ -120,10 +120,14 @@ is bare and the field is a Liquid Glass plate instead, the way the HIG floats controls over content; the hairline stays as a clear 1pt so the bar keeps the height Display::ReplyBarHeight counts on. + A member of a GitHub organization has the web's Post as at the start of the row: the avatar of whoever the + reply goes out as, which opens the menu (see PostAs), and Reply in that one's lane. + The expand button opens the reply in the composer sheet, which has the photos and preview the bar has no room for. It sits where partials/composer-plate puts a composer's tools: inside the plate on iOS, ahead of the field on Android. --}} + @php($replyPostingMe = app(\App\Devnull\Account::class)->user()) @@ -137,13 +141,16 @@ @include('native.partials.mention-suggestions', ['field' => 'reply', 'label' => 'Mention a developer']) + @if ($replyPostingMe !== null && \App\Devnull\PostAs::offered($replyAuthor)) + @include('native.partials.post-as', ['ref' => 'reply-post-as', 'me' => $replyPostingMe, 'picked' => $replyAuthor, 'method' => 'postAsInReply', 'size' => 32]) + @endif @include('native.partials.composer-plate', [ 'ref' => 'reply', 'field' => 'native.partials.reply-field', 'tools' => [['ref' => 'reply-expand', 'icon' => \App\Icons\Lucide::Maximize2, 'label' => 'Reply with photos or a preview', 'press' => "replyInSheet('{$commit->id}')"]], ]) @include('native.partials.body-counter', ['body' => $reply, 'ref' => 'reply-budget']) - Reply + Reply @if (\App\Devnull\Data\CommitBody::hasOversizedUrl($reply)) Each link must not be greater than {{ \App\Devnull\Data\BodyLink::MaxLength }} characters. diff --git a/resources/views/native/partials/commit-sheet.blade.php b/resources/views/native/partials/commit-sheet.blade.php index 97a5b0b1..9a3cb463 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..64f9d176 --- /dev/null +++ b/resources/views/native/partials/post-as.blade.php @@ -0,0 +1,28 @@ +{{-- + 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. + + $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($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/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..ed22582f --- /dev/null +++ b/tests/Feature/Screens/PostAsTest.php @@ -0,0 +1,312 @@ + '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'); + + expect(childRefs($screen, 'reply-row')[0])->toBe('reply-post-as') + ->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('hands the bar\'s choice to the reply sheet and takes the sheet\'s back', 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], + ]); + + $screen = Native::visit('/log/commits/c2', platform: 'ios') + ->call('postAsInReply', 'dev-null-sh') + ->call('replyInSheet', 'c2') + ->assertSet('sheetAuthor', 'dev-null-sh'); + + $screen->call('postAsInSheet', '')->assertSet('replyAuthor', null); + $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'); +}); From cbd3bc480aa5bdeb02987d5421530f4f5195707b Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Wed, 18 Nov 2026 03:17:00 +0000 Subject: [PATCH 2/3] Line the reply bar's Post as avatar up with the field's text The avatar led the row at the row's own inset, 12pt left of the text above it, where the photo button's icon used to line up. post-as takes an inset now, padded inside its tap target, and the bar passes pl-3. Co-Authored-By: Claude Opus 5.5 --- resources/views/native/commit-detail.blade.php | 6 +++--- resources/views/native/partials/post-as.blade.php | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/resources/views/native/commit-detail.blade.php b/resources/views/native/commit-detail.blade.php index b7bc855b..f2645514 100644 --- a/resources/views/native/commit-detail.blade.php +++ b/resources/views/native/commit-detail.blade.php @@ -137,8 +137,8 @@ the stash, then how long the reply is near the limit. 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, which opens the menu (see PostAs). The send button is then - filled with that one's lane. + 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)) @@ -170,7 +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]]] : [], + '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], diff --git a/resources/views/native/partials/post-as.blade.php b/resources/views/native/partials/post-as.blade.php index 64f9d176..b22f86a8 100644 --- a/resources/views/native/partials/post-as.blade.php +++ b/resources/views/native/partials/post-as.blade.php @@ -2,16 +2,18 @@ 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. + 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]) From eaeffdc1b582bc813b96f82ba34f3fbcafa0a87c Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Wed, 18 Nov 2026 05:05:18 +0000 Subject: [PATCH 3/3] Treat an organization's commits as yours when you're a member On the web any member of an organization owns its commits, whoever posted them (Commit::isOwnedBy on the server, useOwnsCommit on the web). The app only counted commits authored by you. Now one Ownership class decides it, from your id and the organizations GET /me last listed, and everything that asked "is this mine" asks it instead. For a member, an organization's commit now offers Delete (in More and in the commit page's nav bar), shows its star count instead of a star, can be quoted while pending, and can't be reported or have its poll voted on. Someone outside the org still gets the star and Report and never Delete. Pin stays person-only, as on the server and the web. No one gets a pastel on an organization's commit, matching the web, which hides it because it would go to whoever posted it. The API only lists who starred an organization's commit to the member who posted it, though the web shows it to every member. The stars sheet now says so on a 404 instead of offering Try again. If devnull refuses a delete because you've left the org, its message shows and the app asks /me again, so the commit stops offering Delete. Rows are cached against your organizations too, so they redraw when that changes. Deleting or posting an organization's commit no longer changes your own profile's kept commit count or list. Co-Authored-By: Claude Opus 5.5 --- app/Devnull/Account.php | 8 + app/Devnull/CommitMenu.php | 15 +- app/Devnull/Data/Commit.php | 11 +- app/Devnull/LastVisit.php | 8 +- app/Devnull/Ownership.php | 72 +++++ app/Devnull/ResponseCache.php | 35 ++- app/Devnull/RowInputs.php | 2 + app/NativeComponents/CommitDetail.php | 6 +- .../Concerns/OpensCommitSheet.php | 14 +- .../Concerns/OpensStargazers.php | 18 +- .../Concerns/RefreshesInBackground.php | 15 +- .../Concerns/ShowsCommits.php | 38 ++- .../Concerns/TalksToDevnull.php | 9 + .../Concerns/VotesOnPolls.php | 4 +- app/NativeComponents/Log.php | 12 +- app/NativeComponents/Organization.php | 1 + app/NativeComponents/Profile.php | 1 + app/NativeComponents/Search.php | 1 + app/NativeComponents/Starred.php | 1 + .../native/partials/commit-actions.blade.php | 14 +- .../native/partials/commit-poll.blade.php | 10 +- .../partials/stargazers-sheet.blade.php | 7 +- .../Screens/OrganizationCommitsTest.php | 256 ++++++++++++++++++ tests/Unit/Devnull/TimelineTest.php | 17 +- 24 files changed, 503 insertions(+), 72 deletions(-) create mode 100644 app/Devnull/Ownership.php create mode 100644 tests/Feature/Screens/OrganizationCommitsTest.php diff --git a/app/Devnull/Account.php b/app/Devnull/Account.php index 2163391d..07f3b10a 100644 --- a/app/Devnull/Account.php +++ b/app/Devnull/Account.php @@ -228,6 +228,14 @@ public function organizations(): array 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. * 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..1175a11e 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; @@ -327,15 +328,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/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/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..15d208c1 100644 --- a/app/Devnull/RowInputs.php +++ b/app/Devnull/RowInputs.php @@ -25,9 +25,11 @@ 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'] ?? [], diff --git a/app/NativeComponents/CommitDetail.php b/app/NativeComponents/CommitDetail.php index 23435b1b..dbc088eb 100644 --- a/app/NativeComponents/CommitDetail.php +++ b/app/NativeComponents/CommitDetail.php @@ -844,9 +844,12 @@ 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 { - return $this->commit !== null && $this->commit->author->username === $this->me()?->username; + return $this->commit !== null && $this->ownership()->owns($this->commit); } public function render(): View @@ -861,6 +864,7 @@ public function render(): View 'replyRows' => $this->replyRows, '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( diff --git a/app/NativeComponents/Concerns/OpensCommitSheet.php b/app/NativeComponents/Concerns/OpensCommitSheet.php index 4bcc9cf4..06df216a 100644 --- a/app/NativeComponents/Concerns/OpensCommitSheet.php +++ b/app/NativeComponents/Concerns/OpensCommitSheet.php @@ -540,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); } /** 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/RefreshesInBackground.php b/app/NativeComponents/Concerns/RefreshesInBackground.php index a64a3a82..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()); } @@ -219,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 { @@ -247,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..28c9c2d8 100644 --- a/app/NativeComponents/Concerns/ShowsCommits.php +++ b/app/NativeComponents/Concerns/ShowsCommits.php @@ -39,6 +39,9 @@ * * 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 { @@ -210,8 +213,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 { @@ -228,7 +231,8 @@ public function toggleStar(string $id): void /** * 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 +242,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; } @@ -258,8 +262,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 +403,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 +479,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 +502,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 +546,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/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..b9ffff17 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; @@ -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/Organization.php b/app/NativeComponents/Organization.php index c2f3718c..7a42a8ce 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), diff --git a/app/NativeComponents/Profile.php b/app/NativeComponents/Profile.php index d4c1e690..360f48c6 100644 --- a/app/NativeComponents/Profile.php +++ b/app/NativeComponents/Profile.php @@ -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/resources/views/native/partials/commit-actions.blade.php b/resources/views/native/partials/commit-actions.blade.php index 5c86cf74..690aa60f 100644 --- a/resources/views/native/partials/commit-actions.blade.php +++ b/resources/views/native/partials/commit-actions.blade.php @@ -10,12 +10,14 @@ 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. + 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 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. @@ -44,15 +46,17 @@ @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($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') : '')) @@ -80,7 +84,7 @@ {{ \App\Devnull\Display::compactCount($commit->pasteisCount) }} - @elseif ($pasteis !== null) + @elseif ($showsPastel) {{ \App\Devnull\Display::compactCount($commit->pasteisCount) }} @@ -122,7 +126,7 @@ - + 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/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/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/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(); });