diff --git a/resources/js/components/search-dialog.tsx b/resources/js/components/search-dialog.tsx index 02d0a114de..45482b5670 100644 --- a/resources/js/components/search-dialog.tsx +++ b/resources/js/components/search-dialog.tsx @@ -15,11 +15,13 @@ import { import type { KeyboardEvent, ReactNode } from 'react'; import { useEffect, useRef, useState } from 'react'; import CommitController from '@/actions/App/Http/Controllers/CommitController'; +import GuildController from '@/actions/App/Http/Controllers/GuildController'; import HeadlineController from '@/actions/App/Http/Controllers/HeadlineController'; import ProfileSearchController from '@/actions/App/Http/Controllers/ProfileSearchController'; import SearchController from '@/actions/App/Http/Controllers/SearchController'; import { AuthorAvatar } from '@/components/author-avatar'; import { GuildSearchHeading } from '@/components/commit-search-results'; +import { GuildIcon } from '@/components/guild-icon'; import { HotTopicContent } from '@/components/hot-topics'; import { OrganizationAvatar } from '@/components/organization-avatar'; import { DialogOverlay, DialogPortal } from '@/components/ui/dialog'; @@ -35,6 +37,8 @@ import { signIn } from '@/lib/auth'; import { searchCandidates } from '@/lib/chat'; import { searchCommits, TooManySearches } from '@/lib/commit-search'; import { groupSearchCommits } from '@/lib/commit-search-results'; +import { guildSearchLimit, guildSearchTerm } from '@/lib/guild-search'; +import { fetchGuilds } from '@/lib/guilds'; import { useKeyLabels } from '@/lib/keyboard'; import type { SearchAction } from '@/lib/search-actions'; import { searchActions } from '@/lib/search-actions'; @@ -51,6 +55,7 @@ import { } from '@/lib/utils'; import { show } from '@/routes/user'; import type { Commit, CommitAuthor, Organization, User } from '@/types'; +import type { GuildBadge } from '@/types/guild'; const developerDebounce = 120; @@ -67,14 +72,15 @@ type Option = | { kind: 'action'; id: string; action: SearchAction } | { kind: 'developer'; id: string; user: User; reason?: string | null } | { kind: 'organization'; id: string; organization: Organization } + | { kind: 'guild'; id: string; guild: GuildBadge } | { kind: 'commit'; id: string; commit: Commit } | { kind: 'all'; id: string; needsSignIn: boolean } | { kind: 'topic'; id: string; term: string; summary: string | null } | { kind: 'recent'; id: string; term: string }; /** - * Searches developers, organizations and commits. Guests only search developers and organizations: each commit search pays for AI, so they're asked to - * sign in for those instead. Picking a developer for a new conversation narrows it to developers, says why + * Searches developers, organizations, guilds and commits. Guests only search developers and organizations: each commit search pays for AI, so they're asked to + * sign in for those instead, and guilds are for members only. Picking a developer for a new conversation narrows it to developers, says why * anyone can't be messaged, and hands the pick back instead of opening their profile. Given `onAction`, it also offers * to write a commit, open an issue or go live when the search names one, above what it found. */ @@ -101,7 +107,7 @@ export function SearchDialog({ pickerScope?: 'remote' | 'share'; onCloseAutoFocus?: (event: Event) => void; }) { - const { auth, hotTopics = [] } = usePage().props; + const { auth, hotTopics = [], guildsEnabled } = usePage().props; const userId = auth.user?.id ?? null; const recentSearches = useRecentSearches(userId); const keys = useKeyLabels(); @@ -116,6 +122,7 @@ export function SearchDialog({ const intent = isPicking ? 'developer' : searchIntent(term); const commitQuery = searchesCommits(intent) ? term : ''; const commitTerm = isMember ? commitQuery : ''; + const guildTerm = isPicking ? '' : guildSearchTerm(term, guildsEnabled); const developers = useDebouncedSearch( developerTerm, @@ -125,6 +132,11 @@ export function SearchDialog({ searchCandidates(value, { for: pickerScope }, signal) : searchDevelopers, ); + const guilds = useDebouncedSearch( + guildTerm, + developerDebounce, + (value, signal) => fetchGuilds({ q: value }, signal), + ); const commits = useDebouncedSearch( commitTerm, commitDebounce, @@ -140,6 +152,9 @@ export function SearchDialog({ const visibleOrganizations = developers .resultsFor(developerTerm) .filter((found): found is FoundOrganization => 'organization' in found); + const visibleGuilds = guilds + .resultsFor(guildTerm) + .slice(0, guildSearchLimit); const visibleCommits = commits.resultsFor(commitTerm); const results = optionsFor( intent, @@ -147,20 +162,24 @@ export function SearchDialog({ intent === 'topic' ? visibleOrganizations.slice(0, 2) : visibleOrganizations, + intent === 'topic' ? visibleGuilds.slice(0, 2) : visibleGuilds, visibleCommits, commitQuery, !isMember, onAction && !isPicking ? searchActions(term, { isLive }) : [], ); - const isLoading = developers.isLoading || commits.isLoading; + const isLoading = + developers.isLoading || guilds.isLoading || commits.isLoading; const hasSearched = developers.hasSearched(developerTerm) && + (guildTerm === '' || guilds.hasSearched(guildTerm)) && (commitTerm === '' || commits.hasSearched(commitTerm)); const isEmpty = term === ''; const isAwaitingDeveloperName = awaitsDeveloperName(term) || (isPicking && isEmpty); const isThrottled = developers.isThrottled(developerTerm) || + guilds.isThrottled(guildTerm) || commits.isThrottled(commitTerm); const foundNothing = !isEmpty && @@ -289,7 +308,7 @@ export function SearchDialog({ {isPicking ? 'Find a developer by name or handle to message.' - : 'Find developers and organizations by name or handle, or commits by what they are about.'} + : 'Find developers, organizations and guilds by name or handle, or commits by what they are about.'}
@@ -543,6 +562,7 @@ function optionsFor( intent: ReturnType, developers: FoundDeveloper[], organizations: FoundOrganization[], + guilds: GuildBadge[], commits: Commit[], commitTerm: string, needsSignIn: boolean, @@ -566,6 +586,11 @@ function optionsFor( organization, }), ); + const guildOptions: Option[] = guilds.map((guild) => ({ + kind: 'guild', + id: `guild-${guild.handle}`, + guild, + })); const commitOptions: Option[] = groupSearchCommits(commits) .flatMap(([, group]) => group) .map((commit) => ({ @@ -583,6 +608,7 @@ function optionsFor( ...seeAll, ...developerOptions, ...organizationOptions, + ...guildOptions, ]; } @@ -590,6 +616,7 @@ function optionsFor( ...actionOptions, ...developerOptions, ...organizationOptions, + ...guildOptions, ...commitOptions, ...seeAll, ]; @@ -599,6 +626,7 @@ const headings: Record = { action: 'Actions', developer: 'Developers', organization: 'Organizations', + guild: 'Guilds', commit: 'Most relevant commits', all: null, recent: ( @@ -654,6 +682,10 @@ function hrefFor( return show(option.organization); } + if (option.kind === 'guild') { + return GuildController.show(option.guild.handle); + } + if (option.kind === 'commit') { return CommitController.show({ profile: option.commit.author, @@ -767,6 +799,10 @@ function OptionContent({ option }: { option: Option }): ReactNode { return ; } + if (option.kind === 'guild') { + return ; + } + if (option.kind === 'commit') { return ; } @@ -906,6 +942,27 @@ function OrganizationResult({ organization }: { organization: Organization }) { ); } +function GuildResult({ guild }: { guild: GuildBadge }) { + return ( + <> + + + + + {guild.name} + + + #{guild.handle} + + + + + ); +} + function CommitResult({ commit }: { commit: Commit }) { const now = useNow(); diff --git a/resources/js/lib/guild-search.ts b/resources/js/lib/guild-search.ts new file mode 100644 index 0000000000..8e29288371 --- /dev/null +++ b/resources/js/lib/guild-search.ts @@ -0,0 +1,18 @@ +/** + * How many guilds the search shows, after the developers and organizations. + */ +export const guildSearchLimit = 3; + +/** + * The term to look guilds up by, or an empty one when the search shouldn't find guilds: for guests and users without + * guilds, and for an "@" search, which is for developers. A leading "#" is how guilds are written, so it is dropped. + */ +export function guildSearchTerm(term: string, guildsEnabled: boolean): string { + const trimmed = term.trim(); + + if (!guildsEnabled || trimmed.startsWith('@')) { + return ''; + } + + return trimmed.replace(/^#/u, '').trim().toLowerCase(); +} diff --git a/resources/js/lib/guilds.ts b/resources/js/lib/guilds.ts index 04c7813509..fab7c9a9a5 100644 --- a/resources/js/lib/guilds.ts +++ b/resources/js/lib/guilds.ts @@ -1,4 +1,5 @@ import { index } from '@/actions/App/Http/Controllers/GuildSuggestionController'; +import { TooManySearches } from '@/lib/commit-search'; import type { GuildBadge } from '@/types/guild'; export async function fetchGuilds( @@ -13,6 +14,10 @@ export async function fetchGuilds( signal, }); + if (response.status === 429) { + throw new TooManySearches(); + } + if (!response.ok) { throw new Error(`Guild lookup failed: ${response.status}`); } diff --git a/tests/Unit/GuildSearch.test.ts b/tests/Unit/GuildSearch.test.ts new file mode 100644 index 0000000000..65d16a627b --- /dev/null +++ b/tests/Unit/GuildSearch.test.ts @@ -0,0 +1,19 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { guildSearchTerm } from '../../resources/js/lib/guild-search.ts'; + +await test('looks guilds up by the trimmed, lowercased term', () => { + assert.equal(guildSearchTerm(' RUST ', true), 'rust'); + assert.equal(guildSearchTerm('php folks', true), 'php folks'); +}); + +await test('ignores a leading #', () => { + assert.equal(guildSearchTerm(' #rust ', true), 'rust'); + assert.equal(guildSearchTerm('#', true), ''); +}); + +await test('finds no guilds for guests, users without guilds or developer searches', () => { + assert.equal(guildSearchTerm('php', false), ''); + assert.equal(guildSearchTerm('@php', true), ''); + assert.equal(guildSearchTerm('', true), ''); +}); diff --git a/tests/Unit/SearchDialogComposition.test.tsx b/tests/Unit/SearchDialogComposition.test.tsx index e11c767f3a..938fdc12fe 100644 --- a/tests/Unit/SearchDialogComposition.test.tsx +++ b/tests/Unit/SearchDialogComposition.test.tsx @@ -9,6 +9,7 @@ let cursor = 0; let effects: Array<() => unknown> | null = null; const visit = vi.fn(); let userId: string | null = null; +let guildsEnabled = false; const storage = new Map(); let hotTopics = [ { id: 'topic-one', name: 'Database indexes', summary: null }, @@ -60,6 +61,7 @@ vi.doMock('@inertiajs/react', async () => ({ usePage: () => ({ props: { auth: { user: userId ? { id: userId } : null }, + guildsEnabled, ...(userId ? { hotTopics } : {}), }, }), @@ -206,6 +208,61 @@ test.each([200, 429])( }, ); +test('says searches are throttled when only the guild lookup is', async () => { + state = []; + storage.clear(); + userId = 'author'; + guildsEnabled = true; + const topics = hotTopics; + hotTopics = []; + effects = []; + vi.useFakeTimers(); + const fetch = vi + .spyOn(globalThis, 'fetch') + .mockImplementation(async (url) => + String(url).includes('/search/guilds') + ? new Response('', { status: 429 }) + : new Response( + JSON.stringify({ users: [], organizations: [] }), + ), + ); + + try { + (input().props.onChange as (event: unknown) => void)({ + target: { value: 'jobs' }, + }); + cursor = 0; + SearchDialog({ open: true, onOpenChange: () => {} }); + effects.forEach((effect) => effect()); + await vi.runAllTimersAsync(); + + cursor = 0; + const settled = SearchDialog({ open: true, onOpenChange: () => {} }); + const statuses = elements(settled) + .filter((element) => element.props.role === 'status') + .map((element) => + React.Children.toArray( + element.props.children as ReactNode, + ).join(''), + ); + assert.ok( + statuses.some((text) => + text.startsWith('error: too many searches'), + ), + ); + assert.equal( + statuses.some((text) => text.startsWith('fatal: nothing matches')), + false, + ); + } finally { + effects = null; + guildsEnabled = false; + hotTopics = topics; + fetch.mockRestore(); + vi.useRealTimers(); + } +}); + test('persists only three distinct searches, evicting the oldest and promoting repeats', () => { storage.clear(); for (const query of [