aberdeen 1.0.13 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -5
- package/dist/aberdeen.d.ts +58 -100
- package/dist/aberdeen.js +201 -184
- package/dist/aberdeen.js.map +3 -3
- package/dist/dispatcher.d.ts +54 -0
- package/dist/dispatcher.js +65 -0
- package/dist/dispatcher.js.map +10 -0
- package/dist/route.d.ts +79 -30
- package/dist/route.js +162 -135
- package/dist/route.js.map +3 -3
- package/dist-min/aberdeen.js +5 -5
- package/dist-min/aberdeen.js.map +3 -3
- package/dist-min/dispatcher.js +4 -0
- package/dist-min/dispatcher.js.map +10 -0
- package/dist-min/route.js +2 -2
- package/dist-min/route.js.map +3 -3
- package/package.json +6 -1
- package/src/aberdeen.ts +303 -349
- package/src/dispatcher.ts +130 -0
- package/src/route.ts +272 -181
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var H=Symbol("matchFailed"),G=Symbol("matchRest");class J{routes=[];addRoute(...q){let j=q.slice(0,-1),k=q[q.length-1];if(typeof k!=="function")throw new Error("Last argument should be a handler function");if(j.filter((C)=>C===G).length>1)throw new Error("Only one matchRest is allowed");this.routes.push({matchers:j,handler:k})}dispatch(q){for(let j of this.routes){let k=K(j,q);if(k)return j.handler(...k),!0}return!1}}function K(q,j){let k=[],B=0;for(let C of q.matchers){if(C===G){let z=j.length-(q.matchers.length-1);if(z<0)return;k.push(j.slice(B,B+z)),B+=z;continue}if(B>=j.length)return;let E=j[B];if(typeof C==="string"){if(E!==C)return}else if(typeof C==="function"){let z=C(E);if(z===H||typeof z==="number"&&isNaN(z))return;k.push(z)}B++}return k}export{G as matchRest,H as matchFailed,J as Dispatcher};
|
|
2
|
+
|
|
3
|
+
//# debugId=80743EF466EF1C6E64756E2164756E21
|
|
4
|
+
//# sourceMappingURL=dispatcher.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/dispatcher.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Symbol to return when a custom {@link Dispatcher.addRoute} matcher cannot match a segment.\n */\nexport const matchFailed: unique symbol = Symbol(\"matchFailed\");\n\n/**\n * Special {@link Dispatcher.addRoute} matcher that matches the rest of the segments as an array of strings.\n */\nexport const matchRest: unique symbol = Symbol(\"matchRest\");\n\ntype Matcher = string | ((segment: string) => any) | typeof matchRest;\n\ntype ExtractParamType<M> = M extends string\n? never : (\n M extends ((segment: string) => infer R)\n ? Exclude<R, typeof matchFailed>\n : (M extends typeof matchRest ? string[] : never)\n);\n\ntype ParamsFromMatchers<T extends Matcher[]> = T extends [infer M1, ...infer Rest]\n? (\n M1 extends Matcher\n ? (\n ExtractParamType<M1> extends never\n ? ParamsFromMatchers<Rest extends Matcher[] ? Rest : []>\n : [ExtractParamType<M1>, ...ParamsFromMatchers<Rest extends Matcher[] ? Rest : []>]\n ) : never\n) : [];\n\ninterface DispatcherRoute {\n matchers: Matcher[];\n handler: (...params: any[]) => void;\n}\n\n/**\n * Simple route matcher and dispatcher.\n * \n * Example usage:\n * \n * ```ts\n * const dispatcher = new Dispatcher();\n * \n * dispatcher.addRoute(\"user\", Number, \"stream\", String, (id, stream) => {\n * console.log(`User ${id}, stream ${stream}`);\n * });\n *\n * dispatcher.dispatch([\"user\", \"42\", \"stream\", \"music\"]);\n * // Logs: User 42, stream music\n * \n * dispatcher.addRoute(\"search\", matchRest, (terms: string[]) => {\n * console.log(\"Search terms:\", terms);\n * });\n * \n * dispatcher.dispatch([\"search\", \"classical\", \"piano\"]);\n * // Logs: Search terms: [ 'classical', 'piano' ]\n * ```\n */\nexport class Dispatcher {\n private routes: Array<DispatcherRoute> = [];\n \n /**\n * Add a route with matchers and a handler function.\n * @param args An array of matchers followed by a handler function. Each matcher can be:\n * - A string: matches exactly that string.\n * - A function: takes a string segment and returns a value (of any type) if it matches, or {@link matchFailed} if it doesn't match. The return value (if not `matchFailed` and not `NaN`) is passed as a parameter to the handler function. The built-in functions `Number` and `String` can be used to match numeric and string segments respectively.\n * - The special {@link matchRest} symbol: matches the rest of the segments as an array of strings. Only one `matchRest` is allowed, and it must be the last matcher.\n * @template T - Array of matcher types.\n * @template H - Handler function type, inferred from the matchers.\n */\n addRoute<T extends Matcher[], H extends (...args: ParamsFromMatchers<T>) => void>(...args: [...T, H]): void {\n const matchers = args.slice(0, -1) as Matcher[];\n const handler = args[args.length - 1] as (...args: any) => any;\n\n if (typeof handler !== \"function\") {\n throw new Error(\"Last argument should be a handler function\");\n }\n \n const restCount = matchers.filter(m => m === matchRest).length;\n if (restCount > 1) {\n throw new Error(\"Only one matchRest is allowed\");\n }\n\n this.routes.push({ matchers, handler });\n }\n \n /**\n * Dispatches the given segments to the first route handler that matches.\n * @param segments Array of string segments to match against the added routes. When using this class with the Aberdeen `route` module, one would typically pass `route.current.p`.\n * @returns True if a matching route was found and handled, false otherwise.\n */\n dispatch(segments: string[]): boolean {\n for (const route of this.routes) {\n const args = matchRoute(route, segments);\n if (args) {\n route.handler(...args);\n return true;\n }\n }\n return false;\n }\n}\n\nfunction matchRoute(route: DispatcherRoute, segments: string[]): any[] | undefined {\n const args: any[] = [];\n let segmentIndex = 0;\n\n for (const matcher of route.matchers) {\n if (matcher === matchRest) {\n const len = segments.length - (route.matchers.length - 1);\n if (len < 0) return;\n args.push(segments.slice(segmentIndex, segmentIndex + len));\n segmentIndex += len;\n continue;\n }\n\n if (segmentIndex >= segments.length) return;\n const segment = segments[segmentIndex];\n \n if (typeof matcher === \"string\") {\n if (segment !== matcher) return;\n } else if (typeof matcher === \"function\") {\n const result = matcher(segment);\n if (result === matchFailed || (typeof result === 'number' && isNaN(result))) return;\n args.push(result);\n }\n \n segmentIndex++;\n }\n return args; // success!\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "AAGO,IAAM,EAA6B,OAAO,aAAa,EAKjD,EAA2B,OAAO,WAAW,EAiDnD,MAAM,CA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runQueue as f,unproxy as N,copy as O,merge as U,clone as X,leakScope as $}from"./aberdeen.js";var J=()=>{};function d(z){if(z===!0)J=console.log.bind(console,"aberdeen router");else if(z===!1)J=()=>{};else J=z}function j(){return W({path:location.pathname,hash:location.hash,search:Object.fromEntries(new URLSearchParams(location.search)),state:history.state?.state||{}},"load",(history.state?.stack?.length||0)+1)}function V(z,A,D){if(z===A)return!0;if(typeof z!=="object"||!z||typeof A!=="object"||!A)return!1;if(z.constructor!==A.constructor)return!1;if(A instanceof Array){if(z.length!==A.length)return!1;for(let G=0;G<A.length;G++)if(!V(z[G],A[G],D))return!1}else{for(let G of Object.keys(A))if(!V(z[G],A[G],D))return!1;if(!D){for(let G of Object.keys(z))if(!A.hasOwnProperty(G))return!1}}return!0}function E(z){let A=new URLSearchParams(z.search).toString();return(A?`${z.path}?${A}`:z.path)+z.hash}function W(z,A,D){let G=z.path||(z.p||[]).join("/")||"/";if(G=(""+G).replace(/\/+$/,""),!G.startsWith("/"))G=`/${G}`;return{path:G,hash:z.hash&&z.hash!=="#"?z.hash.startsWith("#")?z.hash:"#"+z.hash:"",p:G.length>1?G.slice(1).replace(/\/+$/,"").split("/"):[],nav:A,search:typeof z.search==="object"&&z.search?X(z.search):{},state:typeof z.state==="object"&&z.state?X(z.state):{},depth:D}}function Y(z){if(typeof z==="string")z={path:z};else if(z instanceof Array)z={p:z};if(z.p)z.p=z.p.map(String);if(z.search)for(let A of Object.keys(z.search))z.search[A]=String(z.search[A]);return z}function I(z){L=(history.state?.stack||[]).concat(JSON.stringify(N(H)));let D=W(Y(z),"go",L.length+1);O(H,D),J("go",D),history.pushState({state:D.state,stack:L},"",E(D)),f()}function C(z){let A=X(N(H));U(A,Y(z)),I(A)}function P(z={}){let A=Y(z),D=history.state?.stack||[];for(let K=D.length-1;K>=0;K--){let M=JSON.parse(D[K]);if(V(M,A,!0)){let Z=K-D.length;J("back",Z,M),history.go(Z);return}}let G=W(A,"back",D.length+1);J("back not found, replacing",A),O(H,G)}function S(z=1){let A=N(H).p,D=history.state?.stack||[];for(let K=D.length-1;K>=0;K--){let M=JSON.parse(D[K]);if(M.p.length<A.length&&V(M.p,A.slice(0,M.p.length),!1)){J(`up to ${K+1} / ${D.length}`,M),history.go(K-D.length);return}}let G=W({p:A.slice(0,A.length-z)},"back",D.length+1);J("up not found, replacing",G),O(H,G)}function x(z="main"){let A=F();A.addEventListener("scroll",G),B(()=>A.removeEventListener("scroll",G));let D=N(H).state.scroll?.[z];if(D)J("restoring scroll",z,D),Object.assign(A,D);function G(){(H.state.scroll||={})[z]={scrollTop:A.scrollTop,scrollLeft:A.scrollLeft}}}var L,H=Q({});function T(){L=history.state?.stack||[];let z=j();J("initial",z),O(N(H),z)}T();window.addEventListener("popstate",function(z){let A=j(),D=history.state?.stack||[];if(D.length!==L.length){let G=Math.min(L.length,D.length)-1;if(G<0||D[G]===L[G])A.nav=D.length<L.length?"back":"forward"}L=D,J("popstate",A),O(H,A),f()});$(()=>{_(()=>{H.path="/"+Array.from(H.p).join("/")}),_(()=>{let z=history.state?.stack||[],A=W(H,N(H).nav,z.length+1);O(H,A);let D={state:A.state,stack:z},G=E(A);if(G!==location.pathname+location.search+location.hash||!V(history.state,D,!1))J("replaceState",A,D,G),history.replaceState(D,"",G)})});export{S as up,d as setLog,T as reset,C as push,x as persistScroll,I as go,H as current,P as back};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=B6ADEE6973F8780664756E2164756E21
|
|
4
4
|
//# sourceMappingURL=route.js.map
|
package/dist-min/route.js.map
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/route.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import {\n\tclean,\n\tclone,\n\tgetParentElement,\n\timmediateObserve,\n\tobserve,\n\tproxy,\n\trunQueue,\n\tunproxy,\n} from \"./aberdeen.js\";\n\n/**\n * The class for the singleton `route` object.\n *\n */\n\nexport class Route {\n\t/** The current path of the URL split into components. For instance `/` or `/users/123/feed`. Updates will be reflected in the URL and will *push* a new entry to the browser history. */\n\tpath!: string;\n\t/** Array containing the path segments. For instance `[]` or `['users', 123, 'feed']`. Updates will be reflected in the URL and will *push* a new entry to the browser history. Also, the values of `p` and `path` will be synced. */\n\tp!: string[];\n\t/** An observable object containing search parameters (a split up query string). For instance `{order: \"date\", title: \"something\"}` or just `{}`. By default, updates will be reflected in the URL, replacing the current history state. */\n\thash!: string;\n\t/** A part of the browser history *state* that is considered part of the page *identify*, meaning changes will (by default) cause a history push, and when going *back*, it must match. */\n\tsearch!: Record<string, string>;\n\t/** The `hash` interpreted as search parameters. So `\"a=x&b=y\"` becomes `{a: \"x\", b: \"y\"}`. */\n\tid!: Record<string, any>;\n\t/** The auxiliary part of the browser history *state*, not considered part of the page *identity*. Changes will be reflected in the browser history using a replace. */\n\taux!: Record<string, any>;\n\t/** The navigation depth of the current session. Starts at 1. Writing to this property has no effect. */\n\tdepth = 1;\n\t/** The navigation action that got us to this page. Writing to this property has no effect.\n - `\"load\"`: An initial page load.\n - `\"back\"` or `\"forward\"`: When we navigated backwards or forwards in the stack.\n - `\"push\"`: When we added a new page on top of the stack. \n */\n\tnav: \"load\" | \"back\" | \"forward\" | \"push\" = \"load\";\n\t/** As described above, this library takes a best guess about whether pushing an item to the browser history makes sense or not. When `mode` is... \n \t - `\"push\"`: Force creation of a new browser history entry. \n \t - `\"replace\"`: Update the current history entry, even when updates to other keys would normally cause a *push*.\n \t - `\"back\"`: Unwind the history (like repeatedly pressing the *back* button) until we find a page that matches the given `path` and `id` (or that is the first page in our stack), and then *replace* that state by the full given state.\n The `mode` key can be written to `route` but will be immediately and silently removed.\n */\n\tmode: \"push\" | \"replace\" | \"back\" | undefined;\n}\n\n/**\n * The singleton {@link Route} object reflecting the current URL and browser history state. You can make changes to it to affect the URL and browser history. See {@link Route} for details.\n */\nexport const route = proxy(new Route());\n\nlet stateRoute = {\n\tnonce: -1,\n\tdepth: 0,\n};\n\n// Reflect changes to the browser URL (back/forward navigation) in the `route` and `stack`.\nfunction handleLocationUpdate(event?: PopStateEvent) {\n\tconst state = event?.state || {};\n\tlet nav: \"load\" | \"back\" | \"forward\" | \"push\" = \"load\";\n\tif (state.route?.nonce == null) {\n\t\tstate.route = {\n\t\t\tnonce: Math.floor(Math.random() * Number.MAX_SAFE_INTEGER),\n\t\t\tdepth: 1,\n\t\t};\n\t\thistory.replaceState(state, \"\");\n\t} else if (stateRoute.nonce === state.route.nonce) {\n\t\tnav = state.route.depth > stateRoute.depth ? \"forward\" : \"back\";\n\t}\n\tstateRoute = state.route;\n\n\tif (unproxy(route).mode === \"back\") {\n\t\troute.depth = stateRoute.depth;\n\t\t// We are still in the process of searching for a page in our navigation history..\n\t\tupdateHistory();\n\t\treturn;\n\t}\n\n\tconst search: any = {};\n\tfor (const [k, v] of new URLSearchParams(location.search)) {\n\t\tsearch[k] = v;\n\t}\n\n\troute.path = location.pathname;\n\troute.p = location.pathname.slice(1).split(\"/\");\n\troute.search = search;\n\troute.hash = location.hash;\n\troute.id = state.id;\n\troute.aux = state.aux;\n\troute.depth = stateRoute.depth;\n\troute.nav = nav;\n\n\t// Forward or back event. Redraw synchronously, because we can!\n\tif (event) runQueue();\n}\nhandleLocationUpdate();\nwindow.addEventListener(\"popstate\", handleLocationUpdate);\n\n// These immediate-mode observers will rewrite the data in `route` to its canonical form.\n// We want to to this immediately, so that user-code running immediately after a user-code\n// initiated `set` will see the canonical form (instead of doing a rerender shortly after,\n// or crashing due to non-canonical data).\nfunction updatePath(): void {\n\tlet path = route.path;\n\tif (path == null && unproxy(route).p) {\n\t\tupdateP();\n\t\treturn;\n\t}\n\tpath = `${path || \"/\"}`;\n\tif (!path.startsWith(\"/\")) path = `/${path}`;\n\troute.path = path;\n\troute.p = path.slice(1).split(\"/\");\n}\nimmediateObserve(updatePath);\n\nfunction updateP() {\n\tconst p = route.p;\n\tif (p == null && unproxy(route).path) {\n\t\tupdatePath();\n\t\treturn;\n\t}\n\tif (!(p instanceof Array)) {\n\t\tconsole.error(\n\t\t\t`aberdeen route: 'p' must be a non-empty array, not ${JSON.stringify(p)}`,\n\t\t);\n\t\troute.p = [\"\"]; // This will cause a recursive call this observer.\n\t} else if (p.length === 0) {\n\t\troute.p = [\"\"]; // This will cause a recursive call this observer.\n\t} else {\n\t\troute.path = `/${p.join(\"/\")}`;\n\t}\n}\nimmediateObserve(updateP);\n\nimmediateObserve(() => {\n\tif (!route.search || typeof route.search !== \"object\") route.search = {};\n});\n\nimmediateObserve(() => {\n\tif (!route.id || typeof route.id !== \"object\") route.id = {};\n});\n\nimmediateObserve(() => {\n\tif (!route.aux || typeof route.aux !== \"object\") route.aux = {};\n});\n\nimmediateObserve(() => {\n\tlet hash = `${route.hash || \"\"}`;\n\tif (hash && !hash.startsWith(\"#\")) hash = `#${hash}`;\n\troute.hash = hash;\n});\n\nfunction isSamePage(path: string, state: any): boolean {\n\treturn (\n\t\tlocation.pathname === path &&\n\t\tJSON.stringify(history.state.id || {}) === JSON.stringify(state.id || {})\n\t);\n}\n\nfunction updateHistory() {\n\t// Get and delete mode without triggering anything.\n\tlet mode = route.mode;\n\tconst state = {\n\t\tid: clone(route.id),\n\t\taux: clone(route.aux),\n\t\troute: stateRoute,\n\t};\n\n\t// Construct the URL.\n\tconst path = route.path;\n\n\t// Change browser state, according to `mode`.\n\tif (mode === \"back\") {\n\t\troute.nav = \"back\";\n\t\tif (!isSamePage(path, state) && (history.state.route?.depth || 0) > 1) {\n\t\t\thistory.back();\n\t\t\treturn;\n\t\t}\n\t\tmode = \"replace\";\n\t\t// We'll replace the state async, to give the history.go the time to take affect first.\n\t\t//setTimeout(() => history.replaceState(state, '', url), 0)\n\t}\n\n\tif (mode) route.mode = undefined;\n\tconst search = new URLSearchParams(route.search).toString();\n\tconst url = (search ? `${path}?${search}` : path) + route.hash;\n\n\tif (mode === \"push\" || (!mode && !isSamePage(path, state))) {\n\t\tstateRoute.depth++; // stateRoute === state.route\n\t\thistory.pushState(state, \"\", url);\n\t\troute.nav = \"push\";\n\t\troute.depth = stateRoute.depth;\n\t} else {\n\t\t// Default to `push` when the URL changed or top-level state keys changed.\n\t\thistory.replaceState(state, \"\", url);\n\t}\n}\n\n// This deferred-mode observer will update the URL and history based on `route` changes.\nobserve(updateHistory);\n\n/**\n * Restore and store the vertical and horizontal scroll position for\n * the parent element to the page state.\n *\n * @param {string} name - A unique (within this page) name for this\n * scrollable element. Defaults to 'main'.\n *\n * The scroll position will be persisted in `route.aux.scroll.<name>`.\n */\nexport function persistScroll(name = \"main\") {\n\tconst el = getParentElement();\n\tel.addEventListener(\"scroll\", onScroll);\n\tclean(() => el.removeEventListener(\"scroll\", onScroll));\n\n\tconst restore = unproxy(route).aux.scroll?.name;\n\tif (restore) {\n\t\tObject.assign(el, restore);\n\t}\n\n\tfunction onScroll() {\n\t\troute.mode = \"replace\";\n\t\tif (!route.aux.scroll) route.aux.scroll = {};\n\t\troute.aux.scroll[name] = {\n\t\t\tscrollTop: el.scrollTop,\n\t\t\tscrollLeft: el.scrollLeft,\n\t\t};\n\t}\n}\n"
|
|
5
|
+
"import {clean, getParentElement, $, proxy, runQueue, unproxy, copy, merge, clone, leakScope} from \"./aberdeen.js\";\n\ntype NavType = \"load\" | \"back\" | \"forward\" | \"go\";\n\n/**\n* The class for the global `route` object.\n*/\nexport interface Route {\n\t/** The current path of the URL as a string. For instance `\"/\"` or `\"/users/123/feed\"`. Paths are normalized to always start with a `/` and never end with a `/` (unless it's the root path). */\n\tpath: string;\n\t/** An convenience array containing path segments, mapping to `path`. For instance `[]` (for `\"/\"`) or `['users', '123', 'feed']` (for `\"/users/123/feed\"`). */\n\tp: string[];\n\t/** The hash fragment including the leading `#`, or an empty string. For instance `\"#my_section\"` or `\"\"`. */\n\thash: string;\n\t/** The query string interpreted as search parameters. So `\"a=x&b=y\"` becomes `{a: \"x\", b: \"y\"}`. */\n\tsearch: Record<string, string>;\n\t/** An object to be used for any additional data you want to associate with the current page. Data should be JSON-compatible. */\n\tstate: Record<string, any>;\n\t/** The navigation depth of the current session. Starts at 1. Writing to this property has no effect. */\n\tdepth: number;\n\t/** The navigation action that got us to this page. Writing to this property has no effect.\n\t- `\"load\"`: An initial page load.\n\t- `\"back\"` or `\"forward\"`: When we navigated backwards or forwards in the stack.\n\t- `\"go\"`: When we added a new page on top of the stack.\n\tMostly useful for page transition animations. Writing to this property has no effect.\n\t*/\n\tnav: NavType;\n}\n\nlet log: (...args: any) => void = () => {};\n\n/**\n * Configure logging on route changes.\n * @param value `true` to enable logging to console, `false` to disable logging, or a custom logging function. Defaults to `false`.\n */\nexport function setLog(value: boolean | ((...args: any[]) => void)) {\n\tif (value === true) {\n\t\tlog = console.log.bind(console, 'aberdeen router');\n\t} else if (value === false) {\n\t\tlog = () => {};\n\t} else {\n\t\tlog = value;\n\t}\n}\n\nfunction getRouteFromBrowser(): Route {\n\treturn toCanonRoute({\n\t\tpath: location.pathname,\n\t\thash: location.hash,\n\t\tsearch: Object.fromEntries(new URLSearchParams(location.search)),\n\t\tstate: history.state?.state || {},\n\t}, \"load\", (history.state?.stack?.length || 0) + 1);\n}\n\n/**\n* Deep compare `a` and `b`. If `partial` is true, objects contained in `b` may be a subset\n* of their counterparts in `a` and still be considered equal.\n*/\nfunction equal(a: any, b: any, partial: boolean): boolean {\n\tif (a===b) return true;\n\tif (typeof a !== \"object\" || !a || typeof b !== \"object\" || !b) return false; // otherwise they would have been equal\n\tif (a.constructor !== b.constructor) return false;\n\tif (b instanceof Array) {\n\t\tif (a.length !== b.length) return false;\n\t\tfor(let i = 0; i < b.length; i++) {\n\t\t\tif (!equal(a[i], b[i], partial)) return false;\n\t\t}\n\t} else {\n\t\tfor(const k of Object.keys(b)) {\n\t\t\tif (!equal(a[k], b[k], partial)) return false;\n\t\t}\n\t\tif (!partial) {\n\t\t\tfor(const k of Object.keys(a)) {\n\t\t\t\tif (!b.hasOwnProperty(k)) return false;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction getUrl(target: Route) {\n\tconst search = new URLSearchParams(target.search).toString();\n\treturn (search ? `${target.path}?${search}` : target.path) + target.hash;\n}\n\nfunction toCanonRoute(target: Partial<Route>, nav: NavType, depth: number): Route {\n\tlet path = target.path || (target.p || []).join(\"/\") || \"/\";\n\tpath = (\"\"+path).replace(/\\/+$/, \"\");\n\tif (!path.startsWith(\"/\")) path = `/${path}`;\n\t\n\treturn {\n\t\tpath,\n\t\thash: target.hash && target.hash !==\"#\" ? (target.hash.startsWith(\"#\") ? target.hash : \"#\" + target.hash) : \"\",\n\t\tp: path.length > 1 ? path.slice(1).replace(/\\/+$/, \"\").split(\"/\") : [],\n\t\tnav,\n\t\tsearch: typeof target.search === 'object' && target.search ? clone(target.search) : {},\n\t\tstate: typeof target.state === 'object' && target.state ? clone(target.state) : {},\n\t\tdepth,\n\t};\n}\n\n\ntype RouteTarget = string | (string|number)[] | Partial<Omit<Omit<Route,\"p\">,\"search\"> & {\n\t/** An convenience array containing path segments, mapping to `path`. For instance `[]` (for `\"/\"`) or `['users', 123, 'feed']` (for `\"/users/123/feed\"`). Values may be integers but will be converted to strings.*/\n\tp: (string|number)[],\n\t/** The query string interpreted as search parameters. So `\"a=x&b=y\"` becomes `{a: \"x\", b: \"y\", c: 42}`. Values may be integers but will be converted to strings. */\n\tsearch: Record<string,string|number>,\n}>;\n\nfunction targetToPartial(target: RouteTarget) {\n\t// Convert shortcut values to objects\n\tif (typeof target === 'string') {\n\t\ttarget = {path: target};\n\t} else if (target instanceof Array) {\n\t\ttarget = {p: target};\n\t}\n\t// Convert numbers in p and search to strings\n\tif (target.p) {\n\t\ttarget.p = target.p.map(String);\n\t}\n\tif (target.search) {\n\t\tfor(const key of Object.keys(target.search)) {\n\t\t\ttarget.search[key] = String(target.search[key]);\n\t\t}\n\t}\n\treturn target as Partial<Route>;\n}\n\n\n/**\n* Navigate to a new URL by pushing a new history entry.\n* \n* Note that this happens synchronously, immediately updating `route` and processing any reactive updates based on that.\n* \n* @param target A subset of the {@link Route} properties to navigate to. If neither `p` nor `path` is given, the current path is used. For other properties, an empty/default value is assumed if not given. For convenience:\n* - You may pass a string instead of an object, which is interpreted as the `path`.\n* - You may pass an array instead of an object, which is interpreted as the `p` array.\n* - If you pass `p`, it may contain numbers, which will be converted to strings.\n* - If you pass `search`, its values may be numbers, which will be converted to strings.\n* \n* Examples:\n* ```js\n* // Navigate to /users/123\n* route.go(\"/users/123\");\n* \n* // Navigate to /users/123?tab=feed#top\n* route.go({p: [\"users\", 123], search: {tab: \"feed\"}, hash: \"top\"});\n* ```\n*/\nexport function go(target: RouteTarget): void {\n\tconst stack: string[] = history.state?.stack || [];\n\n\tprevStack = stack.concat(JSON.stringify(unproxy(current)));\n\t\n\tconst newRoute: Route = toCanonRoute(targetToPartial(target), \"go\", prevStack.length + 1);\n\tcopy(current, newRoute);\n\t\n\tlog('go', newRoute);\n\thistory.pushState({state: newRoute.state, stack: prevStack}, \"\", getUrl(newRoute));\n\t\n\trunQueue();\n}\n\n/**\n * Modify the current route by merging `target` into it (using {@link merge}), pushing a new history entry.\n * \n * This is useful for things like opening modals or side panels, where you want a browser back action to return to the previous state.\n * \n * @param target Same as for {@link go}, but merged into the current route instead deleting all state.\n */\nexport function push(target: RouteTarget): void {\n\tlet copy = clone(unproxy(current));\n\tmerge(copy, targetToPartial(target));\n\tgo(copy);\n}\n\n/**\n * Try to go back in history to the first entry that matches the given target. If none is found, the given state will replace the current page. This is useful for \"cancel\" or \"close\" actions that should return to the previous page if possible, but create a new page if not (for instance when arriving at the current page through a direct link).\n * \n * Consider using {@link up} to go up in the path hierarchy.\n * \n * @param target The target route to go back to. May be a subset of {@link Route}, or a string (for `path`), or an array of strings (for `p`).\n */\nexport function back(target: RouteTarget = {}): void {\n\tconst partial = targetToPartial(target);\n\tconst stack: string[] = history.state?.stack || [];\n\tfor(let i = stack.length - 1; i >= 0; i--) {\n\t\tconst histRoute: Route = JSON.parse(stack[i]);\n\t\tif (equal(histRoute, partial, true)) {\n\t\t\tconst pages = i - stack.length;\n\t\t\tlog(`back`, pages, histRoute);\n\t\t\thistory.go(pages);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tconst newRoute = toCanonRoute(partial, \"back\", stack.length + 1);\n\tlog(`back not found, replacing`, partial);\n\tcopy(current, newRoute);\n}\n\n/**\n* Navigate up in the path hierarchy, by going back to the first history entry\n* that has a shorter path than the current one. If there's none, we just shorten\n* the current path.\n* \n* Note that going back in browser history happens asynchronously, so `route` will not be updated immediately.\n*/\nexport function up(stripCount: number = 1): void {\n\tconst currentP = unproxy(current).p;\n\tconst stack: string[] = history.state?.stack || [];\n\tfor(let i = stack.length - 1; i >= 0; i--) {\n\t\tconst histRoute: Route = JSON.parse(stack[i]);\n\t\tif (histRoute.p.length < currentP.length && equal(histRoute.p, currentP.slice(0, histRoute.p.length), false)) {\n\t\t\t// This route is shorter and matches the start of the current path\n\t\t\tlog(`up to ${i+1} / ${stack.length}`, histRoute);\n\t\t\thistory.go(i - stack.length);\n\t\t\treturn;\n\t\t}\n\t}\n\t// Replace current route with /\n\tconst newRoute = toCanonRoute({p: currentP.slice(0, currentP.length - stripCount)}, \"back\", stack.length + 1);\n\tlog(`up not found, replacing`, newRoute);\n\tcopy(current, newRoute);\n}\n\n/**\n* Restore and store the vertical and horizontal scroll position for\n* the parent element to the page state.\n*\n* @param {string} name - A unique (within this page) name for this\n* scrollable element. Defaults to 'main'.\n*\n* The scroll position will be persisted in `route.aux.scroll.<name>`.\n*/\nexport function persistScroll(name = \"main\") {\n\tconst el = getParentElement();\n\tel.addEventListener(\"scroll\", onScroll);\n\tclean(() => el.removeEventListener(\"scroll\", onScroll));\n\t\n\tconst restore = unproxy(current).state.scroll?.[name];\n\tif (restore) {\n\t\tlog(\"restoring scroll\", name, restore);\n\t\tObject.assign(el, restore);\n\t}\n\t\n\tfunction onScroll() {\n\t\t(current.state.scroll ||= {})[name] = {\n\t\t\tscrollTop: el.scrollTop,\n\t\t\tscrollLeft: el.scrollLeft,\n\t\t};\n\t}\n}\n\nlet prevStack: string[];\n\n/**\n* The global {@link Route} object reflecting the current URL and browser history state. Changes you make to this affect the current browser history item (modifying the URL if needed).\n*/\nexport const current: Route = proxy({}) as Route;\n\n/**\n * Reset the router to its initial state, based on the current browser state. Intended for testing purposes only.\n * @internal\n * */\nexport function reset() {\n\tprevStack = history.state?.stack || [];\n\tconst initRoute = getRouteFromBrowser();\n\tlog('initial', initRoute);\n\tcopy(unproxy(current), initRoute);\n}\nreset();\n\n// Handle browser history back and forward\nwindow.addEventListener(\"popstate\", function(event: PopStateEvent) {\n\tconst newRoute = getRouteFromBrowser();\n\t\n\t// If the stack length changes, and at least the top-most shared entry is the same,\n\t// we'll interpret this as a \"back\" or \"forward\" navigation.\n\tconst stack: string[] = history.state?.stack || [];\n\tif (stack.length !== prevStack.length) {\n\t\tconst maxIndex = Math.min(prevStack.length, stack.length) - 1;\n\t\tif (maxIndex < 0 || stack[maxIndex] === prevStack[maxIndex]) {\n\t\t\tnewRoute.nav = stack.length < prevStack.length ? \"back\" : \"forward\";\n\t\t}\n\t}\n\t// else nav will be \"load\"\n\t\n\tprevStack = stack;\n\tlog('popstate', newRoute);\n\tcopy(current, newRoute);\n\t\n\trunQueue();\n});\n\n// Make sure these observers are never cleaned up, not even by `unmountAll`.\nleakScope(() => {\n\t// Sync `p` to `path`. We need to do this in a separate, higher-priority observer,\n\t// so that setting `route.p` will not be immediately overruled by the pre-existing `route.path`.\n\t$(() => {\n\t\tcurrent.path = \"/\" + Array.from(current.p).join(\"/\");\n\t});\n\n\t// Do a replaceState based on changes to proxy\n\t$(() => {\n\n\t\t// First normalize `route`\n\t\tconst stack = history.state?.stack || [];\n\t\tconst newRoute = toCanonRoute(current, unproxy(current).nav, stack.length + 1);\n\t\tcopy(current, newRoute);\n\t\t\n\t\t// Then replace the current browser state if something actually changed\n\t\tconst state = {state: newRoute.state, stack};\n\t\tconst url = getUrl(newRoute);\n\t\tif (url !== location.pathname + location.search + location.hash || !equal(history.state, state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CAGP,IAAM,EAAQ,QAAQ,OAAO,OAAS,CAAC,EACjC,EAAW,EAAa,EAAS,EAAQ,CAAO,EAAE,IAAK,EAAM,OAAS,CAAC,EAC7E,EAAK,EAAS,CAAQ,EAGtB,IAAM,EAAQ,CAAC,MAAO,EAAS,MAAO,OAAK,EACrC,EAAM,EAAO,CAAQ,EAC3B,GAAI,IAAQ,SAAS,SAAW,SAAS,OAAS,SAAS,OAAS,EAAM,QAAQ,MAAO,EAAO,EAAK,EACpG,EAAI,eAAgB,EAAU,EAAO,CAAG,EACxC,QAAQ,aAAa,EAAO,GAAI,CAAG,EAEpC,EACD",
|
|
8
|
+
"debugId": "B6ADEE6973F8780664756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aberdeen",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"author": "Frank van Viegen",
|
|
5
5
|
"main": "dist-min/aberdeen.js",
|
|
6
6
|
"devDependencies": {
|
|
@@ -30,6 +30,11 @@
|
|
|
30
30
|
"development": "./dist/prediction.js",
|
|
31
31
|
"types": "./dist/prediction.d.ts"
|
|
32
32
|
},
|
|
33
|
+
"./dispatcher": {
|
|
34
|
+
"default": "./dist-min/dispatcher.js",
|
|
35
|
+
"development": "./dist/dispatcher.js",
|
|
36
|
+
"types": "./dist/dispatcher.d.ts"
|
|
37
|
+
},
|
|
33
38
|
"./package.json": "./package.json"
|
|
34
39
|
},
|
|
35
40
|
"description": "Build fast reactive UIs in pure TypeScript/JavaScript without a virtual DOM.",
|