eno/lib/iso.tsx

78 lines
2.8 KiB
TypeScript
Raw Normal View History

2023-04-05 20:05:21 -04:00
import React from "react";
2023-04-05 23:34:20 -04:00
type Meta = {title:string, description:string, keywords:string, image:string, canonical:string }
type MetaKeys = keyof Meta;
export const Meta:Meta = {
title:"",
description:"",
keywords:"",
image:"",
canonical:""
2023-04-05 20:05:21 -04:00
};
2023-04-05 23:34:20 -04:00
type MetasInputs = { [Property in MetaKeys]?: string };
export const Metas =(props:{concatListed?:boolean; dropUnlisted?:boolean}&MetasInputs):null=>
{
const additive = props.concatListed ? (key:MetaKeys, value:string)=> Meta[key] += value : (key:MetaKeys, value:string)=> Meta[key] = value;
const subtractive = props.dropUnlisted ? (key:MetaKeys)=> Meta[key] = "" : (key:MetaKeys)=> {};
Object.keys(Meta).forEach((key)=>{
const metaKey = key as MetaKeys;
const propValue = props[metaKey]||"";
propValue ? additive(metaKey, propValue) : subtractive(metaKey);
})
console.log(`rendering metas`, Meta)
if(window.innerWidth)
{
document.title = Meta.title;
}
return null;
2023-04-13 22:23:04 -04:00
}
type RoutePath = Array<string>;
type RouteParams = Record<string, string>;
type RouteState = {URL:URL, Path:string[]};
type RouteContext = [Route:RouteState, Update:(inPath?:RoutePath, inParams?:RouteParams)=>void];
type RouteProps = {children:typeof React.Children, url?:URL };
export const Router = {
Path(url:URL)
{
return url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/");
},
Context:React.createContext([{URL:new URL("https://original.route/"), Path:[]}, ()=>{}] as RouteContext),
Provider(props:RouteProps)
{
const url = props.url || new URL(document.location.href);
const path = Router.Path(url);
const [routeGet, routeSet] = React.useState({URL:url, Path:path} as RouteState);
//const routeUpdate:RouteContext[1] =(inURL:URL)=>routeSet({URL:inURL, Path:Router.Path(inURL)});
const routeUpdate:RouteContext[1] =(inPath?:RoutePath, inParams?:RouteParams)=>
{
const clone = new URL(routeGet.URL.href);
inPath && (clone.pathname = `/${inPath.join("/")}`);
inParams && (clone.search = new URLSearchParams(inParams).toString());
routeSet({
URL:clone,
Path: inPath ? inPath : routeGet.Path
});
};
React.useEffect(()=>history.pushState({Path:routeGet.Path, Params:routeGet.URL.search}, "", routeGet.URL), [routeGet.URL.href]);
React.useEffect(()=>{
window.addEventListener("popstate", ()=>routeUpdate());
}, []);
return <Router.Context.Provider value={[routeGet, routeUpdate]}>
{props.children}
</Router.Context.Provider>;
},
Consumer()
{
return React.useContext(Router.Context);
}
};