From a0cf98637e36911aa0ef9afe7d78f2717f0cb018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=8C=E8=B4=A7=E7=88=B1=E5=90=83=E7=99=BD=E8=90=9D?= =?UTF-8?q?=E5=8D=9C?= Date: Mon, 31 Jul 2023 22:03:21 +0800 Subject: [PATCH] fix: getCurrentLink not trigger when scroll (#43917) * fix: getCurrentLink not trigger when scroll * chore: fix lint --- components/anchor/Anchor.tsx | 20 +++++++++----------- components/anchor/__tests__/Anchor.test.tsx | 18 ++++++++++++++++-- scripts/argos-upload.js | 6 +++--- scripts/check-commit.js | 2 +- scripts/check-demo.js | 2 +- scripts/check-site.js | 12 ++++++------ scripts/check-ts-demo.js | 6 +++--- scripts/check-version-md.js | 2 +- scripts/css-variable-sync.js | 8 +++++--- scripts/generate-version.js | 2 +- scripts/generateLegacyLocale.js | 4 ++-- scripts/post-script.js | 2 +- scripts/print-changelog.js | 4 ++-- tests/dekko/lib.test.js | 14 ++++++++------ tests/setup.js | 2 +- 15 files changed, 60 insertions(+), 44 deletions(-) diff --git a/components/anchor/Anchor.tsx b/components/anchor/Anchor.tsx index 1064dbec99..e5e6bbdbcf 100644 --- a/components/anchor/Anchor.tsx +++ b/components/anchor/Anchor.tsx @@ -87,7 +87,7 @@ export interface AntAnchor { ) => void; } -const AnchorContent: React.FC = props => { +const AnchorContent: React.FC = (props) => { const { anchorPrefixCls: prefixCls, className = '', @@ -119,18 +119,18 @@ const AnchorContent: React.FC = props => { const dependencyListItem: React.DependencyList[number] = JSON.stringify(links); const registerLink = React.useCallback( - link => { + (link) => { if (!links.includes(link)) { - setLinks(prev => [...prev, link]); + setLinks((prev) => [...prev, link]); } }, [dependencyListItem], ); const unregisterLink = React.useCallback( - link => { + (link) => { if (links.includes(link)) { - setLinks(prev => prev.filter(i => i !== link)); + setLinks((prev) => prev.filter((i) => i !== link)); } }, [dependencyListItem], @@ -148,7 +148,7 @@ const AnchorContent: React.FC = props => { const getInternalCurrentAnchor = (_links: string[], _offsetTop = 0, _bounds = 5): string => { const linkSections: Section[] = []; const container = getCurrentContainer(); - _links.forEach(link => { + _links.forEach((link) => { const sharpLinkMatch = sharpMatcherRegx.exec(link?.toString()); if (!sharpLinkMatch) { return; @@ -188,9 +188,7 @@ const AnchorContent: React.FC = props => { if (animating.current) { return; } - if (typeof getCurrentAnchor === 'function') { - return; - } + const currentActiveLink = getInternalCurrentAnchor( links, targetOffset !== undefined ? targetOffset : offsetTop || 0, @@ -200,7 +198,7 @@ const AnchorContent: React.FC = props => { }, [dependencyListItem, targetOffset, offsetTop]); const handleScrollTo = React.useCallback<(link: string) => void>( - link => { + (link) => { setCurrentActiveLink(link); const container = getCurrentContainer(); const scrollTop = getScroll(container, true); @@ -305,7 +303,7 @@ const AnchorContent: React.FC = props => { ); }; -const Anchor: React.FC = props => { +const Anchor: React.FC = (props) => { const { prefixCls: customizePrefixCls } = props; const { getPrefixCls } = React.useContext(ConfigContext); const anchorPrefixCls = getPrefixCls('anchor', customizePrefixCls); diff --git a/components/anchor/__tests__/Anchor.test.tsx b/components/anchor/__tests__/Anchor.test.tsx index aa47e56c3c..40e68ebe9d 100644 --- a/components/anchor/__tests__/Anchor.test.tsx +++ b/components/anchor/__tests__/Anchor.test.tsx @@ -381,9 +381,12 @@ describe('Anchor Render', () => { { legacyRoot: true }, ); - expect(onChange).toHaveBeenCalledTimes(1); - fireEvent.click(container.querySelector(`a[href="#${hash2}"]`)!); + // Should be 2 times: + // 1. '' + // 2. hash1 (Since `getCurrentAnchor` still return same hash) expect(onChange).toHaveBeenCalledTimes(2); + fireEvent.click(container.querySelector(`a[href="#${hash2}"]`)!); + expect(onChange).toHaveBeenCalledTimes(3); expect(onChange).toHaveBeenLastCalledWith(`#${hash2}`); }); @@ -431,5 +434,16 @@ describe('Anchor Render', () => { fireEvent.scroll(window || document); }).not.toThrow(); }); + + it('should repeat trigger when scrolling', () => { + const getCurrentAnchor = jest.fn(); + render(); + + for (let i = 0; i < 100; i += 1) { + getCurrentAnchor.mockReset(); + fireEvent.scroll(window || document); + expect(getCurrentAnchor).toHaveBeenCalled(); + } + }); }); }); diff --git a/scripts/argos-upload.js b/scripts/argos-upload.js index 1d3d10b590..f5175babc9 100644 --- a/scripts/argos-upload.js +++ b/scripts/argos-upload.js @@ -2,9 +2,9 @@ // Create chunks for Argos: https://github.com/mui/material-ui/pull/23518 // https://github.com/mui/material-ui/blob/af81aae3b292ed180e7652a665fad1be2b38a7b3/scripts/pushArgos.js const util = require('util'); +const childProcess = require('child_process'); const glob = require('fast-glob'); const lodashChunk = require('lodash/chunk'); -const childProcess = require('child_process'); // eslint-disable-next-line import/no-unresolved const argos = require('@argos-ci/core'); @@ -35,7 +35,7 @@ async function run() { await Promise.all( chunks.map((chunk, chunkIndex) => Promise.all( - chunk.map(screenshot => cpToTemp(screenshot, `${screenshotsChunks}/${chunkIndex}`)), + chunk.map((screenshot) => cpToTemp(screenshot, `${screenshotsChunks}/${chunkIndex}`)), ), ), ); @@ -55,7 +55,7 @@ async function run() { } } -run().catch(error => { +run().catch((error) => { // eslint-disable-next-line no-console console.error(error); process.exit(1); diff --git a/scripts/check-commit.js b/scripts/check-commit.js index 721fd9f177..0179b71303 100755 --- a/scripts/check-commit.js +++ b/scripts/check-commit.js @@ -1,6 +1,6 @@ /* eslint-disable import/no-dynamic-require, no-console */ -const chalk = require('chalk'); const path = require('path'); +const chalk = require('chalk'); const fetch = require('isomorphic-fetch'); const simpleGit = require('simple-git'); diff --git a/scripts/check-demo.js b/scripts/check-demo.js index d903f7cdfc..0b2494c46d 100644 --- a/scripts/check-demo.js +++ b/scripts/check-demo.js @@ -1,7 +1,7 @@ const path = require('path'); +const fs = require('fs'); const yfm = require('yaml-front-matter'); const glob = require('glob'); -const fs = require('fs'); const demoFiles = glob.sync(path.join(process.cwd(), 'components/**/demo/*.md')); // eslint-disable-next-line no-restricted-syntax diff --git a/scripts/check-site.js b/scripts/check-site.js index 188962f55f..98c6607e36 100755 --- a/scripts/check-site.js +++ b/scripts/check-site.js @@ -1,7 +1,7 @@ /* eslint-disable no-await-in-loop */ /* eslint-disable no-restricted-syntax */ -const fetch = require('isomorphic-fetch'); const { join } = require('path'); +const fetch = require('isomorphic-fetch'); const cheerio = require('cheerio'); const glob = require('glob'); const uniq = require('lodash/uniq'); @@ -14,14 +14,14 @@ const components = uniq( cwd: join(process.cwd()), dot: false, }) - .map(path => path.replace(/(\/index)?((\.zh-cn)|(\.en-us))?\.md$/i, '')), + .map((path) => path.replace(/(\/index)?((\.zh-cn)|(\.en-us))?\.md$/i, '')), ); describe('site test', () => { let server; const port = 3000; - const render = async path => { - const resp = await fetch(`http://127.0.0.1:${port}${path}`).then(async res => { + const render = async (path) => { + const resp = await fetch(`http://127.0.0.1:${port}${path}`).then(async (res) => { const html = await res.text(); const $ = cheerio.load(html, { decodeEntities: false, recognizeSelfClosing: true }); return { @@ -33,12 +33,12 @@ describe('site test', () => { return resp; }; - const handleComponentName = name => { + const handleComponentName = (name) => { const componentName = name.split('/')[1]; return componentName.toLowerCase().replace('-', ''); }; - const expectComponent = async component => { + const expectComponent = async (component) => { const { status, $ } = await render(`/${component}/`); expect(status).toBe(200); expect($('.markdown > h1').text().toLowerCase()).toMatch(handleComponentName(component)); diff --git a/scripts/check-ts-demo.js b/scripts/check-ts-demo.js index 9aecabd730..5883bc9656 100644 --- a/scripts/check-ts-demo.js +++ b/scripts/check-ts-demo.js @@ -1,10 +1,10 @@ /* eslint-disable no-await-in-loop, no-console */ const path = require('path'); +const { spawn } = require('child_process'); const glob = require('glob'); const fs = require('fs-extra'); const chalk = require('chalk'); -const { spawn } = require('child_process'); (async () => { console.time('Execution...'); @@ -18,7 +18,7 @@ const { spawn } = require('child_process'); function getTypescriptDemo(content, demoPath) { const lines = content.split(/[\n\r]/); - const tsxStartLine = lines.findIndex(line => + const tsxStartLine = lines.findIndex((line) => line.replace(/\s/g).toLowerCase().includes('```tsx'), ); @@ -72,7 +72,7 @@ const { spawn } = require('child_process'); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); - child.on('exit', async code => { + child.on('exit', async (code) => { console.timeEnd('Execution...'); if (code) { diff --git a/scripts/check-version-md.js b/scripts/check-version-md.js index 0af79fb994..b47ba5bd72 100644 --- a/scripts/check-version-md.js +++ b/scripts/check-version-md.js @@ -1,7 +1,7 @@ /* eslint no-console: 0 */ -const chalk = require('chalk'); const fs = require('fs'); const { join } = require('path'); +const chalk = require('chalk'); const moment = require('moment'); const getChangelogByVersion = (content, version) => { diff --git a/scripts/css-variable-sync.js b/scripts/css-variable-sync.js index f46cb13c16..0264afb13d 100644 --- a/scripts/css-variable-sync.js +++ b/scripts/css-variable-sync.js @@ -3,8 +3,8 @@ * `variable.less` from the `default.less` */ -const fse = require('fs-extra'); const path = require('path'); +const fse = require('fs-extra'); const chalk = require('chalk'); const folderPath = path.resolve(__dirname, '..', 'components', 'style', 'themes'); @@ -25,8 +25,10 @@ function replaceVariable(key, value) { function replaceVariableContent(key, content) { const lines = variableContent.split(/\n/); - const startIndex = lines.findIndex(line => line.includes(`[CSS-VARIABLE-REPLACE-BEGIN: ${key}]`)); - const endIndex = lines.findIndex(line => line.includes(`[CSS-VARIABLE-REPLACE-END: ${key}]`)); + const startIndex = lines.findIndex((line) => + line.includes(`[CSS-VARIABLE-REPLACE-BEGIN: ${key}]`), + ); + const endIndex = lines.findIndex((line) => line.includes(`[CSS-VARIABLE-REPLACE-END: ${key}]`)); if (startIndex !== -1 && endIndex !== -1) { variableContent = [...lines.slice(0, startIndex), content, ...lines.slice(endIndex + 1)].join( diff --git a/scripts/generate-version.js b/scripts/generate-version.js index edb5b56074..9e5d7d0d83 100644 --- a/scripts/generate-version.js +++ b/scripts/generate-version.js @@ -1,5 +1,5 @@ -const fs = require('fs-extra'); const path = require('path'); +const fs = require('fs-extra'); const { version } = require('../package.json'); diff --git a/scripts/generateLegacyLocale.js b/scripts/generateLegacyLocale.js index ba3350b3c7..05d22f33a8 100644 --- a/scripts/generateLegacyLocale.js +++ b/scripts/generateLegacyLocale.js @@ -1,12 +1,12 @@ /* eslint-disable no-console */ /** Generate legacy locale file as shadow of `/locale` to `/locale-provider`. */ -const glob = require('glob'); const fs = require('fs'); +const glob = require('glob'); const chalk = require('chalk'); glob('components/locale/@(*_*|default).tsx', (er, files) => { - files.forEach(filePath => { + files.forEach((filePath) => { const modulePath = filePath.replace(/^components/, '..').replace('.tsx', ''); const legacyModulePath = filePath.replace('locale', 'locale-provider'); diff --git a/scripts/post-script.js b/scripts/post-script.js index a5b142652c..029456116b 100644 --- a/scripts/post-script.js +++ b/scripts/post-script.js @@ -1,9 +1,9 @@ /* eslint-disable no-console */ +const { spawnSync } = require('child_process'); const fetch = require('isomorphic-fetch'); const semver = require('semver'); const moment = require('moment'); const chalk = require('chalk'); -const { spawnSync } = require('child_process'); const DEPRECIATED_VERSION = { '>= 4.21.6 < 4.22.0': ['https://github.com/ant-design/ant-design/pull/36682'], diff --git a/scripts/print-changelog.js b/scripts/print-changelog.js index 388828ba5b..52b6a5b03b 100644 --- a/scripts/print-changelog.js +++ b/scripts/print-changelog.js @@ -1,12 +1,12 @@ /* eslint-disable no-await-in-loop, no-console */ -const chalk = require('chalk'); const { spawn } = require('child_process'); +const path = require('path'); +const chalk = require('chalk'); const jsdom = require('jsdom'); const jQuery = require('jquery'); const fetch = require('isomorphic-fetch'); const open = require('open'); const fs = require('fs-extra'); -const path = require('path'); const simpleGit = require('simple-git'); const { JSDOM } = jsdom; diff --git a/tests/dekko/lib.test.js b/tests/dekko/lib.test.js index fb7be23135..d69e296f48 100644 --- a/tests/dekko/lib.test.js +++ b/tests/dekko/lib.test.js @@ -1,6 +1,6 @@ +const path = require('path'); const $ = require('dekko'); const chalk = require('chalk'); -const path = require('path'); function getFileName(filePath) { return filePath.slice(filePath.lastIndexOf(path.sep) + 1); @@ -12,14 +12,14 @@ $('lib/style').isDirectory().hasFile('index.css').hasFile('default.css'); $('lib/*') .filter( - filename => + (filename) => !filename.endsWith('index.js') && !filename.endsWith('index.d.ts') && !filename.endsWith('.map'), ) .isDirectory() .filter( - filename => + (filename) => !filename.endsWith('style') && !filename.endsWith('_util') && !filename.endsWith('locale'), ) .hasFile('index.js') @@ -29,7 +29,7 @@ $('lib/*') $('lib/*/style').hasFile('css.js').hasFile('index.js'); // locale -const filterLocaleFile = filePath => { +const filterLocaleFile = (filePath) => { const fileName = getFileName(filePath); return ( !fileName.endsWith('index.js') && @@ -47,10 +47,12 @@ const localeProviderFiles = $('lib/locale-provider/*').filter(filterLocaleFile); function compare(originFiles, targetFiles, targetPath) { originFiles.assert( `not exist in '${targetPath}'. Please use 'scripts/generateLegacyLocale.js' to refresh locale files.`, - filePath => { + (filePath) => { const fileName = getFileName(filePath); - return targetFiles.filenames.some(targetFilePath => getFileName(targetFilePath) === fileName); + return targetFiles.filenames.some( + (targetFilePath) => getFileName(targetFilePath) === fileName, + ); }, ); } diff --git a/tests/setup.js b/tests/setup.js index cb8987bd9d..b871346b07 100644 --- a/tests/setup.js +++ b/tests/setup.js @@ -1,5 +1,5 @@ -const React = require('react'); const util = require('util'); +const React = require('react'); // eslint-disable-next-line no-console console.log('Current React Version:', React.version);