Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useComposerMultilinePrompt.ts

43 lines1.6 KB

1import { useLayoutEffect, useState } from "react";
2import { observeResize } from "../../lib/observeResize";
3​
4function measureComposerMultilinePrompt(body: HTMLElement): boolean | null {
5 const editor = body.querySelector<HTMLElement>('[data-testid="composer-editor"]');
6 if (!editor || editor.clientWidth === 0) return null;
7​
8 const bodyStyle = getComputedStyle(body);
9 const expandedWidth =
10 body.clientWidth -
11 Number.parseFloat(bodyStyle.paddingLeft) -
12 Number.parseFloat(bodyStyle.paddingRight);
13 const lineHeight = Number.parseFloat(getComputedStyle(editor).lineHeight);
14 const range = document.createRange();
15 range.selectNodeContents(editor);
16 const bounds = range.getBoundingClientRect();
17​
18 // Measure against expanded width to prevent inline actions oscillating collapse.
19 return bounds.height > lineHeight + 1 || bounds.width > expandedWidth + 1;
21​
22export function useComposerMultilinePrompt(body: HTMLElement | null): boolean {
23 const [isMultiline, setIsMultiline] = useState(false);
24​
25 useLayoutEffect(() => {
26 if (!body) return;
27 const measure = () => {
28 const next = measureComposerMultilinePrompt(body);
29 if (next !== null) setIsMultiline(next);
30 };
31 measure();
32 const editor = body.querySelector<HTMLElement>('[data-testid="composer-editor"]');
33 const stopObserving = observeResize(editor ? [body, editor] : body, measure);
34 const mutationObserver = new MutationObserver(measure);
35 mutationObserver.observe(body, { childList: true, characterData: true, subtree: true });
36 return () => {
37 stopObserving();
38 mutationObserver.disconnect();
39 };
40 }, [body]);
41​
42 return isMultiline;