You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@devlake.apache.org by li...@apache.org on 2022/12/12 08:50:04 UTC

[incubator-devlake] branch main updated: refactor(config-ui): the offline page (#3908)

This is an automated email from the ASF dual-hosted git repository.

likyh pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-devlake.git


The following commit(s) were added to refs/heads/main by this push:
     new 1cc52cbe8 refactor(config-ui): the offline page (#3908)
1cc52cbe8 is described below

commit 1cc52cbe80aa75e3dae261203905d566eab65001
Author: 青湛 <0x...@gmail.com>
AuthorDate: Mon Dec 12 16:49:59 2022 +0800

    refactor(config-ui): the offline page (#3908)
    
    * feat(config-ui): add new component card
    
    * refactor(config-ui): the offline page
---
 config-ui/src/App.js                               |   2 +-
 .../src/components/{index.ts => card/index.tsx}    |  18 +-
 config-ui/src/components/index.ts                  |   1 +
 config-ui/src/pages/index.ts                       |   1 +
 config-ui/src/pages/{index.ts => offline/api.ts}   |   6 +-
 config-ui/src/pages/offline/index.jsx              | 400 ---------------------
 config-ui/src/pages/offline/index.tsx              | 110 ++++++
 .../index.ts => pages/offline/styled.ts}           |  48 ++-
 config-ui/src/pages/offline/use-offline.ts         |  69 ++++
 9 files changed, 234 insertions(+), 421 deletions(-)

diff --git a/config-ui/src/App.js b/config-ui/src/App.js
index bded3e797..dcdf6584d 100644
--- a/config-ui/src/App.js
+++ b/config-ui/src/App.js
@@ -37,6 +37,7 @@ import useDatabaseMigrations from '@/hooks/useDatabaseMigrations'
 
 import { BaseLayout } from '@/layouts'
 import {
+  Offline,
   ProjectHomePage,
   ProjectDetailPage,
   CreateBlueprintPage,
@@ -47,7 +48,6 @@ import Integration from '@/pages/configure/integration/index'
 import ManageIntegration from '@/pages/configure/integration/manage'
 import AddConnection from '@/pages/configure/connections/AddConnection'
 import ConfigureConnection from '@/pages/configure/connections/ConfigureConnection'
-import Offline from '@/pages/offline/index'
 import Blueprints from '@/pages/blueprints/index'
 import CreateBlueprint from '@/pages/blueprints/create-blueprint'
 import BlueprintDetail from '@/pages/blueprints/blueprint-detail'
diff --git a/config-ui/src/components/index.ts b/config-ui/src/components/card/index.tsx
similarity index 77%
copy from config-ui/src/components/index.ts
copy to config-ui/src/components/card/index.tsx
index 77de69cc2..fdaf67567 100644
--- a/config-ui/src/components/index.ts
+++ b/config-ui/src/components/card/index.tsx
@@ -13,14 +13,14 @@
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- *
  */
 
-export * from './loading'
-export * from './divider'
-export * from './page-header'
-export * from './selector'
-export * from './dialog'
-export * from './table'
-export * from './toast2'
-export * from './logo'
+import styled from 'styled-components'
+
+export const Card = styled.div`
+  padding: 24px;
+  background-color: #fff;
+  box-shadow: 0px 2.4px 4.8px -0.8px rgba(0, 0, 0, 0.1),
+    0px 1.6px 8px rgba(0, 0, 0, 0.07);
+  border-radius: 8px;
+`
diff --git a/config-ui/src/components/index.ts b/config-ui/src/components/index.ts
index 77de69cc2..90cf931d2 100644
--- a/config-ui/src/components/index.ts
+++ b/config-ui/src/components/index.ts
@@ -24,3 +24,4 @@ export * from './dialog'
 export * from './table'
 export * from './toast2'
 export * from './logo'
+export * from './card'
diff --git a/config-ui/src/pages/index.ts b/config-ui/src/pages/index.ts
index 89e794d51..ebdab55d4 100644
--- a/config-ui/src/pages/index.ts
+++ b/config-ui/src/pages/index.ts
@@ -16,6 +16,7 @@
  *
  */
 
+export * from './offline'
 export * from './project'
 export * from './blueprint'
 export * from './connections'
diff --git a/config-ui/src/pages/index.ts b/config-ui/src/pages/offline/api.ts
similarity index 89%
copy from config-ui/src/pages/index.ts
copy to config-ui/src/pages/offline/api.ts
index 89e794d51..c18ed2044 100644
--- a/config-ui/src/pages/index.ts
+++ b/config-ui/src/pages/offline/api.ts
@@ -16,6 +16,6 @@
  *
  */
 
-export * from './project'
-export * from './blueprint'
-export * from './connections'
+import request from '@/components/utils/request'
+
+export const ping = () => request('/ping')
diff --git a/config-ui/src/pages/offline/index.jsx b/config-ui/src/pages/offline/index.jsx
deleted file mode 100644
index f69ecac66..000000000
--- a/config-ui/src/pages/offline/index.jsx
+++ /dev/null
@@ -1,400 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-import React, {
-  Fragment,
-  useEffect,
-  useCallback,
-  useState,
-  useRef
-} from 'react'
-import { CSSTransition } from 'react-transition-group'
-import { useHistory } from 'react-router-dom'
-import { ToastNotification } from '@/components/Toast'
-import { DEVLAKE_ENDPOINT } from '@/utils/config'
-import request from '@/utils/request'
-import {
-  H2,
-  Button,
-  Icon,
-  Intent,
-  Card,
-  Elevation,
-  Tag,
-  Tooltip,
-  Position,
-  Spinner,
-  Colors
-} from '@blueprintjs/core'
-import { ReactComponent as Logo } from '@/images/devlake-logo.svg'
-import { ReactComponent as LogoText } from '@/images/devlake-textmark.svg'
-import '@/styles/offline.scss'
-
-const Offline = (props) => {
-  const { pollTimer = 7000, retryLimit = 100, endpointUrl = null } = props
-  const history = useHistory()
-  const testInterval = useRef()
-  const retryCount = useRef()
-
-  const [apiEndpointUrl, setApiEndpointUrl] = useState(
-    `${DEVLAKE_ENDPOINT}/ping`
-  )
-  const [isOffline, setIsOffline] = useState(true)
-  const [testResponse, setTestResponse] = useState({})
-  const [testStatus, setTestStatus] = useState(504)
-  const [cardReady, setCardReady] = useState(false)
-  // eslint-disable-next-line no-unused-vars
-  const [aborted, setAborted] = useState(false)
-
-  const testEndpoint = useCallback(async () => {
-    console.log('>> OFFLINE MODE -  TESTING ENDPOINT!', apiEndpointUrl)
-    retryCount.current++
-    try {
-      setCardReady(false)
-      const t = await request.get(apiEndpointUrl)
-      setTestResponse(t.data)
-      setTestStatus(() => t.status ?? 504)
-    } catch (e) {
-      setTestResponse((tR) => {
-        return {
-          ...tR,
-          data: [],
-          error: e.response.data,
-          statusCode: e.response.status
-        }
-      })
-      setTestStatus(504)
-    }
-  }, [apiEndpointUrl])
-
-  useEffect(() => {
-    console.log('>> OFFLINE MODE -  ENDPOINT TEST RESPONSE = ', testResponse)
-    if (testResponse?.error) {
-      ToastNotification.clear()
-      ToastNotification.show({
-        message: testResponse.error ?? 'Network Error 504 (Gateway Timeout)',
-        intent: 'danger',
-        icon: 'error'
-      })
-    }
-    setTimeout(() => {
-      setCardReady(true)
-    }, 0)
-  }, [testResponse])
-
-  useEffect(() => {
-    console.log('>> OFFLINE MODE - CURRENT API HTTP/STATUS: ', testStatus)
-    setIsOffline(testStatus !== 200)
-    if (testStatus === 200) {
-      clearInterval(testInterval.current)
-      ToastNotification.clear()
-      ToastNotification.show({
-        message: 'DevLake API Online',
-        intent: 'danger',
-        icon: 'tick-circle'
-      })
-      console.log('>> OFFLINE MODE - API RESTORED, TERMINATING POLLING!!!')
-    }
-  }, [testStatus])
-
-  useEffect(() => {
-    console.log('>> OFFLINE MODE -  OFFLINE CHECK?', isOffline)
-  }, [isOffline])
-
-  useEffect(() => {
-    testEndpoint()
-  }, [testEndpoint])
-
-  useEffect(() => {
-    testInterval.current = setInterval(() => {
-      setTestStatus(504)
-      testEndpoint()
-      // retryCount.current++
-    }, pollTimer)
-
-    return () => {
-      clearInterval(testInterval.current)
-      setCardReady(false)
-      setAborted(false)
-    }
-  }, [pollTimer, testEndpoint])
-
-  useEffect(() => {
-    console.log('>> OFFLINE MODE (MOUNTED) - ENDPOINT URL ...', endpointUrl)
-    retryCount.current = 1
-    setAborted(false)
-    setApiEndpointUrl((url) =>
-      endpointUrl !== null && endpointUrl !== url
-        ? endpointUrl
-        : `${DEVLAKE_ENDPOINT}/ping`
-    )
-  }, [endpointUrl])
-
-  useEffect(() => {
-    if (retryCount.current >= retryLimit) {
-      console.log(
-        '>> OFFLINE MODE - RETRY LIMIT EXCEEDED, TERMINATING POLLING!!!'
-      )
-      clearInterval(testInterval.current)
-      setAborted(true)
-      ToastNotification.clear()
-      ToastNotification.show({
-        message: 'Retry Limit Exceeded, please refresh your browser.',
-        intent: 'danger',
-        icon: 'error'
-      })
-    }
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-  }, [retryCount.current, retryLimit])
-
-  return (
-    <>
-      {
-        <div
-          className={`offline-wrapper ${
-            isOffline ? 'is-offline' : 'is-online'
-          }`}
-        >
-          <div
-            style={{
-              maxWidth: '500px',
-              margin: '0 auto',
-              display: 'flex',
-              height: '100%',
-              flexDirection: 'column'
-            }}
-          >
-            <div style={{ margin: 'auto auto', padding: '16px' }}>
-              <div className='devlake-logo' style={{ margin: 0 }}>
-                <Logo width={48} height={48} className='logo' />
-                <LogoText width={100} height={13} className='logo-textmark' />
-              </div>
-              <CSSTransition
-                in={cardReady}
-                timeout={900}
-                classNames='offline-card'
-              >
-                <Card elevation={Elevation.THREE}>
-                  <span
-                    style={{
-                      display: 'block',
-                      position: 'absolute',
-                      right: 0,
-                      top: 0,
-                      margin: '10px'
-                    }}
-                  >
-                    {isOffline ? (
-                      <Spinner size={16} />
-                    ) : (
-                      <Icon icon='tick-circle' size={16} color={Colors.GRAY4} />
-                    )}
-                  </span>
-                  <div style={{ textAlign: 'center' }}>
-                    {isOffline ? (
-                      <img
-                        style={{
-                          margin: '0px auto 10px auto',
-                          width: '54px',
-                          height: '54px',
-                          maxWidth: '5 4px'
-                        }}
-                        width={54}
-                        height={54}
-                        // eslint-disable-next-line max-len
-                        src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOxAAADsQBlSsOGwAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAACAASURBVHic7d13fFbl+cfxz0lCEkLYQ0CmbAggGFCZ4mQ5EVBxD6y492qV1tnaat1a60+rVSvVWveoe7UiLhQXCoLKRhDZI8/vjzu0MSQkeXLOc53xfb9e5wVCeJ6vaJ77Ove57+sGERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERE [...]
-                      />
-                    ) : (
-                      <img
-                        style={{
-                          margin: '0px auto 10px auto',
-                          width: '64px',
-                          height: '64px',
-                          maxWidth: '64px'
-                        }}
-                        width={64}
-                        height={64}
-                        // eslint-disable-next-line max-len
-                        src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOxAAADsQBlSsOGwAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAACAASURBVHic7N15eFTV/Qbw99yZyUaSmUkChGCU1V3c0KqsVVFQ1GqrgoobbuBeF6z+Wm3FraJVCyrudasr4lIFFRUIiCKKu4Dse5LZspJk5p7fH0CLisks995z75338zw+rXLnnBeJud+c+73nAERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERER [...]
-                      />
-                    )}
-                  </div>
-                  <H2>
-                    DevLake API&nbsp;
-                    <CSSTransition
-                      in={cardReady}
-                      timeout={300}
-                      classNames='offline-card-os'
-                    >
-                      {isOffline ? (
-                        <strong
-                          style={{
-                            padding: '0 3px',
-                            fontWeight: '900',
-                            backgroundColor: 'rgba(220,50,50,0.2)',
-                            color: 'rgb(212, 69, 36)'
-                          }}
-                        >
-                          Offline
-                        </strong>
-                      ) : (
-                        <strong
-                          style={{
-                            padding: '0 3px',
-                            fontWeight: '900',
-                            backgroundColor: 'rgba(50,221,80,0.2)',
-                            color: 'rgb(36, 212, 72)'
-                          }}
-                        >
-                          Online
-                        </strong>
-                      )}
-                    </CSSTransition>
-                  </H2>
-                  <Tag>
-                    <code>DEVLAKE_ENDPOINT: {DEVLAKE_ENDPOINT}</code>
-                  </Tag>
-                  {isOffline ? (
-                    <>
-                      <p style={{ fontSize: '16px', color: '#222222' }}>
-                        Please wait for the&nbsp;
-                        <strong>Lake API</strong> to start before accessing the{' '}
-                        <strong>Configuration Interface</strong>.
-                      </p>
-                      <Tooltip
-                        intent={Intent.PRIMARY}
-                        className='offline-continue-tooltip'
-                        targetClassName='offline-continue-tooltip-target'
-                        content={
-                          <>
-                            <Icon size={14} icon='warning-sign' /> Proceed with
-                            caution.
-                          </>
-                        }
-                        position={Position.RIGHT}
-                        style={{ cursor: 'pointer' }}
-                      >
-                        <Button
-                          intent={Intent.PRIMARY}
-                          icon='warning-sign'
-                          style={{ fontWeight: 700 }}
-                          onClick={() => history.replace('/')}
-                        >
-                          Continue
-                        </Button>
-                      </Tooltip>
-                      <Button
-                        icon='refresh'
-                        text='Refresh'
-                        minimal
-                        style={{ marginLeft: '5px' }}
-                        disabled={!cardReady}
-                        onClick={() => testEndpoint()}
-                      />
-                    </>
-                  ) : (
-                    <>
-                      <p style={{ fontSize: '16px', color: '#222222' }}>
-                        Connectivity to the Lake API service was successful.
-                      </p>
-                      <Button
-                        icon='cog'
-                        intent={Intent.PRIMARY}
-                        onClick={() => history.replace('/')}
-                      >
-                        Open Dashboard
-                      </Button>
-                      <a
-                        href='https://github.com/apache/incubator-devlake/blob/main/README.md'
-                        target='_blank'
-                        rel='noreferrer'
-                        style={{ marginLeft: '5px' }}
-                        className='bp3-button bp3-minimal'
-                      >
-                        <Icon
-                          icon='help'
-                          size={16}
-                          style={{ marginRight: '5px' }}
-                        />
-                        Read Documentation
-                      </a>
-                    </>
-                  )}
-                </Card>
-              </CSSTransition>
-              <div
-                style={{
-                  margin: '10px 5px 10px 5px',
-                  display: 'flex',
-                  justifyContnt: 'flex-start'
-                }}
-              >
-                <div style={{ color: 'rgba(33, 33, 33, 0.6)' }}>
-                  {isOffline ? (
-                    <>
-                      <strong style={{ fontWeight: 900, letterSpacing: '2px' }}>
-                        OFFLINE &middot;&nbsp;
-                      </strong>
-                      <a
-                        href='https://github.com/apache/incubator-devlake/blob/main/README.md'
-                        target='_blank'
-                        rel='noreferrer'
-                        style={{ fontWeight: 400, letterSpacing: 0 }}
-                      >
-                        Documentation on{' '}
-                        <span style={{ fontWeight: 800 }}>GitHub</span>
-                      </a>
-                      <br /> Please verify network connectivity if the problem
-                      persists.
-                      <br />
-                      <strong style={{ fontWeight: 600, letterSpacing: '0px' }}>
-                        {retryCount.current} failed attempt(s).
-                      </strong>
-                    </>
-                  ) : (
-                    <>
-                      <strong style={{ fontWeight: 900, letterSpacing: '2px' }}>
-                        ONLINE &middot;&nbsp;
-                      </strong>
-                      <a
-                        href='/integrations'
-                        style={{
-                          color: 'rgba(50,50,50,0.6)',
-                          textDecoration: 'underline',
-                          fontWeight: 400,
-                          letterSpacing: 0
-                        }}
-                      >
-                        Proceed with{' '}
-                        <span style={{ fontWeight: 800 }}>
-                          Data Connections
-                        </span>
-                      </a>
-                      <br /> Lake API connection restored.
-                    </>
-                  )}
-                </div>
-              </div>
-            </div>
-          </div>
-        </div>
-      }
-    </>
-  )
-}
-
-export default Offline
diff --git a/config-ui/src/pages/offline/index.tsx b/config-ui/src/pages/offline/index.tsx
new file mode 100644
index 000000000..221618f6a
--- /dev/null
+++ b/config-ui/src/pages/offline/index.tsx
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import React, { useMemo } from 'react'
+import { useHistory } from 'react-router-dom'
+import {
+  Icon,
+  Tag,
+  ButtonGroup,
+  Button,
+  Intent,
+  Colors,
+  IconName
+} from '@blueprintjs/core'
+
+import { Logo, Card, Loading } from '@/components'
+import { DEVLAKE_ENDPOINT } from '@/utils/config'
+
+import { useOffline } from './use-offline'
+import * as S from './styled'
+
+export const Offline = () => {
+  const history = useHistory()
+  const { loading, offline, onRefresh } = useOffline()
+
+  const [icon, color, text] = useMemo(
+    () => [
+      offline ? 'offline' : 'endorsed',
+      offline ? Colors.RED3 : Colors.GREEN3,
+      offline ? 'Offline' : 'Online'
+    ],
+    [offline]
+  )
+
+  return (
+    <S.Wrapper>
+      <Logo />
+      <Card className='inner'>
+        {loading ? (
+          <Loading />
+        ) : (
+          <>
+            <h2>
+              <Icon icon={icon as IconName} color={color} size={30} />
+              <span>DevLake API</span>
+              <strong style={{ color }}>{text}</strong>
+            </h2>
+            <div className='path'>
+              <Tag>DEVLAKE_ENDPOINT: {DEVLAKE_ENDPOINT}</Tag>
+            </div>
+            {offline ? (
+              <>
+                <p>
+                  Please wait for the&nbsp;
+                  <strong>Lake API</strong> to start before accessing the{' '}
+                  <strong>Configuration Interface</strong>.
+                </p>
+                <ButtonGroup>
+                  <Button
+                    icon='refresh'
+                    intent={Intent.PRIMARY}
+                    text='Refresh'
+                    onClick={onRefresh}
+                  />
+                </ButtonGroup>
+              </>
+            ) : (
+              <>
+                <p>Connectivity to the Lake API service was successful.</p>
+                <ButtonGroup>
+                  <Button
+                    intent={Intent.PRIMARY}
+                    text='Continue'
+                    onClick={() => history.push('/')}
+                  />
+                  <Button
+                    icon='help'
+                    text='Read Documentation'
+                    onClick={() =>
+                      window.open(
+                        'https://github.com/apache/incubator-devlake/blob/main/README.md',
+                        '_blank',
+                        'noopener,noreferrer'
+                      )
+                    }
+                  />
+                </ButtonGroup>
+              </>
+            )}
+          </>
+        )}
+      </Card>
+    </S.Wrapper>
+  )
+}
diff --git a/config-ui/src/components/index.ts b/config-ui/src/pages/offline/styled.ts
similarity index 56%
copy from config-ui/src/components/index.ts
copy to config-ui/src/pages/offline/styled.ts
index 77de69cc2..b6d2724db 100644
--- a/config-ui/src/components/index.ts
+++ b/config-ui/src/pages/offline/styled.ts
@@ -16,11 +16,43 @@
  *
  */
 
-export * from './loading'
-export * from './divider'
-export * from './page-header'
-export * from './selector'
-export * from './dialog'
-export * from './table'
-export * from './toast2'
-export * from './logo'
+import styled from 'styled-components'
+
+export const Wrapper = styled.div`
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  padding-top: 100px;
+  height: 100vh;
+  background-color: #f9f9fa;
+  box-sizing: border-box;
+
+  .inner {
+    margin: 32px auto 0;
+    width: 640px;
+    text-align: center;
+
+    h2 {
+      display: flex;
+      align-items: center;
+      justify-content: center;
+      margin: 0;
+
+      .bp4-icon {
+        margin-right: 4px;
+      }
+
+      strong {
+        margin-left: 4px;
+      }
+    }
+
+    .path {
+      margin: 8px 0;
+    }
+
+    p {
+      margin: 0 0 16px 0;
+    }
+  }
+`
diff --git a/config-ui/src/pages/offline/use-offline.ts b/config-ui/src/pages/offline/use-offline.ts
new file mode 100644
index 000000000..56f86ed79
--- /dev/null
+++ b/config-ui/src/pages/offline/use-offline.ts
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { useState, useEffect, useMemo, useRef } from 'react'
+
+import * as API from './api'
+
+const pollTimer = 10000
+const retryLimit = 10
+
+export const useOffline = () => {
+  const [loading, setLoading] = useState(false)
+  const [offline, setOffline] = useState(true)
+
+  const timer = useRef<any>()
+  const retryCount = useRef<number>(0)
+
+  const ping = async (auto = true) => {
+    setLoading(true)
+    try {
+      await API.ping()
+      setOffline(false)
+    } catch {
+      setOffline(true)
+    } finally {
+      if (auto) {
+        retryCount.current += 1
+      }
+      setLoading(false)
+    }
+  }
+
+  useEffect(() => {
+    timer.current = setInterval(() => {
+      ping()
+    }, pollTimer)
+    return () => clearInterval(timer.current)
+  }, [])
+
+  useEffect(() => {
+    if (retryCount.current >= retryLimit || !offline) {
+      clearInterval(timer.current)
+    }
+  }, [retryCount.current, offline])
+
+  return useMemo(
+    () => ({
+      loading,
+      offline,
+      onRefresh: () => ping(false)
+    }),
+    [loading, offline]
+  )
+}