server-renderer
Version:
library of server side render for React
183 lines (168 loc) • 8.14 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom'), require('url'), require('path-to-regexp'), require('history')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom', 'url', 'path-to-regexp', 'history'], factory) :
(global = global || self, factory(global.ServerRenderer = {}, global.React, global.reactDom, global.url, global.pathToRegexp, global.H));
}(this, (function (exports, React, reactDom, url, pathToRegexp, H) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function findMatchedRoute(url$1, routes = []) {
// 通配符
const wildcard = '(.*)';
const { pathname } = url.parse(url$1);
const matched = routes
.map(route => {
if (route.path === '*') {
return Object.assign(Object.assign({}, route), { path: wildcard });
}
return route;
})
.find(route => {
return pathToRegexp.pathToRegexp(route.path).test(pathname + '');
});
return matched;
}
function callGetInitialProps(App, Component, url, req, res) {
return __awaiter(this, void 0, void 0, function* () {
if (App.getInitialProps) {
const params = {
Component,
url,
req,
res,
};
return yield App.getInitialProps(params);
}
return {};
});
}
const RouterContext = React.createContext({});
const history = 'undefined' === typeof window
? H.createMemoryHistory()
: H.createBrowserHistory();
const useLocation = () => {
return React.useContext(RouterContext).location;
};
const useParams = () => {
return React.useContext(RouterContext).params;
};
function matchParams(path, pathname) {
const matchFn = pathToRegexp.match(path);
const matched = matchFn(pathname);
return matched ? matched.params : {};
}
const Router = props => {
const component = React.useRef(props.component);
const pageProps = React.useRef(props.pageProps);
const [location, setLocation] = React.useState(() => {
const parsedUrl = url.parse(props.url);
return {
pathname: parsedUrl.pathname || '/',
search: parsedUrl.search || '',
hash: parsedUrl.hash || '',
state: null,
};
});
const [params, setParams] = React.useState(() => {
const matchedRoute = findMatchedRoute(props.url, props.routes);
return matchParams(matchedRoute ? matchedRoute.path : '', location.pathname);
});
React.useEffect(() => {
const unlisten = history.listen((newLocation) => __awaiter(void 0, void 0, void 0, function* () {
if (newLocation.pathname === location.pathname) {
// H.locationsAreEqual(location, newLocation)
// 忽略 search 变化
return;
}
const matched = findMatchedRoute(newLocation.pathname, props.routes);
if (matched) {
const initialProps = yield callGetInitialProps(props.App, matched.component, newLocation.pathname);
pageProps.current = initialProps;
component.current = matched.component;
}
else {
component.current = null;
}
reactDom.unstable_batchedUpdates(() => {
setLocation(newLocation);
setParams(matched ? matchParams(matched.path, newLocation.pathname) : {});
});
}));
return unlisten;
}, [location.pathname]);
const store = React.useMemo(() => ({ location, params }), [location]);
return (React.createElement(RouterContext.Provider, { value: store },
React.createElement(props.App, { pageProps: pageProps.current, Component: component.current })));
};
const Root = props => {
return (React.createElement(Router, { url: props.url, routes: props.routes, component: props.component, pageProps: props.pageProps, App: props.App }));
};
const App = (_a) => {
var { Component } = _a, otherProps = __rest(_a, ["Component"]);
if (Component) {
return React.createElement(Component, Object.assign({}, otherProps));
}
return null;
};
App.getInitialProps = (params) => __awaiter(void 0, void 0, void 0, function* () {
const { Component } = params;
if (Component && Component.getInitialProps) {
return yield Component.getInitialProps(params);
}
return {};
});
const Link = (_a) => {
var { to, onClick } = _a, otherProps = __rest(_a, ["to", "onClick"]);
const handler = React.useCallback((evt) => {
if (onClick) {
onClick(evt);
}
if (!evt.isDefaultPrevented()) {
evt.preventDefault();
history.push(to);
}
}, [to, onClick]);
return (React.createElement("a", Object.assign({ onClick: handler, href: to }, otherProps)));
};
function render(options) {
const appData = window.__APP_DATA__;
const matched = findMatchedRoute(window.location.pathname, options.routes);
const App$1 = options.App || App;
const app = (React.createElement(Root, { url: window.location.href, routes: options.routes || [], pageProps: appData.pageProps, component: matched ? matched.component : null, App: App$1 }));
reactDom.hydrate(app, document.querySelector(options.container));
}
exports.Link = Link;
exports.history = history;
exports.render = render;
exports.useLocation = useLocation;
exports.useParams = useParams;
Object.defineProperty(exports, '__esModule', { value: true });
})));