diff --git a/.github/media/shipit-demo.gif b/.github/media/shipit-demo.gif new file mode 100644 index 0000000000..8e06533699 Binary files /dev/null and b/.github/media/shipit-demo.gif differ diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index fbbb5efac0..cc6f0241ae 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -245,6 +245,14 @@ Sources: [composer](resources/js/components/commit-composer.tsx), [commit model] Livestream history: the team settled on calling posts **commits** and their list a **log** on [day one at 2:56:00](https://www.youtube.com/watch?v=6zCNQa3hNm0&t=10560s). At [3:02:19](https://www.youtube.com/watch?v=6zCNQa3hNm0&t=10939s), they agreed to rename the post model too, rather than changing only the UI. These are naming decisions, not timestamps proving the rename had finished. +### Launch posts + +On the web, put `/shipit` on its own final line in the composer and press Enter to select launch mode. Write what you shipped, optionally add a link or images, and press **Ship it** to publish. The command itself is removed from the draft; selecting launch mode never publishes automatically. Canceling launch mode keeps your text. The mode is stashed with the draft and shared between the inline composer and its dialog. Launches use the same moderation as other commits. Scheduling is unavailable in launch mode. + +A launch is a commit with `CommitType::Launch`; ordinary commits use `CommitType::Standard`. Its public card contains a ship. Signed-in readers can press **All aboard** to board as a passenger with their avatar as their face, or press **You're aboard** to step ashore. The author appears in the wheelhouse with their avatar and a captain’s hat, and cannot board their own launch. Boarding is separate from stars and can only happen once per person. Passengers stand on decks in little colored outfits. More passengers lower the ship in the water and make it wobble. At most sixteen avatars are rendered, with a `+N` label for the rest. Reduced motion disables the movements. + +Guests can see an approved launch and its public crew; boarding asks them to sign in. Hidden and deleted commits cannot be boarded. Blocks with the author prevent access, and blocked or banned passengers are omitted from the viewer's crew. Boarding is included in account exports and removed when the account is deleted. + ### Translating commits Public commits and replies offer **Translate** when their detected language differs from the reader's translation language. Choose a translation language in **Settings → Profile**, searching by its English or native name (for example, Hungarian or magyar), independently of the device language, or leave **Browser language (automatic)** selected to follow the browser. This private preference is saved to the account, included in the data export, and erased with the account. Regional variants share a language, such as English for `en-US` and `en-GB`. Language detection runs in the background for posts being read; undetermined posts initially offer Translate rather than guessing. Code-only or indeterminate text is not offered once detected. Generating translations requires sign-in and is limited to ten requests per minute. diff --git a/PRODUCT.md b/PRODUCT.md index 13dbe7437e..66ae5ffa78 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -34,6 +34,7 @@ What exists, one line each (details in the knowledge base): - **Commits:** text with code, images, link cards and embedded players, or a poll; replies, quotes, threads, scheduling, translation. - **Logs:** Following, Latest, and Trending. - **Engagement:** follows, stars, saved commits, pins, mentions, and pastéis (an opt-in daily allowance of pastries). +- **Launch posts:** `/shipit` selects a launch commit for celebrating a release; readers board its public ship as passengers, separately from stars. The author is the captain. Boarding respects moderation and blocks, and survives reloads. - **Profiles:** mirrored from GitHub, with an activity graph, streaks, achievements, a Unix rank, and a live marker while you stream on YouTube. - **Organization pages:** GitHub organizations get a page mirrored from GitHub once an approved commit mentions them, and `@organization` mentions link to it. Their members post commits as the organization, which readers see from the organization alone. - **Remotes:** private one-to-one and group messages (orgs), and calls, one-to-one or in an org. diff --git a/app/Actions/CreateCommit.php b/app/Actions/CreateCommit.php index a08c3c009b..2840d353d4 100644 --- a/app/Actions/CreateCommit.php +++ b/app/Actions/CreateCommit.php @@ -7,6 +7,7 @@ use App\Dto\NewPoll; use App\Dto\ThreadEngagement; use App\Enums\CommitStatus; +use App\Enums\CommitType; use App\Enums\CommitUpdate; use App\Enums\UserUpdate; use App\Events\CommitsUpdated; @@ -62,7 +63,7 @@ public function __construct( * @param array $imageDescriptions * @param array $replyRecipients */ - public function handle(User $user, string $body, ?Commit $parent = null, ?Commit $quotedCommit = null, array $images = [], array $imageDescriptions = [], bool|string $linkPreview = true, ?NewPoll $poll = null, array $replyRecipients = [], ?Organization $organization = null): Commit + public function handle(User $user, string $body, ?Commit $parent = null, ?Commit $quotedCommit = null, array $images = [], array $imageDescriptions = [], bool|string $linkPreview = true, ?NewPoll $poll = null, array $replyRecipients = [], ?Organization $organization = null, CommitType $type = CommitType::Standard): Commit { $url = match ($linkPreview) { true => $this->urls->first($body), @@ -70,7 +71,7 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit default => $linkPreview, }; - return DB::transaction(function () use ($user, $body, $parent, $quotedCommit, $images, $imageDescriptions, $url, $poll, $replyRecipients, $organization): Commit { + return DB::transaction(function () use ($user, $body, $parent, $quotedCommit, $images, $imageDescriptions, $url, $poll, $replyRecipients, $organization, $type): Commit { $linkPreview = $this->linkPreviewFor($url); $createdAt = now(); $hasGoodReputation = $user->hasGoodReputation(); @@ -80,6 +81,7 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit 'user_id' => $user->id, 'author_id' => $organization->id ?? $user->id, 'body' => $this->emojiShortcodes->replace($body), + 'type' => $type, 'mentions' => [...$replyRecipients, ...$mentions], 'parent_id' => $parent?->id, 'root_id' => $parent?->threadRootId(), diff --git a/app/Actions/CreateExport.php b/app/Actions/CreateExport.php index 13b11294ce..23eb891c80 100644 --- a/app/Actions/CreateExport.php +++ b/app/Actions/CreateExport.php @@ -45,6 +45,7 @@ * polls: Generator, * poll_votes: Generator, * stars: Generator, + * launch_boardings: Generator, * following: Generator, * followers: Generator, * muting: Generator, @@ -76,7 +77,7 @@ public function handle(User $user): array { return [ - 'schema_version' => 8, + 'schema_version' => 9, 'exported_at' => now()->toIso8601String(), 'profile' => [ 'github_id' => $user->github_id, @@ -123,6 +124,7 @@ public function handle(User $user): array 'polls' => $this->polls($user), 'poll_votes' => $this->pollVotes($user), 'stars' => $this->stars($user), + 'launch_boardings' => $this->launchBoardings($user), 'following' => $this->handles($user->following()), 'followers' => $this->handles($user->followers()), 'muting' => $this->handles($user->muting()), @@ -198,7 +200,7 @@ private function commits(User $user): Generator { $commits = $user->commits() ->withTrashed() - ->select(['id', 'parent_id', 'quoted_commit_id', 'body', 'status', 'pasteis_count', 'created_at', 'updated_at', 'deleted_at']) + ->select(['id', 'parent_id', 'quoted_commit_id', 'body', 'type', 'status', 'pasteis_count', 'created_at', 'updated_at', 'deleted_at']) ->with('images:id,commit_id') ->lazyById(500); @@ -215,6 +217,7 @@ private function commits(User $user): Generator 'body' => $commit->body, 'cached_translations' => $cached[$translations->key($commit)], 'status' => $commit->status->value, + 'type' => $commit->type->value, 'pasteis_count' => $commit->pasteis_count, 'images' => $commit->images->map(fn (CommitImage $image): string => $image->url())->all(), 'created_at' => $commit->created_at->toIso8601String(), @@ -248,6 +251,7 @@ private function organizationCommits(User $user): Generator 'quoted_commit_id' => $commit->quoted_commit_id, 'body' => $commit->body, 'status' => $commit->status->value, + 'type' => $commit->type->value, 'images' => $commit->images->map(fn (CommitImage $image): string => $image->url())->all(), 'created_at' => $commit->created_at->toIso8601String(), 'deleted_at' => $commit->deleted_at?->toIso8601String(), @@ -331,6 +335,20 @@ private function stars(User $user): Generator } } + /** + * @return Generator + */ + private function launchBoardings(User $user): Generator + { + /** @var LazyCollection $boardings */ + $boardings = DB::table('launch_passengers')->where('user_id', $user->id) + ->select(['commit_id', 'created_at'])->lazyById(500, 'commit_id'); + + foreach ($boardings as $boarding) { + yield ['commit_id' => $boarding->commit_id, 'boarded_at' => CarbonImmutable::parse($boarding->created_at)->toIso8601String()]; + } + } + /** * The messages the user sent. What others sent them is theirs to export. * diff --git a/app/Enums/CommitType.php b/app/Enums/CommitType.php new file mode 100644 index 0000000000..7d5defa210 --- /dev/null +++ b/app/Enums/CommitType.php @@ -0,0 +1,11 @@ +unlockedBadgeNames($user); $organization = $request->organization(); - $commit = $action->handle($user, $request->string('body')->value(), quotedCommit: $request->quotedCommit(), images: $request->images(), imageDescriptions: $request->imageDescriptions(), linkPreview: $request->linkPreview(), poll: $request->poll(), organization: $organization); + $commit = $action->handle($user, $request->string('body')->value(), quotedCommit: $request->quotedCommit(), images: $request->images(), imageDescriptions: $request->imageDescriptions(), linkPreview: $request->linkPreview(), poll: $request->poll(), organization: $organization, type: $request->enum('type', CommitType::class) ?? CommitType::Standard); $unlocked = $achievements->unlockedBadgeNames($user)->diff($before)->values(); diff --git a/app/Http/Controllers/CommitLaunchController.php b/app/Http/Controllers/CommitLaunchController.php new file mode 100644 index 0000000000..60d32ef284 --- /dev/null +++ b/app/Http/Controllers/CommitLaunchController.php @@ -0,0 +1,20 @@ +json($passengers->get($commit, $user))->header('Cache-Control', 'private, no-store'); + } +} diff --git a/app/Http/Controllers/LaunchPassengerController.php b/app/Http/Controllers/LaunchPassengerController.php new file mode 100644 index 0000000000..e13a55f9df --- /dev/null +++ b/app/Http/Controllers/LaunchPassengerController.php @@ -0,0 +1,41 @@ +launchPassengers()->newPivotStatement()->insertOrIgnore([ + 'commit_id' => $commit->id, + 'user_id' => $user->id, + 'created_at' => now(), + ]); + + if ($inserted > 0) { + event(new CommitsUpdated([$commit], CommitUpdate::Engagement)); + } + + return response()->json($passengers->get($commit, $user))->header('Cache-Control', 'private, no-store'); + } + + public function destroy(UpdateLaunchPassengerRequest $request, #[CurrentUser] User $user, Commit $commit, LaunchPassengersQuery $passengers): JsonResponse + { + if ($commit->launchPassengers()->detach($user) > 0) { + event(new CommitsUpdated([$commit], CommitUpdate::Engagement)); + } + + return response()->json($passengers->get($commit, $user))->header('Cache-Control', 'private, no-store'); + } +} diff --git a/app/Http/Requests/CreateCommitRequest.php b/app/Http/Requests/CreateCommitRequest.php index 26264c458b..13dc34cbf2 100644 --- a/app/Http/Requests/CreateCommitRequest.php +++ b/app/Http/Requests/CreateCommitRequest.php @@ -6,6 +6,7 @@ use App\Actions\CreateCommitImages; use App\Dto\NewPoll; +use App\Enums\CommitType; use App\Enums\PollDuration; use App\Models\Commit; use App\Models\Organization; @@ -90,6 +91,7 @@ public function rules(): array return [ 'body' => self::bodyRules($this->hasFile('images')), + 'type' => ['sometimes', Rule::enum(CommitType::class)], 'author' => ['nullable', 'string', new OrganizationToPostAs($user)], 'quoted_commit_id' => ['nullable', 'uuid', 'prohibits:parent_id', new VisibleCommit($user, 'That commit is no longer available to quote.')], 'link_preview_url' => ['nullable', 'string', Rule::in(is_string($body) ? resolve(Urls::class)->all($body) : [])], diff --git a/app/Http/Requests/ShowCommitLaunchRequest.php b/app/Http/Requests/ShowCommitLaunchRequest.php new file mode 100644 index 0000000000..3b3ffce2ad --- /dev/null +++ b/app/Http/Requests/ShowCommitLaunchRequest.php @@ -0,0 +1,31 @@ +route('commit'); + assert($commit instanceof Commit); + + return $commit->type === CommitType::Launch && $commit->isVisibleTo($this->user()) + ? Response::allow() + : Response::denyAsNotFound(); + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Requests/UpdateLaunchPassengerRequest.php b/app/Http/Requests/UpdateLaunchPassengerRequest.php new file mode 100644 index 0000000000..179a82c561 --- /dev/null +++ b/app/Http/Requests/UpdateLaunchPassengerRequest.php @@ -0,0 +1,37 @@ +user(); + assert($user instanceof User); + $commit = $this->route('commit'); + assert($commit instanceof Commit); + + return match (true) { + $commit->type !== CommitType::Launch, $commit->status !== CommitStatus::Approved, ! $commit->isVisibleTo($user) => Response::denyAsNotFound(), + $this->isMethod('post') && $commit->isOwnedBy($user) => Response::deny(), + default => Response::allow(), + }; + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Resources/CommitResource.php b/app/Http/Resources/CommitResource.php index 31dc2a0585..d59070a3da 100644 --- a/app/Http/Resources/CommitResource.php +++ b/app/Http/Resources/CommitResource.php @@ -56,6 +56,7 @@ public function toArray(Request $request): array 'id' => $this->id, 'short_hash' => mb_substr(str_replace('-', '', $this->id), -7), 'body' => $this->body, + 'type' => $this->type, 'parent_id' => $isSigned ? $this->parent_id : $this->parent?->id, 'html_url' => route('commit.show', [$this->author, $this->resource]), 'created_at' => $this->created_at->toIso8601ZuluString(), diff --git a/app/Models/Commit.php b/app/Models/Commit.php index 805af50de6..579bac9300 100644 --- a/app/Models/Commit.php +++ b/app/Models/Commit.php @@ -5,6 +5,7 @@ namespace App\Models; use App\Enums\CommitStatus; +use App\Enums\CommitType; use App\Queries\CommitBuilder; use App\Services\CommitBodies; use App\Services\Mentions; @@ -31,6 +32,7 @@ * @property-read string|null $root_id * @property-read float $hot_score * @property-read string $body + * @property-read CommitType $type * @property-read array|null $mentions * @property-read array|null $organization_mentions * @property-read CommitStatus $status @@ -103,6 +105,7 @@ final class Commit extends Model */ protected $attributes = [ 'pasteis_count' => 0, + 'type' => CommitType::Standard->value, ]; /** @@ -124,6 +127,7 @@ public function casts(): array 'hot_score' => 'float', 'pasteis_count' => 'integer', 'body' => 'string', + 'type' => CommitType::class, 'mentions' => 'array', 'organization_mentions' => 'array', 'status' => CommitStatus::class, @@ -189,6 +193,14 @@ public function stars(): BelongsToMany return $this->belongsToMany(User::class, 'stars')->withTimestamps(); } + /** + * @return BelongsToMany + */ + public function launchPassengers(): BelongsToMany + { + return $this->belongsToMany(User::class, 'launch_passengers')->withPivot('created_at'); + } + /** * @return BelongsToMany */ diff --git a/app/Queries/CommitBuilder.php b/app/Queries/CommitBuilder.php index 34f06f2918..a1a7a5fd28 100644 --- a/app/Queries/CommitBuilder.php +++ b/app/Queries/CommitBuilder.php @@ -31,7 +31,7 @@ final class CommitBuilder extends Builder private const array COLUMNS_BUT_EMBEDDING = [ 'id', 'user_id', 'body', 'created_at', 'updated_at', 'status', 'parent_id', 'deleted_at', 'link_preview_id', 'quoted_commit_id', 'mentions', 'ai_decision', 'ai_categories', 'root_id', 'hot_score', 'pasteis_count', 'author_id', - 'headlines_classified_at', + 'headlines_classified_at', 'type', ]; /** diff --git a/app/Queries/LaunchPassengersQuery.php b/app/Queries/LaunchPassengersQuery.php new file mode 100644 index 0000000000..2e5eaad3d7 --- /dev/null +++ b/app/Queries/LaunchPassengersQuery.php @@ -0,0 +1,41 @@ +} + */ + public function get(Commit $commit, ?User $viewer): array + { + $passengers = $commit->launchPassengers()->whereNull('users.banned_at'); + + if ($viewer instanceof User) { + $passengers->whereNotIn('users.id', $viewer->idsAcrossBlocks()); + } + + return [ + 'count' => (clone $passengers)->count(), + 'boarded' => $viewer instanceof User && (clone $passengers)->where('users.id', $viewer->id)->exists(), + 'passengers' => array_values((clone $passengers) + ->latest('launch_passengers.created_at') + ->orderByDesc('users.id') + ->limit(16) + ->get() + ->map(fn (User $user): array => [ + 'id' => $user->id, + 'handle' => $user->handle, + 'name' => $user->name, + 'avatar_url' => $user->avatar_url, + ])->all()), + ]; + } +} diff --git a/database/migrations/2026_11_12_210000_add_launch_posts.php b/database/migrations/2026_11_12_210000_add_launch_posts.php new file mode 100644 index 0000000000..a6881b4fa6 --- /dev/null +++ b/database/migrations/2026_11_12_210000_add_launch_posts.php @@ -0,0 +1,27 @@ +string('type')->default(CommitType::Standard->value); + }); + + Schema::create('launch_passengers', function (Blueprint $table): void { + $table->foreignUuid('commit_id')->constrained()->cascadeOnDelete(); + $table->foreignUuid('user_id')->constrained()->cascadeOnDelete(); + $table->timestamp('created_at'); + $table->primary(['commit_id', 'user_id']); + $table->index(['commit_id', 'created_at']); + $table->index('user_id'); + }); + } +}; diff --git a/resources/css/app.css b/resources/css/app.css index c1291a8d2b..0ec41bba5c 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -1,6 +1,7 @@ @import 'tailwindcss'; @import 'tw-animate-css'; +@import './shipit.css'; @source '../views'; @source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php'; diff --git a/resources/css/shipit.css b/resources/css/shipit.css new file mode 100644 index 0000000000..1ec39c1261 --- /dev/null +++ b/resources/css/shipit.css @@ -0,0 +1,251 @@ +.launch-sea { + --launch-water: #168591; + position: relative; + height: 272px; + overflow: hidden; + isolation: isolate; + background: linear-gradient( + transparent 72%, + color-mix(in srgb, var(--launch-water) 9%, transparent) + ); +} +.dark .launch-sea { + --launch-water: #71ced1; +} +.launch-vessel { + position: absolute; + bottom: 20px; + left: calc(50% - 120px); + width: 240px; + height: 100px; + translate: 0 var(--launch-sink, 0px); + transition: translate 900ms cubic-bezier(0.4, 0, 0.2, 1); +} +.launch-bob { + position: relative; + width: 100%; + height: 100%; +} +.launch-hull { + position: absolute; + inset: 0; + width: 240px; + height: 100px; +} +.launch-passengers { + margin: 0; + padding: 0; + list-style: none; +} +.launch-passenger-slot { + position: absolute; + width: 26px; + height: 40px; +} +.launch-person { + position: absolute; + top: 0; + left: 0; + width: 26px; + height: 40px; + offset-path: path('M -150 0 C -95 -10 -45 5 0 0'); + offset-distance: 100%; + offset-anchor: 0 0; + offset-rotate: 0deg; +} +.launch-passenger-face { + position: absolute; + z-index: 1; + top: 0; + left: 1px; + box-shadow: 0 0 0 1px var(--background); +} +.launch-person::before { + content: ''; + position: absolute; + bottom: 5px; + left: 4px; + width: 18px; + height: 16px; + border-radius: 7px 7px 3px 3px; + background: var(--passenger-shirt); +} +.launch-person::after { + content: ''; + position: absolute; + bottom: 0; + left: 7px; + width: 12px; + height: 7px; + border-left: 4px solid #34445b; + border-right: 4px solid #34445b; +} +.launch-passenger-deck { + position: absolute; + left: 8px; + width: 169px; + height: 4px; + border: 1px solid var(--foreground); + background: var(--background); +} +.launch-passenger-deck::before, +.launch-passenger-deck::after { + content: ''; + position: absolute; + top: 3px; + width: 2px; + height: 38px; + background: var(--foreground); +} +.launch-passenger-deck::before { + left: 0; +} +.launch-passenger-deck::after { + right: 0; +} +.launch-passenger-railing { + position: absolute; + z-index: 2; + left: 8px; + width: 169px; + height: 11px; + border-top: 1.5px solid var(--foreground); + background: repeating-linear-gradient( + 90deg, + var(--foreground) 0 1px, + transparent 1px 26px + ); + pointer-events: none; +} +.launch-excess { + position: absolute; + top: -106px; + left: 54px; + display: inline-flex; + align-items: center; + gap: 5px; + padding: 5px 8px; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--background); + color: var(--muted-foreground); + font: 11px var(--font-mono); +} +.launch-waves { + position: absolute; + bottom: 5px; + color: var(--launch-water); + pointer-events: none; +} +.launch-smoke { + position: absolute; + left: 187px; + top: 4px; + width: 9px; + height: 9px; + border-radius: 50%; + background: var(--muted-foreground); + opacity: 0; +} +.launch-smoke-later { + animation-delay: 900ms !important; +} +.launch-captain { + position: absolute; + top: 22px; + left: 181px; + z-index: 1; + display: flex; + width: 30px; + height: 36px; + align-items: end; + justify-content: center; +} +.launch-captain-hat { + position: absolute; + top: 0; + width: 28px; + height: 14px; + border: 1px solid #22354c; + border-bottom: 4px solid #22354c; + border-radius: 7px 7px 2px 2px; + background: #fffdf5; +} +.launch-captain-hat::after { + content: '⚓'; + position: absolute; + inset: -1px 0 0; + text-align: center; + color: #22354c; + font-size: 10px; + line-height: 11px; +} +@media (prefers-reduced-motion: no-preference) { + .launch-bob { + animation: launch-bob 2400ms ease-in-out infinite; + } + .launch-overloaded .launch-bob { + animation: launch-wobble 1600ms ease-in-out infinite; + } + .launch-person { + animation: launch-board 900ms cubic-bezier(0.4, 0, 0.2, 1) both; + } + .launch-smoke { + animation: launch-smoke 1800ms ease-out infinite; + } + .launch-waves { + animation: launch-tide 2200ms ease-in-out infinite; + } +} +@keyframes launch-board { + from { + opacity: 0; + offset-distance: 0%; + } + to { + opacity: 1; + offset-distance: 100%; + } +} +@keyframes launch-bob { + 0%, + 100% { + transform: translateY(1px) rotate(-1deg); + } + 50% { + transform: translateY(-3px) rotate(1deg); + } +} +@keyframes launch-wobble { + 0%, + 100% { + transform: rotate(-4deg); + } + 50% { + transform: rotate(4deg); + } +} +@keyframes launch-smoke { + 0% { + opacity: 0.35; + transform: translate(0, 0) scale(0.5); + } + 100% { + opacity: 0; + transform: translate(-25px, -25px) scale(2); + } +} +@keyframes launch-tide { + 0%, + 100% { + transform: translateY(1px); + } + 50% { + transform: translateY(-2px); + } +} +@media (prefers-reduced-motion: reduce) { + .launch-vessel { + transition: none; + } +} diff --git a/resources/js/components/commit-card.tsx b/resources/js/components/commit-card.tsx index edd740d31f..b62293935a 100644 --- a/resources/js/components/commit-card.tsx +++ b/resources/js/components/commit-card.tsx @@ -6,6 +6,7 @@ import CommitController from '@/actions/App/Http/Controllers/CommitController'; import CommitLinkPreviewController from '@/actions/App/Http/Controllers/CommitLinkPreviewController'; import { FoldedCommitBody } from '@/components/commit-body'; import { CommitImages } from '@/components/commit-images'; +import { CommitLaunch } from '@/components/commit-launch'; import { CommitPastelButton } from '@/components/commit-pastel-button'; import { CommitPoll } from '@/components/commit-poll'; import { CommitQuoteButton } from '@/components/commit-quote-button'; @@ -478,6 +479,9 @@ export function CommitCard({ {translation.notice} {showImages && } + {commit.type === 'launch' && ( + + )} {commit.poll && ( ; errors: Record; onKeyDown: (event: KeyboardEvent) => void; drop: () => void; @@ -282,11 +288,15 @@ function CommitComposerBody({ name="body" rows={1} value={body} - onValueChange={issue.change} + onValueChange={(value) => { + if (isIssue || !shipit.change(value)) + issue.change(value); + }} onPaste={ poll === null ? attachments.onPaste : undefined } onKeyDown={(event) => + (!isIssue && shipit.handleKeyDown(event)) || preview.handleShortcut(event) || onKeyDown(event) } @@ -336,6 +346,18 @@ function CommitComposerBody({ )} + {shipit.isCommand && ( +

+ Press Enter to set sail. +

+ )} + {shipit.isLaunch && ( + <> + + + + )} + {issue.hint && ( { setTimezone( Intl.DateTimeFormat().resolvedOptions() @@ -573,7 +597,11 @@ function CommitComposerBody({ ) : ( @@ -588,8 +616,12 @@ function CommitComposerBody({ ? 'Scheduling…' : 'Schedule commit' : processing - ? 'Committing…' - : 'Commit'} + ? shipit.isLaunch + ? 'Shipping…' + : 'Committing…' + : shipit.isLaunch + ? 'Ship it' + : 'Commit'} )} @@ -622,6 +654,7 @@ export function CommitComposer({ const [draftVersion, setDraftVersion] = useState(0); const drop = () => { stash.drop(); + shipit.reset(); linkCard.reset(); setDraftVersion((version) => version + 1); }; @@ -634,6 +667,17 @@ export function CommitComposer({ const [poll, setPoll] = useState(null); const commitRules = useCommitRules(); const isPosting = useRef(false); + const shipit = useComposerShipit({ + body, + updateBody: stash.updateBody, + stashKey: stash.key, + enabled: initialIssue === null, + onLaunch: () => setIsScheduling(false), + }); + + useEffect(() => { + if (shipit.isLaunch) setIsScheduling(false); + }, [shipit.isLaunch, setIsScheduling]); const hasImages = attachments.images.length > 0; const issue = useIssueCommand({ @@ -643,7 +687,8 @@ export function CommitComposer({ !attachments.reading && !hasImages && poll === null && - !isScheduling, + !isScheduling && + !shipit.isLaunch, initialKind: initialIssue, onCreated: () => { drop(); @@ -701,6 +746,9 @@ export function CommitComposer({ return (
{ + if (issue.command === null) shipit.handleSubmit(event); + }} {...(isScheduling ? ScheduledCommitController.store.form() : CommitController.store.form())} @@ -771,6 +819,7 @@ export function CommitComposer({ isSubmittable={isSubmittable} processing={processing} issue={issue} + shipit={shipit} errors={errors} onKeyDown={onKeyDown} drop={drop} diff --git a/resources/js/components/commit-launch.tsx b/resources/js/components/commit-launch.tsx new file mode 100644 index 0000000000..627f1603c4 --- /dev/null +++ b/resources/js/components/commit-launch.tsx @@ -0,0 +1,220 @@ +import { router, useHttp, usePage } from '@inertiajs/react'; +import { Anchor, Check, Ship } from 'lucide-react'; +import { useEffect, useEffectEvent, useRef, useState } from 'react'; +import { toast } from 'sonner'; +import CommitLaunchController from '@/actions/App/Http/Controllers/CommitLaunchController'; +import LaunchPassengerController from '@/actions/App/Http/Controllers/LaunchPassengerController'; +import { LaunchShip } from '@/components/launch-ship'; +import type { LaunchPassenger } from '@/components/launch-ship'; +import { Button } from '@/components/ui/button'; +import { useOwnsCommit } from '@/hooks/use-owns-commit'; +import { signIn } from '@/lib/auth'; +import { formatExactCount } from '@/lib/numbers'; +import { coalesce, commitChannel, listen } from '@/lib/realtime'; +import type { Commit } from '@/types'; + +type Crew = { count: number; boarded: boolean; passengers: LaunchPassenger[] }; + +function capacityMessage(count: number): string { + if (count === 0) return 'A big little moment. Be the first aboard.'; + if (count < 4) return 'Plenty of room. Probably.'; + if (count < 8) return 'We planned for this. Mostly.'; + if (count < 16) return 'That is definitely within spec.'; + return 'Capacity planning has left the chat.'; +} + +export function CommitLaunch({ commit }: { commit: Commit }) { + const { auth } = usePage().props; + const ownsCommit = useOwnsCommit(); + const [crew, setCrew] = useState(null); + const [error, setError] = useState(false); + const [retry, setRetry] = useState(0); + const [element, setElement] = useState(null); + const [visible, setVisible] = useState(false); + const latest = useRef(0); + const busy = useRef(false); + const request = useHttp, Crew>({}); + const onIntersection = useEffectEvent( + ([entry]: IntersectionObserverEntry[]) => + setVisible(entry.isIntersecting), + ); + + const read = useEffectEvent(async (signal?: AbortSignal) => { + if (busy.current || document.hidden) return; + const started = ++latest.current; + try { + const response = await fetch( + CommitLaunchController.show.url(commit), + { + headers: { + Accept: 'application/json', + 'X-Requested-With': 'XMLHttpRequest', + }, + cache: 'no-store', + signal, + }, + ); + if (!response.ok) throw new Error('Could not load crew'); + const fresh = (await response.json()) as Crew; + if (started === latest.current && !busy.current) { + setCrew(fresh); + setError(false); + } + } catch { + if (!signal?.aborted && started === latest.current) setError(true); + } + }); + + useEffect(() => { + if (!element) return; + const observer = new IntersectionObserver(onIntersection, { + rootMargin: '100px', + }); + observer.observe(element); + return () => observer.disconnect(); + }, [element]); + + useEffect(() => { + if (!visible) return; + const controller = new AbortController(); + const refresh = coalesce(() => read(controller.signal), 300); + refresh.request(); + const stop = listen( + commitChannel(commit.id), + { engagement: refresh.request, visibility: refresh.request }, + refresh.request, + ); + const interval = window.setInterval(refresh.request, 20_000); + const onVisible = () => { + if (!document.hidden) refresh.request(); + }; + document.addEventListener('visibilitychange', onVisible); + return () => { + stop(); + refresh.cancel(); + controller.abort(); + window.clearInterval(interval); + document.removeEventListener('visibilitychange', onVisible); + }; + }, [visible, commit.id, auth.user?.id, retry]); + + const toggle = async () => { + if (auth.user === null) { + signIn(); + return; + } + if ( + !crew || + busy.current || + ownsCommit(commit) || + commit.status !== 'approved' + ) + return; + busy.current = true; + ++latest.current; + try { + const fresh = await request.submit( + crew.boarded + ? LaunchPassengerController.destroy(commit) + : LaunchPassengerController.store(commit), + ); + ++latest.current; + setCrew(fresh); + setError(false); + router.flushAll(); + } catch { + toast.error('Could not update your boarding. Try again.'); + } finally { + busy.current = false; + } + }; + const count = crew?.count ?? 0; + + return ( +
event.stopPropagation()} + > +
+ + Shipped it + + + {crew + ? `${formatExactCount(count)} aboard` + : 'Loading crew…'} + +
+

+ Captain @{commit.author.handle} +

+ +
+

+ {capacityMessage(count)} +

+ {ownsCommit(commit) ? ( + + You’re the + captain + + ) : ( + + )} +
+ {commit.status !== 'approved' && ( +

+ Boarding opens once this launch is approved. +

+ )} + {error && ( + + )} +
+ ); +} diff --git a/resources/js/components/composer-shipit.tsx b/resources/js/components/composer-shipit.tsx new file mode 100644 index 0000000000..38ffe0d91f --- /dev/null +++ b/resources/js/components/composer-shipit.tsx @@ -0,0 +1,95 @@ +import { Ship, X } from 'lucide-react'; +import type { KeyboardEvent, SyntheticEvent } from 'react'; +import { useSharedState } from '@/hooks/use-shared-state'; +import { shipitDraft } from '@/lib/shipit'; +import { readStorage, writeStorage } from '@/lib/storage'; + +export function useComposerShipit({ + body, + updateBody, + stashKey, + enabled, + onLaunch, +}: { + body: string; + updateBody: (body: string) => void; + stashKey: string; + enabled: boolean; + onLaunch: () => void; +}) { + const key = `${stashKey}:launch`; + const [selected, setSelected] = useSharedState( + key, + readStorage(key) === '1', + ); + const isLaunch = enabled && selected; + const draft = enabled ? shipitDraft(body) : null; + const select = (value: boolean) => { + writeStorage(key, value ? '1' : ''); + setSelected(value); + }; + const launch = (value: string): boolean => { + const remaining = enabled ? shipitDraft(value) : null; + if (remaining === null) return false; + + updateBody(remaining); + select(true); + onLaunch(); + return true; + }; + + return { + isLaunch, + isCommand: draft !== null, + reset: () => select(false), + change: (value: string) => value.endsWith('\n') && launch(value), + handleKeyDown: (event: KeyboardEvent) => { + if ( + event.key !== 'Enter' || + event.nativeEvent.isComposing || + draft === null || + (!event.ctrlKey && + !event.metaKey && + (event.currentTarget.selectionStart !== body.length || + event.currentTarget.selectionEnd !== body.length)) + ) + return false; + + event.preventDefault(); + event.stopPropagation(); + launch(body); + return true; + }, + handleSubmit: (event: SyntheticEvent) => { + if (draft === null) return; + event.preventDefault(); + event.stopPropagation(); + launch(body); + }, + }; +} + +export function ComposerShipit({ onCancel }: { onCancel: () => void }) { + return ( +
+ +
+

Ready to launch

+

+ Share what you shipped. Everyone can come aboard. +

+
+ +
+ ); +} diff --git a/resources/js/components/launch-ship.tsx b/resources/js/components/launch-ship.tsx new file mode 100644 index 0000000000..f2793eedc0 --- /dev/null +++ b/resources/js/components/launch-ship.tsx @@ -0,0 +1,223 @@ +import { Users } from 'lucide-react'; +import type { CSSProperties } from 'react'; +import { useId } from 'react'; +import { UserAvatar } from '@/components/user-avatar'; +import { cn } from '@/lib/utils'; + +export type LaunchPassenger = { + id: string; + handle: string; + name: string; + avatar_url: string | null; +}; + +export function LaunchShip({ + count, + passengers, + captain, +}: { + count: number; + passengers: LaunchPassenger[]; + captain?: Pick; +}) { + const waveId = useId(); + const shown = passengers.slice(0, 16).toReversed(); + const excess = Math.max(0, count - shown.length); + const decks = Array.from( + { length: Math.ceil(shown.length / 6) }, + (_, index) => index, + ); + + return ( +
= 8 && 'launch-overloaded')} + style={ + { + '--launch-sink': `${Math.min(count, 32) * 0.45}px`, + } as CSSProperties + } + data-test="launch-ship" + data-passengers={count} + > +
+
+ + {captain && ( + + + + )} + {decks + .filter((deck) => deck > 0) + .map((deck) => ( +
+
+ +
+ ); +} diff --git a/resources/js/lib/shipit.ts b/resources/js/lib/shipit.ts new file mode 100644 index 0000000000..54f53f8c07 --- /dev/null +++ b/resources/js/lib/shipit.ts @@ -0,0 +1,12 @@ +import { typedProse } from '@/lib/code'; + +/** A command on its own final line, outside code. The rest of the draft stays byte-for-byte intact. */ +export function shipitDraft(body: string): string | null { + const command = /(?:^|\r?\n)\/shipit[\t ]*\n?$/.exec(body); + + if (!command || !typedProse(body).at(-1)?.endsWith(command[0])) { + return null; + } + + return body.slice(0, command.index); +} diff --git a/resources/js/types/commit.ts b/resources/js/types/commit.ts index 73c8df690e..d70a0a4a73 100644 --- a/resources/js/types/commit.ts +++ b/resources/js/types/commit.ts @@ -2,6 +2,7 @@ import type { User } from '@/types/auth'; import type { Organization } from '@/types/organization'; export type CommitStatus = 'pending' | 'approved' | 'rejected'; +export type CommitType = 'standard' | 'launch'; export type EmbedKind = 'video' | 'audio' | 'code'; @@ -89,6 +90,7 @@ export type Commit = { parent_id: string | null; hot_score: number; body: string; + type?: CommitType; mentions: Record | null; organization_mentions?: Record | null; body_segments: BodySegment[]; diff --git a/routes/web.php b/routes/web.php index 13b13548d1..142f39de5c 100644 --- a/routes/web.php +++ b/routes/web.php @@ -19,6 +19,7 @@ use App\Http\Controllers\CommitContinuationController; use App\Http\Controllers\CommitController; use App\Http\Controllers\CommitImageController; +use App\Http\Controllers\CommitLaunchController; use App\Http\Controllers\CommitLinkPreviewController; use App\Http\Controllers\CommitOpenGraphImageController; use App\Http\Controllers\CommitPastelController; @@ -66,6 +67,7 @@ use App\Http\Controllers\IssueController; use App\Http\Controllers\IssueSuggestionController; use App\Http\Controllers\JoinLinkController; +use App\Http\Controllers\LaunchPassengerController; use App\Http\Controllers\LinkController; use App\Http\Controllers\LiveStreamController; use App\Http\Controllers\LocalSessionController; @@ -339,6 +341,9 @@ Route::get('commits/{commit}/poll', [CommitPollController::class, 'show']) ->middleware('throttle:live-reads') ->name('commit-poll.show'); +Route::get('commits/{commit}/launch', [CommitLaunchController::class, 'show']) + ->middleware('throttle:live-reads') + ->name('commit-launch.show'); Route::get('commits/{commit}/replies', [CommitReplyController::class, 'index']) ->withTrashed() ->name('commit-reply.index'); @@ -475,6 +480,12 @@ Route::post('commits/{commit}/star', [CommitStarController::class, 'store']) ->middleware('throttle:stars') ->name('commit-star.store'); + Route::post('commits/{commit}/launch/passengers', [LaunchPassengerController::class, 'store']) + ->middleware('throttle:stars') + ->name('launch-passenger.store'); + Route::delete('commits/{commit}/launch/passengers', [LaunchPassengerController::class, 'destroy']) + ->middleware('throttle:stars') + ->name('launch-passenger.destroy'); Route::post('commits/{commit}/pasteis', [CommitPastelController::class, 'store']) ->middleware('throttle:60,1') ->name('commit-pastel.store'); diff --git a/tests/Feature/Controllers/Api/CommitControllerTest.php b/tests/Feature/Controllers/Api/CommitControllerTest.php index 79bb90d31f..2dd9929a88 100644 --- a/tests/Feature/Controllers/Api/CommitControllerTest.php +++ b/tests/Feature/Controllers/Api/CommitControllerTest.php @@ -65,6 +65,7 @@ 'id' => '019a2b3c-4d5e-7f60-8a9b-0c1d2e3f4a5b', 'short_hash' => 'e3f4a5b', 'body' => 'Shipped the public API', + 'type' => 'standard', 'parent_id' => null, 'html_url' => route('commit.show', [$user, $commit]), 'created_at' => now()->toIso8601ZuluString(), @@ -295,6 +296,7 @@ 'id' => '019a2b3c-4d5e-7f60-8a9b-0c1d2e3f4a5b', 'short_hash' => 'e3f4a5b', 'body' => 'Ask @nunomaduro about `@Override`', + 'type' => 'standard', 'parent_id' => $root->id, 'html_url' => route('commit.show', [$user, $commit]), 'created_at' => now()->toIso8601ZuluString(), @@ -324,6 +326,7 @@ 'id' => $root->id, 'short_hash' => mb_substr(str_replace('-', '', $root->id), -7), 'body' => 'Who broke prod?', + 'type' => 'standard', 'parent_id' => null, 'html_url' => route('commit.show', [$root->user, $root]), 'created_at' => now()->subMinute()->toIso8601ZuluString(), diff --git a/tests/Feature/Controllers/Api/LogControllerTest.php b/tests/Feature/Controllers/Api/LogControllerTest.php index febb51c342..61b965d589 100644 --- a/tests/Feature/Controllers/Api/LogControllerTest.php +++ b/tests/Feature/Controllers/Api/LogControllerTest.php @@ -51,6 +51,7 @@ 'id' => $older->id, 'short_hash' => mb_substr(str_replace('-', '', $older->id), -7), 'body' => 'It was DNS.', + 'type' => 'standard', 'parent_id' => null, 'html_url' => route('commit.show', [$author, $older]), 'created_at' => now()->subMinute()->toIso8601ZuluString(), diff --git a/tests/Feature/Controllers/Api/NotificationControllerTest.php b/tests/Feature/Controllers/Api/NotificationControllerTest.php index 7070d4ca37..d5736293cd 100644 --- a/tests/Feature/Controllers/Api/NotificationControllerTest.php +++ b/tests/Feature/Controllers/Api/NotificationControllerTest.php @@ -62,6 +62,7 @@ 'id' => $reply->id, 'short_hash' => mb_substr(str_replace('-', '', $reply->id), -7), 'body' => $reply->body, + 'type' => 'standard', 'parent_id' => $reply->parent_id, 'html_url' => route('commit.show', [$replied->actor->user, $reply]), 'created_at' => now()->toIso8601ZuluString(), @@ -77,6 +78,7 @@ 'id' => $reply->parent->id, 'short_hash' => mb_substr(str_replace('-', '', $reply->parent->id), -7), 'body' => $reply->parent->body, + 'type' => 'standard', 'parent_id' => null, 'html_url' => route('commit.show', [$this->user, $reply->parent]), 'created_at' => now()->toIso8601ZuluString(), diff --git a/tests/Feature/Controllers/CommitLaunchControllerTest.php b/tests/Feature/Controllers/CommitLaunchControllerTest.php new file mode 100644 index 0000000000..44a8df9490 --- /dev/null +++ b/tests/Feature/Controllers/CommitLaunchControllerTest.php @@ -0,0 +1,152 @@ +create(); + + $this->actingAs($author)->post(route('commit.store'), [ + 'body' => 'Today I shipped my first package!', + 'type' => CommitType::Launch->value, + ])->assertRedirect(); + + $commit = $author->commits()->sole(); + expect($commit->type)->toBe(CommitType::Launch) + ->and($commit->body)->toBe('Today I shipped my first package!'); +}); + +it('keeps ordinary commits standard and rejects unknown types', function (): void { + $author = User::factory()->create(); + $this->actingAs($author)->post(route('commit.store'), ['body' => 'Hello!'])->assertRedirect(); + expect($author->commits()->sole()->type)->toBe(CommitType::Standard); + + $this->postJson(route('commit.store'), ['body' => 'Nope', 'type' => 'unknown']) + ->assertUnprocessable()->assertJsonValidationErrors('type'); + expect($author->commits()->count())->toBeOne(); +}); + +it('shows a public launch with an empty crew to guests', function (): void { + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $this->getJson(route('commit-launch.show', $commit))->assertOk() + ->assertExactJson(['count' => 0, 'boarded' => false, 'passengers' => []]) + ->assertHeader('Cache-Control', 'no-store, private'); + + $this->getJson(route('api-commit.show', $commit))->assertOk()->assertJsonPath('data.type', 'launch'); +}); + +it('boards only once and persists that crew for other readers', function (): void { + Event::fake([CommitsUpdated::class]); + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $viewer = User::factory()->create(); + + foreach (range(1, 2) as $attempt) { + $this->actingAs($viewer)->postJson(route('launch-passenger.store', $commit)) + ->assertOk()->assertJsonPath('count', 1)->assertJsonPath('boarded', true) + ->assertJsonPath('passengers.0.handle', $viewer->handle); + } + + expect(DB::table('launch_passengers')->count())->toBeOne(); + Event::assertDispatchedTimes(CommitsUpdated::class, 1); + + $this->actingAs(User::factory()->create())->getJson(route('commit-launch.show', $commit)) + ->assertOk()->assertJsonPath('count', 1)->assertJsonPath('boarded', false) + ->assertJsonPath('passengers.0.id', $viewer->id); +}); + +it('lets a passenger step ashore idempotently', function (): void { + Event::fake([CommitsUpdated::class]); + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $viewer = User::factory()->create(); + $commit->launchPassengers()->attach($viewer, ['created_at' => now()]); + + foreach (range(1, 2) as $attempt) { + $this->actingAs($viewer)->deleteJson(route('launch-passenger.destroy', $commit)) + ->assertOk()->assertExactJson(['count' => 0, 'boarded' => false, 'passengers' => []]); + } + + Event::assertDispatchedTimes(CommitsUpdated::class, 1); +}); + +it('requires sign in to board or step ashore', function (): void { + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $this->postJson(route('launch-passenger.store', $commit))->assertUnauthorized(); + $this->deleteJson(route('launch-passenger.destroy', $commit))->assertUnauthorized(); + expect(DB::table('launch_passengers')->count())->toBe(0); +}); + +it('keeps the author as captain instead of adding a self celebration', function (): void { + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $this->actingAs($commit->user)->postJson(route('launch-passenger.store', $commit))->assertForbidden(); + expect(DB::table('launch_passengers')->count())->toBe(0); +}); + +it('hides non launch and unpublished posts from boarding endpoints', function (CommitType $type, CommitStatus $status): void { + $commit = Commit::factory()->create(['type' => $type, 'status' => $status]); + $viewer = User::factory()->create(); + $this->getJson(route('commit-launch.show', $commit))->assertNotFound(); + $this->actingAs($viewer)->postJson(route('launch-passenger.store', $commit))->assertNotFound(); + $this->deleteJson(route('launch-passenger.destroy', $commit))->assertNotFound(); + expect(DB::table('launch_passengers')->count())->toBe(0); +})->with([ + [CommitType::Standard, CommitStatus::Approved], + [CommitType::Launch, CommitStatus::Pending], + [CommitType::Launch, CommitStatus::Rejected], +]); + +it('does not reveal deleted launches', function (): void { + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $commit->delete(); + $this->getJson(route('commit-launch.show', $commit))->assertNotFound(); + $this->actingAs(User::factory()->create())->postJson(route('launch-passenger.store', $commit))->assertNotFound(); +}); + +it('respects blocks with the author in either direction', function (bool $viewerBlocks): void { + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $viewer = User::factory()->create(); + $viewerBlocks ? $viewer->blocking()->attach($commit->user) : $commit->user->blocking()->attach($viewer); + + $this->actingAs($viewer)->getJson(route('commit-launch.show', $commit))->assertNotFound(); + $this->postJson(route('launch-passenger.store', $commit))->assertNotFound(); +})->with([true, false]); + +it('bounds public avatar payloads and exposes no private account fields', function (): void { + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + foreach (User::factory()->count(20)->create() as $passenger) { + $commit->launchPassengers()->attach($passenger, ['created_at' => now()]); + } + + $response = $this->getJson(route('commit-launch.show', $commit))->assertOk() + ->assertJsonPath('count', 20)->assertJsonCount(16, 'passengers'); + expect(array_keys($response->json('passengers.0')))->toBe(['id', 'handle', 'name', 'avatar_url']); +}); + +it('leaves blocked and banned people out of the visible crew', function (): void { + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $viewer = User::factory()->create(); + $blocked = User::factory()->create(); + $banned = User::factory()->create(['banned_at' => now()]); + $visible = User::factory()->create(); + $viewer->blocking()->attach($blocked); + foreach ([$blocked, $banned, $visible] as $passenger) { + $commit->launchPassengers()->attach($passenger, ['created_at' => now()]); + } + + $this->actingAs($viewer)->getJson(route('commit-launch.show', $commit))->assertOk() + ->assertJsonPath('count', 1)->assertJsonCount(1, 'passengers')->assertJsonPath('passengers.0.id', $visible->id); +}); + +it('removes passenger records when an account is deleted', function (): void { + $commit = Commit::factory()->create(['type' => CommitType::Launch]); + $passenger = User::factory()->create(); + $commit->launchPassengers()->attach($passenger, ['created_at' => now()]); + $passenger->delete(); + expect(DB::table('launch_passengers')->count())->toBe(0); +}); diff --git a/tests/Feature/Controllers/ExportControllerTest.php b/tests/Feature/Controllers/ExportControllerTest.php index 1b043d513a..1b529dba91 100644 --- a/tests/Feature/Controllers/ExportControllerTest.php +++ b/tests/Feature/Controllers/ExportControllerTest.php @@ -8,6 +8,7 @@ use App\Actions\DeleteUser; use App\Actions\UpdateDevicePushToken; use App\Contracts\Services\TranslationProvider; +use App\Enums\CommitType; use App\Enums\ModerationReason; use App\Enums\NotificationType; use App\Enums\OrganizationRole; @@ -92,7 +93,7 @@ $data = json_decode($response->streamedContent(), true, flags: JSON_THROW_ON_ERROR); expect($data)->toBe([ - 'schema_version' => 8, + 'schema_version' => 9, 'exported_at' => now()->toIso8601String(), 'profile' => [ 'github_id' => $user->github_id, @@ -139,6 +140,7 @@ 'polls' => [], 'poll_votes' => [], 'stars' => [], + 'launch_boardings' => [], 'following' => [], 'followers' => [], 'muting' => [], @@ -259,6 +261,7 @@ 'translated_at' => now()->getTimestampMs(), ], 'status' => 'approved', + 'type' => 'standard', 'pasteis_count' => 3, 'images' => [], 'created_at' => $approved->created_at->toIso8601String(), @@ -707,3 +710,16 @@ $export = resolve(CreateExport::class)->handle($user); expect($export['push_subscriptions'])->toBe([['id' => $subscription->id]]); }); + +it('exports only the users launch boardings and includes the launch commit type', function (): void { + $user = User::factory()->create(); + $launch = Commit::factory()->create(['type' => CommitType::Launch]); + $own = Commit::factory()->for($user)->create(['type' => CommitType::Launch]); + $launch->launchPassengers()->attach($user, ['created_at' => now()]); + $own->launchPassengers()->attach(User::factory()->create(), ['created_at' => now()]); + + $response = $this->actingAs($user)->get(route('export'))->assertOk(); + $data = json_decode($response->streamedContent(), true, flags: JSON_THROW_ON_ERROR); + expect($data['launch_boardings'])->toBe([['commit_id' => $launch->id, 'boarded_at' => now()->toIso8601String()]]) + ->and($data['commits'][0]['type'])->toBe('launch'); +}); diff --git a/tests/Feature/OrganizationCommitsTest.php b/tests/Feature/OrganizationCommitsTest.php index c74afa5883..00d0772538 100644 --- a/tests/Feature/OrganizationCommitsTest.php +++ b/tests/Feature/OrganizationCommitsTest.php @@ -170,6 +170,7 @@ 'quoted_commit_id' => null, 'body' => 'Laravel 13 is out', 'status' => 'approved', + 'type' => 'standard', 'images' => [], 'created_at' => $commit->created_at->toIso8601String(), 'deleted_at' => null, diff --git a/tests/Unit/Actions/DeleteUserTest.php b/tests/Unit/Actions/DeleteUserTest.php index 8a0ed8401e..da4d9b7261 100644 --- a/tests/Unit/Actions/DeleteUserTest.php +++ b/tests/Unit/Actions/DeleteUserTest.php @@ -9,6 +9,7 @@ use App\Actions\UpdateCommitHotScores; use App\Contracts\Services\TranslationProvider; use App\Dto\ThreadEngagement; +use App\Enums\CommitType; use App\Enums\OrganizationRole; use App\Models\Commit; use App\Models\CommitImage; @@ -474,3 +475,14 @@ resolve(DeleteUser::class)->handle($user); expect(PushSubscription::query()->count())->toBe(0); }); + +it('erases launch boardings with the account and preserves other passengers', function (): void { + $user = User::factory()->create(); + $other = User::factory()->create(); + $launch = Commit::factory()->create(['type' => CommitType::Launch]); + $launch->launchPassengers()->attach([$user->id => ['created_at' => now()], $other->id => ['created_at' => now()]]); + + resolve(DeleteUser::class)->handle($user); + + expect($launch->launchPassengers()->pluck('users.id')->all())->toBe([$other->id]); +}); diff --git a/tests/Unit/ComposerDraft.test.tsx b/tests/Unit/ComposerDraft.test.tsx index 1f6d4270af..85e12b622a 100644 --- a/tests/Unit/ComposerDraft.test.tsx +++ b/tests/Unit/ComposerDraft.test.tsx @@ -89,6 +89,8 @@ const { LinkCardPicker } = const { PollEditor } = await import('../../resources/js/components/poll-editor'); const { GraphRail } = await import('../../resources/js/components/graph-rail'); +const { refreshSharedState } = + await import('../../resources/js/hooks/use-shared-state'); type Element = ReactElement>; @@ -767,6 +769,55 @@ test('turning scheduling off clears the chosen time and commits now', () => { assert.equal(find('id', 'body-scheduled-at')!.props.value, ''); }); +test('a launch selected in another composer cancels this composer’s schedule', () => { + const launchKey = `${draft.key}:launch`; + const immediateAction = render().form.props.action; + const toggle = render().fields.find( + (element) => element.props['aria-controls'] === 'body-schedule', + )!; + (toggle.props.onClick as () => void)(); + assert.notEqual(render().form.props.action, immediateAction); + + try { + refreshSharedState(new Map([[launchKey, true]])); + effects = []; + render(); + effects.forEach((effect) => effect()); + + const view = render(); + assert.equal(view.form.props.action, immediateAction); + assert.equal( + view.fields.some( + (element) => element.props.id === 'body-scheduled-at', + ), + false, + ); + assert.ok( + view.fields.some( + (element) => + element.props.name === 'type' && + element.props.value === 'launch', + ), + ); + assert.equal( + view.fields.find( + (element) => + element.props['aria-controls'] === 'body-schedule', + )!.props.disabled, + true, + ); + assert.equal( + 'scheduled_at' in view.form.props.transform({ body: draft.body }), + false, + ); + + refreshSharedState(new Map([[launchKey, false]])); + assert.equal(render().form.props.action, immediateAction); + } finally { + refreshSharedState(new Map([[launchKey, false]])); + } +}); + test('picker clears its selection before a pending read finishes so the same file can be retried', async () => { const reads: Array<() => void> = []; const selections: File[][] = []; diff --git a/tests/Unit/Models/CommitTest.php b/tests/Unit/Models/CommitTest.php index 17baaae31e..eed0e15a49 100644 --- a/tests/Unit/Models/CommitTest.php +++ b/tests/Unit/Models/CommitTest.php @@ -29,6 +29,7 @@ 'root_id', 'hot_score', 'pasteis_count', + 'type', 'organization_mentions', 'body_segments', 'preview_segments', diff --git a/tests/Unit/Shipit.test.tsx b/tests/Unit/Shipit.test.tsx new file mode 100644 index 0000000000..d02cae886c --- /dev/null +++ b/tests/Unit/Shipit.test.tsx @@ -0,0 +1,82 @@ +import assert from 'node:assert/strict'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { test } from 'vite-plus/test'; +import { LaunchShip } from '../../resources/js/components/launch-ship'; +import { shipitDraft } from '../../resources/js/lib/shipit'; + +test('recognizes a standalone shipit command and preserves the draft before it', () => { + assert.equal(shipitDraft('/shipit'), ''); + assert.equal(shipitDraft('Fix the typo.\n/shipit'), 'Fix the typo.'); + assert.equal( + shipitDraft(' Keep this spacing. \n\n/shipit '), + ' Keep this spacing. \n', + ); + assert.equal(shipitDraft('A mobile draft\n/shipit\n'), 'A mobile draft'); + assert.equal(shipitDraft('Windows draft\r\n/shipit'), 'Windows draft'); +}); + +test('leaves ordinary prose and commands mentioned inside code alone', () => { + for (const body of [ + 'Try /shipit', + '/shipit later', + '/shipit-extra', + '`/shipit`', + '```text\n/shipit', + '```text\n/shipit\n```', + '> /shipit', + '', + ]) { + assert.equal(shipitDraft(body), null, body); + } +}); + +test('allows a command after a closed code block', () => { + const draft = '```sh\necho hello\n```'; + assert.equal(shipitDraft(`${draft}\n/shipit`), draft); +}); + +test('renders at most sixteen passengers on decks and counts everyone else aboard', () => { + const passengers = Array.from({ length: 1000 }, (_, index) => ({ + id: `p${index}`, + name: `Developer ${index}`, + handle: `dev${index}`, + avatar_url: null, + })); + const markup = renderToStaticMarkup( + , + ); + assert.equal( + (markup.match(/data-test="launch-passenger"/g) ?? []).length, + 16, + ); + assert.ok(markup.includes('+984')); + assert.ok(markup.includes('launch-overloaded')); + assert.ok(markup.includes('Developers aboard')); + assert.ok(markup.includes('launch-person')); + assert.ok(markup.includes('launch-passenger-deck')); + assert.ok(!markup.includes('crate')); + assert.ok(!markup.includes('launch-cargo')); +}); + +test('an empty launch still renders a ship without any invented passengers', () => { + const markup = renderToStaticMarkup( + , + ); + assert.ok(markup.includes('shipped it')); + assert.ok(!markup.includes('data-test="launch-passenger"')); + assert.ok(!markup.includes('launch-overloaded')); +}); + +test('the creator is displayed as captain without becoming a passenger', () => { + const markup = renderToStaticMarkup( + , + ); + assert.ok(markup.includes('Captain @creator')); + assert.ok(markup.includes('launch-captain-hat')); + assert.ok(markup.includes('data-passengers="0"')); + assert.ok(!markup.includes('data-test="launch-passenger"')); +});