diff --git a/app/Http/Controllers/Api/CommitPreviewController.php b/app/Http/Controllers/Api/CommitPreviewController.php index c92ded73f4..20e1a07eee 100644 --- a/app/Http/Controllers/Api/CommitPreviewController.php +++ b/app/Http/Controllers/Api/CommitPreviewController.php @@ -5,6 +5,7 @@ namespace App\Http\Controllers\Api; use App\Http\Requests\CreateApiCommitPreviewRequest; +use App\Http\Resources\ShownGuildMentions; use App\Queries\MentionedOrganizationsQuery; use App\Queries\MentionedUsersQuery; use App\Services\CommitBodies; @@ -27,6 +28,7 @@ public function store(CreateApiCommitPreviewRequest $request, EmojiShortcodes $e 'body' => $body, ...$commitBodies->segments($body), 'mentions' => $mentions->positions($body, $mentionedOrganizations->get($body, $mentionedUsers->get($body))), + 'guild_mentions' => ShownGuildMentions::get([$body], $request->user()), ]]); } } diff --git a/app/Http/Controllers/Api/CommitTranslationController.php b/app/Http/Controllers/Api/CommitTranslationController.php index 601545a04a..575c74b8aa 100644 --- a/app/Http/Controllers/Api/CommitTranslationController.php +++ b/app/Http/Controllers/Api/CommitTranslationController.php @@ -7,6 +7,7 @@ use App\Actions\CreateCommitTranslation; use App\Exceptions\CommitProcessingFailed; use App\Http\Requests\CreateApiCommitTranslationRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Commit; use App\Services\CommitTranslations; use Illuminate\Http\JsonResponse; @@ -33,7 +34,7 @@ public function store(CreateApiCommitTranslationRequest $request, Commit $commit ->header('Cache-Control', 'no-store, private'); } - return response()->json(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)]) + return response()->json(ShownGuildMentions::of(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)], $request->user())) ->header('Cache-Control', 'no-store, private'); } } diff --git a/app/Http/Controllers/CommitPollController.php b/app/Http/Controllers/CommitPollController.php index b6ce817f45..1c5a077c2e 100644 --- a/app/Http/Controllers/CommitPollController.php +++ b/app/Http/Controllers/CommitPollController.php @@ -5,6 +5,7 @@ namespace App\Http\Controllers; use App\Http\Requests\ShowCommitPollRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Commit; use App\Models\User; use Illuminate\Container\Attributes\CurrentUser; @@ -18,8 +19,8 @@ */ public function show(ShowCommitPollRequest $request, #[CurrentUser] ?User $user, Commit $commit): JsonResponse { - return response()->json([ + return response()->json(ShownGuildMentions::of([ 'poll' => Commit::query()->withPollFor($user)->findOrFail($commit->id)->poll, - ])->header('Cache-Control', 'no-store, private'); + ], $user))->header('Cache-Control', 'no-store, private'); } } diff --git a/app/Http/Controllers/CommitPollVoteController.php b/app/Http/Controllers/CommitPollVoteController.php index 79b197754c..b27ec63197 100644 --- a/app/Http/Controllers/CommitPollVoteController.php +++ b/app/Http/Controllers/CommitPollVoteController.php @@ -6,6 +6,7 @@ use App\Actions\CreateCommitPollVote; use App\Http\Requests\CreateCommitPollVoteRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Commit; use App\Models\User; use Illuminate\Container\Attributes\CurrentUser; @@ -17,8 +18,8 @@ public function store(CreateCommitPollVoteRequest $request, #[CurrentUser] User { $action->handle($user, $request->option()); - return response()->json([ + return response()->json(ShownGuildMentions::of([ 'poll' => Commit::query()->withPollFor($user)->findOrFail($commit->id)->poll, - ]); + ], $user)); } } diff --git a/app/Http/Controllers/CommitPreviewController.php b/app/Http/Controllers/CommitPreviewController.php index 816e0b2fd2..b1e2d3ea70 100644 --- a/app/Http/Controllers/CommitPreviewController.php +++ b/app/Http/Controllers/CommitPreviewController.php @@ -5,6 +5,7 @@ namespace App\Http\Controllers; use App\Http\Requests\CreateCommitPreviewRequest; +use App\Http\Resources\ShownGuildMentions; use App\Queries\MentionedOrganizationsQuery; use App\Queries\MentionedUsersQuery; use App\Services\CodeSpans; @@ -26,11 +27,13 @@ public function store( ): JsonResponse { $body = $request->string('body')->value(); $mentions = $mentionedUsers->get($body); + $expanded = $emojiShortcodes->replace($body); return response()->json([ - 'segments' => $codeSpans->highlight($emojiShortcodes->replace($body)), + 'segments' => $codeSpans->highlight($expanded), 'mentions' => $mentions, 'organization_mentions' => $mentionedOrganizations->get($body, $mentions), + 'guild_mentions' => ShownGuildMentions::get([$expanded], $request->user()), ]); } } diff --git a/app/Http/Controllers/CommitTranslationController.php b/app/Http/Controllers/CommitTranslationController.php index e6c5d8268b..1a78f833c5 100644 --- a/app/Http/Controllers/CommitTranslationController.php +++ b/app/Http/Controllers/CommitTranslationController.php @@ -8,6 +8,7 @@ use App\Exceptions\CommitProcessingFailed; use App\Http\Requests\CreateCommitTranslationRequest; use App\Http\Requests\ShowCommitTranslationRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Commit; use App\Services\CommitTranslations; use Illuminate\Http\JsonResponse; @@ -20,7 +21,7 @@ */ public function show(ShowCommitTranslationRequest $request, Commit $commit, CommitTranslations $translations): JsonResponse { - return response()->json(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)]) + return response()->json(ShownGuildMentions::of(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)], $request->user())) ->header('Cache-Control', 'no-store, private'); } @@ -39,7 +40,7 @@ public function store(CreateCommitTranslationRequest $request, Commit $commit, C ->header('Cache-Control', 'no-store, private'); } - return response()->json(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)]) + return response()->json(ShownGuildMentions::of(['translation' => $translations->display($commit, $request->string('language')->value(), includePending: true)], $request->user())) ->header('Cache-Control', 'no-store, private'); } } diff --git a/app/Http/Controllers/ConversationController.php b/app/Http/Controllers/ConversationController.php index e8f4869581..b9067a95dd 100644 --- a/app/Http/Controllers/ConversationController.php +++ b/app/Http/Controllers/ConversationController.php @@ -7,6 +7,7 @@ use App\Actions\UpdateConversationReadThrough; use App\Http\Requests\ListConversationsRequest; use App\Http\Requests\ShowConversationRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Conversation; use App\Models\User; use App\Queries\ConversationsQuery; @@ -20,7 +21,7 @@ public function index(ListConversationsRequest $request, #[CurrentUser] User $user, ConversationsQuery $conversations): Response { return Inertia::render('conversation/index', [ - 'inbox' => fn (): array => $conversations->get($user), + 'inbox' => fn (): array => ShownGuildMentions::of($conversations->get($user), $user), 'partner' => null, 'thread' => null, ]); @@ -42,9 +43,9 @@ public function show(ShowConversationRequest $request, #[CurrentUser] User $user $action->handle($user, $conversation, $thread['messages']->last()->id ?? 0); } - return $thread; + return ShownGuildMentions::of($thread, $user); }, - 'inbox' => fn (): array => $conversations->get($user), + 'inbox' => fn (): array => ShownGuildMentions::of($conversations->get($user), $user), 'partner' => $partner, ]); } diff --git a/app/Http/Controllers/ConversationMessageController.php b/app/Http/Controllers/ConversationMessageController.php index 6eb07ee817..555aed8b91 100644 --- a/app/Http/Controllers/ConversationMessageController.php +++ b/app/Http/Controllers/ConversationMessageController.php @@ -8,6 +8,7 @@ use App\Actions\CreateMessage; use App\Http\Requests\CreateConversationMessageRequest; use App\Http\Requests\ListConversationMessagesRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\User; use App\Queries\ConversationThreadQuery; use Illuminate\Container\Attributes\CurrentUser; @@ -17,10 +18,10 @@ { public function index(ListConversationMessagesRequest $request, #[CurrentUser] User $user, User $partner, ConversationThreadQuery $threads): JsonResponse { - return response()->json([ + return response()->json(ShownGuildMentions::of([ 'partner' => $partner, ...$threads->get($user, $partner, $request->afterId(), $request->beforeId(), $request->reactionsAfter()), - ])->header('Cache-Control', 'private, no-store'); + ], $user))->header('Cache-Control', 'private, no-store'); } public function store(CreateConversationMessageRequest $request, #[CurrentUser] User $user, User $partner, CreateConversation $createConversation, CreateMessage $action): JsonResponse @@ -38,6 +39,6 @@ public function store(CreateConversationMessageRequest $request, #[CurrentUser] $request->voiceWaveform(), ); - return response()->json(['message' => $message], 201); + return response()->json(ShownGuildMentions::of(['message' => $message], $user), 201); } } diff --git a/app/Http/Controllers/GuildController.php b/app/Http/Controllers/GuildController.php index de80fc205b..339d19eb6c 100644 --- a/app/Http/Controllers/GuildController.php +++ b/app/Http/Controllers/GuildController.php @@ -6,11 +6,13 @@ use App\Actions\CreateGuild; use App\Actions\UpdateGuild; +use App\Enums\UserUpdate; use App\Exceptions\GuildModeratorRemoved; use App\Http\Requests\CreateGuildRequest; use App\Http\Requests\ListGuildsRequest; use App\Http\Requests\ShowGuildRequest; use App\Http\Requests\UpdateGuildRequest; +use App\Http\Resources\GuildResource; use App\Http\Resources\ShownStreams; use App\Models\Guild; use App\Models\GuildSubmission; @@ -18,6 +20,7 @@ use App\Queries\GuildCommitsQuery; use App\Queries\GuildsQuery; use App\Queries\JoinedGuildsQuery; +use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Http\RedirectResponse; use Illuminate\Http\UploadedFile; @@ -31,7 +34,9 @@ public function index(ListGuildsRequest $request, #[CurrentUser] User $user, Gui return Inertia::render('guild/index', [ 'query' => $request->term(), 'guildPage' => fn () => $query->paginate($request->term(), $request->integer('page', 1), $user) - ->through(fn (Guild $guild): string => $guild->id), + ->through(fn (Guild $guild): array => ['id' => $guild->id, ...GuildResource::make($guild)->resolve($request)]), + 'guilds' => Inertia::live(fn (): array => $query->get($user, $request->visibleGuilds()) + ->map(fn (Guild $guild): array => ['id' => $guild->id, ...GuildResource::make($guild)->resolve($request)])->all(), UserUpdate::Guilds->value, new PrivateChannel($user)), ])->withViewData(['robots' => 'noindex, follow']); } @@ -55,13 +60,14 @@ public function store(CreateGuildRequest $request, #[CurrentUser] User $user, Cr return to_route('guild.show', $guild->handle); } - public function show(ShowGuildRequest $request, Guild $guild, #[CurrentUser] User $user, GuildCommitsQuery $query, JoinedGuildsQuery $joinedGuilds): Response + public function show(ShowGuildRequest $request, Guild $guild, #[CurrentUser] User $user, GuildCommitsQuery $query, JoinedGuildsQuery $joinedGuilds, GuildsQuery $guilds): Response { $commits = $query->get($guild, $user, $request->integer('page', 1)); return Inertia::render('guild/show', [ 'handle' => $guild->handle, 'readFrom' => $joinedGuilds->readFrom($guild, $user), + 'guild' => Inertia::live(fn (): array => ['id' => $guild->id, ...GuildResource::make($guilds->get($user, [$guild->handle])->firstOrFail())->resolve($request)], UserUpdate::Guilds->value, new PrivateChannel($user)), 'canModerate' => $guild->user_id === $user->id, 'pinnedCommit' => ShownStreams::commit($query->pinned($guild, $user)), 'commits' => $commits->currentPage() > 1 diff --git a/app/Http/Controllers/GuildSuggestionController.php b/app/Http/Controllers/GuildSuggestionController.php new file mode 100644 index 0000000000..3626974079 --- /dev/null +++ b/app/Http/Controllers/GuildSuggestionController.php @@ -0,0 +1,22 @@ +json([ + 'guilds' => GuildBadgeResource::collection($request->has('handles') + ? $query->references($request->handles()) + : $query->suggestions($request->string('q')->trim()->lower()->value())), + ])->header('Cache-Control', 'private, no-store'); + } +} diff --git a/app/Http/Controllers/InboxController.php b/app/Http/Controllers/InboxController.php index ce8b3dc5df..7340734ec0 100644 --- a/app/Http/Controllers/InboxController.php +++ b/app/Http/Controllers/InboxController.php @@ -5,6 +5,7 @@ namespace App\Http\Controllers; use App\Http\Requests\ListInboxRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\User; use App\Queries\ConversationsQuery; use Illuminate\Container\Attributes\CurrentUser; @@ -14,12 +15,12 @@ { public function index(ListInboxRequest $request, #[CurrentUser] User $user, ConversationsQuery $conversations): JsonResponse { - return response()->json([ + return response()->json(ShownGuildMentions::of([ ...($request->notificationBaseline() ? ['notification_baseline' => $conversations->notificationBaseline($user)] : []), ...$conversations->get($user, $request->tab(), $request->term(), $request->beforeId()), ...($request->notificationConversations() ? ['notification_conversations' => $conversations->get($user, pinnedFirst: false)['conversations']] : []), 'unread' => $conversations->unreadCount($user), 'requests' => $conversations->requestCount($user), - ])->header('Cache-Control', 'private, no-store'); + ], $user))->header('Cache-Control', 'private, no-store'); } } diff --git a/app/Http/Controllers/MessagePinController.php b/app/Http/Controllers/MessagePinController.php index c4940d2a5d..d57fe2ae89 100644 --- a/app/Http/Controllers/MessagePinController.php +++ b/app/Http/Controllers/MessagePinController.php @@ -8,8 +8,11 @@ use App\Actions\UpdateMessagePin; use App\Http\Requests\DeleteMessagePinRequest; use App\Http\Requests\UpdateMessagePinRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Message; +use App\Models\User; use App\Queries\PinnedMessagesQuery; +use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Http\JsonResponse; /** @@ -18,21 +21,21 @@ */ final readonly class MessagePinController { - public function update(UpdateMessagePinRequest $request, Message $message, UpdateMessagePin $action, PinnedMessagesQuery $pinnedMessages): JsonResponse + public function update(UpdateMessagePinRequest $request, Message $message, #[CurrentUser] User $user, UpdateMessagePin $action, PinnedMessagesQuery $pinnedMessages): JsonResponse { $action->handle($message); $org = $message->conversation()->firstOrFail(); - return response()->json(['pinned' => $pinnedMessages->get($org), 'reactions_version' => $org->reactions_version]); + return response()->json(ShownGuildMentions::of(['pinned' => $pinnedMessages->get($org), 'reactions_version' => $org->reactions_version], $user)); } - public function destroy(DeleteMessagePinRequest $request, Message $message, DeleteMessagePin $action, PinnedMessagesQuery $pinnedMessages): JsonResponse + public function destroy(DeleteMessagePinRequest $request, Message $message, #[CurrentUser] User $user, DeleteMessagePin $action, PinnedMessagesQuery $pinnedMessages): JsonResponse { $action->handle($message); $org = $message->conversation()->firstOrFail(); - return response()->json(['pinned' => $pinnedMessages->get($org), 'reactions_version' => $org->reactions_version]); + return response()->json(ShownGuildMentions::of(['pinned' => $pinnedMessages->get($org), 'reactions_version' => $org->reactions_version], $user)); } } diff --git a/app/Http/Controllers/OrgController.php b/app/Http/Controllers/OrgController.php index 0e779a994f..fddaf82285 100644 --- a/app/Http/Controllers/OrgController.php +++ b/app/Http/Controllers/OrgController.php @@ -10,6 +10,7 @@ use App\Http\Requests\CreateOrgRequest; use App\Http\Requests\ShowOrgRequest; use App\Http\Requests\UpdateOrgRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Conversation; use App\Models\User; use App\Queries\ConversationsQuery; @@ -34,9 +35,9 @@ public function show(ShowOrgRequest $request, #[CurrentUser] User $user, Convers $action->handle($user, $org, $thread['messages']->last()->id ?? 0); - return $thread; + return ShownGuildMentions::of($thread, $user); }, - 'inbox' => fn (): array => $conversations->get($user), + 'inbox' => fn (): array => ShownGuildMentions::of($conversations->get($user), $user), 'partner' => null, 'org' => ['id' => $org->id, 'name' => $org->name], ]); diff --git a/app/Http/Controllers/OrgMentionController.php b/app/Http/Controllers/OrgMentionController.php index 55d68bbc52..f27caba998 100644 --- a/app/Http/Controllers/OrgMentionController.php +++ b/app/Http/Controllers/OrgMentionController.php @@ -6,6 +6,7 @@ use App\Actions\DeleteOrgMentions; use App\Http\Requests\DeleteOrgMentionsRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Conversation; use App\Models\User; use App\Queries\OrgMentionsQuery; @@ -21,6 +22,6 @@ public function destroy(DeleteOrgMentionsRequest $request, #[CurrentUser] User $ { $action->handle($user, $org, $request->messageIds()); - return response()->json($mentions->get($user, $org)); + return response()->json(ShownGuildMentions::of($mentions->get($user, $org), $user)); } } diff --git a/app/Http/Controllers/OrgMessageController.php b/app/Http/Controllers/OrgMessageController.php index 83bdb18233..ee05f7bf66 100644 --- a/app/Http/Controllers/OrgMessageController.php +++ b/app/Http/Controllers/OrgMessageController.php @@ -7,6 +7,7 @@ use App\Actions\CreateMessage; use App\Http\Requests\CreateOrgMessageRequest; use App\Http\Requests\ListOrgMessagesRequest; +use App\Http\Resources\ShownGuildMentions; use App\Models\Conversation; use App\Models\User; use App\Queries\ConversationThreadQuery; @@ -17,10 +18,10 @@ { public function index(ListOrgMessagesRequest $request, #[CurrentUser] User $user, Conversation $org, ConversationThreadQuery $threads): JsonResponse { - return response()->json([ + return response()->json(ShownGuildMentions::of([ 'org' => ['id' => $org->id, 'name' => $org->name], ...$threads->org($user, $org, $request->afterId(), $request->beforeId(), $request->reactionsAfter()), - ])->header('Cache-Control', 'private, no-store'); + ], $user))->header('Cache-Control', 'private, no-store'); } public function store(CreateOrgMessageRequest $request, #[CurrentUser] User $user, Conversation $org, CreateMessage $action): JsonResponse @@ -38,6 +39,6 @@ public function store(CreateOrgMessageRequest $request, #[CurrentUser] User $use $request->voiceWaveform(), ); - return response()->json(['message' => $message], 201); + return response()->json(ShownGuildMentions::of(['message' => $message], $user), 201); } } diff --git a/app/Http/Controllers/ScheduledCommitController.php b/app/Http/Controllers/ScheduledCommitController.php index a9c7ae55d9..e70b6b9644 100644 --- a/app/Http/Controllers/ScheduledCommitController.php +++ b/app/Http/Controllers/ScheduledCommitController.php @@ -28,8 +28,12 @@ public function index(Request $request, #[CurrentUser] User $user, ScheduledCommitsQuery $scheduled): Response { return Inertia::render('scheduled-commits/index', [ - 'scheduledCommits' => Inertia::live(fn (): LengthAwarePaginator => $scheduled->builder($user) - ->paginate(20)->through(fn (ScheduledCommit $scheduledCommit): array => ScheduledCommitResource::make($scheduledCommit)->resolve($request)), on: UserUpdate::ScheduledCommits->value, channel: new PrivateChannel($user)), + 'scheduledCommits' => Inertia::live(function () use ($scheduled, $user, $request): LengthAwarePaginator { + $page = $scheduled->builder($user)->paginate(20); + $page->setCollection(collect(ScheduledCommitResource::collection($page->getCollection())->resolve($request))); + + return $page; + }, on: UserUpdate::ScheduledCommits->value, channel: new PrivateChannel($user)), ]); } diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index 688e741fc5..3eb66a5361 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -5,6 +5,10 @@ namespace App\Http\Controllers; use App\Http\Requests\ListSearchRequest; +use App\Http\Resources\GuildBadgeResource; +use App\Models\User; +use App\Queries\GuildMentionsQuery; +use Illuminate\Container\Attributes\CurrentUser; use Inertia\Inertia; use Inertia\Response; @@ -14,10 +18,16 @@ * Results are fetched by the client from CommitSearchController, so the page renders before the embedding is paid for. * Every query is a page of its own, so search engines follow the results without indexing them. */ - public function index(ListSearchRequest $request): Response + public function index(ListSearchRequest $request, #[CurrentUser] User $user, GuildMentionsQuery $guilds): Response { return Inertia::render('search/index', [ 'query' => $request->term(), + 'guildLookup' => function () use ($request, $user, $guilds): array { + $handle = $request->guildHandle(); + $guild = $handle === null ? null : ($guilds->get([$request->term()], $user)[$handle] ?? null); + + return ['handle' => $handle, 'guild' => $guild === null ? null : GuildBadgeResource::make($guild)->resolve($request)]; + }, ])->withViewData(['robots' => 'noindex, follow']); } } diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index ec2485ad7f..e5f1e0c4b5 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -10,7 +10,9 @@ use App\Enums\UserUpdate; use App\Http\Requests\DeleteUserRequest; use App\Http\Requests\ShowUserRequest; +use App\Http\Resources\GuildResource; use App\Http\Resources\ShownStreams; +use App\Models\Guild; use App\Models\User; use App\Queries\BioProfilesQuery; use App\Queries\FollowersYouKnowQuery; @@ -70,7 +72,10 @@ public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser return Inertia::render('user/show', [ 'user' => Inertia::live(fn (): ?array => ShownStreams::user($getCountedUser()), 'profile', $profile), - 'profileGuilds' => Inertia::live(fn (): ?array => $currentUser instanceof User && $features->available(Feature::Guilds, $currentUser) ? $guilds->joinedHandles($user) : null, 'profile', $profile), + 'profileGuilds' => $currentUser instanceof User + ? Inertia::live(fn (): ?array => $features->available(Feature::Guilds, $currentUser) ? $guilds->joined($user, $currentUser)->map(fn (Guild $guild): array => ['id' => $guild->id, ...GuildResource::make($guild)->resolve($request)])->all() : null, 'profile', $profile) + ->live(UserUpdate::Guilds->value, new PrivateChannel($currentUser)) + : null, 'bioProfiles' => fn (): array => $bioProfiles->get($user), 'pasteisReceived' => Inertia::live(fn (): ?int => $currentUser?->pasteis_mode ? $user->pasteis_received : null, 'profile', $profile), 'isFollowing' => $relationship(fn (): bool => $currentUser?->isFollowing($user) ?? false), diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index 3990f2f6a1..a1f0693d88 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -12,16 +12,13 @@ use App\Enums\RepliesPerPage; use App\Enums\UserUpdate; use App\Http\Requests\ListNotificationsRequest; -use App\Http\Resources\GuildResource; use App\Http\Resources\ShownStreams; use App\Models\Commit; -use App\Models\Guild; use App\Models\Organization; use App\Models\User; use App\Queries\BioProfilesQuery; use App\Queries\ConversationsQuery; use App\Queries\DevelopersCountQuery; -use App\Queries\GuildsQuery; use App\Queries\HotTopicsQuery; use App\Queries\JoinedGuildsQuery; use App\Queries\LiveFollowingQuery; @@ -169,12 +166,7 @@ public function share(Request $request): array 'isLiteMobileApp' => str_contains((string) $request->userAgent(), 'DevNullLite/'), 'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true', 'showsWhoToFollow' => $showsWhoToFollow, - 'guilds' => $user instanceof User - ? Inertia::once(fn (): ?array => resolve(Features::class)->available(Feature::Guilds, $user) ? resolve(GuildsQuery::class)->get($user)->map(fn (Guild $guild): array => [ - 'id' => $guild->id, - ...GuildResource::make($guild)->resolve($request), - ])->all() : null)->until(60)->fresh($request->routeIs('guild.*', 'search.index'))->live(UserUpdate::Guilds->value, new PrivateChannel($user)) - : null, + 'guildsEnabled' => $live(fn (): bool => $user instanceof User && resolve(Features::class)->available(Feature::Guilds, $user), UserUpdate::Guilds), 'joinedGuilds' => $user instanceof User ? Inertia::once(fn (): array => resolve(JoinedGuildsQuery::class)->get($user))->until(60)->live(UserUpdate::Guilds->value, new PrivateChannel($user)) : [], diff --git a/app/Http/Requests/ListGuildSuggestionsRequest.php b/app/Http/Requests/ListGuildSuggestionsRequest.php new file mode 100644 index 0000000000..2abfa77fec --- /dev/null +++ b/app/Http/Requests/ListGuildSuggestionsRequest.php @@ -0,0 +1,37 @@ +available(Feature::Guilds, $this->user()) ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array> */ + public function rules(): array + { + return [ + 'q' => ['nullable', 'string', 'max:100', 'prohibits:handles'], + 'handles' => ['sometimes', 'array', 'list', 'max:100'], + 'handles.*' => ['required', 'string', 'max:60', 'regex:/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD'], + ]; + } + + /** @return list */ + public function handles(): array + { + /** @var list $handles */ + $handles = $this->validated('handles', []); + + return array_values(array_unique(array_map(mb_strtolower(...), $handles))); + } +} diff --git a/app/Http/Requests/ListGuildsRequest.php b/app/Http/Requests/ListGuildsRequest.php index 2752dfa71b..e4ee6cc4e2 100644 --- a/app/Http/Requests/ListGuildsRequest.php +++ b/app/Http/Requests/ListGuildsRequest.php @@ -22,6 +22,8 @@ public function rules(): array return [ 'q' => ['nullable', 'string', 'max:100'], 'page' => ['sometimes', 'integer', 'min:1', 'max:10000'], + 'visible_guilds' => ['sometimes', 'array', 'list', 'max:24'], + 'visible_guilds.*' => ['required', 'string', 'max:60', 'regex:/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD'], ]; } @@ -29,4 +31,21 @@ public function term(): string { return $this->string('q')->trim()->ltrim('#')->trim()->value(); } + + /** @return list */ + public function visibleGuilds(): array + { + /** @var list $handles */ + $handles = $this->validated('visible_guilds', []); + + return $handles; + } + + public function prepareForValidation(): void + { + if ($this->hasHeader('X-Guild-Handles')) { + $handles = json_decode($this->header('X-Guild-Handles', '')); + $this->merge(['visible_guilds' => is_array($handles) ? $handles : null]); + } + } } diff --git a/app/Http/Requests/ListSearchRequest.php b/app/Http/Requests/ListSearchRequest.php index 7ead4b5855..fb4db211cc 100644 --- a/app/Http/Requests/ListSearchRequest.php +++ b/app/Http/Requests/ListSearchRequest.php @@ -27,4 +27,9 @@ public function term(): string { return $this->string('q')->trim()->value(); } + + public function guildHandle(): ?string + { + return preg_match('/^#\p{L}[\p{L}\p{M}\p{N}_]{0,59}$/uD', $this->term()) === 1 ? mb_strtolower(mb_substr($this->term(), 1)) : null; + } } diff --git a/app/Http/Resources/CommitResource.php b/app/Http/Resources/CommitResource.php index 10929956e7..b202866091 100644 --- a/app/Http/Resources/CommitResource.php +++ b/app/Http/Resources/CommitResource.php @@ -38,6 +38,13 @@ */ final class CommitResource extends JsonResource { + public bool $withGuildMentions = true; + + public static function newCollection(mixed $resource): GuildMentionCollection + { + return new GuildMentionCollection($resource, self::class); + } + /** * @return array */ @@ -81,7 +88,7 @@ public function toArray(Request $request): array return $commit; } - return [ + $shown = [ ...$commit, ...resolve(CommitBodies::class)->segments($this->body), 'mentions' => resolve(Mentions::class)->positions($this->body, $this->organization_mentions ?? []), @@ -99,5 +106,7 @@ public function toArray(Request $request): array 'next_cursor' => data_get($this->getAttribute('reply_preview'), 'next_cursor'), ]), ]; + + return $this->withGuildMentions ? ShownGuildMentions::of($shown, $request->user()) : $shown; } } diff --git a/app/Http/Resources/ConversationResource.php b/app/Http/Resources/ConversationResource.php index a9d6011234..017ac2a5aa 100644 --- a/app/Http/Resources/ConversationResource.php +++ b/app/Http/Resources/ConversationResource.php @@ -20,6 +20,13 @@ */ final class ConversationResource extends JsonResource { + public bool $withGuildMentions = true; + + public static function newCollection(mixed $resource): GuildMentionCollection + { + return new GuildMentionCollection($resource, self::class); + } + /** * @return array */ @@ -28,7 +35,7 @@ public function toArray(Request $request): array /** @var ConversationSummary $conversation */ $conversation = $this->resource; - return [ + $shown = [ ...$conversation, 'partner' => $conversation['partner'] instanceof User ? UserResource::make($conversation['partner']) : null, 'members' => $conversation['members']?->map(fn (array $member): array => [ @@ -37,5 +44,7 @@ public function toArray(Request $request): array ]), 'last_message' => $conversation['last_message'] instanceof Message ? MessageResource::make($conversation['last_message']) : null, ]; + + return $this->withGuildMentions ? ShownGuildMentions::of($shown, $request->user()) : $shown; } } diff --git a/app/Http/Resources/ConversationThreadResource.php b/app/Http/Resources/ConversationThreadResource.php index 42d043aea6..b566c502b1 100644 --- a/app/Http/Resources/ConversationThreadResource.php +++ b/app/Http/Resources/ConversationThreadResource.php @@ -42,10 +42,10 @@ public function toArray(Request $request): array /** @var ThreadWithPartner $thread */ $thread = $this->resource; - return [ + return ShownGuildMentions::of([ ...$thread, 'partner' => UserResource::make($thread['partner']), 'messages' => MessageResource::collection($thread['messages']), - ]; + ], $request->user()); } } diff --git a/app/Http/Resources/GuildBadgeResource.php b/app/Http/Resources/GuildBadgeResource.php new file mode 100644 index 0000000000..f477b9f76e --- /dev/null +++ b/app/Http/Resources/GuildBadgeResource.php @@ -0,0 +1,26 @@ + $this->handle, + 'name' => $this->name, + 'emoji' => $this->emoji, + 'icon_url' => $request->routeIs('api-*') ? $this->apiIconUrl($request->user()) : $this->iconUrl(), + ]; + } +} diff --git a/app/Http/Resources/GuildMentionCollection.php b/app/Http/Resources/GuildMentionCollection.php new file mode 100644 index 0000000000..ad624a719f --- /dev/null +++ b/app/Http/Resources/GuildMentionCollection.php @@ -0,0 +1,32 @@ + */ + public $collection; + + public bool $withGuildMentions = true; + + /** + * @return array + */ + public function toArray(Request $request): array + { + $shown = $this->collection->map(function (MessageResource|ScheduledCommitResource|ConversationResource|CommitResource|NotificationResource $resource) use ($request): array { + $resource = clone $resource; + $resource->withGuildMentions = false; + + return $resource->resolve($request); + })->all(); + + return $this->withGuildMentions ? ShownGuildMentions::of($shown, $request->user()) : $shown; + } +} diff --git a/app/Http/Resources/MessageResource.php b/app/Http/Resources/MessageResource.php index a893c30874..37bb893d17 100644 --- a/app/Http/Resources/MessageResource.php +++ b/app/Http/Resources/MessageResource.php @@ -29,12 +29,19 @@ */ final class MessageResource extends JsonResource { + public bool $withGuildMentions = true; + + public static function newCollection(mixed $resource): GuildMentionCollection + { + return new GuildMentionCollection($resource, self::class); + } + /** * @return array */ public function toArray(Request $request): array { - return [ + $shown = [ 'id' => $this->id, 'user_id' => $this->user_id, 'client_id' => $this->client_id, @@ -79,5 +86,7 @@ public function toArray(Request $request): array 'pinned_at' => $this->pinned_at?->toIso8601ZuluString(), 'created_at' => $this->created_at->toIso8601ZuluString(), ]; + + return $this->withGuildMentions ? ShownGuildMentions::of($shown, $request->user()) : $shown; } } diff --git a/app/Http/Resources/NotificationResource.php b/app/Http/Resources/NotificationResource.php index f9bb4a0890..435540e2a6 100644 --- a/app/Http/Resources/NotificationResource.php +++ b/app/Http/Resources/NotificationResource.php @@ -10,6 +10,7 @@ use App\Models\Organization; use App\Models\UserTimeout; use Illuminate\Http\Request; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Illuminate\Http\Resources\Json\JsonResource; /** @@ -22,12 +23,19 @@ */ final class NotificationResource extends JsonResource { + public bool $withGuildMentions = true; + + public static function newCollection(mixed $resource): GuildMentionCollection + { + return new GuildMentionCollection($resource, self::class); + } + /** * @return array */ public function toArray(Request $request): array { - return [ + $shown = [ 'id' => $this->id, 'type' => $this->type, 'subject_id' => $this->subject_id, @@ -35,7 +43,7 @@ public function toArray(Request $request): array 'read_at' => $this->read_at?->toIso8601ZuluString(), 'created_at' => $this->created_at->toIso8601ZuluString(), 'actor' => ProfileResource::make($this->actor), - 'actors' => ProfileResource::collection($this->whenLoaded('actors')), + 'actors' => $this->whenLoaded('actors', fn (): AnonymousResourceCollection => ProfileResource::collection($this->actors)), 'organization' => $this->organization instanceof Organization ? OrganizationResource::make($this->organization) : null, 'group_id' => $this->group_id, 'event_count' => $this->event_count, @@ -48,5 +56,7 @@ public function toArray(Request $request): array 'ends_at' => $this->timeout->ends_at->toIso8601ZuluString(), ]] : [], ]; + + return $this->withGuildMentions ? ShownGuildMentions::of($shown, $request->user()) : $shown; } } diff --git a/app/Http/Resources/OrgThreadResource.php b/app/Http/Resources/OrgThreadResource.php index 8df0efe9b5..3421507be2 100644 --- a/app/Http/Resources/OrgThreadResource.php +++ b/app/Http/Resources/OrgThreadResource.php @@ -51,13 +51,13 @@ public function toArray(Request $request): array 'user' => UserResource::make($member['user']), ]); - return [ + return ShownGuildMentions::of([ ...$thread, 'org' => ['id' => $thread['org']->id, 'name' => $thread['org']->name], 'messages' => MessageResource::collection($thread['messages']), 'pinned' => $thread['pinned'] === null ? null : MessageResource::collection($thread['pinned']), 'mentions' => MessageResource::collection($thread['mentions']), 'members' => $members, - ]; + ], $request->user()); } } diff --git a/app/Http/Resources/ScheduledCommitResource.php b/app/Http/Resources/ScheduledCommitResource.php index c8f1346be5..74e2d5cd58 100644 --- a/app/Http/Resources/ScheduledCommitResource.php +++ b/app/Http/Resources/ScheduledCommitResource.php @@ -18,12 +18,19 @@ */ final class ScheduledCommitResource extends JsonResource { + public bool $withGuildMentions = true; + + public static function newCollection(mixed $resource): GuildMentionCollection + { + return new GuildMentionCollection($resource, self::class); + } + /** * @return array */ public function toArray(Request $request): array { - return [ + $shown = [ 'id' => $this->id, 'author' => $this->author === null ? null : ProfileResource::make($this->author)->resolve($request), ...($this->submitted_at === null && $this->body !== null @@ -35,5 +42,7 @@ public function toArray(Request $request): array 'submitted_at' => $this->submitted_at?->toIso8601String(), 'status' => $this->submitted_at === null ? 'scheduled' : ($this->commit === null || $this->commit->trashed() ? 'deleted' : $this->commit->status->value), ]; + + return $this->withGuildMentions ? ShownGuildMentions::of($shown, $request->user()) : $shown; } } diff --git a/app/Http/Resources/ShownCommitResource.php b/app/Http/Resources/ShownCommitResource.php index 4b46384c36..b40a23ded4 100644 --- a/app/Http/Resources/ShownCommitResource.php +++ b/app/Http/Resources/ShownCommitResource.php @@ -16,7 +16,8 @@ */ final class ShownCommitResource extends JsonResource implements Arrayable { - public function __construct(Commit $resource, private readonly ?string $joinedGuild = null) + /** @param array|null $shown */ + public function __construct(Commit $resource, private readonly ?string $joinedGuild = null, private readonly ?array $shown = null) { parent::__construct($resource); } @@ -28,7 +29,7 @@ public function toArray(?Request $request = null): array { $commit = $this->resource; assert($commit instanceof Commit); - $shown = ShownStreams::commit($commit); + $shown = $this->shown ?? ShownStreams::commit($commit); assert(is_array($shown)); return $commit->trashed() ? $shown : [...$shown, 'joined_guild' => $this->joinedGuild]; diff --git a/app/Http/Resources/ShownGuildMentions.php b/app/Http/Resources/ShownGuildMentions.php new file mode 100644 index 0000000000..322548e215 --- /dev/null +++ b/app/Http/Resources/ShownGuildMentions.php @@ -0,0 +1,147 @@ + $texts + * @return GuildMentions + */ + public static function get(iterable $texts, ?User $viewer): array + { + try { + $guilds = resolve(GuildMentionsQuery::class)->get($texts, $viewer); + } catch (QueryException $queryException) { + report($queryException); + + return []; + } + + /** @var GuildMentions */ + return array_map(fn (Guild $guild): array => GuildBadgeResource::make($guild)->resolve(), $guilds); + } + + /** + * @template TKey of array-key + * + * @param array $shown + * @return array + */ + public static function of(array $shown, ?User $viewer): array + { + $shown = array_map(self::normalize(...), $shown); + $mentions = self::get(self::texts($shown), $viewer); + + return self::apply($shown, $mentions); + } + + /** + * @param iterable> $items + * @return list> + */ + public static function many(iterable $items, ?User $viewer): array + { + $shown = array_values(collect($items)->map(fn (array $item): array => array_map(self::normalize(...), $item))->all()); + $mentions = self::get(collect($shown)->flatMap(self::texts(...))->all(), $viewer); + + return array_map(fn (array $item): array => self::apply($item, $mentions), $shown); + } + + private static function normalize(mixed $value): mixed + { + if ($value instanceof MessageResource || $value instanceof ScheduledCommitResource || $value instanceof ConversationResource || $value instanceof CommitResource || $value instanceof NotificationResource || $value instanceof GuildMentionCollection) { + $value = clone $value; + $value->withGuildMentions = false; + } + + if ($value instanceof JsonResource) { + $value = $value->resolve(); + } elseif ($value instanceof Collection) { + return $value->map(self::normalize(...))->all(); + } elseif ($value instanceof Arrayable) { + $value = $value->toArray(); + } + + return is_array($value) ? array_map(self::normalize(...), $value) : $value; + } + + /** + * @param array $shown + * @return list + */ + private static function texts(array $shown): array + { + $texts = []; + $text = self::text($shown); + + if ($text !== null) { + $texts[] = $text; + } + + foreach ($shown as $value) { + if (is_array($value)) { + array_push($texts, ...self::texts($value)); + } + } + + return $texts; + } + + /** @param array $shown */ + private static function text(array $shown): ?string + { + if (array_key_exists('body', $shown)) { + return is_string($shown['body']) ? $shown['body'] : null; + } + + if (is_string($shown['label'] ?? null) && array_key_exists('votes_count', $shown)) { + return $shown['label']; + } + + // Translations only expose segments, never their original cached body or highlighted code as prose. + return is_array($shown['body_segments'] ?? null) + ? collect($shown['body_segments'])->where('type', 'text')->pluck('text')->implode("\n") + : null; + } + + /** + * @template TKey of array-key + * + * @param array $shown + * @param GuildMentions $mentions + * @return array + */ + private static function apply(array $shown, array $mentions): array + { + $text = self::text($shown); + + foreach ($shown as $key => $value) { + if (is_array($value)) { + $shown[$key] = self::apply($value, $mentions); + } + } + + if ($text !== null) { + $shown['guild_mentions'] = array_intersect_key($mentions, array_flip(resolve(Hashtags::class)->handles($text))); + } + + return $shown; + } +} diff --git a/app/Http/Resources/ShownNotificationResource.php b/app/Http/Resources/ShownNotificationResource.php index 4516176d1e..b2ebff3515 100644 --- a/app/Http/Resources/ShownNotificationResource.php +++ b/app/Http/Resources/ShownNotificationResource.php @@ -17,11 +17,18 @@ */ final class ShownNotificationResource extends JsonResource implements Arrayable { + /** @var array|null */ + public ?array $shown = null; + /** * @return array */ public function toArray(?Request $request = null): array { + if ($this->shown !== null) { + return $this->shown; + } + $notification = $this->resource; assert($notification instanceof Notification); @@ -39,5 +46,6 @@ public function toArray(?Request $request = null): array 'actors' => $notification->actors->map(fn (Profile $actor): array => ShownStreams::profile($actor))->all(), ] : [], ]; + } } diff --git a/app/Http/Resources/ShownStreams.php b/app/Http/Resources/ShownStreams.php index 22ca5281ab..87059bedcd 100644 --- a/app/Http/Resources/ShownStreams.php +++ b/app/Http/Resources/ShownStreams.php @@ -58,7 +58,7 @@ public static function users(iterable $users): array /** * @return array|null */ - public static function commit(?Commit $commit): ?array + public static function commit(?Commit $commit, bool $withGuildMentions = true): ?array { if (! $commit instanceof Commit) { return null; @@ -87,31 +87,33 @@ public static function commit(?Commit $commit): ?array } if (is_array($shown['quoted_commit'] ?? null) && $commit->relationLoaded('quotedCommit')) { - $shown['quoted_commit'] = self::commit($commit->quotedCommit); + $shown['quoted_commit'] = self::commit($commit->quotedCommit, false); } $preview = $commit->hasAttribute('reply_preview') ? $commit->getAttribute('reply_preview') : null; if (is_array($preview) && $preview['data'] instanceof Collection) { - $shown['reply_preview'] = [...$preview, 'data' => self::commits($preview['data'])]; + $shown['reply_preview'] = [...$preview, 'data' => self::commits($preview['data'], false)]; } - return $shown; + return $withGuildMentions ? ShownGuildMentions::of($shown, request()->user()) : $shown; } /** * @param iterable $commits * @return list> */ - public static function commits(iterable $commits): array + public static function commits(iterable $commits, bool $withGuildMentions = true): array { $shown = []; foreach ($commits as $commit) { - $shown[] = self::commit($commit); + $shown[] = self::commit($commit, false); } - return array_values(array_filter($shown)); + $shown = array_values(array_filter($shown)); + + return $withGuildMentions ? ShownGuildMentions::many($shown, request()->user()) : $shown; } /** @@ -123,8 +125,9 @@ public static function commits(iterable $commits): array public static function page(CursorPaginator $page, ?User $joinedGuildsFor = null): CursorPaginator { $guilds = $joinedGuildsFor instanceof User ? resolve(GuildCommitsQuery::class)->joinedFor($page->items(), $joinedGuildsFor) : []; + $cards = self::commits($page->items()); $shown = clone $page; - $shown->setCollection($page->getCollection()->map(fn (Commit $commit): ShownCommitResource => new ShownCommitResource($commit, $guilds[$commit->id] ?? null))); + $shown->setCollection($page->getCollection()->values()->map(fn (Commit $commit, int $index): ShownCommitResource => new ShownCommitResource($commit, $guilds[$commit->id] ?? null, $cards[$index]))); return $shown; } @@ -135,8 +138,14 @@ public static function page(CursorPaginator $page, ?User $joinedGuildsFor = null */ public static function notifications(CursorPaginator $page): CursorPaginator { + $cards = ShownGuildMentions::many($page->getCollection()->map(fn (Notification $notification): array => new ShownNotificationResource($notification)->toArray())->all(), request()->user()); $shown = clone $page; - $shown->setCollection($page->getCollection()->map(fn (Notification $notification): ShownNotificationResource => new ShownNotificationResource($notification))); + $shown->setCollection($page->getCollection()->values()->map(function (Notification $notification, int $index) use ($cards): ShownNotificationResource { + $resource = new ShownNotificationResource($notification); + $resource->shown = $cards[$index]; + + return $resource; + })); return $shown; } @@ -150,9 +159,9 @@ public static function notifications(CursorPaginator $page): CursorPaginator public static function reports(CursorPaginator $reports): CursorPaginator { $shown = clone $reports; - $shown->setCollection($reports->getCollection()->map(fn (CommitReport $report): array => $report->relationLoaded('commit') - ? [...$report->toArray(), 'commit' => self::commit($report->commit)] - : $report->toArray())); + $shown->setCollection(collect(ShownGuildMentions::many($reports->getCollection()->map(fn (CommitReport $report): array => $report->relationLoaded('commit') + ? [...$report->toArray(), 'commit' => self::commit($report->commit, false)] + : $report->toArray())->all(), request()->user()))); return $shown; } diff --git a/app/Queries/GuildMentionsQuery.php b/app/Queries/GuildMentionsQuery.php new file mode 100644 index 0000000000..e87bbc8ac7 --- /dev/null +++ b/app/Queries/GuildMentionsQuery.php @@ -0,0 +1,42 @@ + + */ +final readonly class GuildMentionsQuery +{ + public function __construct(private Features $features, private Hashtags $hashtags, private GuildsQuery $guilds) + { + // + } + + /** + * @param iterable $texts + * @return array + */ + public function get(iterable $texts, ?User $viewer): array + { + if (! $viewer instanceof User) { + return []; + } + + $handles = array_values(collect($texts)->flatMap($this->hashtags->handles(...))->unique()->all()); + + if ($handles === [] || ! $this->features->available(Feature::Guilds, $viewer)) { + return []; + } + + return $this->guilds->references($handles)->keyBy(fn (Guild $guild): string => mb_strtolower($guild->handle))->all(); + } +} diff --git a/app/Queries/GuildsQuery.php b/app/Queries/GuildsQuery.php index ab829625e7..8d220ff1ce 100644 --- a/app/Queries/GuildsQuery.php +++ b/app/Queries/GuildsQuery.php @@ -12,17 +12,20 @@ final readonly class GuildsQuery { - /** @return list */ - public function joinedHandles(User $user): array + /** @return Collection */ + public function joined(User $user, User $viewer): Collection { - return array_values(Guild::query()->whereHas('members', fn (Builder $query): Builder => $query->whereKey($user->id)) - ->orderBy('handle')->get(['handle'])->map(fn (Guild $guild): string => $guild->handle)->all()); + return $this->withPreferencesOf($viewer)->whereHas('members', fn (Builder $query): Builder => $query->whereKey($user->id)) + ->orderBy('handle')->get(); } - /** @return Collection */ - public function get(User $user): Collection + /** + * @param list $handles + * @return Collection + */ + public function get(User $user, array $handles): Collection { - return $this->withPreferencesOf($user)->orderByDesc('members_count')->orderBy('handle')->get(); + return $this->withPreferencesOf($user)->whereIn('handle', $handles)->get(); } public function find(Guild $guild, User $user): Guild @@ -44,6 +47,30 @@ public function paginate(string $term, int $page, User $user): LengthAwarePagina ->paginate(24, page: $page); } + /** + * @param list $handles + * @return Collection + */ + public function references(array $handles): Collection + { + return new Collection(collect(array_chunk($handles, 65535))->flatMap(fn (array $chunk): Collection => Guild::query() + ->select(['handle', 'name', 'emoji', 'icon_path', 'updated_at']) + ->whereIn('handle', $chunk)->orderBy('handle')->get())->all()); + } + + /** @return Collection */ + public function suggestions(string $term): Collection + { + $escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $term); + + return Guild::query()->select(['handle', 'name', 'emoji', 'icon_path', 'updated_at'])->withCount('members') + ->where(fn (Builder $query): Builder => $query + ->whereRaw('TRANSLATE(LOWER(handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"]) + ->orWhereRaw('TRANSLATE(LOWER(name COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"])) + ->orderByRaw('CASE WHEN TRANSLATE(LOWER(handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\' THEN 0 ELSE 1 END', ["{$escaped}%"]) + ->orderByDesc('members_count')->orderBy('handle')->limit(6)->get(); + } + /** * The member count and whether the user joined or muted each guild come from one read, so they always agree. * diff --git a/app/Services/Hashtags.php b/app/Services/Hashtags.php index bec1073d9b..524ff77eae 100644 --- a/app/Services/Hashtags.php +++ b/app/Services/Hashtags.php @@ -14,9 +14,10 @@ public function __construct(private CodeSpans $codeSpans, private Urls $urls) /** @return list */ public function handles(string $text): array { - $urls = collect($this->urls->all($text))->flatMap(fn (string $url): array => [$url, (string) preg_replace('/^https?:\/\//i', '', $url)])->all(); - $prose = str_replace($urls, '', $this->codeSpans->withoutCode($text)); + $prose = $this->codeSpans->withoutCode((string) preg_replace('/^> ?/m', '', $text)); + $prose = $this->urls->withoutUrls($prose); $prose = preg_replace('/(?-])#(\p{L}[\p{L}\p{M}\p{N}_]*)/u', $prose, $matches); return array_values(array_unique(array_map(mb_strtolower(...), $matches[1]))); diff --git a/app/Services/Urls.php b/app/Services/Urls.php index bf47b4953d..d7957f500a 100644 --- a/app/Services/Urls.php +++ b/app/Services/Urls.php @@ -105,6 +105,23 @@ public function all(string $text): array return $urls; } + /** + * Masks recognized prose URL spans, preserving code and the punctuation around each URL. + */ + public function withoutUrls(string $text): string + { + return $this->codeSpans->mapProse($text, fn (string $prose): string => (string) preg_replace_callback($this->pattern, function (array $matches): string { + $match = $this->withoutTrailingPunctuation($matches[0]); + $url = preg_match('/^https?:\/\//i', $match) === 1 ? $match : 'https://'.$match; + + if (str_ends_with($url, '://') || mb_strlen($url) > self::MAX_LENGTH) { + return $matches[0]; + } + + return ' '.mb_substr($matches[0], mb_strlen($match)); + }, $prose)); + } + /** * Shortens every URL in the prose for display, leaving the code as written. */ diff --git a/resources/js/components/app-nav.tsx b/resources/js/components/app-nav.tsx index 9f3974d286..8164fd9b91 100644 --- a/resources/js/components/app-nav.tsx +++ b/resources/js/components/app-nav.tsx @@ -73,7 +73,7 @@ const navLabelClassName = * Guests see the same items, each taking them to sign in. */ function useNavItems(): (NavItem & { isActive: boolean })[] { - const { auth, hasUnmoderatedCommits, guilds } = usePage().props; + const { auth, hasUnmoderatedCommits, guildsEnabled } = usePage().props; const { isCurrentUrl, isCurrentOrParentUrl } = useCurrentUrl(); const { user, log } = auth; const unreadMessages = useUnreadMessages(); @@ -116,7 +116,7 @@ function useNavItems(): (NavItem & { isActive: boolean })[] { href: hrefFor(() => StarredCommitController.index()), icon: Star, }, - ...(guilds !== null && guilds !== undefined + ...(guildsEnabled ? [{ title: 'Guilds', href: guildIndex(), icon: UsersRound }] : []), ...(auth.isAdmin diff --git a/resources/js/components/chat/message-parts.tsx b/resources/js/components/chat/message-parts.tsx index e3b07557d3..56060772fb 100644 --- a/resources/js/components/chat/message-parts.tsx +++ b/resources/js/components/chat/message-parts.tsx @@ -37,7 +37,10 @@ export function MessageText({ message, isMine, }: { - message: Pick; + message: Pick< + Message, + 'body' | 'body_segments' | 'mentions' | 'guild_mentions' + >; isMine: boolean; }) { const segments: BodySegment[] = @@ -47,6 +50,7 @@ export function MessageText({ diff --git a/resources/js/components/commit-body.tsx b/resources/js/components/commit-body.tsx index 1136c2c538..9139ff6c30 100644 --- a/resources/js/components/commit-body.tsx +++ b/resources/js/components/commit-body.tsx @@ -7,11 +7,13 @@ import { bodyBlocks } from '@/lib/code'; import { emojify } from '@/lib/emoji'; import { cn } from '@/lib/utils'; import type { BodySegment, Commit } from '@/types'; +import type { GuildMentions } from '@/types/guild'; export function CommitBody({ segments, mentions, organizationMentions = null, + guildMentions, className, isStatic = false, linksEveryMention = true, @@ -19,6 +21,7 @@ export function CommitBody({ segments: BodySegment[]; mentions: Commit['mentions']; organizationMentions?: Commit['organization_mentions']; + guildMentions?: GuildMentions; className?: string; isStatic?: boolean; /** @@ -44,6 +47,7 @@ export function CommitBody({ segments={block.segments} mentions={mentions} organizationMentions={organizationMentions} + guildMentions={guildMentions} isStatic={isStatic} linksEveryMention={linksEveryMention} /> @@ -54,6 +58,7 @@ export function CommitBody({ segments={block.segments} mentions={mentions} organizationMentions={organizationMentions} + guildMentions={guildMentions} isStatic={isStatic} linksEveryMention={linksEveryMention} /> @@ -67,12 +72,14 @@ export function BodySegments({ segments, mentions, organizationMentions = null, + guildMentions, isStatic = false, linksEveryMention = true, }: { segments: BodySegment[]; mentions: Commit['mentions']; organizationMentions?: Commit['organization_mentions']; + guildMentions?: GuildMentions; isStatic?: boolean; linksEveryMention?: boolean; }) { @@ -89,6 +96,7 @@ export function BodySegments({ text={emojify(segment.text)} mentions={mentions} organizationMentions={organizationMentions} + guildMentions={guildMentions} pasteisMode={Boolean(auth.pasteis)} isStatic={isStatic} linksEveryMention={linksEveryMention} @@ -128,12 +136,14 @@ export function FoldedCommitBody({ previewSegments, mentions, organizationMentions = null, + guildMentions, className, }: { segments: BodySegment[]; previewSegments: BodySegment[] | null; mentions: Commit['mentions']; organizationMentions?: Commit['organization_mentions']; + guildMentions?: GuildMentions; className?: string; }) { const [isUnfolded, setIsUnfolded] = useState(false); @@ -145,6 +155,7 @@ export function FoldedCommitBody({ segments={segments} mentions={mentions} organizationMentions={organizationMentions} + guildMentions={guildMentions} className={className} /> ); @@ -176,6 +187,7 @@ export function FoldedCommitBody({ } mentions={mentions} organizationMentions={organizationMentions} + guildMentions={guildMentions} className={className} /> {!isUnfolded && ( diff --git a/resources/js/components/commit-card.tsx b/resources/js/components/commit-card.tsx index 0f9454e932..096488bad5 100644 --- a/resources/js/components/commit-card.tsx +++ b/resources/js/components/commit-card.tsx @@ -437,6 +437,15 @@ export function CommitCard({ because you joined{' '}

)} @@ -486,6 +495,7 @@ export function CommitCard({
); @@ -78,7 +82,23 @@ export function CommitPoll({ const commitNotFound = useCommitNotFound(); const now = useNow(); const id = useId(); - const [poll, setPoll] = useState(initialPoll); + const [snapshot, setSnapshot] = useState({ + source: initialPoll, + poll: initialPoll, + }); + // Parent refreshes update option badges, but unchanged props must not replace a newer read or vote. + const poll = + snapshot.source === initialPoll + ? snapshot.poll + : { + ...snapshot.poll, + options: snapshot.poll.options.map((option) => ({ + ...option, + guild_mentions: initialPoll.options.find( + (fresh) => fresh.id === option.id, + )?.guild_mentions, + })), + }; const request = useHttp<{ option: string }, { poll: Poll }>({ option: '', }); @@ -103,7 +123,10 @@ export function CommitPoll({ if (response.ok && started === latest.current && !request.processing) { readSince.current = startedAt; - setPoll(((await response.json()) as { poll: Poll }).poll); + setSnapshot({ + source: initialPoll, + poll: ((await response.json()) as { poll: Poll }).poll, + }); } }); const isApproved = commit.status === 'approved'; @@ -191,7 +214,7 @@ export function CommitPoll({ } latest.current++; - setPoll(response.poll); + setSnapshot({ source: initialPoll, poll: response.poll }); router.flushAll(); } catch { if (!isNotFound) { @@ -213,6 +236,7 @@ export function CommitPoll({ @@ -245,6 +269,7 @@ export function CommitPoll({ @@ -306,6 +331,9 @@ export function CommitPoll({ mentions={ commit.mentions ?? null } + guildMentions={ + option.guild_mentions + } isStatic={isStatic} /> {option.voted && ( diff --git a/resources/js/components/commit-search-results.tsx b/resources/js/components/commit-search-results.tsx index 36fe2e720c..995de22472 100644 --- a/resources/js/components/commit-search-results.tsx +++ b/resources/js/components/commit-search-results.tsx @@ -6,18 +6,27 @@ import { GraphCanvas } from '@/components/graph-canvas'; import { GuildIcon } from '@/components/guild-icon'; import { groupSearchCommits } from '@/lib/commit-search-results'; import type { Commit } from '@/types'; +import type { GuildBadge } from '@/types/guild'; export type SearchResultSet = { term: string; commits: Commit[] }; -export function GuildSearchHeading({ handle }: { handle: string }) { - const { guilds } = usePage().props; - const guild = guilds?.find((guild) => guild.handle === handle); +export function GuildSearchHeading({ + handle, + guild, +}: { + handle: string; + guild?: GuildBadge | null; +}) { + const visibleGuild = usePage().props.guildsEnabled ? guild : null; return ( - - - {guild?.name ?? `#${handle}`} + + + {visibleGuild?.name ?? `#${handle}`} ); @@ -75,7 +84,10 @@ export function SearchResults({ {handle && (

- +

)} diff --git a/resources/js/components/commit-thread.tsx b/resources/js/components/commit-thread.tsx index dee57cbc3e..49321cdd17 100644 --- a/resources/js/components/commit-thread.tsx +++ b/resources/js/components/commit-thread.tsx @@ -1660,6 +1660,7 @@ function CommitReply({
(); const [generated, setGenerated] = useState<{ body: string; + source: Commit['translation']; translation: CommitTranslation | null; } | null>(null); const [display, setDisplay] = useState<'original' | 'translated' | null>( @@ -74,7 +75,11 @@ export function useCommitTranslation(commit: Commit) { readSince.current = since; needsRead = false; - setGenerated({ body, translation: fresh.translation }); + setGenerated({ + body, + source: commit.translation, + translation: fresh.translation, + }); } }, 500); const refresh = () => { @@ -123,6 +128,7 @@ export function useCommitTranslation(commit: Commit) { }, [ commit.id, commit.body, + commit.translation, isApproved, language, isTranslated, @@ -170,6 +176,7 @@ export function useCommitTranslation(commit: Commit) { ); setGenerated({ body: commit.body, + source: commit.translation, translation: response.translation, }); setDisplay('translated'); @@ -187,6 +194,14 @@ export function useCommitTranslation(commit: Commit) { previewSegments: translated ? translated.preview_segments : commit.preview_segments, + guildMentions: translated + ? generated?.translation === translation && + generated.source !== commit.translation && + commit.translation?.language === language && + commit.translation.translated + ? commit.translation.translated.guild_mentions + : translated.guild_mentions + : commit.guild_mentions, notice: translation?.available ? (
{translated && ( diff --git a/resources/js/components/composer-preview.tsx b/resources/js/components/composer-preview.tsx index 80791aa088..b8c98631a0 100644 --- a/resources/js/components/composer-preview.tsx +++ b/resources/js/components/composer-preview.tsx @@ -1,14 +1,15 @@ import { useHttp, usePage } from '@inertiajs/react'; import { Eye, Link2 } from 'lucide-react'; import type { KeyboardEvent, RefObject } from 'react'; -import { useId, useState } from 'react'; +import { useEffect, useEffectEvent, useId, useRef, useState } from 'react'; +import { toast } from 'sonner'; import CommitPreviewController from '@/actions/App/Http/Controllers/CommitPreviewController'; import { ActionTooltip } from '@/components/action-tooltip'; import { CommitBody } from '@/components/commit-body'; import { objectUrlFor } from '@/components/commit-image-picker'; import { CommitImages } from '@/components/commit-images'; import { CommitPoll } from '@/components/commit-poll'; -import { hasMention } from '@/components/linkified-text'; +import { hasMention, typedGuildHandles } from '@/components/linkified-text'; import type { PollDraft } from '@/components/poll-editor'; import { Button } from '@/components/ui/button'; import { useNow } from '@/hooks/use-now'; @@ -16,14 +17,17 @@ import { bodySegments, hasCodeBlock } from '@/lib/code'; import { hasModKey, useKeyLabels } from '@/lib/keyboard'; import { cn } from '@/lib/utils'; import type { BodySegment } from '@/types'; +import type { GuildMentions } from '@/types/guild'; type Mentions = Record; type Resolved = { body: string; + guildHandle?: string; segments: BodySegment[]; mentions: Mentions; organizationMentions: Mentions; + guildMentions: GuildMentions; }; const isModifierEnter = (event: KeyboardEvent) => @@ -36,8 +40,8 @@ export type ComposerPreview = ReturnType; /** * Switches a composer between writing and previewing its draft as the commit it becomes. The draft is rendered right - * away, and its code blocks are highlighted and its mentions linked once the server, the only place code is - * highlighted and handles are looked up, sends them back. + * away unless guild badges need resolving first, so their names never replace hashtags in an already visible body. + * Code highlighting and mention links come from the server. */ export function useComposerPreview({ body, @@ -50,8 +54,12 @@ export function useComposerPreview({ textareaRef: RefObject; isSubmittable: boolean; }) { + const { guildsEnabled } = usePage().props; const [isPreviewing, setIsPreviewing] = useState(false); + const [isResolving, setIsResolving] = useState(false); const [resolved, setResolved] = useState(null); + const lookup = useRef(null); + const pendingLookup = useRef(null); const previewId = useId(); const request = useHttp< { body: string; guild_handle?: string }, @@ -59,17 +67,34 @@ export function useComposerPreview({ segments: BodySegment[]; mentions: Mentions | []; organization_mentions: Mentions | []; + guild_mentions: GuildMentions | []; } >({ body: '', }); const draft = body.trim(); - const isResolved = resolved?.body === draft; + const isResolved = + resolved?.body === draft && resolved.guildHandle === guildHandle; const segments = isResolved ? resolved.segments : bodySegments(draft); + const handles = guildsEnabled ? typedGuildHandles(draft) : []; + const needsPreviewRequest = + hasCodeBlock(segments) || hasMention(segments) || handles.length > 0; + const cancelRequest = useEffectEvent(() => request.cancel()); + + useEffect( + () => () => { + lookup.current?.abort(); + cancelRequest(); + lookup.current = null; + pendingLookup.current = null; + setIsResolving(false); + }, + [draft, guildHandle], + ); - const resolve = async () => { - if (isResolved || (!hasCodeBlock(segments) && !hasMention(segments))) { + const resolve = async (controller: AbortController) => { + if (isResolved || !needsPreviewRequest) { return; } @@ -77,14 +102,25 @@ export function useComposerPreview({ body: body.trim(), ...(guildHandle && { guild_handle: guildHandle }), })); + let validationRejected = false; try { const response = await request.submit( CommitPreviewController.store(), + { + onError: () => { + validationRejected = true; + }, + }, ); + if (controller.signal.aborted) { + return; + } + setResolved({ body: draft, + guildHandle, segments: response.segments, mentions: Array.isArray(response.mentions) ? {} @@ -94,38 +130,99 @@ export function useComposerPreview({ ) ? {} : response.organization_mentions, + guildMentions: Array.isArray(response.guild_mentions) + ? {} + : response.guild_mentions, }); } catch { - // The preview keeps the code unhighlighted and the mentions as text. + if (controller.signal.aborted) { + return; + } + + if (validationRejected) { + setResolved({ + body: draft, + guildHandle, + segments: bodySegments(draft), + mentions: {}, + organizationMentions: {}, + guildMentions: {}, + }); + + return; + } + + // Keep writing when guild names could not be resolved, rather than changing the visible preview later. + if (handles.length > 0) { + toast.error('Could not load the preview. Try again.'); + controller.abort(); + } } }; - const show = (previewing: boolean, moveFocus: boolean) => { - setIsPreviewing(previewing); + const show = async (previewing: boolean, moveFocus: boolean) => { + if (previewing && pendingLookup.current) { + return; + } + + lookup.current?.abort(); + request.cancel(); + const controller = new AbortController(); + lookup.current = controller; + pendingLookup.current = null; + setIsResolving(false); if (previewing) { - void resolve(); + const resolving = resolve(controller); + + if (handles.length > 0 && !isResolved) { + pendingLookup.current = controller; + setIsResolving(true); + await resolving; + if (lookup.current === controller) { + pendingLookup.current = null; + setIsResolving(false); + } + } } + if (controller.signal.aborted) { + if (moveFocus && lookup.current === controller) { + textareaRef.current?.focus(); + } + + return; + } + + setIsPreviewing(previewing); + if (moveFocus) { - requestAnimationFrame(() => + requestAnimationFrame(() => { + if (controller.signal.aborted) { + return; + } + (previewing ? document.getElementById(previewId) : textareaRef.current - )?.focus(), - ); + )?.focus(); + }); } }; return { isPreviewing, + isResolving, draft, segments, mentions: isResolved ? resolved.mentions : null, organizationMentions: isResolved ? resolved.organizationMentions : null, + guildMentions: isResolved ? resolved.guildMentions : undefined, previewId, toggle: (moveFocus = false) => show(!isPreviewing, moveFocus), - close: () => setIsPreviewing(false), + close: () => { + void show(false, false); + }, /** * Handles ⌘/Ctrl + Shift + P in the textarea, and tells whether it did. */ @@ -135,7 +232,7 @@ export function useComposerPreview({ } event.preventDefault(); - show(true, true); + void show(true, true); return true; }, @@ -143,7 +240,7 @@ export function useComposerPreview({ if (isPreviewShortcut(event) || event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); - show(false, true); + void show(false, true); } if (isModifierEnter(event) && isSubmittable) { @@ -174,6 +271,8 @@ export function PreviewToggle({ size="icon" onClick={() => preview.toggle(true)} aria-pressed={preview.isPreviewing} + aria-busy={preview.isResolving} + aria-disabled={preview.isResolving} aria-label="Preview" aria-keyshortcuts="Meta+Shift+P Control+Shift+P" className={cn( @@ -217,6 +316,7 @@ export function ComposerPreviewBody({ segments={preview.segments} mentions={preview.mentions} organizationMentions={preview.organizationMentions} + guildMentions={preview.guildMentions} className="text-[15px]" /> ) : ( diff --git a/resources/js/components/guild-preferences.tsx b/resources/js/components/guild-preferences.tsx index ffa2334fe9..d9b9e7994b 100644 --- a/resources/js/components/guild-preferences.tsx +++ b/resources/js/components/guild-preferences.tsx @@ -1,4 +1,4 @@ -import { Link, router } from '@inertiajs/react'; +import { Link, router, usePage } from '@inertiajs/react'; import { UserPlus, Volume2, VolumeX } from 'lucide-react'; import { useState } from 'react'; import { @@ -33,10 +33,13 @@ export function GuildMemberCount({ guild }: { guild: Guild }) { export function GuildPreferences({ guild, showMute = true, + onChange, }: { guild: Guild; showMute?: boolean; + onChange?: (guild: Guild) => void; }) { + const { component } = usePage(); const [processing, setProcessing] = useState(false); const { isJustToggled, markToggled, onMouseLeave } = useFollowHover(); @@ -45,30 +48,70 @@ export function GuildPreferences({ const value = !guild[key]; markToggled(); setProcessing(true); + let succeeded = false; + const change = (item: Guild): Guild => + item.id === guild.id + ? { + ...item, + [key]: value, + ...(kind === 'joined' && value && { is_muted: false }), + member_count: + item.member_count + + (kind === 'joined' + ? Number(value) - Number(item.is_joined) + : 0), + } + : item; + onChange?.(change(guild)); router - .optimistic<{ guilds: Guild[] | null }>((props) => ({ - guilds: props.guilds?.map((item) => - item.id === guild.id - ? { - ...item, - [key]: value, - ...(kind === 'joined' && - value && { is_muted: false }), - member_count: - item.member_count + - (kind === 'joined' ? (value ? 1 : -1) : 0), - } - : item, - ), - })) + .optimistic<{ + guild?: Guild; + guilds?: Guild[]; + profileGuilds?: Guild[] | null; + guildPage?: { data: Guild[] }; + }>((props) => { + return { + ...(props.guild && { guild: change(props.guild) }), + ...(props.profileGuilds && { + profileGuilds: props.profileGuilds.map(change), + }), + ...(props.guildPage && { + guilds: props.guildPage.data.map((item) => + change( + props.guilds?.find( + (fresh) => fresh.id === item.id, + ) ?? item, + ), + ), + guildPage: { + ...props.guildPage, + data: props.guildPage.data.map(change), + }, + }), + }; + }) .put( (kind === 'joined' ? membership : mute).url(guild.id), { [kind]: value }, { - only: ['guilds'], + only: [ + component === 'user/show' + ? 'profileGuilds' + : component === 'guild/index' + ? 'guilds' + : 'guild', + ], preserveScroll: true, - onSuccess: () => router.flushAll(), - onFinish: () => setProcessing(false), + onSuccess: () => { + succeeded = true; + router.flushAll(); + }, + onFinish: () => { + if (!succeeded) { + onChange?.(guild); + } + setProcessing(false); + }, }, ); } diff --git a/resources/js/components/link-topic-commits.tsx b/resources/js/components/link-topic-commits.tsx index 7605078558..fa186f9ca7 100644 --- a/resources/js/components/link-topic-commits.tsx +++ b/resources/js/components/link-topic-commits.tsx @@ -234,6 +234,7 @@ function LinkTopicCommit({
{ + const prose = part.replace( + index === 0 ? /^> ?|(?<=\n)> ?/g : /(?<=\n)> ?/g, + '', + ); + const ranges = [ + ...colorsIn(prose, index === 0), + ...[...prose.matchAll(urlPattern)].flatMap((match) => { + const url = withoutTrailingPunctuation(match[0]); + + return hrefFor(url) === null + ? [] + : [{ index: match.index, length: url.length }]; + }), + ]; + + return [...prose.matchAll(hashtagPattern)] + .filter( + (match) => + !ranges.some( + (range) => + match.index >= range.index && + match.index < range.index + range.length, + ), + ) + .map((match) => match[0].slice(1).toLowerCase()); + }), + ), + ]; +} + // Like X, the hidden parts of a shortened URL stay in the text, so copying it or a screen reader gets the whole URL. function ShortenedUrl({ url }: { url: string }) { const { hiddenStart, shown, hiddenEnd, cut } = shortenUrl(url); @@ -629,19 +663,22 @@ function withWordmarks( export function Hashtag({ hashtag, guild: postedGuild, + guildMentions, }: { hashtag: string; - guild?: Pick | null; + guild?: GuildBadge | null; + guildMentions?: GuildMentions; }) { - const { auth, guilds } = usePage().props; + const { auth, guildsEnabled } = usePage().props; + const handle = hashtag.slice(1).toLowerCase(); const guild = postedGuild ?? - guilds?.find( - (guild) => guild.handle === hashtag.slice(1).toLowerCase(), - ); + (guildMentions && Object.hasOwn(guildMentions, handle) + ? guildMentions[handle] + : undefined); if (guild) { - const canOpenGuild = !!auth.user && !!guilds; + const canOpenGuild = !!auth.user && guildsEnabled; const className = 'inline-flex max-w-full items-baseline gap-[0.3em] rounded-sm bg-muted px-1 py-0.5 align-baseline font-mono text-[0.875em] leading-none font-normal text-foreground'; const content = ( @@ -707,6 +744,7 @@ function withHashtags( offset: number, hashtags: RegExpExecArray[], pasteisMode: boolean, + guildMentions: GuildMentions | undefined, ): ReactNode[] { const parts: ReactNode[] = []; let position = 0; @@ -724,7 +762,11 @@ function withHashtags( offset + position, pasteisMode, ), - , + , ); position = index + hashtag[0].length; @@ -746,6 +788,7 @@ function withColors( colors: Color[], hashtags: RegExpExecArray[], pasteisMode: boolean, + guildMentions: GuildMentions | undefined, ): ReactNode[] { const parts: ReactNode[] = []; let position = 0; @@ -763,6 +806,7 @@ function withColors( offset + position, hashtags, pasteisMode, + guildMentions, ), (null); const listRef = useRef(null); @@ -304,6 +306,17 @@ export function MentionTextarea({ const [issueResult, setIssueResult] = useState( null, ); + const [guildResult, setGuildResult] = useState<{ + query: string; + attempt: number; + guilds: GuildBadge[]; + failed?: boolean; + } | null>(null); + const [guildAttempt, setGuildAttempt] = useState(0); + const guildQuery = + trigger?.kind === 'guild' && guildsEnabled + ? trigger.query.toLowerCase() + : null; const issueQuery = trigger?.kind === 'issue' ? trigger.query : null; const issue = issueQuery === String(issueResult?.number) ? issueResult : null; @@ -328,6 +341,7 @@ export function MentionTextarea({ const close = () => { setTrigger(null); setPosition(null); + setGuildAttempt((attempt) => attempt + 1); }; const track = (textarea: HTMLTextAreaElement) => { @@ -335,7 +349,7 @@ export function MentionTextarea({ textarea, suggestsMentions, suggestsIssues, - suggestsIssues && !!guilds?.length, + suggestsIssues && guildsEnabled, ); if ( @@ -361,6 +375,7 @@ export function MentionTextarea({ next.query !== trigger.query ) { setActiveIndex(0); + setGuildAttempt((attempt) => attempt + 1); } setTrigger(next); @@ -425,6 +440,41 @@ export function MentionTextarea({ }; }, [issueQuery]); + useEffect(() => { + if (guildQuery === null) { + return; + } + + const controller = new AbortController(); + const timeout = setTimeout(() => { + void fetchGuilds({ q: guildQuery }, controller.signal) + .then((guilds) => { + if (!controller.signal.aborted) { + setGuildResult({ + query: guildQuery, + attempt: guildAttempt, + guilds, + }); + } + }) + .catch(() => { + if (!controller.signal.aborted) { + setGuildResult({ + query: guildQuery, + attempt: guildAttempt, + guilds: [], + failed: true, + }); + } + }); + }, debounce); + + return () => { + clearTimeout(timeout); + controller.abort(); + }; + }, [guildQuery, guildAttempt]); + useEffect(() => { if (!trigger) { return; @@ -508,23 +558,13 @@ export function MentionTextarea({ const emojiQuery = trigger?.kind === 'emoji' ? trigger.query.toLowerCase() : ''; const emojis = emojiQuery === '' ? [] : searchEmoji(emojiQuery); - const guildQuery = - trigger?.kind === 'guild' ? trigger.query.toLowerCase() : ''; - const matchingGuilds = - trigger?.kind === 'guild' - ? (guilds ?? []) - .filter( - (guild) => - guild.handle.includes(guildQuery) || - guild.name.toLowerCase().includes(guildQuery), - ) - .toSorted( - (a, b) => - Number(b.handle.startsWith(guildQuery)) - - Number(a.handle.startsWith(guildQuery)), - ) - .slice(0, 6) - : []; + const currentGuildResult = + guildQuery !== null && + guildResult?.query === guildQuery && + guildResult.attempt === guildAttempt + ? guildResult + : null; + const matchingGuilds = currentGuildResult?.guilds ?? []; const optionCount = trigger?.kind === 'guild' ? matchingGuilds.length @@ -540,7 +580,7 @@ export function MentionTextarea({ trigger !== null && position !== null && (trigger.kind === 'guild' - ? matchingGuilds.length > 0 + ? guildQuery !== null : trigger.kind === 'issue' ? issue !== null : trigger.kind === 'emoji' @@ -606,6 +646,19 @@ export function MentionTextarea({ if (isOpen && !event.nativeEvent.isComposing) { const hasModifier = event.metaKey || event.ctrlKey || event.altKey; + if ( + event.key === 'Enter' && + !hasModifier && + !event.shiftKey && + trigger?.kind === 'guild' && + currentGuildResult?.failed + ) { + event.preventDefault(); + setGuildAttempt((attempt) => attempt + 1); + + return; + } + if ( (event.key === 'ArrowDown' || event.key === 'ArrowUp') && optionCount > 0 @@ -664,7 +717,8 @@ export function MentionTextarea({ const activeId = !isOpen ? undefined : trigger?.kind === 'guild' - ? `${id}-guild-${matchingGuilds[selectedIndex].id}` + ? matchingGuilds[selectedIndex] && + `${id}-guild-${matchingGuilds[selectedIndex].handle}` : trigger?.kind === 'issue' ? `${id}-issue-${issue?.number}` : trigger?.kind === 'emoji' @@ -746,7 +800,36 @@ export function MentionTextarea({ data-mention-suggestions data-test="mention-suggestions" > - {trigger?.kind === 'guild' ? ( + {trigger?.kind === 'guild' && + matchingGuilds.length === 0 ? ( +
+ + {currentGuildResult === null + ? 'Looking up guilds…' + : currentGuildResult.failed + ? 'Guild lookup failed. Press Enter to retry.' + : 'No matching guilds.'} + + {currentGuildResult?.failed && ( + + )} +
+ ) : trigger?.kind === 'guild' ? (