layout.tsx 1.81 KB
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
import { Outlet, useNavigate } from '@modern-js/runtime/router';
import dayjs from 'dayjs';
import { ONE_SECOND, helper, localdb } from '@feewee/h5app-common';
import { StyleProvider } from '@ant-design/cssinjs';
import { getServerTime } from './service';
import 'dayjs/locale/zh-cn';
import '@/style/global.scss';

dayjs.locale('zh-cn');

(() => {
  const { error } = console;
  console.error = (...args: any) => {
    if (/defaultProps/.test(args[0])) {
      return;
    }
    error(...args);
  };
})();

export default function Layout() {
  localdb.init('fw_h5_template', 'fw_h5_template', 'fw_h5_template_del');
  const timer = useRef<any>();
  const navigate = useNavigate();

  const saveServerTimeDif = useCallback(async () => {
    const idt = (await localdb.query<number>('i_dt')) || 0;
    if (Math.abs(idt - Date.now()) < 1000 * 60 * 10) {
      return;
    }
    const ser_time = await getServerTime();
    localdb.save<number>(process.env.MODERN_CALKEY ?? 'i_dif', ser_time ? ser_time - Date.now() : 0);
    localdb.save<number>('i_dt', Date.now());
  }, []);

  const lisFn = useCallback((e: any) => {
    if ('hardwareBackPress' === e.data) {
      helper.checkBack(() => navigate(-1));
    }
  }, []);

  useLayoutEffect(() => {
    localdb.clearExpireData();
    saveServerTimeDif();

    timer.current = setInterval(() => localdb.clearExpireData(), ONE_SECOND * 5);
    return () => {
      if (timer.current) {
        clearInterval(timer.current);
      }
    };
  }, [saveServerTimeDif]);

  useEffect(() => {
    window.document.addEventListener('message', lisFn);

    return () => {
      window.document.removeEventListener('message', lisFn);
    };
  }, []);

  return (
    <StyleProvider hashPriority="high">
      <Outlet />
    </StyleProvider>
  );
}