@feoe/fs-router
Version:
file system based routing
102 lines (101 loc) • 3.39 kB
JavaScript
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE_react_router_dom_5358f3fe__ from "react-router-dom";
function pathParser(path) {
const normalizedPath = path.replace(/^\/+|\/+$/g, "");
const pathWithoutExt = normalizedPath.replace(/\.[jt]sx?$/, "");
const pathSegments = pathWithoutExt.split("/");
const params = [];
const processedSegments = pathSegments.filter((segment)=>!segment.startsWith("(") && !segment.endsWith(")") && !segment.startsWith("__")).map((segment)=>{
const optionalMatch = segment.match(/^\[([.\w]+)\$\]$/);
if (optionalMatch) {
const name = optionalMatch[1];
params.push({
name,
optional: true
});
return `:${name}?`;
}
if ("$" === segment) {
params.push({
name: "*",
optional: false
});
return "*";
}
const optionalBracketMatch = segment.match(/^\[\[([.\w]+)\]\]$/);
if (optionalBracketMatch) {
const name = optionalBracketMatch[1];
if (name.startsWith("...")) {
params.push({
name: "*",
optional: true
});
return "*?";
}
params.push({
name,
optional: true
});
return `:${name}?`;
}
const requiredMatch = segment.match(/^\[([.\w]+)\]$/);
if (requiredMatch) {
const name = requiredMatch[1];
if (name.startsWith("...")) {
params.push({
name: "*",
optional: false
});
return "*";
}
params.push({
name
});
return `:${name}`;
}
return segment;
});
if ("page" === processedSegments[processedSegments.length - 1]) processedSegments.pop();
return {
route: processedSegments.join("/"),
params
};
}
function useNavigation() {
const navigate = (0, __WEBPACK_EXTERNAL_MODULE_react_router_dom_5358f3fe__.useNavigate)();
const navigation = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>{
const buildHref = (...args)=>{
const [path, params, query] = args;
let href = (0, __WEBPACK_EXTERNAL_MODULE_react_router_dom_5358f3fe__.generatePath)(path, params);
if (query) {
if (href.includes("?")) href += `&${new URLSearchParams(query).toString()}`;
else href += `?${new URLSearchParams(query).toString()}`;
}
return href;
};
return {
back () {
return navigate(-1);
},
forward () {
return navigate(1);
},
reload () {
return location.reload();
},
buildHref,
push (...args) {
return navigate(buildHref(...args));
},
replace (...args) {
return navigate(buildHref(...args), {
replace: true
});
}
};
}, [
navigate
]);
return navigation;
}
export { pathParser, useNavigation };