aberdeen 1.17.0 → 2.0.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.
Files changed (139) hide show
  1. package/dist/src/aberdeen.d.ts +928 -944
  2. package/dist/src/aberdeen.js +1693 -1704
  3. package/dist/src/aberdeen.js.map +3 -3
  4. package/dist/src/index.d.ts +12 -0
  5. package/dist/src/index.js +11 -0
  6. package/dist/src/index.js.map +10 -0
  7. package/dist/src/prediction.d.ts +7 -4
  8. package/dist/src/prediction.js +18 -23
  9. package/dist/src/prediction.js.map +3 -3
  10. package/dist/src/route.d.ts +112 -99
  11. package/dist/src/route.js +254 -254
  12. package/dist/src/route.js.map +3 -3
  13. package/dist/src/server-dom.d.ts +158 -0
  14. package/dist/src/server-dom.js +458 -0
  15. package/dist/src/server-dom.js.map +10 -0
  16. package/dist/src/server.d.ts +55 -0
  17. package/dist/src/server.js +25 -0
  18. package/dist/src/server.js.map +10 -0
  19. package/dist/src/transitions.js +7 -4
  20. package/dist/src/transitions.js.map +3 -3
  21. package/dist/tests/environment.d.ts +24 -0
  22. package/dist/tests/{fakedom.js → environment.js} +239 -288
  23. package/dist/tests/environment.js.map +11 -0
  24. package/dist/tests/helpers.d.ts +15 -3
  25. package/dist/tests/helpers.js +277 -306
  26. package/dist/tests/helpers.js.map +6 -5
  27. package/dist-docs/Tutorial/index.html +30 -30
  28. package/dist-docs/aberdeen/Aberdeen/index.html +350 -0
  29. package/dist-docs/aberdeen/InitOptions/index.html +4 -0
  30. package/dist-docs/aberdeen/KeyToString/index.html +2 -0
  31. package/dist-docs/aberdeen/PromiseProxy/index.html +6 -6
  32. package/dist-docs/aberdeen/SortKeyType/index.html +2 -0
  33. package/dist-docs/aberdeen/TargetType/index.html +2 -0
  34. package/dist-docs/aberdeen/ValueRef/index.html +2 -0
  35. package/dist-docs/aberdeen/WindowLike/index.html +5 -0
  36. package/dist-docs/aberdeen/{clone → createA}/index.html +10 -5
  37. package/dist-docs/aberdeen/index.html +13 -54
  38. package/dist-docs/assets/aberdeen/aberdeen.d.ts +928 -944
  39. package/dist-docs/assets/aberdeen/aberdeen.js +1693 -1704
  40. package/dist-docs/assets/aberdeen/aberdeen.js.map +3 -3
  41. package/dist-docs/assets/aberdeen/index.d.ts +12 -0
  42. package/dist-docs/assets/aberdeen/index.js +11 -0
  43. package/dist-docs/assets/aberdeen/index.js.map +10 -0
  44. package/dist-docs/assets/aberdeen/prediction.d.ts +7 -4
  45. package/dist-docs/assets/aberdeen/prediction.js +18 -23
  46. package/dist-docs/assets/aberdeen/prediction.js.map +3 -3
  47. package/dist-docs/assets/aberdeen/route.d.ts +112 -99
  48. package/dist-docs/assets/aberdeen/route.js +254 -254
  49. package/dist-docs/assets/aberdeen/route.js.map +3 -3
  50. package/dist-docs/assets/aberdeen/server-dom.d.ts +158 -0
  51. package/dist-docs/assets/aberdeen/server-dom.js +458 -0
  52. package/dist-docs/assets/aberdeen/server-dom.js.map +10 -0
  53. package/dist-docs/assets/aberdeen/server.d.ts +55 -0
  54. package/dist-docs/assets/aberdeen/server.js +25 -0
  55. package/dist-docs/assets/aberdeen/server.js.map +10 -0
  56. package/dist-docs/assets/aberdeen/transitions.js +7 -4
  57. package/dist-docs/assets/aberdeen/transitions.js.map +3 -3
  58. package/dist-docs/assets/navigation.js +1 -1
  59. package/dist-docs/assets/search.js +1 -1
  60. package/dist-docs/dispatcher/Dispatcher/index.html +5 -6
  61. package/dist-docs/dispatcher/MATCH_FAILED/index.html +2 -2
  62. package/dist-docs/dispatcher/MATCH_REST/index.html +2 -2
  63. package/dist-docs/dispatcher/index.html +2 -2
  64. package/dist-docs/hierarchy.html +1 -1
  65. package/dist-docs/index-1/index.html +2 -0
  66. package/dist-docs/index.html +2 -2
  67. package/dist-docs/media/CHANGELOG.md +14 -2
  68. package/dist-docs/modules.html +1 -1
  69. package/dist-docs/prediction/applyCanon/index.html +4 -3
  70. package/dist-docs/prediction/applyPrediction/index.html +4 -3
  71. package/dist-docs/prediction/index.html +2 -2
  72. package/dist-docs/route/Route/index.html +9 -9
  73. package/dist-docs/route/RouteApi/index.html +60 -0
  74. package/dist-docs/route/index.html +6 -15
  75. package/dist-docs/route/init/index.html +5 -0
  76. package/dist-docs/server/RenderToStringOptions/index.html +6 -0
  77. package/dist-docs/server/RenderToStringResult/index.html +6 -0
  78. package/dist-docs/server/index.html +4 -0
  79. package/dist-docs/server/renderToString/index.html +6 -0
  80. package/dist-docs/sitemap.xml +51 -155
  81. package/dist-docs/transitions/grow/index.html +2 -2
  82. package/dist-docs/transitions/index.html +2 -2
  83. package/dist-docs/transitions/shrink/index.html +2 -2
  84. package/package.json +17 -7
  85. package/skill/SKILL.md +28 -28
  86. package/skill/aberdeen.md +471 -3448
  87. package/skill/dispatcher.md +6 -16
  88. package/skill/prediction.md +17 -5
  89. package/skill/route.md +95 -77
  90. package/skill/transitions.md +3 -3
  91. package/src/aberdeen.ts +1226 -740
  92. package/src/index.ts +13 -0
  93. package/src/prediction.ts +25 -24
  94. package/src/route.ts +192 -142
  95. package/src/server-dom.ts +508 -0
  96. package/src/server.ts +74 -0
  97. package/src/transitions.ts +9 -3
  98. package/dist/tests/fakedom.d.ts +0 -9
  99. package/dist/tests/fakedom.js.map +0 -10
  100. package/dist-docs/aberdeen/A/index.html +0 -115
  101. package/dist-docs/aberdeen/CUSTOM_DUMP/index.html +0 -7
  102. package/dist-docs/aberdeen/NO_COPY/index.html +0 -2
  103. package/dist-docs/aberdeen/OPAQUE/index.html +0 -12
  104. package/dist-docs/aberdeen/clean/index.html +0 -11
  105. package/dist-docs/aberdeen/copy/index.html +0 -22
  106. package/dist-docs/aberdeen/count/index.html +0 -7
  107. package/dist-docs/aberdeen/cssVars/index.html +0 -11
  108. package/dist-docs/aberdeen/darkMode/index.html +0 -9
  109. package/dist-docs/aberdeen/default/index.html +0 -341
  110. package/dist-docs/aberdeen/derive/index.html +0 -18
  111. package/dist-docs/aberdeen/disableCreateDestroy/index.html +0 -6
  112. package/dist-docs/aberdeen/dump/index.html +0 -11
  113. package/dist-docs/aberdeen/insertCss/index.html +0 -30
  114. package/dist-docs/aberdeen/insertGlobalCss/index.html +0 -19
  115. package/dist-docs/aberdeen/invertString/index.html +0 -13
  116. package/dist-docs/aberdeen/isEmpty/index.html +0 -12
  117. package/dist-docs/aberdeen/map/index.html +0 -26
  118. package/dist-docs/aberdeen/merge/index.html +0 -11
  119. package/dist-docs/aberdeen/mount/index.html +0 -17
  120. package/dist-docs/aberdeen/multiMap/index.html +0 -28
  121. package/dist-docs/aberdeen/onEach/index.html +0 -19
  122. package/dist-docs/aberdeen/partition/index.html +0 -36
  123. package/dist-docs/aberdeen/peek/index.html +0 -40
  124. package/dist-docs/aberdeen/proxy/index.html +0 -35
  125. package/dist-docs/aberdeen/ref/index.html +0 -13
  126. package/dist-docs/aberdeen/runQueue/index.html +0 -13
  127. package/dist-docs/aberdeen/setErrorHandler/index.html +0 -16
  128. package/dist-docs/aberdeen/setSpacingCssVars/index.html +0 -8
  129. package/dist-docs/aberdeen/unmountAll/index.html +0 -5
  130. package/dist-docs/aberdeen/unproxy/index.html +0 -11
  131. package/dist-docs/route/back/index.html +0 -4
  132. package/dist-docs/route/current/index.html +0 -2
  133. package/dist-docs/route/go/index.html +0 -14
  134. package/dist-docs/route/interceptLinks/index.html +0 -8
  135. package/dist-docs/route/matchCurrent/index.html +0 -10
  136. package/dist-docs/route/persistScroll/index.html +0 -6
  137. package/dist-docs/route/push/index.html +0 -6
  138. package/dist-docs/route/setLog/index.html +0 -3
  139. package/dist-docs/route/up/index.html +0 -5
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Default browser entry point for Aberdeen.
3
+ *
4
+ * It exports a ready-to-use Aberdeen instance (`A`) bound to the global `window`, so you can
5
+ * `import A from 'aberdeen'` and start building UI with zero setup. Advanced users (and the
6
+ * `aberdeen/server` SSR entry) can instead import {@link createA} to create instances bound to a
7
+ * specific window, including multiple isolated instances.
8
+ */
9
+ export { createA } from "./aberdeen.js";
10
+ export type { Aberdeen, WindowLike, InitOptions, ValueRef, PromiseProxy } from "./aberdeen.js";
11
+ import { createA } from "./aberdeen.js";
12
+
13
+ export default createA(typeof window !== "undefined" ? (window as any) : undefined);
package/src/prediction.ts CHANGED
@@ -1,21 +1,18 @@
1
- import {
2
- defaultEmitHandler,
3
- withEmitHandler,
4
- EMPTY,
5
- MAP_SIZE_SYMBOL,
6
- } from "./aberdeen.js";
7
- import type { TargetType } from "./aberdeen.js";
1
+ // This module operates on a specific Aberdeen instance, which is passed as the first argument
2
+ // (`A`) to its public functions. `A` provides the emit handlers and the EMPTY/MAP_SIZE_SYMBOL
3
+ // markers it needs.
4
+ type Aberdeen = any;
8
5
 
