eno/lib/iso.tsx

342 lines
13 KiB
TypeScript
Raw Permalink Normal View History

2023-04-29 11:15:54 -04:00
import TWPreTail from "https://esm.sh/v115/@twind/preset-tailwind@1.1.4/es2022/preset-tailwind.mjs";
import TWPreAuto from "https://esm.sh/v115/@twind/preset-autoprefix@1.0.7/es2022/preset-autoprefix.mjs";
2023-04-05 20:05:21 -04:00
import React from "react";
2023-04-29 11:15:54 -04:00
export const CSS = {
presets: [TWPreTail(), TWPreAuto()],
hash:false
};
if(!window.innerWidth)
2023-04-29 20:16:28 -04:00
{
import(import.meta.resolve("../../server.tsx")).then(()=>{console.log("...imported!");});
}
2023-04-29 11:15:54 -04:00
2023-04-29 21:15:14 -04:00
type MetasInputs = { [Property in MetaKeys]?: string };
type MetasModeArgs = {concatListed?:boolean; dropUnlisted?:boolean};
type MetasStackItem = MetasModeArgs&MetasInputs&{id:string, depth:number}
2023-04-05 23:34:20 -04:00
type Meta = {title:string, description:string, keywords:string, image:string, canonical:string }
type MetaKeys = keyof Meta;
2023-04-05 20:05:21 -04:00
2023-04-29 21:15:14 -04:00
export const Meta =
2023-04-05 23:34:20 -04:00
{
2023-04-29 21:15:14 -04:00
Stack:[] as Array<MetasStackItem>,
Meta: {
title:"",
description:"",
keywords:"",
image:"",
canonical:""
} as Meta,
Context: React.createContext([[], ()=>{}] as [Get:MetasStackItem[], Set:React.StateUpdater<MetasStackItem[]>]),
Provider({children}:{children:Children})
2023-04-05 23:34:20 -04:00
{
2023-04-29 21:15:14 -04:00
const binding = React.useState([] as MetasStackItem[]);
React.useEffect(()=>{
const stack = binding[0];
const last = stack[stack.length-1];
console.log("updating page title", stack);
document.title = last?.title||"";
})
return <Meta.Context.Provider value={binding}>{children}</Meta.Context.Provider>;
},
Metas({concatListed=false, dropUnlisted=false, ...props}:MetasModeArgs&MetasInputs):null
{
const id = React.useId();
const [, metasSet] = React.useContext(Meta.Context);
const {depth} = React.useContext(SwitchContext);
2023-04-05 23:34:20 -04:00
2023-04-29 21:15:14 -04:00
React.useEffect(()=>{
metasSet((m)=>{
console.log(`adding meta`, props, depth);
const clone = [...m];
let i;
for(i=clone.length-1; i>-1; i--)
{
if(clone[i].depth <= depth)
{
break;
}
}
clone.splice(i+1, 0, {id, depth, concatListed, dropUnlisted, ...props});
return clone;
});
return ()=>
{
metasSet((m)=>{
const clone = [...m];
const ind = clone.findIndex(i=>i.id === id);
if(ind > -1)
{
console.log(`removing meta`, props, depth);
clone.splice(ind, 1);
}
return clone;
});
};
}, []);
React.useEffect(()=>{
metasSet((m)=>{
const clone = [...m];
const ind = clone.findIndex(i=>i.id === id);
if(ind > -1)
{
console.log(`updating meta`, props, depth);
clone[ind] = {...clone[ind], ...props};
}
return clone;
});
}, Object.keys(props).map( (key) => props[key as MetaKeys] ));
return null;
}
};
2023-04-13 22:23:04 -04:00
2023-04-16 21:33:09 -04:00
export type Children = string | number | React.JSX.Element | React.JSX.Element[];
2023-04-13 22:23:04 -04:00
type RoutePath = Array<string>;
2023-04-14 06:58:12 -04:00
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];
2023-04-16 21:33:09 -04:00
type RouteProps = {children:Children, url?:URL };
2023-04-13 22:23:04 -04:00
export const Router = {
2023-04-14 06:58:12 -04:00
Parse(url:URL):RouteState
2023-04-13 22:23:04 -04:00
{
2023-04-14 06:58:12 -04:00
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;
2023-04-13 22:23:04 -04:00
},
2023-04-14 06:58:12 -04:00
Context:React.createContext([{URL:new URL("https://original.route/"), Path:[], Params:{}, Anchor:""}, ()=>{}] as RouteContext),
2023-04-13 22:23:04 -04:00
Provider(props:RouteProps)
{
2023-04-14 06:58:12 -04:00
const [routeGet, routeSet] = React.useState(Router.Parse(props.url || new URL(document.location.href)));
2023-04-14 21:41:01 -04:00
const [dirtyGet, dirtySet] = React.useState(true);
2023-04-13 22:23:04 -04:00
2023-04-14 06:58:12 -04:00
const routeUpdate:RouteContext[1] =(inPath, inParams, inAnchor)=>
2023-04-13 22:23:04 -04:00
{
2023-04-14 06:58:12 -04:00
const clone = new URL(routeGet.URL);
inPath && (clone.pathname = inPath.join("/"));
inParams && (clone.search = new URLSearchParams(inParams as Record<string, string>).toString());
2023-04-13 22:23:04 -04:00
routeSet({
URL:clone,
2023-04-14 06:58:12 -04:00
Path: inPath || routeGet.Path,
Params: inParams || routeGet.Params,
Anchor: inAnchor || routeGet.Anchor
2023-04-13 22:23:04 -04:00
});
};
2023-04-14 06:58:12 -04:00
// when the state changes, update the page url
2023-04-14 21:41:01 -04:00
React.useEffect(()=> dirtyGet ? dirtySet(false) : history.pushState({...routeGet, URL:undefined}, "", routeGet.URL), [routeGet.URL.href]);
2023-04-14 06:58:12 -04:00
React.useEffect(()=>{
2023-04-14 21:41:01 -04:00
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;
2023-04-29 21:15:14 -04:00
const path = e.composedPath() as HTMLAnchorElement[];
for(let i=0; i<path.length; i++)
2023-04-14 21:41:01 -04:00
{
2023-04-29 21:15:14 -04:00
if(path[i].href)
2023-04-14 21:41:01 -04:00
{
2023-04-29 21:15:14 -04:00
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;
2023-04-14 21:41:01 -04:00
}
}
})
2023-04-13 22:23:04 -04:00
}, []);
2023-04-16 21:33:09 -04:00
return <Router.Context.Provider value={[routeGet, routeUpdate]}>{props.children}</Router.Context.Provider>;
2023-04-13 22:23:04 -04:00
},
Consumer()
{
return React.useContext(Router.Context);
}
2023-04-15 12:39:08 -04:00
};
type SwitchContext = {depth:number, keys:Record<string, string>};
export const SwitchContext = React.createContext({depth:0, keys:{}} as SwitchContext);
2023-04-16 21:33:09 -04:00
export const Switch =({children}:{children:Children})=>
2023-04-15 12:39:08 -04:00
{
2023-04-16 21:33:09 -04:00
let fallback = null;
if(Array.isArray(children))
2023-04-15 12:39:08 -04:00
{
2023-04-16 21:33:09 -04:00
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)
2023-04-15 12:39:08 -04:00
{
2023-04-16 21:33:09 -04:00
return false;
2023-04-15 12:39:08 -04:00
}
2023-04-16 21:33:09 -04:00
const output:SwitchContext = {depth:contextSelection.depth+parts.length, keys:{}};
for(let i=0; i<parts.length; i++)
2023-04-15 12:39:08 -04:00
{
2023-04-16 21:33:09 -04:00
const partRoute = routeSegment[i];
const partCase = parts[i];
if(partCase[0] == ":")
{
output.keys[partCase.substring(1)] = partRoute;
}
else if(partCase != "*" && partCase != partRoute)
{
return false;
}
2023-04-15 12:39:08 -04:00
}
2023-04-16 21:33:09 -04:00
return output;
2023-04-15 12:39:08 -04:00
}
2023-04-16 21:33:09 -04:00
return false;
2023-04-15 12:39:08 -04:00
}
2023-04-16 21:33:09 -04:00
for(let i=0; i<children.length; i++)
2023-04-15 12:39:08 -04:00
{
2023-04-16 21:33:09 -04:00
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)
{
2023-04-29 21:15:14 -04:00
//console.log(routeSegment);
2023-04-16 21:33:09 -04:00
fallback = childCaseChildren;
}
}
}
return fallback;
2023-04-15 12:39:08 -04:00
};
2023-04-16 21:33:09 -04:00
export const Case =({children, value}:{children:Children, value?:string, default?:true})=>null;
2023-04-18 22:22:59 -04:00
export const useRouteVars =()=> React.useContext(SwitchContext).keys;
2023-04-22 13:48:32 -04:00
export type FetchCachOptions = {CacheFor:number, CacheOnServer:boolean, DelaySSR:boolean, Seed:boolean};
export type FetchRecord = {URL:string, Promise?:Promise<FetchRecord>, CachedAt:number, Error?:string, JSON?:object} & FetchCachOptions;
2023-04-22 12:08:58 -04:00
type FetchGuide = [Record:FetchRecord, Init:boolean, Listen:boolean];
export type FetchHookState = [Data:undefined|object, Updating:boolean];
2023-04-18 22:22:59 -04:00
export const Fetch = {
Cache:new Map() as Map<string, FetchRecord>,
2023-04-21 20:27:37 -04:00
ServerBlocking:false as false|Promise<FetchRecord>[],
2023-04-21 22:21:04 -04:00
ServerTouched:false as false|Set<FetchRecord>,
2023-04-22 06:22:53 -04:00
ServerRemove:false as false|Set<FetchRecord>,
2023-04-21 20:27:37 -04:00
Seed(seed:FetchRecord[])
{
seed.forEach(r=>{
2023-04-22 12:08:58 -04:00
//r.Promise = Promise.resolve(r);
2023-04-21 20:27:37 -04:00
Fetch.Cache.set(r.URL, r)
});
},
2023-04-22 13:48:32 -04:00
DefaultOptions:{CacheFor:60, CacheOnServer:true, DelaySSR:true, Seed:true} as FetchCachOptions,
Request(URL:string, Init?:RequestInit|null, CacheFor:number = 60, CacheOnServer:boolean = true, DelaySSR:boolean = true, Seed:boolean = true):FetchGuide
2023-04-18 22:22:59 -04:00
{
let check = Fetch.Cache.get(URL);
2023-04-19 20:56:30 -04:00
const load =(inCheck:FetchRecord)=>
2023-04-18 22:22:59 -04:00
{
Fetch.Cache.set(URL, inCheck);
2023-04-19 20:56:30 -04:00
inCheck.CachedAt = 0;
2023-04-22 13:48:32 -04:00
inCheck.Promise = fetch(URL, Init?Init:undefined).then(resp=>resp.json()).then((json)=>{
2023-04-19 20:56:30 -04:00
inCheck.JSON = json;
inCheck.CachedAt = new Date().getTime();
2023-04-29 21:15:14 -04:00
//console.log(`...cached!`);
2023-04-19 20:56:30 -04:00
return inCheck;
});
2023-04-18 22:22:59 -04:00
return inCheck;
2023-04-22 12:08:58 -04:00
};
2023-04-18 22:22:59 -04:00
if(!check)
{
2023-04-22 12:08:58 -04:00
// not in the cache
// - listen
2023-04-29 21:15:14 -04:00
//console.log(`making new cache record...`);
2023-04-22 12:08:58 -04:00
return [load({URL, CacheFor, CachedAt:0, CacheOnServer, DelaySSR, Seed}), false, true];
2023-04-18 22:22:59 -04:00
}
2023-04-19 20:56:30 -04:00
else if(check.CachedAt == 0)
2023-04-18 22:22:59 -04:00
{
2023-04-22 12:08:58 -04:00
// loading started but not finished
// - listen
// - possibly init if there is something in JSON
2023-04-29 21:15:14 -04:00
//console.log(`currently being cached...`);
2023-04-22 12:08:58 -04:00
return [check, check.JSON ? true : false, true];
2023-04-18 22:22:59 -04:00
}
2023-04-19 20:56:30 -04:00
else
2023-04-18 22:22:59 -04:00
{
2023-04-29 21:15:14 -04:00
//console.log(`found in cache...`);
2023-04-19 20:56:30 -04:00
let secondsAge = (new Date().getTime() - check.CachedAt)/1000;
2023-04-18 22:22:59 -04:00
if(secondsAge > check.CacheFor)
{
2023-04-22 12:08:58 -04:00
// cached but expired
// - listen
// - init
2023-04-29 21:15:14 -04:00
//console.log(`...outdated...`);
2023-04-22 12:08:58 -04:00
return [load(check), true, true];
2023-04-18 22:22:59 -04:00
}
else
{
2023-04-22 12:08:58 -04:00
// cached and ready
// - init
2023-04-29 21:15:14 -04:00
//console.log(`...retrieved!`);
2023-04-22 12:08:58 -04:00
return [check, true, false];
2023-04-18 22:22:59 -04:00
}
}
2023-04-19 20:56:30 -04:00
},
2023-04-22 13:48:32 -04:00
Use(URL:string, Init?:RequestInit|null, Options?:FetchCachOptions)
2023-04-19 20:56:30 -04:00
{
2023-04-22 13:48:32 -04:00
const config = {...Fetch.DefaultOptions, ...Options};
const [receipt, init, listen] = Fetch.Request(URL, Init, config.CacheFor, config.CacheOnServer, config.DelaySSR, config.Seed);
2023-04-22 12:08:58 -04:00
const initialState:FetchHookState = init ? [receipt.JSON, listen] : [undefined, true];
const [cacheGet, cacheSet] = React.useState(initialState);
2023-04-22 13:48:32 -04:00
if(Fetch.ServerBlocking && Fetch.ServerTouched && config.DelaySSR) // if server-side rendering
2023-04-20 21:07:26 -04:00
{
2023-04-22 12:08:58 -04:00
if(listen) // if the request is pending
2023-04-20 21:07:26 -04:00
{
2023-04-22 12:08:58 -04:00
receipt.Promise && Fetch.ServerBlocking.push(receipt.Promise); // add promise to blocking list
return [undefined, listen] as FetchHookState; // no need to return any actual data while waiting server-side
2023-04-21 20:27:37 -04:00
}
2023-04-22 12:08:58 -04:00
else // if request is ready
2023-04-21 20:27:37 -04:00
{
2023-04-22 12:08:58 -04:00
receipt.Seed && Fetch.ServerTouched.add(receipt); // add record to client seed list (if specified in receipt.seed)
return [receipt.JSON, false] as FetchHookState;
2023-04-20 21:07:26 -04:00
}
}
2023-04-22 12:08:58 -04:00
2023-04-19 20:56:30 -04:00
React.useEffect(()=>
{
2023-04-22 12:08:58 -04:00
if(listen)
{
//const receipt = Fetch.Request(URL, Init, CacheFor, CacheOnServer, DelaySSR);
receipt.Promise?.then(()=>cacheSet([receipt.JSON, receipt.CachedAt === 0]));
}
2023-04-19 20:56:30 -04:00
}
, []);
return cacheGet;
2023-04-18 22:22:59 -04:00
}
2023-04-20 21:07:26 -04:00
};