render.js 7.42 KB
Newer Older
邓晓峰's avatar
邓晓峰 committed
1
import React, { useEffect } from 'react';
2 3 4
import ReactDOM from 'react-dom';
import { history } from '@wisdom-utils/runtime';
import { Provider } from 'react-redux';
邓晓峰's avatar
邓晓峰 committed
5 6
import Cookies from 'js-cookie';
import { getToken } from './utils/utils';
7
import { ConfigProvider, message, Modal, notification } from 'antd';
8
import { ConnectedRouter } from 'connected-react-router/immutable';
9
import { ErrorBoundary, LocaleContainer } from '@wisdom-utils/components';
邓晓峰's avatar
邓晓峰 committed
10 11 12 13
import Login from './pages/user/login/login';
import { params, Storeage } from '@wisdom-utils/utils/lib/helpers';
import { updateCSS } from 'rc-util/lib/Dom/dynamicCSS';
import canUseDom from 'rc-util/lib/Dom/canUseDom';
14
import App from './containers/App';
邓晓峰's avatar
邓晓峰 committed
15 16 17 18 19 20 21
import Container from './components/Container';
import store from './stores';
import { appService } from './api';
import { defaultApp, initMicroApps } from './micro';
import { actionCreators } from './containers/App/store';
const { getThemeVariables } = require('antd/dist/theme');
const defaultSetting = require('../config/defaultSetting');
22
const MOUNT_NODE = document.getElementById('root');
23
const customPrefixCls = 'panda-console-base';
邓晓峰's avatar
邓晓峰 committed
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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
const namespace = `__PANDA_STORE__${location.hostname}`;
window.createStoreage = new Storeage(namespace);


const dynamicStyleMark = `-panda-${Date.now()}-${Math.random()}`;
function getStyle(prefixCls, theme) {
  const variables = {};

  Object.keys(theme).forEach(item => {
    variables[item] = theme[item]
  })
  const cssList = Object.keys(variables).map(
    key => `--${prefixCls}-${key}: ${variables[key]};`,
  );

  return `
  :root {
    ${cssList.join('\n')}
  }
  `.trim();


}

const registerTheme = function(prefixCls, theme) {
  const style = getStyle(prefixCls, theme);
  if(canUseDom()) {
    updateCSS(style, `${dynamicStyleMark}-dynamic-theme`)
  }
}