9
6
  /**
10
7
  * Represents a set of changes that can be applied to proxied objects.
11
8
  * This is an opaque type - its internal structure is not part of the public API.
12
9
  * @private
13
10
  */
14
- export type Patch = Map<TargetType, Map<any, [any, any]>>;
11
+ export type Patch = Map<any, Map<any, [any, any]>>;
15
12
 
16
- function recordPatch(func: () => void): Patch {
13
+ function recordPatch(A: Aberdeen, func: () => void): Patch {
17
14
  const recordingPatch = new Map();
18
- withEmitHandler((target, index, newData, oldData) => {
15
+ A.withEmitHandler((target: any, index: any, newData: any, oldData: any) => {
19
16
  addToPatch(recordingPatch, target, index, newData, oldData);
20
17
  }, func);
21
18
  return recordingPatch;
@@ -23,7 +20,7 @@ function recordPatch(func: () => void): Patch {
23
20
 
24
21
  function addToPatch(
25
22
  patch: Patch,
26
- collection: TargetType,
23
+ collection: any,
27
24
  index: any,
28
25
  newData: any,
29
26
  oldData: any,
@@ -39,10 +36,10 @@ function addToPatch(
39
36
  else collectionMap.set(index, [newData, oldData0]);
40
37
  }
41
38
 
42
- function emitPatch(patch: Patch) {
39
+ function emitPatch(A: Aberdeen, patch: Patch) {
43
40
  for (const [collection, collectionMap] of patch) {
44
41
  for (const [index, [newData, oldData]] of collectionMap) {
45
- defaultEmitHandler(collection, index, newData, oldData);
42
+ A.defaultEmitHandler(collection, index, newData, oldData);
46
43
  }
47
44
  }
48
45
  }
@@ -61,11 +58,12 @@ function mergePatch(target: Patch, source: Patch, reverse = false) {
61
58
  }
62
59
  }
63
60
 
64
- function silentlyApplyPatch(patch: Patch, force = false): boolean {
61
+ function silentlyApplyPatch(A: Aberdeen, patch: Patch, force = false): boolean {
62
+ const EMPTY = A.EMPTY;
65
63
  for (const [collection, collectionMap] of patch) {
66
64
  for (const [index, [newData, oldData]] of collectionMap) {
67
65
  // MAP_SIZE_SYMBOL is synthetic - size is derived from add/delete operations
68
- if (index === MAP_SIZE_SYMBOL) continue;
66
+ if (index === A.MAP_SIZE_SYMBOL) continue;
69
67
  const actualData =
70
68
  collection instanceof Map
71
69
  ? collection.has(index)
@@ -76,7 +74,7 @@ function silentlyApplyPatch(patch: Patch, force = false): boolean {
76
74
  : EMPTY;
77
75
  if (actualData !== oldData) {
78
76
  if (force)
79
- setTimeout(() => {
77
+ (A.window?.setTimeout ?? setTimeout)(() => {
80
78
  throw new Error(
81
79
  `Applying invalid patch: data ${String(actualData)} is unequal to expected old data ${String(oldData)} for index ${String(index)}`,
82
80
  );
@@ -87,7 +85,7 @@ function silentlyApplyPatch(patch: Patch, force = false): boolean {
87
85
  }
88
86
  for (const [collection, collectionMap] of patch) {
89
87
  for (const [index, [newData, oldData]] of collectionMap) {
90
- if (index === MAP_SIZE_SYMBOL) continue;
88
+ if (index === A.MAP_SIZE_SYMBOL) continue;
91
89
  if (collection instanceof Map) {
92
90
  if (newData === EMPTY) collection.delete(index);
93
91
  else collection.set(index, newData);
@@ -106,15 +104,16 @@ const appliedPredictions: Array<Patch> = [];
106
104
  * Run the provided function, while treating all changes to Observables as predictions,
107
105
  * meaning they will be reverted when changes come back from the server (or some other
108
106
  * async source).
107
+ * @param A The Aberdeen instance (the default export of `aberdeen`, or one from `init`).
109
108
  * @param predictFunc The function to run. It will generally modify some Observables
110
109
  * to immediately reflect state (as closely as possible) that we expect the server
111
110
  * to communicate back to us later on.
112
111
  * @returns A `Patch` object. Don't modify it. This is only meant to be passed to `applyCanon`.
113
112
  */
114
- export function applyPrediction(predictFunc: () => void): Patch {
115
- const patch = recordPatch(predictFunc);
113
+ export function applyPrediction(A: Aberdeen, predictFunc: () => void): Patch {
114
+ const patch = recordPatch(A, predictFunc);
116
115
  appliedPredictions.push(patch);
117
- emitPatch(patch);
116
+ emitPatch(A, patch);
118
117
  return patch;
119
118
  }
120
119
 
@@ -127,6 +126,7 @@ export function applyPrediction(predictFunc: () => void): Patch {
127
126
  *
128
127
  * All of this is done such that redraws are only triggered if the overall effect is an
129
128
  * actual change to an `Observable`.
129
+ * @param A The Aberdeen instance (the default export of `aberdeen`, or one from `init`).
130
130
  * @param canonFunc The function to run without any predictions applied. This will typically
131
131
  * make authoritative changes to the data, based on a server response.
132
132
  * @param dropPredictions An optional list of predictions (as returned by `applyPrediction`)
@@ -134,22 +134,23 @@ export function applyPrediction(predictFunc: () => void): Patch {
134
134
  * you'd want to drop the prediction that was done for that request.
135
135
  */
136
136
  export function applyCanon(
137
+ A: Aberdeen,
137
138
  canonFunc?: () => void,
138
139
  dropPredictions: Array<Patch> = [],
139
140
  ) {
140
141
  const resultPatch = new Map();
141
142
  for (const prediction of appliedPredictions)
142
143
  mergePatch(resultPatch, prediction, true);
143
- silentlyApplyPatch(resultPatch, true);
144
+ silentlyApplyPatch(A, resultPatch, true);
144
145
 
145
146
  for (const prediction of dropPredictions) {
146
147
  const pos = appliedPredictions.indexOf(prediction);
147
148
  if (pos >= 0) appliedPredictions.splice(pos, 1);
148
149
  }
149
- if (canonFunc) mergePatch(resultPatch, recordPatch(canonFunc));
150
+ if (canonFunc) mergePatch(resultPatch, recordPatch(A, canonFunc));
150
151
 
151
152
  for (let idx = 0; idx < appliedPredictions.length; idx++) {
152
- if (silentlyApplyPatch(appliedPredictions[idx])) {
153
+ if (silentlyApplyPatch(A, appliedPredictions[idx])) {
153
154
  mergePatch(resultPatch, appliedPredictions[idx]);
154
155
  } else {
155
156
  appliedPredictions.splice(idx, 1);
@@ -157,5 +158,5 @@ export function applyCanon(
157
158
  }
158
159
  }
159
160
 
160
- emitPatch(resultPatch);
161
+ emitPatch(A, resultPatch);
161
162
  }
package/src/route.ts CHANGED
@@ -1,5 +1,3 @@
1
- import A, {leakScope} from "./aberdeen.js";
2
-
3
1
  type NavType = "load" | "back" | "forward" | "go" | "push";
4
2
 
5
3
  /**
@@ -28,13 +26,148 @@ export interface Route {
28
26
  nav: NavType;
29
27
  }
30
28
 
31
- let log: (...args: any) => void = () => {};
29
+ type RouteTarget = string | (string|number)[] | Partial<Omit<Omit<Route,"p">,"search"> & {
30
+ /** 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.*/
31
+ p: (string|number)[],
32
+ /** 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. */
33
+ search: Record<string,string|number>,
34
+ }>;
35
+
36
+ /**
37
+ * The router API returned by {@link init}, bound to a specific Aberdeen instance's window.
38
+ */
39
+ export interface RouteApi {
40
+ /**
41
+ * 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).
42
+ */
43
+ current: Route;
44
+ /**
45
+ * Configure logging on route changes.
46
+ * @param value `true` to enable logging to console, `false` to disable logging, or a custom logging function. Defaults to `false`.
47
+ */
48
+ setLog(value: boolean | ((...args: any[]) => void)): void;
49
+ /**
50
+ * Navigate to a new URL by pushing a new history entry.
51
+ *
52
+ * Note that this happens synchronously, immediately updating `route` and processing any reactive updates based on that.
53
+ *
54
+ * @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:
55
+ * - You may pass a string instead of an object, which is interpreted as the `path`.
56
+ * - You may pass an array instead of an object, which is interpreted as the `p` array.
57
+ * - If you pass `p`, it may contain numbers, which will be converted to strings.
58
+ * - If you pass `search`, its values may be numbers, which will be converted to strings.
59
+ *
60
+ * Examples:
61
+ * ```js
62
+ * // Navigate to /users/123
63
+ * route.go("/users/123");
64
+ *
65
+ * // Navigate to /users/123?tab=feed#top
66
+ * route.go({p: ["users", 123], search: {tab: "feed"}, hash: "top"});
67
+ * ```
68
+ */
69
+ go(target: RouteTarget, nav?: NavType): void;
70
+ /**
71
+ * Returns `true` if the current route matches `target`.
72
+ *
73
+ * Path must match exactly. Any search params specified in `target` must be present
74
+ * in the current URL, but extra params in the current URL are allowed.
75
+ *
76
+ * Reactive: only reevaluates when the path changes to/from the target path, and
77
+ * when target k/v search pairs are (un)set.
78
+ *
79
+ * Primary usage: 'active' status for menu items.
80
+ *
81
+ * @example
82
+ * ```js
83
+ * // This example assumes interceptLinks() has been called
84
+ * A('a.my-button text=Users href=/users .is-active=', route.matchCurrent('/users'));
85
+ *
86
+ * // Alternatively a route object can be given
87
+ * route.matchCurrent({path: '/users', search: {tab: 'profile'}});
88
+ * ```
89
+ */
90
+ matchCurrent(target: RouteTarget): boolean;
91
+ /**
92
+ * Modify the current route by merging `target` into it (using {@link aberdeen!Aberdeen.merge | A.merge}), pushing a new history entry.
93
+ *
94
+ * This is useful for things like opening modals or side panels, where you want a browser back action to return to the previous state.
95
+ *
96
+ * @param target Same as for {@link go}, but merged into the current route instead deleting all state.
97
+ * @param nav The navigation type to use. Defaults to `undefined`, meaning the navigation type is unchanged from the current route,
98
+ * preventing unwanted page transition animations.
99
+ */
100
+ push(target: RouteTarget, nav?: NavType): void;
101
+ /**
102
+ * 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).
103
+ *
104
+ * Consider using {@link up} to go up in the path hierarchy.
105
+ *
106
+ * @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`).
107
+ */
108
+ back(target?: RouteTarget): void;
109
+ /**
110
+ * Navigate up in the path hierarchy, by going back to the first history entry
111
+ * that has a shorter path than the current one. If there's none, we just shorten
112
+ * the current path.
113
+ *
114
+ * Note that going back in browser history happens asynchronously, so `route` will not be updated immediately.
115
+ */
116
+ up(stripCount?: number): void;
117
+ /** @internal */
118
+ reset(): void;
119
+ /**
120
+ * Run the router's browser-dependent setup: sync the `route` proxy to the current URL,
121
+ * start listening for `popstate`, and start the observers that keep the browser URL in sync
122
+ * with `route`. Safe to call multiple times (subsequent calls are no-ops).
123
+ *
124
+ * This runs automatically on import in a browser. Outside a browser it is a no-op until a
125
+ * window has been provided via `setWindow`, after which you should call it yourself (or call
126
+ * `reset` to re-sync to a new request URL). See the `aberdeen/server` SSR entry point.
127
+ * @internal
128
+ */
129
+ initRouter(): void;
130
+ /**
131
+ * Restore and store the vertical and horizontal scroll position for
132
+ * the parent element to the page state.
133
+ *
134
+ * @param {string} name - A unique (within this page) name for this
135
+ * scrollable element. Defaults to 'main'.
136
+ *
137
+ * The scroll position will be persisted in `route.aux.scroll.<name>`.
138
+ */
139
+ persistScroll(name?: string): void;
140
+ /**
141
+ * Intercept clicks and Enter key presses on links (`<a>` tags) and use Aberdeen routing
142
+ * instead of browser navigation for local paths (paths without a protocol or host).
143
+ *
144
+ * This allows you to use regular HTML anchor tags for navigation without needing to
145
+ * manually attach click handlers to each link.
146
+ *
147
+ * @example
148
+ * ```js
149
+ * // In your root component:
150
+ * route.interceptLinks();
151
+ *
152
+ * // Now you can use regular anchor tags:
153
+ * A('a text=About href=/corporate/about');
154
+ * ```
155
+ */
156
+ interceptLinks(): void;
157
+ }
32
158
 
33
159
  /**
34
- * Configure logging on route changes.
35
- * @param value `true` to enable logging to console, `false` to disable logging, or a custom logging function. Defaults to `false`.
160
+ * Initialise routing for an Aberdeen instance and return the router API, bound to that
161
+ * instance's window. In the browser, use the default instance: `init(A)`. For server-side
162
+ * rendering, pass the instance provided by `aberdeen/server`'s render callback.
163
+ *
164
+ * @param A An Aberdeen instance (the default export of `aberdeen`, or one from `init`).
36
165
  */
37
- export function setLog(value: boolean | ((...args: any[]) => void)) {
166
+ export function init(A: any): RouteApi {
167
+
168
+ let log: (...args: any) => void = () => {};
169
+
170
+ function setLog(value: boolean | ((...args: any[]) => void)) {
38
171
  if (value === true) {
39
172
  log = console.log.bind(console, 'aberdeen router');
40
173
  } else if (value === false) {
@@ -44,18 +177,20 @@ export function setLog(value: boolean | ((...args: any[]) => void)) {
44
177
  }
45
178
  }
46
179
 
47
- declare const ABERDEEN_FAKE_WINDOW: Window | undefined;
48
- const windowE = typeof ABERDEEN_FAKE_WINDOW !== 'undefined'? ABERDEEN_FAKE_WINDOW : window;
49
- const locationE = windowE.location;
50
- const historyE = windowE.history;
180
+ // The window/location/history are resolved lazily (rather than captured at import time) so
181
+ // that this module can be imported in a non-browser environment and have a window injected
182
+ // later via `setWindow` (see the `aberdeen/server` SSR entry point).
183
+ const windowE = () => A.window;
184
+ const locationE = () => A.window.location;
185
+ const historyE = () => A.window.history;
51
186
 
52
187
  function getRouteFromBrowser(): Route {
53
188
  return toCanonRoute({
54
- path: locationE.pathname,
55
- hash: locationE.hash,
56
- search: Object.fromEntries(new URLSearchParams(locationE.search)),
57
- state: historyE.state?.state || {},
58
- }, "load", (historyE.state?.stack?.length || 0) + 1);
189
+ path: locationE().pathname,
190
+ hash: locationE().hash,
191
+ search: Object.fromEntries(new URLSearchParams(locationE().search)),
192
+ state: historyE().state?.state || {},
193
+ }, "load", (historyE().state?.stack?.length || 0) + 1);
59
194
  }
60
195
 
61
196
  /**
@@ -106,13 +241,6 @@ function toCanonRoute(target: Partial<Route>, nav: NavType, depth: number): Rout
106
241
  }
107
242
 
108
243
 
109
- type RouteTarget = string | (string|number)[] | Partial<Omit<Omit<Route,"p">,"search"> & {
110
- /** 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.*/
111
- p: (string|number)[],
112
- /** 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. */
113
- search: Record<string,string|number>,
114
- }>;
115
-
116
244
  function targetToPartial(target: RouteTarget, undefinedOnExternal: true): Partial<Route> | undefined;
117
245
  function targetToPartial(target: RouteTarget): Partial<Route>;
118
246
 
@@ -121,10 +249,10 @@ function targetToPartial(target: RouteTarget, undefinedOnExternal: boolean=false
121
249
  // Convert shortcut values to objects
122
250
  if (typeof target === 'string') {
123
251
  // Parse using URL to handle both absolute and relative paths correctly
124
- const url = new URL(target, locationE.href);
125
- if (url.host !== locationE.host) {
252
+ const url = new URL(target, locationE().href);
253
+ if (url.host !== locationE().host) {
126
254
  if (undefinedOnExternal) return;
127
- throw new Error(`Unexpected external URL: ${url.host} != ${locationE.host}`);
255
+ throw new Error(`Unexpected external URL: ${url.host} != ${locationE().host}`);
128
256
  }
129
257
  target = {
130
258
  path: url.pathname,
@@ -147,29 +275,9 @@ function targetToPartial(target: RouteTarget, undefinedOnExternal: boolean=false
147
275
  }
148
276
 
149
277
 
150
- /**
151
- * Navigate to a new URL by pushing a new history entry.
152
- *
153
- * Note that this happens synchronously, immediately updating `route` and processing any reactive updates based on that.
154
- *
155
- * @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:
156
- * - You may pass a string instead of an object, which is interpreted as the `path`.
157
- * - You may pass an array instead of an object, which is interpreted as the `p` array.
158
- * - If you pass `p`, it may contain numbers, which will be converted to strings.
159
- * - If you pass `search`, its values may be numbers, which will be converted to strings.
160
- *
161
- * Examples:
162
- * ```js
163
- * // Navigate to /users/123
164
- * route.go("/users/123");
165
- *
166
- * // Navigate to /users/123?tab=feed#top
167
- * route.go({p: ["users", 123], search: {tab: "feed"}, hash: "top"});
168
- * ```
169
- */
170
- export function go(target: RouteTarget, nav: NavType = "go"): void {
278
+ function go(target: RouteTarget, nav: NavType = "go"): void {
171
279
  pendingGoOffset = 0;
172
- const stack: string[] = historyE.state?.stack || [];
280
+ const stack: string[] = historyE().state?.stack || [];
173
281
 
174
282
  prevStack = stack.concat(JSON.stringify(A.unproxy(current)));
175
283
 
@@ -177,32 +285,12 @@ export function go(target: RouteTarget, nav: NavType = "go"): void {
177
285
  A.copy(current, newRoute);
178
286
 
179
287
  log(nav, newRoute);
180
- historyE.pushState({state: newRoute.state, stack: prevStack}, "", getUrl(newRoute));
288
+ historyE().pushState({state: newRoute.state, stack: prevStack}, "", getUrl(newRoute));
181
289
 
182
290
  A.runQueue();
183
291
  }
184
292
 
185
- /**
186
- * Returns `true` if the current route matches `target`.
187
- *
188
- * Path must match exactly. Any search params specified in `target` must be present
189
- * in the current URL, but extra params in the current URL are allowed.
190
- *
191
- * Reactive: only reevaluates when the path changes to/from the target path, and
192
- * when target k/v search pairs are (un)set.
193
- *
194
- * Primary usage: 'active' status for menu items.
195
- *
196
- * @example
197
- * ```js
198
- * // This example assumes interceptLinks() has been called
199
- * A('a.my-button text=Users href=/users .is-active=', route.matchCurrent('/users'));
200
- *
201
- * // Alternatively a route object can be given
202
- * route.matchCurrent({path: '/users', search: {tab: 'profile'}});
203
- * ```
204
- */
205
- export function matchCurrent(target: RouteTarget): boolean {
293
+ function matchCurrent(target: RouteTarget): boolean {
206
294
  const partial = targetToPartial(target, true);
207
295
  if (!partial) return false; // External link
208
296
 
@@ -221,31 +309,15 @@ export function matchCurrent(target: RouteTarget): boolean {
221
309
  return true;
222
310
  }
223
311
 
224
- /**
225
- * Modify the current route by merging `target` into it (using {@link aberdeen.merge | A.merge}), pushing a new history entry.
226
- *
227
- * This is useful for things like opening modals or side panels, where you want a browser back action to return to the previous state.
228
- *
229
- * @param target Same as for {@link go}, but merged into the current route instead deleting all state.
230
- * @param nav The navigation type to use. Defaults to `undefined`, meaning the navigation type is unchanged from the current route,
231
- * preventing unwanted page transition animations.
232
- */
233
- export function push(target: RouteTarget, nav?: NavType): void {
312
+ function push(target: RouteTarget, nav?: NavType): void {
234
313
  const c = A.clone(A.unproxy(current));
235
314
  A.merge(c, targetToPartial(target));
236
315
  go(c, nav || c.nav);
237
316
  }
238
317
 
239
- /**
240
- * 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).
241
- *
242
- * Consider using {@link up} to go up in the path hierarchy.
243
- *
244
- * @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`).
245
- */
246
- export function back(target: RouteTarget = {}): void {
318
+ function back(target: RouteTarget = {}): void {
247
319
  const partial = targetToPartial(target);
248
- const stack: string[] = historyE.state?.stack || [];
320
+ const stack: string[] = historyE().state?.stack || [];
249
321
  const effectiveLen = stack.length + pendingGoOffset;
250
322
  for(let i = effectiveLen - 1; i >= 0; i--) {
251
323
  const histRoute: Route = JSON.parse(stack[i]);
@@ -262,16 +334,9 @@ export function back(target: RouteTarget = {}): void {
262
334
  A.copy(current, newRoute);
263
335
  }
264
336
 
265
- /**
266
- * Navigate up in the path hierarchy, by going back to the first history entry
267
- * that has a shorter path than the current one. If there's none, we just shorten
268
- * the current path.
269
- *
270
- * Note that going back in browser history happens asynchronously, so `route` will not be updated immediately.
271
- */
272
- export function up(stripCount: number = 1): void {
337
+ function up(stripCount: number = 1): void {
273
338
  const currentP = A.unproxy(current).p;
274
- const stack: string[] = historyE.state?.stack || [];
339
+ const stack: string[] = historyE().state?.stack || [];
275
340
  const effectiveLen = stack.length + pendingGoOffset;
276
341
  for(let i = effectiveLen - 1; i >= 0; i--) {
277
342
  const histRoute: Route = JSON.parse(stack[i]);
@@ -291,25 +356,22 @@ export function up(stripCount: number = 1): void {
291
356
 
292
357
  let prevStack: string[];
293
358
 
294
- // Track pending historyE.go() offset. Multiple back()/up() calls before the event loop
295
- // processes them are batched into a single historyE.go() via queueMicrotask.
359
+ // Track pending historyE().go() offset. Multiple back()/up() calls before the event loop
360
+ // processes them are batched into a single historyE().go() via queueMicrotask.
296
361
  let pendingGoOffset = 0;
297
362
 
298
363
  function scheduleHistoryGo(delta: number) {
299
364
  pendingGoOffset += delta;
300
- setTimeout(() => {
365
+ (A.window.setTimeout ?? setTimeout)(() => {
301
366
  if (pendingGoOffset) {
302
367
  const offset = pendingGoOffset;
303
368
  pendingGoOffset = 0;
304
- historyE.go(offset);
369
+ historyE().go(offset);
305
370
  }
306
371
  }, 0);
307
372
  }
308
373
 
309
- /**
310
- * 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).
311
- */
312
- export const current: Route = A.proxy({}) as Route;
374
+ const current: Route = A.proxy({}) as Route;
313
375
 
314
376
  // Proxied object with keys for the current path and "k=v" search pairs.
315
377
  // Used by matchCurrent to subscribe only to relevant route changes.
@@ -319,22 +381,28 @@ const currentRouteParts = A.proxy({} as Record<string,true>);
319
381
  * Reset the router to its initial state, based on the current browser state. Intended for testing purposes only.
320
382
  * @internal
321
383
  * */
322
- export function reset() {
323
- prevStack = historyE.state?.stack || [];
384
+ function reset() {
385
+ prevStack = historyE().state?.stack || [];
324
386
  const initRoute = getRouteFromBrowser();
325
387
  log('initial', initRoute);
326
388
  A.copy(A.unproxy(current), initRoute);
327
389
  }
328
- reset();
390
+ let routerInited = false;
391
+
392
+ function initRouter() {
393
+ if (routerInited || !A.window) return;
394
+ routerInited = true;
329
395
 
330
- // Handle browser history back and forward
331
- windowE.addEventListener("popstate", function(event: PopStateEvent) {
396
+ reset();
397
+
398
+ // Handle browser history back and forward
399
+ windowE().addEventListener("popstate", function(event: PopStateEvent) {
332
400
  pendingGoOffset = 0;
333
401
  const newRoute = getRouteFromBrowser();
334
402
 
335
403
  // If the stack length changes, and at least the top-most shared entry is the same,
336
404
  // we'll interpret this as a "back" or "forward" navigation.
337
- const stack: string[] = historyE.state?.stack || [];
405
+ const stack: string[] = historyE().state?.stack || [];
338
406
  if (stack.length !== prevStack.length) {
339
407
  const maxIndex = Math.min(prevStack.length, stack.length) - 1;
340
408
  if (maxIndex < 0 || stack[maxIndex] === prevStack[maxIndex]) {
@@ -351,7 +419,7 @@ windowE.addEventListener("popstate", function(event: PopStateEvent) {
351
419
  });
352
420
 
353
421
  // Make sure these observers are never cleaned up, not even by `unmountAll`.
354
- leakScope(() => {
422
+ A.leakScope(() => {
355
423
  // Sync `p` to `path`. We need to do this in a separate, higher-priority observer,
356
424
  // so that setting `route.p` will not be immediately overruled by the pre-existing `route.path`.
357
425
  A(() => {
@@ -361,16 +429,16 @@ leakScope(() => {
361
429
  // Do a replaceState based on changes to A.proxy
362
430
  A(() => {
363
431
  // First normalize `route`
364
- const stack = historyE.state?.stack || [];
432
+ const stack = historyE().state?.stack || [];
365
433
  const newRoute = toCanonRoute(current, A.unproxy(current).nav, stack.length + 1);
366
434
  A.copy(current, newRoute);
367
435
 
368
436
  // Then replace the current browser state if something actually changed
369
437
  const state = {state: newRoute.state, stack};
370
438
  const url = getUrl(newRoute);
371
- if (url !== locationE.pathname + locationE.search + locationE.hash || !equal(historyE.state, state, false)) {
439
+ if (url !== locationE().pathname + locationE().search + locationE().hash || !equal(historyE().state, state, false)) {
372
440
  log('replaceState', newRoute, state, url);
373
- historyE.replaceState(state, "", url);
441
+ historyE().replaceState(state, "", url);
374
442
  }
375
443
  });
376
444
 
@@ -384,18 +452,13 @@ leakScope(() => {
384
452
  A.copy(currentRouteParts, n);
385
453
  });
386
454
  });
455
+ }
387
456
 
457
+ // Initialise immediately in a browser; a no-op (until `setWindow`) on the server.
458
+ initRouter();
388
459
 
389
- /**
390
- * Restore and store the vertical and horizontal scroll position for
391
- * the parent element to the page state.
392
- *
393
- * @param {string} name - A unique (within this page) name for this
394
- * scrollable element. Defaults to 'main'.
395
- *
396
- * The scroll position will be persisted in `route.aux.scroll.<name>`.
397
- */
398
- export function persistScroll(name = "main") {
460
+
461
+ function persistScroll(name = "main") {
399
462
  const el = A()!;
400
463
  A('scroll=', onScroll);
401
464
 
@@ -413,23 +476,7 @@ export function persistScroll(name = "main") {
413
476
  }
414
477
  }
415
478
 
416
- /**
417
- * Intercept clicks and Enter key presses on links (`<a>` tags) and use Aberdeen routing
418
- * instead of browser navigation for local paths (paths without a protocol or host).
419
- *
420
- * This allows you to use regular HTML anchor tags for navigation without needing to
421
- * manually attach click handlers to each link.
422
- *
423
- * @example
424
- * ```js
425
- * // In your root component:
426
- * route.interceptLinks();
427
- *
428
- * // Now you can use regular anchor tags:
429
- * A('a text=About href=/corporate/about');
430
- * ```
431
- */
432
- export function interceptLinks() {
479
+ function interceptLinks() {
433
480
  A({
434
481
  click: handleEvent,
435
482
  keydown: handleKeyEvent,
@@ -471,3 +518,6 @@ export function interceptLinks() {
471
518
  go(href);
472
519
  }
473
520
  }
521
+
522
+ return { current, setLog, go, matchCurrent, push, back, up, reset, initRouter, persistScroll, interceptLinks } as unknown as RouteApi;
523
+ }