Suggest assignees by alias as you type

Assigning someone meant finding and pasting their DID. Now the input
searches aliases and lists you, the repo's delegates and other known
peers, so a DID is only needed for someone the node has never seen.
This commit is contained in:
Rūdolfs Ošiņš
2026-10-07 14:06:15 +02:00
parent 66dcf55fd3
commit 9ca793f393
12 changed files with 563 additions and 34 deletions
+301 -26
View File
@@ -1,18 +1,41 @@
<script lang="ts">
import type { Author } from "@bindings/cob/Author";
import {
autoUpdate,
computePosition,
flip,
hide,
offset,
shift,
size,
} from "@floating-ui/dom";
import debounce from "lodash/debounce";
import type { AssigneeSuggestion } from "@app/lib/assigneeSuggestions";
import {
matchesAssignee,
rankAssigneeSuggestions,
} from "@app/lib/assigneeSuggestions";
import { parseAssignee } from "@app/lib/inputValidation";
import { invoke } from "@app/lib/invoke";
import { authorForNodeId, publicKeyFromDid } from "@app/lib/utils";
import { cachedSearchAliases, invoke } from "@app/lib/invoke";
import { portal } from "@app/lib/portal";
import {
authorForNodeId,
publicKeyFromDid,
truncateId,
} from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
import NodeId from "@app/components/NodeId.svelte";
import TextInput from "@app/components/TextInput.svelte";
import UserAvatar from "@app/components/UserAvatar.svelte";
interface Props {
allowedToEdit: boolean;
assignees: Author[];
delegates?: Author[];
submitInProgress: boolean;
save: (updatedAssignees: Author[]) => void;
preview?: boolean;
@@ -21,6 +44,7 @@
const {
allowedToEdit = false,
assignees = $bindable(),
delegates = [],
submitInProgress = false,
save,
preview = false,
@@ -35,6 +59,150 @@
let removeToggles: Record<string, boolean> = $state({});
const maxSuggestions = 10;
let focused = $state(false);
let dismissed = $state(false);
let suggestions: AssigneeSuggestion[] = $state([]);
let loadedQuery: string | undefined = $state();
let activeIndex = $state(0);
let anchorEl: HTMLDivElement | undefined = $state();
let floatingEl: HTMLDivElement | undefined = $state();
const rowElements: (HTMLButtonElement | undefined)[] = [];
const searching = $derived(
showInput && focused && !dismissed && parsed.did === undefined,
);
const loaded = $derived(loadedQuery === inputValue.trim());
const open = $derived(searching && loaded && suggestions.length > 0);
const showError = $derived(showInput && validationMessage !== undefined);
const noMatches = $derived(
searching &&
loaded &&
parsed.error === undefined &&
suggestions.length === 0 &&
loadedQuery !== "",
);
const noMatchesMessage = $derived(
updatedAssignees.some(assignee => matchesAssignee(inputValue, assignee))
? "This assignee is already added"
: `No one matches “${inputValue.trim()}”`,
);
const panelVisible = $derived(open || showError || noMatches);
const loadSuggestions = debounce((query: string) => {
void collectSuggestions(query)
.then(collected => {
if (inputValue.trim() !== query) return;
suggestions = collected;
loadedQuery = query;
activeIndex = query === "" ? -1 : 0;
})
.catch(error => {
console.warn("Not able to load assignee suggestions", error);
suggestions = [];
});
}, 80);
$effect(() => {
if (!showInput) {
loadSuggestions.cancel();
suggestions = [];
loadedQuery = undefined;
return;
}
loadSuggestions(inputValue.trim());
});
async function collectSuggestions(
query: string,
): Promise<AssigneeSuggestion[]> {
const aliases = await cachedSearchAliases(query.replace(/^did:key:/, ""));
return rankAssigneeSuggestions({
query,
aliases,
delegates,
assignees: updatedAssignees,
limit: maxSuggestions,
});
}
$effect(() => {
if (!panelVisible || !floatingEl || !anchorEl) return;
const reference = anchorEl;
const floating = floatingEl;
return autoUpdate(reference, floating, () => {
void computePosition(reference, floating, {
placement: "bottom-start",
middleware: [
offset(8),
flip(),
shift({ padding: 8 }),
hide({ padding: 8 }),
size({
padding: 8,
apply({ availableHeight, rects, elements }) {
elements.floating.style.minWidth = `${rects.reference.width}px`;
elements.floating.style.maxHeight = `${Math.min(availableHeight, 384)}px`;
},
}),
],
}).then(({ x, y, middlewareData }) => {
floating.style.left = `${x}px`;
floating.style.top = `${y}px`;
floating.style.visibility = middlewareData.hide?.referenceHidden
? "hidden"
: "visible";
});
});
});
$effect(() => {
if (!open) return;
rowElements[activeIndex]?.scrollIntoView({ block: "nearest" });
});
function handleKeydown(event: KeyboardEvent): boolean {
if ((open || noMatches) && event.key === "Escape") {
dismissed = true;
return true;
}
if (!open) return false;
switch (event.key) {
case "ArrowDown":
activeIndex = (activeIndex + 1) % suggestions.length;
return true;
case "ArrowUp":
activeIndex =
activeIndex <= 0 ? suggestions.length - 1 : activeIndex - 1;
return true;
case "Enter":
case "Tab": {
const suggestion = suggestions[activeIndex];
if (!suggestion) return false;
selectSuggestion(suggestion);
return true;
}
default:
return false;
}
}
function commit(assignee: Author) {
updatedAssignees = [...updatedAssignees, assignee];
inputValue = "";
save($state.snapshot(updatedAssignees));
showInput = false;
}
function selectSuggestion(suggestion: AssigneeSuggestion) {
commit({ did: suggestion.did, alias: suggestion.alias });
}
$effect(() => {
// Reset component state whenever the assignees change in the parent. This
// happens when the issue ID changes for example when the user navigates
@@ -51,13 +219,7 @@
const alias = await invoke<string | null>("alias", {
nid: publicKeyFromDid(assignee),
});
updatedAssignees = [
...updatedAssignees,
{ did: assignee, alias: alias ?? undefined },
];
inputValue = "";
save($state.snapshot(updatedAssignees));
showInput = false;
commit({ did: assignee, alias: alias ?? undefined });
}
}
@@ -77,18 +239,74 @@
flex-wrap: wrap;
gap: 0.5rem;
}
.input-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.suggestions {
position: fixed;
top: 0;
left: 0;
visibility: hidden;
z-index: 400;
display: flex;
flex-direction: column;
max-width: 28rem;
overflow-y: auto;
padding: 0.25rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
box-shadow: var(--elevation-low);
}
.suggestion {
width: 100%;
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.375rem 0.5rem;
border-radius: var(--border-radius-sm);
color: var(--color-text-primary);
font: var(--txt-body-m-regular);
text-align: left;
}
.suggestion.selected {
background-color: var(--color-surface-subtle);
}
.suggestion-primary {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.suggestion-primary.mono {
font-family: var(--font-family-code);
}
.suggestion-secondary {
margin-left: auto;
padding-left: 0.5rem;
color: var(--color-text-secondary);
font: var(--txt-body-s-regular);
font-family: var(--font-family-code);
}
.no-matches,
.validation-message {
padding: 0.375rem 0.5rem;
color: var(--color-text-secondary);
font: var(--txt-body-m-regular);
}
.validation-message {
display: flex;
align-items: center;
gap: 0.25rem;
color: var(--color-feedback-error-text);
position: relative;
margin-top: 0.5rem;
}
.input-row {
display: flex;
align-items: center;
gap: 0.5rem;
.suggestion-badge {
flex-shrink: 0;
padding: 0 0.25rem;
border-radius: var(--border-radius-tiny);
background-color: var(--color-fill-ghost);
color: var(--color-text-secondary);
}
button {
border: 0;
@@ -115,7 +333,10 @@
</Button>
{#each updatedAssignees as assignee}
<span style:color="var(--color-text-secondary)">
<NodeId {...authorForNodeId(assignee)} />
<NodeId
{...authorForNodeId(assignee)}
cardPlacement="top-start"
cardOffset={12} />
</span>
{/each}
</div>
@@ -123,15 +344,68 @@
<div class="row">
{#if showInput}
<div class="input-row">
<div style:flex="1" style:min-width="0">
<div style:flex="1" style:min-width="0" bind:this={anchorEl}>
<TextInput
autofocus
{valid}
disabled={submitInProgress}
placeholder="Assignee DID, e.g. did:key:z6MkwPUeUS2…"
placeholder="Alias or DID, e.g. did:key:z6MkwPUeUS2…"
bind:value={inputValue}
oninput={() => (dismissed = false)}
onFocus={() => {
focused = true;
dismissed = false;
}}
onBlur={() => (focused = false)}
onKeydown={handleKeydown}
onSubmit={addAssignee} />
</div>
{#if panelVisible}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="suggestions"
bind:this={floatingEl}
use:portal
onmousedown={event => event.preventDefault()}>
{#if showError}
<div class="validation-message">
<Icon name="warning" />{validationMessage}
</div>
{/if}
{#each suggestions as suggestion, index (suggestion.did)}
{@const nid = publicKeyFromDid(suggestion.did)}
<button
type="button"
bind:this={rowElements[index]}
class="suggestion"
class:selected={index === activeIndex}
onmouseenter={() => (activeIndex = index)}
onmousedown={event => {
event.preventDefault();
selectSuggestion(suggestion);
}}>
<UserAvatar nodeId={nid} styleWidth="1rem" />
<span
class="suggestion-primary"
class:mono={suggestion.alias === undefined}>
{suggestion.alias ?? truncateId(nid)}
</span>
{#if suggestion.badge}
<span class="suggestion-badge txt-body-s-medium">
{suggestion.badge}
</span>
{/if}
<span class="suggestion-secondary">
{truncateId(nid)}
</span>
</button>
{:else}
{#if noMatches}
<div class="no-matches">{noMatchesMessage}</div>
{/if}
{/each}
</div>
{/if}
<Button
variant="outline"
onclick={() => {
@@ -148,6 +422,7 @@
title={allowedToEdit ? undefined : "Only delegates can add assignees"}
onclick={() => {
inputValue = "";
dismissed = false;
showInput = true;
}}>
<Icon name="avatar-incognito" />
@@ -165,7 +440,10 @@
class="txt-body-m-regular"
onclick={() =>
(removeToggles[assignee.did] = !removeToggles[assignee.did])}>
<NodeId {...authorForNodeId(assignee)} />
<NodeId
{...authorForNodeId(assignee)}
cardPlacement="top-start"
cardOffset={12} />
{#if removeToggles[assignee.did]}
<Icon name="close" onclick={() => removeAssignee(assignee)} />
{/if}
@@ -173,14 +451,11 @@
{/each}
{:else}
{#each updatedAssignees as assignee}
<NodeId {...authorForNodeId(assignee)} />
<NodeId
{...authorForNodeId(assignee)}
cardPlacement="top-start"
cardOffset={12} />
{/each}
{/if}
</div>
{#if !valid && validationMessage}
<div class="validation-message">
<Icon name="warning" />{validationMessage}
</div>
{/if}
{/if}
+1
View File
@@ -101,6 +101,7 @@
submitInProgress={labelSaveInProgress}
save={saveLabels} />
<AssigneeInput
delegates={repo.delegates}
allowedToEdit={isDelegate}
assignees={issue.assignees}
submitInProgress={assigneesSaveInProgress}
+7 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import type { Config } from "@bindings/config/Config";
import type { Placement } from "@floating-ui/dom";
import type { ComponentProps } from "svelte";
import { cachedAlias, cachedConfig, writeToClipboard } from "@app/lib/invoke";
@@ -21,6 +22,8 @@
// Hides the alias; the card still shows it.
avatarOnly?: boolean;
avatarSize?: string;
cardPlacement?: Placement;
cardOffset?: number;
oncardtoggle?: (expanded: boolean) => void;
}
@@ -31,6 +34,8 @@
styleFont = undefined,
avatarOnly = false,
avatarSize = "1rem",
cardPlacement = "bottom-start",
cardOffset = undefined,
oncardtoggle,
}: Props = $props();
@@ -287,7 +292,8 @@
<Popover
popoverPadding="0"
placement="bottom-start"
placement={cardPlacement}
offset={cardOffset}
styleDisplay={inline ? "inline-flex" : undefined}
bind:expanded={cardExpanded}>
{#snippet toggle(_onclick)}
+1
View File
@@ -496,6 +496,7 @@
submitInProgress={labelSaveInProgress}
save={saveLabels} />
<AssigneeInput
delegates={repo.delegates}
allowedToEdit={!!roles.isDelegate(
config.publicKey,
repo.delegates.map(delegate => delegate.did),
+7
View File
@@ -19,6 +19,7 @@
onDismiss?: () => void;
onFocus?: () => void;
onBlur?: () => void;
onKeydown?: (event: KeyboardEvent) => boolean;
onSubmit?: () => void;
onModifierSubmit?: () => void;
oninput?: FormEventHandler<HTMLInputElement>;
@@ -41,6 +42,7 @@
onDismiss,
onFocus,
onBlur,
onKeydown,
onSubmit,
onModifierSubmit,
oninput,
@@ -80,6 +82,11 @@
}
function handleKeydown(event: KeyboardEvent) {
if (!event.isComposing && onKeydown?.(event)) {
event.preventDefault();
return;
}
if (matchesShortcut(event, "submit") && onModifierSubmit) {
event.preventDefault();
onModifierSubmit();
+71
View File
@@ -0,0 +1,71 @@
import type { AliasSuggestion } from "@bindings/cob/AliasSuggestion";
import type { Author } from "@bindings/cob/Author";
export interface AssigneeSuggestion {
did: string;
alias?: string;
badge?: "delegate" | "following" | "you";
}
export function matchesAssignee(
query: string,
{ did, alias }: { did: string; alias?: string },
): boolean {
const needle = query.trim().toLowerCase();
const key = needle.replace(/^did:key:/, "");
return (
did
.replace(/^did:key:/, "")
.toLowerCase()
.startsWith(key) ||
(alias?.toLowerCase().includes(needle) ?? false)
);
}
export function rankAssigneeSuggestions({
query,
aliases,
delegates,
assignees,
limit,
}: {
query: string;
aliases: AliasSuggestion[];
delegates: Author[];
assignees: Author[];
limit: number;
}): AssigneeSuggestion[] {
const assigned = new Set(assignees.map(({ did }) => did));
const seen = new Set<string>();
const matchingDelegates = delegates.filter(delegate =>
matchesAssignee(query, delegate),
);
const rows = [...matchingDelegates, ...aliases].flatMap(author => {
if (assigned.has(author.did) || seen.has(author.did)) return [];
seen.add(author.did);
const match = aliases.find(({ did }) => did === author.did);
const badge: AssigneeSuggestion["badge"] = match?.isSelf
? "you"
: delegates.some(({ did }) => did === author.did)
? "delegate"
: match?.followed
? "following"
: undefined;
return [{ did: author.did, alias: author.alias, badge }];
});
const others = rows.filter(
row => row.badge !== "you" && row.badge !== "delegate",
);
return [
...rows.filter(row => row.badge === "you"),
...rows.filter(row => row.badge === "delegate"),
...others.filter(row => row.alias !== undefined),
...others.filter(row => row.alias === undefined),
].slice(0, limit);
}
+4 -1
View File
@@ -26,9 +26,12 @@ export function parseAssignee(
input: string,
assignees: { did: string }[],
): { did?: string; error?: string } {
input = input.trim();
if (input === "") return {};
const nodeId = parseNodeId(input);
if (!nodeId) return { error: "This is not a valid DID" };
if (!nodeId) {
return input.startsWith("did:") ? { error: "This is not a valid DID" } : {};
}
const did = `${nodeId.prefix}${nodeId.pubkey}`;
if (assignees.some(assignee => assignee.did === did)) {
return { error: "This assignee is already added" };
+1
View File
@@ -204,6 +204,7 @@
labels = newLabels;
}} />
<AssigneeInput
delegates={repo.delegates}
allowedToEdit={true}
{preview}
bind:assignees
+26 -3
View File
@@ -62,8 +62,8 @@ test("an assignee can be added by DID", async ({ page, peer }) => {
await openIssue(page, peer);
await page.getByRole("button", { name: "Add assignees" }).click();
const input = page.getByPlaceholder(/^Assignee DID/);
await input.fill("alice");
const input = page.getByPlaceholder(/^Alias or DID/);
await input.fill("did:key:alice");
await expect(page.getByText("This is not a valid DID")).toBeVisible();
await input.fill(`did:key:${peer.nodeId}`);
@@ -77,7 +77,30 @@ test("an assignee can be added by DID", async ({ page, peer }) => {
await expect(assignees).toBeVisible();
await reload(page);
await assignees.click();
await page.getByPlaceholder(/^Assignee DID/).fill(peer.nodeId);
await page.getByPlaceholder(/^Alias or DID/).fill(peer.nodeId);
await expect(page.getByText("This assignee is already added")).toBeVisible();
});
test("an assignee can be picked by alias", async ({ page, peer }) => {
await openIssue(page, peer);
await page.getByRole("button", { name: "Add assignees" }).click();
const input = page.getByPlaceholder(/^Alias or DID/);
await input.fill("zzz");
await expect(page.getByText("No one matches “zzz”")).toBeVisible();
await input.fill("ali");
const suggestion = page.locator(".suggestion", { hasText: "alice" });
await expect(suggestion).toContainText("you");
await waitForCommand(page, "edit_issue", () => input.press("Enter"));
await expect(input).toBeHidden();
const assignees = page.getByRole("button", {
name: "icon-avatar-incognito Assignees",
exact: true,
});
await reload(page);
await assignees.click();
await page.getByPlaceholder(/^Alias or DID/).fill("alice");
await expect(page.getByText("This assignee is already added")).toBeVisible();
});
+1 -1
View File
@@ -142,7 +142,7 @@ test("an assignee can be added to a patch", async ({ page, peer }) => {
await openPatch(page, peer);
await page.getByRole("button", { name: "Add assignees" }).click();
const input = page.getByPlaceholder(/^Assignee DID/);
const input = page.getByPlaceholder(/^Alias or DID/);
await input.fill(peer.nodeId);
await waitForCommand(page, "edit_patch", () => input.press("Enter"));
+129
View File
@@ -0,0 +1,129 @@
import type { AliasSuggestion } from "@bindings/cob/AliasSuggestion";
import { describe, expect, test } from "vitest";
import {
matchesAssignee,
rankAssigneeSuggestions,
} from "@app/lib/assigneeSuggestions";
const self = "did:key:z6MkSelf";
const delegate = "did:key:z6MkDelegate";
const followed = "did:key:z6MkFollowed";
const known = "did:key:z6MkKnown";
const plain = "did:key:z6MkPlain";
function alias(
did: string,
name: string | undefined,
extra: Partial<AliasSuggestion> = {},
): AliasSuggestion {
return { did, alias: name, followed: false, isSelf: false, ...extra };
}
const aliases = [
alias(plain, undefined),
alias(followed, "fiona", { followed: true }),
alias(known, "kim"),
alias(self, "alice", { isSelf: true }),
];
function rank(
overrides: Partial<Parameters<typeof rankAssigneeSuggestions>[0]> = {},
) {
return rankAssigneeSuggestions({
query: "",
aliases,
delegates: [{ did: delegate, alias: "dave" }],
assignees: [],
limit: 10,
...overrides,
});
}
describe("rankAssigneeSuggestions", () => {
test("orders you, delegates, aliased people, then bare DIDs", () => {
expect(rank().map(({ did }) => did)).toEqual([
self,
delegate,
followed,
known,
plain,
]);
});
test("badges each group", () => {
expect(rank().map(({ badge }) => badge)).toEqual([
"you",
"delegate",
"following",
undefined,
undefined,
]);
});
test("leaves out people who are already assigned", () => {
const dids = rank({ assignees: [{ did: self }, { did: delegate }] }).map(
({ did }) => did,
);
expect(dids).toEqual([followed, known, plain]);
});
test("filters delegates by alias or DID, ignoring case", () => {
const delegates = [{ did: delegate, alias: "dave" }];
const dids = (query: string) =>
rank({ query, aliases: [], delegates }).map(({ did }) => did);
expect(dids("DAV")).toEqual([delegate]);
expect(dids("z6mkdeleg")).toEqual([delegate]);
expect(dids(" did:key:z6MkDeleg ")).toEqual([delegate]);
expect(dids("zzz")).toEqual([]);
});
test("doesn't match delegates on the DID prefix or mid-key", () => {
const delegates = [{ did: delegate, alias: "dave" }];
const dids = (query: string) =>
rank({ query, aliases: [], delegates }).map(({ did }) => did);
expect(dids("k")).toEqual([]);
expect(dids("did:")).toEqual([]);
expect(dids("Delegate")).toEqual([]);
});
test("lists a delegate who is also a search result once", () => {
const result = rank({
aliases: [alias(delegate, "dave", { followed: true })],
});
expect(result).toEqual([
{ did: delegate, alias: "dave", badge: "delegate" },
]);
});
test("marks yourself as you even when you are a delegate", () => {
const result = rank({
delegates: [{ did: self, alias: "alice" }],
});
expect(result[0]).toEqual({ did: self, alias: "alice", badge: "you" });
expect(result.filter(({ did }) => did === self)).toHaveLength(1);
});
test("caps the list at the limit", () => {
expect(rank({ limit: 2 })).toHaveLength(2);
});
});
describe("matchesAssignee", () => {
const author = { did: "did:key:z6MkAlice", alias: "alice" };
test("matches the alias anywhere and the key from its start", () => {
expect(matchesAssignee("lic", author)).toBe(true);
expect(matchesAssignee("z6mka", author)).toBe(true);
expect(matchesAssignee("did:key:z6MkA", author)).toBe(true);
expect(matchesAssignee("Alice", author)).toBe(true);
});
test("rejects other text", () => {
expect(matchesAssignee("bob", author)).toBe(false);
expect(matchesAssignee("key", author)).toBe(false);
});
});
+14 -2
View File
@@ -36,16 +36,28 @@ describe("parseAssignee", () => {
});
});
test("ignores surrounding whitespace", () => {
expect(parseAssignee(` ${nid} `, [])).toEqual({ did: `did:key:${nid}` });
expect(parseAssignee(` did:key:${nid}`, [])).toEqual({
did: `did:key:${nid}`,
});
});
test("rejects an assignee that is already added", () => {
expect(parseAssignee(nid, [{ did: `did:key:${nid}` }])).toEqual({
error: "This assignee is already added",
});
});
test("rejects anything else, but not an empty input", () => {
expect(parseAssignee("alice", [])).toEqual({
test("rejects a malformed DID", () => {
expect(parseAssignee("did:key:alice", [])).toEqual({
error: "This is not a valid DID",
});
});
test("treats other input as a search, not an error", () => {
expect(parseAssignee("alice", [])).toEqual({});
expect(parseAssignee("z6Mkq", [])).toEqual({});
expect(parseAssignee("", [])).toEqual({});
});
});