Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: make canonical tag suggestions keyboard accessible (#7136)

[._.]/ Adam Eivyaf94b4f61d5a
diff --git a/client/src/components/TagPicker.jsx b/client/src/components/TagPicker.jsx
index 2077cf7db2..d3a7721336 100644
--- a/client/src/components/TagPicker.jsx
+++ b/client/src/components/TagPicker.jsx
@@ -13,8 +13,7 @@
* `noir` don't both show as chips before save (matching the server's dedup).
*/
-import { useEffect, useRef, useState } from 'react';
-import useMounted from '../hooks/useMounted';
+import { useEffect, useId, useRef, useState } from 'react';
import { X } from 'lucide-react';
import { listCatalogTags } from '../services/apiCatalog';
import { canonicalTagKey } from '../lib/catalogTypes';
@@ -30,24 +29,26 @@ export default function TagPicker({
const [input, setInput] = useState('');
const [suggestions, setSuggestions] = useState([]);
const [open, setOpen] = useState(false);
- const mountedRef = useMounted();
+ const [activeId, setActiveId] = useState(null);
+ const listId = useId();
+ const inputRef = useRef(null);
+ const activeOptionRef = useRef(null);
- // Debounced autocomplete fetch. A stale generation counter prevents an
- // earlier-but-slower response from clobbering a later one's results.
- const genRef = useRef(0);
+ // Clear old options immediately and ignore responses after input changes.
useEffect(() => {
+ let cancelled = false;
+ setSuggestions([]);
+ setActiveId(null);
const term = input.trim();
- if (!term) { setSuggestions([]); return undefined; }
- const gen = ++genRef.current;
+ if (!term) return undefined;
const timer = setTimeout(() => {
listCatalogTags({ q: term, limit: 8, silent: true })
.then((res) => {
- if (!mountedRef.current || gen !== genRef.current) return;
- setSuggestions(Array.isArray(res?.items) ? res.items : []);
+ if (!cancelled) setSuggestions(Array.isArray(res?.items) ? res.items : []);
})
- .catch(() => { if (mountedRef.current && gen === genRef.current) setSuggestions([]); });
+ .catch(() => { if (!cancelled) setSuggestions([]); });
}, 200);
- return () => clearTimeout(timer);
+ return () => { cancelled = true; clearTimeout(timer); };
}, [input]);
const selectedKeys = new Set(value.map(canonicalTagKey));
@@ -61,6 +62,8 @@ export default function TagPicker({
onChange?.([...value, label]);
setInput('');
setSuggestions([]);
+ setActiveId(null);
+ setOpen(false);
};
const removeTag = (label) => {
@@ -68,21 +71,51 @@ export default function TagPicker({
onChange?.(value.filter((t) => canonicalTagKey(t) !== key));
};
+ // Track option identity, not position, as filtering can remove an option.
+ const visibleSuggestions = suggestions.filter((s) => !selectedKeys.has(canonicalTagKey(s.label)));
+ const expanded = open && value.length < maxTags && visibleSuggestions.length > 0;
+ const activeIndex = expanded ? visibleSuggestions.findIndex((s) => s.id === activeId) : -1;
+
+ useEffect(() => {
+ activeOptionRef.current?.scrollIntoView({ block: 'nearest' });
+ }, [activeId, activeIndex]);
+
+ const pickSuggestion = (label) => {
+ // Assistive clicks can focus an option. Move focus before removing it.
+ inputRef.current?.focus();
+ addTag(label);
+ };
+
const handleKeyDown = (e) => {
- if (e.key === 'Enter' || e.key === ',') {
+ if (e.nativeEvent.isComposing) return;
+ if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && visibleSuggestions.length > 0) {
e.preventDefault();
- if (input.trim()) addTag(input);
+ setOpen(true);
+ const next = e.key === 'ArrowDown'
+ ? (activeIndex + 1) % visibleSuggestions.length
+ : (activeIndex <= 0 ? visibleSuggestions.length : activeIndex) - 1;
+ setActiveId(visibleSuggestions[next].id);
+ } else if (e.key === 'Escape') {
+ if (expanded) { e.preventDefault(); e.stopPropagation(); }
+ setOpen(false);
+ setActiveId(null);
+ } else if (e.key === 'Enter' || e.key === ',') {
+ e.preventDefault();
+ if (e.key === 'Enter' && activeIndex >= 0) pickSuggestion(visibleSuggestions[activeIndex].label);
+ else if (input.trim()) addTag(input);
} else if (e.key === 'Backspace' && !input && value.length > 0) {
- // Backspace on an empty input pops the last chip (common chip-input UX).
removeTag(value[value.length - 1]);
}
};
- // Suggestions not already selected.
- const visibleSuggestions = suggestions.filter((s) => !selectedKeys.has(canonicalTagKey(s.label)));
-
return (
- <div className="relative">
+ <div className="relative" onBlur={(e) => {
+ if (e.currentTarget.contains(e.relatedTarget)) return;
+ // Preserve pending text when leaving for Save/Send, but not on internal focus moves.
+ if (input.trim()) addTag(input);
+ setOpen(false);
+ setActiveId(null);
+ }}>
<div className="flex flex-wrap items-center gap-1.5 px-2 py-1.5 bg-port-bg border border-port-border rounded focus-within:border-port-accent">
{value.map((label) => (
<span
@@ -101,37 +134,38 @@ export default function TagPicker({
</span>
))}
<input
+ ref={inputRef}
id={id}
+ role="combobox"
+ aria-autocomplete="list"
+ aria-expanded={expanded}
+ aria-controls={expanded ? listId : undefined}
+ aria-activedescendant={activeIndex >= 0 ? `${listId}-${activeIndex}` : undefined}
type="text"
value={input}
onChange={(e) => { setInput(e.target.value); setOpen(true); }}
onKeyDown={handleKeyDown}
onFocus={() => setOpen(true)}
- onBlur={() => {
- // Commit a typed-but-uncommitted tag on blur so clicking Save/Send
- // (which blurs this input) doesn't silently drop it. addTag dedups
- // and guards empty/max, so it's a no-op for a blank or duplicate
- // input. Suggestion picks use onMouseDown+preventDefault and never
- // blur, so they can't double-add here.
- if (input.trim()) addTag(input);
- setTimeout(() => { if (mountedRef.current) setOpen(false); }, 120);
- }}
placeholder={value.length >= maxTags ? `Max ${maxTags} tags` : placeholder}
disabled={value.length >= maxTags}
maxLength={maxTagChars}
className="flex-1 min-w-[8ch] bg-transparent text-white text-sm focus:outline-none disabled:opacity-50"
/>
</div>
- {open && visibleSuggestions.length > 0 && (
- <ul className="absolute z-20 mt-1 w-full max-h-48 overflow-y-auto bg-port-card border border-port-border rounded shadow-lg">
- {visibleSuggestions.map((s) => (
- <li key={s.id}>
- {/* onMouseDown (not onClick) fires before the input's onBlur so the
- pick lands before the dropdown closes. */}
+ {expanded && (
+ <ul id={listId} role="listbox" aria-label="Tag suggestions" className="absolute z-20 mt-1 w-full max-h-48 overflow-y-auto bg-port-card border border-port-border rounded shadow-lg">
+ {visibleSuggestions.map((s, index) => (
+ <li key={s.id} role="presentation">
<button
type="button"
- onMouseDown={(e) => { e.preventDefault(); addTag(s.label); }}
- className="w-full text-left px-3 py-1.5 text-sm text-gray-200 hover:bg-port-bg flex items-center gap-2"
+ role="option"
+ ref={activeIndex === index ? activeOptionRef : undefined}
+ id={`${listId}-${index}`}
+ aria-selected={activeIndex === index}
+ tabIndex={-1}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => pickSuggestion(s.label)}
+ className={`w-full text-left px-3 py-1.5 text-sm text-gray-200 hover:bg-port-bg flex items-center gap-2 ${activeIndex === index ? 'bg-port-bg outline outline-port-accent' : ''}`}
>
{s.color && (
<span
diff --git a/client/src/components/TagPicker.test.jsx b/client/src/components/TagPicker.test.jsx
index 05cb380c43..5b66574d27 100644
--- a/client/src/components/TagPicker.test.jsx
+++ b/client/src/components/TagPicker.test.jsx
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, fireEvent } from '@testing-library/react';
+import { useState } from 'react';
+import userEvent from '@testing-library/user-event';
+import { act, render, screen, fireEvent } from '@testing-library/react';
vi.mock('../services/apiCatalog', () => ({
listCatalogTags: vi.fn(),
@@ -26,7 +28,7 @@ describe('TagPicker', () => {
it('commits the input as a tag on Enter', () => {
const onChange = vi.fn();
render(<TagPicker id="tp" value={[]} onChange={onChange} />);
- const input = screen.getByRole('textbox');
+ const input = screen.getByRole('combobox');
fireEvent.change(input, { target: { value: 'Noir' } });
fireEvent.keyDown(input, { key: 'Enter' });
expect(onChange).toHaveBeenCalledWith(['Noir']);
@@ -35,7 +37,7 @@ describe('TagPicker', () => {
it('commits a typed-but-uncommitted tag on blur (so clicking Save does not drop it)', () => {
const onChange = vi.fn();
render(<TagPicker value={[]} onChange={onChange} />);
- const input = screen.getByRole('textbox');
+ const input = screen.getByRole('combobox');
fireEvent.change(input, { target: { value: 'noir' } });
// No Enter/comma — the user clicks elsewhere (e.g. Save), blurring the input.
fireEvent.blur(input);
@@ -45,7 +47,7 @@ describe('TagPicker', () => {
it('does not commit a blank input on blur', () => {
const onChange = vi.fn();
render(<TagPicker value={['noir']} onChange={onChange} />);
- const input = screen.getByRole('textbox');
+ const input = screen.getByRole('combobox');
fireEvent.change(input, { target: { value: ' ' } });
fireEvent.blur(input);
expect(onChange).not.toHaveBeenCalled();
@@ -54,7 +56,7 @@ describe('TagPicker', () => {
it('commits the input as a tag on comma', () => {
const onChange = vi.fn();
render(<TagPicker value={[]} onChange={onChange} />);
- const input = screen.getByRole('textbox');
+ const input = screen.getByRole('combobox');
fireEvent.change(input, { target: { value: 'pulp' } });
fireEvent.keyDown(input, { key: ',' });
expect(onChange).toHaveBeenCalledWith(['pulp']);
@@ -63,7 +65,7 @@ describe('TagPicker', () => {
it('dedups a casing variant of an already-selected tag (no onChange)', () => {
const onChange = vi.fn();
render(<TagPicker value={['Noir']} onChange={onChange} />);
- const input = screen.getByRole('textbox');
+ const input = screen.getByRole('combobox');
fireEvent.change(input, { target: { value: 'NOIR' } });
fireEvent.keyDown(input, { key: 'Enter' });
expect(onChange).not.toHaveBeenCalled();
@@ -72,7 +74,7 @@ describe('TagPicker', () => {
it('pops the last chip on Backspace with empty input', () => {
const onChange = vi.fn();
render(<TagPicker value={['a', 'b']} onChange={onChange} />);
- const input = screen.getByRole('textbox');
+ const input = screen.getByRole('combobox');
fireEvent.keyDown(input, { key: 'Backspace' });
expect(onChange).toHaveBeenCalledWith(['a']);
});
@@ -81,18 +83,113 @@ describe('TagPicker', () => {
listCatalogTags.mockResolvedValue({ items: [{ id: 'cat-tag-noir', label: 'noir', color: null }] });
const onChange = vi.fn();
render(<TagPicker value={[]} onChange={onChange} />);
- const input = screen.getByRole('textbox');
+ const input = screen.getByRole('combobox');
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'no' } });
const suggestion = await screen.findByText('noir');
- fireEvent.mouseDown(suggestion);
+ fireEvent.click(suggestion);
expect(onChange).toHaveBeenCalledWith(['noir']);
});
it('disables the input and shows a max-tags placeholder at the cap', () => {
render(<TagPicker value={['a', 'b']} onChange={vi.fn()} maxTags={2} />);
- const input = screen.getByRole('textbox');
+ const input = screen.getByRole('combobox');
expect(input.disabled).toBe(true);
expect(input.getAttribute('placeholder')).toMatch(/Max 2 tags/);
});
});
+
+function ControlledPicker(props) {
+ const [value, setValue] = useState(props.value ?? []);
+ return <>
+ <label htmlFor="tags">Tags</label>
+ <TagPicker {...props} id="tags" value={value} onChange={(next) => { setValue(next); props.onChange?.(next); }} />
+ <button type="button">Save</button>
+ </>;
+}
+
+describe('TagPicker combobox interactions', () => {
+ const items = [{ id: 'example', label: 'Example tag' }, { id: 'extra', label: 'Extra tag' }];
+
+ it('navigates, dismisses without changing text, and commits the canonical label once', async () => {
+ listCatalogTags.mockResolvedValue({ items });
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(<ControlledPicker onChange={onChange} />);
+ const input = screen.getByRole('combobox');
+ await user.type(input, 'Ex');
+ const list = await screen.findByRole('listbox');
+ expect(input.getAttribute('aria-controls')).toBe(list.id);
+ await user.keyboard('{ArrowUp}');
+ expect(screen.getByRole('option', { name: 'Extra tag' }).getAttribute('aria-selected')).toBe('true');
+ await user.keyboard('{Escape}');
+ expect(input.getAttribute('aria-expanded')).toBe('false');
+ expect(input.hasAttribute('aria-activedescendant')).toBe(false);
+ expect(input.value).toBe('Ex');
+ await user.keyboard('{ArrowDown}');
+ expect(input.getAttribute('aria-activedescendant')).toBe(screen.getByRole('option', { name: 'Example tag' }).id);
+ await user.keyboard('{Enter}');
+ await user.tab();
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(['Example tag']);
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Save' }));
+ });
+
+ it('preserves internal focus moves and supports click without mousedown', async () => {
+ listCatalogTags.mockResolvedValue({ items });
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(<ControlledPicker value={['Existing']} onChange={onChange} />);
+ const input = screen.getByRole('combobox');
+ await user.type(input, 'Ex');
+ const option = await screen.findByRole('option', { name: 'Example tag' });
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Remove tag Existing' }));
+ expect(onChange).not.toHaveBeenCalled();
+ expect(screen.getByRole('listbox')).toBeTruthy();
+ act(() => option.focus());
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.click(option);
+ expect(document.activeElement).toBe(input);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(['Existing', 'Example tag']);
+ });
+
+ it('tabs past suggestions and commits normalized pending input before Save', async () => {
+ listCatalogTags.mockResolvedValue({ items });
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(<ControlledPicker onChange={onChange} maxTagChars={10} />);
+ await user.type(screen.getByRole('combobox'), ' Ex tag ');
+ await screen.findByRole('listbox');
+ await user.tab();
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Save' }));
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(['Ex tag']);
+ expect(screen.queryByRole('listbox')).toBeNull();
+ });
+
+ it('removes active relationships when a parent selects the active option', async () => {
+ listCatalogTags.mockResolvedValue({ items });
+ const view = render(<TagPicker value={[]} onChange={vi.fn()} />);
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, { target: { value: 'Ex' } });
+ await screen.findByRole('listbox');
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ view.rerender(<TagPicker value={['Example tag']} onChange={vi.fn()} />);
+ expect(screen.queryByRole('option', { name: 'Example tag' })).toBeNull();
+ expect(input.hasAttribute('aria-activedescendant')).toBe(false);
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ expect(input.getAttribute('aria-activedescendant')).toBe(screen.getByRole('option', { name: 'Extra tag' }).id);
+ });
+
+ it('rejects an in-flight response after input is cleared', async () => {
+ let resolveLater;
+ listCatalogTags.mockImplementation(() => new Promise((resolve) => { resolveLater = resolve; }));
+ render(<TagPicker value={[]} onChange={vi.fn()} />);
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, { target: { value: 'Ex' } });
+ await vi.waitFor(() => expect(resolveLater).toBeTypeOf('function'));
+ fireEvent.change(input, { target: { value: '' } });
+ await act(async () => resolveLater({ items }));
+ expect(input.getAttribute('aria-expanded')).toBe('false');
+ expect(input.hasAttribute('aria-activedescendant')).toBe(false);
+ });
+});