@tanstack/react-router 0.0.1-beta.4 → 0.0.1-beta.45

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.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ */
9
+
10
+ 'use strict'
11
+
12
+ // Intentionally not using named imports because Rollup uses dynamic
13
+ // dispatch for CommonJS interop named imports.
14
+ import * as React from 'react'
15
+
16
+ export const useSyncExternalStore = React.useSyncExternalStore
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ */
9
+
10
+ import { useSyncExternalStore as client } from './useSyncExternalStoreShimClient'
11
+ import { useSyncExternalStore as server } from './useSyncExternalStoreShimServer'
12
+ import { useSyncExternalStore as builtInAPI } from 'react'
13
+
14
+ const shim = typeof document === 'undefined' ? server : client
15
+
16
+ export const useSyncExternalStore: <T>(
17
+ subscribe: (cb: () => void) => () => void,
18
+ getSnapshot: () => T,
19
+ getServerSnapshot?: () => T,
20
+ ) => T = builtInAPI !== undefined ? builtInAPI : shim
@@ -0,0 +1,87 @@
1
+ import * as React from 'react'
2
+ const { useState, useEffect, useLayoutEffect, useDebugValue } = React
3
+
4
+ let didWarnOld18Alpha = false
5
+ let didWarnUncachedGetSnapshot = false
6
+
7
+ export function useSyncExternalStore<T>(
8
+ subscribe: (cb: () => void) => () => void,
9
+ getSnapshot: () => T,
10
+ getServerSnapshot?: () => T,
11
+ ): T {
12
+ const value = getSnapshot()
13
+
14
+ // Because updates are synchronous, we don't queue them. Instead we force a
15
+ // re-render whenever the subscribed state changes by updating an some
16
+ // arbitrary useState hook. Then, during render, we call getSnapshot to read
17
+ // the current value.
18
+ //
19
+ // Because we don't actually use the state returned by the useState hook, we
20
+ // can save a bit of memory by storing other stuff in that slot.
21
+ //
22
+ // To implement the early bailout, we need to track some things on a mutable
23
+ // object. Usually, we would put that in a useRef hook, but we can stash it in
24
+ // our useState hook instead.
25
+ //
26
+ // To force a re-render, we call forceUpdate({inst}). That works because the
27
+ // new object always fails an equality check.
28
+ const [{ inst }, forceUpdate] = useState({ inst: { value, getSnapshot } })
29
+
30
+ // Track the latest getSnapshot function with a ref. This needs to be updated
31
+ // in the layout phase so we can access it during the tearing check that
32
+ // happens on subscribe.
33
+ useLayoutEffect(() => {
34
+ inst.value = value
35
+ inst.getSnapshot = getSnapshot
36
+
37
+ // Whenever getSnapshot or subscribe changes, we need to check in the
38
+ // commit phase if there was an interleaved mutation. In concurrent mode
39
+ // this can happen all the time, but even in synchronous mode, an earlier
40
+ // effect may have mutated the store.
41
+ if (checkIfSnapshotChanged(inst)) {
42
+ // Force a re-render.
43
+ forceUpdate({ inst })
44
+ }
45
+ }, [subscribe, value, getSnapshot])
46
+
47
+ useEffect(() => {
48
+ // Check for changes right before subscribing. Subsequent changes will be
49
+ // detected in the subscription handler.
50
+ if (checkIfSnapshotChanged(inst)) {
51
+ // Force a re-render.
52
+ forceUpdate({ inst })
53
+ }
54
+ const handleStoreChange = () => {
55
+ // TODO: Because there is no cross-renderer API for batching updates, it's
56
+ // up to the consumer of this library to wrap their subscription event
57
+ // with unstable_batchedUpdates. Should we try to detect when this isn't
58
+ // the case and print a warning in development?
59
+
60
+ // The store changed. Check if the snapshot changed since the last time we
61
+ // read from the store.
62
+ if (checkIfSnapshotChanged(inst)) {
63
+ // Force a re-render.
64
+ forceUpdate({ inst })
65
+ }
66
+ }
67
+ // Subscribe to the store and return a clean-up function.
68
+ return subscribe(handleStoreChange)
69
+ }, [subscribe])
70
+
71
+ useDebugValue(value)
72
+ return value
73
+ }
74
+
75
+ function checkIfSnapshotChanged<T>(inst: {
76
+ value: T
77
+ getSnapshot: () => T
78
+ }): boolean {
79
+ const latestGetSnapshot = inst.getSnapshot
80
+ const prevValue = inst.value
81
+ try {
82
+ const nextValue = latestGetSnapshot()
83
+ return !Object.is(prevValue, nextValue)
84
+ } catch (error) {
85
+ return true
86
+ }
87
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ */
9
+
10
+ export function useSyncExternalStore<T>(
11
+ subscribe: (cb: () => void) => () => void,
12
+ getSnapshot: () => T,
13
+ getServerSnapshot?: () => T,
14
+ ): T {
15
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
16
+ // React do not expose a way to check if we're hydrating. So users of the shim
17
+ // will need to track that themselves and return the correct value
18
+ // from `getSnapshot`.
19
+ return getSnapshot()
20
+ }
@@ -1,465 +0,0 @@
1
- /**
2
- * react-router
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
16
- var React = require('react');
17
- var shim = require('use-sync-external-store/shim');
18
- var index = require('../../router-core/build/esm/index.js');
19
-
20
- function _interopNamespace(e) {
21
- if (e && e.__esModule) return e;
22
- var n = Object.create(null);
23
- if (e) {
24
- Object.keys(e).forEach(function (k) {
25
- if (k !== 'default') {
26
- var d = Object.getOwnPropertyDescriptor(e, k);
27
- Object.defineProperty(n, k, d.get ? d : {
28
- enumerable: true,
29
- get: function () { return e[k]; }
30
- });
31
- }
32
- });
33
- }
34
- n["default"] = e;
35
- return Object.freeze(n);
36
- }
37
-
38
- var React__namespace = /*#__PURE__*/_interopNamespace(React);
39
-
40
- const _excluded = ["type", "children", "target", "activeProps", "inactiveProps", "activeOptions", "disabled", "hash", "search", "params", "to", "preload", "preloadDelay", "preloadMaxAge", "replace", "style", "className", "onClick", "onFocus", "onMouseEnter", "onMouseLeave", "onTouchStart", "onTouchEnd"],
41
- _excluded2 = ["pending", "caseSensitive", "children"],
42
- _excluded3 = ["children", "router"];
43
- //
44
- const matchesContext = /*#__PURE__*/React__namespace.createContext(null);
45
- const routerContext = /*#__PURE__*/React__namespace.createContext(null); // Detect if we're in the DOM
46
-
47
- const isDOM = Boolean(typeof window !== 'undefined' && window.document && window.document.createElement);
48
- const useLayoutEffect = isDOM ? React__namespace.useLayoutEffect : React__namespace.useEffect;
49
- function MatchesProvider(props) {
50
- return /*#__PURE__*/React__namespace.createElement(matchesContext.Provider, props);
51
- }
52
-
53
- const useRouterSubscription = router => {
54
- shim.useSyncExternalStore(cb => router.subscribe(() => cb()), () => router.state, () => router.state);
55
- };
56
-
57
- function createReactRouter(opts) {
58
- const makeRouteExt = (route, router) => {
59
- return {
60
- useRoute: function useRoute(subRouteId) {
61
- if (subRouteId === void 0) {
62
- subRouteId = '.';
63
- }
64
-
65
- const resolvedRouteId = router.resolvePath(route.routeId, subRouteId);
66
- const resolvedRoute = router.getRoute(resolvedRouteId);
67
- useRouterSubscription(router);
68
- index.invariant(resolvedRoute, "Could not find a route for route \"" + resolvedRouteId + "\"! Did you forget to add it to your route config?");
69
- return resolvedRoute;
70
- },
71
- linkProps: options => {
72
- var _functionalUpdate, _functionalUpdate2;
73
-
74
- const {
75
- // custom props
76
- target,
77
- activeProps = () => ({
78
- className: 'active'
79
- }),
80
- inactiveProps = () => ({}),
81
- disabled,
82
- // element props
83
- style,
84
- className,
85
- onClick,
86
- onFocus,
87
- onMouseEnter,
88
- onMouseLeave
89
- } = options,
90
- rest = _rollupPluginBabelHelpers.objectWithoutPropertiesLoose(options, _excluded);
91
-
92
- const linkInfo = route.buildLink(options);
93
-
94
- if (linkInfo.type === 'external') {
95
- const {
96
- href
97
- } = linkInfo;
98
- return {
99
- href
100
- };
101
- }
102
-
103
- const {
104
- handleClick,
105
- handleFocus,
106
- handleEnter,
107
- handleLeave,
108
- isActive,
109
- next
110
- } = linkInfo;
111
-
112
- const composeHandlers = handlers => e => {
113
- e.persist();
114
- handlers.forEach(handler => {
115
- if (handler) handler(e);
116
- });
117
- }; // Get the active props
118
-
119
-
120
- const resolvedActiveProps = isActive ? (_functionalUpdate = index.functionalUpdate(activeProps, {})) != null ? _functionalUpdate : {} : {}; // Get the inactive props
121
-
122
- const resolvedInactiveProps = isActive ? {} : (_functionalUpdate2 = index.functionalUpdate(inactiveProps, {})) != null ? _functionalUpdate2 : {};
123
- return _rollupPluginBabelHelpers["extends"]({}, resolvedActiveProps, resolvedInactiveProps, rest, {
124
- href: disabled ? undefined : next.href,
125
- onClick: composeHandlers([handleClick, onClick]),
126
- onFocus: composeHandlers([handleFocus, onFocus]),
127
- onMouseEnter: composeHandlers([handleEnter, onMouseEnter]),
128
- onMouseLeave: composeHandlers([handleLeave, onMouseLeave]),
129
- target,
130
- style: _rollupPluginBabelHelpers["extends"]({}, style, resolvedActiveProps.style, resolvedInactiveProps.style),
131
- className: [className, resolvedActiveProps.className, resolvedInactiveProps.className].filter(Boolean).join(' ') || undefined
132
- }, disabled ? {
133
- role: 'link',
134
- 'aria-disabled': true
135
- } : undefined, {
136
- ['data-status']: isActive ? 'active' : undefined
137
- });
138
- },
139
- Link: /*#__PURE__*/React__namespace.forwardRef((props, ref) => {
140
- const linkProps = route.linkProps(props);
141
- useRouterSubscription(router);
142
- return /*#__PURE__*/React__namespace.createElement("a", _rollupPluginBabelHelpers["extends"]({
143
- ref: ref
144
- }, linkProps, {
145
- children: typeof props.children === 'function' ? props.children({
146
- isActive: linkProps['data-status'] === 'active'
147
- }) : props.children
148
- }));
149
- }),
150
- MatchRoute: opts => {
151
- const {
152
- pending,
153
- caseSensitive
154
- } = opts,
155
- rest = _rollupPluginBabelHelpers.objectWithoutPropertiesLoose(opts, _excluded2);
156
-
157
- const params = route.matchRoute(rest, {
158
- pending,
159
- caseSensitive
160
- });
161
-
162
- if (!params) {
163
- return null;
164
- }
165
-
166
- return typeof opts.children === 'function' ? opts.children(params) : opts.children;
167
- }
168
- };
169
- };
170
-
171
- const coreRouter = index.createRouter(_rollupPluginBabelHelpers["extends"]({}, opts, {
172
- createRouter: router => {
173
- const routerExt = {
174
- useState: () => {
175
- useRouterSubscription(router);
176
- return router.state;
177
- },
178
- useMatch: routeId => {
179
- useRouterSubscription(router);
180
- index.invariant(routeId !== index.rootRouteId, "\"" + index.rootRouteId + "\" cannot be used with useMatch! Did you mean to useRoute(\"" + index.rootRouteId + "\")?");
181
-
182
- const runtimeMatch = _useMatch();
183
-
184
- const match = router.state.matches.find(d => d.routeId === routeId);
185
- index.invariant(match, "Could not find a match for route \"" + routeId + "\" being rendered in this component!");
186
- index.invariant(runtimeMatch.routeId == (match == null ? void 0 : match.routeId), "useMatch('" + (match == null ? void 0 : match.routeId) + "') is being called in a component that is meant to render the '" + runtimeMatch.routeId + "' route. Did you mean to 'useRoute(" + (match == null ? void 0 : match.routeId) + ")' instead?");
187
-
188
- if (!match) {
189
- index.invariant('Match not found!');
190
- }
191
-
192
- return match;
193
- }
194
- };
195
- const routeExt = makeRouteExt(router.getRoute('/'), router);
196
- Object.assign(router, routerExt, routeExt);
197
- },
198
- createRoute: _ref => {
199
- let {
200
- router,
201
- route
202
- } = _ref;
203
- const routeExt = makeRouteExt(route, router);
204
- Object.assign(route, routeExt);
205
- },
206
- createElement: async element => {
207
- if (typeof element === 'function') {
208
- const res = await element(); // Support direct import() calls
209
-
210
- if (typeof res === 'object' && res.default) {
211
- return /*#__PURE__*/React__namespace.createElement(res.default);
212
- } else {
213
- return res;
214
- }
215
- }
216
-
217
- return element;
218
- }
219
- }));
220
- return coreRouter;
221
- }
222
- function RouterProvider(_ref2) {
223
- let {
224
- children,
225
- router
226
- } = _ref2,
227
- rest = _rollupPluginBabelHelpers.objectWithoutPropertiesLoose(_ref2, _excluded3);
228
-
229
- router.update(rest);
230
- useRouterSubscription(router);
231
- useLayoutEffect(() => {
232
- return router.mount();
233
- }, [router]);
234
- return /*#__PURE__*/React__namespace.createElement(routerContext.Provider, {
235
- value: {
236
- router
237
- }
238
- }, /*#__PURE__*/React__namespace.createElement(MatchesProvider, {
239
- value: router.state.matches
240
- }, children != null ? children : /*#__PURE__*/React__namespace.createElement(Outlet, null)));
241
- }
242
-
243
- function useRouter() {
244
- const value = React__namespace.useContext(routerContext);
245
- index.warning(!value, 'useRouter must be used inside a <Router> component!');
246
- useRouterSubscription(value.router);
247
- return value.router;
248
- }
249
-
250
- function useMatches() {
251
- return React__namespace.useContext(matchesContext);
252
- } // function useParentMatches(): RouteMatch[] {
253
- // const router = useRouter()
254
- // const match = useMatch()
255
- // const matches = router.state.matches
256
- // return matches.slice(
257
- // 0,
258
- // matches.findIndex((d) => d.matchId === match.matchId) - 1,
259
- // )
260
- // }
261
-
262
-
263
- function _useMatch() {
264
- var _useMatches;
265
-
266
- return (_useMatches = useMatches()) == null ? void 0 : _useMatches[0];
267
- }
268
-
269
- function Outlet() {
270
- var _childMatch$options$c;
271
-
272
- const router = useRouter();
273
- const [, ...matches] = useMatches();
274
- const childMatch = matches[0];
275
- if (!childMatch) return null;
276
-
277
- const element = (() => {
278
- var _childMatch$__$errorE, _ref4;
279
-
280
- if (!childMatch) {
281
- return null;
282
- }
283
-
284
- const errorElement = (_childMatch$__$errorE = childMatch.__.errorElement) != null ? _childMatch$__$errorE : router.options.defaultErrorElement;
285
-
286
- if (childMatch.status === 'error') {
287
- if (errorElement) {
288
- return errorElement;
289
- }
290
-
291
- if (childMatch.options.useErrorBoundary || router.options.useErrorBoundary) {
292
- throw childMatch.error;
293
- }
294
-
295
- return /*#__PURE__*/React__namespace.createElement(DefaultErrorBoundary, {
296
- error: childMatch.error
297
- });
298
- }
299
-
300
- if (childMatch.status === 'loading' || childMatch.status === 'idle') {
301
- if (childMatch.isPending) {
302
- var _childMatch$__$pendin;
303
-
304
- const pendingElement = (_childMatch$__$pendin = childMatch.__.pendingElement) != null ? _childMatch$__$pendin : router.options.defaultPendingElement;
305
-
306
- if (childMatch.options.pendingMs || pendingElement) {
307
- var _ref3;
308
-
309
- return (_ref3 = pendingElement) != null ? _ref3 : null;
310
- }
311
- }
312
-
313
- return null;
314
- }
315
-
316
- return (_ref4 = childMatch.__.element) != null ? _ref4 : router.options.defaultElement;
317
- })();
318
-
319
- const catchElement = (_childMatch$options$c = childMatch == null ? void 0 : childMatch.options.catchElement) != null ? _childMatch$options$c : router.options.defaultCatchElement;
320
- return /*#__PURE__*/React__namespace.createElement(MatchesProvider, {
321
- value: matches,
322
- key: childMatch.matchId
323
- }, /*#__PURE__*/React__namespace.createElement(CatchBoundary, {
324
- catchElement: catchElement
325
- }, element));
326
- }
327
-
328
- class CatchBoundary extends React__namespace.Component {
329
- constructor() {
330
- super(...arguments);
331
- this.state = {
332
- error: false
333
- };
334
-
335
- this.reset = () => {
336
- this.setState({
337
- error: false,
338
- info: false
339
- });
340
- };
341
- }
342
-
343
- componentDidCatch(error, info) {
344
- console.error(error);
345
- this.setState({
346
- error,
347
- info
348
- });
349
- }
350
-
351
- render() {
352
- var _this$props$catchElem;
353
-
354
- const catchElement = (_this$props$catchElem = this.props.catchElement) != null ? _this$props$catchElem : DefaultErrorBoundary;
355
-
356
- if (this.state.error) {
357
- return typeof catchElement === 'function' ? catchElement(this.state) : catchElement;
358
- }
359
-
360
- return this.props.children;
361
- }
362
-
363
- }
364
-
365
- function DefaultErrorBoundary(_ref5) {
366
- let {
367
- error
368
- } = _ref5;
369
- return /*#__PURE__*/React__namespace.createElement("div", {
370
- style: {
371
- padding: '.5rem',
372
- maxWidth: '100%'
373
- }
374
- }, /*#__PURE__*/React__namespace.createElement("strong", {
375
- style: {
376
- fontSize: '1.2rem'
377
- }
378
- }, "Something went wrong!"), /*#__PURE__*/React__namespace.createElement("div", {
379
- style: {
380
- height: '.5rem'
381
- }
382
- }), /*#__PURE__*/React__namespace.createElement("div", null, /*#__PURE__*/React__namespace.createElement("pre", null, error.message ? /*#__PURE__*/React__namespace.createElement("code", {
383
- style: {
384
- fontSize: '.7em',
385
- border: '1px solid red',
386
- borderRadius: '.25rem',
387
- padding: '.5rem',
388
- color: 'red'
389
- }
390
- }, error.message) : null)), /*#__PURE__*/React__namespace.createElement("div", {
391
- style: {
392
- height: '1rem'
393
- }
394
- }), /*#__PURE__*/React__namespace.createElement("div", {
395
- style: {
396
- fontSize: '.8em',
397
- borderLeft: '3px solid rgba(127, 127, 127, 1)',
398
- paddingLeft: '.5rem',
399
- opacity: 0.5
400
- }
401
- }, "If you are the owner of this website, it's highly recommended that you configure your own custom Catch/Error boundaries for the router. You can optionally configure a boundary for each route."));
402
- }
403
- function usePrompt(message, when) {
404
- const router = useRouter();
405
- React__namespace.useEffect(() => {
406
- if (!when) return;
407
- let unblock = router.history.block(transition => {
408
- if (window.confirm(message)) {
409
- unblock();
410
- transition.retry();
411
- } else {
412
- router.location.pathname = window.location.pathname;
413
- }
414
- });
415
- return unblock;
416
- }, [when, location, message]);
417
- }
418
- function Prompt(_ref6) {
419
- let {
420
- message,
421
- when,
422
- children
423
- } = _ref6;
424
- usePrompt(message, when != null ? when : true);
425
- return children != null ? children : null;
426
- }
427
-
428
- exports.cascadeLoaderData = index.cascadeLoaderData;
429
- exports.cleanPath = index.cleanPath;
430
- exports.createBrowserHistory = index.createBrowserHistory;
431
- exports.createHashHistory = index.createHashHistory;
432
- exports.createMemoryHistory = index.createMemoryHistory;
433
- exports.createRoute = index.createRoute;
434
- exports.createRouteConfig = index.createRouteConfig;
435
- exports.createRouteMatch = index.createRouteMatch;
436
- exports.createRouter = index.createRouter;
437
- exports.decode = index.decode;
438
- exports.defaultParseSearch = index.defaultParseSearch;
439
- exports.defaultStringifySearch = index.defaultStringifySearch;
440
- exports.encode = index.encode;
441
- exports.functionalUpdate = index.functionalUpdate;
442
- exports.interpolatePath = index.interpolatePath;
443
- exports.invariant = index.invariant;
444
- exports.joinPaths = index.joinPaths;
445
- exports.last = index.last;
446
- exports.matchByPath = index.matchByPath;
447
- exports.matchPathname = index.matchPathname;
448
- exports.parsePathname = index.parsePathname;
449
- exports.parseSearchWith = index.parseSearchWith;
450
- exports.replaceEqualDeep = index.replaceEqualDeep;
451
- exports.resolvePath = index.resolvePath;
452
- exports.rootRouteId = index.rootRouteId;
453
- exports.stringifySearchWith = index.stringifySearchWith;
454
- exports.trimPath = index.trimPath;
455
- exports.trimPathLeft = index.trimPathLeft;
456
- exports.trimPathRight = index.trimPathRight;
457
- exports.warning = index.warning;
458
- exports.DefaultErrorBoundary = DefaultErrorBoundary;
459
- exports.MatchesProvider = MatchesProvider;
460
- exports.Outlet = Outlet;
461
- exports.Prompt = Prompt;
462
- exports.RouterProvider = RouterProvider;
463
- exports.createReactRouter = createReactRouter;
464
- exports.usePrompt = usePrompt;
465
- //# sourceMappingURL=index.js.map