export const AppInitState = () => {


  const getClient = () => {
    const value = params.getParams('client') || Cookies.get('client');
    const client = value && value !== 'undefined' ? value : 'city';
    return client;
  }

  const client = getClient();

  let config = window.globalConfig || {};
  createStoreage.remove(`__PANDA_STORE__${location.hostname}`);
  
  window.globalConfig = {};
  window.__INITIAL_STATE__ = {};

  if (!getToken() || config.token == null) {
    // eslint-disable-next-line no-undef
    createStoreage.remove(namespace);
    config = {};
  }
  if (!params.getParams('client', window.location.search) && config) {
    // eslint-disable-next-line no-undef
    createStoreage.remove(namespace);
  }

  // eslint-disable-next-line no-undef
  if (!createStoreage.get('globalConfig')) {
    window.createStoreage = new Storeage(namespace);
  }

  if (!getToken()) {
    localStorage.removeItem('loginSite');
  }

  const initGeteWay = () => {
    appService.getWateWayConfig({ignoreSite: true}).then(res => {
      const hasGateWay = !res || !res.data ? false : _.isString(res.data) ? JSON.parse(res.data) : typeof res.data === 'boolean' ? res.data : false;
      return {
        hasGateWay,
        apiGatewayDomain: `${window.location.origin}${hasGateWay ? '/PandaCore/GateWay' : ''}`,
      };
    }).then(gateWayConfig => {
      initGlobalConfig(gateWayConfig);
    }).catch(err => {
      initGlobalConfig();
    });
  }


  const initGlobalConfig = (gateWayConfig = {}) => {
    appService.queryConfig({
      client: client || 'city',
      ignoreSite: true,
    }).then(res => {
      if (res) {
        const { data } = res;
        if (!data.client) {
          data.client = client;
        }
        store.dispatch(actionCreators.getConfig(Object.assign({},data,{
          token: '',
          access_token: '',
          userInfo: null,
        },gateWayConfig)));
        const products = (data.products || []).map(item => {
          if (item.PackageName === 'civweb4') {
            return 'web4_console'
          }
          return `${item.PackageName}-main`;
        });

        if(products && products.length > 0) {
          Object.keys(products).forEach(item => {
            window[products[item]] && window[products[item]] && window[products[item]].unmount && window[products[item]].unmount({ store: store });
          });
          initMicroApps();
        }
        // eslint-disable-next-line no-new
        if (getToken()) {
          // eslint-disable-next-line no-new
          const action = new Login({
              global: Object.assign({}, data,
                {
                  token: getToken(),
                },
                gateWayConfig,
              ),
              // eslint-disable-next-line no-shadow
              updateConfig: data => store.dispatch(actionCreators.getConfig(data)),
              isInit: false,
              logout: () => store.dispatch(actionCreators.logout()),
            },
            () => {
              (async () => {
                (await (getToken() &&
                  window.globalConfig &&
                  window.globalConfig.token)) &&
                  initMicroApps(loader, store);
              })();
            },
            true,
          );
          action.events.on('loginSuccess', event =>{
            window.history.pushState('', '', `/?client=${client}`);
            defaultApp();
          })
        }
邓晓峰's avatar
邓晓峰 committed
165
        return window.globalConfig.variableTheme
邓晓峰's avatar
邓晓峰 committed
166 167
      }
    })
邓晓峰's avatar
邓晓峰 committed
168 169 170 171 172 173 174 175 176 177 178 179 180
    .then(themeConfig => {
      ConfigProvider.config({
        prefixCls: customPrefixCls,
        theme: {
          primaryColor: themeConfig.primaryColor
        }
      });

      registerTheme(customPrefixCls, {
        'header-bg-color': themeConfig.headerPrimaryColor
        //'linear-gradient(0deg, #0066d6, #39a9ff 100%)',
      });
    })
邓晓峰's avatar
邓晓峰 committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    .catch(error => {
      store.dispatch(actionCreators.getConfigError(error));
    });
  }


  const initLocale = () => {
    localStorage.setItem('umi_locale', 'zh-CN');
  };

  // 语音播报全局拦截
  const initMessageVoice = () => {
    const rawSpeak = window.speechSynthesis.speak;
    window.speechSynthesis.speak = function(...args) {
      if (
        window.globalConfig &&
        // eslint-disable-next-line no-prototype-builtins
        window.globalConfig.hasOwnProperty('messageVoice') &&
        window.globalConfig.messageVoice === false
      )
        return;
      rawSpeak.apply(window.speechSynthesis, args);
    };
  };


  initLocale();
  initMessageVoice();
  initGeteWay();
}

const RootContainer = () => {

  useEffect(() => {
    AppInitState();
  }, []);

  const finalConfig = {
    ...{
      prefixCls: customPrefixCls,
      theme: {
        "root-entry-name": "default",
        ...getThemeVariables({}),
        primaryColor: defaultSetting.primaryColor,
      },
    }
  }

  if(finalConfig.prefixCls) {
    Modal.config({
      rootPrefixCls: customPrefixCls
    });
    message.config({
      rootPrefixCls: `${finalConfig.prefixCls}-message`
    });
    notification.config({
      rootPrefixCls: `${finalConfig.prefixCls}-notification`
    });
  }

  return React.createElement(Provider, {
    store: store
  }, React.createElement(ConnectedRouter, {
    history: history
  }, React.createElement(LocaleContainer, {
    prefixCls: customPrefixCls
  }, React.createElement(ConfigProvider, {
    prefixCls: customPrefixCls
  }, React.createElement(Container, null, React.createElement(App))))))
}

252

253
export const render = () => {
邓晓峰's avatar
邓晓峰 committed
254
  // eslint-disable-next-line react-hooks/rules-of-hooks
邓晓峰's avatar
邓晓峰 committed
255
  ReactDOM.render(<RootContainer/>, MOUNT_NODE);
邓晓峰's avatar
邓晓峰 committed
256
};
邓晓峰's avatar
邓晓峰 committed
257

邓晓峰's avatar
邓晓峰 committed
258 259
// updateTheme('#ff9600');
const loader = (appContent, loading) => render({ appContent, loading });
260

邓晓峰's avatar
邓晓峰 committed
261
export default loader;