eno/lib/iso.tsx

246 lines
9.1 KiB
TypeScript

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);
})
if(window.innerWidth)
{
document.title = Meta.title;
}
return null;
}
export type Children = string | number | React.JSX.Element | React.JSX.Element[];
type RoutePath = Array<string>;
type RouteParams = Record<string, string|number|boolean>;
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: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(true);
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<string, string>).toString());
routeSet({
URL:clone,
Path: inPath || routeGet.Path,
Params: inParams || routeGet.Params,
Anchor: inAnchor || routeGet.Anchor
});
};
// when the state changes, update the page url
React.useEffect(()=> dirtyGet ? dirtySet(false) : history.pushState({...routeGet, URL:undefined}, "", routeGet.URL), [routeGet.URL.href]);
React.useEffect(()=>{
history.replaceState({...routeGet, URL:undefined}, "", routeGet.URL);
window.addEventListener("popstate", ({state})=>
{
dirtySet(true);
routeUpdate(state.Path, state.Params, state.Anchor);
});
document.addEventListener("click", e=>
{
const t = e.target as HTMLAnchorElement;
if(t.href)
{
const u = new URL(t.href);
if(u.origin == document.location.origin)
{
e.preventDefault();
const parts = Router.Parse(u);
routeUpdate(parts.Path, parts.Params, parts.Anchor);
}
}
})
}, []);
return <Router.Context.Provider value={[routeGet, routeUpdate]}>{props.children}</Router.Context.Provider>;
},
Consumer()
{
return React.useContext(Router.Context);
}
};
type SwitchContext = {depth:number, keys:Record<string, string>};
export const SwitchContext = React.createContext({depth:0, keys:{}} as SwitchContext);
export const Switch =({children}:{children:Children})=>
{
let fallback = null;
if(Array.isArray(children))
{
const contextSelection = React.useContext(SwitchContext);
const [contextRoute] = Router.Consumer();
const routeSegment = contextRoute.Path.slice(contextSelection.depth);
const checkChild =(inChild:{props:{value?:string}})=>
{
if(inChild?.props?.value)
{
const parts = inChild.props.value.split("/");
if(parts.length > routeSegment.length)
{
return false;
}
const output:SwitchContext = {depth:contextSelection.depth+parts.length, keys:{}};
for(let i=0; i<parts.length; i++)
{
const partRoute = routeSegment[i];
const partCase = parts[i];
if(partCase[0] == ":")
{
output.keys[partCase.substring(1)] = partRoute;
}
else if(partCase != "*" && partCase != partRoute)
{
return false;
}
}
return output;
}
return false;
}
for(let i=0; i<children.length; i++)
{
const childCase = children[i];
const childCaseChildren = childCase.props?.__args?.[2] || childCase.props.children;
const newContextValue = checkChild(childCase);
if(newContextValue)
{
return <SwitchContext.Provider value={newContextValue}>{childCaseChildren}</SwitchContext.Provider>
}
if(childCase?.props?.default && !fallback)
{
console.log(routeSegment);
fallback = childCaseChildren;
}
}
}
return fallback;
};
export const Case =({children, value}:{children:Children, value?:string, default?:true})=>null;
export const useRouteVars =()=> React.useContext(SwitchContext).keys;
export type FetchRecord = {URL:string, CacheFor:number, CachedAt:number, CacheOnServer:boolean, Promise?:Promise<FetchRecord>, DelaySSR:boolean, Seed:boolean, Error?:string, JSON?:object};
export const Fetch = {
Cache:new Map() as Map<string, FetchRecord>,
ServerBlocking:false as false|Promise<FetchRecord>[],
ServerTouched:false as false|Set<FetchRecord>,
ServerRemove:false as false|Set<FetchRecord>,
Seed(seed:FetchRecord[])
{
seed.forEach(r=>{
r.Promise = Promise.resolve(r);
Fetch.Cache.set(r.URL, r)
});
},
Request(URL:string, Init?:RequestInit, CacheFor:number = 60, CacheOnServer:boolean = true, DelaySSR:boolean = true, Seed:boolean = true)
{
let check = Fetch.Cache.get(URL);
const load =(inCheck:FetchRecord)=>
{
Fetch.Cache.set(URL, inCheck);
inCheck.CachedAt = 0;
inCheck.Promise = fetch(URL, Init).then(resp=>resp.json()).then((json)=>{
inCheck.JSON = json;
inCheck.CachedAt = new Date().getTime();
console.log(`...cached!`);
return inCheck;
});
return inCheck;
}
if(!check)
{
console.log(`making new cache record...`);
return load({URL, CacheFor, CachedAt:0, CacheOnServer, DelaySSR, Seed});
}
else if(check.CachedAt == 0)
{
console.log(`currently being cached...`);
return check;
}
else
{
console.log(`found in cache...`);
let secondsAge = (new Date().getTime() - check.CachedAt)/1000;
if(secondsAge > check.CacheFor)
{
console.log(`...outdated...`);
return load(check);
}
else
{
console.log(`...retrieved!`);
return check;
}
}
},
Use(URL:string, Init?:RequestInit, CacheFor:number = 60, CacheOnServer:boolean = true, DelaySSR:boolean = true, Seed:boolean = true)
{
type FetchHookState = [Data:undefined|object, Updating:boolean];
const [cacheGet, cacheSet] = React.useState([undefined, true] as FetchHookState);
if(Fetch.ServerBlocking && Fetch.ServerTouched && DelaySSR)
{
const receipt = Fetch.Request(URL, Init, CacheFor, CacheOnServer, DelaySSR, Seed);
if(receipt.CachedAt === 0 && receipt.Promise)// request for something that hasnt been cached yet
{
Fetch.ServerBlocking.push(receipt.Promise);
}
else if(receipt.Seed)
{
Fetch.ServerTouched.add(receipt);
}
return [receipt.JSON, receipt.CachedAt === 0];
}
React.useEffect(()=>
{
const receipt = Fetch.Request(URL, Init, CacheFor, CacheOnServer, DelaySSR);
receipt.Promise?.then(()=>cacheSet([receipt.JSON, receipt.CachedAt === 0]));
}
, []);
return cacheGet;
}
};