import React from "react"; 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:"" }; 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; } type RoutePath = Array; type RouteParams = Record; type RouteState = {URL:URL, Path:RoutePath, Params:RouteParams, Anchor:string}; type RouteContext = [Route:RouteState, Update:(inPath?:RoutePath, inParams?:RouteParams, inAnchor?:string)=>void]; type RouteProps = {children:typeof React.Children, url?:URL }; export const Router = { Parse(url:URL):RouteState { const Path = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/"); const Params:RouteParams = {}; new URLSearchParams(url.search).forEach((k, v)=> Params[k] = v); const Anchor = url.hash.substring(1); return {URL:url, Path, Params, Anchor} as RouteState; }, Context:React.createContext([{URL:new URL("https://original.route/"), Path:[], Params:{}, Anchor:""}, ()=>{}] as RouteContext), Provider(props:RouteProps) { const [routeGet, routeSet] = React.useState(Router.Parse(props.url || new URL(document.location.href))); const [dirtyGet, dirtySet] = React.useState(false); const routeUpdate:RouteContext[1] =(inPath, inParams, inAnchor)=> { const clone = new URL(routeGet.URL); inPath && (clone.pathname = inPath.join("/")); inParams && (clone.search = new URLSearchParams(inParams as Record).toString()); routeSet({ URL:clone, Path: inPath || routeGet.Path, Params: inParams || routeGet.Params, Anchor: inAnchor || routeGet.Anchor }); dirtySet(true); }; // when the state changes, update the page url React.useEffect(()=>{ history.pushState({...routeGet, URL:undefined}, "", routeGet.URL); }, [routeGet.URL.href]); React.useEffect(()=>{ // when the history changes, update the state window.addEventListener("popstate", ({state})=>{routeUpdate(state.Path, state.Params, state.Anchor)}); }, []); return {props.children} ; }, Consumer() { return React.useContext(Router.Context); } };