File size: 3,518 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import * as React from 'react';
import { Tabs } from 'antd';
import { createStyles } from 'antd-style';
import classNames from 'classnames';
import throttle from 'lodash/throttle';

import scrollTo from '../../../../components/_util/scrollTo';

const listenerEvents: (keyof WindowEventMap)[] = ['scroll', 'resize'];

const useStyle = createStyles(({ token, css }) => {
  const { boxShadowSecondary, antCls } = token;

  return {
    affixTabs: css`
      position: fixed;
      top: 0;
      inset-inline-end: 0;
      inset-inline-start: 0;
      z-index: 1001;
      padding: 0 40px;
      background: #fff;
      box-shadow: ${boxShadowSecondary};
      transform: translate3d(0, -100%, 0);
      opacity: 0;
      transition:
        opacity ${token.motionDurationSlow},
        transform ${token.motionDurationSlow};

      ${antCls}-tabs {
        max-width: 1208px;
        margin: 0 auto;

        ${antCls}-tabs-nav {
          margin: 0;

          &::before {
            border-bottom-color: transparent;
          }

          ${antCls}-tabs-tab {
            padding: 21px 0;
          }
        }
      }
    `,
    affixTabsFixed: css`
      transform: translate3d(0, 0, 0);
      opacity: 1;
    `,
    span: css`
      text-transform: capitalize;
    `,
  };
});

const VIEW_BALANCE = 32;

const AffixTabs: React.FC = () => {
  const containerRef = React.useRef<HTMLDivElement>(null);
  const idsRef = React.useRef<string[]>([]);
  const [loaded, setLoaded] = React.useState(false);
  const [fixedId, setFixedId] = React.useState<string | undefined>(undefined);

  const {
    styles: { affixTabs, affixTabsFixed, span },
  } = useStyle();

  function scrollToId(id: string) {
    const targetNode = document.getElementById(id);

    if (targetNode) {
      const newTop = targetNode.offsetTop - containerRef.current!.offsetHeight - VIEW_BALANCE;
      scrollTo(newTop);
    }
  }

  React.useEffect(() => {
    const nodeList = document.querySelectorAll<HTMLHeadingElement>('h2[id]');
    idsRef.current = Array.from(nodeList).map<string>(({ id }) => id);
    setLoaded(true);
  }, []);

  React.useEffect(() => {
    const hashId = decodeURIComponent((location.hash || '').slice(1));
    if (hashId) {
      scrollToId(hashId);
    }
  }, [loaded]);

  const onSyncAffix = React.useMemo(() => {
    function doSync() {
      const { scrollY } = window;
      const containerHeight = containerRef.current!.offsetHeight;

      for (let i = idsRef.current.length - 1; i >= 0; i -= 1) {
        const id = idsRef.current[i];
        const current = document.getElementById(id)!;
        const offsetTop = current.offsetTop - containerHeight - VIEW_BALANCE;

        if (offsetTop <= scrollY) {
          setFixedId(id);
          return;
        }
      }

      setFixedId(undefined);
    }

    return throttle(doSync);
  }, []);

  React.useEffect(() => {
    listenerEvents.forEach((event) => window.addEventListener(event, onSyncAffix));
    onSyncAffix();
    return () => {
      listenerEvents.forEach((event) => window.removeEventListener(event, onSyncAffix));
    };
  }, []);

  return (
    <div className={classNames(affixTabs, fixedId && affixTabsFixed)} ref={containerRef}>
      <Tabs
        activeKey={fixedId}
        centered
        size="large"
        onChange={scrollToId}
        items={idsRef.current.map((id) => ({
          key: id,
          label: <span className={span}>{id.replace(/-/g, ' ')}</span>,
        }))}
      />
    </div>
  );
};

export default AffixTabs;