| 480 | * view when it is off screen, then blinked. Returns the id while it blinks. |
| 481 | */ |
| 482 | const useBlinkLinkedRow = (campaignId?: string): string | undefined => { |
| 483 | const [blinkingId, setBlinkingId] = useState<string>(); |
| 484 | const doneIdRef = useRef<string>(); |
| 485 | const timeoutRef = useRef<ReturnType<typeof setTimeout>>(); |
| 486 | const frameRef = useRef<number>(); |
| 487 | |
| 488 | // Re-renders don't cancel a pending blink, only leaving the page does |
| 489 | useEffect( |
| 490 | () => () => { |
| 491 | clearTimeout(timeoutRef.current); |
| 492 | cancelAnimationFrame(frameRef.current ?? 0); |
| 493 | }, |
| 494 | [], |
| 495 | ); |
| 496 | |
| 497 | // Runs after every render until the row is on the page |
| 498 | useEffect(() => { |
| 499 | if (!campaignId || doneIdRef.current === campaignId) { |
| 500 | return; |
| 501 | } |
| 502 | |
| 503 | const row = document.querySelector(`[data-campaign-id="${campaignId}"]`); |
| 504 | // Not laid out yet, like while dev styles load |
| 505 | if (!row?.getClientRects().length) { |
| 506 | return; |
| 507 | } |
| 508 | |
| 509 | doneIdRef.current = campaignId; |
| 510 | const blink = () => { |
| 511 | cancelAnimationFrame(frameRef.current ?? 0); |
| 512 | setBlinkingId(campaignId); |
| 513 | timeoutRef.current = setTimeout(() => setBlinkingId(undefined), 1200); |
| 514 | }; |
| 515 | const { top, bottom } = row.getBoundingClientRect(); |
| 516 | |
| 517 | if (top >= 0 && bottom <= window.innerHeight) { |
| 518 | blink(); |
| 519 | return; |
| 520 | } |
| 521 | |
| 522 | const reduceMotion = window.matchMedia( |
| 523 | '(prefers-reduced-motion: reduce)', |
| 524 | ).matches; |
| 525 | row.scrollIntoView({ |
| 526 | block: 'center', |
| 527 | behavior: reduceMotion ? 'auto' : 'smooth', |
| 528 | }); |
| 529 | |
| 530 | // Blink once the page has moved and held still for a few frames (longer |
| 531 | // if it never moves, as smooth scrolling can start late), or after 1.5s |
| 532 | let lastY = window.scrollY; |
| 533 | let stillFrames = 0; |
| 534 | let hasMoved = false; |
| 535 | const waitForStill = () => { |
| 536 | const isStill = window.scrollY === lastY; |
| 537 | hasMoved = hasMoved || !isStill; |
| 538 | stillFrames = isStill ? stillFrames + 1 : 0; |
| 539 | lastY = window.scrollY; |