Skip to content

Commit

Permalink
feat(useActiveDescendant): Changing active descendant scrolls into vi…
Browse files Browse the repository at this point in the history
…ew (#29992)

* feat(useActiveDescendant): Changing active descendant scrolls into view

During the change to the next active descendant, check if it needs to be
scrolled into view and do so.

* changefile
  • Loading branch information
ling1726 authored Dec 5, 2023
1 parent f712c83 commit 8a9fadf
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "minor",
"comment": "feat(useActiveDescendant): Changing active descendant scrolls into view",
"packageName": "@fluentui/react-aria",
"email": "lingfangao@hotmail.com",
"dependentChangeType": "patch"
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,32 @@ export function useActiveDescendant<TActiveParentElement extends HTMLElement, TL
return listboxRef.current?.querySelector<HTMLElement>(`[${ACTIVEDESCENDANT_ATTRIBUTE}]`);
};

const scrollActiveIntoView = (active: HTMLElement) => {
if (!listboxRef.current) {
return;
}

if (listboxRef.current.offsetHeight >= listboxRef.current.scrollHeight) {
return;
}

const { offsetHeight, offsetTop } = active;
const { offsetHeight: parentOffsetHeight, scrollTop } = listboxRef.current;

const isAbove = offsetTop < scrollTop;
const isBelow = offsetTop + offsetHeight > scrollTop + parentOffsetHeight;

const buffer = 2;

if (isAbove) {
listboxRef.current.scrollTo(0, offsetTop - buffer);
}

if (isBelow) {
listboxRef.current.scrollTo(0, offsetTop - parentOffsetHeight + offsetHeight + buffer);
}
};

const setActiveDescendant = (nextActive: HTMLElement | undefined) => {
const active = getActiveDescendant();
if (active) {
Expand All @@ -21,6 +47,7 @@ export function useActiveDescendant<TActiveParentElement extends HTMLElement, TL

if (nextActive) {
nextActive.setAttribute(ACTIVEDESCENDANT_ATTRIBUTE, '');
scrollActiveIntoView(nextActive);
activeParentRef.current?.setAttribute('aria-activedescendant', nextActive.id);
} else {
activeParentRef.current?.removeAttribute('aria-activedescendant');
Expand All @@ -33,6 +60,7 @@ export function useActiveDescendant<TActiveParentElement extends HTMLElement, TL
return;
}

optionWalker.setCurrent(listboxRef.current);
const first = optionWalker.first();
if (first) {
setActiveDescendant(first);
Expand Down Expand Up @@ -65,14 +93,18 @@ export function useActiveDescendant<TActiveParentElement extends HTMLElement, TL
}

optionWalker.setCurrent(active);
if (!matchOption(active)) {
optionWalker.prev();
}

const next = optionWalker.prev();

if (next && next !== listboxRef.current) {
setActiveDescendant(next);
}
},
blur: () => {
if (!listboxRef.current || !activeParentRef.current) {
if (!activeParentRef.current) {
return;
}

Expand Down

0 comments on commit 8a9fadf

Please sign in to comment.