Skip to content
This repository has been archived by the owner on Nov 1, 2024. It is now read-only.

Commit

Permalink
fix(refresh-on.tsx): add debounce processing
Browse files Browse the repository at this point in the history
  • Loading branch information
refirst11 committed Oct 24, 2024
1 parent 2bf19ef commit cc839f3
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/core/component/refresh-on.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
'use client';

import { useEffect } from 'react';
import { useEffect, useTransition } from 'react';
import { useRouter, usePathname } from 'next/navigation';

export const RefreshOn = () => {
const router = useRouter();
const pathname = usePathname();
const [, startTransition] = useTransition();

useEffect(() => {
const handleClick = (e: MouseEvent) => {
const target = e.target as HTMLElement;
const targetAnchor = target.closest('a');
if (pathname && targetAnchor instanceof HTMLAnchorElement && targetAnchor.origin === window.location.origin) router.refresh();
};

let isRefreshing = false; // Debounce processing
const observeStyleSheets = () => {
const styleObserver = new MutationObserver(mutations => {
if (isRefreshing) return;
for (const mutation of mutations) {
if (mutation.type === 'childList') {
const addedNodes = Array.from(mutation.addedNodes);
if (addedNodes.some(node => node instanceof HTMLStyleElement || node instanceof HTMLLinkElement)) {
requestAnimationFrame(() => {
if (
addedNodes.some(
node =>
node instanceof HTMLStyleElement || (node instanceof HTMLLinkElement && !(node.rel === 'preload' && node.getAttribute('as') === 'style'))
)
) {
startTransition(() => {
isRefreshing = true;
router.refresh();
setTimeout(() => {
isRefreshing = false;
}, 100);
});
break;
}
Expand Down

0 comments on commit cc839f3

Please sign in to comment.