fix: getCurrentLink not trigger when scroll (#43917)

* fix: getCurrentLink not trigger when scroll

* chore: fix lint
This commit is contained in:
二货爱吃白萝卜 2023-07-31 22:03:21 +08:00 committed by GitHub
parent 2b43f73ff9
commit a0cf98637e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 60 additions and 44 deletions

View File

@ -87,7 +87,7 @@ export interface AntAnchor {
) => void;
}
const AnchorContent: React.FC<InternalAnchorProps> = props => {
const AnchorContent: React.FC<InternalAnchorProps> = (props) => {
const {
anchorPrefixCls: prefixCls,
className = '',
@ -119,18 +119,18 @@ const AnchorContent: React.FC<InternalAnchorProps> = props => {
const dependencyListItem: React.DependencyList[number] = JSON.stringify(links);
const registerLink = React.useCallback<AntAnchor['registerLink']>(
link => {
(link) => {
if (!links.includes(link)) {
setLinks(prev => [...prev, link]);
setLinks((prev) => [...prev, link]);
}
},
[dependencyListItem],
);
const unregisterLink = React.useCallback<AntAnchor['unregisterLink']>(
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<InternalAnchorProps> = 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<InternalAnchorProps> = 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<InternalAnchorProps> = 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<InternalAnchorProps> = props => {
);
};
const Anchor: React.FC<AnchorProps> = props => {
const Anchor: React.FC<AnchorProps> = (props) => {
const { prefixCls: customizePrefixCls } = props;
const { getPrefixCls } = React.useContext<ConfigConsumerProps>(ConfigContext);
const anchorPrefixCls = getPrefixCls('anchor', customizePrefixCls);

View File

@ -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(<Anchor getCurrentAnchor={getCurrentAnchor} />);
for (let i = 0; i < 100; i += 1) {
getCurrentAnchor.mockReset();
fireEvent.scroll(window || document);
expect(getCurrentAnchor).toHaveBeenCalled();
}
});
});
});

View File

@ -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);

View File

@ -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');

View File

@ -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

View File

@ -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));

View File

@ -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) {

View File

@ -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) => {

View File

@ -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(

View File

@ -1,5 +1,5 @@
const fs = require('fs-extra');
const path = require('path');
const fs = require('fs-extra');
const { version } = require('../package.json');

View File

@ -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');

View File

@ -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'],

View File

@ -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;

View File

@ -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,
);
},
);
}

View File

@ -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);