From 788b4a76d8879220c50257b5dd30868db11dfe07 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Thu, 4 Mar 2021 19:46:36 +0300 Subject: [PATCH] feat(v2): auto focus to tab if it is outside viewport (#4209) * Simplify solution * fix typo Co-authored-by: slorber --- .../src/theme/Tabs/index.tsx | 24 +++++++++++++++++++ .../src/theme/Tabs/styles.module.css | 12 ++++++++++ 2 files changed, 36 insertions(+) diff --git a/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx b/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx index fd6f97aba1..9e1a1414ac 100644 --- a/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx +++ b/packages/docusaurus-theme-classic/src/theme/Tabs/index.tsx @@ -14,6 +14,13 @@ import clsx from 'clsx'; import styles from './styles.module.css'; +function isInViewport(element: HTMLElement) { + const {top, left, bottom, right} = element.getBoundingClientRect(); + const {innerHeight, innerWidth} = window; + + return top >= 0 && right <= innerWidth && bottom <= innerHeight && left >= 0; +} + const keys = { left: 37, right: 39, @@ -48,6 +55,23 @@ function Tabs(props: Props): JSX.Element { if (groupId != null) { setTabGroupChoices(groupId, selectedTabValue); + + setTimeout(() => { + if (isInViewport(selectedTab)) { + return; + } + + selectedTab.scrollIntoView({ + block: 'center', + behavior: 'smooth', + }); + + selectedTab.classList.add(styles.tabItemActive); + setTimeout( + () => selectedTab.classList.remove(styles.tabItemActive), + 2000, + ); + }, 150); } }; diff --git a/packages/docusaurus-theme-classic/src/theme/Tabs/styles.module.css b/packages/docusaurus-theme-classic/src/theme/Tabs/styles.module.css index 2b6739bc84..f2e834d3aa 100644 --- a/packages/docusaurus-theme-classic/src/theme/Tabs/styles.module.css +++ b/packages/docusaurus-theme-classic/src/theme/Tabs/styles.module.css @@ -9,3 +9,15 @@ margin-top: 0 !important; } +.tabItemActive { + animation: blink 0.5s ease-in-out 5; +} + +@keyframes blink { + 0% { + background-color: var(--ifm-hover-overlay); + } + 100% { + background-color: rgba(0, 0, 0, 0); + } +}