mdf-plugin-viewhook
Version:
template view hook plugin for mdd framework
63 lines (52 loc) • 1.95 kB
JavaScript
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import beautify from 'js-beautify'
import html from './html'
import Isomorph from 'src/common/helpers/Isomorph'
import routes from 'src/common/redux/routes'
const routesMap = {
index: routes
};
const rebuildPaths = ['/', '/portal', '/register', '/wechat', '/forget'];
const directNext = function (ctx) {
if (rebuildPaths.indexOf(ctx.path) > -1
|| ctx.path.startsWith('/login')
|| ctx.path.startsWith('/billing')
|| ctx.path.startsWith('/meta')
|| ctx.path.startsWith('/platform')
|| ctx.path.startsWith('/echartcarousel'))
return false;
return true;
}
export default function viewhook(_options = { beautify: true, internals: true }) {
const options = Object.assign({}, _options)
return async function (ctx, next) {
if (directNext(ctx)) {
await next();
return;
}
const isTouch = ctx.header['user-agent'].match(/(Android);?[\s\/]+([\d.]+)?/) || ctx.path === '/billing/touch' || ctx.path === '/login/touch';
if (isTouch)
ctx.entryPoint = 'touch';
else if (ctx.path === '/billing')
ctx.entryPoint = 'billing';
else
ctx.entryPoint = 'index';
ctx.store = Isomorph.createStore(ctx.entryPoint)
ctx.history = Isomorph.createHistory(ctx.store, ctx.path)
ctx.render = function (pageInfo, internals = options.internals || true) {
const render = internals
? ReactDOMServer.renderToString
: ReactDOMServer.renderToStaticMarkup
let markup = render(<Isomorph store={ctx.store} history={ctx.history}
routes={routesMap[ctx.entryPoint]} />)
if (options.beautify) {
markup = beautify.html(markup)
}
ctx.type = 'html';
// 判断页面是否为billing, 传入html加载不同的依赖
ctx.body = html(Object.assign({ entryPoint: ctx.entryPoint }, pageInfo), markup, ctx.store.getState())
}
await next()
}
}