← All proposals

Global search

A net-new component, GlobalSearch: one input that shows results in groups.

Net-new componentOpen in Storybook

proposals/GlobalSearch/GlobalSearch.tsx737 lines · View on GitHub
import {
	Icon,
	type PDSIcon,
	Spinner,
	Tag,
	useKeyboardShortcut,
} from '@pantheon-systems/pds-toolkit-react';
import {
	type ComponentPropsWithoutRef,
	type KeyboardEvent,
	type ReactNode,
	useEffect,
	useMemo,
	useRef,
	useState,
} from 'react';

import { Badge } from '../Badge/Badge';

import './global-search.css';

/**
 * One result row.
 */
export interface GlobalSearchOption {
	/**
	 * Label for the row's action, shown at the end of the active row (for example "Jump to").
	 */
	actionLabel?: string;
	/**
	 * A second line under the label (for example a domain).
	 */
	description?: string;
	/**
	 * Icon at the start of the row.
	 */
	iconName?: PDSIcon;
	/**
	 * Unique id of the option.
	 */
	id: string;
	/**
	 * Quiet text beside the label (for example the workspace a result belongs to).
	 */
	inlineText?: string;
	/**
	 * Main text of the row. The part that matches the query is highlighted.
	 */
	label: string;
	/**
	 * Show the action label on every row of the list, not only the active one.
	 */
	showActionAlways?: boolean;
	/**
	 * Tags after the label. Short text, for example "Framework: WordPress 6.9".
	 */
	tags?: string[];
}

/**
 * A heading and its rows. Groups with no options are not rendered.
 */
export interface GlobalSearchGroup {
	/**
	 * Heading of the group.
	 */
	heading: string;
	/**
	 * Unique id of the group.
	 */
	id: string;
	/**
	 * Rows in the group.
	 */
	options: GlobalSearchOption[];
}

export interface GlobalSearchTranslationStrings {
	/**
	 * Accessible name of the dialog (`variant='dialog'`).
	 */
	dialogLabel?: string;
	/**
	 * Name of the key shown in the field while the results are open.
	 */
	escapeKey: string;
	/**
	 * Words after the arrow keys in the dialog footer (`variant='dialog'`).
	 */
	navigateHint?: string;
	/**
	 * Accessible name of the results list.
	 */
	resultsLabel: string;
	/**
	 * Words after the Enter key in the dialog footer (`variant='dialog'`).
	 */
	selectHint?: string;
}

export type GlobalSearchVariant = 'dialog' | 'inline';

/**
 * Prop types for GlobalSearch
 */
export interface GlobalSearchProps extends Omit<
	ComponentPropsWithoutRef<'div'>,
	'defaultValue'
