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
61 changes: 57 additions & 4 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,7 @@ 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 { matchGuilds } from '@/lib/guild-search';
import { useKeyLabels } from '@/lib/keyboard';
import type { SearchAction } from '@/lib/search-actions';
import { searchActions } from '@/lib/search-actions';
Expand All @@ -51,6 +54,7 @@ import {
} from '@/lib/utils';
import { show } from '@/routes/user';
import type { Commit, CommitAuthor, Organization, User } from '@/types';
import type { Guild } from '@/types/guild';

const developerDebounce = 120;

Expand All @@ -67,14 +71,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: Guild }
| { 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 +106,7 @@ export function SearchDialog({
pickerScope?: 'remote' | 'share';
onCloseAutoFocus?: (event: Event) => void;
}) {
const { auth, hotTopics = [] } = usePage().props;
const { auth, hotTopics = [], guilds } = usePage().props;
const userId = auth.user?.id ?? null;
const recentSearches = useRecentSearches(userId);
const keys = useKeyLabels();
Expand Down Expand Up @@ -140,13 +145,15 @@ export function SearchDialog({
const visibleOrganizations = developers
.resultsFor(developerTerm)
.filter((found): found is FoundOrganization => 'organization' in found);
const visibleGuilds = isPicking ? [] : matchGuilds(guilds, term);
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,
Expand Down Expand Up @@ -289,7 +296,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 +550,7 @@ function optionsFor(
intent: ReturnType<typeof searchIntent>,
developers: FoundDeveloper[],
organizations: FoundOrganization[],
guilds: Guild[],
commits: Commit[],
commitTerm: string,
needsSignIn: boolean,
Expand All @@ -566,6 +574,11 @@ function optionsFor(
organization,
}),
);
const guildOptions: Option[] = guilds.map((guild) => ({
kind: 'guild',
id: `guild-${guild.id}`,
guild,
}));
const commitOptions: Option[] = groupSearchCommits(commits)
.flatMap(([, group]) => group)
.map((commit) => ({
Expand All @@ -583,13 +596,15 @@ function optionsFor(
...seeAll,
...developerOptions,
...organizationOptions,
...guildOptions,
];
}

return [
...actionOptions,
...developerOptions,
...organizationOptions,
...guildOptions,
...commitOptions,
...seeAll,
];
Expand All @@ -599,6 +614,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 @@ -651,6 +667,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 @@ -764,6 +784,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 @@ -903,6 +927,35 @@ function OrganizationResult({ organization }: { organization: Organization }) {
);
}

function GuildResult({ guild }: { guild: Guild }) {
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>
{guild.description && (
<span
className="block truncate text-sm text-muted-foreground"
title={guild.description}
>
{guild.description}
</span>
)}
</span>
</>
);
}

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

Expand Down
59 changes: 59 additions & 0 deletions resources/js/lib/guild-search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { Guild } from '@/types/guild';

/**
* The guilds whose handle or name matches the term, closest first and then biggest. Every guild is already on the
* page for members, so this filters them in place instead of asking the server. An "@" search is for developers, so
* it finds no guilds; a leading "#" is how guilds are written, so it is ignored.
*/
export function matchGuilds(
guilds: Guild[] | null | undefined,
term: string,
limit = 3,
): Guild[] {
const trimmed = term.trim();

if (!guilds || trimmed.startsWith('@')) {
return [];
}

const needle = trimmed.replace(/^#/u, '').trim().toLowerCase();

if (needle === '') {
return [];
}

return guilds
.map((guild) => ({ guild, rank: rank(guild, needle) }))
.filter(({ rank }) => rank !== null)
.sort(
(a, b) =>
a.rank! - b.rank! ||
b.guild.member_count - a.guild.member_count ||
a.guild.handle.localeCompare(b.guild.handle),
)
.slice(0, limit)
.map(({ guild }) => guild);
}

function rank(guild: Guild, needle: string): number | null {
const handle = guild.handle.toLowerCase();
const name = guild.name.toLowerCase();

if (handle === needle) {
return 0;
}

if (handle.startsWith(needle)) {
return 1;
}

if (name.startsWith(needle)) {
return 2;
}

if (handle.includes(needle) || name.includes(needle)) {
return 3;
}

return null;
}
64 changes: 64 additions & 0 deletions tests/Unit/GuildSearch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { matchGuilds } from '../../resources/js/lib/guild-search.ts';
import type { Guild } from '../../resources/js/types/guild';

function guild(handle: string, name: string, member_count = 1): Guild {
return {
id: handle,
handle,
name,
description: '',
emoji: '#',
icon_url: null,
member_count,
is_joined: false,
is_muted: false,
is_paused: false,
};
}

const guilds = [
guild('laravel', 'Laravel', 40),
guild('php', 'PHP folks', 90),
guild('rust', 'Rustaceans', 10),
guild('larabelles', 'Larabelles', 5),
guild('frontend', 'Frontend in PHP', 200),
];

await test('finds guilds by handle or name, case-insensitively', () => {
assert.deepEqual(
matchGuilds(guilds, 'RUST').map(({ handle }) => handle),
['rust'],
);
assert.deepEqual(
matchGuilds(guilds, 'folks').map(({ handle }) => handle),
['php'],
);
});

await test('puts an exact handle first, then handle and name prefixes, then the biggest', () => {
assert.deepEqual(
matchGuilds(guilds, 'php').map(({ handle }) => handle),
['php', 'frontend'],
);
assert.deepEqual(
matchGuilds(guilds, 'lara').map(({ handle }) => handle),
['laravel', 'larabelles'],
);
});

await test('ignores a leading # and keeps to the limit', () => {
assert.deepEqual(
matchGuilds(guilds, ' #rust ').map(({ handle }) => handle),
['rust'],
);
assert.equal(matchGuilds(guilds, 'a', 2).length, 2);
});

await test('finds nothing for guests, empty terms or developer searches', () => {
assert.deepEqual(matchGuilds(null, 'php'), []);
assert.deepEqual(matchGuilds(guilds, ''), []);
assert.deepEqual(matchGuilds(guilds, '#'), []);
assert.deepEqual(matchGuilds(guilds, '@php'), []);
});