Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 62 additions & 5 deletions resources/js/components/search-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';
Expand All @@ -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;

Expand All @@ -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.
*/
Expand All @@ -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();
Expand All @@ -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<FoundDeveloper | FoundOrganization>(
developerTerm,
Expand All @@ -125,6 +132,11 @@ export function SearchDialog({
searchCandidates(value, { for: pickerScope }, signal)
: searchDevelopers,
);
const guilds = useDebouncedSearch<GuildBadge>(
guildTerm,
developerDebounce,
(value, signal) => fetchGuilds({ q: value }, signal),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
);
const commits = useDebouncedSearch(
commitTerm,
commitDebounce,
Expand All @@ -140,27 +152,34 @@ 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,
intent === 'topic' ? visibleDevelopers.slice(0, 2) : visibleDevelopers,
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 &&
Expand Down Expand Up @@ -289,7 +308,7 @@ export function SearchDialog({
<DialogPrimitive.Description className="sr-only">
{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.'}
</DialogPrimitive.Description>

<div className="flex items-center gap-3 border-b px-4">
Expand Down Expand Up @@ -543,6 +562,7 @@ function optionsFor(
intent: ReturnType<typeof searchIntent>,
developers: FoundDeveloper[],
organizations: FoundOrganization[],
guilds: GuildBadge[],
commits: Commit[],
commitTerm: string,
needsSignIn: boolean,
Expand All @@ -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) => ({
Expand All @@ -583,13 +608,15 @@ function optionsFor(
...seeAll,
...developerOptions,
...organizationOptions,
...guildOptions,
];
}

return [
...actionOptions,
...developerOptions,
...organizationOptions,
...guildOptions,
...commitOptions,
...seeAll,
];
Expand All @@ -599,6 +626,7 @@ const headings: Record<Option['kind'], ReactNode> = {
action: 'Actions',
developer: 'Developers',
organization: 'Organizations',
guild: 'Guilds',
commit: 'Most relevant commits',
all: null,
recent: (
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -767,6 +799,10 @@ function OptionContent({ option }: { option: Option }): ReactNode {
return <OrganizationResult organization={option.organization} />;
}

if (option.kind === 'guild') {
return <GuildResult guild={option.guild} />;
}

if (option.kind === 'commit') {
return <CommitResult commit={option.commit} />;
}
Expand Down Expand Up @@ -906,6 +942,27 @@ function OrganizationResult({ organization }: { organization: Organization }) {
);
}

function GuildResult({ guild }: { guild: GuildBadge }) {
return (
<>
<GuildIcon guild={guild} className="size-9 rounded-md text-lg" />
<span className="min-w-0 flex-1">
<span className="flex items-baseline gap-1.5">
<span className="truncate font-semibold" title={guild.name}>
{guild.name}
</span>
<span
className="min-w-0 shrink truncate font-mono text-[13px] text-muted-foreground"
title={`#${guild.handle}`}
>
#{guild.handle}
</span>
</span>
</span>
</>
);
}

function CommitResult({ commit }: { commit: Commit }) {
const now = useNow();

Expand Down
18 changes: 18 additions & 0 deletions resources/js/lib/guild-search.ts
Original file line number Diff line number Diff line change
@@ -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();
}
5 changes: 5 additions & 0 deletions resources/js/lib/guilds.ts
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -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}`);
}
Expand Down
19 changes: 19 additions & 0 deletions tests/Unit/GuildSearch.test.ts
Original file line number Diff line number Diff line change
@@ -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), '');
});
57 changes: 57 additions & 0 deletions tests/Unit/SearchDialogComposition.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>();
let hotTopics = [
{ id: 'topic-one', name: 'Database indexes', summary: null },
Expand Down Expand Up @@ -60,6 +61,7 @@ vi.doMock('@inertiajs/react', async () => ({
usePage: () => ({
props: {
auth: { user: userId ? { id: userId } : null },
guildsEnabled,
...(userId ? { hotTopics } : {}),
},
}),
Expand Down Expand Up @@ -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 [
Expand Down