diff --git a/app/components/Sidebar/components/SharedWithMe.tsx b/app/components/Sidebar/components/SharedWithMe.tsx index a803e2dc4b..ef600a2841 100644 --- a/app/components/Sidebar/components/SharedWithMe.tsx +++ b/app/components/Sidebar/components/SharedWithMe.tsx @@ -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), - sidebarContext: "shared", - }, - }); + history.push( + patchLocation(history.location, { + state: { + ...(history.location.state as Record), + sidebarContext: "shared", + }, + }) + ); return; } @@ -81,13 +83,14 @@ function SharedWithMe() { ); if (groupWithActiveDocument) { - history.push({ - ...history.location, - state: { - ...(history.location.state as Record), - sidebarContext: groupSidebarContext(groupWithActiveDocument.id), - }, - }); + history.push( + patchLocation(history.location, { + state: { + ...(history.location.state as Record), + sidebarContext: groupSidebarContext(groupWithActiveDocument.id), + }, + }) + ); } }, [ ui.activeDocumentId, diff --git a/app/hooks/useEditorClickHandlers.ts b/app/hooks/useEditorClickHandlers.ts index 7e791536d2..6704cea576 100644 --- a/app/hooks/useEditorClickHandlers.ts +++ b/app/hooks/useEditorClickHandlers.ts @@ -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; } diff --git a/app/menus/TableOfContentsMenu.tsx b/app/menus/TableOfContentsMenu.tsx index 07a3b89721..aee6364250 100644 --- a/app/menus/TableOfContentsMenu.tsx +++ b/app/menus/TableOfContentsMenu.tsx @@ -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}` }) + ) ) ), }) diff --git a/app/scenes/Document/components/Contents.tsx b/app/scenes/Document/components/Contents.tsx index 7a19e7c5ba..eeb9fb9b36 100644 --- a/app/scenes/Document/components/Contents.tsx +++ b/app/scenes/Document/components/Contents.tsx @@ -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(); const scrollPosition = useWindowScrollPosition({ throttle: 100, @@ -21,6 +24,27 @@ function Contents() { const { headings } = useDocumentContext(); const itemRefs = useRef>({}); + const handleClick = useCallback( + (event: React.MouseEvent, 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} > - + handleClick(event, heading.id)} + > {heading.title} diff --git a/app/scenes/Document/components/SearchHighlightChip.tsx b/app/scenes/Document/components/SearchHighlightChip.tsx index 552286622f..cff11abbe6 100644 --- a/app/scenes/Document/components/SearchHighlightChip.tsx +++ b/app/scenes/Document/components/SearchHighlightChip.tsx @@ -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) { diff --git a/app/scenes/Document/index.tsx b/app/scenes/Document/index.tsx index a51aa59a78..03cf6859ea 100644 --- a/app/scenes/Document/index.tsx +++ b/app/scenes/Document/index.tsx @@ -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]); diff --git a/app/utils/history.test.ts b/app/utils/history.test.ts new file mode 100644 index 0000000000..0b2b92201c --- /dev/null +++ b/app/utils/history.test.ts @@ -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" }); + }); +}); diff --git a/app/utils/history.ts b/app/utils/history.ts index 75a8d9c938..ccc35917a9 100644 --- a/app/utils/history.ts +++ b/app/utils/history.ts @@ -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;