Server: Phase 2 (REVIEW not respected yet)
This commit is contained in:
1 parent
5d16ded553
commit
142b47674d
4271 files changed
+1203269
No files matched your search
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-present Tanner Linsley
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
//#region src/index.ts
|
||||
var stateIndexKey = "__TSR_index";
|
||||
var popStateEvent = "popstate";
|
||||
var beforeUnloadEvent = "beforeunload";
|
||||
/**
|
||||
* Turn protocol-relative inputs such as "//evil.example" into paths
|
||||
* such as "/evil.example", keeping navigation on the current origin.
|
||||
*
|
||||
* For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,
|
||||
* removes tabs/newlines, and treats backslashes as slashes, so inputs like
|
||||
* "/\evil.example" also need normalization. This only allocates when those
|
||||
* rules would make the input protocol-relative.
|
||||
*/
|
||||
var protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/;
|
||||
function normalizeProtocolRelative(url) {
|
||||
const match = protocolRelativePrefix.exec(url);
|
||||
return match ? "/" + url.slice(match[0].length) : url;
|
||||
}
|
||||
function normalizeHref(href) {
|
||||
if (/[\x00-\x1f\x7f]/.test(href)) href = href.replace(/[\x00-\x1f\x7f]/g, (character) => " \n\r".includes(character) ? "" : encodeURIComponent(character));
|
||||
return normalizeProtocolRelative(href);
|
||||
}
|
||||
function createHistory(opts) {
|
||||
let location = opts.getLocation();
|
||||
const subscribers = /* @__PURE__ */ new Set();
|
||||
const notify = (action) => {
|
||||
location = opts.getLocation();
|
||||
subscribers.forEach((subscriber) => subscriber({
|
||||
location,
|
||||
action
|
||||
}));
|
||||
};
|
||||
const handleIndexChange = (action) => {
|
||||
if (opts.notifyOnIndexChange ?? true) notify(action);
|
||||
else location = opts.getLocation();
|
||||
};
|
||||
const tryNavigation = async ({ task, navigateOpts, ...actionInfo }) => {
|
||||
if (navigateOpts?.ignoreBlocker ?? false) {
|
||||
task();
|
||||
return;
|
||||
}
|
||||
const blockers = opts.getBlockers?.() ?? [];
|
||||
const isPushOrReplace = actionInfo.type === "PUSH" || actionInfo.type === "REPLACE";
|
||||
if (typeof document !== "undefined" && blockers.length && isPushOrReplace) for (const blocker of blockers) {
|
||||
const nextLocation = parseHref(actionInfo.path, actionInfo.state);
|
||||
if (await blocker.blockerFn({
|
||||
currentLocation: location,
|
||||
nextLocation,
|
||||
action: actionInfo.type
|
||||
})) {
|
||||
opts.onBlocked?.();
|
||||
return;
|
||||
}
|
||||
}
|
||||
task();
|
||||
};
|
||||
return {
|
||||
get location() {
|
||||
return location;
|
||||
},
|
||||
get length() {
|
||||
return opts.getLength();
|
||||
},
|
||||
subscribers,
|
||||
subscribe: (cb) => {
|
||||
subscribers.add(cb);
|
||||
return () => {
|
||||
subscribers.delete(cb);
|
||||
};
|
||||
},
|
||||
push: (path, state, navigateOpts) => {
|
||||
const currentIndex = location.state[stateIndexKey];
|
||||
state = assignKeyAndIndex(currentIndex + 1, state);
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.pushState(path, state);
|
||||
notify({ type: "PUSH" });
|
||||
},
|
||||
navigateOpts,
|
||||
type: "PUSH",
|
||||
path,
|
||||
state
|
||||
});
|
||||
},
|
||||
replace: (path, state, navigateOpts) => {
|
||||
const currentIndex = location.state[stateIndexKey];
|
||||
state = assignKeyAndIndex(currentIndex, state);
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.replaceState(path, state);
|
||||
notify({ type: "REPLACE" });
|
||||
},
|
||||
navigateOpts,
|
||||
type: "REPLACE",
|
||||
path,
|
||||
state
|
||||
});
|
||||
},
|
||||
go: (index, navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.go(index, navigateOpts?.ignoreBlocker ?? false);
|
||||
handleIndexChange({
|
||||
type: "GO",
|
||||
index
|
||||
});
|
||||
},
|
||||
navigateOpts,
|
||||
type: "GO"
|
||||
});
|
||||
},
|
||||
back: (navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.back(navigateOpts?.ignoreBlocker ?? false);
|
||||
handleIndexChange({ type: "BACK" });
|
||||
},
|
||||
navigateOpts,
|
||||
type: "BACK"
|
||||
});
|
||||
},
|
||||
forward: (navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.forward(navigateOpts?.ignoreBlocker ?? false);
|
||||
handleIndexChange({ type: "FORWARD" });
|
||||
},
|
||||
navigateOpts,
|
||||
type: "FORWARD"
|
||||
});
|
||||
},
|
||||
canGoBack: () => location.state[stateIndexKey] !== 0,
|
||||
createHref: (str) => opts.createHref(str),
|
||||
block: (blocker) => {
|
||||
if (!opts.setBlockers) return () => {};
|
||||
const blockers = opts.getBlockers?.() ?? [];
|
||||
opts.setBlockers([...blockers, blocker]);
|
||||
return () => {
|
||||
const blockers = opts.getBlockers?.() ?? [];
|
||||
opts.setBlockers?.(blockers.filter((b) => b !== blocker));
|
||||
};
|
||||
},
|
||||
flush: () => opts.flush?.(),
|
||||
destroy: () => opts.destroy?.(),
|
||||
notify,
|
||||
_getBlockers: () => opts.getBlockers?.() ?? []
|
||||
};
|
||||
}
|
||||
function assignKeyAndIndex(index, state) {
|
||||
const key = createRandomKey();
|
||||
return {
|
||||
...state,
|
||||
key,
|
||||
__TSR_key: key,
|
||||
[stateIndexKey]: index
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Creates a history object that can be used to interact with the browser's
|
||||
* navigation. This is a lightweight API wrapping the browser's native methods.
|
||||
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
|
||||
* IMPORTANT: This API implements history throttling via a microtask to prevent
|
||||
* excessive calls to the history API. In some browsers, calling history.pushState or
|
||||
* history.replaceState in quick succession can cause the browser to ignore subsequent
|
||||
* calls. This API smooths out those differences and ensures that your application
|
||||
* state will *eventually* match the browser state. In most cases, this is not a problem,
|
||||
* but if you need to ensure that the browser state is up to date, you can use the
|
||||
* `history.flush` method to immediately flush all pending state changes to the browser URL.
|
||||
* @param opts
|
||||
* @param opts.getHref A function that returns the current href (path + search + hash)
|
||||
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
|
||||
* @returns A history instance
|
||||
*/
|
||||
function createBrowserHistory(opts) {
|
||||
const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
|
||||
const originalPushState = win.history.pushState;
|
||||
const originalReplaceState = win.history.replaceState;
|
||||
let blockers = [];
|
||||
const _getBlockers = () => blockers;
|
||||
const _setBlockers = (newBlockers) => blockers = newBlockers;
|
||||
const createHref = (path) => normalizeHref(opts?.createHref ? opts.createHref(path) : path);
|
||||
const parseLocation = opts?.parseLocation ?? (() => parseHref(`${win.location.pathname}${win.location.search}${win.location.hash}`, win.history.state));
|
||||
if (!win.history.state?.__TSR_key && !win.history.state?.key) {
|
||||
const addedKey = createRandomKey();
|
||||
win.history.replaceState({
|
||||
[stateIndexKey]: 0,
|
||||
key: addedKey,
|
||||
__TSR_key: addedKey
|
||||
}, "");
|
||||
}
|
||||
let currentLocation = parseLocation();
|
||||
let rollbackLocation;
|
||||
let nextPopIsGo = false;
|
||||
let ignoreNextPop = false;
|
||||
let skipBlockerNextPop = false;
|
||||
let ignoreNextBeforeUnload = false;
|
||||
const getLocation = () => currentLocation;
|
||||
let next;
|
||||
const flush = () => {
|
||||
if (!next) return;
|
||||
history._ignoreSubscribers = true;
|
||||
(next[2] ? win.history.pushState : win.history.replaceState)(next[1], "", next[0]);
|
||||
history._ignoreSubscribers = false;
|
||||
next = void 0;
|
||||
rollbackLocation = void 0;
|
||||
};
|
||||
const queueHistoryAction = (isPush, destHref, state) => {
|
||||
const href = opts?.createHref ? createHref(destHref) : void 0;
|
||||
const hasPendingAction = !!next;
|
||||
if (!hasPendingAction) rollbackLocation = currentLocation;
|
||||
currentLocation = parseHref(destHref, state);
|
||||
next = [
|
||||
href ?? currentLocation.href,
|
||||
state,
|
||||
next?.[2] || isPush
|
||||
];
|
||||
if (!hasPendingAction) queueMicrotask(() => flush());
|
||||
};
|
||||
const onPushPop = (type) => {
|
||||
currentLocation = parseLocation();
|
||||
history.notify({ type });
|
||||
};
|
||||
const onPushPopEvent = async () => {
|
||||
ignoreNextBeforeUnload = false;
|
||||
if (ignoreNextPop) {
|
||||
ignoreNextPop = false;
|
||||
return;
|
||||
}
|
||||
const nextLocation = parseLocation();
|
||||
const delta = nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey];
|
||||
const isForward = delta === 1;
|
||||
const isBack = delta === -1;
|
||||
const isGo = !isForward && !isBack || nextPopIsGo;
|
||||
nextPopIsGo = false;
|
||||
const action = isGo ? "GO" : isBack ? "BACK" : "FORWARD";
|
||||
const notify = isGo ? {
|
||||
type: "GO",
|
||||
index: delta
|
||||
} : { type: isBack ? "BACK" : "FORWARD" };
|
||||
if (skipBlockerNextPop) skipBlockerNextPop = false;
|
||||
else {
|
||||
const blockers = _getBlockers();
|
||||
if (typeof document !== "undefined" && blockers.length) {
|
||||
for (const blocker of blockers) if (await blocker.blockerFn({
|
||||
currentLocation,
|
||||
nextLocation,
|
||||
action
|
||||
})) {
|
||||
ignoreNextPop = true;
|
||||
win.history.go(-delta);
|
||||
history.notify(notify);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
currentLocation = parseLocation();
|
||||
history.notify(notify);
|
||||
};
|
||||
const onBeforeUnload = (e) => {
|
||||
if (ignoreNextBeforeUnload) {
|
||||
ignoreNextBeforeUnload = false;
|
||||
return;
|
||||
}
|
||||
let shouldBlock = false;
|
||||
const blockers = _getBlockers();
|
||||
if (typeof document !== "undefined" && blockers.length) for (const blocker of blockers) {
|
||||
const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true;
|
||||
if (shouldHaveBeforeUnload === true) {
|
||||
shouldBlock = true;
|
||||
break;
|
||||
}
|
||||
if (typeof shouldHaveBeforeUnload === "function" && shouldHaveBeforeUnload() === true) {
|
||||
shouldBlock = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (shouldBlock) {
|
||||
e.preventDefault();
|
||||
return e.returnValue = "";
|
||||
}
|
||||
};
|
||||
const history = createHistory({
|
||||
getLocation,
|
||||
getLength: () => win.history.length,
|
||||
pushState: (href, state) => queueHistoryAction(true, href, state),
|
||||
replaceState: (href, state) => queueHistoryAction(false, href, state),
|
||||
back: (ignoreBlocker) => {
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true;
|
||||
ignoreNextBeforeUnload = true;
|
||||
}
|
||||
return win.history.back();
|
||||
},
|
||||
forward: (ignoreBlocker) => {
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true;
|
||||
ignoreNextBeforeUnload = true;
|
||||
}
|
||||
win.history.forward();
|
||||
},
|
||||
go: (n, ignoreBlocker) => {
|
||||
nextPopIsGo = true;
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true;
|
||||
ignoreNextBeforeUnload = true;
|
||||
}
|
||||
win.history.go(n);
|
||||
},
|
||||
createHref: (href) => createHref(href),
|
||||
flush,
|
||||
destroy: () => {
|
||||
win.history.pushState = originalPushState;
|
||||
win.history.replaceState = originalReplaceState;
|
||||
win.removeEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
|
||||
win.removeEventListener(popStateEvent, onPushPopEvent);
|
||||
},
|
||||
onBlocked: () => {
|
||||
if (rollbackLocation && currentLocation !== rollbackLocation) currentLocation = rollbackLocation;
|
||||
},
|
||||
getBlockers: _getBlockers,
|
||||
setBlockers: _setBlockers,
|
||||
notifyOnIndexChange: false
|
||||
});
|
||||
history._ignoreNextBeforeUnload = (href) => {
|
||||
ignoreNextBeforeUnload = false;
|
||||
try {
|
||||
href = new URL(href, win.document.baseURI).href;
|
||||
ignoreNextBeforeUnload = /^https?:/.test(href) && (!href.includes("#") || href.split("#")[0] !== win.location.href.split("#")[0]);
|
||||
} catch {}
|
||||
};
|
||||
win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
|
||||
win.addEventListener(popStateEvent, onPushPopEvent);
|
||||
win.history.pushState = function(...args) {
|
||||
const res = originalPushState.apply(win.history, args);
|
||||
if (!history._ignoreSubscribers) onPushPop("PUSH");
|
||||
return res;
|
||||
};
|
||||
win.history.replaceState = function(...args) {
|
||||
const res = originalReplaceState.apply(win.history, args);
|
||||
if (!history._ignoreSubscribers) onPushPop("REPLACE");
|
||||
return res;
|
||||
};
|
||||
return history;
|
||||
}
|
||||
/**
|
||||
* Create a hash-based history implementation.
|
||||
* Useful for static hosts or environments without server URL rewriting.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
function createHashHistory(opts) {
|
||||
const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
|
||||
return createBrowserHistory({
|
||||
window: win,
|
||||
parseLocation: () => {
|
||||
const hashSplit = win.location.hash.split("#").slice(1);
|
||||
const pathPart = hashSplit[0] ?? "/";
|
||||
const searchPart = win.location.search;
|
||||
const hashEntries = hashSplit.slice(1);
|
||||
return parseHref(`${pathPart}${searchPart}${hashEntries.length === 0 ? "" : `#${hashEntries.join("#")}`}`, win.history.state);
|
||||
},
|
||||
createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Create an in-memory history implementation.
|
||||
* Ideal for server rendering, tests, and non-DOM environments.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
function createMemoryHistory(opts = { initialEntries: ["/"] }) {
|
||||
const entries = opts.initialEntries;
|
||||
let index = opts.initialIndex ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) : entries.length - 1;
|
||||
const states = entries.map((_entry, index) => assignKeyAndIndex(index, void 0));
|
||||
const getLocation = () => parseHref(entries[index], states[index]);
|
||||
let blockers = [];
|
||||
const _getBlockers = () => blockers;
|
||||
const _setBlockers = (newBlockers) => blockers = newBlockers;
|
||||
return createHistory({
|
||||
getLocation,
|
||||
getLength: () => entries.length,
|
||||
pushState: (path, state) => {
|
||||
index = index < entries.length - 1 ? index + 1 : entries.length;
|
||||
states[index] = state;
|
||||
entries[index] = path;
|
||||
if (index < entries.length - 1) {
|
||||
entries.length = index + 1;
|
||||
states.length = index + 1;
|
||||
}
|
||||
},
|
||||
replaceState: (path, state) => {
|
||||
states[index] = state;
|
||||
entries[index] = path;
|
||||
},
|
||||
back: () => {
|
||||
index = Math.max(index - 1, 0);
|
||||
},
|
||||
forward: () => {
|
||||
index = Math.min(index + 1, entries.length - 1);
|
||||
},
|
||||
go: (n) => {
|
||||
index = Math.min(Math.max(index + n, 0), entries.length - 1);
|
||||
},
|
||||
createHref: normalizeHref,
|
||||
getBlockers: _getBlockers,
|
||||
setBlockers: _setBlockers
|
||||
});
|
||||
}
|
||||
var noop = () => {};
|
||||
var ServerHistory = class {
|
||||
constructor(location) {
|
||||
this.location = location;
|
||||
}
|
||||
get length() {
|
||||
return 1;
|
||||
}
|
||||
get subscribers() {
|
||||
return this._subscribers ??= /* @__PURE__ */ new Set();
|
||||
}
|
||||
subscribe() {
|
||||
return noop;
|
||||
}
|
||||
push() {}
|
||||
replace() {}
|
||||
go() {}
|
||||
back() {}
|
||||
forward() {}
|
||||
canGoBack() {
|
||||
return false;
|
||||
}
|
||||
createHref(href) {
|
||||
return normalizeHref(href);
|
||||
}
|
||||
block() {
|
||||
return noop;
|
||||
}
|
||||
flush() {}
|
||||
destroy() {}
|
||||
notify() {}
|
||||
_getBlockers() {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
/** A fixed request location; server navigation is a no-op. */
|
||||
function createServerHistory(href) {
|
||||
return new ServerHistory(parseHref(href, void 0));
|
||||
}
|
||||
function parseHref(href, state) {
|
||||
const sanitizedHref = normalizeHref(href);
|
||||
const hashIndex = sanitizedHref.indexOf("#");
|
||||
const searchIndex = sanitizedHref.indexOf("?");
|
||||
if (!state) {
|
||||
const key = createRandomKey();
|
||||
state = {
|
||||
[stateIndexKey]: 0,
|
||||
key,
|
||||
__TSR_key: key
|
||||
};
|
||||
}
|
||||
return {
|
||||
href: sanitizedHref,
|
||||
pathname: sanitizedHref.substring(0, hashIndex > 0 ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > 0 ? searchIndex : sanitizedHref.length),
|
||||
hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : "",
|
||||
search: searchIndex > -1 ? sanitizedHref.slice(searchIndex, hashIndex === -1 ? void 0 : hashIndex) : "",
|
||||
state
|
||||
};
|
||||
}
|
||||
function createRandomKey() {
|
||||
return (Math.random() + 1).toString(36).substring(7);
|
||||
}
|
||||
//#endregion
|
||||
exports.createBrowserHistory = createBrowserHistory;
|
||||
exports.createHashHistory = createHashHistory;
|
||||
exports.createHistory = createHistory;
|
||||
exports.createMemoryHistory = createMemoryHistory;
|
||||
exports.createServerHistory = createServerHistory;
|
||||
exports.normalizeProtocolRelative = normalizeProtocolRelative;
|
||||
exports.parseHref = parseHref;
|
||||
|
||||
//# sourceMappingURL=index.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["// While the public API was clearly inspired by the \"history\" npm package,\n// This implementation attempts to be more lightweight by\n// making assumptions about the way TanStack Router works\n\nexport interface NavigateOptions {\n ignoreBlocker?: boolean\n}\n\ntype SubscriberHistoryAction =\n | {\n type: Exclude<HistoryAction, 'GO'>\n }\n | {\n type: 'GO'\n index: number\n }\n\ntype SubscriberArgs = {\n location: HistoryLocation\n action: SubscriberHistoryAction\n}\n\nexport interface RouterHistory {\n location: HistoryLocation\n length: number\n subscribers: Set<(opts: SubscriberArgs) => void>\n subscribe: (cb: (opts: SubscriberArgs) => void) => () => void\n push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void\n replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void\n go: (index: number, navigateOpts?: NavigateOptions) => void\n back: (navigateOpts?: NavigateOptions) => void\n forward: (navigateOpts?: NavigateOptions) => void\n canGoBack: () => boolean\n createHref: (href: string) => string\n block: (blocker: NavigationBlocker) => () => void\n flush: () => void\n destroy: () => void\n notify: (action: SubscriberHistoryAction) => void\n _getBlockers: () => Array<NavigationBlocker>\n _ignoreSubscribers?: boolean\n _ignoreNextBeforeUnload?: (href: string) => void\n}\n\nexport interface HistoryLocation extends ParsedPath {\n state: ParsedHistoryState\n}\n\nexport interface ParsedPath {\n href: string\n pathname: string\n search: string\n hash: string\n}\n\nexport interface HistoryState {}\n\nexport type ParsedHistoryState = HistoryState & {\n key?: string // TODO: Remove in v2 - use __TSR_key instead\n __TSR_key?: string\n __TSR_index: number\n}\n\ntype ShouldAllowNavigation = any\n\nexport type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO'\n\nexport type BlockerFnArgs = {\n currentLocation: HistoryLocation\n nextLocation: HistoryLocation\n action: HistoryAction\n}\n\nexport type BlockerFn = (\n args: BlockerFnArgs,\n) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation\n\nexport type NavigationBlocker = {\n blockerFn: BlockerFn\n enableBeforeUnload?: (() => boolean) | boolean\n}\n\ntype TryNavigateArgs = {\n task: () => void\n type: 'PUSH' | 'REPLACE' | 'BACK' | 'FORWARD' | 'GO'\n navigateOpts?: NavigateOptions\n} & (\n | {\n type: 'PUSH' | 'REPLACE'\n path: string\n state: any\n }\n | {\n type: 'BACK' | 'FORWARD' | 'GO'\n }\n)\n\nconst stateIndexKey = '__TSR_index'\nconst popStateEvent = 'popstate'\nconst beforeUnloadEvent = 'beforeunload'\n\n/**\n * Turn protocol-relative inputs such as \"//evil.example\" into paths\n * such as \"/evil.example\", keeping navigation on the current origin.\n *\n * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,\n * removes tabs/newlines, and treats backslashes as slashes, so inputs like\n * \"/\\evil.example\" also need normalization. This only allocates when those\n * rules would make the input protocol-relative.\n */\n// eslint-disable-next-line no-control-regex\nconst protocolRelativePrefix = /^[\\x00-\\x20]*(?:[\\\\/][\\t\\n\\r]*){2,}/\n\nexport function normalizeProtocolRelative(url: string): string {\n const match = protocolRelativePrefix.exec(url)\n return match ? '/' + url.slice(match[0].length) : url\n}\n\nfunction normalizeHref(href: string): string {\n // eslint-disable-next-line no-control-regex\n if (/[\\x00-\\x1f\\x7f]/.test(href)) {\n // eslint-disable-next-line no-control-regex\n href = href.replace(/[\\x00-\\x1f\\x7f]/g, (character) =>\n '\\t\\n\\r'.includes(character) ? '' : encodeURIComponent(character),\n )\n }\n return normalizeProtocolRelative(href)\n}\n\nexport function createHistory(opts: {\n getLocation: () => HistoryLocation\n getLength: () => number\n pushState: (path: string, state: any) => void\n replaceState: (path: string, state: any) => void\n go: (n: number, ignoreBlocker: boolean) => void\n back: (ignoreBlocker: boolean) => void\n forward: (ignoreBlocker: boolean) => void\n createHref: (path: string) => string\n flush?: () => void\n destroy?: () => void\n onBlocked?: () => void\n getBlockers?: () => Array<NavigationBlocker>\n setBlockers?: (blockers: Array<NavigationBlocker>) => void\n // Avoid notifying on forward/back/go, used for browser history as we already get notified by the popstate event\n notifyOnIndexChange?: boolean\n}): RouterHistory {\n let location = opts.getLocation()\n const subscribers = new Set<(opts: SubscriberArgs) => void>()\n\n const notify = (action: SubscriberHistoryAction) => {\n location = opts.getLocation()\n subscribers.forEach((subscriber) => subscriber({ location, action }))\n }\n\n const handleIndexChange = (action: SubscriberHistoryAction) => {\n if (opts.notifyOnIndexChange ?? true) notLine truncated
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
export interface NavigateOptions {
|
||||
ignoreBlocker?: boolean;
|
||||
}
|
||||
type SubscriberHistoryAction = {
|
||||
type: Exclude<HistoryAction, 'GO'>;
|
||||
} | {
|
||||
type: 'GO';
|
||||
index: number;
|
||||
};
|
||||
type SubscriberArgs = {
|
||||
location: HistoryLocation;
|
||||
action: SubscriberHistoryAction;
|
||||
};
|
||||
export interface RouterHistory {
|
||||
location: HistoryLocation;
|
||||
length: number;
|
||||
subscribers: Set<(opts: SubscriberArgs) => void>;
|
||||
subscribe: (cb: (opts: SubscriberArgs) => void) => () => void;
|
||||
push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void;
|
||||
replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void;
|
||||
go: (index: number, navigateOpts?: NavigateOptions) => void;
|
||||
back: (navigateOpts?: NavigateOptions) => void;
|
||||
forward: (navigateOpts?: NavigateOptions) => void;
|
||||
canGoBack: () => boolean;
|
||||
createHref: (href: string) => string;
|
||||
block: (blocker: NavigationBlocker) => () => void;
|
||||
flush: () => void;
|
||||
destroy: () => void;
|
||||
notify: (action: SubscriberHistoryAction) => void;
|
||||
_getBlockers: () => Array<NavigationBlocker>;
|
||||
_ignoreSubscribers?: boolean;
|
||||
_ignoreNextBeforeUnload?: (href: string) => void;
|
||||
}
|
||||
export interface HistoryLocation extends ParsedPath {
|
||||
state: ParsedHistoryState;
|
||||
}
|
||||
export interface ParsedPath {
|
||||
href: string;
|
||||
pathname: string;
|
||||
search: string;
|
||||
hash: string;
|
||||
}
|
||||
export interface HistoryState {
|
||||
}
|
||||
export type ParsedHistoryState = HistoryState & {
|
||||
key?: string;
|
||||
__TSR_key?: string;
|
||||
__TSR_index: number;
|
||||
};
|
||||
type ShouldAllowNavigation = any;
|
||||
export type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO';
|
||||
export type BlockerFnArgs = {
|
||||
currentLocation: HistoryLocation;
|
||||
nextLocation: HistoryLocation;
|
||||
action: HistoryAction;
|
||||
};
|
||||
export type BlockerFn = (args: BlockerFnArgs) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation;
|
||||
export type NavigationBlocker = {
|
||||
blockerFn: BlockerFn;
|
||||
enableBeforeUnload?: (() => boolean) | boolean;
|
||||
};
|
||||
export declare function normalizeProtocolRelative(url: string): string;
|
||||
export declare function createHistory(opts: {
|
||||
getLocation: () => HistoryLocation;
|
||||
getLength: () => number;
|
||||
pushState: (path: string, state: any) => void;
|
||||
replaceState: (path: string, state: any) => void;
|
||||
go: (n: number, ignoreBlocker: boolean) => void;
|
||||
back: (ignoreBlocker: boolean) => void;
|
||||
forward: (ignoreBlocker: boolean) => void;
|
||||
createHref: (path: string) => string;
|
||||
flush?: () => void;
|
||||
destroy?: () => void;
|
||||
onBlocked?: () => void;
|
||||
getBlockers?: () => Array<NavigationBlocker>;
|
||||
setBlockers?: (blockers: Array<NavigationBlocker>) => void;
|
||||
notifyOnIndexChange?: boolean;
|
||||
}): RouterHistory;
|
||||
/**
|
||||
* Creates a history object that can be used to interact with the browser's
|
||||
* navigation. This is a lightweight API wrapping the browser's native methods.
|
||||
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
|
||||
* IMPORTANT: This API implements history throttling via a microtask to prevent
|
||||
* excessive calls to the history API. In some browsers, calling history.pushState or
|
||||
* history.replaceState in quick succession can cause the browser to ignore subsequent
|
||||
* calls. This API smooths out those differences and ensures that your application
|
||||
* state will *eventually* match the browser state. In most cases, this is not a problem,
|
||||
* but if you need to ensure that the browser state is up to date, you can use the
|
||||
* `history.flush` method to immediately flush all pending state changes to the browser URL.
|
||||
* @param opts
|
||||
* @param opts.getHref A function that returns the current href (path + search + hash)
|
||||
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
|
||||
* @returns A history instance
|
||||
*/
|
||||
export declare function createBrowserHistory(opts?: {
|
||||
parseLocation?: () => HistoryLocation;
|
||||
createHref?: (path: string) => string;
|
||||
window?: any;
|
||||
}): RouterHistory;
|
||||
/**
|
||||
* Create a hash-based history implementation.
|
||||
* Useful for static hosts or environments without server URL rewriting.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
export declare function createHashHistory(opts?: {
|
||||
window?: any;
|
||||
}): RouterHistory;
|
||||
/**
|
||||
* Create an in-memory history implementation.
|
||||
* Ideal for server rendering, tests, and non-DOM environments.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
export declare function createMemoryHistory(opts?: {
|
||||
initialEntries: Array<string>;
|
||||
initialIndex?: number;
|
||||
}): RouterHistory;
|
||||
/** A fixed request location; server navigation is a no-op. */
|
||||
export declare function createServerHistory(href: string): RouterHistory;
|
||||
export declare function parseHref(href: string, state: ParsedHistoryState | undefined): HistoryLocation;
|
||||
export {};
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
export interface NavigateOptions {
|
||||
ignoreBlocker?: boolean;
|
||||
}
|
||||
type SubscriberHistoryAction = {
|
||||
type: Exclude<HistoryAction, 'GO'>;
|
||||
} | {
|
||||
type: 'GO';
|
||||
index: number;
|
||||
};
|
||||
type SubscriberArgs = {
|
||||
location: HistoryLocation;
|
||||
action: SubscriberHistoryAction;
|
||||
};
|
||||
export interface RouterHistory {
|
||||
location: HistoryLocation;
|
||||
length: number;
|
||||
subscribers: Set<(opts: SubscriberArgs) => void>;
|
||||
subscribe: (cb: (opts: SubscriberArgs) => void) => () => void;
|
||||
push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void;
|
||||
replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void;
|
||||
go: (index: number, navigateOpts?: NavigateOptions) => void;
|
||||
back: (navigateOpts?: NavigateOptions) => void;
|
||||
forward: (navigateOpts?: NavigateOptions) => void;
|
||||
canGoBack: () => boolean;
|
||||
createHref: (href: string) => string;
|
||||
block: (blocker: NavigationBlocker) => () => void;
|
||||
flush: () => void;
|
||||
destroy: () => void;
|
||||
notify: (action: SubscriberHistoryAction) => void;
|
||||
_getBlockers: () => Array<NavigationBlocker>;
|
||||
_ignoreSubscribers?: boolean;
|
||||
_ignoreNextBeforeUnload?: (href: string) => void;
|
||||
}
|
||||
export interface HistoryLocation extends ParsedPath {
|
||||
state: ParsedHistoryState;
|
||||
}
|
||||
export interface ParsedPath {
|
||||
href: string;
|
||||
pathname: string;
|
||||
search: string;
|
||||
hash: string;
|
||||
}
|
||||
export interface HistoryState {
|
||||
}
|
||||
export type ParsedHistoryState = HistoryState & {
|
||||
key?: string;
|
||||
__TSR_key?: string;
|
||||
__TSR_index: number;
|
||||
};
|
||||
type ShouldAllowNavigation = any;
|
||||
export type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO';
|
||||
export type BlockerFnArgs = {
|
||||
currentLocation: HistoryLocation;
|
||||
nextLocation: HistoryLocation;
|
||||
action: HistoryAction;
|
||||
};
|
||||
export type BlockerFn = (args: BlockerFnArgs) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation;
|
||||
export type NavigationBlocker = {
|
||||
blockerFn: BlockerFn;
|
||||
enableBeforeUnload?: (() => boolean) | boolean;
|
||||
};
|
||||
export declare function normalizeProtocolRelative(url: string): string;
|
||||
export declare function createHistory(opts: {
|
||||
getLocation: () => HistoryLocation;
|
||||
getLength: () => number;
|
||||
pushState: (path: string, state: any) => void;
|
||||
replaceState: (path: string, state: any) => void;
|
||||
go: (n: number, ignoreBlocker: boolean) => void;
|
||||
back: (ignoreBlocker: boolean) => void;
|
||||
forward: (ignoreBlocker: boolean) => void;
|
||||
createHref: (path: string) => string;
|
||||
flush?: () => void;
|
||||
destroy?: () => void;
|
||||
onBlocked?: () => void;
|
||||
getBlockers?: () => Array<NavigationBlocker>;
|
||||
setBlockers?: (blockers: Array<NavigationBlocker>) => void;
|
||||
notifyOnIndexChange?: boolean;
|
||||
}): RouterHistory;
|
||||
/**
|
||||
* Creates a history object that can be used to interact with the browser's
|
||||
* navigation. This is a lightweight API wrapping the browser's native methods.
|
||||
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
|
||||
* IMPORTANT: This API implements history throttling via a microtask to prevent
|
||||
* excessive calls to the history API. In some browsers, calling history.pushState or
|
||||
* history.replaceState in quick succession can cause the browser to ignore subsequent
|
||||
* calls. This API smooths out those differences and ensures that your application
|
||||
* state will *eventually* match the browser state. In most cases, this is not a problem,
|
||||
* but if you need to ensure that the browser state is up to date, you can use the
|
||||
* `history.flush` method to immediately flush all pending state changes to the browser URL.
|
||||
* @param opts
|
||||
* @param opts.getHref A function that returns the current href (path + search + hash)
|
||||
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
|
||||
* @returns A history instance
|
||||
*/
|
||||
export declare function createBrowserHistory(opts?: {
|
||||
parseLocation?: () => HistoryLocation;
|
||||
createHref?: (path: string) => string;
|
||||
window?: any;
|
||||
}): RouterHistory;
|
||||
/**
|
||||
* Create a hash-based history implementation.
|
||||
* Useful for static hosts or environments without server URL rewriting.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
export declare function createHashHistory(opts?: {
|
||||
window?: any;
|
||||
}): RouterHistory;
|
||||
/**
|
||||
* Create an in-memory history implementation.
|
||||
* Ideal for server rendering, tests, and non-DOM environments.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
export declare function createMemoryHistory(opts?: {
|
||||
initialEntries: Array<string>;
|
||||
initialIndex?: number;
|
||||
}): RouterHistory;
|
||||
/** A fixed request location; server navigation is a no-op. */
|
||||
export declare function createServerHistory(href: string): RouterHistory;
|
||||
export declare function parseHref(href: string, state: ParsedHistoryState | undefined): HistoryLocation;
|
||||
export {};
|
||||
+472
@@ -0,0 +1,472 @@
|
||||
//#region src/index.ts
|
||||
var stateIndexKey = "__TSR_index";
|
||||
var popStateEvent = "popstate";
|
||||
var beforeUnloadEvent = "beforeunload";
|
||||
/**
|
||||
* Turn protocol-relative inputs such as "//evil.example" into paths
|
||||
* such as "/evil.example", keeping navigation on the current origin.
|
||||
*
|
||||
* For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,
|
||||
* removes tabs/newlines, and treats backslashes as slashes, so inputs like
|
||||
* "/\evil.example" also need normalization. This only allocates when those
|
||||
* rules would make the input protocol-relative.
|
||||
*/
|
||||
var protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/;
|
||||
function normalizeProtocolRelative(url) {
|
||||
const match = protocolRelativePrefix.exec(url);
|
||||
return match ? "/" + url.slice(match[0].length) : url;
|
||||
}
|
||||
function normalizeHref(href) {
|
||||
if (/[\x00-\x1f\x7f]/.test(href)) href = href.replace(/[\x00-\x1f\x7f]/g, (character) => " \n\r".includes(character) ? "" : encodeURIComponent(character));
|
||||
return normalizeProtocolRelative(href);
|
||||
}
|
||||
function createHistory(opts) {
|
||||
let location = opts.getLocation();
|
||||
const subscribers = /* @__PURE__ */ new Set();
|
||||
const notify = (action) => {
|
||||
location = opts.getLocation();
|
||||
subscribers.forEach((subscriber) => subscriber({
|
||||
location,
|
||||
action
|
||||
}));
|
||||
};
|
||||
const handleIndexChange = (action) => {
|
||||
if (opts.notifyOnIndexChange ?? true) notify(action);
|
||||
else location = opts.getLocation();
|
||||
};
|
||||
const tryNavigation = async ({ task, navigateOpts, ...actionInfo }) => {
|
||||
if (navigateOpts?.ignoreBlocker ?? false) {
|
||||
task();
|
||||
return;
|
||||
}
|
||||
const blockers = opts.getBlockers?.() ?? [];
|
||||
const isPushOrReplace = actionInfo.type === "PUSH" || actionInfo.type === "REPLACE";
|
||||
if (typeof document !== "undefined" && blockers.length && isPushOrReplace) for (const blocker of blockers) {
|
||||
const nextLocation = parseHref(actionInfo.path, actionInfo.state);
|
||||
if (await blocker.blockerFn({
|
||||
currentLocation: location,
|
||||
nextLocation,
|
||||
action: actionInfo.type
|
||||
})) {
|
||||
opts.onBlocked?.();
|
||||
return;
|
||||
}
|
||||
}
|
||||
task();
|
||||
};
|
||||
return {
|
||||
get location() {
|
||||
return location;
|
||||
},
|
||||
get length() {
|
||||
return opts.getLength();
|
||||
},
|
||||
subscribers,
|
||||
subscribe: (cb) => {
|
||||
subscribers.add(cb);
|
||||
return () => {
|
||||
subscribers.delete(cb);
|
||||
};
|
||||
},
|
||||
push: (path, state, navigateOpts) => {
|
||||
const currentIndex = location.state[stateIndexKey];
|
||||
state = assignKeyAndIndex(currentIndex + 1, state);
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.pushState(path, state);
|
||||
notify({ type: "PUSH" });
|
||||
},
|
||||
navigateOpts,
|
||||
type: "PUSH",
|
||||
path,
|
||||
state
|
||||
});
|
||||
},
|
||||
replace: (path, state, navigateOpts) => {
|
||||
const currentIndex = location.state[stateIndexKey];
|
||||
state = assignKeyAndIndex(currentIndex, state);
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.replaceState(path, state);
|
||||
notify({ type: "REPLACE" });
|
||||
},
|
||||
navigateOpts,
|
||||
type: "REPLACE",
|
||||
path,
|
||||
state
|
||||
});
|
||||
},
|
||||
go: (index, navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.go(index, navigateOpts?.ignoreBlocker ?? false);
|
||||
handleIndexChange({
|
||||
type: "GO",
|
||||
index
|
||||
});
|
||||
},
|
||||
navigateOpts,
|
||||
type: "GO"
|
||||
});
|
||||
},
|
||||
back: (navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.back(navigateOpts?.ignoreBlocker ?? false);
|
||||
handleIndexChange({ type: "BACK" });
|
||||
},
|
||||
navigateOpts,
|
||||
type: "BACK"
|
||||
});
|
||||
},
|
||||
forward: (navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.forward(navigateOpts?.ignoreBlocker ?? false);
|
||||
handleIndexChange({ type: "FORWARD" });
|
||||
},
|
||||
navigateOpts,
|
||||
type: "FORWARD"
|
||||
});
|
||||
},
|
||||
canGoBack: () => location.state[stateIndexKey] !== 0,
|
||||
createHref: (str) => opts.createHref(str),
|
||||
block: (blocker) => {
|
||||
if (!opts.setBlockers) return () => {};
|
||||
const blockers = opts.getBlockers?.() ?? [];
|
||||
opts.setBlockers([...blockers, blocker]);
|
||||
return () => {
|
||||
const blockers = opts.getBlockers?.() ?? [];
|
||||
opts.setBlockers?.(blockers.filter((b) => b !== blocker));
|
||||
};
|
||||
},
|
||||
flush: () => opts.flush?.(),
|
||||
destroy: () => opts.destroy?.(),
|
||||
notify,
|
||||
_getBlockers: () => opts.getBlockers?.() ?? []
|
||||
};
|
||||
}
|
||||
function assignKeyAndIndex(index, state) {
|
||||
const key = createRandomKey();
|
||||
return {
|
||||
...state,
|
||||
key,
|
||||
__TSR_key: key,
|
||||
[stateIndexKey]: index
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Creates a history object that can be used to interact with the browser's
|
||||
* navigation. This is a lightweight API wrapping the browser's native methods.
|
||||
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
|
||||
* IMPORTANT: This API implements history throttling via a microtask to prevent
|
||||
* excessive calls to the history API. In some browsers, calling history.pushState or
|
||||
* history.replaceState in quick succession can cause the browser to ignore subsequent
|
||||
* calls. This API smooths out those differences and ensures that your application
|
||||
* state will *eventually* match the browser state. In most cases, this is not a problem,
|
||||
* but if you need to ensure that the browser state is up to date, you can use the
|
||||
* `history.flush` method to immediately flush all pending state changes to the browser URL.
|
||||
* @param opts
|
||||
* @param opts.getHref A function that returns the current href (path + search + hash)
|
||||
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
|
||||
* @returns A history instance
|
||||
*/
|
||||
function createBrowserHistory(opts) {
|
||||
const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
|
||||
const originalPushState = win.history.pushState;
|
||||
const originalReplaceState = win.history.replaceState;
|
||||
let blockers = [];
|
||||
const _getBlockers = () => blockers;
|
||||
const _setBlockers = (newBlockers) => blockers = newBlockers;
|
||||
const createHref = (path) => normalizeHref(opts?.createHref ? opts.createHref(path) : path);
|
||||
const parseLocation = opts?.parseLocation ?? (() => parseHref(`${win.location.pathname}${win.location.search}${win.location.hash}`, win.history.state));
|
||||
if (!win.history.state?.__TSR_key && !win.history.state?.key) {
|
||||
const addedKey = createRandomKey();
|
||||
win.history.replaceState({
|
||||
[stateIndexKey]: 0,
|
||||
key: addedKey,
|
||||
__TSR_key: addedKey
|
||||
}, "");
|
||||
}
|
||||
let currentLocation = parseLocation();
|
||||
let rollbackLocation;
|
||||
let nextPopIsGo = false;
|
||||
let ignoreNextPop = false;
|
||||
let skipBlockerNextPop = false;
|
||||
let ignoreNextBeforeUnload = false;
|
||||
const getLocation = () => currentLocation;
|
||||
let next;
|
||||
const flush = () => {
|
||||
if (!next) return;
|
||||
history._ignoreSubscribers = true;
|
||||
(next[2] ? win.history.pushState : win.history.replaceState)(next[1], "", next[0]);
|
||||
history._ignoreSubscribers = false;
|
||||
next = void 0;
|
||||
rollbackLocation = void 0;
|
||||
};
|
||||
const queueHistoryAction = (isPush, destHref, state) => {
|
||||
const href = opts?.createHref ? createHref(destHref) : void 0;
|
||||
const hasPendingAction = !!next;
|
||||
if (!hasPendingAction) rollbackLocation = currentLocation;
|
||||
currentLocation = parseHref(destHref, state);
|
||||
next = [
|
||||
href ?? currentLocation.href,
|
||||
state,
|
||||
next?.[2] || isPush
|
||||
];
|
||||
if (!hasPendingAction) queueMicrotask(() => flush());
|
||||
};
|
||||
const onPushPop = (type) => {
|
||||
currentLocation = parseLocation();
|
||||
history.notify({ type });
|
||||
};
|
||||
const onPushPopEvent = async () => {
|
||||
ignoreNextBeforeUnload = false;
|
||||
if (ignoreNextPop) {
|
||||
ignoreNextPop = false;
|
||||
return;
|
||||
}
|
||||
const nextLocation = parseLocation();
|
||||
const delta = nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey];
|
||||
const isForward = delta === 1;
|
||||
const isBack = delta === -1;
|
||||
const isGo = !isForward && !isBack || nextPopIsGo;
|
||||
nextPopIsGo = false;
|
||||
const action = isGo ? "GO" : isBack ? "BACK" : "FORWARD";
|
||||
const notify = isGo ? {
|
||||
type: "GO",
|
||||
index: delta
|
||||
} : { type: isBack ? "BACK" : "FORWARD" };
|
||||
if (skipBlockerNextPop) skipBlockerNextPop = false;
|
||||
else {
|
||||
const blockers = _getBlockers();
|
||||
if (typeof document !== "undefined" && blockers.length) {
|
||||
for (const blocker of blockers) if (await blocker.blockerFn({
|
||||
currentLocation,
|
||||
nextLocation,
|
||||
action
|
||||
})) {
|
||||
ignoreNextPop = true;
|
||||
win.history.go(-delta);
|
||||
history.notify(notify);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
currentLocation = parseLocation();
|
||||
history.notify(notify);
|
||||
};
|
||||
const onBeforeUnload = (e) => {
|
||||
if (ignoreNextBeforeUnload) {
|
||||
ignoreNextBeforeUnload = false;
|
||||
return;
|
||||
}
|
||||
let shouldBlock = false;
|
||||
const blockers = _getBlockers();
|
||||
if (typeof document !== "undefined" && blockers.length) for (const blocker of blockers) {
|
||||
const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true;
|
||||
if (shouldHaveBeforeUnload === true) {
|
||||
shouldBlock = true;
|
||||
break;
|
||||
}
|
||||
if (typeof shouldHaveBeforeUnload === "function" && shouldHaveBeforeUnload() === true) {
|
||||
shouldBlock = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (shouldBlock) {
|
||||
e.preventDefault();
|
||||
return e.returnValue = "";
|
||||
}
|
||||
};
|
||||
const history = createHistory({
|
||||
getLocation,
|
||||
getLength: () => win.history.length,
|
||||
pushState: (href, state) => queueHistoryAction(true, href, state),
|
||||
replaceState: (href, state) => queueHistoryAction(false, href, state),
|
||||
back: (ignoreBlocker) => {
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true;
|
||||
ignoreNextBeforeUnload = true;
|
||||
}
|
||||
return win.history.back();
|
||||
},
|
||||
forward: (ignoreBlocker) => {
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true;
|
||||
ignoreNextBeforeUnload = true;
|
||||
}
|
||||
win.history.forward();
|
||||
},
|
||||
go: (n, ignoreBlocker) => {
|
||||
nextPopIsGo = true;
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true;
|
||||
ignoreNextBeforeUnload = true;
|
||||
}
|
||||
win.history.go(n);
|
||||
},
|
||||
createHref: (href) => createHref(href),
|
||||
flush,
|
||||
destroy: () => {
|
||||
win.history.pushState = originalPushState;
|
||||
win.history.replaceState = originalReplaceState;
|
||||
win.removeEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
|
||||
win.removeEventListener(popStateEvent, onPushPopEvent);
|
||||
},
|
||||
onBlocked: () => {
|
||||
if (rollbackLocation && currentLocation !== rollbackLocation) currentLocation = rollbackLocation;
|
||||
},
|
||||
getBlockers: _getBlockers,
|
||||
setBlockers: _setBlockers,
|
||||
notifyOnIndexChange: false
|
||||
});
|
||||
history._ignoreNextBeforeUnload = (href) => {
|
||||
ignoreNextBeforeUnload = false;
|
||||
try {
|
||||
href = new URL(href, win.document.baseURI).href;
|
||||
ignoreNextBeforeUnload = /^https?:/.test(href) && (!href.includes("#") || href.split("#")[0] !== win.location.href.split("#")[0]);
|
||||
} catch {}
|
||||
};
|
||||
win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
|
||||
win.addEventListener(popStateEvent, onPushPopEvent);
|
||||
win.history.pushState = function(...args) {
|
||||
const res = originalPushState.apply(win.history, args);
|
||||
if (!history._ignoreSubscribers) onPushPop("PUSH");
|
||||
return res;
|
||||
};
|
||||
win.history.replaceState = function(...args) {
|
||||
const res = originalReplaceState.apply(win.history, args);
|
||||
if (!history._ignoreSubscribers) onPushPop("REPLACE");
|
||||
return res;
|
||||
};
|
||||
return history;
|
||||
}
|
||||
/**
|
||||
* Create a hash-based history implementation.
|
||||
* Useful for static hosts or environments without server URL rewriting.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
function createHashHistory(opts) {
|
||||
const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
|
||||
return createBrowserHistory({
|
||||
window: win,
|
||||
parseLocation: () => {
|
||||
const hashSplit = win.location.hash.split("#").slice(1);
|
||||
const pathPart = hashSplit[0] ?? "/";
|
||||
const searchPart = win.location.search;
|
||||
const hashEntries = hashSplit.slice(1);
|
||||
return parseHref(`${pathPart}${searchPart}${hashEntries.length === 0 ? "" : `#${hashEntries.join("#")}`}`, win.history.state);
|
||||
},
|
||||
createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Create an in-memory history implementation.
|
||||
* Ideal for server rendering, tests, and non-DOM environments.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
function createMemoryHistory(opts = { initialEntries: ["/"] }) {
|
||||
const entries = opts.initialEntries;
|
||||
let index = opts.initialIndex ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) : entries.length - 1;
|
||||
const states = entries.map((_entry, index) => assignKeyAndIndex(index, void 0));
|
||||
const getLocation = () => parseHref(entries[index], states[index]);
|
||||
let blockers = [];
|
||||
const _getBlockers = () => blockers;
|
||||
const _setBlockers = (newBlockers) => blockers = newBlockers;
|
||||
return createHistory({
|
||||
getLocation,
|
||||
getLength: () => entries.length,
|
||||
pushState: (path, state) => {
|
||||
index = index < entries.length - 1 ? index + 1 : entries.length;
|
||||
states[index] = state;
|
||||
entries[index] = path;
|
||||
if (index < entries.length - 1) {
|
||||
entries.length = index + 1;
|
||||
states.length = index + 1;
|
||||
}
|
||||
},
|
||||
replaceState: (path, state) => {
|
||||
states[index] = state;
|
||||
entries[index] = path;
|
||||
},
|
||||
back: () => {
|
||||
index = Math.max(index - 1, 0);
|
||||
},
|
||||
forward: () => {
|
||||
index = Math.min(index + 1, entries.length - 1);
|
||||
},
|
||||
go: (n) => {
|
||||
index = Math.min(Math.max(index + n, 0), entries.length - 1);
|
||||
},
|
||||
createHref: normalizeHref,
|
||||
getBlockers: _getBlockers,
|
||||
setBlockers: _setBlockers
|
||||
});
|
||||
}
|
||||
var noop = () => {};
|
||||
var ServerHistory = class {
|
||||
constructor(location) {
|
||||
this.location = location;
|
||||
}
|
||||
get length() {
|
||||
return 1;
|
||||
}
|
||||
get subscribers() {
|
||||
return this._subscribers ??= /* @__PURE__ */ new Set();
|
||||
}
|
||||
subscribe() {
|
||||
return noop;
|
||||
}
|
||||
push() {}
|
||||
replace() {}
|
||||
go() {}
|
||||
back() {}
|
||||
forward() {}
|
||||
canGoBack() {
|
||||
return false;
|
||||
}
|
||||
createHref(href) {
|
||||
return normalizeHref(href);
|
||||
}
|
||||
block() {
|
||||
return noop;
|
||||
}
|
||||
flush() {}
|
||||
destroy() {}
|
||||
notify() {}
|
||||
_getBlockers() {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
/** A fixed request location; server navigation is a no-op. */
|
||||
function createServerHistory(href) {
|
||||
return new ServerHistory(parseHref(href, void 0));
|
||||
}
|
||||
function parseHref(href, state) {
|
||||
const sanitizedHref = normalizeHref(href);
|
||||
const hashIndex = sanitizedHref.indexOf("#");
|
||||
const searchIndex = sanitizedHref.indexOf("?");
|
||||
if (!state) {
|
||||
const key = createRandomKey();
|
||||
state = {
|
||||
[stateIndexKey]: 0,
|
||||
key,
|
||||
__TSR_key: key
|
||||
};
|
||||
}
|
||||
return {
|
||||
href: sanitizedHref,
|
||||
pathname: sanitizedHref.substring(0, hashIndex > 0 ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > 0 ? searchIndex : sanitizedHref.length),
|
||||
hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : "",
|
||||
search: searchIndex > -1 ? sanitizedHref.slice(searchIndex, hashIndex === -1 ? void 0 : hashIndex) : "",
|
||||
state
|
||||
};
|
||||
}
|
||||
function createRandomKey() {
|
||||
return (Math.random() + 1).toString(36).substring(7);
|
||||
}
|
||||
//#endregion
|
||||
export { createBrowserHistory, createHashHistory, createHistory, createMemoryHistory, createServerHistory, normalizeProtocolRelative, parseHref };
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["// While the public API was clearly inspired by the \"history\" npm package,\n// This implementation attempts to be more lightweight by\n// making assumptions about the way TanStack Router works\n\nexport interface NavigateOptions {\n ignoreBlocker?: boolean\n}\n\ntype SubscriberHistoryAction =\n | {\n type: Exclude<HistoryAction, 'GO'>\n }\n | {\n type: 'GO'\n index: number\n }\n\ntype SubscriberArgs = {\n location: HistoryLocation\n action: SubscriberHistoryAction\n}\n\nexport interface RouterHistory {\n location: HistoryLocation\n length: number\n subscribers: Set<(opts: SubscriberArgs) => void>\n subscribe: (cb: (opts: SubscriberArgs) => void) => () => void\n push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void\n replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void\n go: (index: number, navigateOpts?: NavigateOptions) => void\n back: (navigateOpts?: NavigateOptions) => void\n forward: (navigateOpts?: NavigateOptions) => void\n canGoBack: () => boolean\n createHref: (href: string) => string\n block: (blocker: NavigationBlocker) => () => void\n flush: () => void\n destroy: () => void\n notify: (action: SubscriberHistoryAction) => void\n _getBlockers: () => Array<NavigationBlocker>\n _ignoreSubscribers?: boolean\n _ignoreNextBeforeUnload?: (href: string) => void\n}\n\nexport interface HistoryLocation extends ParsedPath {\n state: ParsedHistoryState\n}\n\nexport interface ParsedPath {\n href: string\n pathname: string\n search: string\n hash: string\n}\n\nexport interface HistoryState {}\n\nexport type ParsedHistoryState = HistoryState & {\n key?: string // TODO: Remove in v2 - use __TSR_key instead\n __TSR_key?: string\n __TSR_index: number\n}\n\ntype ShouldAllowNavigation = any\n\nexport type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO'\n\nexport type BlockerFnArgs = {\n currentLocation: HistoryLocation\n nextLocation: HistoryLocation\n action: HistoryAction\n}\n\nexport type BlockerFn = (\n args: BlockerFnArgs,\n) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation\n\nexport type NavigationBlocker = {\n blockerFn: BlockerFn\n enableBeforeUnload?: (() => boolean) | boolean\n}\n\ntype TryNavigateArgs = {\n task: () => void\n type: 'PUSH' | 'REPLACE' | 'BACK' | 'FORWARD' | 'GO'\n navigateOpts?: NavigateOptions\n} & (\n | {\n type: 'PUSH' | 'REPLACE'\n path: string\n state: any\n }\n | {\n type: 'BACK' | 'FORWARD' | 'GO'\n }\n)\n\nconst stateIndexKey = '__TSR_index'\nconst popStateEvent = 'popstate'\nconst beforeUnloadEvent = 'beforeunload'\n\n/**\n * Turn protocol-relative inputs such as \"//evil.example\" into paths\n * such as \"/evil.example\", keeping navigation on the current origin.\n *\n * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,\n * removes tabs/newlines, and treats backslashes as slashes, so inputs like\n * \"/\\evil.example\" also need normalization. This only allocates when those\n * rules would make the input protocol-relative.\n */\n// eslint-disable-next-line no-control-regex\nconst protocolRelativePrefix = /^[\\x00-\\x20]*(?:[\\\\/][\\t\\n\\r]*){2,}/\n\nexport function normalizeProtocolRelative(url: string): string {\n const match = protocolRelativePrefix.exec(url)\n return match ? '/' + url.slice(match[0].length) : url\n}\n\nfunction normalizeHref(href: string): string {\n // eslint-disable-next-line no-control-regex\n if (/[\\x00-\\x1f\\x7f]/.test(href)) {\n // eslint-disable-next-line no-control-regex\n href = href.replace(/[\\x00-\\x1f\\x7f]/g, (character) =>\n '\\t\\n\\r'.includes(character) ? '' : encodeURIComponent(character),\n )\n }\n return normalizeProtocolRelative(href)\n}\n\nexport function createHistory(opts: {\n getLocation: () => HistoryLocation\n getLength: () => number\n pushState: (path: string, state: any) => void\n replaceState: (path: string, state: any) => void\n go: (n: number, ignoreBlocker: boolean) => void\n back: (ignoreBlocker: boolean) => void\n forward: (ignoreBlocker: boolean) => void\n createHref: (path: string) => string\n flush?: () => void\n destroy?: () => void\n onBlocked?: () => void\n getBlockers?: () => Array<NavigationBlocker>\n setBlockers?: (blockers: Array<NavigationBlocker>) => void\n // Avoid notifying on forward/back/go, used for browser history as we already get notified by the popstate event\n notifyOnIndexChange?: boolean\n}): RouterHistory {\n let location = opts.getLocation()\n const subscribers = new Set<(opts: SubscriberArgs) => void>()\n\n const notify = (action: SubscriberHistoryAction) => {\n location = opts.getLocation()\n subscribers.forEach((subscriber) => subscriber({ location, action }))\n }\n\n const handleIndexChange = (action: SubscriberHistoryAction) => {\n if (opts.notifyOnIndexChange ?? true) notiLine truncated
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"name": "@tanstack/history",
|
||||
"version": "1.162.4",
|
||||
"description": "Modern and scalable routing for React applications",
|
||||
"author": "Tanner Linsley",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/TanStack/router.git",
|
||||
"directory": "packages/history"
|
||||
},
|
||||
"homepage": "https://tanstack.com/router",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
},
|
||||
"keywords": [
|
||||
"history",
|
||||
"typescript"
|
||||
],
|
||||
"type": "module",
|
||||
"types": "dist/esm/index.d.ts",
|
||||
"main": "dist/cjs/index.cjs",
|
||||
"module": "dist/esm/index.js",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/esm/index.d.ts",
|
||||
"default": "./dist/esm/index.js"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/cjs/index.d.cts",
|
||||
"default": "./dist/cjs/index.cjs"
|
||||
}
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"files": [
|
||||
"dist",
|
||||
"src"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "*",
|
||||
"@tanstack/vite-config": "0.5.2",
|
||||
"vitest": "^4.1.4",
|
||||
"jsdom": "^25.0.1",
|
||||
"@arethetypeswrong/cli": "^0.18.4",
|
||||
"publint": "^0.3.16",
|
||||
"rimraf": "^6.1.2"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf ./dist && rimraf ./coverage",
|
||||
"test:eslint": "eslint ./src",
|
||||
"test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"",
|
||||
"test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js",
|
||||
"test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js",
|
||||
"test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js",
|
||||
"test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js",
|
||||
"test:types:ts60": "tsc6",
|
||||
"test:types:ts70": "tsc",
|
||||
"test:build": "publint --strict && attw --ignore-rules no-resolution --pack .",
|
||||
"test:unit": "vitest",
|
||||
"test:unit:dev": "pnpm run test:unit --watch",
|
||||
"build": "vite build"
|
||||
}
|
||||
}
|
||||
+781
@@ -0,0 +1,781 @@
|
||||
// While the public API was clearly inspired by the "history" npm package,
|
||||
// This implementation attempts to be more lightweight by
|
||||
// making assumptions about the way TanStack Router works
|
||||
|
||||
export interface NavigateOptions {
|
||||
ignoreBlocker?: boolean
|
||||
}
|
||||
|
||||
type SubscriberHistoryAction =
|
||||
| {
|
||||
type: Exclude<HistoryAction, 'GO'>
|
||||
}
|
||||
| {
|
||||
type: 'GO'
|
||||
index: number
|
||||
}
|
||||
|
||||
type SubscriberArgs = {
|
||||
location: HistoryLocation
|
||||
action: SubscriberHistoryAction
|
||||
}
|
||||
|
||||
export interface RouterHistory {
|
||||
location: HistoryLocation
|
||||
length: number
|
||||
subscribers: Set<(opts: SubscriberArgs) => void>
|
||||
subscribe: (cb: (opts: SubscriberArgs) => void) => () => void
|
||||
push: (path: string, state?: any, navigateOpts?: NavigateOptions) => void
|
||||
replace: (path: string, state?: any, navigateOpts?: NavigateOptions) => void
|
||||
go: (index: number, navigateOpts?: NavigateOptions) => void
|
||||
back: (navigateOpts?: NavigateOptions) => void
|
||||
forward: (navigateOpts?: NavigateOptions) => void
|
||||
canGoBack: () => boolean
|
||||
createHref: (href: string) => string
|
||||
block: (blocker: NavigationBlocker) => () => void
|
||||
flush: () => void
|
||||
destroy: () => void
|
||||
notify: (action: SubscriberHistoryAction) => void
|
||||
_getBlockers: () => Array<NavigationBlocker>
|
||||
_ignoreSubscribers?: boolean
|
||||
_ignoreNextBeforeUnload?: (href: string) => void
|
||||
}
|
||||
|
||||
export interface HistoryLocation extends ParsedPath {
|
||||
state: ParsedHistoryState
|
||||
}
|
||||
|
||||
export interface ParsedPath {
|
||||
href: string
|
||||
pathname: string
|
||||
search: string
|
||||
hash: string
|
||||
}
|
||||
|
||||
export interface HistoryState {}
|
||||
|
||||
export type ParsedHistoryState = HistoryState & {
|
||||
key?: string // TODO: Remove in v2 - use __TSR_key instead
|
||||
__TSR_key?: string
|
||||
__TSR_index: number
|
||||
}
|
||||
|
||||
type ShouldAllowNavigation = any
|
||||
|
||||
export type HistoryAction = 'PUSH' | 'REPLACE' | 'FORWARD' | 'BACK' | 'GO'
|
||||
|
||||
export type BlockerFnArgs = {
|
||||
currentLocation: HistoryLocation
|
||||
nextLocation: HistoryLocation
|
||||
action: HistoryAction
|
||||
}
|
||||
|
||||
export type BlockerFn = (
|
||||
args: BlockerFnArgs,
|
||||
) => Promise<ShouldAllowNavigation> | ShouldAllowNavigation
|
||||
|
||||
export type NavigationBlocker = {
|
||||
blockerFn: BlockerFn
|
||||
enableBeforeUnload?: (() => boolean) | boolean
|
||||
}
|
||||
|
||||
type TryNavigateArgs = {
|
||||
task: () => void
|
||||
type: 'PUSH' | 'REPLACE' | 'BACK' | 'FORWARD' | 'GO'
|
||||
navigateOpts?: NavigateOptions
|
||||
} & (
|
||||
| {
|
||||
type: 'PUSH' | 'REPLACE'
|
||||
path: string
|
||||
state: any
|
||||
}
|
||||
| {
|
||||
type: 'BACK' | 'FORWARD' | 'GO'
|
||||
}
|
||||
)
|
||||
|
||||
const stateIndexKey = '__TSR_index'
|
||||
const popStateEvent = 'popstate'
|
||||
const beforeUnloadEvent = 'beforeunload'
|
||||
|
||||
/**
|
||||
* Turn protocol-relative inputs such as "//evil.example" into paths
|
||||
* such as "/evil.example", keeping navigation on the current origin.
|
||||
*
|
||||
* For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,
|
||||
* removes tabs/newlines, and treats backslashes as slashes, so inputs like
|
||||
* "/\evil.example" also need normalization. This only allocates when those
|
||||
* rules would make the input protocol-relative.
|
||||
*/
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/
|
||||
|
||||
export function normalizeProtocolRelative(url: string): string {
|
||||
const match = protocolRelativePrefix.exec(url)
|
||||
return match ? '/' + url.slice(match[0].length) : url
|
||||
}
|
||||
|
||||
function normalizeHref(href: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (/[\x00-\x1f\x7f]/.test(href)) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
href = href.replace(/[\x00-\x1f\x7f]/g, (character) =>
|
||||
'\t\n\r'.includes(character) ? '' : encodeURIComponent(character),
|
||||
)
|
||||
}
|
||||
return normalizeProtocolRelative(href)
|
||||
}
|
||||
|
||||
export function createHistory(opts: {
|
||||
getLocation: () => HistoryLocation
|
||||
getLength: () => number
|
||||
pushState: (path: string, state: any) => void
|
||||
replaceState: (path: string, state: any) => void
|
||||
go: (n: number, ignoreBlocker: boolean) => void
|
||||
back: (ignoreBlocker: boolean) => void
|
||||
forward: (ignoreBlocker: boolean) => void
|
||||
createHref: (path: string) => string
|
||||
flush?: () => void
|
||||
destroy?: () => void
|
||||
onBlocked?: () => void
|
||||
getBlockers?: () => Array<NavigationBlocker>
|
||||
setBlockers?: (blockers: Array<NavigationBlocker>) => void
|
||||
// Avoid notifying on forward/back/go, used for browser history as we already get notified by the popstate event
|
||||
notifyOnIndexChange?: boolean
|
||||
}): RouterHistory {
|
||||
let location = opts.getLocation()
|
||||
const subscribers = new Set<(opts: SubscriberArgs) => void>()
|
||||
|
||||
const notify = (action: SubscriberHistoryAction) => {
|
||||
location = opts.getLocation()
|
||||
subscribers.forEach((subscriber) => subscriber({ location, action }))
|
||||
}
|
||||
|
||||
const handleIndexChange = (action: SubscriberHistoryAction) => {
|
||||
if (opts.notifyOnIndexChange ?? true) notify(action)
|
||||
else location = opts.getLocation()
|
||||
}
|
||||
|
||||
const tryNavigation = async ({
|
||||
task,
|
||||
navigateOpts,
|
||||
...actionInfo
|
||||
}: TryNavigateArgs) => {
|
||||
const ignoreBlocker = navigateOpts?.ignoreBlocker ?? false
|
||||
if (ignoreBlocker) {
|
||||
task()
|
||||
return
|
||||
}
|
||||
|
||||
const blockers = opts.getBlockers?.() ?? []
|
||||
const isPushOrReplace =
|
||||
actionInfo.type === 'PUSH' || actionInfo.type === 'REPLACE'
|
||||
if (typeof document !== 'undefined' && blockers.length && isPushOrReplace) {
|
||||
for (const blocker of blockers) {
|
||||
const nextLocation = parseHref(actionInfo.path, actionInfo.state)
|
||||
const isBlocked = await blocker.blockerFn({
|
||||
currentLocation: location,
|
||||
nextLocation,
|
||||
action: actionInfo.type,
|
||||
})
|
||||
if (isBlocked) {
|
||||
opts.onBlocked?.()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task()
|
||||
}
|
||||
|
||||
return {
|
||||
get location() {
|
||||
return location
|
||||
},
|
||||
get length() {
|
||||
return opts.getLength()
|
||||
},
|
||||
subscribers,
|
||||
subscribe: (cb: (opts: SubscriberArgs) => void) => {
|
||||
subscribers.add(cb)
|
||||
|
||||
return () => {
|
||||
subscribers.delete(cb)
|
||||
}
|
||||
},
|
||||
push: (path, state, navigateOpts) => {
|
||||
const currentIndex = location.state[stateIndexKey]
|
||||
state = assignKeyAndIndex(currentIndex + 1, state)
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.pushState(path, state)
|
||||
notify({ type: 'PUSH' })
|
||||
},
|
||||
navigateOpts,
|
||||
type: 'PUSH',
|
||||
path,
|
||||
state,
|
||||
})
|
||||
},
|
||||
replace: (path, state, navigateOpts) => {
|
||||
const currentIndex = location.state[stateIndexKey]
|
||||
state = assignKeyAndIndex(currentIndex, state)
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.replaceState(path, state)
|
||||
notify({ type: 'REPLACE' })
|
||||
},
|
||||
navigateOpts,
|
||||
type: 'REPLACE',
|
||||
path,
|
||||
state,
|
||||
})
|
||||
},
|
||||
go: (index, navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.go(index, navigateOpts?.ignoreBlocker ?? false)
|
||||
handleIndexChange({ type: 'GO', index })
|
||||
},
|
||||
navigateOpts,
|
||||
type: 'GO',
|
||||
})
|
||||
},
|
||||
back: (navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.back(navigateOpts?.ignoreBlocker ?? false)
|
||||
handleIndexChange({ type: 'BACK' })
|
||||
},
|
||||
navigateOpts,
|
||||
type: 'BACK',
|
||||
})
|
||||
},
|
||||
forward: (navigateOpts) => {
|
||||
tryNavigation({
|
||||
task: () => {
|
||||
opts.forward(navigateOpts?.ignoreBlocker ?? false)
|
||||
handleIndexChange({ type: 'FORWARD' })
|
||||
},
|
||||
navigateOpts,
|
||||
type: 'FORWARD',
|
||||
})
|
||||
},
|
||||
canGoBack: () => location.state[stateIndexKey] !== 0,
|
||||
createHref: (str) => opts.createHref(str),
|
||||
block: (blocker) => {
|
||||
if (!opts.setBlockers) return () => {}
|
||||
const blockers = opts.getBlockers?.() ?? []
|
||||
opts.setBlockers([...blockers, blocker])
|
||||
|
||||
return () => {
|
||||
const blockers = opts.getBlockers?.() ?? []
|
||||
opts.setBlockers?.(blockers.filter((b) => b !== blocker))
|
||||
}
|
||||
},
|
||||
flush: () => opts.flush?.(),
|
||||
destroy: () => opts.destroy?.(),
|
||||
notify,
|
||||
_getBlockers: () => opts.getBlockers?.() ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
function assignKeyAndIndex(index: number, state: HistoryState | undefined) {
|
||||
const key = createRandomKey()
|
||||
return {
|
||||
...state,
|
||||
key, // TODO: Remove in v2 - use __TSR_key instead
|
||||
__TSR_key: key,
|
||||
[stateIndexKey]: index,
|
||||
} as ParsedHistoryState
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a history object that can be used to interact with the browser's
|
||||
* navigation. This is a lightweight API wrapping the browser's native methods.
|
||||
* It is designed to work with TanStack Router, but could be used as a standalone API as well.
|
||||
* IMPORTANT: This API implements history throttling via a microtask to prevent
|
||||
* excessive calls to the history API. In some browsers, calling history.pushState or
|
||||
* history.replaceState in quick succession can cause the browser to ignore subsequent
|
||||
* calls. This API smooths out those differences and ensures that your application
|
||||
* state will *eventually* match the browser state. In most cases, this is not a problem,
|
||||
* but if you need to ensure that the browser state is up to date, you can use the
|
||||
* `history.flush` method to immediately flush all pending state changes to the browser URL.
|
||||
* @param opts
|
||||
* @param opts.getHref A function that returns the current href (path + search + hash)
|
||||
* @param opts.createHref A function that takes a path and returns a href (path + search + hash)
|
||||
* @returns A history instance
|
||||
*/
|
||||
export function createBrowserHistory(opts?: {
|
||||
parseLocation?: () => HistoryLocation
|
||||
createHref?: (path: string) => string
|
||||
window?: any
|
||||
}): RouterHistory {
|
||||
const win =
|
||||
opts?.window ??
|
||||
(typeof document !== 'undefined' ? window : (undefined as any))
|
||||
|
||||
const originalPushState = win.history.pushState
|
||||
const originalReplaceState = win.history.replaceState
|
||||
|
||||
let blockers: Array<NavigationBlocker> = []
|
||||
const _getBlockers = () => blockers
|
||||
const _setBlockers = (newBlockers: Array<NavigationBlocker>) =>
|
||||
(blockers = newBlockers)
|
||||
|
||||
const createHref = (path: string) =>
|
||||
normalizeHref(opts?.createHref ? opts.createHref(path) : path)
|
||||
const parseLocation =
|
||||
opts?.parseLocation ??
|
||||
(() =>
|
||||
parseHref(
|
||||
`${win.location.pathname}${win.location.search}${win.location.hash}`,
|
||||
win.history.state,
|
||||
))
|
||||
|
||||
// Ensure there is always a key to start
|
||||
if (!win.history.state?.__TSR_key && !win.history.state?.key) {
|
||||
const addedKey = createRandomKey()
|
||||
win.history.replaceState(
|
||||
{
|
||||
[stateIndexKey]: 0,
|
||||
key: addedKey, // TODO: Remove in v2 - use __TSR_key instead
|
||||
__TSR_key: addedKey,
|
||||
},
|
||||
'',
|
||||
)
|
||||
}
|
||||
|
||||
let currentLocation = parseLocation()
|
||||
let rollbackLocation: HistoryLocation | undefined
|
||||
|
||||
let nextPopIsGo = false
|
||||
let ignoreNextPop = false
|
||||
// TODO: An ignored traversal past a history boundary emits neither popstate
|
||||
// nor beforeunload, leaving these bypasses active for a later navigation.
|
||||
// The History API provides no completion signal for such no-op traversals.
|
||||
let skipBlockerNextPop = false
|
||||
let ignoreNextBeforeUnload = false
|
||||
|
||||
const getLocation = () => currentLocation
|
||||
|
||||
let next:
|
||||
| undefined
|
||||
| [
|
||||
// The latest location that we were attempting to push/replace
|
||||
href: string,
|
||||
// The latest state that we were attempting to push/replace
|
||||
state: any,
|
||||
// Whether any queued update needs to push rather than replace
|
||||
isPush: boolean,
|
||||
]
|
||||
|
||||
// This function flushes the next update to the browser history
|
||||
const flush = () => {
|
||||
if (!next) {
|
||||
return
|
||||
}
|
||||
|
||||
// We need to ignore any updates to the subscribers while we update the browser history
|
||||
history._ignoreSubscribers = true
|
||||
|
||||
// Update the browser history
|
||||
;(next[2 /* is push */] ? win.history.pushState : win.history.replaceState)(
|
||||
next[1 /* state */],
|
||||
'',
|
||||
next[0 /* href */],
|
||||
)
|
||||
|
||||
// Stop ignoring subscriber updates
|
||||
history._ignoreSubscribers = false
|
||||
|
||||
// Clear the queued action after it reaches browser history.
|
||||
next = undefined
|
||||
rollbackLocation = undefined
|
||||
}
|
||||
|
||||
// This function queues up a call to update the browser history
|
||||
const queueHistoryAction = (
|
||||
isPush: boolean,
|
||||
destHref: string,
|
||||
state: any,
|
||||
) => {
|
||||
// A formatter changes the URL space and must receive the original input.
|
||||
// Otherwise parseHref below already produces the browser destination.
|
||||
const href = opts?.createHref ? createHref(destHref) : undefined
|
||||
const hasPendingAction = !!next
|
||||
|
||||
if (!hasPendingAction) {
|
||||
rollbackLocation = currentLocation
|
||||
}
|
||||
|
||||
// Keep the optimistic location in the router's logical URL space.
|
||||
currentLocation = parseHref(destHref, state)
|
||||
|
||||
// Keep track of the next location we need to flush to the URL
|
||||
next = [
|
||||
href ?? currentLocation.href,
|
||||
state,
|
||||
next?.[2 /* is push */] || isPush,
|
||||
]
|
||||
|
||||
if (!hasPendingAction) {
|
||||
// Schedule an update to the browser history
|
||||
queueMicrotask(() => flush())
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: this function can probably be removed
|
||||
const onPushPop = (type: 'PUSH' | 'REPLACE') => {
|
||||
currentLocation = parseLocation()
|
||||
history.notify({ type })
|
||||
}
|
||||
|
||||
const onPushPopEvent = async () => {
|
||||
// Same-document traversals do not fire beforeunload, so consume their
|
||||
// exemption here instead of carrying it into a later document navigation.
|
||||
ignoreNextBeforeUnload = false
|
||||
|
||||
if (ignoreNextPop) {
|
||||
ignoreNextPop = false
|
||||
return
|
||||
}
|
||||
|
||||
const nextLocation = parseLocation()
|
||||
const delta =
|
||||
nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey]
|
||||
const isForward = delta === 1
|
||||
const isBack = delta === -1
|
||||
const isGo = (!isForward && !isBack) || nextPopIsGo
|
||||
nextPopIsGo = false
|
||||
|
||||
const action = isGo ? 'GO' : isBack ? 'BACK' : 'FORWARD'
|
||||
const notify: SubscriberHistoryAction = isGo
|
||||
? {
|
||||
type: 'GO',
|
||||
index: delta,
|
||||
}
|
||||
: {
|
||||
type: isBack ? 'BACK' : 'FORWARD',
|
||||
}
|
||||
|
||||
if (skipBlockerNextPop) {
|
||||
skipBlockerNextPop = false
|
||||
} else {
|
||||
const blockers = _getBlockers()
|
||||
if (typeof document !== 'undefined' && blockers.length) {
|
||||
for (const blocker of blockers) {
|
||||
const isBlocked = await blocker.blockerFn({
|
||||
currentLocation,
|
||||
nextLocation,
|
||||
action,
|
||||
})
|
||||
if (isBlocked) {
|
||||
ignoreNextPop = true
|
||||
win.history.go(-delta)
|
||||
history.notify(notify)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
currentLocation = parseLocation()
|
||||
history.notify(notify)
|
||||
}
|
||||
|
||||
const onBeforeUnload = (e: BeforeUnloadEvent) => {
|
||||
if (ignoreNextBeforeUnload) {
|
||||
ignoreNextBeforeUnload = false
|
||||
return
|
||||
}
|
||||
|
||||
let shouldBlock = false
|
||||
|
||||
// If one blocker has a non-disabled beforeUnload, we should block
|
||||
const blockers = _getBlockers()
|
||||
if (typeof document !== 'undefined' && blockers.length) {
|
||||
for (const blocker of blockers) {
|
||||
const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true
|
||||
if (shouldHaveBeforeUnload === true) {
|
||||
shouldBlock = true
|
||||
break
|
||||
}
|
||||
|
||||
if (
|
||||
typeof shouldHaveBeforeUnload === 'function' &&
|
||||
shouldHaveBeforeUnload() === true
|
||||
) {
|
||||
shouldBlock = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldBlock) {
|
||||
e.preventDefault()
|
||||
return (e.returnValue = '')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const history = createHistory({
|
||||
getLocation,
|
||||
getLength: () => win.history.length,
|
||||
pushState: (href, state) => queueHistoryAction(true, href, state),
|
||||
replaceState: (href, state) => queueHistoryAction(false, href, state),
|
||||
back: (ignoreBlocker) => {
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true
|
||||
ignoreNextBeforeUnload = true
|
||||
}
|
||||
return win.history.back()
|
||||
},
|
||||
forward: (ignoreBlocker) => {
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true
|
||||
ignoreNextBeforeUnload = true
|
||||
}
|
||||
win.history.forward()
|
||||
},
|
||||
go: (n, ignoreBlocker) => {
|
||||
nextPopIsGo = true
|
||||
if (ignoreBlocker) {
|
||||
skipBlockerNextPop = true
|
||||
ignoreNextBeforeUnload = true
|
||||
}
|
||||
win.history.go(n)
|
||||
},
|
||||
createHref: (href) => createHref(href),
|
||||
flush,
|
||||
destroy: () => {
|
||||
win.history.pushState = originalPushState
|
||||
win.history.replaceState = originalReplaceState
|
||||
win.removeEventListener(beforeUnloadEvent, onBeforeUnload, {
|
||||
capture: true,
|
||||
})
|
||||
win.removeEventListener(popStateEvent, onPushPopEvent)
|
||||
},
|
||||
onBlocked: () => {
|
||||
// If a navigation is blocked, we need to rollback the location
|
||||
// that we optimistically updated in memory.
|
||||
if (rollbackLocation && currentLocation !== rollbackLocation) {
|
||||
currentLocation = rollbackLocation
|
||||
}
|
||||
},
|
||||
getBlockers: _getBlockers,
|
||||
setBlockers: _setBlockers,
|
||||
notifyOnIndexChange: false,
|
||||
})
|
||||
|
||||
history._ignoreNextBeforeUnload = (href) => {
|
||||
ignoreNextBeforeUnload = false
|
||||
try {
|
||||
href = new URL(href, win.document.baseURI).href
|
||||
// External handlers and same-document fragments may emit neither
|
||||
// beforeunload nor popstate, leaving an exemption for a later departure.
|
||||
ignoreNextBeforeUnload =
|
||||
/^https?:/.test(href) &&
|
||||
(!href.includes('#') ||
|
||||
href.split('#')[0] !== win.location.href.split('#')[0])
|
||||
} catch {
|
||||
// Invalid URLs cannot unload the document.
|
||||
}
|
||||
}
|
||||
|
||||
win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true })
|
||||
win.addEventListener(popStateEvent, onPushPopEvent)
|
||||
|
||||
win.history.pushState = function (...args: Array<any>) {
|
||||
const res = originalPushState.apply(win.history, args as any)
|
||||
if (!history._ignoreSubscribers) onPushPop('PUSH')
|
||||
return res
|
||||
}
|
||||
|
||||
win.history.replaceState = function (...args: Array<any>) {
|
||||
const res = originalReplaceState.apply(win.history, args as any)
|
||||
if (!history._ignoreSubscribers) onPushPop('REPLACE')
|
||||
return res
|
||||
}
|
||||
|
||||
return history
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a hash-based history implementation.
|
||||
* Useful for static hosts or environments without server URL rewriting.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
export function createHashHistory(opts?: { window?: any }): RouterHistory {
|
||||
const win =
|
||||
opts?.window ??
|
||||
(typeof document !== 'undefined' ? window : (undefined as any))
|
||||
return createBrowserHistory({
|
||||
window: win,
|
||||
parseLocation: () => {
|
||||
const hashSplit = win.location.hash.split('#').slice(1)
|
||||
const pathPart = hashSplit[0] ?? '/'
|
||||
const searchPart = win.location.search
|
||||
const hashEntries = hashSplit.slice(1)
|
||||
const hashPart =
|
||||
hashEntries.length === 0 ? '' : `#${hashEntries.join('#')}`
|
||||
const hashHref = `${pathPart}${searchPart}${hashPart}`
|
||||
return parseHref(hashHref, win.history.state)
|
||||
},
|
||||
createHref: (href) =>
|
||||
`${win.location.pathname}${win.location.search}#${href}`,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an in-memory history implementation.
|
||||
* Ideal for server rendering, tests, and non-DOM environments.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
|
||||
*/
|
||||
export function createMemoryHistory(
|
||||
opts: {
|
||||
initialEntries: Array<string>
|
||||
initialIndex?: number
|
||||
} = {
|
||||
initialEntries: ['/'],
|
||||
},
|
||||
): RouterHistory {
|
||||
const entries = opts.initialEntries
|
||||
let index = opts.initialIndex
|
||||
? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1)
|
||||
: entries.length - 1
|
||||
const states = entries.map((_entry, index) =>
|
||||
assignKeyAndIndex(index, undefined),
|
||||
)
|
||||
|
||||
const getLocation = () => parseHref(entries[index]!, states[index])
|
||||
|
||||
let blockers: Array<NavigationBlocker> = []
|
||||
const _getBlockers = () => blockers
|
||||
const _setBlockers = (newBlockers: Array<NavigationBlocker>) =>
|
||||
(blockers = newBlockers)
|
||||
|
||||
return createHistory({
|
||||
getLocation,
|
||||
getLength: () => entries.length,
|
||||
pushState: (path, state) => {
|
||||
// Removes all subsequent entries after the current index to start a new branch
|
||||
index = index < entries.length - 1 ? index + 1 : entries.length
|
||||
states[index] = state
|
||||
entries[index] = path
|
||||
if (index < entries.length - 1) {
|
||||
entries.length = index + 1
|
||||
states.length = index + 1
|
||||
}
|
||||
},
|
||||
replaceState: (path, state) => {
|
||||
states[index] = state
|
||||
entries[index] = path
|
||||
},
|
||||
back: () => {
|
||||
index = Math.max(index - 1, 0)
|
||||
},
|
||||
forward: () => {
|
||||
index = Math.min(index + 1, entries.length - 1)
|
||||
},
|
||||
go: (n) => {
|
||||
index = Math.min(Math.max(index + n, 0), entries.length - 1)
|
||||
},
|
||||
createHref: normalizeHref,
|
||||
getBlockers: _getBlockers,
|
||||
setBlockers: _setBlockers,
|
||||
})
|
||||
}
|
||||
|
||||
const noop = () => {}
|
||||
|
||||
class ServerHistory implements RouterHistory {
|
||||
declare private _subscribers?: RouterHistory['subscribers']
|
||||
|
||||
constructor(public location: HistoryLocation) {}
|
||||
|
||||
get length() {
|
||||
return 1
|
||||
}
|
||||
|
||||
// Preserve the history interface without allocating a Set for each request.
|
||||
get subscribers() {
|
||||
return (this._subscribers ??= new Set())
|
||||
}
|
||||
|
||||
subscribe() {
|
||||
return noop
|
||||
}
|
||||
|
||||
push() {}
|
||||
replace() {}
|
||||
go() {}
|
||||
back() {}
|
||||
forward() {}
|
||||
|
||||
canGoBack() {
|
||||
return false
|
||||
}
|
||||
|
||||
createHref(href: string) {
|
||||
return normalizeHref(href)
|
||||
}
|
||||
|
||||
block() {
|
||||
return noop
|
||||
}
|
||||
|
||||
flush() {}
|
||||
destroy() {}
|
||||
notify() {}
|
||||
|
||||
_getBlockers(): Array<NavigationBlocker> {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** A fixed request location; server navigation is a no-op. */
|
||||
export function createServerHistory(href: string): RouterHistory {
|
||||
return new ServerHistory(parseHref(href, undefined))
|
||||
}
|
||||
|
||||
export function parseHref(
|
||||
href: string,
|
||||
state: ParsedHistoryState | undefined,
|
||||
): HistoryLocation {
|
||||
const sanitizedHref = normalizeHref(href)
|
||||
const hashIndex = sanitizedHref.indexOf('#')
|
||||
const searchIndex = sanitizedHref.indexOf('?')
|
||||
if (!state) {
|
||||
const key = createRandomKey()
|
||||
state = { [stateIndexKey]: 0, key, __TSR_key: key }
|
||||
}
|
||||
|
||||
return {
|
||||
href: sanitizedHref,
|
||||
pathname: sanitizedHref.substring(
|
||||
0,
|
||||
hashIndex > 0
|
||||
? searchIndex > 0
|
||||
? Math.min(hashIndex, searchIndex)
|
||||
: hashIndex
|
||||
: searchIndex > 0
|
||||
? searchIndex
|
||||
: sanitizedHref.length,
|
||||
),
|
||||
hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : '',
|
||||
search:
|
||||
searchIndex > -1
|
||||
? sanitizedHref.slice(
|
||||
searchIndex,
|
||||
hashIndex === -1 ? undefined : hashIndex,
|
||||
)
|
||||
: '',
|
||||
state,
|
||||
}
|
||||
}
|
||||
|
||||
// Thanks co-pilot!
|
||||
function createRandomKey() {
|
||||
return (Math.random() + 1).toString(36).substring(7)
|
||||
}
|
||||
Reference in new issue
Block a user