> {
	/**
	 * Additional class names
	 */
	className?: string;
	/**
	 * Id of the option that starts active. Use it to show the keyboard state.
	 */
	defaultActiveId?: string;
	/**
	 * Initial query when the component is uncontrolled.
	 */
	defaultQuery?: string;
	/**
	 * Message shown in place of the results when the search failed.
	 */
	errorText?: string;
	/**
	 * Result groups, in display order. Pass the recent searches and suggestions when the query is
	 * empty, matches when it is not. The component does not search; it shows what it is given.
	 */
	groups?: GlobalSearchGroup[];
	/**
	 * Dim the page behind the open results.
	 * @default true
	 */
	hasBackdrop?: boolean;
	/**
	 * Id of the input. The list and the options derive their ids from it.
	 */
	id: string;
	/**
	 * Whether a search is running. With no results yet it shows `loadingText`; with results on
	 * screen they stay until the next ones arrive.
	 */
	isLoading?: boolean;
	/**
	 * Control whether the results are open. Leave unset to let the component open on focus and
	 * close on Esc, Tab and outside clicks.
	 */
	isOpen?: boolean;
	/**
	 * Accessible name of the input. Visually hidden.
	 */
	label: string;
	/**
	 * Text shown next to the spinner while the first results load.
	 */
	loadingText?: string;
	/**
	 * Message shown above the groups when nothing matched. The screen decides when: pass it only
	 * for a query with no matches. Groups (for example an assistant) can still follow it.
	 */
	noResultsText?: string;
	/**
	 * Called when the results open or close.
	 */
	onOpenChange?: (isOpen: boolean) => void;
	/**
	 * Called when a row is clicked or chosen with Enter. The consumer navigates or acts: the
	 * component is router-agnostic.
	 */
	onOptionSelect?: (option: GlobalSearchOption) => void;
	/**
	 * Called when the text changes.
	 */
	onQueryChange?: (query: string) => void;
	/**
	 * Called when the send button is pressed, or Enter is pressed with no row active.
	 */
	onQuerySubmit?: (query: string) => void;
	/**
	 * Placeholder text.
	 */
	placeholder?: string;
	/**
	 * Current text. Pass it with `onQueryChange` to control the input.
	 */
	query?: string;
	/**
	 * Key that opens the dialog from anywhere on the page, for example `/`. Shown in the trigger and
	 * bound with `useKeyboardShortcut`. Only used with `variant='dialog'`.
	 */
	shortcut?: string;
	/**
	 * Message read out by screen readers when the results change (for example "5 results available").
	 */
	statusText?: string;
	/**
	 * Accessible name of the send button. The send button shows with `variant='inline'` only.
	 */
	submitLabel?: string;
	/**
	 * Translatable strings.
	 */
	translationStrings?: GlobalSearchTranslationStrings;
	/**
	 * `inline`: the field stays where it is and its results open under it as one box. `dialog`: a
	 * compact trigger (for a navigation bar) opens a dialog over itself, with its own field.
	 * @default 'inline'
	 */
	variant?: GlobalSearchVariant;
}

const defaultTranslationStrings: GlobalSearchTranslationStrings = {
	dialogLabel: 'Search',
	escapeKey: 'esc',
	navigateHint: 'to navigate',
	resultsLabel: 'Search results',
	selectHint: 'to select',
};

const escapeForRegExp = (value: string) =>
	value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

/** Wraps the part of `text` that matches the query so it can be styled. */
const highlight = (
	text: string,
	query: string,
	matchClass: string,
): ReactNode => {
	if (!query) return text;
	return text
		.split(new RegExp(`(${escapeForRegExp(query)})`, 'gi'))
		.map((part, index) =>
			part.toLowerCase() === query.toLowerCase() ? (
				// The parts are positional, so the index is the key.
				<span className={matchClass} key={index}>
					{part}
				</span>
			) : (
				// The parts are positional, so the index is the key.
				<span key={index}>{part}</span>
			),
		);
};

/**
 * GlobalSearch UI component. One input that searches across many kinds of things (recent
 * searches, sites, environments, workspaces, accounts, an assistant) and shows the results in
 * groups. While open, the field and the results read as one expanding box.
 *
 * Focus stays in the input: the results are a listbox reached through `aria-activedescendant`.
 * Arrow keys move through the rows, Enter chooses one, Esc closes. The component holds no data
 * and no content: the screen passes the groups, the labels and what each row does.
 */
