Skip to content

feat(@clayui/autocomplete): adds loading indicator and live announcer to infinite scrolling #6060

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
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
59 changes: 48 additions & 11 deletions packages/clay-autocomplete/src/Autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
* SPDX-License-Identifier: BSD-3-Clause
*/

import {
__NOT_PUBLIC_COLLECTION,
__NOT_PUBLIC_LIVE_ANNOUNCER,
} from '@clayui/core';
import {Announcer, LiveAnnouncer, __NOT_PUBLIC_COLLECTION} from '@clayui/core';
import DropDown from '@clayui/drop-down';
import {ClayInput as Input} from '@clayui/form';
import LoadingIndicator from '@clayui/loading-indicator';
Expand All @@ -27,10 +24,9 @@ import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';

import {AutocompleteContext} from './Context';

import type {AnnouncerAPI, ICollectionProps} from '@clayui/core';
import type {ICollectionProps} from '@clayui/core';

const {Collection, useCollection, useVirtual} = __NOT_PUBLIC_COLLECTION;
const {LiveAnnouncer} = __NOT_PUBLIC_LIVE_ANNOUNCER;

type ItemProps<T> = {
children: React.ReactElement;
Expand Down Expand Up @@ -110,6 +106,9 @@ export interface IProps<T>
* Messages for autocomplete.
*/
messages?: {
infiniteScrollingListCountPlural?: string;
infiniteScrollingLoaded?: string;
infiniteScrollingLoading?: string;
listCount?: string;
listCountPlural?: string;
loading: string;
Expand Down Expand Up @@ -189,6 +188,9 @@ function hasItem<T extends Record<string, any> | string | number>(
const ESCAPE_REGEXP = /[.*+?^${}()|[\]\\]/g;

const defaultMessages = {
infiniteScrollingListCountPlural: '{0} items loaded.',
infiniteScrollingLoaded: '{0} more items loaded.',
infiniteScrollingLoading: 'Loading more items.',
listCount: '{0} option available.',
listCountPlural: '{0} options available.',
loading: 'Loading...',
Expand Down Expand Up @@ -268,8 +270,6 @@ function AutocompleteInner<T extends Record<string, any> | string | number>(

const ariaControlsId = useId();

const announcerAPI = useRef<AnnouncerAPI>(null);

const isFirst = useIsFirstRender();

const filterFn = useCallback(
Expand Down Expand Up @@ -347,6 +347,7 @@ function AutocompleteInner<T extends Record<string, any> | string | number>(

const virtualizer = useVirtual({
estimateSize: 37,
isLoading,
items: filteredItems,
parentRef: menuRef,
});
Expand Down Expand Up @@ -396,6 +397,11 @@ function AutocompleteInner<T extends Record<string, any> | string | number>(
[value]
),
items: filteredItems,
load: (
<DropDown.Item aria-disabled="true" roleItem="option">
<LoadingIndicator size="sm" />
</DropDown.Item>
),
notFound: (
<DropDown.Item
aria-disabled="true"
Expand Down Expand Up @@ -443,26 +449,57 @@ function AutocompleteInner<T extends Record<string, any> | string | number>(
}
}, [active]);

useEffect(() => {
const lastKey = collection.getLastItem();

if (onLoadMore && !isLoading && activeDescendant === lastKey?.key) {
onLoadMore();
}
}, [activeDescendant]);

const optionCount = collection.getItems().length;
const lastSize = useRef(optionCount);

const itemsSizeRef = useRef(items?.length);

useEffect(() => {
itemsSizeRef.current = items?.length;
}, [items?.length]);

// TODO: Move to Collection in the future and identify a better standard for
// all components.
useEffect(() => {
if (active && isLoading) {
Announcer.announce(messages!.infiniteScrollingLoading!);

return () => {
Announcer.announce(
sub(messages!.infiniteScrollingLoaded!, [
itemsSizeRef.current! - items!.length!,
])
);
};
}
}, [active, messages!.infiniteScrollingLoading, isLoading]);

useEffect(() => {
// Only announces the number of options available when the menu is open
// if there is no item with focus, with the exception of Voice Over
// which does not include the message.
if (
announcerAPI.current &&
active &&
(!activeDescendant ||
isAppleDevice() ||
optionCount !== lastSize.current)
) {
const optionCount = collection.getItems().length;

announcerAPI.current.announce(
Announcer.announce(
sub(
optionCount === 1
? messages!.listCount!
: onLoadMore
? messages!.infiniteScrollingListCountPlural!
: messages!.listCountPlural!,
[optionCount]
)
Expand Down Expand Up @@ -490,7 +527,7 @@ function AutocompleteInner<T extends Record<string, any> | string | number>(

return (
<>
<LiveAnnouncer ref={announcerAPI} />
<LiveAnnouncer />

<As
{...otherProps}
Expand Down
91 changes: 86 additions & 5 deletions packages/clay-autocomplete/stories/Autocomplete.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@
*/

import {Text, TextHighlight} from '@clayui/core';
import {useResource} from '@clayui/data-provider';
import {
FetchPolicy,
NetworkStatus,
} from '@clayui/data-provider/src/useResource';
import {FetchPolicy, NetworkStatus, useResource} from '@clayui/data-provider';
import DropDown from '@clayui/drop-down';
import Layout from '@clayui/layout';
import {FocusScope, useDebounce} from '@clayui/shared';
Expand Down Expand Up @@ -288,6 +284,69 @@ export const AsyncFilter = () => {
);
};

export const InfiniteScroller = () => {
const [value, setValue] = useState('');

const [networkStatus, setNetworkStatus] = useState<NetworkStatus>(
NetworkStatus.Unused
);
const {loadMore, resource} = useResource({
fetch: async (link, options) => {
const result = await fetch(link, options);
const json = await result.json();

return {
cursor: json.info.next,
items: json.results,
};
},
fetchPolicy: FetchPolicy.CacheFirst,
link: 'https://rickandmortyapi.com/api/character/',
onNetworkStatusChange: setNetworkStatus,
variables: {name: value},
});

return (
<div className="row">
<div className="col-md-5">
<div className="sheet">
<div className="form-group">
<label
htmlFor="clay-autocomplete-1"
id="clay-autocomplete-label-1"
>
Name
</label>
<ClayAutocomplete
aria-labelledby="clay-autocomplete-label-1"
id="clay-autocomplete-1"
items={(resource as Array<RickandMorty>) ?? []}
loadingState={networkStatus}
messages={{
listCount: '{0} option available.',
listCountPlural: '{0} options available.',
loading: 'Loading...',
notFound: 'No results found',
}}
onChange={setValue}
onItemsChange={() => {}}
onLoadMore={loadMore}
placeholder="Enter a name"
value={value}
>
{(item) => (
<ClayAutocomplete.Item key={item.id}>
{item.name}
</ClayAutocomplete.Item>
)}
</ClayAutocomplete>
</div>
</div>
</div>
</div>
);
};

export const Keyboard = () => {
const inputRef = useRef<HTMLInputElement | null>(null);
const [value, setValue] = useState('');
Expand All @@ -305,6 +364,17 @@ export const Keyboard = () => {
<div className="row">
<div className="col-md-5">
<div className="sheet">
<div className="alert alert-danger">
This Autocomplete implementation uses the deprecated
implementation, we recommend using the{' '}
<a
href="https://clayui.com/docs/components/autocomplete"
target="__blank"
>
new pattern
</a>
.
</div>
<div className="form-group">
<label>Numbers (one-five)</label>
<FocusScope>
Expand Down Expand Up @@ -362,6 +432,17 @@ export const AsyncData = () => {
<div className="row">
<div className="col-md-5">
<div className="sheet">
<div className="alert alert-danger">
This Autocomplete implementation uses the deprecated
implementation, we recommend using the{' '}
<a
href="https://clayui.com/docs/components/autocomplete"
target="__blank"
>
new pattern
</a>
.
</div>
<div className="form-group">
<label>Name</label>
<ClayAutocomplete>
Expand Down
2 changes: 1 addition & 1 deletion packages/clay-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"@clayui/provider": "^3.128.0",
"@clayui/shared": "^3.136.0",
"@clayui/table": "^3.111.0",
"@tanstack/react-virtual": "3.0.0-beta.54",
"@tanstack/react-virtual": "^3.13.8",
"aria-hidden": "^1.2.2",
"classnames": "^2.2.6",
"fuzzy": "^0.1.3",
Expand Down
3 changes: 1 addition & 2 deletions packages/clay-core/src/collection/Collection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ export function Collection<
const target = event.target as HTMLElement;

if (
target.scrollTop + target.clientHeight >=
target.scrollHeight - 40 &&
target.scrollTop + target.clientHeight >= target.scrollHeight &&
!isLoading
) {
onLoadMore!();
Expand Down
5 changes: 5 additions & 0 deletions packages/clay-core/src/collection/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ export type Props<P, K> = {
*/
notFound?: JSX.Element;

/**
* Renders an element when it is loading more items.
*/
load?: JSX.Element;

/**
* Defines which key should be used as the item identifier.
*/
Expand Down
Loading
Loading