diff --git a/.github/workflows/pkgPrNew.yml b/.github/workflows/pkgPrNew.yml new file mode 100644 index 0000000..dadbbff --- /dev/null +++ b/.github/workflows/pkgPrNew.yml @@ -0,0 +1,61 @@ +name: Publish to pkg.pr.new + +on: + push: + branches: + - master + pull_request: + types: + - opened + - reopened + - synchronize + +permissions: + contents: read + +env: + BUILD_SCRIPT: yarn build + BUILD_SCRIPT_OUTPUT: dist + APP_NAME: table + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + # Делаем checkout текущей ветки + - uses: actions/checkout@master + # Устанавливаем Node.JS для сборки приложения + - uses: actions/setup-node@v1 + with: + node-version: 22 + + - name: Install yarn + id: yarn-setup + run: | + yarn policies set-version 1.22.18 + echo "::set-output name=cache_dir::$(yarn cache dir)" + + - name: Настройка кэширования yarn + uses: actions/cache@v4 + with: + path: ${{ steps.yarn-setup.outputs.cache_dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + + - name: Install dependencies + run: yarn add "install-peers-cli@https://github.com/evless/install-peers-cli#fix-yarn-policies" && yarn --frozen-lockfile + + # Записываем в переменные окружения имя текущей ветки + # Чтобы избежать конфиликтов с URL, меняем точки на _, а слеши на минусы + - name: Get branch name + shell: bash + run: | + echo "BRANCH_NAME=$(echo ${GITHUB_REF#refs/heads/} | sed 's/\//-/g' | sed 's/\./_/g')" >> $GITHUB_ENV + + # Собираем приложение + - name: Build Appliction + run: $BUILD_SCRIPT + # Доставляем собранное приложение на сервер + - name: Publish to pkg.pr.new + run: yarn pkg-pr-new publish './dist' diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 899e18e..818341c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -34,10 +34,12 @@ jobs: restore-keys: | ${{ runner.os }}-yarn- - name: Установка зависимостей - run: yarn add "install-peers-cli@https://github.com/evless/install-peers-cli#fix-yarn-policies" && yarn --frozen-lockfile + run: yarn add "install-peers-cli@https://github.com/evless/install-peers-cli#fix-yarn-policies" && yarn --frozen-lockfile && yarn playwright install chromium - name: Проверка TS - run: yarn run tsc-dry-run + run: yarn run test:ts - name: Unit тесты - run: yarn run unit + run: yarn run test:unit - name: Проверка eslint & stylelint run: yarn run lint + - name: Проверка орфографии + run: yarn test:cspell diff --git a/babel.config.js b/babel.config.js index 4bb0025..532e316 100644 --- a/babel.config.js +++ b/babel.config.js @@ -60,6 +60,64 @@ module.exports = { regenerator: true, }, ], + ...(!isProduction + ? [ + [ + './scripts/babel-plugin-reatom-name/src/index.ts', + { + functionConfig: [ + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'factoryComponent', + argNameIndex: 1, + }, + + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'rangeAtom', + argNameIndex: 2, + }, + + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'forkRef', + argNameIndex: 1, + }, + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'computedSet', + argNameIndex: 1, + }, + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'clickOutsideEffect', + argNameIndex: 1, + }, + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'isTouch', + argNameIndex: 0, + }, + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'onEventEffect', + argNameIndex: 3, + }, + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'keysEffect', + argNameIndex: 1, + }, + { + path: '@consta/uikit/__internal__/src/utils/state', + functionName: 'resizeObservedAtom', + argNameIndex: 2, + }, + ], + }, + ], + ] + : []), ...(isProduction ? [ [ diff --git a/cspell.json b/cspell.json new file mode 100644 index 0000000..db1944d --- /dev/null +++ b/cspell.json @@ -0,0 +1,243 @@ +/* cspell:disable */ +/* cspell:enable */ +/* cspell:disable-next-line */ +{ + "import": ["@cspell/dict-ru_ru/cspell-ext.json"], + "files": ["src/**"], + "language": "en, ru", + "ignorePaths": ["*.svg", "*.json"], + "words": [ + "автодополнения", + "автозаполнения", + "автокомплит", + "Автофокус", + "аудиофайлы", + "бейджей", + "бейджи", + "бейджика", + "Бейджики", + "бейджиков", + "бейджику", + "брейкпоинт", + "брейкпоинтов", + "брейкпоинты", + "брендинга", + "брендового", + "брендовых", + "бэкенд", + "бэкенда", + "бэкенде", + "верхнеуровневая", + "верхнеуровневой", + "видеостен", + "виртуализацию", + "вьюпорт", + "вьюпорта", + "вьюпортом", + "ГГГГ", + "Грейд", + "дженерики", + "дженериков", + "диспатчить", + "дозагружать", + "дроном", + "дропа", + "инпут", + "инпута", + "информер", + "информера", + "информере", + "кастомизацию", + "кастомизируемый", + "кастомная", + "кастомного", + "кастомное", + "кастомной", + "кастомную", + "кастомным", + "кастомными", + "категоризации", + "категоризация", + "клампинг", + "клампинга", + "клампит", + "клампится", + "колбэк", + "колбэка", + "колбэки", + "комбобокс", + "комбобоксе", + "контрибьюторам", + "контрибьюторов", + "контрол", + "контрола", + "контролов", + "контролы", + "лейаут", + "лейаута", + "лейбл", + "лейблам", + "лейблов", + "лейблом", + "лейблу", + "лейблы", + "лемонграсс", + "Мамулик", + "маппинга", + "маппит", + "межбуквенное", + "межбуквенный", + "межбуквенным", + "мемоизируйте", + "микротему", + "микротемы", + "миксинов", + "миксином", + "неактивности", + "неактивность", + "отрендерился", + "отрисовалась", + "отрисовку", + "отрисовывается", + "отрисовывать", + "отрисовываться", + "отрисовываются", + "отсортируется", + "перерендере", + "плейсхолдер", + "плейсхолдера", + "плейсхолдеры", + "подгрузки", + "подгрузку", + "подскролливаем", + "попап", + "попапа", + "поповер", + "поповера", + "преднастроенного", + "преднастроенных", + "предпросмотра", + "пресет", + "пресета", + "пресетах", + "пресете", + "пресетов", + "Приветушки", + "присвоился", + "промисов", + "проскроллили", + "проставятся", + "прочитанности", + "Пупкин", + "радиокнопкам", + "радиокнопках", + "радиокнопке", + "радиокнопкой", + "радиокнопок", + "рассинхронизацию", + "редполитика", + "рендера", + "рендере", + "рендерим", + "рендерит", + "рендерится", + "рендерить", + "рендериться", + "рендером", + "рендерятся", + "ререндер", + "ререндера", + "ресайза", + "ресайзе", + "ресайзер", + "Ресайзеры", + "рефки", + "сайдбар", + "сайдбара", + "сайдбаре", + "сайдбаром", + "свайпами", + "свайпов", + "сейсмик", + "селект", + "селекта", + "селекте", + "скважина", + "скважины", + "скролл", + "скролла", + "скроллбар", + "скроллбара", + "скроллбаров", + "скролле", + "скроллом", + "Скрольте", + "спане", + "спозиционирован", + "стейт", + "стилизуется", + "сonsta", + "таба", + "табам", + "табах", + "табов", + "табом", + "табы", + "тематизации", + "тематизация", + "типографики", + "тулбар", + "тулбаре", + "тулбара", + "тултип", + "тултипа", + "тултипе", + "тултипов", + "тултипом", + "тултипы", + "фуллскрин", + "Халку", + "хелпер", + "ховер", + "ховера", + "ховеру", + "Чаепительный", + "чекбоксам", + "чекбоксах", + "чекбоксов", + "чекбоксом", + "чекбоксу", + "чекбоксы", + "Шаблонирование", + "consta", + "customizer", + "Droppedfile", + "emlx", + "extralight", + "hocs", + "imask", + "indexs", + "lowheader", + "mixs", + "msword", + "nowrap", + "parametrs", + "Paranja", + "prefixs", + "reatom", + "resizer", + "resizers", + "rrggbb", + "rrggbbaa", + "setted", + "splited", + "srgb", + "steparray", + "strs", + "stylelint", + "targz", + "textarray", + "unsort", + "userselect" + ] +} diff --git a/jest.config.js b/jest.config.js deleted file mode 100644 index b689d1f..0000000 --- a/jest.config.js +++ /dev/null @@ -1,22 +0,0 @@ -module.exports = { - verbose: true, - preset: 'ts-jest', - moduleNameMapper: { - '\\.css$': '/__mocks__/styleMock.js', - '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': - '/__mocks__/fileMock.js', - '##/(.*)$': '/src/$1', - }, - transform: { - '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest', - }, - testMatch: ['**/*.test.{ts,tsx}'], - modulePathIgnorePatterns: ['/dist/'], - transformIgnorePatterns: [ - // Транспайлим библиотеки на es-модулях в commonjs-модули - `/node_modules/(?!(@consta)/).+\\.(js|jsx|ts|tsx)`, - ], - collectCoverageFrom: ['**/*.{ts,tsx}', '!**/*.stories.tsx'], - testEnvironment: 'jsdom', - setupFilesAfterEnv: ['./jest.setup.ts'], -}; diff --git a/jest.setup.ts b/jest.setup.ts deleted file mode 100644 index 8fd2002..0000000 --- a/jest.setup.ts +++ /dev/null @@ -1,7 +0,0 @@ -import '@testing-library/jest-dom'; - -global.ResizeObserver = jest.fn().mockImplementation(() => ({ - observe: jest.fn(), - unobserve: jest.fn(), - disconnect: jest.fn(), -})); diff --git a/package.json b/package.json index 830ff65..6c9d37d 100644 --- a/package.json +++ b/package.json @@ -13,10 +13,10 @@ } ], "peerDependencies": { - "@consta/icons": "^1.6.0", - "@consta/uikit": "^5.30.0", - "@reatom/core": "3.10.1", - "@reatom/npm-react": "3.10.6" + "@consta/icons": "^1.7.1", + "@consta/uikit": "https://pkg.pr.new/consta-design-system/uikit/@consta/uikit@55b1010", + "@reatom/core": "^1001.3.0", + "@reatom/react": "https://pkg.pr.new/@reatom/react@8e287d5" }, "files": [ "*", @@ -40,13 +40,14 @@ "pre-push": "yarn run tsc-dry-run", "pre-commit": "yarn run lint-staged", "pre-build": "node scripts/preBuild.js --config=scripts/generateReExportsConfig.js", - "test": "yarn tsc-dry-run && yarn unit", - "unit": "jest", - "unit:watch": "jest --watch", - "unit:clear": "jest --clearCache", + "test:unit": "yarn vitest", + "test:ts": "yarn tsc-dry-run", + "test:cspell": "yarn cspell --no-progress", + "test": "yarn test:ts && yarn test:unit && yarn test:cspell", + "vitest": "vitest run", "build:css": "cross-env NODE_ENV=buildProduction postcss 'src/**/*.css' --base src --dir dist/__internal__/src/", "build:js": "cross-env NODE_ENV=buildProduction BUILDING_JS=true babel --extensions '.ts,.tsx' --config-file ./babel.config.js --source-maps --out-dir dist/__internal__/src/ ./src", - "build:types": "cross-env NODE_ENV=buildProduction tsc --declaration --outDir dist/__internal__/src/ --emitDeclarationOnly -p tsconfig.build.json && node ./scripts/copy.js --src=./tsconfig.json --dest=./dist/__internal__/tsconfig.json && tsconfig-replace-paths -p ./dist/__internal__/tsconfig.json -s ./dist/__internal__ -o ./dist/__internal__ && node ./scripts/rm.js --path=./dist/__internal__/tsconfig.json", + "build:types": "cross-env NODE_ENV=buildProduction tsc --declaration --outDir dist/__internal__ --emitDeclarationOnly -p tsconfig.build.json && node ./scripts/copy.js --src=./tsconfig.json --dest=./dist/__internal__/tsconfig.json && tsconfig-replace-paths -p ./dist/__internal__/tsconfig.json -s ./dist/__internal__ -o ./dist/__internal__ && node ./scripts/rm.js --path=./dist/__internal__/tsconfig.json", "build:package.json": "node scripts/prepare-package-json.js", "build:reexports": "node scripts/generateReExports.js --config=scripts/generateReExportsConfig.js", "build:copy-assets": "node scripts/copyAssets.js", @@ -101,7 +102,8 @@ "@bem-react/classnames": "^1.3.10", "@bem/sdk.naming.cell.match": "^0.1.3", "@bem/sdk.naming.presets": "^0.2.3", - "@consta/stand": "^0.0.155", + "@consta/stand": "https://pkg.pr.new/consta-design-system/stand/@consta/stand@73a81c3", + "@cspell/dict-ru_ru": "^2.2.4", "@mdx-js/loader": "^2.1.5", "@oclif/command": "^1.8.16", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.3", @@ -110,11 +112,13 @@ "@testing-library/react-hooks": "^7.0.2", "@types/jest": "^27.4.1", "@types/node": "^16.7.13", - "@types/react": "^18.3.12", - "@types/react-dom": "^18.3.1", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", "@types/react-transition-group": "^4.4.12", "@typescript-eslint/eslint-plugin": "^5.30.7", "@typescript-eslint/parser": "^5.30.7", + "@vitejs/plugin-react": "^6.1.1", + "@vitest/browser-playwright": "^5.0.0", "autoprefixer": "^10.4.4", "babel-jest": "^27.4.2", "babel-loader": "^8.2.4", @@ -129,6 +133,7 @@ "commitizen": "^4.2.5", "compute-scroll-into-view": "^3.1.1", "cross-env": "^7.0.3", + "cspell": "^8.16.1", "css-loader": "^6.5.1", "css-minimizer-webpack-plugin": "^3.4.1", "cssnano": "^5.1.12", @@ -154,6 +159,8 @@ "jest-environment-jsdom": "^28.1.3", "lint-staged": "^13.0.3", "mini-css-extract-plugin": "^2.6.0", + "pkg-pr-new": "^0.0.88", + "playwright": "^1.59.1", "postcss": "^8.4.31", "postcss-cli": "^10.0.0", "postcss-color-function": "^4.1.0", @@ -168,10 +175,10 @@ "postcss-syntax": "^0.36.2", "prettier": "^3.8.1", "prompts": "^2.4.2", - "react": ">= 16.8.0", + "react": ">= 19.3.1", "react-app-polyfill": "^3.0.0", "react-dev-utils": "^12.0.0", - "react-dom": ">= 16.8.0", + "react-dom": ">= 19.3.1", "react-dropzone": "11.3.4", "react-imask": "^7.2.1", "react-refresh": "^0.11.0", @@ -199,6 +206,8 @@ "typescript": "^5.8.3", "typescript-transform-paths": "^3.3.1", "use-subscription": "^1.5.1", + "vite": "^8.2.2", + "vitest": "^5.0.0", "web-vitals": "^2.1.0", "webpack": "^5.76.0", "webpack-cli": "^4.9.2", @@ -206,5 +215,9 @@ "webpack-manifest-plugin": "^4.0.2", "workbox-webpack-plugin": "^6.4.1" }, + "resolutions": { + "@types/react": "19.3.0", + "csstype": "3.2.3" + }, "homepage": "http://consta.design/libs/table" } diff --git a/scripts/babel-plugin-reatom-name/package.json b/scripts/babel-plugin-reatom-name/package.json new file mode 100644 index 0000000..9b8cea5 --- /dev/null +++ b/scripts/babel-plugin-reatom-name/package.json @@ -0,0 +1,10 @@ +{ + "name": "babel-plugin-reatom-name", + "version": "1.0.0", + "private": true, + "description": "Babel plugin to automatically add/remove names for reatom atoms, actions, computeds, effects and factory components", + "main": "src/index.ts", + "scripts": { + "test": "vitest run" + } +} diff --git a/scripts/babel-plugin-reatom-name/src/__tests__/plugin.unit.ts b/scripts/babel-plugin-reatom-name/src/__tests__/plugin.unit.ts new file mode 100644 index 0000000..818ec6e --- /dev/null +++ b/scripts/babel-plugin-reatom-name/src/__tests__/plugin.unit.ts @@ -0,0 +1,613 @@ +import { describe, it, expect } from 'vitest'; +import babel from '@babel/core'; +import reatomNamePlugin from '../index'; + +const transform = (code: string) => { + const result = babel.transformSync(code, { + plugins: [[reatomNamePlugin]], + presets: [['@babel/preset-typescript']], + filename: 'test.ts', + configFile: false, + babelrc: false, + }); + return result?.code || ''; +}; + +const transformWithConfig = ( + code: string, + functionConfig: Array<{ + path: string; + functionName: string; + argNameIndex: number; + }>, +) => { + const result = babel.transformSync(code, { + plugins: [[reatomNamePlugin, { functionConfig }]], + presets: [['@babel/preset-typescript']], + filename: 'test.ts', + configFile: false, + babelrc: false, + }); + return result?.code || ''; +}; + +describe('babel-plugin-reatom-name', () => { + it('adds name to atom', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const countAtom = atom(0); + `); + expect(result).toContain('countAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to computed', () => { + const result = transform(` + import { computed } from '@reatom/core'; + const itemsAtom = computed(() => propsAtom().items); + `); + expect(result).toContain('itemsAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to action', () => { + const result = transform(` + import { action } from '@reatom/core'; + const onClick = action((e) => {}); + `); + expect(result).toContain('onClick'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to effect', () => { + const result = transform(` + import { effect } from '@reatom/core'; + const myEffect = effect(() => {}); + `); + expect(result).toContain('myEffect'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to reatomBoolean', () => { + const result = transform(` + import { reatomBoolean } from '@reatom/core'; + const openAtom = reatomBoolean(false); + `); + expect(result).toContain('openAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to reatomNumber', () => { + const result = transform(` + import { reatomNumber } from '@reatom/core'; + const countAtom = reatomNumber(0); + `); + expect(result).toContain('countAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to reatomString with non-empty initial value', () => { + const result = transform(` + import { reatomString } from '@reatom/core'; + const nameAtom = reatomString('initial'); + `); + expect(result).toContain('nameAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to reatomArray', () => { + const result = transform(` + import { reatomArray } from '@reatom/core'; + const itemsAtom = reatomArray([]); + `); + expect(result).toContain('itemsAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to reatomEnum', () => { + const result = transform(` + import { reatomEnum } from '@reatom/core'; + const statusAtom = reatomEnum(['idle', 'loading']); + `); + expect(result).toContain('statusAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to reatomRecord', () => { + const result = transform(` + import { reatomRecord } from '@reatom/core'; + const configAtom = reatomRecord({}); + `); + expect(result).toContain('configAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to factoryComponent with custom config', () => { + const result = transformWithConfig( + ` + import { factoryComponent } from '##/utils/state'; + export const SelectPopover = factoryComponent(({ controlElAtom }) => { + return (props) => null; + }); + `, + [ + { + path: '##/utils/state', + functionName: 'factoryComponent', + argNameIndex: 1, + }, + ], + ); + expect(result).toContain('SelectPopover'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to rangeAtom from subpath with custom config', () => { + const result = transformWithConfig( + ` + import { rangeAtom } from '##/utils/state/rangeAtom'; + const itemsAtom = rangeAtom(countAtom); + `, + [ + { + path: '##/utils/state/rangeAtom', + functionName: 'rangeAtom', + argNameIndex: 1, + }, + ], + ); + expect(result).toContain('itemsAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('adds name to rangeAtom with generic type', () => { + const result = transformWithConfig( + ` + import { rangeAtom } from '##/utils/state/rangeAtom'; + const listElementsAtom = rangeAtom(lengthAtom); + `, + [ + { + path: '##/utils/state/rangeAtom', + functionName: 'rangeAtom', + argNameIndex: 1, + }, + ], + ); + expect(result).toContain('listElementsAtom'); + expect(result).toContain('generateAtomName'); + }); + + it('skips if argument already exists at index', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const countAtom = atom(0, 'countAtom'); + `); + // Имя уже было, не должно продублироваться — должен остаться только один 'countAtom' + expect(result).toContain("'countAtom'"); + // Проверяем, что нет дублирования + const matches = result.match(/'countAtom'/g); + expect(matches).toHaveLength(1); + }); + + it('skips if argument at index is a variable', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const name = 'myAtom'; + const countAtom = atom(0, name); + `); + // Если по индексу 1 уже есть аргумент (переменная name) — не добавляем + expect(result).toContain('atom(0, name)'); + // Не должно быть generateAtomName + expect(result).not.toContain('generateAtomName'); + }); + + it('handles wrap(action(...))', () => { + const result = transform(` + import { action, wrap } from '@reatom/core'; + const ref = wrap(action(() => {})); + `); + expect(result).toContain('ref'); + expect(result).toContain('generateAtomName'); + }); + + it('handles action with type assertion', () => { + const result = transform(` + import { action } from '@reatom/core'; + const Enter = action((e) => {}) as unknown as (e: KeyboardEvent) => void; + `); + expect(result).toContain('Enter'); + expect(result).toContain('generateAtomName'); + }); + + it('does not add name to non-reatom functions', () => { + const result = transform(` + import { computed } from 'other-lib'; + const itemsAtom = computed(() => []); + `); + // Имя переменной есть в коде, но оно не должно быть добавлено как аргумент + expect(result).toContain('const itemsAtom = computed(() =>'); + expect(result).not.toContain('generateAtomName'); + }); + + it('does not add name to functions not from @reatom/core', () => { + const result = transform(` + import { isTouch } from '##/utils/state/isTouch'; + const touchAtom = isTouch(); + `); + // Имя переменной есть в коде, но оно не должно быть добавлено как аргумент + expect(result).toContain('const touchAtom = isTouch()'); + expect(result).not.toContain('generateAtomName'); + }); + + it('skips computed with multiple args (dep + fn) because index 1 is occupied', () => { + const result = transform(` + import { computed } from '@reatom/core'; + const valueAtom = computed(depAtom, (ctx) => ctx.get(depAtom)); + `); + // По индексу 1 уже есть колбэк — имя не добавляется + expect(result).not.toContain('generateAtomName'); + }); + + it('skips action with multiple args because index 1 is occupied', () => { + const result = transform(` + import { action } from '@reatom/core'; + const handleClick = action((e, item) => {}, { someOption: true }); + `); + // По индексу 1 уже есть объект опций — имя не добавляется + expect(result).not.toContain('generateAtomName'); + }); + + it('adds import { generateAtomName } from ##/utils/state/generateAtomName when needed', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const countAtom = atom(0); + `); + // babel может использовать двойные или одинарные кавычки + expect(result).toContain('generateAtomName'); + expect(result).toContain('##/utils/state/generateAtomName'); + expect(result).toContain('import'); + }); + + it('does not duplicate generateAtomName import', () => { + const result = transform(` + import { generateAtomName } from '##/utils/state/generateAtomName'; + import { atom } from '@reatom/core'; + const countAtom = atom(0); + `); + // generateAtomName уже импортирован — не должно быть дублирования + const generateAtomNameImports = result.match( + /import\s*\{[^}]*generateAtomName[^}]*\}\s*from\s*['"]##\/utils\/state\/generateAtomName['"]/g, + ); + expect(generateAtomNameImports).toHaveLength(1); + }); + + it('skips atom with argNameIndex 0 because index 0 is occupied', () => { + const result = transformWithConfig( + ` + import { atom } from '@reatom/core'; + const countAtom = atom(0); + `, + [ + { + path: '@reatom/core', + functionName: 'atom', + argNameIndex: 0, + }, + ], + ); + // По индексу 0 уже есть 0 — не добавляем + expect(result).not.toContain('generateAtomName'); + }); + + it('skips if argument at index 0 already exists', () => { + const result = transformWithConfig( + ` + import { atom } from '@reatom/core'; + const countAtom = atom(0); + `, + [ + { + path: '@reatom/core', + functionName: 'atom', + argNameIndex: 0, + }, + ], + ); + // По индексу 0 уже есть 0 — не добавляем + expect(result).not.toContain('generateAtomName'); + }); + + // ============================================================ + // Тесты для вызова функции без присваивания переменной + // ============================================================ + + it('uses function name when no variable declaration (atom)', () => { + const result = transform(` + import { atom } from '@reatom/core'; + atom(0); + `); + // Должно использовать имя функции 'atom' вместо имени переменной + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("atom")'); + }); + + it('uses function name when no variable declaration (action)', () => { + const result = transform(` + import { action } from '@reatom/core'; + action((e) => {}); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("action")'); + }); + + it('uses function name when no variable declaration (computed)', () => { + const result = transform(` + import { computed } from '@reatom/core'; + computed(() => 0); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("computed")'); + }); + + it('uses function name when no variable declaration (effect)', () => { + const result = transform(` + import { effect } from '@reatom/core'; + effect(() => {}); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("effect")'); + }); + + it('uses function name when no variable declaration (reatomBoolean)', () => { + const result = transform(` + import { reatomBoolean } from '@reatom/core'; + reatomBoolean(false); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("reatomBoolean")'); + }); + + it('uses function name when no variable declaration (reatomNumber)', () => { + const result = transform(` + import { reatomNumber } from '@reatom/core'; + reatomNumber(0); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("reatomNumber")'); + }); + + it('uses function name when no variable declaration (reatomString)', () => { + const result = transform(` + import { reatomString } from '@reatom/core'; + reatomString('initial'); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("reatomString")'); + }); + + it('uses function name when no variable declaration (reatomArray)', () => { + const result = transform(` + import { reatomArray } from '@reatom/core'; + reatomArray([]); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("reatomArray")'); + }); + + it('uses function name when no variable declaration (reatomEnum)', () => { + const result = transform(` + import { reatomEnum } from '@reatom/core'; + reatomEnum(['idle', 'loading']); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("reatomEnum")'); + }); + + it('uses function name when no variable declaration (reatomRecord)', () => { + const result = transform(` + import { reatomRecord } from '@reatom/core'; + reatomRecord({}); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("reatomRecord")'); + }); + + it('uses function name with custom config when no variable declaration', () => { + const result = transformWithConfig( + ` + import { factoryComponent } from '##/utils/state'; + factoryComponent(({ controlElAtom }) => { + return (props) => null; + }); + `, + [ + { + path: '##/utils/state', + functionName: 'factoryComponent', + argNameIndex: 1, + }, + ], + ); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("factoryComponent")'); + }); + + it('uses function name with wrap() when no variable declaration', () => { + const result = transform(` + import { action, wrap } from '@reatom/core'; + wrap(action(() => {})); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("action")'); + }); + + it('uses function name with type assertion when no variable declaration', () => { + const result = transform(` + import { action } from '@reatom/core'; + action((e) => {}) as unknown as (e: KeyboardEvent) => void; + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("action")'); + }); + + it('still uses variable name when variable declaration exists', () => { + // Проверяем, что поведение с переменной не сломалось + const result = transform(` + import { atom } from '@reatom/core'; + const countAtom = atom(0); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("countAtom")'); + // Должен быть вызов generateAtomName("countAtom"), а не generateAtomName("atom") + expect(result).not.toContain('generateAtomName("atom")'); + }); + + // ============================================================ + // Тесты для вызова внутри функции (enclosing function name) + // ============================================================ + + it('adds enclosing function name when atom inside arrow function', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const myFn = () => { + const state = atom(0); + }; + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("myFn", "state")'); + }); + + it('adds enclosing function name when atom inside function declaration', () => { + const result = transform(` + import { atom } from '@reatom/core'; + function myFn() { + const state = atom(0); + } + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("myFn", "state")'); + }); + + it('adds enclosing function name when effect inside arrow function', () => { + const result = transform(` + import { effect } from '@reatom/core'; + const loadData = () => { + const dataEffect = effect(() => {}); + }; + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("loadData", "dataEffect")'); + }); + + it('adds enclosing function name when action inside function declaration', () => { + const result = transform(` + import { action } from '@reatom/core'; + function handleSubmit() { + const submitAction = action((e) => {}); + } + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("handleSubmit", "submitAction")'); + }); + + it('adds enclosing function name for nested functions (inner function)', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const outer = () => { + const inner = () => { + const state = atom(0); + }; + }; + `); + // Должно использовать имя ближайшей enclosing функции — 'inner' + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("inner", "state")'); + }); + + it('adds enclosing function name with computed inside arrow function', () => { + const result = transform(` + import { computed } from '@reatom/core'; + const useTheme = () => { + const themeAtom = computed(() => ({})); + }; + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("useTheme", "themeAtom")'); + }); + + it('adds enclosing function name with reatomBoolean inside function', () => { + const result = transform(` + import { reatomBoolean } from '@reatom/core'; + function createFlags() { + const openAtom = reatomBoolean(false); + } + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("createFlags", "openAtom")'); + }); + + it('adds enclosing function name with custom config inside arrow function', () => { + const result = transformWithConfig( + ` + import { rangeAtom } from '##/utils/state/rangeAtom'; + const usePagination = () => { + const pageAtom = rangeAtom(countAtom); + }; + `, + [ + { + path: '##/utils/state/rangeAtom', + functionName: 'rangeAtom', + argNameIndex: 1, + }, + ], + ); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("usePagination", "pageAtom")'); + }); + + it('does not add enclosing function name when atom is at top level (no enclosing function)', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const countAtom = atom(0); + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("countAtom")'); + // Не должно быть двух аргументов + expect(result).not.toContain('generateAtomName("countAtom", "countAtom")'); + }); + + it('adds enclosing function name when atom inside function expression', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const myFn = function() { + const state = atom(0); + }; + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("myFn", "state")'); + }); + + it('adds enclosing function name when atom inside wrap inside function', () => { + const result = transform(` + import { atom, wrap } from '@reatom/core'; + const myFn = () => { + const state = wrap(atom(0)); + }; + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("myFn", "state")'); + }); + + it('adds enclosing function name when atom inside function with type assertion', () => { + const result = transform(` + import { atom } from '@reatom/core'; + const myFn = () => { + const state = atom(0) as unknown as number; + }; + `); + expect(result).toContain('generateAtomName'); + expect(result).toContain('generateAtomName("myFn", "state")'); + }); +}); \ No newline at end of file diff --git a/scripts/babel-plugin-reatom-name/src/index.ts b/scripts/babel-plugin-reatom-name/src/index.ts new file mode 100644 index 0000000..b3b6301 --- /dev/null +++ b/scripts/babel-plugin-reatom-name/src/index.ts @@ -0,0 +1,362 @@ +import type { NodePath, PluginObj, PluginPass } from '@babel/core'; +import type { CallExpression, VariableDeclarator } from '@babel/types'; +import { types as t } from '@babel/core'; + +interface PluginState extends PluginPass { + importCache: Map; + generateAtomNameImported: boolean; +} + +interface FunctionConfig { + /** Путь импорта функции (например, '@reatom/core') */ + path: string; + /** Имя функции (например, 'atom', 'action') */ + functionName: string; + /** + * Индекс аргумента, в который нужно вставить имя. + * - 0 — первый аргумент + * - 1 — второй аргумент + */ + argNameIndex: number; +} + +type PluginOptions = { + functionConfig: FunctionConfig[]; +}; + +// ============================================================ +// Конфиги для функций из @reatom/core +// ============================================================ + +const REATOM_CORE_CONFIGS: FunctionConfig[] = [ + { path: '@reatom/core', functionName: 'atom', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'computed', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'action', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'effect', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'reatomBoolean', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'reatomNumber', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'reatomString', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'reatomArray', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'reatomEnum', argNameIndex: 1 }, + { path: '@reatom/core', functionName: 'reatomRecord', argNameIndex: 1 }, +]; + +/** + * Проверяет, является ли имя функции reatom-функцией (начинается с 'reatom') + */ +function isReatomFunction(name: string): boolean { + return name.startsWith('reatom'); +} + +/** + * Собирает все конфиги: дефолтные для @reatom/core + кастомные из опций. + * Кастомные конфиги перезаписывают дефолтные при совпадении ключа (path:functionName). + */ +function buildFunctionConfigs( + defaultConfigs: FunctionConfig[], + customConfigs: FunctionConfig[], +): FunctionConfig[] { + const configMap = new Map(); + + for (const cfg of defaultConfigs) { + configMap.set(`${cfg.path}:${cfg.functionName}`, cfg); + } + + for (const cfg of customConfigs) { + configMap.set(`${cfg.path}:${cfg.functionName}`, cfg); + } + + return Array.from(configMap.values()); +} + +/** + * Находит конфиг для функции по её имени и источнику импорта. + * Для reatom* функций из @reatom/core создаёт конфиг на лету, если его нет в списке. + */ +function findConfig( + functionConfigs: FunctionConfig[], + functionName: string, + importSource: string, +): FunctionConfig | null { + // Ищем точное совпадение + const exact = functionConfigs.find( + (cfg) => importSource.includes(cfg.path) && cfg.functionName === functionName, + ); + if (exact) return exact; + + + return null; +} + +/** + * Получает имя переменной, в которую присваивается вызов. + * Обрабатывает: + * - const X = fn(...) → 'X' + * - const X = wrap(fn(...)) → 'X' + * - const X = fn(...) as Type → 'X' + * - export const X = fn(...) → 'X' + */ +function getVariableName(path: NodePath): string | null { + const declarator = path.findParent( + (p) => p.isVariableDeclarator(), + ) as NodePath | null; + + if (!declarator) return null; + + const id = declarator.node.id; + if (t.isIdentifier(id)) { + return id.name; + } + return null; +} + +/** + * Получает имя родительской функции (стрелочной или обычной), внутри которой находится вызов. + * Обрабатывает: + * - const myFn = () => { atom(...) } → 'myFn' + * - const myFn = function() { atom(...) } → 'myFn' + * - function myFn() { atom(...) } → 'myFn' + * - export default () => { atom(...) } → null (нет имени) + */ +function getEnclosingFunctionName(path: NodePath): string | null { + let current: NodePath | null = path; + + while (current) { + // Ищем FunctionDeclaration или FunctionExpression со стрелочной функцией + if (current.isArrowFunctionExpression() || current.isFunctionExpression()) { + const parent = current.parentPath; + if (parent) { + // const myFn = () => { ... } + if (parent.isVariableDeclarator() && t.isIdentifier(parent.node.id)) { + return parent.node.id.name; + } + // const myFn = function() { ... } + // obj = { myFn: function() { ... } } + if (parent.isAssignmentExpression()) { + if (t.isIdentifier(parent.node.left)) { + return parent.node.left.name; + } + // obj.myFn = function() { ... } + if (t.isMemberExpression(parent.node.left) && t.isIdentifier(parent.node.left.property)) { + return parent.node.left.property.name; + } + } + } + } + + // function myFn() { ... } + if (current.isFunctionDeclaration()) { + const id = current.node.id; + if (id && t.isIdentifier(id)) { + return id.name; + } + } + + // export default () => { ... } — нет имени + if (current.isExportDefaultDeclaration()) { + return null; + } + + // Поднимаемся выше + current = current.parentPath; + } + + return null; +} + +/** + * Распаковывает CallExpression из обёрток: + * - wrap(fn(...)) → fn(...) + * - fn(...) as Type → fn(...) + * + * Возвращает распакованный CallExpression и имя функции. + */ +function unwrapCallExpression( + path: NodePath, +): { calleeName: string | null; callPath: NodePath } | null { + let current: NodePath = path; + + // Если мы внутри wrap(...), берём первый аргумент + if ( + current.isCallExpression() && + t.isIdentifier(current.node.callee) && + (current.node.callee as any).name === 'wrap' + ) { + const arg = (current.node as CallExpression).arguments[0]; + if (!arg || !t.isCallExpression(arg)) return null; + const argPath = current.get('arguments')[0]; + if (!argPath || !argPath.isCallExpression()) return null; + current = argPath; + } + + // Если мы внутри TSAsExpression (as Type), берём expression + if (current.parentPath && current.parentPath.isTSAsExpression()) { + current = current.parentPath.get('expression') as NodePath; + } + + if (!current.isCallExpression()) return null; + + const callee = current.node.callee; + let calleeName: string | null = null; + + if (t.isIdentifier(callee)) { + calleeName = callee.name; + } + + return { calleeName, callPath: current as NodePath }; +} + +/** + * Проверяет, что по указанному индексу уже есть какой-либо аргумент. + * Если аргумент есть (любой) — считаем, что имя уже указано и пропускаем. + */ +function hasArgumentAtIndex( + callPath: NodePath, + index: number, +): boolean { + const args = callPath.node.arguments; + if (index < 0 || index >= args.length) return false; + return true; +} + +/** + * Добавляет импорт { generateAtomName } из '##/utils/state/generateAtomName', если его ещё нет. + */ +function ensureGenerateAtomNameImport(path: NodePath, state: PluginState): void { + if (state.generateAtomNameImported) return; + state.generateAtomNameImported = true; + + const program = path.findParent((p) => p.isProgram()); + if (!program) return; + + const importStmt = t.importDeclaration( + [ + t.importSpecifier( + t.identifier('generateAtomName'), + t.identifier('generateAtomName'), + ), + ], + t.stringLiteral('##/utils/state/generateAtomName'), + ); + + // Вставляем после последнего импорта + let insertAfter: NodePath | null = null; + program.traverse({ + ImportDeclaration(importPath) { + insertAfter = importPath; + }, + }); + + if (insertAfter) { + (insertAfter as NodePath).insertAfter(importStmt); + } else { + const body = program.get('body'); + if (Array.isArray(body) && body.length > 0) { + body[0].insertBefore(importStmt); + } + } +} + +export default function (): PluginObj { + return { + name: 'babel-plugin-reatom-name', + + pre() { + this.importCache = new Map(); + this.generateAtomNameImported = false; + + // Инициализируем конфиги сразу в pre(), чтобы они были доступны + // до обхода ImportDeclaration + const pluginOptions = this.opts as PluginOptions; + const customConfigs = pluginOptions.functionConfig || []; + (this as any).functionConfigs = buildFunctionConfigs( + REATOM_CORE_CONFIGS, + customConfigs, + ); + }, + + visitor: { + + ImportDeclaration(path, state) { + const pluginState = state as PluginState; + const node = path.node; + const source = node.source.value; + + for (const specifier of node.specifiers) { + if (t.isImportSpecifier(specifier)) { + const importedName = specifier.local.name; + pluginState.importCache.set(importedName, source); + + // Если уже импортирован generateAtomName из '##/utils/state/generateAtomName' — запоминаем + if ( + importedName === 'generateAtomName' && + source === '##/utils/state/generateAtomName' + ) { + pluginState.generateAtomNameImported = true; + } + } + } + }, + + CallExpression(path, state) { + const pluginState = state as PluginState; + + // Распаковываем вызов из wrap / as + const unwrapped = unwrapCallExpression(path); + if (!unwrapped || !unwrapped.calleeName) return; + + const { calleeName, callPath } = unwrapped; + + // Проверяем, что функция импортирована из нужного источника + const importSource = pluginState.importCache.get(calleeName); + if (!importSource) return; + + // Ищем конфиг для этой функции + const config = findConfig( + (pluginState as any).functionConfigs, + calleeName, + importSource, + ); + if (!config) return; + + // Если по индексу уже есть аргумент (любой) — пропускаем + if (hasArgumentAtIndex(callPath, config.argNameIndex)) return; + + // Получаем имя переменной (const X = fn(...)) или имя функции (fn(...)) + const varName = getVariableName(path); + const name = varName || calleeName; + + // Получаем имя родительской функции, если вызов внутри неё + const enclosingFnName = getEnclosingFunctionName(path); + + // Добавляем импорт generateAtomName, если ещё не добавили + ensureGenerateAtomNameImport(path, pluginState); + + // Формируем name-аргумент: + // - Если есть enclosingFnName: generateAtomName('myFn', 'state') + // - Если нет: generateAtomName('countAtom') + const nameArgs: t.StringLiteral[] = []; + if (enclosingFnName) { + nameArgs.push(t.stringLiteral(enclosingFnName)); + } + nameArgs.push(t.stringLiteral(name)); + + const nameArg = t.callExpression( + t.identifier('generateAtomName'), + nameArgs, + ); + + const args = callPath.node.arguments; + + // Вставляем на нужную позицию + if (config.argNameIndex >= args.length) { + // Если аргументов меньше индекса — просто добавляем в конец + args.push(nameArg); + } else { + // Вставляем на нужную позицию + args.splice(config.argNameIndex, 0, nameArg); + } + }, + }, + }; +} \ No newline at end of file diff --git a/scripts/babel-plugin-reatom-name/src/vite-plugin.ts b/scripts/babel-plugin-reatom-name/src/vite-plugin.ts new file mode 100644 index 0000000..f94c3e0 --- /dev/null +++ b/scripts/babel-plugin-reatom-name/src/vite-plugin.ts @@ -0,0 +1,70 @@ +import { transformSync } from '@babel/core'; +import type { Plugin } from 'vitest/config'; + +import reatomNamePlugin from './index'; + +export interface FunctionConfig { + /** Путь импорта функции (например, '@reatom/core') */ + path: string; + /** Имя функции (например, 'atom', 'action') */ + functionName: string; + /** + * Индекс аргумента, в который нужно вставить имя. + * - 0 — первый аргумент + * - 1 — второй аргумент + */ + argNameIndex: number; +} + +export type VitePluginReatomNameOptions = { + include?: RegExp[]; + exclude?: RegExp[]; + /** Кастомные конфиги для функций (перезаписывают дефолтные для @reatom/core) */ + functionConfig?: FunctionConfig[]; +}; + +export function vitePluginReatomName( + options: VitePluginReatomNameOptions = {}, +): Plugin { + const include = options.include ?? [/\/src\//]; + const exclude = options.exclude ?? [/node_modules/, /\.css$/]; + const functionConfig = options.functionConfig; + + return { + name: 'vite-plugin-reatom-name', + enforce: 'pre', + + transform(code: string, id: string) { + // Проверяем, нужно ли обрабатывать файл + const shouldInclude = include.some((pattern) => pattern.test(id)); + const shouldExclude = exclude.some((pattern) => pattern.test(id)); + + if (!shouldInclude || shouldExclude) { + return null; + } + + // Формируем опции для babel-плагина + const pluginOptions = functionConfig + ? { functionConfig } + : undefined; + + // Применяем babel с плагином reatom-name + const result = transformSync(code, { + plugins: [[reatomNamePlugin, pluginOptions].filter(Boolean)], + presets: [['@babel/preset-typescript']], + filename: id, + configFile: false, + babelrc: false, + }); + + if (result?.code) { + return { + code: result.code, + map: null, + }; + } + + return null; + }, + }; +} \ No newline at end of file diff --git a/scripts/babel-plugin-reatom-name/vitest.config.ts b/scripts/babel-plugin-reatom-name/vitest.config.ts new file mode 100644 index 0000000..760c4ea --- /dev/null +++ b/scripts/babel-plugin-reatom-name/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['**/*.unit.{ts,js,tsx}'], + environment: 'node', + }, + resolve: { + alias: { + '##': '/src', + }, + }, +}); \ No newline at end of file diff --git a/src/components/Collapse/Collapse.tsx b/src/components/Collapse/Collapse.tsx index 9123a00..b951760 100644 --- a/src/components/Collapse/Collapse.tsx +++ b/src/components/Collapse/Collapse.tsx @@ -1,13 +1,15 @@ import './Collapse.css'; -import { withCtx } from '@consta/uikit/__internal__/src/utils/state/withCtx'; +import { + computedSet, + factoryComponent, +} from '@consta/uikit/__internal__/src/utils/state'; import { isString } from '@consta/uikit/__internal__/src/utils/type-guards'; import { animateTimeout } from '@consta/uikit/MixPopoverAnimate'; import { Text } from '@consta/uikit/Text'; -import { useMutableRef } from '@consta/uikit/useMutableRef'; -import { useAction, useAtom, useUpdate } from '@reatom/npm-react'; -import React, { forwardRef, useRef } from 'react'; -import { Transition } from 'react-transition-group'; +import { Transition } from '@consta/uikit/Transition'; +import { action, atom, reatomBoolean, wrap } from '@reatom/core'; +import React from 'react'; import { Toolbar } from '##/components/Toolbar'; import { cn } from '##/utils/bem'; @@ -19,7 +21,7 @@ import { CollapseFullscreenIcon } from './CollapseFullscreenIcon'; const cnCollapse = cn('Collapse'); -export type CollapseProps = JSX.IntrinsicElements['div'] & { +export type CollapseProps = React.JSX.IntrinsicElements['div'] & { expandButton?: boolean; expanded?: boolean; expandedMaxHeight?: number | 'auto'; @@ -32,14 +34,14 @@ export type CollapseProps = JSX.IntrinsicElements['div'] & { ) => void; leftSide: React.ReactNode; rightSide?: React.ReactNode; - fullscreenContainer?: Element | React.RefObject; + fullscreenContainer?: Element | React.RefObject; fullscreenZIndex?: number; }; /** * Props for the Collapse component. * - * @extends JSX.IntrinsicElements['div'] + * @extends React.JSX.IntrinsicElements['div'] * @property {boolean} [expandButton] - показывает кнопку раскрытия.. * @property {boolean} [expanded=false] - указывает, раскрыт ли компонент. * @property {number | 'auto'} [expandedMaxHeight='auto'] - максимальная высота при раскрытии.. @@ -49,20 +51,48 @@ export type CollapseProps = JSX.IntrinsicElements['div'] & { * @property {(value: boolean, e: React.MouseEvent) => void} [onFullscreen] - обработчик изменения полноэкранного режима. * @property {React.ReactNode} leftSide - контент для отображения на левой стороне. * @property {React.ReactNode} [rightSide] - контент для отображения на правой стороне. - * @property {Element | React.RefObject} [fullscreenContainer=`window.document.body`] - контейнер для полноэкранного режима. + * @property {Element | React.RefObject} [fullscreenContainer=`window.document.body`] - контейнер для полноэкранного режима. * @property {number} [fullscreenZIndex=1000] - уровень z-index для полноэкранного режима. * @property {string} [className] - дополнительный класс. * @property {React.ReactNode} children - контент для отображения внутри компонента. */ -export const Collapse = withCtx( - forwardRef((props, ref) => { - const { +export const Collapse = factoryComponent( + ({ expanded }, propsAtom) => { + const contentElementAtom = atom(null); + + const expandedAtom = computedSet(() => !!propsAtom().expanded); + const fullscreenAtom = computedSet(() => !!propsAtom().fullscreen); + const fakeContentHeightAtom = atom(undefined); + const expandedContentMountedAtom = reatomBoolean(expanded); + + const toggleExpanded = action((e: React.MouseEvent) => { + const value = !expandedAtom(); + propsAtom().onExpand?.(value, e); + expandedAtom.set(value); + if (value) { + expandedContentMountedAtom.setTrue(); + } + }); + + const toggleFullscreen = action( + (e: React.MouseEvent) => { + const value = !fullscreenAtom(); + propsAtom().onFullscreen?.(value, e); + fullscreenAtom.set(value); + + fakeContentHeightAtom.set( + value ? contentElementAtom()?.clientHeight : undefined, + ); + }, + ); + + return ({ expandButton, - expanded: expandedProp = false, + expanded: expandedProp, onExpand, fullscreenButton, - fullscreen: fullscreenProp = false, + fullscreen: fullscreenProp, onFullscreen, leftSide, rightSide, @@ -71,125 +101,94 @@ export const Collapse = withCtx( fullscreenContainer = window.document.body, fullscreenZIndex = 1000, expandedMaxHeight = 'auto', + ref, ...otherProps - } = props; - - const refs = useMutableRef([onExpand, onFullscreen]); - - const contentRef = useRef(null); - - const [expanded, , expandedAtom] = useAtom(expandedProp); - const [fullscreen, , fullscreenAtom] = useAtom(fullscreenProp); - const [fakeContentHeight, setFakeContentHeight] = useAtom< - number | undefined - >(undefined); - const [expandedContentMounted, , expandedContentMountedAtom] = - useAtom(expanded); - - const toggleExpanded = useAction( - (ctx, e: React.MouseEvent) => { - const value = !ctx.get(expandedAtom); - refs.current[0]?.(value, e); - expandedAtom(ctx, value); - if (value) { - expandedContentMountedAtom(ctx, true); - } - }, - ); - - const toggleFullscreen = useAction( - (ctx, e: React.MouseEvent) => { - const value = !ctx.get(fullscreenAtom); - refs.current[1]?.(value, e); - fullscreenAtom(ctx, value); - - setFakeContentHeight( - value ? contentRef.current?.clientHeight : undefined, - ); - }, - ); - - const afterExitExpanded = useAction((ctx) => { - expandedContentMountedAtom(ctx, false); - }); - - const title = isString(leftSide) ? ( - - {leftSide} - - ) : ( - leftSide - ); - - useUpdate(expandedAtom, [expandedProp]); - useUpdate(fullscreenAtom, [fullscreenProp]); - - return ( - <> -
- - ) : null, - ...(Array.isArray(title) ? title : [title]), - ]} - rightSide={[ - ...(Array.isArray(rightSide) ? rightSide : [rightSide]), - fullscreenButton ? ( - - ) : null, - ]} - /> - {children && ( -
- { + const expanded = expandedAtom(); + const expandedContentMounted = expandedContentMountedAtom(); + const fullscreen = fullscreenAtom(); + const fakeContentHeight = fakeContentHeightAtom(); + + const title = isString(leftSide) ? ( + + {leftSide} + + ) : ( + leftSide + ); + + return ( + <> +
+ + ) : null, + ...(Array.isArray(title) ? title : [title]), + ]} + rightSide={[ + ...(Array.isArray(rightSide) ? rightSide : [rightSide]), + fullscreenButton ? ( + + ) : null, + ]} + /> + {children && ( +
-
- {children} -
- -
+ {() => ( +
{ + contentElementAtom.set(el); + })} + style={{ maxHeight: expandedMaxHeight }} + > + {children} +
+ )} + +
+ )} +
+ {children && ( + + {children} + )} -
- {children && ( - - {children} - - )} - - ); - }), + + ); + }; + }, ); diff --git a/src/components/Collapse/CollapseButton/CollapseButton.tsx b/src/components/Collapse/CollapseButton/CollapseButton.tsx index 7cd5c55..d7a2451 100644 --- a/src/components/Collapse/CollapseButton/CollapseButton.tsx +++ b/src/components/Collapse/CollapseButton/CollapseButton.tsx @@ -7,10 +7,11 @@ export const CollapseButton: React.FC<{ icon?: IconComponent; active?: boolean; onClick?: React.MouseEventHandler; -}> = ({ icon, active, onClick }) => ( + className?: string; +}> = ({ icon, active, ...otherProps }) => (