1- import { lazy , memo , Suspense } from "react" ;
1+ import { lazy , memo , Suspense , useLayoutEffect , useRef , useState } from "react" ;
2+
3+ import { observeResize } from "../../lib/observeResize" ;
24
35import { RenderErrorBoundary } from "../RenderErrorBoundary" ;
46
@@ -14,6 +16,20 @@ export const MarkdownMath = memo(function MarkdownMath(props: {
1416 display : boolean ;
1517 focusable ?: boolean ;
1618} ) {
19+ const viewportRef = useRef < HTMLSpanElement > ( null ) ;
20+ const contentRef = useRef < HTMLSpanElement > ( null ) ;
21+ const [ overflows , setOverflows ] = useState ( false ) ;
22+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes formula DOM width to make overflowing equations keyboard scrollable
23+ useLayoutEffect ( ( ) => {
24+ const viewport = viewportRef . current ;
25+ const content = contentRef . current ;
26+ if ( ! viewport || ! content || props . focusable === false ) return ;
27+ const measure = ( ) => setOverflows ( viewport . scrollWidth > viewport . clientWidth ) ;
28+ measure ( ) ;
29+ // Typesetting and streamed TeX can change content width without resizing the viewport.
30+ return observeResize ( [ viewport , content ] , measure ) ;
31+ } , [ props . focusable ] ) ;
32+ const scrollable = props . focusable !== false && overflows ;
1733 const tex = props . tex . trim ( ) ;
1834 const source = props . display ? `\\[\n${ tex } \n\\]` : `\\(${ tex } \\)` ;
1935 const fallback = < span className = "whitespace-pre-wrap" > { source } </ span > ;
@@ -36,17 +52,21 @@ export const MarkdownMath = memo(function MarkdownMath(props: {
3652 }
3753 >
3854 < span
55+ ref = { viewportRef }
3956 className = "block max-w-full overflow-x-auto overflow-y-hidden in-[.chat-markdown-table-container]:max-w-none in-[.chat-markdown-table-container]:overflow-visible px-0.5 py-0.75 focus-visible:outline-1 focus-visible:outline-solid focus-visible:-outline-offset-1 focus-visible:outline-border [&::-webkit-scrollbar]:h-2 [&::-webkit-scrollbar-thumb]:rounded [&::-webkit-scrollbar-thumb]:border [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-clip-content"
40- tabIndex = { props . focusable === false ? - 1 : 0 }
57+ tabIndex = { scrollable ? 0 : - 1 }
4158 aria-label = {
42- props . focusable === false
59+ ! scrollable
4360 ? undefined
4461 : props . display
4562 ? "Scroll display equation"
4663 : "Scroll inline equation"
4764 }
4865 >
49- < span className = { props . display ? "inline-block w-max min-w-full" : "inline-block w-max" } >
66+ < span
67+ ref = { contentRef }
68+ className = { props . display ? "inline-block w-max min-w-full" : "inline-block w-max" }
69+ >
5070 < RenderErrorBoundary resetKeys = { [ tex ] } fallback = { fallback } >
5171 < Suspense fallback = { fallback } >
5272 < MathTypeset tex = { tex } display = { props . display } fallback = { fallback } />
0 commit comments