Skip to content

Commit 96e5138

Browse files
committed
dont use useResizeObserver because we want to catch fonts changing
1 parent 0ecf094 commit 96e5138

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

packages/dev/s2-docs/src/TitleResizer.tsx

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
'use client';
22

33
import {useCallback, useRef} from 'react';
4-
import {useLayoutEffect, useResizeObserver} from '@react-aria/utils';
4+
import {useLayoutEffect} from '@react-aria/utils';
55

6+
// TODO: this causes a flash when the headings change size, maybe we just move this code
7+
// to client and append suppressHydrationWarning to the h1s
68
export function TitleResizer() {
79
let titleRef = useRef<HTMLHeadingElement>(null);
10+
let raf = useRef<number | null>(null);
811

912
// Size the title to fit the available space.
1013
let updateTitleFontSize = useCallback(() => {
@@ -35,13 +38,38 @@ export function TitleResizer() {
3538

3639
useLayoutEffect(() => {
3740
titleRef.current = document.querySelector('h1');
41+
42+
if (titleRef.current == null) {
43+
return;
44+
}
45+
3846
updateTitleFontSize();
39-
}, [updateTitleFontSize]);
47+
// Use ResizeObserver where available to detect size changes not related to window resizing, e.g. font loading.
48+
if (typeof ResizeObserver !== 'undefined') {
49+
let observer = new ResizeObserver(() => {
50+
if (!raf.current) {
51+
// Avoid updating the layout during the resize event and creating circular notifications.
52+
raf.current = requestAnimationFrame(() => {
53+
updateTitleFontSize();
54+
raf.current = null;
55+
});
56+
}
57+
});
58+
observer.observe(titleRef.current);
4059

41-
useResizeObserver({
42-
ref: titleRef,
43-
onResize: updateTitleFontSize
44-
});
60+
return () => {
61+
observer.disconnect();
62+
if (raf.current) {
63+
cancelAnimationFrame(raf.current);
64+
}
65+
};
66+
} else {
67+
window.addEventListener('resize', updateTitleFontSize);
68+
return () => {
69+
window.removeEventListener('resize', updateTitleFontSize);
70+
};
71+
}
72+
}, [updateTitleFontSize]);
4573

4674
return null;
4775
}

0 commit comments

Comments
 (0)