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
This commit is contained in:
Tom Moor authored and GitHub committed 2026-09-18 18:28:26 -04:00
1 parent ed7a1e9ffc
commit b57d02c4fc
3 files changed
+121 -4

No files matched your search

+72 -4
View File
@@ -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<React.HTMLAttributes<HTMLSpanElement>, "ref" | "onChange"> & {
@@ -13,6 +14,7 @@ type Props = Omit<React.HTMLAttributes<HTMLSpanElement>, "ref" | "onChange"> & {
onBlur?: React.FocusEventHandler<HTMLSpanElement> | undefined;
onInput?: React.FormEventHandler<HTMLSpanElement> | undefined;
onKeyDown?: React.KeyboardEventHandler<HTMLSpanElement> | undefined;
onCompositionEnd?: React.CompositionEventHandler<HTMLSpanElement> | 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<HTMLSpanElement>) => {
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<HTMLSpanElement>) {
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" &&
+26
View File
@@ -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("");
});
});
});
+23
View File
@@ -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("");
}
}