smart-react-components
Version:
React UI library, wide variety of editable ready to use Styled and React components.
192 lines (181 loc) • 8.12 kB
JavaScript
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var React = require('react');
var React__default = _interopDefault(React);
var reactRouter = require('react-router');
var RouterContext = React.createContext(null);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
class RouterHelper {
/**
* Gets window location.
*/
static getUrl() {
return window.location.pathname + window.location.search;
}
/**
* Creates a url object by the fullpath.
*
* @param fullpath
*/
static setUrl(fullpath) {
if (fullpath) {
let [pathname, search] = fullpath.split("#")[0].split("?");
if (!search)
search = "";
const params = pathname.split("/");
const querySplit = search.split("&");
let query = {};
querySplit.forEach(item => {
const [key, value] = item.split("=");
query[key] = value;
});
return {
pathname,
search,
fullpath,
params,
query
};
}
return null;
}
/**
* Runs all the matched get methods from loader modules for ssr.
*
* @param routes
* @param fullpath
* @param params
*/
static runLoaders(routes, fullpath, params = {}) {
const { pathname, query } = this.setUrl(fullpath);
return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
const loaderMethods = [];
yield this.getLoaderMethods(routes, pathname, query, loaderMethods, params);
for (let i in loaderMethods) {
yield loaderMethods[i]();
}
resolve(loaderMethods);
}));
}
/**
* Gets all the matched get methods from loader modules.
*
* @param routes
* @param url
* @param query
* @param arr
* @param params
*/
static getLoaderMethods(routes, url, query, arr, params, oldUrl, setPercentage = (_ => { }), setCancelCallback = (() => { })) {
return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
for (let i in routes) {
const item = routes[i];
const match = this.matchPath(url, query, { path: item.path, exact: item.exact, searchKeys: item.searchKeys, defaultSearchValues: item.defaultSearchValues });
let pass;
if (!oldUrl)
pass = !!match;
else {
const oldUrlPathname = oldUrl.pathname;
const oldUrlQuery = oldUrl.query;
let oldMatch;
pass =
match &&
(!(oldMatch = this.matchPath(oldUrlPathname, oldUrlQuery, { path: item.path, exact: item.exact, searchKeys: item.searchKeys, defaultSearchValues: item.defaultSearchValues })) ||
(oldMatch && oldMatch.key != match.key));
}
if (match) {
if (pass && item.loaderModule) {
const _module = yield item.loaderModule.preload();
arr.push(_module.default.get.bind({}, match, Object.assign(Object.assign({}, this.setUrl(url)), { query }), setPercentage, setCancelCallback, params));
}
if (item.children)
yield this.getLoaderMethods(item.children, url, query, arr, params, oldUrl, setPercentage, setCancelCallback);
break;
}
}
resolve();
}));
}
/**
* Checks if the given path matches the url.
*
* @param url
* @param param1
*/
static matchPath(url, query, { path, exact, emptyQueryActive, searchKeys, defaultSearchValues }) {
let match = reactRouter.matchPath(url, { path: (typeof path === "string" ? path.split("?")[0] : path), exact });
let key = "";
if (match && typeof path === "string") {
const searchSplit = path.split("?");
if (searchSplit.length > 1) {
searchSplit[1].split("&").forEach(searchItem => {
const [searchKey, searchValue] = searchItem.split("=");
if (query[searchKey] != searchValue && (!emptyQueryActive || query[searchKey]))
match = null;
});
}
}
if (match) {
var _key = {
matchKey: match.params,
searchKey: {}
};
if (searchKeys) {
searchKeys.forEach(item => {
if (query[item])
_key.searchKey[item] = query[item];
else if (defaultSearchValues && defaultSearchValues[item])
_key.searchKey[item] = defaultSearchValues[item];
});
}
key = JSON.stringify(_key);
}
return match ? Object.assign(Object.assign({}, match), { key }) : null;
}
}
var useLinkMethods = ({ to, path, exact, emptyQueryActive, checkActive = true }) => {
const router = React__default.useContext(RouterContext);
const isActive = (url) => url && (RouterHelper.matchPath(url.pathname, url.query, { path: (path || to), exact, emptyQueryActive, searchKeys: null }) ? true : false);
const [active, setActive] = React__default.useState(() => checkActive ? isActive(router.state.url) : false);
const [activating, setActivating] = React__default.useState(() => checkActive ? isActive(router.state.newUrl) : false);
React__default.useEffect(() => {
if (checkActive)
setActive(isActive(router.state.url));
}, [router.state.url]);
React__default.useEffect(() => {
if (checkActive)
setActivating(isActive(router.state.newUrl));
}, [router.state.newUrl]);
const click = (e) => {
if (e.ctrlKey)
return;
e.preventDefault();
if ((!router.state.newUrl && router.state.url.fullpath != to) || (router.state.newUrl && router.state.newUrl.fullpath != to))
history.push(to);
};
return { click, active, activating };
};
exports.RouterContext = RouterContext;
exports.RouterHelper = RouterHelper;
exports.__awaiter = __awaiter;
exports.useLinkMethods = useLinkMethods;
;