Skip to content
This repository was archived by the owner on Jan 30, 2025. It is now read-only.

Commit 16d0c45

Browse files
committed
feat(refresh-on): fix refresh-on-navigate to refresh-on added hot reload feature
1 parent f6fe336 commit 16d0c45

File tree

3 files changed

+52
-27
lines changed

3 files changed

+52
-27
lines changed

src/core/component/refresh-on-navigate.tsx

Lines changed: 0 additions & 25 deletions
This file was deleted.

src/core/component/refresh-on.tsx

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'use client';
2+
3+
import { useEffect } from 'react';
4+
import { useRouter, usePathname } from 'next/navigation';
5+
6+
export const RefreshOn = () => {
7+
const router = useRouter();
8+
const pathname = usePathname();
9+
10+
useEffect(() => {
11+
const handleClick = (e: MouseEvent) => {
12+
const target = e.target as HTMLElement;
13+
const targetAnchor = target.closest('a');
14+
if (pathname && targetAnchor instanceof HTMLAnchorElement && targetAnchor.origin === window.location.origin) router.refresh();
15+
};
16+
17+
const observeStyleSheets = () => {
18+
const styleObserver = new MutationObserver(mutations => {
19+
for (const mutation of mutations) {
20+
if (mutation.type === 'childList') {
21+
const addedNodes = Array.from(mutation.addedNodes);
22+
if (addedNodes.some(node => node instanceof HTMLStyleElement || node instanceof HTMLLinkElement)) {
23+
requestAnimationFrame(() => {
24+
router.refresh();
25+
});
26+
break;
27+
}
28+
}
29+
}
30+
});
31+
32+
styleObserver.observe(document.head, {
33+
childList: true,
34+
subtree: false,
35+
});
36+
37+
return styleObserver;
38+
};
39+
40+
document.addEventListener('click', handleClick);
41+
const cssObserver = observeStyleSheets();
42+
43+
return () => {
44+
document.removeEventListener('click', handleClick);
45+
cssObserver.disconnect();
46+
};
47+
}, [router, pathname]);
48+
49+
return null;
50+
};

src/core/component/server-style-preview.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { getServerCSS } from '../../_internal/utils/inject-server-css';
22
import { isDevServer } from '../../_internal/utils/helper';
3-
import { RefreshOnNavigate } from './refresh-on-navigate';
3+
import { RefreshOn } from './refresh-on';
44

55
export const ServerStylePreview = (): JSX.Element | null => {
66
if (!isDevServer) return null;
@@ -9,7 +9,7 @@ export const ServerStylePreview = (): JSX.Element | null => {
99

1010
return (
1111
<>
12-
<RefreshOnNavigate />
12+
<RefreshOn />
1313
<style dangerouslySetInnerHTML={{ __html: serverCSS }} />
1414
</>
1515
);

0 commit comments

Comments
 (0)