@octanejs/wouter 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # @octanejs/wouter
2
+
3
+ An Octane port of [`wouter`](https://github.com/molefrog/wouter), pinned to
4
+ `wouter@3.10.0`.
5
+
6
+ ```tsrx
7
+ import { Link, Route, Router } from "@octanejs/wouter";
8
+ import { memoryLocation } from "@octanejs/wouter/memory-location";
9
+
10
+ const memory = memoryLocation({ path: "/" });
11
+
12
+ export function App() @{
13
+ <Router hook={memory.hook}>
14
+ <nav>
15
+ <Link href="/">Home</Link>
16
+ <Link href="/about">About</Link>
17
+ </nav>
18
+ <Route path="/about">About Octane</Route>
19
+ </Router>
20
+ }
21
+ ```
22
+
23
+ The main entry exports `Router`, `Route`, `Link`, `Switch`, `Redirect`,
24
+ `useRouter`, `useLocation`, `useSearch`, `useSearchParams`, `useRoute`,
25
+ `useParams`, and `matchRoute`. Browser, hash, and memory location hooks are
26
+ available from the matching upstream-compatible subpaths.
27
+
28
+ Octane refs are props, so `Link` accepts `ref` directly. `Switch` inspects
29
+ element descriptors; pass explicit descriptor arrays (for example with
30
+ `createElement`) when its children are assembled dynamically. Nested TSRX
31
+ children are opaque render blocks and cannot be inspected by `Switch`.
32
+
33
+ See [`UPSTREAM.md`](./UPSTREAM.md) for the source pin, export crosswalk, adapted
34
+ test disposition, and explicit platform gaps.
package/UPSTREAM.md ADDED
@@ -0,0 +1,101 @@
1
+ # Upstream crosswalk
2
+
3
+ ## Pin and source boundary
4
+
5
+ - Package: `wouter@3.10.0`
6
+ - Advertised compatibility: `wouter@3.10.x`
7
+ - Canonical repository: <https://github.com/molefrog/wouter>
8
+ - Immutable tag commit: `708c23639d4174ba7deda06c40c8208118899da7`
9
+ - npm integrity:
10
+ `sha512-zTfddD80zc2/J5l8JKcdvzOK6AwP0kpyHEI3DxRN2bn8U1oJPnrSVm8v+X3WwDamvLAOxTO7ZvkxkpRWlyeJ1Q==`
11
+ - npm `gitHead`: `708c23639d4174ba7deda06c40c8208118899da7`
12
+ - License: Unlicense
13
+
14
+ The immutable repository checkout supplies the canonical source, declarations,
15
+ and tests under [`upstream/canonical`](./upstream/canonical). Its
16
+ `packages/wouter/package.json` still reports `3.9.0` at the tag commit. The npm
17
+ tarball under [`upstream/npm`](./upstream/npm) reports `3.10.0`; this port pins
18
+ the published `3.10.0` package and records the repository metadata mismatch
19
+ rather than rewriting either artifact. The runtime modules are byte-equivalent
20
+ at the two source boundaries.
21
+
22
+ Vendored evidence is excluded from the published package. `src/` mirrors the
23
+ canonical runtime module layout, with TypeScript declarations integrated into
24
+ the authored modules and `internal.ts`, `location-hook.ts`, and `router.ts`
25
+ providing Octane slot and public type support.
26
+
27
+ ## Export crosswalk
28
+
29
+ | Upstream entry/export | Octane disposition | Evidence |
30
+ | --- | --- | --- |
31
+ | `wouter`: `Router` | Ported | `tests/components.test.ts` |
32
+ | `wouter`: `Route` | Ported | `tests/components.test.ts` |
33
+ | `wouter`: `Link` | Ported; `ref` is a prop instead of `forwardRef` | `tests/components.test.ts` |
34
+ | `wouter`: `Switch` | Ported; explicit descriptors are inspectable, nested TSRX children are opaque | `tests/components.test.ts` |
35
+ | `wouter`: `Redirect` | Ported | `tests/components.test.ts` |
36
+ | `wouter`: `useRouter` | Ported | `tests/components.test.ts` |
37
+ | `wouter`: `useParams` | Ported | `tests/components.test.ts` |
38
+ | `wouter`: `useLocation` | Ported with trailing hook-slot forwarding | `tests/components.test.ts`, `tests/use-route.test.ts` |
39
+ | `wouter`: `useSearch` | Ported with trailing hook-slot forwarding | `tests/location-hooks.test.ts` |
40
+ | `wouter`: `useSearchParams` | Ported with isolated `useMemo`/`useEvent` slots | `tests/components.test.ts` |
41
+ | `wouter`: `useRoute` | Ported | `tests/use-route.test.ts` |
42
+ | `wouter`: `matchRoute` | Ported with the upstream algorithm | `tests/use-route.test.ts` |
43
+ | `wouter`: public route, match, navigation, router, and search-param types | Ported to `OctaneNode`, native `MouseEvent`, Octane descriptors, and refs-as-props | package typecheck |
44
+ | `wouter/use-browser-location`: `useLocationProperty` | Ported onto Octane `useSyncExternalStore` | `tests/location-hooks.test.ts` |
45
+ | `wouter/use-browser-location`: `useSearch` | Ported | `tests/location-hooks.test.ts` |
46
+ | `wouter/use-browser-location`: `usePathname` | Ported | `tests/location-hooks.test.ts` |
47
+ | `wouter/use-browser-location`: `useHistoryState` | Ported | `tests/location-hooks.test.ts` |
48
+ | `wouter/use-browser-location`: `navigate` | Ported | `tests/location-hooks.test.ts` |
49
+ | `wouter/use-browser-location`: `useBrowserLocation` | Ported with optional trailing slot | `tests/location-hooks.test.ts` |
50
+ | `wouter/use-hash-location`: `navigate` | Ported | `tests/location-hooks.test.ts` |
51
+ | `wouter/use-hash-location`: `useHashLocation` | Ported with optional trailing slot and `hrefs` formatter | `tests/location-hooks.test.ts` |
52
+ | `wouter/memory-location`: `memoryLocation` | Ported, including search, state, recording, and reset | `tests/memory-location.test.ts` |
53
+ | `src/paths.js` | Reused algorithm unchanged as `src/paths.ts` | route/location suites |
54
+ | `src/use-sync-external-store.js` | Replaced by Octane's built-in `useSyncExternalStore`; no shim dependency | location suites |
55
+ | `src/use-sync-external-store.native.js` | GAP: Octane has no React Native shim entry | Not exported |
56
+ | Wouter's Preact package | GAP: a separate Preact binding is outside `@octanejs/wouter` | Not published |
57
+
58
+ ## Upstream test disposition
59
+
60
+ Every adapted case retains its upstream title and cites its source file. No
61
+ adapted test is skipped or marked todo.
62
+
63
+ | Canonical test artifact | Disposition |
64
+ | --- | --- |
65
+ | `test/memory-location.test.ts` | Fully adapted in `tests/memory-location.test.ts` |
66
+ | `test/use-route.test.tsx` | Fully adapted in `tests/use-route.test.ts` |
67
+ | `test/link.test.tsx` | Adapted core link/ref/navigation/asChild cases in `tests/components.test.ts`; active-link rerender variants remain out of scope for this first pass |
68
+ | `test/route.test.tsx` | Fully adapted in `tests/components.test.ts` |
69
+ | `test/redirect.test.tsx` | Fully adapted in `tests/components.test.ts` |
70
+ | `test/view-transitions.test.tsx` | Fully adapted in `tests/components.test.ts` |
71
+ | `test/use-browser-location.test.tsx` | Adapted in `tests/location-hooks.test.ts`; asynchronous `history.back()` remains a jsdom gap |
72
+ | `test/use-hash-location.test.tsx` | Adapted synchronous browser cases in `tests/location-hooks.test.ts`; server, `data:` URL, and asynchronous listener-order cases remain environment lanes |
73
+ | `test/use-search.test.tsx` | Fully adapted in `tests/location-hooks.test.ts` |
74
+ | `test/use-search-params.test.tsx` | Adapted browser read/write/empty-query cases in `tests/components.test.ts`; custom-router and Unicode variants are already covered by the `useSearch` suite |
75
+ | `test/parser.test.tsx` | Adapted with a custom parser in `tests/components.test.ts`; the upstream `path-to-regexp` oracle is not a runtime dependency |
76
+ | `test/router.test.tsx` | Adapted construction, identity, base, and SSR-option cases in `tests/components.test.ts`; remaining nested inheritance variants are not yet adapted |
77
+ | `test/switch.test.tsx` | Adapted descriptor, fallback, array, and Fragment cases in `tests/components.test.ts`; async consistency cases are not yet adapted |
78
+ | `test/use-params.test.tsx` | Adapted default and closest-route cases in `tests/components.test.ts`; nested/reactive cases are not yet adapted |
79
+ | `test/use-location.test.tsx` | Covered by browser, hash, memory, base-path, and navigation tests across the adapted suites; the upstream parameterized file is not duplicated |
80
+ | `test/nested-route.test.tsx` | Adapted in `tests/nested-route.test.ts` |
81
+ | `test/ssr.test.tsx` | Adapted in `tests/ssr.test.ts` using `octane/server` `renderToStaticMarkup` |
82
+ | `test/history-patch.test.ts` | Browser patch behavior is exercised through `useBrowserLocation`; the duplicate React/Preact export assertion is not applicable |
83
+ | `test/setup.ts` | Adapted to Vitest/jsdom in `tests/setup.ts` |
84
+ | `test/test-utils.ts` | Not needed by the synchronous jsdom adaptation |
85
+ | `test/jest-dom.d.ts` | Not applicable; adapted assertions use DOM properties directly |
86
+ | `test/*.test-d.ts`, `test/*.test-d.tsx` | A focused accepted/rejected API slice is adapted in `tests/public-types.test-d.ts`; a one-for-one upstream type oracle remains a first-pass gap |
87
+
88
+ ## Intentional Octane differences and gaps
89
+
90
+ - Runtime source imports only from `octane`; React and
91
+ `use-sync-external-store` are not dependencies.
92
+ - `Link` receives `ref` as a normal prop. Octane has no `forwardRef`.
93
+ - `useLocationFromRouter` forwards the compiler's trailing symbol into dynamic
94
+ `router.hook(router, slot)` calls. Browser, hash, and memory hooks accept
95
+ `(options, slot?)`, and also treat a symbol in the first position as the slot.
96
+ `useEvent` independently sub-slots its ref and insertion effect.
97
+ - `Switch` can inspect explicit `createElement` descriptors and descriptor
98
+ arrays. Nested TSRX children are opaque render blocks, so consumers assembling
99
+ a switch dynamically must pass `children={[...]}` or explicit descriptors.
100
+ - The native `use-sync-external-store.native.js` entry and Wouter's separate
101
+ Preact package have no Octane equivalents.
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@octanejs/wouter",
3
+ "version": "0.0.1",
4
+ "license": "Unlicense",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22.22.2"
8
+ },
9
+ "octane": {
10
+ "hookSlots": {
11
+ "manual": [
12
+ "src"
13
+ ]
14
+ }
15
+ },
16
+ "description": "wouter for Octane, ported from wouter 3.10.0.",
17
+ "author": {
18
+ "name": "Dominic Gannaway",
19
+ "email": "dg@domgan.com"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/octanejs/octane.git",
27
+ "directory": "packages/wouter"
28
+ },
29
+ "main": "src/index.ts",
30
+ "module": "src/index.ts",
31
+ "types": "src/index.ts",
32
+ "files": [
33
+ "src",
34
+ "README.md",
35
+ "UPSTREAM.md",
36
+ "LICENSE"
37
+ ],
38
+ "exports": {
39
+ ".": "./src/index.ts",
40
+ "./use-browser-location": "./src/use-browser-location.ts",
41
+ "./use-hash-location": "./src/use-hash-location.ts",
42
+ "./memory-location": "./src/memory-location.ts",
43
+ "./package.json": "./package.json"
44
+ },
45
+ "dependencies": {
46
+ "mitt": "^3.0.1",
47
+ "regexparam": "^3.0.0"
48
+ },
49
+ "peerDependencies": {
50
+ "octane": "0.1.45"
51
+ },
52
+ "devDependencies": {
53
+ "@testing-library/jest-dom": "^6.9.1",
54
+ "vitest": "^4.1.10",
55
+ "@octanejs/testing-library": "0.1.42",
56
+ "octane": "0.1.45"
57
+ },
58
+ "scripts": {
59
+ "test": "vitest run --root ../.. --config vitest.config.js --project wouter",
60
+ "typecheck": "tsrx-tsc --noEmit"
61
+ }
62
+ }
package/src/index.ts ADDED
@@ -0,0 +1,529 @@
1
+ import { parse as parsePattern } from 'regexparam';
2
+ import {
3
+ Fragment,
4
+ cloneElement,
5
+ createContext,
6
+ createElement as h,
7
+ isValidElement,
8
+ useContext,
9
+ useIsomorphicLayoutEffect,
10
+ useMemo,
11
+ useRef,
12
+ useEvent,
13
+ } from './react-deps';
14
+ import { useBrowserLocation, useSearch as useBrowserSearch } from './use-browser-location';
15
+ import { absolutePath, relativePath, sanitizeSearch } from './paths';
16
+ import { splitSlot, subSlot } from './internal';
17
+ import type {
18
+ BaseLocationHook,
19
+ BaseSearchHook,
20
+ HookNavigationOptions,
21
+ HookReturnValue,
22
+ Path,
23
+ PathPattern,
24
+ } from './location-hook';
25
+ import type {
26
+ AroundNavHandler,
27
+ NavigateOptions,
28
+ Parser,
29
+ RouterObject,
30
+ RouterOptions,
31
+ SsrContext,
32
+ } from './router';
33
+ import {
34
+ isChildrenBlock,
35
+ type ComponentBody,
36
+ type ElementDescriptor,
37
+ type OctaneNode,
38
+ } from 'octane';
39
+ import type { JSX, Octane } from 'octane/jsx-runtime';
40
+ import type { RouteParams } from 'regexparam';
41
+
42
+ export type * from './location-hook';
43
+ export type * from './router';
44
+
45
+ type RuntimeRouter = Omit<RouterObject, 'ownBase'>;
46
+
47
+ const defaultRouter: RuntimeRouter = {
48
+ hook: useBrowserLocation,
49
+ searchHook: useBrowserSearch,
50
+ parser: parsePattern as Parser,
51
+ base: '',
52
+ ssrPath: undefined,
53
+ ssrSearch: undefined,
54
+ ssrContext: undefined,
55
+ hrefs: (value) => value,
56
+ aroundNav: (navigate, to, options) => navigate(to, options),
57
+ };
58
+
59
+ const RouterCtx = createContext(defaultRouter);
60
+
61
+ export function useRouter(): RouterObject {
62
+ return useContext(RouterCtx) as RouterObject;
63
+ }
64
+
65
+ export interface DefaultParams {
66
+ readonly [paramName: string | number]: string | undefined;
67
+ }
68
+
69
+ export type Params<T extends DefaultParams = DefaultParams> = T;
70
+ export type StringRouteParams<T extends string> = RouteParams<T> & {
71
+ [param: number]: string | undefined;
72
+ };
73
+ export type RegexRouteParams = {
74
+ [key: string | number]: string | undefined;
75
+ };
76
+ export type MatchWithParams<T extends DefaultParams = DefaultParams> = [true, Params<T>];
77
+ export type NoMatch = [false, null];
78
+ export type Match<T extends DefaultParams = DefaultParams> = MatchWithParams<T> | NoMatch;
79
+
80
+ const Params0: DefaultParams = {};
81
+ const ParamsCtx = createContext(Params0);
82
+
83
+ export function useParams<T = undefined>(): T extends string
84
+ ? StringRouteParams<T>
85
+ : T extends undefined
86
+ ? DefaultParams
87
+ : T {
88
+ return useContext(ParamsCtx) as T extends string
89
+ ? StringRouteParams<T>
90
+ : T extends undefined
91
+ ? DefaultParams
92
+ : T;
93
+ }
94
+
95
+ type Navigate = (to: Path, options?: NavigateOptions) => void;
96
+
97
+ function useLocationFromRouter(router: RuntimeRouter, ...rest: [slot?: symbol]): [Path, Navigate] {
98
+ const [, slot] = splitSlot(rest);
99
+ const [location, navigate] = router.hook(router, subSlot(slot, 'location:router-hook'));
100
+
101
+ return [
102
+ relativePath(router.base, location),
103
+ useEvent(
104
+ (to: Path, options?: NavigateOptions) =>
105
+ router.aroundNav(navigate as Navigate, absolutePath(to, router.base), options),
106
+ subSlot(slot, 'location:navigate'),
107
+ ),
108
+ ];
109
+ }
110
+
111
+ export function useLocation<
112
+ H extends BaseLocationHook = typeof useBrowserLocation,
113
+ >(): HookReturnValue<H>;
114
+ export function useLocation(...rest: [slot?: symbol]): [Path, Navigate] {
115
+ const [, slot] = splitSlot(rest);
116
+ return useLocationInternal(slot);
117
+ }
118
+
119
+ function useLocationInternal(slot: symbol | undefined): [Path, Navigate] {
120
+ return useLocationFromRouter(useRouter() as RuntimeRouter, subSlot(slot, 'use-location'));
121
+ }
122
+
123
+ export function useSearch<H extends BaseSearchHook = typeof useBrowserSearch>(): ReturnType<H>;
124
+ export function useSearch(...rest: [slot?: symbol]): string {
125
+ const [, slot] = splitSlot(rest);
126
+ return useSearchInternal(slot);
127
+ }
128
+
129
+ function useSearchInternal(slot: symbol | undefined): string {
130
+ const router = useRouter() as RuntimeRouter;
131
+ return sanitizeSearch(router.searchHook(router, subSlot(slot, 'use-search')));
132
+ }
133
+
134
+ export function matchRoute<
135
+ T extends DefaultParams | undefined = undefined,
136
+ RoutePath extends PathPattern = PathPattern,
137
+ >(
138
+ parser: Parser,
139
+ route: RoutePath,
140
+ path: string,
141
+ loose?: boolean,
142
+ ): Match<
143
+ T extends DefaultParams
144
+ ? T
145
+ : RoutePath extends string
146
+ ? StringRouteParams<RoutePath>
147
+ : RegexRouteParams
148
+ >;
149
+ export function matchRoute(
150
+ parser: Parser,
151
+ route: PathPattern | undefined,
152
+ path: string,
153
+ loose?: boolean,
154
+ ): Match & [boolean, DefaultParams | null, string?] {
155
+ const { pattern, keys } =
156
+ route instanceof RegExp
157
+ ? { keys: false as const, pattern: route }
158
+ : parser(route || '*', loose);
159
+ const execResult = pattern.exec(path);
160
+ const result = execResult || [];
161
+ const [$base, ...matches] = result;
162
+
163
+ return (
164
+ $base !== undefined
165
+ ? [
166
+ true,
167
+ (() => {
168
+ const groups =
169
+ keys !== false
170
+ ? Object.fromEntries(keys.map((key, index) => [key, matches[index]]))
171
+ : execResult?.groups;
172
+ const params = { ...matches } as unknown as DefaultParams;
173
+ if (groups) {
174
+ Object.assign(params, groups);
175
+ }
176
+ return params;
177
+ })(),
178
+ ...(loose ? [$base] : []),
179
+ ]
180
+ : [false, null]
181
+ ) as Match & [boolean, DefaultParams | null, string?];
182
+ }
183
+
184
+ export function useRoute<
185
+ T extends DefaultParams | undefined = undefined,
186
+ RoutePath extends PathPattern = PathPattern,
187
+ >(
188
+ pattern: RoutePath,
189
+ ): Match<
190
+ T extends DefaultParams
191
+ ? T
192
+ : RoutePath extends string
193
+ ? StringRouteParams<RoutePath>
194
+ : RegexRouteParams
195
+ >;
196
+ export function useRoute(pattern: PathPattern, ...rest: [slot?: symbol]): Match {
197
+ const [, slot] = splitSlot(rest);
198
+ return matchRoute(
199
+ useRouter().parser,
200
+ pattern,
201
+ useLocationInternal(subSlot(slot, 'use-route'))[0],
202
+ );
203
+ }
204
+
205
+ export type RouterProps = RouterOptions & {
206
+ children: OctaneNode;
207
+ };
208
+
209
+ const ROUTER_REF_SLOT = Symbol.for('@octanejs/wouter:Router:ref');
210
+
211
+ export function Router({ children, ...props }: RouterProps): OctaneNode {
212
+ const parentFromContext = useRouter() as RuntimeRouter;
213
+ const parent = props.hook ? defaultRouter : parentFromContext;
214
+ let value = parent;
215
+
216
+ const [path, search = props.ssrSearch ?? ''] = props.ssrPath?.split('?') ?? [];
217
+ if (path) {
218
+ props.ssrSearch = search;
219
+ props.ssrPath = path;
220
+ }
221
+
222
+ props.hrefs = props.hrefs ?? props.hook?.hrefs;
223
+ props.searchHook = props.searchHook ?? props.hook?.searchHook;
224
+
225
+ const ref = useRef<Record<string, unknown>>({}, ROUTER_REF_SLOT);
226
+ const previous = ref.current;
227
+ let next = previous;
228
+
229
+ for (const key in parent) {
230
+ const option =
231
+ key === 'base'
232
+ ? parent.base + ((props as Record<string, unknown>)[key] ?? '')
233
+ : ((props as Record<string, unknown>)[key] ??
234
+ (parent as unknown as Record<string, unknown>)[key]);
235
+
236
+ if (previous === next && option !== next[key]) {
237
+ ref.current = next = { ...next };
238
+ }
239
+ next[key] = option;
240
+
241
+ if (
242
+ option !== (parent as unknown as Record<string, unknown>)[key] ||
243
+ option !== (value as unknown as Record<string, unknown>)[key]
244
+ ) {
245
+ value = next as RuntimeRouter;
246
+ }
247
+ }
248
+
249
+ return h(RouterCtx.Provider, { value, children });
250
+ }
251
+
252
+ export interface RouteComponentProps<T extends DefaultParams = DefaultParams> {
253
+ params: T;
254
+ }
255
+
256
+ export interface RouteProps<
257
+ T extends DefaultParams | undefined = undefined,
258
+ RoutePath extends PathPattern = PathPattern,
259
+ > {
260
+ children?:
261
+ | ((
262
+ params: T extends DefaultParams
263
+ ? T
264
+ : RoutePath extends string
265
+ ? StringRouteParams<RoutePath>
266
+ : RegexRouteParams,
267
+ ) => OctaneNode)
268
+ | OctaneNode;
269
+ path?: RoutePath;
270
+ component?: ComponentBody<
271
+ RouteComponentProps<
272
+ T extends DefaultParams
273
+ ? T
274
+ : RoutePath extends string
275
+ ? StringRouteParams<RoutePath>
276
+ : RegexRouteParams
277
+ >
278
+ >;
279
+ nest?: boolean;
280
+ }
281
+
282
+ type InternalRouteProps = RouteProps<any, any> & {
283
+ match?: [boolean, DefaultParams | null, string?];
284
+ };
285
+
286
+ function renderRoute(
287
+ { children, component }: Pick<InternalRouteProps, 'children' | 'component'>,
288
+ params: DefaultParams,
289
+ ): OctaneNode {
290
+ if (component) {
291
+ return h(component as ComponentBody<{ params: DefaultParams }>, { params });
292
+ }
293
+ return typeof children === 'function' && !isChildrenBlock(children) ? children(params) : children;
294
+ }
295
+
296
+ function useCachedParams(value: DefaultParams, slot: symbol | undefined): DefaultParams {
297
+ const previous = useRef(Params0, slot);
298
+ const current = previous.current;
299
+ return (previous.current =
300
+ Object.keys(value).length !== Object.keys(current).length ||
301
+ Object.entries(value).some(([key, item]) => item !== current[key])
302
+ ? value
303
+ : current);
304
+ }
305
+
306
+ const ROUTE_LOCATION_SLOT = Symbol.for('@octanejs/wouter:Route:location');
307
+ const ROUTE_PARAMS_SLOT = Symbol.for('@octanejs/wouter:Route:params');
308
+
309
+ export function Route<
310
+ T extends DefaultParams | undefined = undefined,
311
+ RoutePath extends PathPattern = PathPattern,
312
+ >({
313
+ path,
314
+ nest,
315
+ match,
316
+ ...renderProps
317
+ }: RouteProps<T, RoutePath> & {
318
+ match?: [boolean, DefaultParams | null, string?];
319
+ }): OctaneNode {
320
+ const router = useRouter() as RuntimeRouter;
321
+ const [location] = useLocationFromRouter(router, ROUTE_LOCATION_SLOT);
322
+ const [matches, routeParams, base] =
323
+ match ?? matchRoute(router.parser, path as PathPattern, location, nest);
324
+ const params = useCachedParams({ ...useParams(), ...routeParams }, ROUTE_PARAMS_SLOT);
325
+
326
+ if (!matches) {
327
+ return null;
328
+ }
329
+
330
+ const children = base
331
+ ? h(Router, { base, children: renderRoute(renderProps, params) } as RouterProps)
332
+ : renderRoute(renderProps, params);
333
+
334
+ return h(ParamsCtx.Provider, { value: params, children });
335
+ }
336
+
337
+ export type NavigationalProps<H extends BaseLocationHook = typeof useBrowserLocation> = (
338
+ { to: Path; href?: never } | { href: Path; to?: never }
339
+ ) &
340
+ HookNavigationOptions<H>;
341
+
342
+ export type RedirectProps<H extends BaseLocationHook = typeof useBrowserLocation> =
343
+ NavigationalProps<H> & {
344
+ children?: never;
345
+ };
346
+
347
+ type HTMLLinkAttributes = Omit<JSX.IntrinsicElements['a'], 'className' | 'ref'> & {
348
+ className?: string | ((isActive: boolean) => string | undefined);
349
+ ref?: Octane.Ref<HTMLAnchorElement>;
350
+ };
351
+
352
+ type AsChildProps =
353
+ | ({ asChild?: false } & HTMLLinkAttributes)
354
+ | {
355
+ asChild: true;
356
+ children: ElementDescriptor;
357
+ onClick?: (event: MouseEvent) => void;
358
+ ref?: Octane.Ref<HTMLAnchorElement>;
359
+ };
360
+
361
+ export type LinkProps<H extends BaseLocationHook = typeof useBrowserLocation> =
362
+ NavigationalProps<H> & AsChildProps;
363
+
364
+ const LINK_LOCATION_SLOT = Symbol.for('@octanejs/wouter:Link:location');
365
+ const LINK_EVENT_SLOT = Symbol.for('@octanejs/wouter:Link:event');
366
+
367
+ export function Link<H extends BaseLocationHook = typeof useBrowserLocation>(
368
+ props: LinkProps<H>,
369
+ ): OctaneNode {
370
+ const router = useRouter() as RuntimeRouter;
371
+ const [currentPath, navigate] = useLocationFromRouter(router, LINK_LOCATION_SLOT);
372
+
373
+ const {
374
+ to = '',
375
+ href: targetPath = to,
376
+ onClick: onClickProp,
377
+ asChild,
378
+ children,
379
+ className,
380
+ replace: _replace,
381
+ state: _state,
382
+ transition: _transition,
383
+ ref,
384
+ ...restProps
385
+ } = props as unknown as {
386
+ to?: Path;
387
+ href?: Path;
388
+ onClick?: (event: MouseEvent) => void;
389
+ asChild?: boolean;
390
+ children?: OctaneNode;
391
+ className?: string | ((isActive: boolean) => string | undefined);
392
+ replace?: boolean;
393
+ state?: unknown;
394
+ transition?: boolean;
395
+ ref?: Octane.Ref<HTMLAnchorElement>;
396
+ [key: string]: unknown;
397
+ };
398
+
399
+ const onClick = useEvent((event: MouseEvent) => {
400
+ if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey || event.button !== 0) {
401
+ return;
402
+ }
403
+
404
+ onClickProp?.(event);
405
+ if (!event.defaultPrevented) {
406
+ event.preventDefault();
407
+ navigate(targetPath, props);
408
+ }
409
+ }, LINK_EVENT_SLOT);
410
+
411
+ const resolvedHref = router.hrefs(
412
+ targetPath[0] === '~' ? targetPath.slice(1) : router.base + targetPath,
413
+ router,
414
+ );
415
+
416
+ return asChild && isValidElement(children)
417
+ ? cloneElement(children, { onClick, href: resolvedHref })
418
+ : h('a', {
419
+ ...restProps,
420
+ onClick,
421
+ href: resolvedHref,
422
+ className:
423
+ typeof className === 'function' ? className(currentPath === targetPath) : className,
424
+ children,
425
+ ref,
426
+ });
427
+ }
428
+
429
+ function flattenChildren(children: OctaneNode): OctaneNode[] {
430
+ return Array.isArray(children)
431
+ ? children.flatMap((child) =>
432
+ flattenChildren(
433
+ child && isValidElement(child) && child.type === Fragment ? child.props.children : child,
434
+ ),
435
+ )
436
+ : [children];
437
+ }
438
+
439
+ export interface SwitchProps {
440
+ location?: string;
441
+ children: OctaneNode;
442
+ }
443
+
444
+ const SWITCH_LOCATION_SLOT = Symbol.for('@octanejs/wouter:Switch:location');
445
+
446
+ export function Switch({ children, location }: SwitchProps): OctaneNode {
447
+ const router = useRouter() as RuntimeRouter;
448
+ const [originalLocation] = useLocationFromRouter(router, SWITCH_LOCATION_SLOT);
449
+
450
+ for (const element of flattenChildren(children)) {
451
+ let match: [boolean, DefaultParams | null, string?] | 0 = 0;
452
+
453
+ if (
454
+ isValidElement(element) &&
455
+ (match = matchRoute(
456
+ router.parser,
457
+ element.props.path,
458
+ location || originalLocation,
459
+ element.props.nest,
460
+ ) as [boolean, DefaultParams | null, string?])[0]
461
+ ) {
462
+ return cloneElement(element, { match });
463
+ }
464
+ }
465
+
466
+ return null;
467
+ }
468
+
469
+ const REDIRECT_LOCATION_SLOT = Symbol.for('@octanejs/wouter:Redirect:location');
470
+ const REDIRECT_EVENT_SLOT = Symbol.for('@octanejs/wouter:Redirect:event');
471
+ const REDIRECT_EFFECT_SLOT = Symbol.for('@octanejs/wouter:Redirect:effect');
472
+
473
+ export function Redirect<H extends BaseLocationHook = typeof useBrowserLocation>(
474
+ props: RedirectProps<H>,
475
+ ): null {
476
+ const { to, href = to } = props as RedirectProps & {
477
+ to?: Path;
478
+ href?: Path;
479
+ };
480
+ const router = useRouter() as RuntimeRouter;
481
+ const [, navigate] = useLocationFromRouter(router, REDIRECT_LOCATION_SLOT);
482
+ const redirect = useEvent(() => navigate(to || href || '', props), REDIRECT_EVENT_SLOT);
483
+
484
+ useIsomorphicLayoutEffect(
485
+ () => {
486
+ redirect();
487
+ },
488
+ [],
489
+ REDIRECT_EFFECT_SLOT,
490
+ );
491
+
492
+ if (router.ssrContext) {
493
+ router.ssrContext.redirectTo = to;
494
+ }
495
+ return null;
496
+ }
497
+
498
+ export type URLSearchParamsInit = ConstructorParameters<typeof URLSearchParams>[0];
499
+ export type SetSearchParams = (
500
+ nextInit: URLSearchParamsInit | ((previous: URLSearchParams) => URLSearchParamsInit),
501
+ options?: { replace?: boolean; state?: any },
502
+ ) => void;
503
+
504
+ export function useSearchParams(): [URLSearchParams, SetSearchParams];
505
+ export function useSearchParams(...rest: [slot?: symbol]): [URLSearchParams, SetSearchParams] {
506
+ const [, slot] = splitSlot(rest);
507
+ const [location, navigate] = useLocationInternal(subSlot(slot, 'search-params:location'));
508
+ const search = useSearchInternal(subSlot(slot, 'search-params:search'));
509
+ const searchParams = useMemo(
510
+ () => new URLSearchParams(search),
511
+ [search],
512
+ subSlot(slot, 'search-params:memo'),
513
+ );
514
+ let temporarySearchParams = searchParams;
515
+
516
+ const setSearchParams = useEvent<SetSearchParams>(
517
+ (nextInit, options) => {
518
+ temporarySearchParams = new URLSearchParams(
519
+ typeof nextInit === 'function' ? nextInit(temporarySearchParams) : nextInit,
520
+ );
521
+ navigate(location + (temporarySearchParams.size ? '?' + temporarySearchParams : ''), options);
522
+ },
523
+ subSlot(slot, 'search-params:setter'),
524
+ );
525
+
526
+ return [searchParams, setSearchParams];
527
+ }
528
+
529
+ export type { AroundNavHandler, NavigateOptions, Parser, RouterObject, RouterOptions, SsrContext };
@@ -0,0 +1,39 @@
1
+ const subSlotCache = new Map<symbol, Map<string, symbol>>();
2
+ const bareTagCache = new Map<string, symbol>();
3
+
4
+ export function subSlot(slot: symbol | undefined, tag: string): symbol {
5
+ if (slot === undefined) {
6
+ let bare = bareTagCache.get(tag);
7
+ if (bare === undefined) {
8
+ bare = Symbol.for(`@octanejs/wouter:${tag}`);
9
+ bareTagCache.set(tag, bare);
10
+ }
11
+ return bare;
12
+ }
13
+
14
+ let byTag = subSlotCache.get(slot);
15
+ if (byTag === undefined) {
16
+ byTag = new Map();
17
+ subSlotCache.set(slot, byTag);
18
+ }
19
+
20
+ let child = byTag.get(tag);
21
+ if (child === undefined) {
22
+ child = Symbol.for(`${slot.description ?? ''}:wouter:${tag}`);
23
+ byTag.set(tag, child);
24
+ }
25
+ return child;
26
+ }
27
+
28
+ export function splitSlot(args: unknown[]): [unknown[], symbol | undefined] {
29
+ const tail = args[args.length - 1];
30
+ const slot = typeof tail === 'symbol' ? tail : undefined;
31
+ return [slot === undefined ? args : args.slice(0, -1), slot];
32
+ }
33
+
34
+ export function optionAndSlot<T extends object>(
35
+ first: T | symbol | undefined,
36
+ second: symbol | undefined,
37
+ ): [T, symbol | undefined] {
38
+ return typeof first === 'symbol' ? ([{}, first] as [T, symbol]) : [first ?? ({} as T), second];
39
+ }
@@ -0,0 +1,25 @@
1
+ export type Path = string;
2
+ export type PathPattern = string | RegExp;
3
+ export type SearchString = string;
4
+
5
+ export type HrefsFormatter = (href: string, router?: unknown) => string;
6
+
7
+ export type BaseLocationHook = {
8
+ (...args: any[]): [Path, (path: Path, ...args: any[]) => any];
9
+ searchHook?: BaseSearchHook;
10
+ hrefs?: HrefsFormatter;
11
+ };
12
+
13
+ export type BaseSearchHook = (...args: any[]) => SearchString;
14
+
15
+ export type HookReturnValue<H extends BaseLocationHook> = ReturnType<H>;
16
+
17
+ type EmptyInterfaceWhenAnyOrNever<T> = 0 extends 1 & T
18
+ ? Record<never, never>
19
+ : [T] extends [never]
20
+ ? Record<never, never>
21
+ : T;
22
+
23
+ export type HookNavigationOptions<H extends BaseLocationHook> = EmptyInterfaceWhenAnyOrNever<
24
+ NonNullable<Parameters<HookReturnValue<H>[1]>[1]>
25
+ >;
@@ -0,0 +1,130 @@
1
+ import mitt from 'mitt';
2
+ import { useSyncExternalStore } from './react-deps';
3
+ import { optionAndSlot, subSlot } from './internal';
4
+ import type { BaseLocationHook, BaseSearchHook, Path, SearchString } from './location-hook';
5
+
6
+ type Navigate<S = any> = (
7
+ to: Path,
8
+ options?: { replace?: boolean; state?: S; transition?: boolean },
9
+ ) => void;
10
+
11
+ type MemoryLocationResult<S> = {
12
+ hook: BaseLocationHook;
13
+ searchHook: BaseSearchHook;
14
+ navigate: Navigate<S>;
15
+ readonly state: S | null;
16
+ };
17
+
18
+ type RecordedMemoryLocation = {
19
+ history: Path[];
20
+ reset: () => void;
21
+ };
22
+
23
+ export function memoryLocation<S = unknown>(options?: {
24
+ path?: Path;
25
+ searchPath?: SearchString;
26
+ state?: S;
27
+ static?: boolean;
28
+ record?: false;
29
+ }): MemoryLocationResult<S>;
30
+ export function memoryLocation<S = unknown>(options: {
31
+ path?: Path;
32
+ searchPath?: SearchString;
33
+ state?: S;
34
+ static?: boolean;
35
+ record: true;
36
+ }): MemoryLocationResult<S> & RecordedMemoryLocation;
37
+ export function memoryLocation<S = unknown>({
38
+ path = '/',
39
+ searchPath = '',
40
+ state = null,
41
+ static: staticLocation,
42
+ record,
43
+ }: {
44
+ path?: Path;
45
+ searchPath?: SearchString;
46
+ state?: S | null;
47
+ static?: boolean;
48
+ record?: boolean;
49
+ } = {}): MemoryLocationResult<S> & Partial<RecordedMemoryLocation> {
50
+ let initialPath = path;
51
+ const initialState = state;
52
+ if (searchPath) {
53
+ initialPath += path.split('?')[1] ? '&' : '?';
54
+ initialPath += searchPath;
55
+ }
56
+
57
+ let [currentPath, currentSearch = ''] = initialPath.split('?');
58
+ let currentState = initialState;
59
+ const history = [initialPath];
60
+ const emitter = mitt<{ navigate: string }>();
61
+
62
+ const navigateImplementation: Navigate<S> = (
63
+ nextPath,
64
+ { replace = false, state: nextState } = {},
65
+ ) => {
66
+ if (record) {
67
+ if (replace) {
68
+ history.splice(history.length - 1, 1, nextPath);
69
+ } else {
70
+ history.push(nextPath);
71
+ }
72
+ }
73
+
74
+ [currentPath, currentSearch = ''] = nextPath.split('?');
75
+ if (nextState !== undefined) {
76
+ currentState = nextState;
77
+ }
78
+ emitter.emit('navigate', nextPath);
79
+ };
80
+
81
+ const navigate: Navigate<S> = !staticLocation ? navigateImplementation : () => undefined;
82
+
83
+ const subscribe = (callback: () => void) => {
84
+ emitter.on('navigate', callback);
85
+ return () => emitter.off('navigate', callback);
86
+ };
87
+
88
+ function useMemoryLocation(first?: object | symbol, second?: symbol): [Path, Navigate<S>] {
89
+ const [, slot] = optionAndSlot(first, second);
90
+ return [
91
+ useSyncExternalStore(
92
+ subscribe,
93
+ () => currentPath,
94
+ () => currentPath,
95
+ subSlot(slot, 'memory-location'),
96
+ ),
97
+ navigate,
98
+ ];
99
+ }
100
+
101
+ function useMemoryQuery(first?: object | symbol, second?: symbol): SearchString {
102
+ const [, slot] = optionAndSlot(first, second);
103
+ return useSyncExternalStore(
104
+ subscribe,
105
+ () => currentSearch,
106
+ () => currentSearch,
107
+ subSlot(slot, 'memory-search'),
108
+ );
109
+ }
110
+
111
+ useMemoryLocation.searchHook = useMemoryQuery;
112
+
113
+ function reset() {
114
+ history.splice(0, history.length);
115
+ navigateImplementation(initialPath, { state: initialState as S });
116
+ }
117
+
118
+ const result: MemoryLocationResult<S> & Partial<RecordedMemoryLocation> = {
119
+ hook: useMemoryLocation,
120
+ searchHook: useMemoryQuery,
121
+ navigate,
122
+ history: record ? history : undefined,
123
+ reset: record ? reset : undefined,
124
+ get state() {
125
+ return currentState;
126
+ },
127
+ };
128
+
129
+ return result;
130
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,36 @@
1
+ /*
2
+ * Transforms `path` into its relative `base` version
3
+ * If base isn't part of the path provided returns absolute path e.g. `~/app`
4
+ */
5
+ const _relativePath = (base: string, path: string) =>
6
+ !path.toLowerCase().indexOf(base.toLowerCase()) ? path.slice(base.length) || '/' : '~' + path;
7
+
8
+ /**
9
+ * When basepath is `undefined` or '/' it is ignored (we assume it's empty string)
10
+ */
11
+ const baseDefaults = (base = '') => (base === '/' ? '' : base);
12
+
13
+ export const absolutePath = (to: string, base?: string) =>
14
+ to[0] === '~' ? to.slice(1) : baseDefaults(base) + to;
15
+
16
+ export const relativePath = (base = '', path: string) =>
17
+ _relativePath(unescape(baseDefaults(base)), unescape(path));
18
+
19
+ /*
20
+ * Removes leading question mark
21
+ */
22
+ const stripQm = (str: string) => (str[0] === '?' ? str.slice(1) : str);
23
+
24
+ /*
25
+ * decodes escape sequences such as %20
26
+ */
27
+ const unescape = (str: string) => {
28
+ try {
29
+ return decodeURI(str);
30
+ } catch (_e) {
31
+ // fail-safe mode: if string can't be decoded do nothing
32
+ return str;
33
+ }
34
+ };
35
+
36
+ export const sanitizeSearch = (search: string) => unescape(stripQm(search));
@@ -0,0 +1,59 @@
1
+ import {
2
+ Fragment,
3
+ cloneElement,
4
+ createContext,
5
+ createElement,
6
+ isValidElement,
7
+ useContext,
8
+ useEffect,
9
+ useInsertionEffect,
10
+ useLayoutEffect,
11
+ useMemo,
12
+ useRef,
13
+ useState,
14
+ useSyncExternalStore,
15
+ } from 'octane';
16
+ import { splitSlot, subSlot } from './internal';
17
+
18
+ export {
19
+ Fragment,
20
+ cloneElement,
21
+ createContext,
22
+ createElement,
23
+ isValidElement,
24
+ useContext,
25
+ useMemo,
26
+ useRef,
27
+ useState,
28
+ useSyncExternalStore,
29
+ };
30
+
31
+ const canUseDOM = !!(
32
+ typeof window !== 'undefined' &&
33
+ typeof window.document !== 'undefined' &&
34
+ typeof window.document.createElement !== 'undefined'
35
+ );
36
+
37
+ export const useIsomorphicLayoutEffect = canUseDOM ? useLayoutEffect : useEffect;
38
+
39
+ export function useEvent<T extends (...args: any[]) => any>(fn: T): T;
40
+ export function useEvent<T extends (...args: any[]) => any>(fn: T, slot: symbol): T;
41
+ export function useEvent<T extends (...args: any[]) => any>(fn: T, ...rest: [slot?: symbol]): T {
42
+ const [, slot] = splitSlot(rest);
43
+ const ref = useRef<[T, T] | undefined>(undefined, subSlot(slot, 'use-event:ref'));
44
+
45
+ if (ref.current === undefined) {
46
+ const pair = [fn, ((...args: Parameters<T>) => pair[0](...args)) as T] as [T, T];
47
+ ref.current = pair;
48
+ }
49
+
50
+ useInsertionEffect(
51
+ () => {
52
+ ref.current![0] = fn;
53
+ },
54
+ undefined,
55
+ subSlot(slot, 'use-event:insertion-effect'),
56
+ );
57
+
58
+ return ref.current[1];
59
+ }
package/src/router.ts ADDED
@@ -0,0 +1,51 @@
1
+ import type {
2
+ BaseLocationHook,
3
+ BaseSearchHook,
4
+ HrefsFormatter,
5
+ Path,
6
+ SearchString,
7
+ } from './location-hook';
8
+
9
+ export type Parser = (route: Path, loose?: boolean) => { pattern: RegExp; keys: string[] };
10
+
11
+ export type NavigateOptions<S = any> = {
12
+ replace?: boolean;
13
+ state?: S;
14
+ transition?: boolean;
15
+ };
16
+
17
+ export type AroundNavHandler = (
18
+ navigate: (to: Path, options?: NavigateOptions) => void,
19
+ to: Path,
20
+ options?: NavigateOptions,
21
+ ) => void;
22
+
23
+ export interface RouterObject {
24
+ readonly hook: BaseLocationHook;
25
+ readonly searchHook: BaseSearchHook;
26
+ readonly base: Path;
27
+ readonly ownBase: Path;
28
+ readonly parser: Parser;
29
+ readonly ssrPath?: Path;
30
+ readonly ssrSearch?: SearchString;
31
+ readonly ssrContext?: SsrContext;
32
+ readonly hrefs: HrefsFormatter;
33
+ readonly aroundNav: AroundNavHandler;
34
+ }
35
+
36
+ export type SsrContext = {
37
+ redirectTo?: Path;
38
+ statusCode?: number;
39
+ };
40
+
41
+ export type RouterOptions = {
42
+ hook?: BaseLocationHook;
43
+ searchHook?: BaseSearchHook;
44
+ base?: Path;
45
+ parser?: Parser;
46
+ ssrPath?: Path;
47
+ ssrSearch?: SearchString;
48
+ ssrContext?: SsrContext;
49
+ hrefs?: HrefsFormatter;
50
+ aroundNav?: AroundNavHandler;
51
+ };
@@ -0,0 +1,136 @@
1
+ import { useSyncExternalStore } from './react-deps';
2
+ import { optionAndSlot, splitSlot, subSlot } from './internal';
3
+ import type { Path, SearchString } from './location-hook';
4
+
5
+ const eventPopstate = 'popstate';
6
+ const eventPushState = 'pushState';
7
+ const eventReplaceState = 'replaceState';
8
+ const eventHashchange = 'hashchange';
9
+ const events = [eventPopstate, eventPushState, eventReplaceState, eventHashchange];
10
+
11
+ const subscribeToLocationUpdates = (callback: () => void) => {
12
+ for (const event of events) {
13
+ addEventListener(event, callback);
14
+ }
15
+ return () => {
16
+ for (const event of events) {
17
+ removeEventListener(event, callback);
18
+ }
19
+ };
20
+ };
21
+
22
+ type Primitive = string | number | bigint | boolean | null | undefined | symbol;
23
+
24
+ function useLocationPropertyInternal<S>(
25
+ fn: () => S,
26
+ ssrFn: (() => S) | undefined,
27
+ slot: symbol | undefined,
28
+ ): S {
29
+ return useSyncExternalStore(
30
+ subscribeToLocationUpdates,
31
+ fn,
32
+ ssrFn,
33
+ subSlot(slot, 'location-property'),
34
+ );
35
+ }
36
+
37
+ export function useLocationProperty<S extends Primitive>(fn: () => S, ssrFn?: () => S): S;
38
+ export function useLocationProperty<S extends Primitive>(
39
+ fn: () => S,
40
+ ...rest: [ssrFn?: () => S, slot?: symbol]
41
+ ): S {
42
+ const [args, slot] = splitSlot(rest);
43
+ return useLocationPropertyInternal(fn, args[0] as (() => S) | undefined, slot);
44
+ }
45
+
46
+ const currentSearch = () => location.search;
47
+
48
+ export type BrowserSearchHook = (options?: { ssrSearch?: SearchString }) => SearchString;
49
+
50
+ export function useSearch(options?: { ssrSearch?: SearchString }): SearchString;
51
+ export function useSearch(
52
+ first: { ssrSearch?: SearchString } | symbol = {},
53
+ second?: symbol,
54
+ ): SearchString {
55
+ const [{ ssrSearch }, slot] = optionAndSlot(first, second);
56
+ return useLocationPropertyInternal(
57
+ currentSearch,
58
+ ssrSearch != null ? () => ssrSearch : currentSearch,
59
+ subSlot(slot, 'search'),
60
+ );
61
+ }
62
+
63
+ const currentPathname = () => location.pathname;
64
+
65
+ function usePathnameInternal({ ssrPath }: { ssrPath?: Path }, slot: symbol | undefined): Path {
66
+ return useLocationPropertyInternal(
67
+ currentPathname,
68
+ ssrPath != null ? () => ssrPath : currentPathname,
69
+ subSlot(slot, 'pathname'),
70
+ );
71
+ }
72
+
73
+ export function usePathname(options?: { ssrPath?: Path }): Path;
74
+ export function usePathname(first: { ssrPath?: Path } | symbol = {}, second?: symbol): Path {
75
+ const [options, slot] = optionAndSlot(first, second);
76
+ return usePathnameInternal(options, slot);
77
+ }
78
+
79
+ const currentHistoryState = () => history.state as unknown;
80
+
81
+ export function useHistoryState<T = any>(): T;
82
+ export function useHistoryState<T = any>(...rest: [slot?: symbol]): T {
83
+ const [, slot] = splitSlot(rest);
84
+ return useLocationPropertyInternal(
85
+ currentHistoryState as () => T,
86
+ () => null as T,
87
+ subSlot(slot, 'history-state'),
88
+ );
89
+ }
90
+
91
+ export function navigate<S = any>(
92
+ to: string | URL,
93
+ options?: { replace?: boolean; state?: S; transition?: boolean },
94
+ ): void;
95
+ export function navigate<S = any>(
96
+ to: string | URL,
97
+ {
98
+ replace = false,
99
+ state = null,
100
+ }: { replace?: boolean; state?: S | null; transition?: boolean } = {},
101
+ ): void {
102
+ history[replace ? eventReplaceState : eventPushState](state, '', to);
103
+ }
104
+
105
+ export type BrowserLocationHook = (options?: { ssrPath?: Path }) => [Path, typeof navigate];
106
+
107
+ export function useBrowserLocation(options?: { ssrPath?: Path }): [Path, typeof navigate];
108
+ export function useBrowserLocation(
109
+ first: { ssrPath?: Path } | symbol = {},
110
+ second?: symbol,
111
+ ): [Path, typeof navigate] {
112
+ const [options, slot] = optionAndSlot(first, second);
113
+ return [usePathnameInternal(options, subSlot(slot, 'browser-location')), navigate];
114
+ }
115
+
116
+ const patchKey = Symbol.for('wouter_v3');
117
+
118
+ if (
119
+ typeof history !== 'undefined' &&
120
+ typeof window !== 'undefined' &&
121
+ typeof (window as unknown as Record<PropertyKey, unknown>)[patchKey] === 'undefined'
122
+ ) {
123
+ for (const type of [eventPushState, eventReplaceState] as const) {
124
+ const original = history[type];
125
+ history[type] = function (...args: Parameters<History[typeof type]>) {
126
+ const result = original.apply(this, args);
127
+ const event = new Event(type) as Event & { arguments?: unknown[] };
128
+ event.arguments = args;
129
+
130
+ dispatchEvent(event);
131
+ return result;
132
+ };
133
+ }
134
+
135
+ Object.defineProperty(window, patchKey, { value: true });
136
+ }
@@ -0,0 +1,77 @@
1
+ import { useSyncExternalStore } from './react-deps';
2
+ import { optionAndSlot, subSlot } from './internal';
3
+ import type { Path } from './location-hook';
4
+
5
+ const listeners: { v: Array<() => void> } = {
6
+ v: [],
7
+ };
8
+
9
+ const onHashChange = () => listeners.v.forEach((callback) => callback());
10
+
11
+ const subscribeToHashUpdates = (callback: () => void) => {
12
+ if (listeners.v.push(callback) === 1) {
13
+ addEventListener('hashchange', onHashChange);
14
+ }
15
+
16
+ return () => {
17
+ listeners.v = listeners.v.filter((item) => item !== callback);
18
+ if (!listeners.v.length) {
19
+ removeEventListener('hashchange', onHashChange);
20
+ }
21
+ };
22
+ };
23
+
24
+ const currentHashLocation = () => '/' + location.hash.replace(/^#?\/?/, '');
25
+
26
+ export function navigate<S = any>(
27
+ to: Path,
28
+ options?: { state?: S; replace?: boolean; transition?: boolean },
29
+ ): void;
30
+ export function navigate<S = any>(
31
+ to: Path,
32
+ {
33
+ state = null,
34
+ replace = false,
35
+ }: { state?: S | null; replace?: boolean; transition?: boolean } = {},
36
+ ): void {
37
+ const oldURL = location.href;
38
+ const [hash, search] = to.replace(/^#?\/?/, '').split('?');
39
+ const url = new URL(location.href);
40
+ url.hash = `/${hash}`;
41
+ if (search) {
42
+ url.search = search;
43
+ }
44
+ const newURL = url.href;
45
+
46
+ if (replace) {
47
+ history.replaceState(state, '', newURL);
48
+ } else {
49
+ history.pushState(state, '', newURL);
50
+ }
51
+
52
+ const event =
53
+ typeof HashChangeEvent !== 'undefined'
54
+ ? new HashChangeEvent('hashchange', { oldURL, newURL })
55
+ : new Event('hashchange');
56
+
57
+ dispatchEvent(event);
58
+ }
59
+
60
+ export function useHashLocation(options?: { ssrPath?: Path }): [Path, typeof navigate];
61
+ export function useHashLocation(
62
+ first: { ssrPath?: Path } | symbol = {},
63
+ second?: symbol,
64
+ ): [Path, typeof navigate] {
65
+ const [{ ssrPath = '/' }, slot] = optionAndSlot(first, second);
66
+ return [
67
+ useSyncExternalStore(
68
+ subscribeToHashUpdates,
69
+ currentHashLocation,
70
+ () => ssrPath,
71
+ subSlot(slot, 'hash-location'),
72
+ ),
73
+ navigate,
74
+ ];
75
+ }
76
+
77
+ useHashLocation.hrefs = (href: string) => '#' + href;