Skip to content

Commit 11a07c0

Browse files
nikzandayoyo837
andauthored
fix(Anchor): avoid duplicate onChange with getCurrentAnchor (#58834)
* fix(Anchor): avoid duplicate onChange with getCurrentAnchor * fix(Anchor): avoid remapping getCurrentAnchor results * fix(Anchor): preserve raw click identity * test(Anchor): use named demo props interface --------- Co-authored-by: Amumu <[email protected]>
1 parent c4b9f5e commit 11a07c0

2 files changed

Lines changed: 99 additions & 12 deletions

File tree

‎components/anchor/Anchor.tsx‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ const Anchor: React.FC<AnchorProps> = (props) => {
167167
const [links, setLinks] = React.useState<string[]>([]);
168168
const [activeLink, setActiveLink] = React.useState<string | null>(null);
169169
const activeLinkRef = React.useRef<string | null>(activeLink);
170+
const rawActiveLinkRef = React.useRef<string | null>(activeLink);
170171

171172
const wrapperRef = React.useRef<HTMLDivElement>(null);
172173
const spanLinkNodeRef = React.useRef<HTMLSpanElement>(null);
@@ -261,17 +262,21 @@ const Anchor: React.FC<AnchorProps> = (props) => {
261262
return '';
262263
};
263264

264-
const setCurrentActiveLink = useEvent((link: string) => {
265-
// FIXME: Seems a bug since this compare is not equals
266-
// `activeLinkRef` is parsed value which will always trigger `onChange` event.
267-
if (activeLinkRef.current === link) {
268-
return;
269-
}
265+
const setCurrentActiveLink = useEvent((link: string, forceTriggerChange = false) => {
266+
rawActiveLinkRef.current = link;
270267

271268
// https://github.com/ant-design/ant-design/issues/30584
272269
const newLink = isFunction(getCurrentAnchor) ? getCurrentAnchor(link) : link;
273-
setActiveLink(newLink);
274-
activeLinkRef.current = newLink;
270+
const isSameLink = activeLinkRef.current === newLink;
271+
272+
if (isSameLink && !forceTriggerChange) {
273+
return;
274+
}
275+
276+
if (!isSameLink) {
277+
setActiveLink(newLink);
278+
activeLinkRef.current = newLink;
279+
}
275280

276281
// onChange should respect the original link (which may caused by
277282
// window scroll or user click), not the new link
@@ -295,8 +300,8 @@ const Anchor: React.FC<AnchorProps> = (props) => {
295300

296301
const handleScrollTo = React.useCallback<(link: string, targetOffsetParams?: number) => void>(
297302
(link, targetOffsetParams) => {
298-
const previousActiveLink = activeLinkRef.current;
299-
setCurrentActiveLink(link);
303+
const previousRawActiveLink = rawActiveLinkRef.current;
304+
setCurrentActiveLink(link, previousRawActiveLink !== link);
300305
const sharpLinkMatch = sharpMatcherRegex.exec(link);
301306
if (!sharpLinkMatch) {
302307
return;
@@ -307,7 +312,7 @@ const Anchor: React.FC<AnchorProps> = (props) => {
307312
}
308313

309314
if (animatingRef.current) {
310-
if (previousActiveLink === link) {
315+
if (previousRawActiveLink === link) {
311316
return;
312317
}
313318
scrollRequestIdRef.current?.();
@@ -404,7 +409,7 @@ const Anchor: React.FC<AnchorProps> = (props) => {
404409

405410
React.useEffect(() => {
406411
if (isFunction(getCurrentAnchor)) {
407-
setCurrentActiveLink(getCurrentAnchor(activeLinkRef.current || ''));
412+
setCurrentActiveLink(rawActiveLinkRef.current || '');
408413
}
409414
}, [getCurrentAnchor]);
410415

‎components/anchor/__tests__/Anchor.test.tsx‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,54 @@ describe('Anchor Render', () => {
671671
expect(onChange).toHaveBeenLastCalledWith(`#${hash2}`);
672672
});
673673

674+
it('should trigger onChange when a raw link matches the mapped active link', () => {
675+
const hash1 = getHashUrl();
676+
const hash2 = getHashUrl();
677+
const onChange = jest.fn();
678+
const { container } = render(
679+
<Anchor
680+
onChange={onChange}
681+
getCurrentAnchor={(link) => (link === `#${hash1}` ? `#${hash2}` : link)}
682+
items={[
683+
{ key: hash1, href: `#${hash1}`, title: hash1 },
684+
{ key: hash2, href: `#${hash2}`, title: hash2 },
685+
]}
686+
/>,
687+
);
688+
689+
fireEvent.click(container.querySelector(`a[href="#${hash1}"]`)!);
690+
expect(container.querySelector(`.ant-anchor-link-title-active`)?.textContent).toBe(hash2);
691+
expect(onChange).toHaveBeenLastCalledWith(`#${hash1}`);
692+
onChange.mockClear();
693+
fireEvent.click(container.querySelector(`a[href="#${hash2}"]`)!);
694+
expect(onChange).toHaveBeenCalledTimes(1);
695+
expect(onChange).toHaveBeenCalledWith(`#${hash2}`);
696+
});
697+
698+
it('should not trigger onChange repeatedly when scrolling with getCurrentAnchor', () => {
699+
const hash1 = getHashUrl();
700+
const hash2 = getHashUrl();
701+
const onChange = jest.fn();
702+
const getCurrentAnchor = jest.fn(() => `#${hash2}`);
703+
render(
704+
<Anchor
705+
onChange={onChange}
706+
getCurrentAnchor={getCurrentAnchor}
707+
items={[
708+
{ key: hash1, href: `#${hash1}`, title: hash1 },
709+
{ key: hash2, href: `#${hash2}`, title: hash2 },
710+
]}
711+
/>,
712+
);
713+
714+
onChange.mockClear();
715+
getCurrentAnchor.mockClear();
716+
fireEvent.scroll(window);
717+
fireEvent.scroll(window);
718+
expect(getCurrentAnchor).toHaveBeenCalledTimes(2);
719+
expect(onChange).not.toHaveBeenCalled();
720+
});
721+
674722
// https://github.com/ant-design/ant-design/issues/34784
675723
it('getCurrentAnchor have default link as argument', () => {
676724
const hash1 = getHashUrl();
@@ -711,6 +759,40 @@ describe('Anchor Render', () => {
711759
expect(container.querySelector(`.ant-anchor-link-title-active`)?.textContent).toBe(hash2);
712760
});
713761

762+
it('should apply getCurrentAnchor once when it changes', () => {
763+
const hash1 = getHashUrl();
764+
const hash2 = getHashUrl();
765+
const hash3 = getHashUrl();
766+
interface DemoProps {
767+
mappedLink: string;
768+
}
769+
770+
const Demo: React.FC<DemoProps> = ({ mappedLink }) => (
771+
<Anchor
772+
getCurrentAnchor={(link) => {
773+
if (link === `#${hash1}`) {
774+
return `#${hash2}`;
775+
}
776+
if (link === `#${hash2}`) {
777+
return `#${mappedLink}`;
778+
}
779+
return link;
780+
}}
781+
items={[
782+
{ key: hash1, href: `#${hash1}`, title: hash1 },
783+
{ key: hash2, href: `#${hash2}`, title: hash2 },
784+
{ key: hash3, href: `#${hash3}`, title: hash3 },
785+
]}
786+
/>
787+
);
788+
const { container, rerender } = render(<Demo mappedLink={hash2} />);
789+
fireEvent.click(container.querySelector(`a[href="#${hash1}"]`)!);
790+
expect(container.querySelector(`.ant-anchor-link-title-active`)?.textContent).toBe(hash2);
791+
792+
rerender(<Demo mappedLink={hash3} />);
793+
expect(container.querySelector(`.ant-anchor-link-title-active`)?.textContent).toBe(hash2);
794+
});
795+
714796
it('should render correctly when href is null', () => {
715797
expect(() => {
716798
render(

0 commit comments

Comments
 (0)