Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions src/components/MentionTextarea.dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,114 @@ it("shows text another program writes through the field's value setter, and hand
expect(mirror()).toBe("hi from dictation\n");
act(() => root.unmount());
});

function stubZoomedComputedStyle(metrics: { zoom: number; fontSize: string; lineHeight: string }) {
const realGetComputedStyle = globalThis.getComputedStyle;
const stub = vi.fn((element: Element, pseudoElt?: string | null) => {
const computed = realGetComputedStyle(element, pseudoElt);
const read = (property: string): string | null => {
if (element.tagName === "TEXTAREA") {
if (property === "font-size") return metrics.fontSize;
if (property === "line-height") return metrics.lineHeight;
return null;
}
if (element instanceof HTMLElement && element.classList.contains("mention-editor-mirror")) {
if (property !== "font-size" && property !== "line-height") return null;
const inline = element.style.getPropertyValue(property);
const px = Number.parseFloat(inline);
if (!Number.isFinite(px)) return inline || null;
return `${Math.round(px * metrics.zoom * 1000) / 1000}px`;
}
return null;
};
return new Proxy(computed, {
get(target, prop) {
if (prop === "getPropertyValue") return (name: string) => read(name) ?? target.getPropertyValue(name);
if (prop === "fontSize") return read("font-size") ?? target.fontSize;
if (prop === "lineHeight") return read("line-height") ?? target.lineHeight;
const value = Reflect.get(target, prop, target);
return typeof value === "function" ? value.bind(target) : value;
},
});
});
vi.stubGlobal("getComputedStyle", stub);
return stub;
}

it("undoes WebView text zoom on the mirror so it matches the field without rewriting it on scroll", async () => {
vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });
// Android WebView's setTextZoom scales inline font-size and line-height even under text-size-adjust: none.
stubZoomedComputedStyle({ zoom: 1.3, fontSize: "20.8px", lineHeight: "31.2px" });
const root = createRoot(document.body.appendChild(document.createElement("div")));
const inputRef = createRef<HTMLTextAreaElement>();
await act(async () => {
root.render(createElement(MentionTextarea, { inputRef, peers: [], value: "hello", onChange: () => {} }));
});
const input = inputRef.current!;
const mirror = document.querySelector<HTMLElement>(".mention-editor-mirror")!;
expect([mirror.style.fontSize, mirror.style.lineHeight]).toEqual(["16px", "24px"]);
const mirrorStyle = getComputedStyle(mirror);
expect([mirrorStyle.getPropertyValue("font-size"), mirrorStyle.getPropertyValue("line-height")]).toEqual(["20.8px", "31.2px"]);

const setProperty = vi.spyOn(mirror.style, "setProperty");
await act(async () => {
input.dispatchEvent(new Event("scroll"));
});
const rewritten = setProperty.mock.calls.map(([property]) => property);
expect(rewritten).not.toContain("font-size");
expect(rewritten).not.toContain("line-height");
setProperty.mockRestore();
await act(async () => root.unmount());
});

it("copies non-numeric lengths like normal line-height onto the mirror without NaN", async () => {
vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });
stubZoomedComputedStyle({ zoom: 1.3, fontSize: "20.8px", lineHeight: "normal" });
const root = createRoot(document.body.appendChild(document.createElement("div")));
const inputRef = createRef<HTMLTextAreaElement>();
await act(async () => {
root.render(createElement(MentionTextarea, { inputRef, peers: [], value: "hello", onChange: () => {} }));
});
const mirror = document.querySelector<HTMLElement>(".mention-editor-mirror")!;
expect([mirror.style.fontSize, mirror.style.lineHeight]).toEqual(["16px", "normal"]);
await act(async () => root.unmount());
});

it("re-syncs the field height and mirror size on dusk:text-scale, and stops listening on unmount", async () => {
vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });
const metrics = { zoom: 1.3, fontSize: "20.8px", lineHeight: "31.2px" };
const computedSpy = stubZoomedComputedStyle(metrics);
const scrollHeight = vi.spyOn(HTMLTextAreaElement.prototype, "scrollHeight", "get").mockReturnValue(500);
const removeListener = vi.spyOn(window, "removeEventListener");
const root = createRoot(document.body.appendChild(document.createElement("div")));
const inputRef = createRef<HTMLTextAreaElement>();
await act(async () => {
root.render(createElement(MentionTextarea, { inputRef, peers: [], value: "hello", onChange: () => {} }));
});
const input = inputRef.current!;
const mirror = document.querySelector<HTMLElement>(".mention-editor-mirror")!;
expect(input.style.height).toBe("187.2px");
expect([mirror.style.fontSize, mirror.style.lineHeight]).toEqual(["16px", "24px"]);

