From b57d02c4fc34bc94740a6397115e40bdba0f2f74 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 18:28:26 -0400 Subject: [PATCH] fix: Enforce maxLength for all input paths in `ContentEditable` (#13793) * fix: Enforce maxLength on paste, drop and IME input in ContentEditable * fix: Count code points and hold over-limit change during IME composition --- app/components/ContentEditable.tsx | 76 ++++++++++++++++++++++++++++-- shared/utils/TextHelper.test.ts | 26 ++++++++++ shared/utils/TextHelper.ts | 23 +++++++++ 3 files changed, 121 insertions(+), 4 deletions(-) diff --git a/app/components/ContentEditable.tsx b/app/components/ContentEditable.tsx index 20b3948e81..14cd0ddf97 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -2,6 +2,7 @@ import isPrintableKeyEvent from "is-printable-key-event"; import * as React from "react"; import styled from "styled-components"; import { s } from "@shared/styles"; +import { TextHelper } from "@shared/utils/TextHelper"; import useOnScreen from "~/hooks/useOnScreen"; type Props = Omit, "ref" | "onChange"> & { @@ -13,6 +14,7 @@ type Props = Omit, "ref" | "onChange"> & { onBlur?: React.FocusEventHandler | undefined; onInput?: React.FormEventHandler | undefined; onKeyDown?: React.KeyboardEventHandler | undefined; + onCompositionEnd?: React.CompositionEventHandler | undefined; placeholder?: string; maxLength?: number; autoFocus?: boolean; @@ -39,6 +41,7 @@ const ContentEditable = React.forwardRef(function ContentEditable_( onFocus, onBlur, onKeyDown, + onCompositionEnd, value, children, className, @@ -95,18 +98,32 @@ const ContentEditable = React.forwardRef(function ContentEditable_( return; } - const text = event.currentTarget.textContent || ""; + let text = event.currentTarget.textContent || ""; + const overLimit = + !!maxLength && TextHelper.codePointLength(text) > maxLength; if ( maxLength && event.nativeEvent instanceof KeyboardEvent && isPrintableKeyEvent(event.nativeEvent) && - text.length >= maxLength + TextHelper.codePointLength(text) >= maxLength ) { event.preventDefault(); return; } + // Paste, drop, IME and other non-keyboard input paths bypass the check + // above, so clamp whatever landed in the DOM. Editing the DOM would + // break an active IME session, so wait for composition end and do not + // publish the over-limit buffer in the meantime. + if (overLimit && maxLength) { + if (isComposing(event)) { + callback?.(event); + return; + } + text = truncateContent(event.currentTarget, maxLength); + } + if (text !== lastValue.current) { lastValue.current = text; onChange?.(text); @@ -146,10 +163,21 @@ const ContentEditable = React.forwardRef(function ContentEditable_( const handlePaste = React.useCallback( (event: React.ClipboardEvent) => { event.preventDefault(); - const text = event.clipboardData.getData("text/plain"); + let text = event.clipboardData.getData("text/plain"); + + if (maxLength) { + const current = event.currentTarget.textContent || ""; + const selected = window.getSelection()?.toString() || ""; + const remaining = + maxLength - + (TextHelper.codePointLength(current) - + TextHelper.codePointLength(selected)); + text = TextHelper.truncate(text, remaining); + } + window.document.execCommand("insertText", false, text); }, - [] + [maxLength] ); const contentEditable = !disabled && !readOnly; @@ -163,6 +191,7 @@ const ContentEditable = React.forwardRef(function ContentEditable_( onFocus={wrappedEvent(onFocus)} onBlur={wrappedEvent(onBlur)} onKeyDown={wrappedEvent(onKeyDown)} + onCompositionEnd={wrappedEvent(onCompositionEnd)} onPaste={handlePaste} data-placeholder={placeholder} suppressContentEditableWarning @@ -175,6 +204,45 @@ const ContentEditable = React.forwardRef(function ContentEditable_( ); }); +function isComposing(event: React.SyntheticEvent) { + const native = event.nativeEvent; + return ( + (native instanceof InputEvent || native instanceof KeyboardEvent) && + native.isComposing + ); +} + +/** + * Truncates the text content of an element to the given number of code points + * while keeping the caret at its current position where possible. + */ +function truncateContent(element: HTMLElement, maxLength: number): string { + const selection = window.getSelection(); + const range = selection?.rangeCount ? selection.getRangeAt(0) : undefined; + let offset = Number.MAX_SAFE_INTEGER; + + if (range && element.contains(range.startContainer)) { + const before = range.cloneRange(); + before.selectNodeContents(element); + before.setEnd(range.startContainer, range.startOffset); + offset = before.toString().length; + } + + const text = TextHelper.truncate(element.textContent || "", maxLength); + element.textContent = text; + + const textNode = element.firstChild; + if (textNode && selection) { + const caret = document.createRange(); + caret.setStart(textNode, Math.min(offset, text.length)); + caret.collapse(true); + selection.removeAllRanges(); + selection.addRange(caret); + } + + return text; +} + function placeCaret(element: HTMLElement, atStart: boolean) { if ( typeof window.getSelection !== "undefined" && diff --git a/shared/utils/TextHelper.test.ts b/shared/utils/TextHelper.test.ts index bdbbab52ed..745f21b0e8 100644 --- a/shared/utils/TextHelper.test.ts +++ b/shared/utils/TextHelper.test.ts @@ -28,4 +28,30 @@ describe("TextHelper", () => { expect(result).toBe("Hello January 1, 2021"); }); }); + + describe("codePointLength", () => { + it("should count code points rather than UTF-16 units", () => { + expect(TextHelper.codePointLength("abc")).toBe(3); + expect(TextHelper.codePointLength("😀")).toBe(1); + expect(TextHelper.codePointLength("a😀b")).toBe(3); + expect(TextHelper.codePointLength("")).toBe(0); + }); + }); + + describe("truncate", () => { + it("should not split surrogate pairs", () => { + expect(TextHelper.truncate("😀", 1)).toBe("😀"); + expect(TextHelper.truncate("a😀b", 2)).toBe("a😀"); + expect(TextHelper.truncate("abc", 2)).toBe("ab"); + }); + + it("should return the text unchanged when within the limit", () => { + expect(TextHelper.truncate("abc", 5)).toBe("abc"); + }); + + it("should return an empty string for a non-positive limit", () => { + expect(TextHelper.truncate("abc", 0)).toBe(""); + expect(TextHelper.truncate("abc", -1)).toBe(""); + }); + }); }); diff --git a/shared/utils/TextHelper.ts b/shared/utils/TextHelper.ts index 39987f7c16..6b14aeb7c4 100644 --- a/shared/utils/TextHelper.ts +++ b/shared/utils/TextHelper.ts @@ -29,4 +29,27 @@ export class TextHelper { .replace(/{datetime}/g, getCurrentDateTimeAsString(locales)) .replace(/{author}/g, user.name); } + + /** + * Returns the length of the text in Unicode code points rather than UTF-16 + * code units, matching the server-side length validation. + * + * @param text The text to measure + * @returns The number of code points in the text + */ + static codePointLength(text: string): number { + return Array.from(text).length; + } + + /** + * Truncates the text to a maximum number of Unicode code points without + * splitting surrogate pairs. + * + * @param text The text to truncate + * @param maxLength The maximum number of code points to keep + * @returns The truncated text + */ + static truncate(text: string, maxLength: number): string { + return Array.from(text).slice(0, Math.max(0, maxLength)).join(""); + } }