From f9c5b0149a76f8d6d6919522c2327b2497cc4978 Mon Sep 17 00:00:00 2001 From: Pauline Vos Date: Tue, 17 Nov 2026 15:33:18 +0000 Subject: [PATCH] feat: paginate and search the guild directory --- KNOWLEDGE_BASE.md | 2 +- app/Http/Controllers/GuildController.php | 9 +- app/Http/Requests/ListGuildsRequest.php | 12 +- app/Queries/GuildsQuery.php | 15 ++ ...252_add_search_indexes_to_guilds_table.php | 21 ++ resources/js/app.tsx | 8 +- resources/js/pages/guild/index.tsx | 186 +++++++++++++++++- .../Controllers/GuildControllerTest.php | 86 ++++++++ tests/Unit/GuildControls.test.tsx | 68 +++++++ 9 files changed, 391 insertions(+), 16 deletions(-) create mode 100644 database/migrations/2026_11_17_164252_add_search_indexes_to_guilds_table.php diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 0f47f9f37..cb8955308 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -660,7 +660,7 @@ Sources: [issue command UI](resources/js/components/issue-command.tsx), [issue v Guilds are public groups around hashtags and are not generally available yet. In the preview, matching hashtags become small clickable guild labels; ordinary hashtags still open search. Create a guild from the Guilds overview or a hashtag's search page. From the overview, its display name determines the hashtag: “Laravel 4ever” becomes `#laravel4ever`. Display names and handles each allow up to 60 characters. When claiming a hashtag, the display name must match its letters, numbers and underscores, ignoring case; spaces, punctuation and decorative symbols are ignored, so `/dev/null` is valid for `#devnull`. Accents and underscores remain significant. Its creator joins automatically and maintains its icon and description. Each person can create up to 100 guilds. A guild's name, description and icon pass the same automated moderation as commits before the guild is published or edited; a guild that the moderation flags is not saved. -The Guilds page lists groups by member count. Click a guild's member count to browse its members: the moderator appears first, labeled “(moderator)”, followed by newest joins, with 50 people per page and Load more for the next page. Joining adds matching commits to Following without following every author and clears any existing mute. When a commit appears only because of a joined guild, it says “because you joined” beside the guild label. Leave a guild to reveal its Mute control. Muting hides matching commits from logs and search, including commits by followed authors. You can still open the guild or a commit directly. +The Guilds page lists groups by member count, with 24 guilds per page. Search matches keywords in guild names, handles, and descriptions, ignoring case; a leading `#` is optional. This directory search is keyword-based, not semantic. Click a guild's member count to browse its members: the moderator appears first, labeled “(moderator)”, followed by newest joins, with 50 people per page and Load more for the next page. Joining adds matching commits to Following without following every author and clears any existing mute. When a commit appears only because of a joined guild, it says “because you joined” beside the guild label. Leave a guild to reveal its Mute control. Muting hides matching commits from logs and search, including commits by followed authors. You can still open the guild or a commit directly. Each guild's bulletin board shows commits posted directly to it and regular commits containing its exact hashtag—not semantic search. Matching replies bring their thread onto the board, even when the root has no hashtag. Threads show reply previews and expand like a regular commit log, ordered by root date, newest first. Each page contains 30 distinct root commits; replies do not use up that limit, and Load more adds the next page. Posts from the board's composer stay attached to that guild without an automatic hashtag, including scheduled posts. They count toward the author's commit count but do not appear in their profile log or general feeds. They appear in Following when you join the guild, and in semantic search suggestions and results under a divider with the guild's name and icon. Regular hashtag commits keep appearing on profiles and in feeds as usual. Typing a hashtag offers matching guilds in the autocomplete menu; select one with the keyboard or pointer to insert its handle. diff --git a/app/Http/Controllers/GuildController.php b/app/Http/Controllers/GuildController.php index 93fd6eaab..9e5f64bd8 100644 --- a/app/Http/Controllers/GuildController.php +++ b/app/Http/Controllers/GuildController.php @@ -15,6 +15,7 @@ use App\Models\Guild; use App\Models\User; use App\Queries\GuildCommitsQuery; +use App\Queries\GuildsQuery; use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Http\RedirectResponse; use Illuminate\Http\UploadedFile; @@ -23,9 +24,13 @@ final readonly class GuildController { - public function index(ListGuildsRequest $request): Response + public function index(ListGuildsRequest $request, GuildsQuery $query): Response { - return Inertia::render('guild/index')->withViewData(['robots' => 'noindex, follow']); + return Inertia::render('guild/index', [ + 'query' => $request->term(), + 'guildPage' => fn () => $query->paginate($request->term(), $request->integer('page', 1)) + ->through(fn (Guild $guild): string => $guild->id), + ])->withViewData(['robots' => 'noindex, follow']); } public function store(CreateGuildRequest $request, #[CurrentUser] User $user, CreateGuild $action): RedirectResponse diff --git a/app/Http/Requests/ListGuildsRequest.php b/app/Http/Requests/ListGuildsRequest.php index 6fa867405..2752dfa71 100644 --- a/app/Http/Requests/ListGuildsRequest.php +++ b/app/Http/Requests/ListGuildsRequest.php @@ -16,9 +16,17 @@ public function authorize(Features $features): Response return $features->available(Feature::Guilds, $this->user()) ? Response::allow() : Response::denyAsNotFound(); } - /** @return array{} */ + /** @return array> */ public function rules(): array { - return []; + return [ + 'q' => ['nullable', 'string', 'max:100'], + 'page' => ['sometimes', 'integer', 'min:1', 'max:10000'], + ]; + } + + public function term(): string + { + return $this->string('q')->trim()->ltrim('#')->trim()->value(); } } diff --git a/app/Queries/GuildsQuery.php b/app/Queries/GuildsQuery.php index f3a7eae7e..d3d2fde77 100644 --- a/app/Queries/GuildsQuery.php +++ b/app/Queries/GuildsQuery.php @@ -8,6 +8,7 @@ use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Pagination\LengthAwarePaginator; final readonly class GuildsQuery { @@ -19,4 +20,18 @@ public function get(User $user): Collection 'muters as is_muted' => fn (Builder $query): Builder => $query->whereKey($user->id), ])->orderByDesc('members_count')->orderBy('handle')->get(); } + + /** @return LengthAwarePaginator */ + public function paginate(string $term, int $page): LengthAwarePaginator + { + $escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $term); + + return Guild::query()->select('id')->withCount('members') + ->when($term !== '', fn (Builder $query): Builder => $query->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}%"]) + ->orWhereRaw('TRANSLATE(LOWER(description COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"]))) + ->orderByDesc('members_count')->orderBy('handle') + ->paginate(24, page: $page); + } } diff --git a/database/migrations/2026_11_17_164252_add_search_indexes_to_guilds_table.php b/database/migrations/2026_11_17_164252_add_search_indexes_to_guilds_table.php new file mode 100644 index 000000000..cfd72d759 --- /dev/null +++ b/database/migrations/2026_11_17_164252_add_search_indexes_to_guilds_table.php @@ -0,0 +1,21 @@ +rawIndex('translate(lower(handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') gin_trgm_ops', 'guilds_lower_handle_trigram_index')->algorithm('gin'); + $table->rawIndex('translate(lower(name COLLATE "pg_c_utf8"), \'ς\', \'σ\') gin_trgm_ops', 'guilds_lower_name_trigram_index')->algorithm('gin'); + $table->rawIndex('translate(lower(description COLLATE "pg_c_utf8"), \'ς\', \'σ\') gin_trgm_ops', 'guilds_lower_description_trigram_index')->algorithm('gin'); + }); + } +}; diff --git a/resources/js/app.tsx b/resources/js/app.tsx index bacb23229..21d407f4e 100644 --- a/resources/js/app.tsx +++ b/resources/js/app.tsx @@ -12,7 +12,7 @@ import { trackAnalyticsEvents } from '@/lib/analytics'; import { setServerTime } from '@/lib/commit-changes'; import { trackCommitPhotoPage } from '@/lib/commit-photo'; import { initializeCommitState } from '@/lib/commit-state'; -import { trackCurrentPage } from '@/lib/current-page'; +import { currentPageComponent, trackCurrentPage } from '@/lib/current-page'; import { createEcho } from '@/lib/echo'; import { trackFollowRequests } from '@/lib/follow-requests'; import { startLiteMobileApp } from '@/lib/lite-mobile-app'; @@ -47,6 +47,9 @@ router.on('start', (event) => { router.on('navigate', (event) => { if (event.detail.type === 'history' || event.detail.cached === true) { catchUpAfterRestore(); + if (event.detail.page.component === 'guild/index') { + router.reload({ only: ['guildPage', 'guilds'] }); + } } else if (visitStartedAt !== null) { pageReadAt(visitStartedAt); } @@ -56,6 +59,9 @@ router.on('navigate', (event) => { window.addEventListener('pageshow', (event) => { if (event.persisted) { catchUpAfterRestore(); + if (currentPageComponent() === 'guild/index') { + router.reload({ only: ['guildPage', 'guilds'] }); + } } }); diff --git a/resources/js/pages/guild/index.tsx b/resources/js/pages/guild/index.tsx index f912b3fff..e36c5dc9a 100644 --- a/resources/js/pages/guild/index.tsx +++ b/resources/js/pages/guild/index.tsx @@ -1,7 +1,7 @@ -import { Head, Link, usePage } from '@inertiajs/react'; -import { Plus } from 'lucide-react'; +import { Form, Head, Link, usePage } from '@inertiajs/react'; +import { ChevronLeft, ChevronRight, Plus, Search } from 'lucide-react'; import { useState } from 'react'; -import { show } from '@/actions/App/Http/Controllers/GuildController'; +import { index, show } from '@/actions/App/Http/Controllers/GuildController'; import { GuildDialog } from '@/components/guild-dialog'; import { GuildIcon } from '@/components/guild-icon'; import { @@ -11,11 +11,25 @@ import { import { Button } from '@/components/ui/button'; import AppLayout from '@/layouts/app-layout'; -export default function Index() { +export default function Index({ + query, + guildPage, +}: { + query: string; + guildPage: { + data: string[]; + current_page: number; + last_page: number; + total: number; + }; +}) { const { guilds } = usePage().props; - const [order] = useState(() => guilds?.map((guild) => guild.id) ?? []); - const ranked = guilds?.toSorted( - (a, b) => order.indexOf(a.id) - order.indexOf(b.id), + const [search, setSearch] = useState({ query, value: query }); + if (search.query !== query) { + setSearch({ query, value: query }); + } + const ranked = guildPage.data.flatMap( + (id) => guilds?.find((guild) => guild.id === id) ?? [], ); return ( @@ -27,6 +41,59 @@ export default function Index() { Public groups, biggest first. Join to see their commits in Following.

+
+ {({ processing, errors }) => ( + <> +
+
+ + + setSearch({ + query, + value: event.target.value, + }) + } + maxLength={100} + aria-label="Search guilds" + aria-describedby="guild-search-help" + placeholder="Search guilds" + className="h-10 w-full rounded-md border bg-background pr-3 pl-9 text-base outline-none placeholder:text-muted-foreground focus-visible:border-ring md:text-sm" + /> +
+ +
+

+ {errors.q ?? + 'Search names, #handles, and descriptions.'} +

+ + )} +

@@ -39,9 +106,94 @@ export default function Index() {

- {guilds?.length ? ( + + {ranked.length ? (
    - {ranked?.map((guild) => ( + {ranked.map((guild) => (
  • ) : (

    - No guilds yet. Create the first one. + {query !== '' + ? 'No guilds found on this page. Try another keyword or return to the first page.' + : guildPage.current_page > 1 + ? 'No guilds on this page. Return to the first page.' + : 'No guilds yet. Create the first one.'} + {(query !== '' || guildPage.current_page > 1) && ( + + Browse all guilds + + )}

    )} diff --git a/tests/Feature/Controllers/GuildControllerTest.php b/tests/Feature/Controllers/GuildControllerTest.php index da32fae80..54e6eea94 100644 --- a/tests/Feature/Controllers/GuildControllerTest.php +++ b/tests/Feature/Controllers/GuildControllerTest.php @@ -529,6 +529,92 @@ $this->assertDatabaseMissing('guild_preferences', ['guild_id' => $jobs->id, 'user_id' => $admin->id]); }); +it('paginates matching guilds biggest first with handle ordering for ties', function (): void { + $admin = User::factory()->create(['handle' => 'admin']); + $guilds = Guild::factory()->count(25)->state(['user_id' => $admin->id])->sequence(fn ($sequence): array => [ + 'handle' => 'group'.mb_str_pad((string) $sequence->index, 2, '0', STR_PAD_LEFT), + 'name' => 'Builders', + ])->create(); + $popular = $guilds->last(); + $popular->members()->attach($admin, ['joined_at' => now()]); + Guild::factory()->create(['user_id' => $admin->id, 'name' => 'Unrelated', 'handle' => 'unrelated', 'description' => 'Other discussions.']); + + $this->actingAs($admin)->get(route('guild.index', ['q' => 'Builders']))->assertOk()->assertInertia(fn ($page) => $page + ->where('query', 'Builders')->where('guildPage.total', 25)->where('guildPage.last_page', 2) + ->where('guildPage.current_page', 1)->where('guildPage.data', [$popular->id, ...$guilds->take(23)->modelKeys()])); + $this->get(route('guild.index', ['q' => 'Builders', 'page' => 2]))->assertOk()->assertInertia(fn ($page) => $page + ->where('query', 'Builders')->where('guildPage.current_page', 2)->where('guildPage.total', 25) + ->where('guildPage.data', [$guilds[23]->id])); + $this->get(route('guild.index', ['q' => 'Builders', 'page' => 3]))->assertOk()->assertInertia(fn ($page) => $page + ->where('guildPage.data', [])->where('guildPage.total', 25)); +}); + +it('searches guild names handles and descriptions literally without case sensitivity', function (string $term, string $normalized, bool $matches): void { + $admin = User::factory()->create(['handle' => 'admin']); + $guild = Guild::factory()->create(['user_id' => $admin->id, 'handle' => 'rustaceans', 'name' => 'Systems Builders', 'description' => '100% safe_code!']); + Guild::factory()->create(['user_id' => $admin->id, 'handle' => 'other', 'name' => 'Different people', 'description' => '100 percent safeXcode.']); + + $this->actingAs($admin)->get(route('guild.index', ['q' => $term]))->assertOk()->assertInertia(fn ($page) => $page + ->where('query', $normalized)->where('guildPage.data', $matches ? [$guild->id] : [])); +})->with([ + 'name' => ['bUiLdErS', 'bUiLdErS', true], + 'handle' => [' #RuStAcEaNs ', 'RuStAcEaNs', true], + 'description' => ['SAFE_CODE', 'SAFE_CODE', true], + 'literal percent' => ['%', '%', true], + 'literal underscore' => ['_', '_', true], + 'literal escape' => ['!', '!', true], + 'no matches' => ['missing', 'missing', false], +]); + +it('matches Unicode search terms consistently even with C-collated guild columns', function (string $field, string $text, string $term): void { + DB::statement(sprintf('ALTER TABLE guilds ALTER COLUMN %s TYPE text COLLATE "C"', $field)); + $admin = User::factory()->create(['handle' => 'admin']); + $guild = Guild::factory()->create(['user_id' => $admin->id, $field => $text]); + Guild::factory()->create(['user_id' => $admin->id, 'handle' => 'unrelated', 'name' => 'Other', 'description' => 'No match.']); + + $this->actingAs($admin)->get(route('guild.index', ['q' => $term]))->assertOk()->assertInertia(fn ($page) => $page + ->where('guildPage.data', [$guild->id])); +})->with(['handle', 'name', 'description'])->with([ + 'Greek prefix ending in sigma' => ['ΟΣΑ', 'ΟΣ'], + 'lowercase final sigma' => ['κοσμος', 'ΚΟΣΜΟΣ'], + 'uppercase final sigma' => ['ΚΟΣΜΟΣ', 'κοσμος'], + 'accented capital' => ['ÉCOLE', 'école'], +]); + +it('keeps directory results out of membership-only refreshes', function (): void { + $admin = User::factory()->create(['handle' => 'admin']); + $guild = Guild::factory()->create(['user_id' => $admin->id]); + $this->actingAs($admin)->put(route('guild-membership.update', $guild), ['joined' => true])->assertRedirect(); + + $this->get(route('guild.index'), [ + 'X-Inertia-Version' => (string) resolve(HandleInertiaRequests::class)->version(request()), + 'X-Inertia' => 'true', 'X-Inertia-Partial-Component' => 'guild/index', 'X-Inertia-Partial-Data' => 'guilds', + ])->assertOk()->assertJsonPath('props.guilds.0.is_joined', true)->assertJsonMissingPath('props.guildPage'); +}); + +it('includes newly created guild cards when refreshing directory search results', function (): void { + $admin = User::factory()->create(['handle' => 'admin']); + $this->actingAs($admin)->get(route('guild.index'))->assertOk()->assertInertia(fn ($page) => $page->where('guildPage.data', [])); + $guild = Guild::factory()->create(['user_id' => $admin->id, 'handle' => 'rust', 'name' => 'Rust']); + + $this->get(route('guild.index', ['q' => 'rust']), [ + 'X-Inertia-Version' => (string) resolve(HandleInertiaRequests::class)->version(request()), + 'X-Inertia' => 'true', 'X-Inertia-Partial-Component' => 'guild/index', 'X-Inertia-Partial-Data' => 'guildPage,query,guilds', + ])->assertOk()->assertJsonPath('props.guildPage.data', [$guild->id])->assertJsonPath('props.guilds.0.id', $guild->id) + ->assertJsonPath('props.guilds.0.name', 'Rust'); +}); + +it('validates guild directory search and page inputs', function (array $input, string $field): void { + $this->actingAs(User::factory()->create(['handle' => 'admin'])) + ->getJson(route('guild.index', $input))->assertUnprocessable()->assertJsonValidationErrors($field); +})->with([ + 'array query' => [['q' => ['rust']], 'q'], + 'long query' => [['q' => str_repeat('a', 101)], 'q'], + 'zero page' => [['page' => 0], 'page'], + 'fractional page' => [['page' => 1.5], 'page'], + 'large page' => [['page' => 10001], 'page'], +]); + it('guards guild discovery and preferences with the preview flag and validates boolean inputs', function (): void { $guild = Guild::factory()->create(); $this->get(route('guild.index'))->assertRedirectToRoute('home'); diff --git a/tests/Unit/GuildControls.test.tsx b/tests/Unit/GuildControls.test.tsx index 80aa8515c..2a8aaa23c 100644 --- a/tests/Unit/GuildControls.test.tsx +++ b/tests/Unit/GuildControls.test.tsx @@ -8,6 +8,13 @@ import type { Guild } from '../../resources/js/types/guild'; let state: unknown[]; let cursor = 0; const errors = { setError: vi.fn(), clearErrors: vi.fn() }; +vi.doMock('@inertiajs/react', async () => ({ + ...(await vi.importActual('@inertiajs/react')), + usePage: () => ({ props: { guilds: [] } }), +})); +vi.doMock('../../resources/js/layouts/app-layout', () => ({ + default: () => null, +})); vi.doMock('react', () => ({ ...React, useRef: () => ({ current: errors }), @@ -35,6 +42,8 @@ const { GuildDialog } = await import('../../resources/js/components/guild-dialog'); const { GuildPreferences } = await import('../../resources/js/components/guild-preferences'); +const { default: GuildIndex } = + await import('../../resources/js/pages/guild/index'); type Element = ReactElement>; function elements(node: ReactNode): Element[] { if (!React.isValidElement(node)) return []; @@ -65,6 +74,65 @@ beforeEach(() => { vi.clearAllMocks(); }); +test('refreshes card data with directory search and navigation so newly created guilds can render', () => { + const view = elements( + GuildIndex({ + query: 'rust', + guildPage: { data: [], current_page: 2, last_page: 3, total: 50 }, + }), + ); + const form = view.find((element) => element.type === Form)!; + const searches = (form.props.options as { only: string[] }).only; + const navigation = view.filter((element) => + Array.isArray(element.props.only), + ); + + assert.equal(navigation.length, 3); + for (const only of [ + searches, + ...navigation.map((element) => element.props.only as string[]), + ]) { + assert.ok(only.includes('guildPage')); + assert.ok(only.includes('guilds')); + } +}); + +test('keeps the search input mounted while accepting drafts and restored queries', () => { + const input = (query: string) => { + cursor = 0; + const form = elements( + GuildIndex({ + query, + guildPage: { + data: [], + current_page: 1, + last_page: 1, + total: 0, + }, + }), + ).find((element) => element.type === Form)!; + return elements( + (form.props.children as (props: unknown) => ReactNode)({ + processing: false, + errors: {}, + }), + ).find((element) => element.props.name === 'q')!; + }; + const initial = input('rust'); + (initial.props.onChange as (event: unknown) => void)({ + target: { value: 'laravel' }, + }); + assert.equal(input('rust').props.value, 'laravel'); + input('laravel'); + const submitted = input('laravel'); + assert.equal(submitted.key, initial.key); + assert.equal(submitted.props.value, 'laravel'); + input('rust'); + const restored = input('rust'); + assert.equal(restored.key, initial.key); + assert.equal(restored.props.value, 'rust'); +}); + test('cancels invalid guild creation before Inertia sends a request and accepts decorated matches', () => { let view = dialog('devnull'); const name = view.fields.find((element) => element.props.name === 'name')!;