Browse Source

fix: scroll in low network speed

DaiQiangReal 3 years ago
parent
commit
944f5ae848
1 changed files with 60 additions and 56 deletions
  1. 60 56
      src/templates/postTemplate.js

+ 60 - 56
src/templates/postTemplate.js

@@ -45,9 +45,10 @@ import cls from 'classnames';
 import { IconLink, IconFile, IconHelpCircle } from '@douyinfe/semi-icons';
 import { Switch, TabPane, Tabs } from '../../packages/semi-ui';
 import DesignPageAnchor from 'components/DesignPageAnchor';
-import transContent, {getAnotherSideUrl, isHaveUedDocs, isJumpToDesignSite} from './toUEDUtils/toUED';
+import transContent, { getAnotherSideUrl, isHaveUedDocs, isJumpToDesignSite } from './toUEDUtils/toUED';
 import ImageBox from 'components/ImageBox';
 import './toUEDUtils/toUED.scss';
+import { debounce } from 'lodash';
 const Text = ({ lang, letterSpacing, size, lineHeight, text }) => {
     letterSpacing = letterSpacing || 'auto';
     return (
@@ -88,7 +89,7 @@ const SemiComponents = {
         </Tooltip>
     ),
     Notice,
-    CustomH4, 
+    CustomH4,
     CustomH5,
     Checkbox,
     Radio,
@@ -209,23 +210,23 @@ const components = {
     ...Blocks,
     code,
     pre,
-    hr: ({}) => <hr className={'gatsby-hr'} />,
+    hr: ({ }) => <hr className={'gatsby-hr'} />,
     h2: ({ children }) => {
         const intl = useIntl();
         return (
             <h2 className="md markdown gatsby-h2" id={makeAnchorId(children)}>
                 {children}
                 {
-                    children === '设计变量'?
+                    children === '设计变量' ?
                         <Tooltip content={
                             <span>
                                 如何使用可查阅:
                                 <a href='https://semi.design/dsm_manual/zh-CN/web/componentToken' target="_blank">Semi DSM 手册</a>
                             </span>}
                         >
-                            <IconHelpCircle size='large' type="help_circle" style={{ color: ' --semi-color-tertiary-light-default', marginLeft: 4 }}/>
+                            <IconHelpCircle size='large' type="help_circle" style={{ color: ' --semi-color-tertiary-light-default', marginLeft: 4 }} />
                         </Tooltip>
-                    : null
+                        : null
                 }
                 {
                     children === 'Design Tokens' ? <Tooltip content={
@@ -277,7 +278,7 @@ const components = {
         return (
             <h4 className="md markdown gatsby-h4" id={makeAnchorId(children)}>
                 {children}
-                { version && <SemiSiteChangeLogDiff style={{ marginLeft: 16 }} hoverContent={children} /> }
+                {version && <SemiSiteChangeLogDiff style={{ marginLeft: 16 }} hoverContent={children} />}
             </h4>
         );
     },
@@ -308,9 +309,9 @@ const components = {
     li: ({ children }) => {
         if (Array.isArray(children)) {
             children = [...children];
-            
+
             // For convience of adding new feature in different type, we use "if else" group instead of object or map.
-            
+
             if (children[0] === '【Feature】' || children[0] === '【Feat】') {
                 children[0] = <div className={'changelog-title'}>🎁【Feature】</div>;
             }
@@ -389,7 +390,7 @@ const components = {
                         duration: 3,
                         textMaxWidth: 300
                     })) : noop}
-                    >
+                >
                     {props.children}
                 </a>
             );
@@ -423,9 +424,9 @@ const components = {
             })
             return dataSource;
         }
-        
+
         let tableCls = 'md markdown gatsby-table';
-        
+
         try {
             const columns = getColumnsFromFiber(columnsFiber);
             const dataSource = getDataFromFiber(dataFiber);
@@ -449,11 +450,11 @@ const components = {
         //         </div>
         //     );
         // } catch {
-            return (
-                <div className='table-container gatsby-table-container'>
-                    <table className={tableCls}>{children}</table>
-                </div>
-            );
+        return (
+            <div className='table-container gatsby-table-container'>
+                <table className={tableCls}>{children}</table>
+            </div>
+        );
         // }
     },
     ApiType,
@@ -511,7 +512,7 @@ const getCNtype = type => {
 };
 
 export default function Template(args) {
-    const { pageContext, data,location }=args
+    const { pageContext, data, location } = args
     useEffect(() => {
         const { hash } = window.location;
 
@@ -526,19 +527,23 @@ export default function Template(args) {
                 const dom = document.querySelector(id);
                 if (dom) {
                     let timer = null;
-                    const messageHandle = (e)=>{
-                        if(e.data === "oneCodeLoaded"){
+                    const scrollIntoView = debounce(()=>{
+                        window.scroll(0, dom.offsetTop);
+                    },1000)
+                    const messageHandle = (e) => {
+                        if (e.data === "oneCodeLoaded") {
                             // dom.scrollIntoView();
-                            window.scroll(0,dom.offsetTop)
-                            console.log("===>",dom.offsetHeight);
-                            clearTimeout(timer);
-                            timer = setTimeout(()=>{
-                                window.removeEventListener('message',messageHandle);
-                            },5000)
+                            setTimeout(() => {
+                                scrollIntoView();
+                                clearTimeout(timer);
+                                timer = setTimeout(() => {
+                                    window.removeEventListener('message', messageHandle);
+                                }, 5000)
+                            },100)
                         }
                     }
-                    window.addEventListener('message',messageHandle);
-            
+                    window.addEventListener('message', messageHandle);
+
                 }
             }
         } catch (e) {
@@ -605,39 +610,39 @@ export default function Template(args) {
         window.EvaluateSDK && window.EvaluateSDK(appKey, email, options);
     };
 
-    const [iframeAnchorData,setIframeAnchorData]=useState(null);
+    const [iframeAnchorData, setIframeAnchorData] = useState(null);
 
-    useEffect(()=>{
-        const handleMessage=(e)=>{
-            if(e.data==='toRD'){
+    useEffect(() => {
+        const handleMessage = (e) => {
+            if (e.data === 'toRD') {
                 transContent('main');
                 return;
             }
 
             let data;
-            try{
-                data=JSON.parse(e.data);
-            }catch (e){
+            try {
+                data = JSON.parse(e.data);
+            } catch (e) {
                 return;
             }
-            if(data.type==='anchorData'){
+            if (data.type === 'anchorData') {
                 setIframeAnchorData(data.value);
             }
 
         }
-        window.addEventListener('message',handleMessage);
-        return ()=>window.removeEventListener('message',handleMessage);
-    },[]);
+        window.addEventListener('message', handleMessage);
+        return () => window.removeEventListener('message', handleMessage);
+    }, []);
 
 
     const isComponentPage = COMPONENT_LIST.some(item => item.toLowerCase() === enTitle.toLowerCase());
-    const haveUedDoc=isHaveUedDocs(location?.pathname || window.location.pathname);
-    const jumpToDesignSite=isJumpToDesignSite(location?.pathname || window.location.pathname);
-    const [tabValue,setTabValue]=useState('rd');
+    const haveUedDoc = isHaveUedDocs(location?.pathname || window.location.pathname);
+    const jumpToDesignSite = isJumpToDesignSite(location?.pathname || window.location.pathname);
+    const [tabValue, setTabValue] = useState('rd');
     return (
         <div className={calcClassName()}>
             <SEO lang="zh-CN" title={`${current.frontmatter.title} - Semi Design`} />
-            <div className="title-area" style={haveUedDoc?{}:{borderBottom:`1px solid var(--semi-color-border)`}}>
+            <div className="title-area" style={haveUedDoc ? {} : { borderBottom: `1px solid var(--semi-color-border)` }}>
                 <div>
                     {current.frontmatter.draft ? (
                         <Tag className="article-tag" color="orange">
@@ -649,9 +654,8 @@ export default function Template(args) {
                     <div className="header-tinyTitle">
                         {intl.locale === 'zh-CN'
                             ? `${getCNtype(current.fields.type)} · ${enTitle}`
-                            : `${current.fields.type[0].toUpperCase() + current.fields.type.slice(1)} · ${
-                                  current.frontmatter.title
-                              }`}
+                            : `${current.fields.type[0].toUpperCase() + current.fields.type.slice(1)} · ${current.frontmatter.title
+                            }`}
                     </div>
                     <div className="header-title">{intl.locale === 'zh-CN' ? cnTitle : current.frontmatter.title}</div>
                     <div className="article-brief">{current.frontmatter.brief}</div>
@@ -665,32 +669,32 @@ export default function Template(args) {
                     )}
                 </div>
 
-                {current.fields.type !== 'start' && haveUedDoc  &&  (
-                    <Tabs activeKey={tabValue} onTabClick={(key)=>{
-                        if(key==='ued'){
-                            if(jumpToDesignSite){
+                {current.fields.type !== 'start' && haveUedDoc && (
+                    <Tabs activeKey={tabValue} onTabClick={(key) => {
+                        if (key === 'ued') {
+                            if (jumpToDesignSite) {
                                 window.open(getAnotherSideUrl('design'));
-                            }else{
+                            } else {
                                 transContent('design');
                                 setTabValue('ued');
                             }
 
-                        }else{
+                        } else {
                             transContent('rd');
                             setTabValue('rd');
                         }
                     }}>
-                        <TabPane tab={intl.formatMessage({id:'apiDoc'})} itemKey={'rd'}/>
-                        <TabPane tab={intl.formatMessage({id:'designDoc'})} itemKey={'ued'}/>
+                        <TabPane tab={intl.formatMessage({ id: 'apiDoc' })} itemKey={'rd'} />
+                        <TabPane tab={intl.formatMessage({ id: 'designDoc' })} itemKey={'ued'} />
                     </Tabs>
                 )}
             </div>
             <div className={'pageAnchor'}>
-                {(tabValue==='rd' || (["Accessibility "].includes(enTitle))) && (
+                {(tabValue === 'rd' || (["Accessibility "].includes(enTitle))) && (
                     <PageAnchor slug={pageContext.slug} data={current.tableOfContents.items} />
                 )}
                 {
-                    iframeAnchorData && tabValue==='ued' && <DesignPageAnchor data={iframeAnchorData}/>
+                    iframeAnchorData && tabValue === 'ued' && <DesignPageAnchor data={iframeAnchorData} />
                 }
             </div>
             <div className="main-article">