refactor: import jest as global; unify import style of some modules (#6898)

* refactor: import jest as global

* fix react
This commit is contained in:
Joshua Chen 2022-03-11 19:04:27 +08:00 committed by GitHub
parent e97dc0d37e
commit c9ee6e467c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
59 changed files with 177 additions and 139 deletions

View file

@ -166,7 +166,12 @@ module.exports = {
// selector:
// @ 'ExportDefaultDeclaration > Identifier, ExportNamedDeclaration[source=null] > ExportSpecifier',
// message: 'Export in one statement'
// }
// },
...['path', 'fs-extra', 'webpack', 'lodash'].map((m) => ({
selector: `ImportDeclaration[importKind=value]:has(Literal[value=${m}]) > ImportSpecifier[importKind=value]`,
message:
'Default-import this, both for readability and interoperability with ESM',
})),
],
'no-template-curly-in-string': WARNING,
'no-unused-expressions': [WARNING, {allowTaggedTemplates: true}],
@ -312,5 +317,11 @@ module.exports = {
'@typescript-eslint/explicit-module-boundary-types': OFF,
},
},
{
files: ['*.test.ts', '*.test.tsx'],
rules: {
'import/no-extraneous-dependencies': OFF,
},
},
],
};

View file

@ -4,7 +4,6 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable import/no-extraneous-dependencies */
import {Globby} from '@docusaurus/utils';
import fs from 'fs-extra';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import logger from '../index';
describe('formatters', () => {

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import remark from 'remark';
import mdx from 'remark-mdx';

View file

@ -5,22 +5,20 @@
* LICENSE file in the root directory of this source tree.
*/
import {join} from 'path';
import path from 'path';
import remark from 'remark';
import mdx from 'remark-mdx';
import vfile from 'to-vfile';
import plugin from '..';
const processFixture = async (name) => {
const path = join(__dirname, '__fixtures__', name);
const file = await vfile.read(path);
const processFixture = async (name: string) => {
const file = await vfile.read(path.join(__dirname, '__fixtures__', name));
const result = await remark().use(mdx).use(plugin).process(file);
return result.toString();
};
const processFixtureAST = async (name) => {
const path = join(__dirname, '__fixtures__', name);
const file = await vfile.read(path);
const processFixtureAST = async (name: string) => {
const file = await vfile.read(path.join(__dirname, '__fixtures__', name));
return remark().use(mdx).use(plugin).parse(file);
};

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {migrateDocusaurusProject} from '../index';
import path from 'path';
import fs from 'fs-extra';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import fs from 'fs-extra';
import {createBlogFeedFiles} from '../feed';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import pluginContentBlog from '../index';
import type {DocusaurusConfig, LoadContext, I18n} from '@docusaurus/types';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import fs from 'fs-extra';
import path from 'path';
import {linkify, type LinkifyParams, getSourceToPermalink} from '../blogUtils';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import {cliDocsVersionCommand} from '../cli';
import type {

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import {loadContext} from '@docusaurus/core/src/server/index';
import {

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import {isMatch} from 'picomatch';
import commander from 'commander';
@ -29,7 +30,7 @@ import type {
} from '../sidebars/types';
import {toSidebarsProp} from '../props';
import {validate} from 'webpack';
import webpack from 'webpack';
import {DefaultSidebarItemsGenerator} from '../sidebars/generator';
import {DisabledSidebars} from '../sidebars';
@ -311,7 +312,7 @@ describe('simple website', () => {
undefined,
content,
);
const errors = validate(config);
const errors = webpack.validate(config);
expect(errors).toBeUndefined();
});

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import fs from 'fs-extra';
import path from 'path';
import shell from 'shelljs';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import {
getVersionsFilePath,

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import fs from 'fs-extra';
import path from 'path';
import {linkify} from '../linkify';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {DefaultSidebarItemsGenerator} from '../generator';
import type {SidebarItemsGenerator} from '../types';
import {DefaultNumberPrefixParser} from '../../numberPrefix';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {processSidebars} from '../processor';
import type {
SidebarItem,

View file

@ -6,8 +6,8 @@
*/
import React, {
type ComponentProps,
isValidElement,
type ComponentProps,
type ReactElement,
} from 'react';
import Head from '@docusaurus/Head';
@ -52,7 +52,7 @@ const MDXComponents: MDXComponentsObject = {
const shouldBeInline = React.Children.toArray(props.children).every(
(el) =>
(typeof el === 'string' && !el.includes('\n')) ||
(React.isValidElement(el) && inlineElements.includes(el.props.mdxType)),
(isValidElement(el) && inlineElements.includes(el.props.mdxType)),
);
return shouldBeInline ? <code {...props} /> : <CodeBlock {...props} />;

View file

@ -8,7 +8,6 @@
import React, {
useState,
cloneElement,
Children,
isValidElement,
type ReactElement,
} from 'react';
@ -40,7 +39,7 @@ function TabsComponent(props: Props): JSX.Element {
groupId,
className,
} = props;
const children = Children.map(props.children, (child) => {
const children = React.Children.map(props.children, (child) => {
if (isValidElement(child) && isTabItem(child)) {
return child;
}

View file

@ -11,11 +11,11 @@ import React, {
useEffect,
useRef,
useCallback,
useLayoutEffect,
type RefObject,
type Dispatch,
type SetStateAction,
type ReactNode,
useLayoutEffect,
} from 'react';
const DefaultAnimationEasing = 'ease-in-out';

View file

@ -6,10 +6,10 @@
*/
import React, {
type ComponentProps,
type ReactElement,
useRef,
useState,
type ComponentProps,
type ReactElement,
} from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';
import clsx from 'clsx';

View file

@ -10,9 +10,8 @@ import React, {
useEffect,
useCallback,
useMemo,
type ReactNode,
useContext,
createContext,
type ReactNode,
} from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';
import {createStorageSlot} from './storageUtils';
@ -96,7 +95,9 @@ const useAnnouncementBarContextValue = (): AnnouncementBarAPI => {
);
};
const AnnouncementBarContext = createContext<AnnouncementBarAPI | null>(null);
const AnnouncementBarContext = React.createContext<AnnouncementBarAPI | null>(
null,
);
export function AnnouncementBarProvider({
children,

View file

@ -11,6 +11,7 @@ import React, {
useEffect,
useContext,
useMemo,
useRef,
type ReactNode,
} from 'react';
import {ReactContextError} from './reactUtils';
@ -96,7 +97,7 @@ function useColorModeContextValue(): ColorModeContextValue {
// be reset to dark when exiting print mode, disregarding user settings. When
// the listener fires only because of a print/screen switch, we don't change
// color mode. See https://github.com/facebook/docusaurus/pull/6490
const previousMediaIsPrint = React.useRef(false);
const previousMediaIsPrint = useRef(false);
useEffect(() => {
if (disableSwitch && !respectPrefersColorScheme) {

View file

@ -6,12 +6,11 @@
*/
import React, {
createContext,
type ReactNode,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import {useThemeConfig, type DocsVersionPersistence} from '../useThemeConfig';
import {isDocsPluginEnabled} from '../docsUtils';
@ -131,7 +130,9 @@ function useContextValue() {
type DocsPreferredVersionContextValue = ReturnType<typeof useContextValue>;
const Context = createContext<DocsPreferredVersionContextValue | null>(null);
const Context = React.createContext<DocsPreferredVersionContextValue | null>(
null,
);
export function DocsPreferredVersionContextProvider({
children,

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import React, {createContext, type ReactNode, useContext} from 'react';
import React, {type ReactNode, useContext} from 'react';
import {
useActivePlugin,
useAllDocsData,
@ -29,7 +29,7 @@ export const isDocsPluginEnabled: boolean = !!useAllDocsData;
// Inspired by https://github.com/jamiebuilds/unstated-next/blob/master/src/unstated-next.tsx
const EmptyContextValue: unique symbol = Symbol('EmptyContext');
const DocsVersionContext = createContext<
const DocsVersionContext = React.createContext<
PropVersionMetadata | typeof EmptyContextValue
>(EmptyContextValue);
@ -69,7 +69,7 @@ export function useDocById(id: string | undefined): PropVersionDoc | undefined {
return doc;
}
const DocsSidebarContext = createContext<
const DocsSidebarContext = React.createContext<
PropSidebar | null | typeof EmptyContextValue
>(EmptyContextValue);

View file

@ -7,12 +7,11 @@
import React, {
useState,
type ReactNode,
useContext,
createContext,
useEffect,
type ComponentType,
useMemo,
type ReactNode,
type ComponentType,
} from 'react';
import {ReactContextError} from './reactUtils';
@ -46,7 +45,7 @@ function useContextValue() {
type ContextValue = ReturnType<typeof useContextValue>;
const Context = createContext<ContextValue | null>(null);
const Context = React.createContext<ContextValue | null>(null);
export function MobileSecondaryMenuProvider({
children,

View file

@ -6,14 +6,13 @@
*/
import React, {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
type ReactNode,
} from 'react';
import {useDynamicCallback, ReactContextError} from './reactUtils';
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
@ -57,7 +56,7 @@ function useScrollControllerContextValue(): ScrollController {
);
}
const ScrollMonitorContext = createContext<ScrollController | undefined>(
const ScrollMonitorContext = React.createContext<ScrollController | undefined>(
undefined,
);

View file

@ -9,7 +9,6 @@ import React, {
useState,
useCallback,
useEffect,
createContext,
useMemo,
useContext,
type ReactNode,
@ -24,7 +23,7 @@ type TabGroupChoiceContextValue = {
readonly setTabGroupChoices: (groupId: string, newChoice: string) => void;
};
const TabGroupChoiceContext = createContext<
const TabGroupChoiceContext = React.createContext<
TabGroupChoiceContextValue | undefined
>(undefined);

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {extractThemeCodeMessages} from '../update';
import path from 'path';
import fs from 'fs-extra';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import Joi from '../Joi';
import {JoiFrontMatter} from '../JoiFrontMatter';
import {validateFrontMatter} from '../validationUtils';
@ -21,7 +22,9 @@ describe('validateFrontMatter', () => {
});
test('should reject bad values', () => {
const consoleError = jest.spyOn(console, 'error').mockImplementation();
const consoleError = jest
.spyOn(console, 'error')
.mockImplementation(() => {});
const schema = Joi.object<{test: string}>({
test: Joi.string(),
});

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {genChunkName, readOutputHTMLFile, generate} from '../emitUtils';
import path from 'path';
import fs from 'fs-extra';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {
removeSuffix,
removePrefix,

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import React, {type ReactNode, useContext, createContext} from 'react';
import React, {type ReactNode, useContext} from 'react';
type LinksCollector = {
collectLink: (link: string) => void;
@ -26,7 +26,7 @@ export const createStatefulLinksCollector = (): StatefulLinksCollector => {
};
};
const Context = createContext<LinksCollector>({
const Context = React.createContext<LinksCollector>({
collectLink: () => {
// noop by default for client
// we only use the broken links checker server-side

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import normalizeLocation from '../normalizeLocation';
describe('normalizeLocation', () => {

View file

@ -6,7 +6,7 @@
*/
import React from 'react';
import {hydrate, render} from 'react-dom';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import {HelmetProvider} from 'react-helmet-async';
@ -30,7 +30,8 @@ if (ExecutionEnvironment.canUseDOM) {
// first-load experience.
// For development, there is no existing markup so we had to render it.
// We also preload async component to avoid first-load loading screen.
const renderMethod = process.env.NODE_ENV === 'production' ? hydrate : render;
const renderMethod =
process.env.NODE_ENV === 'production' ? ReactDOM.hydrate : ReactDOM.render;
preload(routes, window.location.pathname).then(() => {
renderMethod(
<HelmetProvider>

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import React, {type ReactNode} from 'react';
import React, {isValidElement, type ReactNode} from 'react';
import type {
InterpolateProps,
InterpolateValues,
@ -49,7 +49,7 @@ export function interpolate<Str extends string, Value extends ReactNode>(
const value = values?.[key];
if (typeof value !== 'undefined') {
const element = React.isValidElement(value)
const element = isValidElement(value)
? value
: // For non-React elements: basic primitive->string conversion
String(value);

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import React from 'react';
import renderer from 'react-test-renderer';
import BrowserOnly from '../BrowserOnly';

View file

@ -5,12 +5,13 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import useBaseUrl, {useBaseUrlUtils} from '../useBaseUrl';
import useDocusaurusContext from '../useDocusaurusContext';
jest.mock('../useDocusaurusContext', () => jest.fn(), {virtual: true});
jest.mock('../useDocusaurusContext');
const mockedContext = <jest.Mock>useDocusaurusContext;
const mockedContext = useDocusaurusContext as jest.Mock;
const forcePrepend = {forcePrependBaseUrl: true};

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import fs from 'fs-extra';
import {ThemePath, createTempSiteDir, Components} from './testUtils';

View file

@ -62,7 +62,7 @@ declare module '@slorber/static-site-generator-webpack-plugin' {
}
declare module 'webpack/lib/HotModuleReplacementPlugin' {
import {HotModuleReplacementPlugin} from 'webpack';
import type {HotModuleReplacementPlugin} from 'webpack';
export default HotModuleReplacementPlugin;
}

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import _ from 'lodash';
import {handleBrokenLinks} from '../brokenLinks';
@ -157,7 +158,7 @@ describe('handleBrokenLinks', () => {
test('no-op for ignore', async () => {
// In any case, _.mapValues will always be called, unless handleBrokenLinks
// has already bailed
const lodashMock = jest.spyOn(_, 'mapValues').mockImplementation();
const lodashMock = jest.spyOn(_, 'mapValues');
await handleBrokenLinks({
allCollectedLinks,
onBrokenLinks: 'ignore',

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {handleDuplicateRoutes} from '../duplicateRoutes';
import type {RouteConfig} from '@docusaurus/types';

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {loadI18n, localizePath, getDefaultLocaleConfig} from '../i18n';
import {DEFAULT_I18N_CONFIG} from '../configValidation';
import path from 'path';
@ -79,7 +80,7 @@ describe('defaultLocaleConfig', () => {
});
describe('loadI18n', () => {
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
beforeEach(() => {
consoleSpy.mockClear();
});

View file

@ -20,6 +20,7 @@ export function sortAliases(aliases: ThemeAliases): ThemeAliases {
const entries = _.sortBy(Object.entries(aliases), ([alias]) => alias);
// @theme/NavbarItem should be after @theme/NavbarItem/LocaleDropdown
entries.sort(([alias1], [alias2]) =>
// eslint-disable-next-line no-nested-ternary
alias1.includes(`${alias2}/`) ? -1 : alias2.includes(`${alias1}/`) ? 1 : 0,
);
return Object.fromEntries(entries);

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import {
ensureTranslationFileContent,
writeTranslationFileContent,
@ -560,7 +561,7 @@ describe('getPluginsDefaultCodeTranslationMessages', () => {
});
describe('applyDefaultCodeTranslations', () => {
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
beforeEach(() => {
consoleSpy.mockClear();
});

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import fs from 'fs-extra';
import tmp from 'tmp-promise';
import {

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {jest} from '@jest/globals';
import path from 'path';
import {

View file

@ -5,7 +5,8 @@
* LICENSE file in the root directory of this source tree.
*/
import {validate} from 'webpack';
import {jest} from '@jest/globals';
import webpack from 'webpack';
import createClientConfig from '../client';
import loadSetup from '../../server/__tests__/testUtils';
@ -15,7 +16,7 @@ describe('webpack dev config', () => {
console.log = jest.fn();
const props = await loadSetup('simple');
const config = await createClientConfig(props);
const errors = validate(config);
const errors = webpack.validate(config);
expect(errors).toBeUndefined();
});
@ -23,7 +24,7 @@ describe('webpack dev config', () => {
console.log = jest.fn();
const props = await loadSetup('custom');
const config = await createClientConfig(props);
const errors = validate(config);
const errors = webpack.validate(config);
expect(errors).toBeUndefined();
});
});

View file

@ -5,7 +5,8 @@
* LICENSE file in the root directory of this source tree.
*/
import {validate} from 'webpack';
import {jest} from '@jest/globals';
import webpack from 'webpack';
import createServerConfig from '../server';
import loadSetup from '../../server/__tests__/testUtils';
@ -15,7 +16,7 @@ describe('webpack production config', () => {
console.log = jest.fn();
const props = await loadSetup('simple');
const config = await createServerConfig({props});
const errors = validate(config);
const errors = webpack.validate(config);
expect(errors).toBeUndefined();
});
@ -23,7 +24,7 @@ describe('webpack production config', () => {
console.log = jest.fn();
const props = await loadSetup('custom');
const config = await createServerConfig({props});
const errors = validate(config);
const errors = webpack.validate(config);
expect(errors).toBeUndefined();
});
});

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {validate, type Configuration, type RuleSetRule} from 'webpack';
import webpack, {type Configuration, type RuleSetRule} from 'webpack';
import path from 'path';
import {
@ -86,7 +86,7 @@ describe('extending generated webpack config', () => {
filename: 'new.bundle.js',
},
});
const errors = validate(config);
const errors = webpack.validate(config);
expect(errors).toBeUndefined();
});
@ -116,7 +116,7 @@ describe('extending generated webpack config', () => {
filename: 'new.bundle.js',
},
});
const errors = validate(config);
const errors = webpack.validate(config);
expect(errors).toBeUndefined();
});

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {Template, type Compiler} from 'webpack';
import webpack, {type Compiler} from 'webpack';
const pluginName = 'chunk-asset-plugin';
@ -48,7 +48,7 @@ export default class ChunkAssetPlugin {
chunkNameToId,
)}[chunkId]||chunkId; return __webpack_require__.p + __webpack_require__.u(chunkId); };`,
);
return Template.asString(buf);
return webpack.Template.asString(buf);
});
});
}

View file

@ -13,7 +13,9 @@ describe('lqip library', () => {
const invalidPath = path.join(__dirname, '__fixtures__', 'docusaurus.svg');
it('should reject unknown or unsupported file format', async () => {
await expect(lqip.base64(invalidPath)).rejects.toBeTruthy();
await expect(lqip.base64(invalidPath)).rejects.toThrow(
/Error: Input file is missing or uses unsupported image format, lqip v.*/,
);
});
it('should generate a valid base64', async () => {

View file

@ -11,13 +11,13 @@ import type {Palette} from 'node-vibrant/lib/color';
import {toPalette, toBase64} from '../utils';
describe('lqip-loader', () => {
describe('toBase64', () => {
test('should return a properly formatted Base64 image string', () => {
const expected = 'data:image/jpeg;base64,aGVsbG8gd29ybGQ=';
const mockedMimeType = 'image/jpeg';
const mockedBase64Data = Buffer.from('hello world');
expect(toBase64(mockedMimeType, mockedBase64Data)).toEqual(expected);
expect(toBase64(mockedMimeType, mockedBase64Data)).toEqual(
'data:image/jpeg;base64,aGVsbG8gd29ybGQ=',
);
});
});
@ -26,7 +26,7 @@ describe('lqip-loader', () => {
let testSwatchWithNull: Palette & {Vibrant?: null} = {};
beforeAll(() => {
const imgPath = path.join(__dirname, '__fixtures__', 'endi.jpg');
const imgPath = path.join(__dirname, '__fixtures__/endi.jpg');
const vibrant = new Vibrant(imgPath, {});
return vibrant.getPalette().then((palette) => {
@ -43,4 +43,3 @@ describe('lqip-loader', () => {
expect(toPalette(testSwatchWithNull)).toHaveLength(5);
});
});
});

View file

@ -5,12 +5,12 @@
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import React, {useRef} from 'react';
import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
export default function LinkTest(): JSX.Element {
const anchorRef = React.useRef<HTMLAnchorElement>(null);
const anchorRef = useRef<HTMLAnchorElement>(null);
return (
<Layout>
<main className="container margin-vert--xl">

View file

@ -102,7 +102,7 @@ import MyComponentSource from '!!raw-loader!@site/src/pages/examples/\_myCompone
```jsx live
function Demo() {
React.useEffect(() => console.log('mount'), []);
useEffect(() => console.log('mount'), []);
return null;
}
```

View file

@ -6,14 +6,12 @@
*/
import React, {
Children,
type ComponentProps,
type ReactElement,
type ReactNode,
isValidElement,
useRef,
useEffect,
forwardRef,
} from 'react';
import {useHistory} from '@docusaurus/router';
import styles from './styles.module.css';
@ -27,19 +25,18 @@ interface Props {
function getText(node: ReactElement): string {
let curNode: ReactNode = node;
while (isValidElement(curNode)) {
[curNode] = Children.toArray(curNode.props.children);
[curNode] = React.Children.toArray(curNode.props.children);
}
return curNode as string;
}
const APITableRow = forwardRef(
(
function APITableRow(
{
name,
children,
}: {name: string | undefined; children: ReactElement<ComponentProps<'tr'>>},
ref: React.ForwardedRef<HTMLTableRowElement>,
) => {
) {
const entryName = getText(children);
const id = name ? `${name}-${entryName}` : entryName;
const anchor = `#${id}`;
@ -60,8 +57,9 @@ const APITableRow = forwardRef(
{children.props.children}
</tr>
);
},
);
}
const APITableRowComp = React.forwardRef(APITableRow);
/*
* Note: this is not a quite robust component since it makes a lot of
@ -69,19 +67,19 @@ const APITableRow = forwardRef(
* should be generally correct in the MDX context.
*/
export default function APITable({children, name}: Props): JSX.Element {
const [thead, tbody] = Children.toArray(
const [thead, tbody] = React.Children.toArray(
children.props.children,
) as ReactElement[];
const highlightedRow = useRef<HTMLTableRowElement>(null);
useEffect(() => {
highlightedRow.current?.focus();
}, [highlightedRow]);
const rows = Children.map(
const rows = React.Children.map(
tbody.props.children,
(row: ReactElement<ComponentProps<'tr'>>) => (
<APITableRow name={name} ref={highlightedRow}>
<APITableRowComp name={name} ref={highlightedRow}>
{row}
</APITableRow>
</APITableRowComp>
),
);

View file

@ -6,12 +6,10 @@
*/
import {TagList, sortedUsers, type User} from '../users';
// eslint-disable-next-line import/no-extraneous-dependencies
import {Joi} from '@docusaurus/utils-validation';
import fs from 'fs-extra';
import path from 'path';
// eslint-disable-next-line import/no-extraneous-dependencies
import imageSize from 'image-size';
declare global {

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import React, {memo} from 'react';
import React from 'react';
import clsx from 'clsx';
import Image from '@theme/IdealImage';
import Link from '@docusaurus/Link';
@ -95,4 +95,4 @@ function ShowcaseCard({user}: {user: User}) {
);
}
export default memo(ShowcaseCard);
export default React.memo(ShowcaseCard);

View file

@ -6,12 +6,12 @@
*/
import React, {
type ComponentProps,
type ReactNode,
type ReactElement,
useCallback,
useState,
useEffect,
type ComponentProps,
type ReactNode,
type ReactElement,
} from 'react';
import {useHistory, useLocation} from '@docusaurus/router';
import {toggleListItem} from '@site/src/utils/jsUtils';