able-baker/iso-router.tsx

108 lines
4.0 KiB
TypeScript
Raw Normal View History

2024-05-07 20:05:38 -04:00
import * as Signal from "@preact/signals";
import * as React from "react";
///////// Metas
type MetaFields = {title?:string, description?:string};
type MetaRecord = MetaFields&{id:string}
const Stack = [] as MetaRecord[];
const StackPush =(m:MetaRecord)=> {Stack.push(m); Update();}
const StackPop =(id:string)=> {Stack.splice(Stack.findIndex( item => item.id === id ), 1); Update();}
const Update =()=> document.title = Stack[Stack.length-1]?.title || "---";
Update();
export const useMeta=(fields:MetaFields)=>
{
const id = React.useId();
React.useEffect(()=>{
StackPush({...fields, id});
return ()=>StackPop(id);
}, []);
}
export const Meta =(props:MetaFields)=> { useMeta(props); return null; }
2024-05-16 12:18:01 -04:00
2024-05-07 20:05:38 -04:00
//////// Router
//// Create Signals
2024-05-16 12:18:01 -04:00
export const pageURL = Signal.signal(new URL(globalThis?.location.href || ""));
2024-05-07 20:05:38 -04:00
export const pagePath = Signal.signal([] as string[]);
Signal.effect(()=> pagePath.value = pageURL.value.pathname.split("/").filter(part=>part!=""));
//// Add handlers
globalThis.addEventListener("click", e=>
{
(e.composedPath() as HTMLAnchorElement[]).find((step)=>{
if(step.href)
{
const url = new URL(step.href);
if(url.origin == document.location.origin)
{
e.preventDefault();
history.pushState({}, "", url);
pageURL.value = url;
}
return true;
}
})
});
globalThis.addEventListener("popstate", _=> pageURL.value = new URL(globalThis.location.href) );
/// Rendering context
type RouteContextData = {
/** Current nested depth of the router */ nestedDepth:number,
/** Index into the page path to start matching routes */ pathIndex:number,
2024-05-16 12:18:01 -04:00
/** Collection of keys from matched routes ("page/:key/") */ keys: Record<string, string>,
blocked: Signal.Signal<string | false>
2024-05-07 20:05:38 -04:00
}
2024-05-16 12:18:01 -04:00
const context = React.createContext({nestedDepth:0, pathIndex:0, keys:{}, blocked:Signal.signal(false as false|string)} as RouteContextData);
type PathFields = {pathAfter:string[], pathBefore:[], compare:typeof compare}
const compare =(pathA:string[], pathB:string[])=>
2024-05-07 20:05:38 -04:00
{
2024-05-16 12:18:01 -04:00
const emptyMatch = !pathA.length && !pathB.length;
const comparisonSize = Math.min(pathA.length, pathB.length);
2024-05-07 20:05:38 -04:00
if(comparisonSize == 0 && emptyMatch === false) // one of the arrays is empty and one is not
{
return null;
}
const keys = {} as Record<string, string>; // not doing anything with this currently
for(let i=0; i<comparisonSize; i++)
{
2024-05-16 12:18:01 -04:00
const partPage = pathB[i];
const partRoute = pathA[i];
2024-05-07 20:05:38 -04:00
if(partPage !== partRoute) // theres a mismatch
{
if(partRoute?.startsWith(":")) // mismatch because variable capture, consider it a match and capture
{
const key = partRoute?.substring(1);
key && (keys[key] = partPage);
}
else if(partRoute !== "*") // otherwise quit if its not a wildcard section
{
return null;
}
}
}
2024-05-16 12:18:01 -04:00
return {comparisonSize, keys};
};
export const useRoute =()=> {
const routeContext = React.useContext(context);
const pathFull = pagePath.value;
const pathAfter = pathFull.slice(routeContext.pathIndex);
const pathBefore = pathFull.slice(0, Math.max(0, routeContext.pathIndex-1));
return { ...routeContext, pathAfter, pathBefore, compare } as PathFields&RouteContextData;
}
export const Route =(props:{path:string[], children:React.ReactNode|React.ReactNode[]}):React.JSX.Element|null=>
{
const {nestedDepth, pathIndex, pathAfter, compare, keys} = useRoute();
const check = compare(props.path, pathAfter);
if (check)
{
return <context.Provider value={{
nestedDepth:nestedDepth+1,
pathIndex:pathIndex+check.comparisonSize,
keys: {...keys, ...check.keys},
blocked:Signal.signal(false)
}}>{props.children}</context.Provider>;
}
else
{
return null;
}
2024-05-07 20:05:38 -04:00
}