diff --git a/README-ru.md b/README-ru.md index 1665583..0602075 100644 --- a/README-ru.md +++ b/README-ru.md @@ -387,7 +387,7 @@ type MenuItem = { id: string; // uniq id title?: string; // string title icon?: ReactNode; // node of icon - iconSize?: number | string; // icon size in px as number or as string with units + iconSize?: number | string; // deprecated: not applied, set the size on the icon element handler?: (item: ConfigItem) => void; // custom item action handler visible?: (item: ConfigItem) => boolean; // optional visibility handler for filtering menu items className?: string; // custom class property @@ -401,6 +401,13 @@ type MenuItem = { DashKit.setSettings({menu: [] as Array}); ``` +Встроенные пункты — `copy`, `delete` и `settings` (`MenuItems`): + +- строкой `copy` и `delete` получают текст и действие по умолчанию, в том числе рядом с пользовательскими + пунктами в любом порядке; `settings` строкой не показывается, потому что настройки открывает кнопка с шестерёнкой; +- объектом без `title` встроенный пункт получает текст по умолчанию, а без `handler` — и действие по умолчанию; + так показывается и `settings`. + ### Перетаскиваемые элементы из `ActionPanel` #### `DashKitDnDWrapper` diff --git a/README.md b/README.md index 9a5282a..4760fa2 100644 --- a/README.md +++ b/README.md @@ -461,7 +461,7 @@ type MenuItem = { id: string; // uniq id title?: string; // string title icon?: ReactNode; // node of icon - iconSize?: number | string; // icon size in px as number or as string with units + iconSize?: number | string; // deprecated: not applied, set the size on the icon element handler?: (item: ConfigItem) => void; // custom item action handler visible?: (item: ConfigItem) => boolean; // optional visibility handler for filtering menu items className?: string; // custom class property @@ -475,6 +475,13 @@ type MenuItem = { DashKit.setSettings({menu: [] as Array}); ``` +Default items are `copy`, `delete` and `settings` (`MenuItems`): + +- given as a string, `copy` and `delete` keep their default text and action, also next to custom items in any + order; `settings` as a string is not shown, because the gear button opens the settings; +- given as an object without `title`, a default item gets its default text, and without `handler` its default + action; this way `settings` is shown too. + ### Draggable items from ActionPanel #### DashKitDnDWrapper diff --git a/docs/migration-to-v11.md b/docs/migration-to-v11.md index 64ac0af..05df8e2 100644 --- a/docs/migration-to-v11.md +++ b/docs/migration-to-v11.md @@ -12,8 +12,9 @@ and what to do about each change. | `react`, `react-dom` | `^16.8.0 \|\| ^17 \|\| ^18 \|\| ^19` | `^18.0.0 \|\| ^19.0.0` | Upgrade the application to uikit 8 first: see the -[uikit migration guide](https://github.com/gravity-ui/uikit/blob/main/docs/migration-to-v8.md). Two uikit -majors in one bundle are two sets of providers, and DashKit would not see the theme of the application. +[uikit migration guide](https://github.com/gravity-ui/uikit/blob/main/docs/migration-to-v8.md), also installed +as `node_modules/@gravity-ui/uikit/build/docs/guides/migration-to-v8.md`. Two uikit majors in one bundle are two +sets of providers, and DashKit would not see the theme of the application. ## Theme provider @@ -27,10 +28,15 @@ The menu behind the "…" button of a widget is the uikit 8 `Menu` instead of th DashKit did not change: `overlayMenuItems`, `Settings.menu`, and the `title`, `handler`, `visible`, `className` and `qa` of a custom item work as before. +`iconSize` of a menu item is deprecated: the menu never applied it. Set the size on the icon element. `iconSize` +of an `overlayControls` button still works. + What changes is the markup, so check your CSS overrides and tests: - Items are `button.g-menu-item[role="menuitem"]` inside `.g-menu`. The `.g-dropdown-menu__*` classes and the `li > div[role="menuitem"]` structure are gone. +- `role="menu"` is on the popup element around `.g-menu`, not on `.g-menu` itself: find the menu by its role + (`getByRole('menu')`), not with `.g-menu[role="menu"]`. - `qa` of a custom item is the `data-qa` of that button. - `icon` of a custom item is rendered inside `div.g-menu-item__icon`, a 16px box. An `` without `size` and an `` without `width` and `height` get 16px. Items without an icon are indented to line up with the ones that @@ -56,6 +62,11 @@ DashKit texts (the overlay menu, the error of the Text plugin) follow the langua Without `lang` on a `Provider` they follow `configure({lang})`, as before. An application that only calls `configure` needs no change. +The texts now re-render when the language changes, from either source. A DashKit 10 application had to remount +DashKit or pass it a new `context` to see the new language; for the texts of DashKit itself that workaround can be +removed. The texts of the application, such as the titles of its menu items or plugins that take the language from +`context`, stay its own. + ## ActionPanel The default hover background of an item is `--g-color-base-contrast-light-simple-hover`: uikit 8 removed @@ -69,10 +80,40 @@ The default hover background of an item is `--g-color-base-contrast-light-simple - `lodash` is replaced with `es-toolkit`. `es-toolkit`, `tslib` and `@gravity-ui/i18n` are dependencies of DashKit, so nothing has to be installed next to it. - Unit tests are no longer published in the package. +- The types of DashKit compile with `skipLibCheck: false`; DashKit 10 needed `skipLibCheck: true`. They need + `@types/react` 18.2.6 or later (they use `React.JSX`), and with `moduleResolution: node10` also + `esModuleInterop` or `allowSyntheticDefaultImports`, because they default-import `react` and + `react-grid-layout`; `bundler`, `node16` and `nodenext` work as they are. +- `@types/react-grid-layout` is a dependency: the public types import `react-grid-layout`. It accepts any + `@types/react`; if the package manager installs a second copy of `@types/react` for it next to the application's + one, dedupe it (`overrides` in npm, `resolutions` in yarn). - uikit 8 brings two dependencies that ship only ES modules, `colors-named` and `colors-named-hex`, and they load with any import of `@gravity-ui/uikit`. Bundlers are not affected. - - In Jest, a test that imports `@gravity-ui/uikit` or DashKit without mocking uikit fails with "Unexpected token - 'export'". Let Jest transform these two packages to CommonJS: take them out of `transformIgnorePatterns` and - make sure the transformer handles `.js` files of `node_modules` (`babel-jest` does, `ts-jest` does not). - - In Node, the CommonJS build needs `require(esm)` for them (Node 20.19 or 22.12 and later). As before, the main - entry also needs a DOM; `@gravity-ui/dashkit/helpers` does not. + + - In Jest, a test that imports `@gravity-ui/uikit` or DashKit without mocking uikit fails to load them: Jest 29 + reports "SyntaxError: Unexpected token 'export'", Jest 30 "Must use import to load ES Module". Take the two + packages out of `transformIgnorePatterns` and let a transformer that turns ES modules into CommonJS handle + their `.js` files. Keep the rest of the configuration, such as the CSS stub and jsdom. Transformers that do it: + + - `ts-jest` 29.3.2 or later, by itself; 29.3.0 and 29.3.1 only with `"isolatedModules": true`; older versions + leave the files as they are; + - `babel-jest` with `@babel/preset-env` or `@babel/plugin-transform-modules-commonjs` 7.x in a project-wide + `babel.config.js`: a `.babelrc` does not apply to files in `node_modules`; + - a small transformer for these two packages only, which works with any `ts-jest`; `jest/esmTransform.js` in + the DashKit repository is one (it calls `typescript.transpileModule`). + + ```js + // jest.config.js (jest.config.cjs in a package with "type": "module"), with ts-jest 29.3.2 or later + module.exports = { + transform: { + '^.+\\.[jt]sx?$': 'ts-jest', + }, + transformIgnorePatterns: ['/node_modules/(?!(colors-named|colors-named-hex)/)'], + // with pnpm, whose packages live in node_modules/.pnpm: + // transformIgnorePatterns: ['/node_modules/\\.pnpm/(?!(colors-named|colors-named-hex)@)'], + }; + ``` + + - In Node, the CommonJS build needs `require(esm)` for them (Node 20.19 or 22.12 and later). The main entry + also imports CSS and needs a DOM, so it loads only under a bundler or a test runner that stubs CSS; + `@gravity-ui/dashkit/helpers` loads in plain Node. diff --git a/package-lock.json b/package-lock.json index fa8f8a0..fa002c6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "@bem-react/classname": "^1.6.0", "@gravity-ui/i18n": "^1.8.0", + "@types/react-grid-layout": "^1.3.5", "es-toolkit": "^1.53.2", "hashids": "^2.2.8", "immutability-helper": "^3.1.1", @@ -43,7 +44,6 @@ "@types/jest": "^29.5.14", "@types/react": "^19.2.16", "@types/react-dom": "^19.2.3", - "@types/react-grid-layout": "^1.3.5", "@types/react-transition-group": "^4.4.12", "copyfiles": "^2.4.1", "eslint": "^8.57.1", @@ -6421,7 +6421,6 @@ "version": "19.2.16", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.16.tgz", "integrity": "sha512-esJiCAnl0kfpNdE69f3So4WJUXy95dLZydX0KwK46riIHDzHM7O9Vtf9xCHW0PXIqvgqNrswl522kA/5yx+F4w==", - "dev": true, "license": "MIT", "dependencies": { "csstype": "^3.2.2" @@ -6439,7 +6438,6 @@ }, "node_modules/@types/react-grid-layout": { "version": "1.3.5", - "dev": true, "license": "MIT", "dependencies": { "@types/react": "*" diff --git a/package.json b/package.json index 7d1f9ee..a4b2a48 100644 --- a/package.json +++ b/package.json @@ -76,6 +76,7 @@ "dependencies": { "@bem-react/classname": "^1.6.0", "@gravity-ui/i18n": "^1.8.0", + "@types/react-grid-layout": "^1.3.5", "es-toolkit": "^1.53.2", "hashids": "^2.2.8", "immutability-helper": "^3.1.1", @@ -114,7 +115,6 @@ "@types/jest": "^29.5.14", "@types/react": "^19.2.16", "@types/react-dom": "^19.2.3", - "@types/react-grid-layout": "^1.3.5", "@types/react-transition-group": "^4.4.12", "copyfiles": "^2.4.1", "eslint": "^8.57.1", diff --git a/scripts/check-build.mjs b/scripts/check-build.mjs index ec55546..7636812 100644 --- a/scripts/check-build.mjs +++ b/scripts/check-build.mjs @@ -1,31 +1,10 @@ #!/usr/bin/env node // Checks the built package (run `npm run build` first). Adapted from gravity-ui/chartkit#957. -// -// Load: `require` of build/cjs and `import` of build/esm for every entry point of the `exports` -// map, through the package's own name. Node resolves dashkit's files strictly, so a missing -// extension, a directory import or a CommonJS file with ESM syntax fails here. CSS and JSON are -// handled the way bundlers handle them: Node cannot load CSS, and imports JSON only with an import -// attribute (build/esm/i18n and uikit import it without one). `module.registerHooks` hooks run for -// both `import` and `require`, so `require.extensions` is not needed. -// Dependencies are resolved the way bundlers resolve them: an `import` of a package without an -// `exports` map follows its `module` field, and a specifier may omit `.js` or name a directory -// (the uikit 7 ESM build and its dependencies rely on all three). dashkit's own imports get none -// of this, except the packages in OWN_IMPORTS_THROUGH_MODULE_FIELD. Every run prints what needed -// these rules. -// ES modules that the CommonJS build reaches through `require` are printed too: CommonJS -// consumers need require(esm) for them (Node 20.19+ / 22.12+). One of dashkit's own files among -// them is an error. The list is best effort; `node --no-experimental-require-module -// scripts/check-build.mjs` gives the exact answer. -// `./helpers` must load without a DOM. `.` creates a window focus observer at module level, so it -// loads under jsdom globals, after the DOM-free entries. Both builds must export the same names. -// -// Scan: every emitted `.js` for ESM syntax (CommonJS build), extensionless relative specifiers -// (ESM build) and relative imports of missing files; every `.js` and `.d.ts` for bare specifiers -// that are neither dependencies nor peer dependencies. -// -// Misses: render-time failures, styles, bundler-specific behaviour beyond the rules above, and -// type packages that live only in devDependencies (`@types/react-grid-layout`: -// `react-grid-layout` itself is a dependency). +// - Load: every `exports` entry of both builds through the package name; CSS is stubbed, JSON loads +// without import attributes, dependencies resolve as in bundlers, `.` loads under jsdom. +// - Scan: ESM syntax in build/cjs, extensionless imports in build/esm, missing files, undeclared +// packages and `@types`, types spelled out from `@types/react` 19. +// - Types: the `.d.ts` compile with `skipLibCheck: false` under bundler, nodenext and node10. import {existsSync, readFileSync, readdirSync, statSync} from 'node:fs'; import * as nodeModule from 'node:module'; import {dirname, join, relative, resolve, sep} from 'node:path'; @@ -33,6 +12,8 @@ import {exit, stderr, stdout} from 'node:process'; import {fileURLToPath, pathToFileURL} from 'node:url'; import {compileFunction} from 'node:vm'; +import ts from 'typescript'; + const {builtinModules, createRequire, registerHooks} = nodeModule; if (!registerHooks) { @@ -49,15 +30,13 @@ const DECLARED = new Set([ ...Object.keys(pkg.peerDependencies ?? {}), ]); -// Entry points whose modules touch `window` or `document` at load time. +// Entries whose modules touch `window` or `document` at load time. const DOM_ENTRIES = new Set(['.']); -// Packages the `.d.ts` files may name without declaring them: types that consumers get through -// the `@gravity-ui/uikit` peer. Add one only with the reason it is safe. +// Packages the `.d.ts` may name undeclared: types that come with the uikit peer. const TYPES_THROUGH_UIKIT = new Map(); -// dashkit's own imports that may follow the `module` field, as bundlers do. Without a bundler -// they fail for the reason given; the run says when an entry is no longer needed. +// dashkit's own imports allowed to follow the `module` field; the run reports stale entries. const OWN_IMPORTS_THROUGH_MODULE_FIELD = new Map(); for (const format of ['cjs', 'esm']) { @@ -68,8 +47,7 @@ for (const format of ['cjs', 'esm']) { } const require = createRequire(import.meta.url); -// Loaded before the hooks are registered, so that jsdom's own modules do not go through them. -// jsdom comes with jest-environment-jsdom, a devDependency. +// jsdom (from jest-environment-jsdom) loads before the hooks, so its modules skip them. const {JSDOM} = createRequire(require.resolve('jest-environment-jsdom'))('jsdom'); let failed = false; @@ -104,8 +82,7 @@ function isFile(path) { return existsSync(path) && statSync(path).isFile(); } -// A path the way bundlers resolve it: the file, the file with `.js`, or a directory through its -// own `package.json` (`module` before `main`) or its `index.js`. +// Resolve like a bundler: the file, + `.js`, or a directory (`module`, `main`, `index.js`). function resolvePath(path) { if (isFile(path)) { return path; @@ -127,8 +104,7 @@ function resolvePath(path) { return isFile(join(path, 'index.js')) ? join(path, 'index.js') : undefined; } -// The directory and manifest of an installed package without an `exports` map, as seen from -// `parentURL`; packages with `exports` are left to Node. +// Directory and manifest of an installed package without `exports`; the rest is left to Node. function packageWithoutExports(name, parentURL) { try { const manifestPath = createRequire(parentURL).resolve(`${name}/package.json`); @@ -195,9 +171,7 @@ function resolveLikeBundlers(specifier, context, nextResolve) { } } -// The loader passes a `.js` file of a package without `type` on without a format and detects -// ESM syntax only after the hooks. The same test as Node's: it does not compile as CommonJS -// because of ESM syntax. +// Node detects ESM syntax in a `.js` without `type` only after the hooks: test it the same way. const ESM_SYNTAX_ERRORS = [ 'Cannot use import statement outside a module', "Unexpected token 'export'", @@ -253,8 +227,7 @@ function installDom() { pretendToBeVisual: true, url: 'http://localhost/', }); - // Only what Node lacks (`window`, `document`, `self`, `HTMLElement`, `requestAnimationFrame`…): - // Node's own `Event`, `URL`, timers and the rest stay. + // Only what Node lacks; Node's own `Event`, `URL` and timers stay. for (const key of Object.getOwnPropertyNames(window)) { if (!(key in globalThis)) { Object.defineProperty(globalThis, key, {configurable: true, get: () => window[key]}); @@ -263,8 +236,7 @@ function installDom() { return window; } -// The names, with `default` only when the module has a default export: the CommonJS build has -// the key only when TypeScript emitted one, like the ESM build. +// Export names; `default` only when the module has a default export. function exportNames(module) { return Object.keys(module) .filter((key) => key !== '__esModule') @@ -401,8 +373,7 @@ function relativeSpecifiers(code) { return specifiers(code).filter((specifier) => specifier.startsWith('.')); } -// A relative specifier must point to a file that exists (a `.js` one, in a `.d.ts`, to its -// declaration): a failed `.scss` compile leaves a `.css` import without its file. +// A relative import must point to an existing file (to its `.d.ts` in a declaration). function missingFiles(code, file) { const isDeclaration = file.endsWith('.d.ts'); const missing = [...new Set(relativeSpecifiers(code))].filter((specifier) => { @@ -420,6 +391,41 @@ function typesPackage(name) { return `@types/${name.startsWith('@') ? name.slice(1).replace('/', '__') : name}`; } +const DEPENDENCIES = new Set(Object.keys(pkg.dependencies ?? {})); +const typesResolutionCache = new Map(); + +// The `@types` package TypeScript takes the types of `name` from, if any. +function typesFromAtTypes(name, file) { + const format = relative(BUILD, file).split(sep)[0]; + const key = `${format}:${name}`; + if (!typesResolutionCache.has(key)) { + const options = + format === 'cjs' + ? { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + } + : {module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler}; + const resolvedFile = ts.resolveModuleName(name, file, options, ts.sys).resolvedModule + ?.resolvedFileName; + const match = + resolvedFile && /[\\/]node_modules[\\/](@types[\\/][^\\/]+)[\\/]/.exec(resolvedFile); + typesResolutionCache.set(key, match ? match[1].replace('\\', '/') : undefined); + } + return typesResolutionCache.get(key); +} + +// A dependency typed by an `@types` package needs it in dependencies (peers: the consumer's). +function dependenciesWithoutTypes(names, file) { + return names + .filter((name) => DEPENDENCIES.has(name)) + .map((name) => typesFromAtTypes(name, file)) + .filter((name) => name && !DEPENDENCIES.has(name)); +} + +// Types of `@types/react` 19 spelled out in a `.d.ts` break consumers on `@types/react` 18. +const REACT_19_TYPES = /\bbigint\b|\bAwaitedReactNode\b/; + function undeclaredPackages(code, file) { const isDeclaration = file.endsWith('.d.ts'); const names = specifiers(code) @@ -431,8 +437,15 @@ function undeclaredPackages(code, file) { const undeclared = [...new Set([...names, ...referenced])].filter( (name) => !DECLARED.has(name) && !(isDeclaration && TYPES_THROUGH_UIKIT.has(name)), ); - return undeclared.length - ? `not in dependencies or peerDependencies: ${undeclared.join(', ')}` + if (undeclared.length) { + return `not in dependencies or peerDependencies: ${undeclared.join(', ')}`; + } + const missingTypes = isDeclaration ? dependenciesWithoutTypes([...new Set(names)], file) : []; + if (missingTypes.length) { + return `types of a dependency are not in dependencies: ${missingTypes.join(', ')}`; + } + return isDeclaration && REACT_19_TYPES.test(withoutComments(code)) + ? 'a type spelled out from @types/react 19 (bigint, AwaitedReactNode): annotate it' : undefined; } @@ -479,11 +492,66 @@ scanBuild('esm', (code) => { return bad.length ? `relative import without an extension: ${bad.join(', ')}` : undefined; }); +// The `.d.ts` of the entries, compiled as a consumer with `skipLibCheck: false` does. +function checkDeclarations(label, format, options) { + const rootNames = entries.map((entry) => + join(BUILD, format, `${entry === '.' ? 'index' : entry.slice(2)}.d.ts`), + ); + const program = ts.createProgram(rootNames, { + noEmit: true, + strict: true, + skipLibCheck: false, + jsx: ts.JsxEmit.ReactJSX, + lib: ['lib.es2022.d.ts', 'lib.dom.d.ts'], + types: [], + ...options, + }); + const diagnostics = ts.getPreEmitDiagnostics(program); + const own = diagnostics.filter( + // TypeScript paths use `/` on every platform + (diagnostic) => + !diagnostic.file || resolve(diagnostic.file.fileName).startsWith(`${BUILD}${sep}`), + ); + const others = diagnostics.length - own.length; + if (own.length) { + const text = ts.formatDiagnostics(own, { + getCanonicalFileName: (fileName) => fileName, + getCurrentDirectory: () => ROOT, + getNewLine: () => '\n', + }); + fail(`${label}: declarations do not compile with skipLibCheck: false:\n${text}`); + } else { + stdout.write( + `${label}: declarations compile with skipLibCheck: false` + + (others ? ` (${others} error(s) in the types of other packages)\n` : '\n'), + ); + } +} + +checkDeclarations('build/esm, bundler', 'esm', { + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, +}); +checkDeclarations('build/esm, nodenext', 'esm', { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, +}); +checkDeclarations('build/cjs, nodenext', 'cjs', { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, +}); +// node10 reads build/esm through `typesVersions` and needs `esModuleInterop` for default imports. +checkDeclarations('build/esm, node10', 'esm', { + module: ts.ModuleKind.CommonJS, + moduleResolution: ts.ModuleResolutionKind.Node10, + esModuleInterop: true, +}); + domWindow?.close(); if (failed) { exit(1); } stdout.write('Both builds load through the package exports and export the same names.\n'); -// jsdom or a dependency may leave handles open, which would keep the process alive. +// Open handles of jsdom or dependencies would keep the process alive. exit(0); diff --git a/src/components/DashKit/DashKit.tsx b/src/components/DashKit/DashKit.tsx index 031021d..77aa6dd 100644 --- a/src/components/DashKit/DashKit.tsx +++ b/src/components/DashKit/DashKit.tsx @@ -88,8 +88,8 @@ const registerManager = new RegisterManager(); /** * @internal Not part of the public API. Do not use in production code. - * Module-scoped symbol — not accessible to external consumers holding a ref, - * preventing synthetic event injection via instance._emit. + * A symbol instead of a method name, so that a ref to DashKit does not offer `_emit`. It is exported + * for tests and left out of the types, but the package root still exports it at runtime. */ export const _emitSymbol = Symbol('DashKit._emit'); @@ -266,6 +266,12 @@ export class DashKit extends React.PureComponent { return () => this._off(eventName, handler); } + /** + * @internal + * @param eventName the event to emit + * @param event the object passed to its handlers + * @returns nothing + */ [_emitSymbol] = (eventName: T, event: DashKitEventMap[T]): void => { const handlers = this._handlers.get(eventName); if (!handlers) { diff --git a/src/components/GridLayout/GridLayout.tsx b/src/components/GridLayout/GridLayout.tsx index 6221ec9..fd6d288 100644 --- a/src/components/GridLayout/GridLayout.tsx +++ b/src/components/GridLayout/GridLayout.tsx @@ -865,7 +865,8 @@ export default class GridLayout extends React.PureComponent void; visible?: (item: ConfigItem) => boolean; @@ -321,7 +325,12 @@ class OverlayControlsInner extends React.Component { return memo; }, []) : menu.reduce((memo, item: MenuItem) => { + // a default item given by its id next to custom items: as in a menu of ids only if (typeof item === 'string') { + const defaultItem = this.getDropDownMenuItemConfig(item, true); + if (defaultItem) { + memo.push({text: defaultItem.text, onClick: defaultItem.action}); + } return memo; } // custom menu dropdown item filter @@ -341,8 +350,12 @@ class OverlayControlsInner extends React.Component { : this.getDropDownMenuItemConfig(item.id)?.action || (() => {}); memo.push({ - // @ts-expect-error - text: item.title || this.props.t(item.id), + text: + item.title || + // a default item without a title keeps its default text + this.getDropDownMenuItemConfig(item.id)?.text || + // @ts-expect-error the id of a custom item is not a key of the keyset + this.props.t(item.id), icon: item.icon, /** * if the logic of creating the 'onClick' field is changed, it is necessary to update the logic of the method shallowEqualDropdownMenu diff --git a/src/components/OverlayControls/__tests__/OverlayControls.test.tsx b/src/components/OverlayControls/__tests__/OverlayControls.test.tsx index 066a9bc..daa6162 100644 --- a/src/components/OverlayControls/__tests__/OverlayControls.test.tsx +++ b/src/components/OverlayControls/__tests__/OverlayControls.test.tsx @@ -5,7 +5,7 @@ import React from 'react'; import {Provider, configure} from '@gravity-ui/uikit'; import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; -import {DRAGGABLE_CANCEL_CLASS_NAME} from '../../../constants'; +import {DRAGGABLE_CANCEL_CLASS_NAME, MenuItems} from '../../../constants'; import {DashkitOverlayControlsContext} from '../../../context'; import type {OverlayControlsCtxShape} from '../../../context'; import type {ConfigItem} from '../../../shared'; @@ -151,6 +151,64 @@ describe('OverlayControls menu', () => { expect(screen.getByRole('menuitem', {name: 'Inspect'}).children).toHaveLength(0); }); + it('gives default items of a custom menu without a title their default texts', async () => { + renderControls( + createContext({ + menu: [ + {id: MenuItems.Settings}, + {id: 'inspect', title: 'Inspect'}, + {id: MenuItems.Copy}, + {id: MenuItems.Delete}, + ], + }), + undefined, + 'ru', + ); + + await act(async () => { + fireEvent.click(screen.getByRole('button', {name: 'Дополнительные опции'})); + }); + + expect(getMenuItemTexts()).toEqual(['Настройки', 'Inspect', 'Копировать', 'Удалить']); + }); + + it('keeps default items given as strings next to custom items', async () => { + const context = createContext({ + menu: [ + MenuItems.Copy, + {id: 'inspect', title: 'Inspect'}, + MenuItems.Delete, + MenuItems.Settings, + ], + }); + renderControls(context); + await openMenu(); + + // settings as a string is left to the gear button, as in a menu of ids only + expect(getMenuItemTexts()).toEqual(['Copy', 'Inspect', 'Delete']); + + await act(async () => { + fireEvent.click(screen.getByRole('menuitem', {name: 'Delete'})); + }); + + expect(context.removeItem).toHaveBeenCalledWith('item1'); + }); + + it('leaves settings to the gear button in a menu of ids only', async () => { + renderControls(createContext({menu: [MenuItems.Copy, MenuItems.Settings]})); + await openMenu(); + + expect(getMenuItemTexts()).toEqual(['Copy']); + expect(screen.getByRole('button', {name: 'Settings'})).toBeTruthy(); + }); + + it('shows the id of a custom item without a title', async () => { + renderControls(createContext({menu: [{id: 'inspect'}]})); + await openMenu(); + + expect(getMenuItemTexts()).toEqual(['inspect']); + }); + it('gives a default item of a custom menu its default action', async () => { const context = createContext({menu: [{id: 'settings', title: 'Edit'}]}); renderControls(context);