fix: Open internal sidebar links at the canonical location

This commit is contained in:
Tom Moor committed 2026-11-11 08:15:09 -05:00
1 parent e1a1d753a2
commit ca43faa76f
5 files changed
+216 -59

No files matched your search

@@ -1,17 +1,15 @@
import type { Location } from "history";
import { parsePath } from "history";
import { observer } from "mobx-react";
import { EditIcon, LinkIcon, TrashIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import type { match } from "react-router";
import styled from "styled-components";
import { toast } from "sonner";
import useShare from "@shared/hooks/useShare";
import type { NavigationNode } from "@shared/types";
import { errToString } from "@shared/utils/error";
import type { FlattenedTreeNode } from "@shared/utils/tree";
import { isInternalUrl, sanitizeUrl } from "@shared/utils/urls";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
import { isDocumentUrl, sanitizeUrl } from "@shared/utils/urls";
import type Collection from "~/models/Collection";
import { DropdownMenu } from "~/components/Menu/DropdownMenu";
import { OverflowMenuButton } from "~/components/Menu/OverflowMenuButton";
@@ -19,14 +17,17 @@ import { createAction } from "~/actions";
import { DocumentSection } from "~/actions/sections";
import useBoolean from "~/hooks/useBoolean";
import { useMenuAction } from "~/hooks/useMenuAction";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import { toRelative } from "~/utils/urls";
import useStores from "~/hooks/useStores";
import history from "~/utils/history";
import { isModKey } from "@shared/utils/keyboard";
import { useDragLink } from "../hooks/useDragAndDrop";
import { useLinkDialog } from "../hooks/useLinkDialog";
import { resolveInternalLink, toInternalPath } from "./internalLinks";
import Relative from "./Relative";
import { useReorderDropCursors } from "./ReorderDropCursors";
import type { SidebarContextType } from "./SidebarContext";
import { useSidebarContext } from "./SidebarContext";
import { determineSidebarContext } from "./SidebarContext";
import SidebarLink from "./SidebarLink";
interface Props {
@@ -47,8 +48,8 @@ interface Props {
const noAncestors: FlattenedTreeNode[] = [];
/**
* A sidebar row for a link. A link to a page in this app opens through the
* router, any other link opens in a new tab.
* A sidebar row for a link. A link to a page in this app opens the canonical
* location of that page through the router, any other link opens in a new tab.
*/
export const ExternalLink = observer(function ExternalLink({
node,
@@ -60,7 +61,8 @@ export const ExternalLink = observer(function ExternalLink({
}: Props) {
const { t } = useTranslation();
const { shareId } = useShare();
const sidebarContext = useSidebarContext();
const stores = useStores();
const user = useCurrentUser({ rejectOnEmpty: false });
const linkDialog = useLinkDialog();
const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean();
const canCollection = usePolicy(collection);
@@ -90,21 +92,55 @@ export const ExternalLink = observer(function ExternalLink({
});
// In a public share, app pages other than the share are not available.
const to = React.useMemo(() => {
const path = shareId ? undefined : toInternalPath(node.url);
return path
? { ...parsePath(path), state: { title: node.title, sidebarContext } }
: undefined;
}, [shareId, node.url, node.title, sidebarContext]);
const isActive = React.useCallback(
(
routeMatch: match | null,
location: Location<{ sidebarContext?: SidebarContextType }>
) => !!routeMatch && location.state?.sidebarContext === sidebarContext,
[sidebarContext]
const internalPath = React.useMemo(
() => (shareId ? undefined : toInternalPath(node.url)),
[shareId, node.url]
);
const handleClick = React.useCallback(
async (ev: React.MouseEvent<HTMLAnchorElement>) => {
// Let the browser open a new tab or window for modified clicks.
if (
!internalPath ||
isModKey(ev.nativeEvent) ||
ev.shiftKey ||
ev.button !== 0
) {
return;
}
ev.preventDefault();
const { path, document, collection } = await resolveInternalLink(
internalPath,
stores
);
// Open the page at its own place in the sidebar, not at this link.
const sidebarContext =
document && user
? determineSidebarContext({
document,
user,
currentContext: "collections",
})
: collection?.isPersonal
? "personal"
: "collections";
history.push(path, { sidebarContext });
},
[internalPath, stores, user]
);
const handlePrefetch = React.useCallback(() => {
const slug =
internalPath && isDocumentUrl(internalPath)
? parseDocumentSlug(internalPath)
: undefined;
if (slug) {
void stores.documents.prefetchDocument(slug).catch(() => undefined);
}
}, [internalPath, stores]);
const handleEdit = React.useCallback(() => {
if (collection) {
linkDialog.openEdit(collection, node);
@@ -158,10 +194,12 @@ export const ExternalLink = observer(function ExternalLink({
{cursorBefore}
<Draggable ref={dragRef} $isDragging={isDragging}>
<SidebarLink
to={to}
href={to ? undefined : sanitizeUrl(node.url)}
external={!to}
isActive={to ? isActive : undefined}
href={internalPath ?? sanitizeUrl(node.url)}
target={internalPath ? undefined : "_blank"}
rel={internalPath ? undefined : "noopener noreferrer"}
onClick={internalPath ? handleClick : undefined}
onClickIntent={internalPath ? handlePrefetch : undefined}
external
depth={depth}
icon={depth === 0 ? <LinkIcon /> : undefined}
label={node.title}
@@ -175,30 +213,6 @@ export const ExternalLink = observer(function ExternalLink({
);
});
/**
* Returns the router path for a url that points to a page in this app.
*
* @param url The url of the link.
* @returns the path, or undefined if the url must open as a normal link.
*/
function toInternalPath(url: string): string | undefined {
if (!isInternalUrl(url)) {
return undefined;
}
try {
const path = toRelative(url);
// The API is not part of the app, and the router cannot decode a
// malformed percent-encoding. The result is used so that the minifier
// keeps the call.
const decoded = decodeURI(path);
return decoded && !path.startsWith("/api/") ? path : undefined;
} catch (_err) {
return undefined;
}
}
const Draggable = styled.div<{ $isDragging: boolean }>`
transition: opacity 250ms ease;
opacity: ${(props) => (props.$isDragging ? 0.1 : 1)};
@@ -87,7 +87,7 @@ type Props = Omit<NavLinkProps, "to"> & {
scrollIntoViewIfNeeded?: boolean;
/** Optional context menu action to display */
contextAction?: ActionWithChildren | ActionFactory;
/** Whether the link points to an external location, opened in a new tab */
/** Whether to show an arrow that marks the row as a link */
external?: boolean;
};
@@ -231,8 +231,6 @@ function SidebarLink({
onMouseLeave={handleMouseLeave}
onDragEnter={handleMouseEnter}
href={href}
target={external ? "_blank" : undefined}
rel={external ? "noopener noreferrer" : undefined}
className={className}
ref={ref}
{...rest}
@@ -0,0 +1,30 @@
import env from "@shared/env";
import { toInternalPath } from "./internalLinks";
describe("toInternalPath", () => {
const origin = window.location.origin;
beforeEach(() => {
env.URL = origin;
});
it("should return the path, search and hash of an internal url", () => {
expect(toInternalPath(`${origin}/doc/title-abc123defg?x=1#heading`)).toBe(
"/doc/title-abc123defg?x=1#heading"
);
});
it("should not route external urls", () => {
expect(toInternalPath("https://example.com/doc/title-abc123defg")).toBe(
undefined
);
});
it("should not route api urls", () => {
expect(toInternalPath(`${origin}/api/documents.info`)).toBe(undefined);
});
it("should not route a malformed percent-encoding", () => {
expect(toInternalPath(`${origin}/doc/50%off`)).toBe(undefined);
});
});
@@ -0,0 +1,107 @@
import { parsePath } from "history";
import parseCollectionSlug from "@shared/utils/parseCollectionSlug";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
import {
isCollectionUrl,
isDocumentUrl,
isInternalUrl,
} from "@shared/utils/urls";
import type Collection from "~/models/Collection";
import type Document from "~/models/Document";
import type RootStore from "~/stores/RootStore";
import { toRelative } from "~/utils/urls";
/** The canonical location of an internal link, and the model it points to. */
export interface ResolvedInternalLink {
/** The canonical path, with the search and hash of the link. */
path: string;
/** The document that the link points to, if any. */
document?: Document;
/** The collection that the link points to, if any. */
collection?: Collection;
}
/**
* Returns the router path for a url that points to a page in this app.
*
* @param url The url of the link.
* @returns the path, or undefined if the url must open as a normal link.
*/
export function toInternalPath(url: string): string | undefined {
if (!isInternalUrl(url)) {
return undefined;
}
try {
const path = toRelative(url);
// The API is not part of the app, and the router cannot decode a
// malformed percent-encoding. The result is used so that the minifier
// keeps the call.
const decoded = decodeURI(path);
return decoded && !path.startsWith("/api/") ? path : undefined;
} catch (_err) {
return undefined;
}
}
/**
* Resolves an internal path to the canonical path of the document or
* collection that it points to. A model that is not loaded is fetched, and
* the path is returned as given if that fails.
*
* @param path The internal path of the link.
* @param stores The root store.
* @returns the canonical path and the model that it points to.
*/
export async function resolveInternalLink(
path: string,
{ documents, collections }: Pick<RootStore, "documents" | "collections">
): Promise<ResolvedInternalLink> {
const { search, hash } = parsePath(path);
if (isDocumentUrl(path)) {
const slug = parseDocumentSlug(path);
const document = slug
? (documents.get(slug) ??
(await documents.fetch(slug).catch(() => undefined)))
: undefined;
if (document) {
return { path: `${document.path}${search}${hash}`, document };
}
}
if (isCollectionUrl(path)) {
const slug = parseCollectionSlug(path);
const collection = slug
? (collections.get(slug) ??
(await collections.fetch(slug).catch(() => undefined)))
: undefined;
if (collection) {
return { path: `${collection.path}${search}${hash}`, collection };
}
}
return { path };
}
/**
* Returns the canonical url for a link, so that it opens directly when it is
* not handled by the router, such as in a new tab. Other urls are unchanged.
*
* @param url The url of the link.
* @param stores The root store.
* @returns the canonical url.
*/
export async function toCanonicalUrl(
url: string,
stores: Pick<RootStore, "documents" | "collections">
): Promise<string> {
const path = toInternalPath(url);
if (!path) {
return url;
}
const resolved = await resolveInternalLink(path, stores);
return `${new URL(url).origin}${resolved.path}`;
}
+13 -5
View File
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import type { NavigationNode } from "@shared/types";
import type Collection from "~/models/Collection";
import useStores from "~/hooks/useStores";
import { toCanonicalUrl } from "../components/internalLinks";
import { LinkDialog, type LinkDialogValues } from "../components/LinkDialog";
/**
@@ -11,7 +12,8 @@ import { LinkDialog, type LinkDialogValues } from "../components/LinkDialog";
* @returns functions to open the create and edit dialogs.
*/
export function useLinkDialog() {
const { dialogs } = useStores();
const stores = useStores();
const { dialogs } = stores;
const { t } = useTranslation();
const openCreate = React.useCallback(
@@ -21,7 +23,10 @@ export function useLinkDialog() {
onCreated?: () => void
) => {
const handleSubmit = async (values: LinkDialogValues) => {
await collection.addLink(values, parentDocumentId);
await collection.addLink(
{ ...values, url: await toCanonicalUrl(values.url, stores) },
parentDocumentId
);
onCreated?.();
dialogs.closeAllModals();
};
@@ -31,13 +36,16 @@ export function useLinkDialog() {
content: <LinkDialog onSubmit={handleSubmit} />,
});
},
[dialogs, t]
[stores, dialogs, t]
);
const openEdit = React.useCallback(
(collection: Collection, node: NavigationNode) => {
const handleSubmit = async (values: LinkDialogValues) => {
await collection.updateLink(node.id, values);
await collection.updateLink(node.id, {
...values,
url: await toCanonicalUrl(values.url, stores),
});
dialogs.closeAllModals();
};
@@ -51,7 +59,7 @@ export function useLinkDialog() {
),
});
},
[dialogs, t]
[stores, dialogs, t]
);
return { openCreate, openEdit };