Skip to content

Commit ae26ab6

Browse files
committed
auto scroll to default language
1 parent b52811a commit ae26ab6

File tree

1 file changed

+23
-8
lines changed
  • packages/docusaurus-theme-openapi-docs/src/theme/ApiExplorer/CodeTabs

1 file changed

+23
-8
lines changed

packages/docusaurus-theme-openapi-docs/src/theme/ApiExplorer/CodeTabs/index.tsx

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
* LICENSE file in the root directory of this source tree.
66
* ========================================================================== */
77

8-
import React, { cloneElement, ReactElement } from "react";
8+
import React, { cloneElement, ReactElement, useEffect, useRef } from "react";
99

1010
import {
1111
sanitizeTabsChildren,
@@ -43,18 +43,31 @@ function TabList({
4343
selectValue,
4444
tabValues,
4545
}: CodeTabsProps & ReturnType<typeof useTabs>) {
46-
const tabRefs: (HTMLLIElement | null)[] = [];
46+
const tabRefs = useRef<(HTMLLIElement | null)[]>([]);
4747
const { blockElementScrollPositionUntilNextRender } =
4848
useScrollPositionBlocker();
4949

50+
useEffect(() => {
51+
const activeTab = tabRefs.current.find(
52+
(tab) => tab?.getAttribute("aria-selected") === "true"
53+
);
54+
if (activeTab) {
55+
activeTab.scrollIntoView({
56+
behavior: "auto",
57+
block: "center",
58+
inline: "start",
59+
});
60+
}
61+
}, []);
62+
5063
const handleTabChange = (
5164
event:
5265
| React.FocusEvent<HTMLLIElement>
5366
| React.MouseEvent<HTMLLIElement>
5467
| React.KeyboardEvent<HTMLLIElement>
5568
) => {
5669
const newTab = event.currentTarget;
57-
const newTabIndex = tabRefs.indexOf(newTab);
70+
const newTabIndex = tabRefs.current.indexOf(newTab);
5871
const newTabValue = tabValues[newTabIndex]!.value;
5972

6073
if (newTabValue !== selectedValue) {
@@ -96,13 +109,15 @@ function TabList({
96109
break;
97110
}
98111
case "ArrowRight": {
99-
const nextTab = tabRefs.indexOf(event.currentTarget) + 1;
100-
focusElement = tabRefs[nextTab] ?? tabRefs[0]!;
112+
const nextTab = tabRefs.current.indexOf(event.currentTarget) + 1;
113+
focusElement = tabRefs.current[nextTab] ?? tabRefs.current[0]!;
101114
break;
102115
}
103116
case "ArrowLeft": {
104-
const prevTab = tabRefs.indexOf(event.currentTarget) - 1;
105-
focusElement = tabRefs[prevTab] ?? tabRefs[tabRefs.length - 1]!;
117+
const prevTab = tabRefs.current.indexOf(event.currentTarget) - 1;
118+
focusElement =
119+
tabRefs.current[prevTab] ??
120+
tabRefs.current[tabRefs.current.length - 1]!;
106121
break;
107122
}
108123
default:
@@ -132,7 +147,7 @@ function TabList({
132147
tabIndex={selectedValue === value ? 0 : -1}
133148
aria-selected={selectedValue === value}
134149
key={value}
135-
ref={(tabControl) => tabRefs.push(tabControl)}
150+
ref={(tabControl) => tabRefs.current.push(tabControl)}
136151
onKeyDown={handleKeydown}
137152
onClick={handleTabChange}
138153
{...attributes}

0 commit comments

Comments
 (0)