MCPcopy Create free account
hub / github.com/dailydotdev/apps / useKeyboardFit

Function useKeyboardFit

packages/shared/src/hooks/utils/useKeyboardFit.ts:19–52  ·  view source on GitHub ↗
(
  ref: RefObject<HTMLElement>,
  enabled: boolean,
)

Source from the content-addressed store, hash-verified

17// at the top, so a header stays put and a composer sits on the keyboard.
18// Returns that height, or undefined while there is no keyboard.
19export const useKeyboardFit = (
20 ref: RefObject<HTMLElement>,
21 enabled: boolean,
22): number | undefined => {
23 const viewport = useVisualViewport(enabled);
24 const [height, setHeight] = useState<number>();
25
26 useLayoutEffect(() => {
27 const visibleHeight = viewport.height ?? 0;
28 const isKeyboardOpen =
29 enabled &&
30 !!visibleHeight &&
31 Math.abs((viewport.scale ?? 1) - 1) <= 0.01 &&
32 document.documentElement.clientHeight - visibleHeight >=
33 keyboardThreshold &&
34 isEditing();
35
36 if (!isKeyboardOpen) {
37 setHeight(undefined);
38 return;
39 }
40 if (window.scrollY !== 0) {
41 window.scrollTo(0, 0);
42 }
43 // In layout coordinates the visible area ends at offsetTop + height:
44 // if the browser keeps a pan the scroll can't undo, the element still
45 // ends on the keyboard instead of leaving a gap above it.
46 const visibleBottom = (viewport.offsetTop ?? 0) + visibleHeight;
47 const top = ref.current?.getBoundingClientRect().top ?? 0;
48 setHeight(Math.max(0, Math.round(visibleBottom - top)));
49 }, [enabled, ref, viewport]);
50
51 return height;
52};

Callers 2

MessagesScreenFunction · 0.90
ScreenFunction · 0.90

Calls 2

useVisualViewportFunction · 0.90
isEditingFunction · 0.85

Tested by 1

ScreenFunction · 0.72