umi#formatMessage JavaScript Examples

The following examples show how to use umi#formatMessage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From acy-dex-interface with MIT License 6 votes vote down vote up
render() {
    const { className } = this.props;
    const selectedLang = getLocale();
    const locales = ['zh-CN', 'zh-TW', 'en-US', 'pt-BR'];
    const languageLabels = {
      'zh-CN': '简体中文',
      'zh-TW': '繁体中文',
      'en-US': 'English',
      'pt-BR': 'Português',
    };
    const languageIcons = {
      'zh-CN': '??',
      'zh-TW': '??',
      'en-US': '??',
      'pt-BR': '??',
    };
    const langMenu = (
      <Menu className={styles.menu} selectedKeys={[selectedLang]} onClick={this.changeLang}>
        {locales.map(locale => (
          <Menu.Item key={locale}>
            <span role="img" aria-label={languageLabels[locale]}>
              {languageIcons[locale]}
            </span>{' '}
            {languageLabels[locale]}
          </Menu.Item>
        ))}
      </Menu>
    );
    return (
      <HeaderDropdown overlay={langMenu} placement="bottomRight">
        <span className={classNames(styles.dropDown, className)}>
          <Icon type="global" title={formatMessage({ id: 'navBar.lang' })} />
        </span>
      </HeaderDropdown>
    );
  }