export const GlobalSearch = ({
	className,
	defaultActiveId,
	defaultQuery = '',
	errorText,
	groups = [],
	hasBackdrop = true,
	id,
	isLoading = false,
	isOpen,
	label,
	loadingText,
	noResultsText,
	onOpenChange,
	onOptionSelect,
	onQueryChange,
	onQuerySubmit,
	placeholder,
	query,
	shortcut,
	statusText,
	submitLabel,
	translationStrings: translationStringsProp,
	variant = 'inline',
	...props
}: GlobalSearchProps) => {
	// Set up classes.
	const baseClass = 'pds-global-search';
	const listboxId = `${id}-listbox`;

	const isDialog = variant === 'dialog';
	const translationStrings = {
		...defaultTranslationStrings,
		...translationStringsProp,
	};

	const rootRef = useRef<HTMLDivElement>(null);
	const inputRef = useRef<HTMLInputElement>(null);
	const triggerRef = useRef<HTMLButtonElement>(null);
	const scrollToActiveRef = useRef(false);
	const [internalQuery, setInternalQuery] = useState(defaultQuery);
	const [internalOpen, setInternalOpen] = useState(false);
	const [rawActiveId, setRawActiveId] = useState(defaultActiveId);

	const queryValue = query ?? internalQuery;
	const trimmedQuery = queryValue.trim();
	const open = isOpen ?? internalOpen;

	const visibleGroups = useMemo(
		() => groups.filter((group) => group.options.length > 0),
		[groups],
	);
	const options = useMemo(
		() => visibleGroups.flatMap((group) => group.options),
		[visibleGroups],
	);
	// The active row only counts while it is still in the list (results change under it).
	const activeId = options.some((option) => option.id === rawActiveId)
		? rawActiveId
		: undefined;

	const hasGroups = visibleGroups.length > 0;
	const showLoading = isLoading && !hasGroups && !errorText;
	const showNoResults = !!noResultsText && !isLoading && !errorText;
	const hasPanel =
		open && (hasGroups || showLoading || !!errorText || showNoResults);

	const setOpen = (next: boolean) => {
		if (isOpen === undefined) setInternalOpen(next);
		onOpenChange?.(next);
		// Closing the dialog puts focus back on the trigger that opened it.
		if (!next && isDialog) triggerRef.current?.focus();
	};

	// The shortcut opens the dialog from anywhere. The hook skips form fields and pauses while a
	// PDS overlay is open.
	useKeyboardShortcut(
		shortcut ?? '/',
		() => {
			setOpen(true);
		},
		{ enabled: isDialog && !!shortcut, preventDefault: true },
		[isDialog, shortcut, isOpen],
	);

	// Opening the dialog moves focus into its field.
	useEffect(() => {
		if (isDialog && open) inputRef.current?.focus();
	}, [isDialog, open]);

	// Without a visible label the send button needs its own name.
	useEffect(() => {
		if (!isDialog && !submitLabel && process.env.NODE_ENV !== 'production') {
			console.warn(
				'[GlobalSearch] `submitLabel` is needed with variant="inline": the send button has no accessible name.',
			);
		}
	}, [isDialog, submitLabel]);

	const setQuery = (next: string) => {
		if (query === undefined) setInternalQuery(next);
		setRawActiveId(undefined);
		onQueryChange?.(next);
	};

	// Keep the arrow-key row in view inside the scrolling list. Only keyboard moves scroll: a
	// row that starts active, or one under the mouse, must not move the list or the page.
	useEffect(() => {
		if (!activeId || !scrollToActiveRef.current) return;
		scrollToActiveRef.current = false;
		document
			.getElementById(`${listboxId}-${activeId}`)
			?.scrollIntoView({ block: 'nearest' });
	}, [activeId, listboxId]);

	// Clicking anywhere outside the component closes the results.
	useEffect(() => {
		if (!open) return undefined;
		const closeOnOutsideMouseDown = (event: MouseEvent) => {
			const target = event.target as Element;
			// The backdrop sits inside the root, but a click on it is a click outside.
			const isOutside =
				!rootRef.current?.contains(target) ||
				target.classList.contains(`${baseClass}__backdrop`);
			if (isOutside) {
				if (isOpen === undefined) setInternalOpen(false);
				onOpenChange?.(false);
				if (isDialog) triggerRef.current?.focus();
			}
		};
		document.addEventListener('mousedown', closeOnOutsideMouseDown);
		return () => {
			document.removeEventListener('mousedown', closeOnOutsideMouseDown);
		};
	}, [open, isOpen, onOpenChange, isDialog]);

	const choose = (option: GlobalSearchOption) => {
		onOptionSelect?.(option);
	};

	const move = (step: 1 | -1) => {
		if (options.length === 0) return;
		const index = options.findIndex((option) => option.id === activeId);
		let next: number;
		if (index === -1) {
			next = step === 1 ? 0 : options.length - 1;
		} else {
			next = (index + step + options.length) % options.length;
		}
		scrollToActiveRef.current = true;
		setRawActiveId(options[next].id);
	};

	const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
		if (event.key === 'ArrowDown') {
			event.preventDefault();
			setOpen(true);
			move(1);
		} else if (event.key === 'ArrowUp') {
			event.preventDefault();
			setOpen(true);
			move(-1);
		} else if (event.key === 'Enter') {
			event.preventDefault();
			const active = options.find((option) => option.id === activeId);
			if (active) {
				choose(active);
			} else {
				onQuerySubmit?.(queryValue);
			}
		} else if (event.key === 'Escape' || event.key === 'Tab') {
			setOpen(false);
		}
	};

	const input = (
		<input
			aria-activedescendant={activeId ? `${listboxId}-${activeId}` : undefined}
			aria-autocomplete='list'
			aria-controls={hasPanel && hasGroups ? listboxId : undefined}
			aria-expanded={hasPanel}
			autoComplete='off'
			className={`pds-copy-s ${baseClass}__input`}
			id={id}
			ref={inputRef}
			onChange={(event) => {
				setQuery(event.target.value);
				setOpen(true);
			}}
			onClick={() => {
				setOpen(true);
			}}
			onFocus={() => {
				setOpen(true);
			}}
			onKeyDown={handleKeyDown}
			placeholder={placeholder}
			role='combobox'
			type='text'
			value={queryValue}
		/>
	);

	const panel = hasPanel && (
		<div className={`${baseClass}__panel`}>
			{showLoading && (
				<p className={`${baseClass}__message`}>
					<Spinner isInline size='s' />
					<span>{loadingText}</span>
				</p>
			)}
			{errorText && (
				<p className={`${baseClass}__message`} role='alert'>
					<Icon iconName='diamondExclamation' size='s' />
					<span>{errorText}</span>
				</p>
			)}
			{showNoResults && (
				<p className={`pds-copy-s ${baseClass}__message`}>{noResultsText}</p>
			)}
			{hasGroups && (
				<div
					aria-busy={isLoading}
					aria-label={translationStrings.resultsLabel}
					id={listboxId}
					role='listbox'
				>
					{visibleGroups.map((group) => (
						<div
							aria-labelledby={`${listboxId}-${group.id}`}
							className={`${baseClass}__group`}
							key={group.id}
							role='group'
						>
							<p
								className={`pds-copy-xs ${baseClass}__heading`}
								id={`${listboxId}-${group.id}`}
							>
								<span className={`${baseClass}__heading-text`}>
									{group.heading}
								</span>
							</p>
							{group.options.map((option) => {
								const isActive = option.id === activeId;
								return (
									// Keyboard use goes through the input (aria-activedescendant), so options
									// take no tab stop or key handlers; mouse down is cancelled to keep focus.
									<div
										aria-selected={isActive}
										className={`pds-copy-s ${baseClass}__option${
											isActive ? ` ${baseClass}__option--active` : ''
										}`}
										id={`${listboxId}-${option.id}`}
										key={option.id}
										onClick={() => {
											choose(option);
										}}
										onMouseDown={(event) => {
											event.preventDefault();
										}}
										onMouseMove={() => {
											setRawActiveId(option.id);
										}}
										role='option'
									>
										{option.iconName && (
											<Icon
												className={`${baseClass}__icon`}
												iconName={option.iconName}
												size='s'
											/>
										)}
										<div className={`${baseClass}__body`}>
											<div className={`${baseClass}__line`}>
												<span className={`${baseClass}__label`}>
													{highlight(
														option.label,
														trimmedQuery,
														`${baseClass}__match`,
													)}
												</span>
												{option.inlineText && (
													<span className={`pds-copy-xs ${baseClass}__inline`}>
														{option.inlineText}
													</span>
												)}
												{option.tags?.map((tag) => (
													<Tag
														key={tag}
														size='xs'
														tagColor='slate'
														tagLabel={tag}
														truncationLength={0}
													/>
												))}
											</div>
											{option.description && (
												<span
													className={`pds-copy-xs ${baseClass}__description`}
												>
													{highlight(
														option.description,
														trimmedQuery,
														`${baseClass}__match`,
													)}
												</span>
											)}
										</div>
										{option.actionLabel && (
											<span
												className={`pds-copy-2xs ${baseClass}__action${
													isActive || option.showActionAlways
														? ` ${baseClass}__action--shown`
														: ''
												}`}
											>
												{option.actionLabel}
											</span>
										)}
									</div>
								);
							})}
						</div>
					))}
				</div>
			)}
		</div>
	);

	const liveRegion = (
		<span aria-live='polite' className='visually-hidden' role='status'>
			{open && statusText ? statusText : ''}
		</span>
	);

	const rootClasses = [
		baseClass,
		isDialog ? `${baseClass}--dialog` : null,
		open ? `${baseClass}--open` : null,
		hasPanel && !isDialog ? `${baseClass}--expanded` : null,
		className ?? null,
	]
		.filter(Boolean)
		.join(' ');

	const backdrop = (
		<div aria-hidden='true' className={`${baseClass}__backdrop`} />
	);

	// The dialog variant: a compact trigger, and a dialog that opens over it with its own field.
	if (isDialog) {
		return (
			<div className={rootClasses} ref={rootRef} {...props}>
				<button
					aria-expanded={open}
					aria-haspopup='dialog'
					className={`pds-copy-s ${baseClass}__trigger`}
					onClick={() => {
						setOpen(true);
					}}
					ref={triggerRef}
					type='button'
				>
					<Icon
						className={`${baseClass}__trigger-icon`}
						iconName='magnifyingGlass'
						size='s'
					/>
					<span className={`${baseClass}__trigger-text`}>
						{placeholder ?? label}
					</span>
					{shortcut && (
						<Badge as='kbd' color='silver-muted' label={shortcut} size='xs' />
					)}
				</button>
				{open && (
					<>
						{backdrop}
						<div
							aria-label={translationStrings.dialogLabel}
							aria-modal='true'
							className={`${baseClass}__dialog`}
							role='dialog'
						>
							<div className={`${baseClass}__field`}>
								<Icon
									className={`${baseClass}__field-icon`}
									iconName='magnifyingGlass'
									size='s'
								/>
								<label className='visually-hidden' htmlFor={id}>
									{label}
								</label>
								{input}
								<Badge
									as='kbd'
									className={`${baseClass}__escape`}
									color='silver-muted'
									label={translationStrings.escapeKey}
									size='xs'
								/>
							</div>
							{panel}
							<div aria-hidden='true' className={`${baseClass}__footer`}>
								<Badge as='kbd' color='silver-muted' label='↑' size='xs' />
								<Badge as='kbd' color='silver-muted' label='↓' size='xs' />
								<span className='pds-copy-xs'>
									{translationStrings.navigateHint}
								</span>
								<Badge as='kbd' color='silver-muted' label='↵' size='xs' />
								<span className='pds-copy-xs'>
									{translationStrings.selectHint}
								</span>
							</div>
							{liveRegion}
						</div>
					</>
				)}
			</div>
		);
	}

	// The inline variant: the field stays put and its results open under it as one box.
	return (
		<div className={rootClasses} ref={rootRef} {...props}>
			{open && hasBackdrop && backdrop}
			<div className={`${baseClass}__box`}>
				<div className={`${baseClass}__field`}>
					<label className='visually-hidden' htmlFor={id}>
						{label}
					</label>
					{input}
					{open && (
						<Badge
							as='kbd'
							className={`${baseClass}__escape`}
							color='silver-muted'
							label={translationStrings.escapeKey}
							size='xs'
						/>
					)}
					<button
						aria-label={submitLabel}
						className={`${baseClass}__submit`}
						onClick={() => onQuerySubmit?.(queryValue)}
						title={submitLabel}
						type='button'
					>
						<svg
							aria-hidden='true'
							fill='none'
							height='16'
							viewBox='0 0 16 16'
							width='16'
						>
							<line
								stroke='currentColor'
								strokeLinecap='round'
								strokeWidth='1.5'
								x1='8'
								x2='8'
								y1='13'
								y2='3'
							/>
							<polyline
								fill='none'
								points='4,7 8,3 12,7'
								stroke='currentColor'
								strokeLinecap='round'
								strokeLinejoin='round'
								strokeWidth='1.5'
							/>
						</svg>
					</button>
				</div>

				{panel}
				{liveRegion}
			</div>
		</div>
	);
};