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

useComposerMultilinePrompt.ts

46 lines1.8 KB

1import { useLayoutEffect, useState } from "react";
2​
3export function measureComposerMultilinePrompt(body: HTMLElement): boolean | null {
4 const editor = body.querySelector<HTMLElement>('[data-testid="composer-editor"]');
5 if (!editor || editor.clientWidth === 0) return null;
6​
7 const bodyStyle = getComputedStyle(body);
8 const expandedWidth =
9 body.clientWidth -
10 Number.parseFloat(bodyStyle.paddingLeft) -
11 Number.parseFloat(bodyStyle.paddingRight);
12 const lineHeight = Number.parseFloat(getComputedStyle(editor).lineHeight);
13 const range = document.createRange();
14 range.selectNodeContents(editor);
15 const bounds = range.getBoundingClientRect();
16​
17 // Measure content, not the editor's minimum height. While resting, the
18 // prompt is unwrapped: compare its width with the expanded row so that
19 // moving the actions inline cannot make collapse and expansion oscillate.
20 return bounds.height > lineHeight + 1 || bounds.width > expandedWidth + 1;
22​
23export function useComposerMultilinePrompt(body: HTMLElement | null): boolean {
24 const [isMultiline, setIsMultiline] = useState(false);
25​
26 useLayoutEffect(() => {
27 if (!body) return;
28 const measure = () => {
29 const next = measureComposerMultilinePrompt(body);
30 if (next !== null) setIsMultiline(next);
31 };
32 measure();
33 const resizeObserver = new ResizeObserver(measure);
34 resizeObserver.observe(body);
35 const editor = body.querySelector<HTMLElement>('[data-testid="composer-editor"]');
36 if (editor) resizeObserver.observe(editor);
37 const mutationObserver = new MutationObserver(measure);
38 mutationObserver.observe(body, { childList: true, characterData: true, subtree: true });
39 return () => {
40 resizeObserver.disconnect();
41 mutationObserver.disconnect();
42 };
43 }, [body]);
44​
45 return isMultiline;