fix: Retain location state when clicking on hash links in doc and TOC (#12805)

* fix: Retain location state when clicking on hash links in doc and TOC

* fix: Pass explicit location fields when navigating to hash links

Avoid spreading history.location (which carries internal fields like key)
and preserve the href's query string for absolute same-path links.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Refactor to patchLocation helper

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Tom MoorandClaude Opus 4.8 authored and GitHub committed 2026-06-23 21:00:41 -04:00
1 parent 0daea28ab9
commit e7613baccf
8 files changed
+127 -29

No files matched your search

@@ -22,6 +22,7 @@ import SidebarContext, { groupSidebarContext } from "./SidebarContext";
import SidebarLink from "./SidebarLink";
import { useHistory } from "react-router-dom";
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
import { patchLocation } from "~/utils/history";
function SharedWithMe() {
const { ui, userMemberships, groupMemberships } = useStores();
@@ -62,13 +63,14 @@ function SharedWithMe() {
);
if (isActiveDocSharedDirectly) {
history.push({
...history.location,
state: {
...(history.location.state as Record<string, unknown>),
sidebarContext: "shared",
},
});
history.push(
patchLocation(history.location, {
state: {
...(history.location.state as Record<string, unknown>),
sidebarContext: "shared",
},
})
);
return;
}
@@ -81,13 +83,14 @@ function SharedWithMe() {
);
if (groupWithActiveDocument) {
history.push({
...history.location,
state: {
...(history.location.state as Record<string, unknown>),
sidebarContext: groupSidebarContext(groupWithActiveDocument.id),
},
});
history.push(
patchLocation(history.location, {
state: {
...(history.location.state as Record<string, unknown>),
sidebarContext: groupSidebarContext(groupWithActiveDocument.id),
},
})
);
}
}, [
ui.activeDocumentId,
+15 -1
View File
@@ -2,6 +2,7 @@ import { useCallback } from "react";
import { useHistory } from "react-router-dom";
import { isModKey } from "@shared/utils/keyboard";
import { isDocumentUrl, isInternalUrl } from "@shared/utils/urls";
import { patchLocation } from "~/utils/history";
import { sharedModelPath } from "~/utils/routeHelpers";
import { isHash } from "~/utils/urls";
import useStores from "./useStores";
@@ -19,7 +20,20 @@ export default function useEditorClickHandlers({ shareId }: Params) {
(href: string, event?: MouseEvent) => {
// on page hash
if (isHash(href)) {
window.location.href = href;
// Navigate via history rather than assigning window.location so the
// current location state (e.g. the active sidebar context) is retained
// when scrolling to an anchor within the same document. The hash (and
// search, for an absolute link) come from the href; everything else
// stays as the current location.
const target = href.startsWith("#")
? { hash: href, search: history.location.search }
: new URL(href);
history.push(
patchLocation(history.location, {
search: target.search,
hash: target.hash,
})
);
return;
}
+7 -2
View File
@@ -10,6 +10,7 @@ import Button from "~/components/Button";
import { useDocumentContext } from "~/components/DocumentContext";
import { DropdownMenu } from "~/components/Menu/DropdownMenu";
import { useMenuAction } from "~/hooks/useMenuAction";
import history, { patchLocation } from "~/utils/history";
function TableOfContentsMenu() {
const { headings } = useDocumentContext();
@@ -33,8 +34,12 @@ function TableOfContentsMenu() {
section: ActiveDocumentSection,
perform: () =>
requestAnimationFrame(() =>
requestAnimationFrame(
() => (window.location.hash = `#${heading.id}`)
requestAnimationFrame(() =>
// Navigate via history so the location state (active sidebar
// context) is retained when scrolling to the heading.
history.push(
patchLocation(history.location, { hash: `#${heading.id}` })
)
)
),
})
+29 -2
View File
@@ -1,7 +1,8 @@
import { observer } from "mobx-react";
import { transparentize } from "polished";
import { useState, useEffect, useRef } from "react";
import { useState, useEffect, useRef, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { EmojiText } from "@shared/components/EmojiText";
@@ -9,11 +10,13 @@ import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import { depths, hideScrollbars, s } from "@shared/styles";
import { useDocumentContext } from "~/components/DocumentContext";
import useWindowScrollPosition from "~/hooks/useWindowScrollPosition";
import { patchLocation } from "~/utils/history";
import { decodeURIComponentSafe } from "~/utils/urls";
const HEADING_OFFSET = 20;
function Contents() {
const history = useHistory();
const [activeSlug, setActiveSlug] = useState<string>();
const scrollPosition = useWindowScrollPosition({
throttle: 100,
@@ -21,6 +24,27 @@ function Contents() {
const { headings } = useDocumentContext();
const itemRefs = useRef<Record<string, HTMLLIElement | null>>({});
const handleClick = useCallback(
(event: React.MouseEvent<HTMLAnchorElement>, id: string) => {
// Let modified clicks (open in new tab, copy link, etc.) fall through to
// the native anchor behavior.
if (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
// Navigate via history so the location state (active sidebar context) is
// retained rather than dropped by a native hash navigation.
event.preventDefault();
history.push(patchLocation(history.location, { hash: `#${id}` }));
},
[history]
);
useEffect(() => {
let activeId = headings.length > 0 ? headings[0].id : undefined;
@@ -81,7 +105,10 @@ function Contents() {
level={heading.level - headingAdjustment}
active={activeSlug === heading.id}
>
<Link href={`#${heading.id}`}>
<Link
href={`#${heading.id}`}
onClick={(event) => handleClick(event, heading.id)}
>
<EmojiText>{heading.title}</EmojiText>
</Link>
</ListItem>
@@ -6,6 +6,7 @@ import styled from "styled-components";
import { ellipsis } from "@shared/styles";
import { useDocumentContext } from "~/components/DocumentContext";
import Tooltip from "~/components/Tooltip";
import { patchLocation } from "~/utils/history";
import { undraggableOnDesktop } from "~/styles";
export function SearchHighlightChip() {
@@ -20,12 +21,9 @@ export function SearchHighlightChip() {
const params = new URLSearchParams(location.search);
params.delete("q");
const search = params.toString();
history.replace({
pathname: location.pathname,
search: search ? `?${search}` : "",
hash: location.hash,
state: location.state,
});
history.replace(
patchLocation(location, { search: search ? `?${search}` : "" })
);
}, [editor, history, location]);
if (!searchHighlight) {
+6 -4
View File
@@ -5,6 +5,7 @@ import type { RouteComponentProps } from "react-router-dom";
import type { SidebarContextType } from "~/components/Sidebar/components/SidebarContext";
import { useTrackLastVisitedPath } from "~/hooks/useLastVisitedPath";
import useStores from "~/hooks/useStores";
import { patchLocation } from "~/utils/history";
import DataLoader from "./components/DataLoader";
import Document from "./components/Document";
import { Footer } from "./components/Footer";
@@ -35,10 +36,11 @@ export default function DocumentScene(props: Props) {
useEffect(() => {
// When opening a document directly on app load, sidebarContext will not be set.
if (!props.location.state?.sidebarContext) {
history.replace({
...props.location,
state: { ...props.location.state, sidebarContext: "collections" }, // optimistic preference of "collections"
});
history.replace(
patchLocation(props.location, {
state: { ...props.location.state, sidebarContext: "collections" }, // optimistic preference of "collections"
})
);
}
}, [props.location, history]);
+31
View File
@@ -0,0 +1,31 @@
import type { Location } from "history";
import { patchLocation } from "./history";
describe("patchLocation", () => {
const location: Location = {
pathname: "/doc/my-doc",
search: "?foo=bar",
hash: "#one",
state: { sidebarContext: "starred-123" },
key: "abc123",
};
it("carries over the safe fields and applies the patch", () => {
expect(patchLocation(location, { hash: "#two" })).toEqual({
pathname: "/doc/my-doc",
search: "?foo=bar",
hash: "#two",
state: { sidebarContext: "starred-123" },
});
});
it("does not carry over internal fields such as key", () => {
expect(patchLocation(location, {})).not.toHaveProperty("key");
});
it("can override multiple fields at once", () => {
expect(
patchLocation(location, { search: "?q=1", hash: "#three" })
).toMatchObject({ search: "?q=1", hash: "#three" });
});
});
+18
View File
@@ -1,5 +1,23 @@
import type { Location, LocationDescriptorObject } from "history";
import { createBrowserHistory } from "history";
/**
* Creates a location descriptor from an existing location with the given fields
* overridden. Only the pathname, search, hash, and state are carried over so
* that internal fields (such as key) are not duplicated into the new entry.
*
* @param location The location to patch, typically history.location.
* @param patch The location fields to override.
* @returns A location descriptor suitable for history.push or history.replace.
*/
export function patchLocation(
location: Location,
patch: LocationDescriptorObject
): LocationDescriptorObject {
const { pathname, search, hash, state } = location;
return { pathname, search, hash, state, ...patch };
}
const history = createBrowserHistory();
export default history;