fix: Uncaught URI malformed error

This commit is contained in:
Tom Moor
2024-09-02 21:42:27 -04:00
parent 2afec241a0
commit 63e667d6d3
3 changed files with 17 additions and 5 deletions

View File

@@ -6,6 +6,7 @@ import breakpoint from "styled-components-breakpoint";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import { depths, s } from "@shared/styles";
import useWindowScrollPosition from "~/hooks/useWindowScrollPosition";
import { decodeURIComponentSafe } from "~/utils/urls";
const HEADING_OFFSET = 20;
@@ -30,7 +31,7 @@ export default function Contents({ headings }: Props) {
for (let key = 0; key < headings.length; key++) {
const heading = headings[key];
const element = window.document.getElementById(
decodeURIComponent(heading.id)
decodeURIComponentSafe(heading.id)
);
if (element) {

View File

@@ -33,6 +33,7 @@ import {
documentPath,
matchDocumentHistory,
} from "~/utils/routeHelpers";
import { decodeURIComponentSafe } from "~/utils/urls";
import MultiplayerEditor from "./AsyncMultiplayerEditor";
import DocumentMeta from "./DocumentMeta";
import DocumentTitle from "./DocumentTitle";
@@ -224,7 +225,7 @@ function DocumentEditor(props: Props, ref: React.RefObject<any>) {
ref={mergeRefs([ref, handleRefChanged])}
autoFocus={!!document.title && !props.defaultValue}
placeholder={t("Type '/' to insert, or start writing…")}
scrollTo={decodeURIComponent(window.location.hash)}
scrollTo={decodeURIComponentSafe(window.location.hash)}
readOnly={readOnly}
shareId={shareId}
userId={user?.id}

View File

@@ -21,10 +21,20 @@ export function isHash(href: string) {
return false;
}
/**
* Decodes a URI component without throwing an error in case of invalid encoding.
*
* @param text The text to decode.
* @returns The decoded text.
*/
export function decodeURIComponentSafe(text: string) {
return text
? decodeURIComponent(text.replace(/%(?![0-9][0-9a-fA-F]+)/g, "%25"))
: text;
try {
return text
? decodeURIComponent(text.replace(/%(?![0-9][0-9a-fA-F]+)/g, "%25"))
: text;
} catch (_) {
return text;
}
}
/**