|
1 | 1 | 'use client';
|
2 | 2 |
|
3 | 3 | import {useCallback, useRef} from 'react';
|
4 |
| -import {useLayoutEffect, useResizeObserver} from '@react-aria/utils'; |
| 4 | +import {useLayoutEffect} from '@react-aria/utils'; |
5 | 5 |
|
| 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 |
6 | 8 | export function TitleResizer() {
|
7 | 9 | let titleRef = useRef<HTMLHeadingElement>(null);
|
| 10 | + let raf = useRef<number | null>(null); |
8 | 11 |
|
9 | 12 | // Size the title to fit the available space.
|
10 | 13 | let updateTitleFontSize = useCallback(() => {
|
@@ -35,13 +38,38 @@ export function TitleResizer() {
|
35 | 38 |
|
36 | 39 | useLayoutEffect(() => {
|
37 | 40 | titleRef.current = document.querySelector('h1');
|
| 41 | + |
| 42 | + if (titleRef.current == null) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
38 | 46 | 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); |
40 | 59 |
|
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]); |
45 | 73 |
|
46 | 74 | return null;
|
47 | 75 | }
|
0 commit comments