metrics.zoom = 1.5;
metrics.fontSize = "27px";
metrics.lineHeight = "40.5px";
await act(async () => {
window.dispatchEvent(new Event("dusk:text-scale"));
});
expect(input.style.height).toBe("243px");
expect([mirror.style.fontSize, mirror.style.lineHeight]).toEqual(["18px", "27px"]);
const mirrorStyle = getComputedStyle(mirror);
expect([mirrorStyle.getPropertyValue("font-size"), mirrorStyle.getPropertyValue("line-height")]).toEqual(["27px", "40.5px"]);

await act(async () => root.unmount());
expect(inputRef.current).toBeNull();
expect(removeListener).toHaveBeenCalledWith("dusk:text-scale", expect.any(Function));
computedSpy.mockClear();
await act(async () => {
window.dispatchEvent(new Event("dusk:text-scale"));
});
expect(computedSpy).not.toHaveBeenCalled();
removeListener.mockRestore();
scrollHeight.mockRestore();
});
40 changes: 37 additions & 3 deletions src/components/MentionTextarea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,35 @@ import { openExternalLink } from "@/lib/app-links";
import { type MentionPeer } from "@/lib/mentions";
import { MentionText } from "./MentionText";

const TEXT_LAYOUT = ["font-family", "font-size", "font-weight", "font-style", "font-stretch", "font-feature-settings", "font-variation-settings",
"letter-spacing", "word-spacing", "line-height", "text-indent", "tab-size", "padding-top", "padding-right", "padding-bottom", "padding-left"] as const;
const TEXT_LAYOUT = ["font-family", "font-weight", "font-style", "font-stretch", "font-feature-settings", "font-variation-settings",
"letter-spacing", "word-spacing", "text-indent", "tab-size", "padding-top", "padding-right", "padding-bottom", "padding-left"] as const;
const ZOOMED_TEXT_LAYOUT = ["font-size", "line-height"] as const;

/** Android WebView's WebSettings.setTextZoom scales font-size and line-height even under text-size-adjust: none, so
* copying getComputedStyle(input) onto the mirror applies the system font scale a second time. Adjust the written
* value when the mirror's computed length drifts from the field's so both render at the same metrics. */
function syncZoomedLength(
mirror: HTMLDivElement,
mirrorStyle: CSSStyleDeclaration,
property: (typeof ZOOMED_TEXT_LAYOUT)[number],
value: string,
): void {
const target = Number.parseFloat(value);
if (!Number.isFinite(target) || target <= 0) {
mirror.style.setProperty(property, value);
return;
}
const current = Number.parseFloat(mirrorStyle.getPropertyValue(property));
if (mirror.style.getPropertyValue(property) && Number.isFinite(current) && Math.abs(current - target) <= 0.05) return;
let specified = target;
mirror.style.setProperty(property, value);
for (let step = 0; step < 2; step++) {
const actual = Number.parseFloat(mirrorStyle.getPropertyValue(property));
if (!Number.isFinite(actual) || actual <= 0 || Math.abs(actual - target) <= 0.05) return;
specified *= target / actual;
mirror.style.setProperty(property, `${Math.round(specified * 1000) / 1000}px`);
}
}

/** React 19 copies a controlled textarea's value into its defaultValue on every change, which replaces the textarea's
* text child; Chromium 158 answers that child change with a :has() restyle of the subtree the field sits
Expand Down Expand Up @@ -66,6 +93,8 @@ export function MentionTextarea({ inputRef, peers, everyone = false, wrapperClas
if (!input || !mirror) return;
const style = getComputedStyle(input);
for (const property of TEXT_LAYOUT) mirror.style.setProperty(property, style.getPropertyValue(property));
const mirrorStyle = getComputedStyle(mirror);
for (const property of ZOOMED_TEXT_LAYOUT) syncZoomedLength(mirror, mirrorStyle, property, style.getPropertyValue(property));
mirror.style.width = `${input.clientWidth}px`;
// the field can carry a margin inside the wrapper, or the wrapper a padding; the mirror sits exactly over the field,
// or the text drifts off the caret
Expand Down Expand Up @@ -97,7 +126,12 @@ export function MentionTextarea({ inputRef, peers, everyone = false, wrapperClas
else sync();
});
if (inputRef.current) observer.observe(inputRef.current);
return () => observer.disconnect();
const onTextScale = () => resize();
window.addEventListener("dusk:text-scale", onTextScale);
return () => {
observer.disconnect();
window.removeEventListener("dusk:text-scale", onTextScale);
};
}, [inputRef, resize, sync]);
return <div className={cn("mention-editor relative min-w-0 flex-1 self-center", wrapperClassName)}>
<div ref={mirrorRef} dir={props.dir} aria-hidden="true" data-command-hint={command?.hint ? "" : undefined} className="mention-editor-mirror pointer-events-none absolute inset-0 overflow-hidden">
Expand Down