Example #2
Source File: menu.js    From acy-dex-interface with MIT License 6 votes vote down vote up
// Conversion router to menu.
function formatter(data, parentAuthority, parentName) {
  return data
    .map(item => {
      if (!item.name || !item.path) {
        return null;
      }

      let locale = 'menu';
      if (parentName) {
        locale = `${parentName}.${item.name}`;
      } else {
        locale = `menu.${item.name}`;
      }

      const result = {
        ...item,
        name: formatMessage({ id: locale, defaultMessage: item.name }),
        locale,
        authority: item.authority || parentAuthority,
      };
      if (item.routes) {
        const children = formatter(item.routes, item.authority, locale);
        // Reduce memory usage
        result.children = children;
      }
      delete result.routes;
      return result;
    })
    .filter(item => item);
}
Example #3
Source File: global.js    From acy-dex-interface with MIT License 5 votes vote down vote up
// Notify user if offline now
window.addEventListener('sw.offline', () => {
  message.warning(formatMessage({ id: 'app.pwa.offline' }));
});
Example #4
Source File: global.js    From acy-dex-interface with MIT License 5 votes vote down vote up
// Pop up a prompt on the page asking the user if they want to use the latest version
window.addEventListener('sw.updated', e => {
  const reloadSW = async () => {
    // Check if there is sw whose state is waiting in ServiceWorkerRegistration
    // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
    const worker = e.detail && e.detail.waiting;
    if (!worker) {
      return Promise.resolve();
    }
    // Send skip-waiting event to waiting SW with MessageChannel
    await new Promise((resolve, reject) => {
      const channel = new MessageChannel();
      channel.port1.onmessage = event => {
        if (event.data.error) {
          reject(event.data.error);
        } else {
          resolve(event.data);
        }
      };
      worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
    });
    // Refresh current page to use the updated HTML and other assets after SW has skiped waiting
    window.location.reload(true);
    return true;
  };
  const key = `open${Date.now()}`;
  const btn = (
    <Button
      type="primary"
      onClick={() => {
        notification.close(key);
        reloadSW();
      }}
    >
      {formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
    </Button>
  );
  notification.open({
    message: formatMessage({ id: 'app.pwa.serviceworker.updated' }),
    description: formatMessage({ id: 'app.pwa.serviceworker.updated.hint' }),
    btn,
    key,
    onClose: async () => {},
  });
});
Example #5
Source File: BasicLayout.js    From acy-dex-interface with MIT License 4 votes vote down vote up
BasicLayout =props=> {
  // constructor(props) {
  //   super(props);
  //   getPageTitle = memoizeOne(getPageTitle);
  //   matchParamsPath = memoizeOne(matchParamsPath, isEqual);
  // }

  // componentDidMount() {
  //   const {
  //     dispatch,
  //     route: { routes, authority },
  //   } = props;
  //   // dispatch({
  //   //   type: 'user/fetchCurrent',
  //   // });
  //   dispatch({
  //     type: 'setting/getSetting',
  //   });
  //   dispatch({
  //     type: 'menu/getMenuData',
  //     payload: { routes, authority },
  //   });
  // }
  useEffect(() => {
    const {
      dispatch,
      route: { routes, authority },
    } = props;
    // dispatch({
    //   type: 'user/fetchCurrent',
    // });
    dispatch({
      type: 'setting/getSetting',
    });
    dispatch({
      type: 'menu/getMenuData',
      payload: { routes, authority },
    });
  },[])
  // 根据不同页面切换背景色
  const [bgColor,setBgColor]=useState('radialBg');
  useEffect(() => {
    const {
      location: { pathname },
    } = props;
    if(pathname.indexOf('/market')>-1){
      setBgColor('marketRadialBg');
    }
    if(pathname.indexOf('/exchange')>-1){
      setBgColor('radialBg');
    }
    if(pathname.indexOf('/liquidity')>-1){
      setBgColor('liquidityRadialBg');
    }
    if(pathname.indexOf('/farms')>-1){
      setBgColor('farmsRadialBg');
    }
    if(pathname.indexOf('/dao')>-1){
      setBgColor('daoRadialBg');
    }
    if(pathname.indexOf('/launchpad')>-1){
      setBgColor('launchpadRadialBg');
    }
    if(pathname.indexOf('/perpetual')>-1){
      setBgColor('launchpadRadialBg');
    }
    if(pathname.indexOf('/stablecoin')>-1){
      setBgColor('stableCoinRadialBg');
    }
    if(pathname.indexOf('/stats')>-1){
      setBgColor('statsRadialBg');
    }
  })
  // componentDidUpdate(preProps) {
  //   // After changing to phone mode,
  //   // if collapsed is true, you need to click twice to display
  //   const { collapsed, isMobile } = props;
  //   if (isMobile && !preProps.isMobile && !collapsed) {
  //     handleMenuCollapse(false);
  //   }
  // }

 const  getContext=()=> {
    const { location, breadcrumbNameMap } = props;
    return {
      location,
      breadcrumbNameMap,
    };
  }

  const matchParamsPath = (pathname, breadcrumbNameMap) => {
    const pathKey = Object.keys(breadcrumbNameMap).find(key => pathToRegexp(key).test(pathname));
    return breadcrumbNameMap[pathKey];
  };

  const getRouterAuthority = (pathname, routeData) => {
    let routeAuthority = ['noAuthority'];
    const getAuthority = (key, routes) => {
      routes.forEach(route => {
        if (route.path && pathToRegexp(route.path).test(key)) {
          routeAuthority = route.authority;
        } else if (route.routes) {
          routeAuthority = getAuthority(key, route.routes);
        }
        return route;
      });
      return routeAuthority;
    };
    return getAuthority(pathname, routeData);
  };

  const getPageTitle = (pathname, breadcrumbNameMap) => {
    const currRouterData = matchParamsPath(pathname, breadcrumbNameMap);

    if (!currRouterData) {
      return title;
    }
    const pageName = formatMessage({
      id: currRouterData.locale || currRouterData.name,
      defaultMessage: currRouterData.name,
    });

    return `${pageName} - ${title}`;
  };

  const getLayoutStyle = () => {
    const { fixSiderbar, isMobile, collapsed, layout } = props;
    if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
      return {
        paddingLeft: collapsed ? '80px' : '256px',
      };
    }
    return null;
  };

  const handleMenuCollapse = collapsed => {
    const { dispatch } = props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  };

  const renderSettingDrawer = () => {
    // Do not render SettingDrawer in production
    // unless it is deployed in preview.pro.ant.design as demo
    if (process.env.NODE_ENV === 'production' && APP_TYPE !== 'site') {
      return null;
    }
    return <SettingDrawer />;
  };

  const getLibrary=(provider, connector)=> {
    return new Web3Provider(provider); // this will vary according to whether you use e.g. ethers or web3.js
  }
  
    const {
      navTheme,
      layout: PropsLayout,
      children,
      location: { pathname },
      isMobile,
      menuData,
      breadcrumbNameMap,
      route: { routes },
      fixedHeader,
    } = props;
    const isTop = PropsLayout === 'topmenu';
    const routerConfig = getRouterAuthority(pathname, routes);
    const contentStyle = !fixedHeader ? { paddingTop: 0 } : {};
    const layout = 
      <Layout>
        {/* Conditional rendering: show Sidebar only in certain pages */}
        {pathname.indexOf('/launchpad')>-1 && false &&
        <Sidebar />
        }
        <Layout 
          style={{ ...getLayoutStyle(), minHeight: '100vh' }
            // background: styles.radialBg
          } 
          className={styles[bgColor]}
        >
          <SideMenu menuData={menuData} handleMenuCollapse={handleMenuCollapse} logo={logo} isMobile={isMobile} {...props} />
          <Content className={styles.content} style={contentStyle}>
            <Header menuData={menuData} handleMenuCollapse={handleMenuCollapse} logo={logo} isMobile={isMobile} {...props} />
            {children}
          </Content>
          {/* <Footer /> */}
        </Layout>
      </Layout>;
    return (
      <React.Fragment>
        <DocumentTitle title={getPageTitle(pathname, breadcrumbNameMap)}>
          <ContainerQuery query={query}>
            {params => (
              <Context.Provider value={getContext()}>
                <Web3ReactProvider getLibrary={getLibrary}>
                  <div className={classNames(params)}>{layout}</div>
                </Web3ReactProvider>
              </Context.Provider>
            )}
          </ContainerQuery>
        </DocumentTitle>
        {/* <Suspense fallback={<PageLoading />}>{renderSettingDrawer()}</Suspense> */}
      </React.Fragment>
    );
}