From 97ad52532a9e89befb9cd0e2fac15c93cda286dd Mon Sep 17 00:00:00 2001 From: capyq <60133108+capyq@users.noreply.github.com> Date: Mon, 5 Aug 2024 16:34:37 +0200 Subject: [PATCH] update printWidth to 120 (#533) --- .eslintrc.json | 52 ++-- .prettierrc.json | 1 + babel.config.json | 4 +- demo/data/EquipmentSearchBar.js | 8 +- demo/data/ReportViewer.js | 9 +- demo/src/FlatParametersTab.jsx | 4 +- demo/src/InputsTab.jsx | 42 +-- demo/src/TableTab.jsx | 63 +---- demo/src/TreeViewFinderConfig.jsx | 64 +---- demo/src/app.jsx | 145 +++------- demo/src/equipment-search.tsx | 25 +- demo/src/inline-search.tsx | 17 +- demo/src/right-resizable-box.jsx | 9 +- jest.config.ts | 4 +- license-checker-config.json | 5 +- src/_mocks_/svg.tsx | 4 +- .../AuthenticationRouter.tsx | 67 +---- .../CardErrorBoundary/card-error-boundary.tsx | 24 +- .../CustomAGGrid/custom-aggrid.style.ts | 3 +- src/components/CustomAGGrid/custom-aggrid.tsx | 96 +++---- .../directory-item-selector.tsx | 103 ++----- .../element-search-dialog.tsx | 21 +- .../element-search-input.tsx | 33 +-- .../ElementSearchDialog/equipment-item.tsx | 19 +- .../ElementSearchDialog/tag-renderer.tsx | 15 +- .../use-element-search.tsx | 5 +- .../ExpandableGroup/expandable-group.tsx | 12 +- .../FlatParameters/FlatParameters.tsx | 110 ++------ src/components/Login/Login.tsx | 32 +-- src/components/Login/Logout.tsx | 29 +- .../MuiVirtualizedTable/ColumnHeader.tsx | 122 +++----- .../KeyedColumnsRowIndexer.tsx | 108 ++----- .../MuiVirtualizedTable.tsx | 264 ++++-------------- src/components/MuiVirtualizedTable/index.ts | 5 +- .../MultipleSelectionDialog.tsx | 23 +- .../OverflowableText/overflowable-text.tsx | 28 +- src/components/ReportViewer/filter-button.tsx | 13 +- .../ReportViewer/log-report-item.ts | 31 +- src/components/ReportViewer/log-report.ts | 20 +- src/components/ReportViewer/log-table.tsx | 34 +-- .../ReportViewer/multi-select-list.tsx | 24 +- src/components/ReportViewer/report-item.tsx | 31 +- src/components/ReportViewer/report-viewer.tsx | 31 +- .../report-viewer-dialog.tsx | 23 +- .../SignInCallbackHandler.tsx | 5 +- .../SilentRenewCallbackHandler.tsx | 5 +- .../SnackbarProvider/SnackbarProvider.tsx | 11 +- src/components/TopBar/AboutDialog.tsx | 166 +++-------- src/components/TopBar/GridLogo.tsx | 32 +-- src/components/TopBar/TopBar.tsx | 146 ++-------- .../TreeViewFinder/TreeViewFinder.tsx | 154 +++------- src/components/TreeViewFinder/index.ts | 10 +- src/components/dialogs/custom-mui-dialog.tsx | 25 +- .../description-modification-dialog.tsx | 12 +- .../dialogs/modify-element-selection.tsx | 6 +- .../dialogs/popup-confirmation-dialog.tsx | 9 +- .../criteria-based-filter-edition-dialog.tsx | 40 +-- .../criteria-based-filter-form.tsx | 15 +- .../criteria-based-filter-utils.ts | 82 ++---- .../criteria-based/criteria-based-form.tsx | 35 +-- .../criteria-based/filter-free-properties.tsx | 16 +- .../criteria-based/filter-properties.tsx | 123 +++----- .../filter/criteria-based/filter-property.tsx | 8 +- .../filter/expert/expert-filter-constants.ts | 14 +- .../expert/expert-filter-edition-dialog.tsx | 23 +- .../filter/expert/expert-filter-form.tsx | 13 +- .../filter/expert/expert-filter-utils.ts | 144 +++------- .../filter/expert/styles-expert-filter.css | 26 +- .../explicit-naming-filter-edition-dialog.tsx | 31 +- .../explicit-naming-filter-form.tsx | 80 ++---- .../filter/filter-creation-dialog.tsx | 55 +--- src/components/filter/filter-form.tsx | 20 +- src/components/filter/utils/filter-api.ts | 11 +- .../react-hook-form/ExpandingTextField.tsx | 18 +- .../ag-grid-table/bottom-right-buttons.tsx | 28 +- .../cell-editors/numericEditor.ts | 9 +- .../csv-uploader/csv-uploader.tsx | 64 +---- .../ag-grid-table/custom-ag-grid-table.tsx | 51 +--- .../autocomplete-input.tsx | 40 +-- .../multiple-autocomplete-input.tsx | 8 +- .../booleans/boolean-input.tsx | 11 +- .../booleans/checkbox-input.tsx | 9 +- .../react-hook-form/booleans/switch-input.tsx | 9 +- .../react-hook-form/directory-items-input.tsx | 58 +--- .../error-management/error-input.tsx | 6 +- .../react-hook-form/numbers/integer-input.tsx | 5 +- .../provider/custom-form-provider.tsx | 11 +- .../provider/use-custom-form-context.ts | 5 +- .../inputs/react-hook-form/radio-input.tsx | 17 +- .../inputs/react-hook-form/range-input.tsx | 34 +-- .../select-inputs/countries-input.tsx | 7 +- .../select-inputs/mui-select-input.tsx | 11 +- .../select-inputs/select-input.tsx | 18 +- .../inputs/react-hook-form/slider-input.tsx | 20 +- .../inputs/react-hook-form/text-input.tsx | 37 +-- .../react-hook-form/unique-name-input.tsx | 22 +- .../react-hook-form/utils/field-label.tsx | 6 +- .../react-hook-form/utils/functions.tsx | 22 +- .../react-hook-form/utils/submit-button.tsx | 5 +- .../utils/text-field-with-adornment.tsx | 82 ++---- .../inputs/react-query-builder/add-button.tsx | 10 +- .../group-value-editor.tsx | 19 +- .../rule-value-editor.tsx | 25 +- .../custom-react-query-builder.tsx | 28 +- .../element-value-editor.tsx | 11 +- .../property-value-editor.tsx | 30 +- .../react-query-builder/remove-button.tsx | 15 +- .../translated-value-editor.tsx | 8 +- .../react-query-builder/use-convert-value.ts | 17 +- .../react-query-builder/value-editor.tsx | 49 +--- src/components/inputs/select-clearable.tsx | 10 +- .../translations/card-error-boundary-en.ts | 6 +- src/components/translations/filter-en.ts | 9 +- .../translations/filter-expert-en.ts | 9 +- .../translations/filter-expert-fr.ts | 6 +- src/components/translations/filter-fr.ts | 9 +- src/components/translations/login-en.ts | 9 +- src/components/translations/login-fr.ts | 9 +- src/hooks/localized-countries-hook.ts | 31 +- src/hooks/predefined-properties-hook.ts | 10 +- src/hooks/useDebounce.ts | 10 +- src/hooks/useSnackMessage.ts | 34 +-- src/index.ts | 53 +--- src/redux/authActions.ts | 32 +-- src/services/apps-metadata.ts | 4 +- src/services/directory.ts | 31 +- src/services/explore.ts | 24 +- src/services/study.ts | 6 +- src/services/utils.ts | 34 +-- src/utils/AuthService.ts | 88 ++---- src/utils/ElementType.ts | 6 +- src/utils/EquipmentType.ts | 8 +- src/utils/UserManagerMock.ts | 32 +-- src/utils/conversion-utils.ts | 12 +- ...-types-for-predefined-properties-mapper.ts | 4 +- src/utils/functions.ts | 3 +- src/utils/styles.ts | 22 +- vite.config.mts | 26 +- 138 files changed, 1049 insertions(+), 3412 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 847a599f..0e71c6a9 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,28 +1,28 @@ { - "root": true, - "extends": [ - "airbnb", - "airbnb-typescript", - "airbnb/hooks", - "plugin:prettier/recommended", - "plugin:react/jsx-runtime" - ], - "parserOptions": { - "project": "./tsconfig.json" - }, - "ignorePatterns": [ - // node_modules is implicitly always ignored - "dist", - "vite.config.mts", - "jest.config.ts", - "jest.setup.ts" - ], - "rules": { - "prettier/prettier": "warn", - "curly": "error", - "no-console": "off", - "react/jsx-props-no-spreading": "off", - "react/require-default-props": "off", - "no-plusplus": ["error", { "allowForLoopAfterthoughts": true }] - } + "root": true, + "extends": [ + "airbnb", + "airbnb-typescript", + "airbnb/hooks", + "plugin:prettier/recommended", + "plugin:react/jsx-runtime" + ], + "parserOptions": { + "project": "./tsconfig.json" + }, + "ignorePatterns": [ + // node_modules is implicitly always ignored + "dist", + "vite.config.mts", + "jest.config.ts", + "jest.setup.ts" + ], + "rules": { + "prettier/prettier": "warn", + "curly": "error", + "no-console": "off", + "react/jsx-props-no-spreading": "off", + "react/require-default-props": "off", + "no-plusplus": ["error", { "allowForLoopAfterthoughts": true }] + } } diff --git a/.prettierrc.json b/.prettierrc.json index 27512b6a..fda48c32 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,5 +1,6 @@ { "trailingComma": "es5", "tabWidth": 4, + "printWidth": 120, "singleQuote": true } diff --git a/babel.config.json b/babel.config.json index 23889e4e..60dd45eb 100644 --- a/babel.config.json +++ b/babel.config.json @@ -6,7 +6,5 @@ "@babel/preset-typescript", "babel-preset-vite" ], - "plugins": [ - "@babel/plugin-transform-runtime" - ] + "plugins": ["@babel/plugin-transform-runtime"] } diff --git a/demo/data/EquipmentSearchBar.js b/demo/data/EquipmentSearchBar.js index 4e13fabd..229db862 100644 --- a/demo/data/EquipmentSearchBar.js +++ b/demo/data/EquipmentSearchBar.js @@ -152,12 +152,8 @@ const searchEquipments = (searchTerm, equipmentLabelling) => { if (searchTerm) { return getEquipmentsInfosForSearchBar( equipmentLabelling - ? EQUIPMENTS.filter((equipment) => - (equipment.name || equipment.id).includes(searchTerm) - ) - : EQUIPMENTS.filter((equipment) => - equipment.id.includes(searchTerm) - ), + ? EQUIPMENTS.filter((equipment) => (equipment.name || equipment.id).includes(searchTerm)) + : EQUIPMENTS.filter((equipment) => equipment.id.includes(searchTerm)), equipmentLabelling ? (e) => e.name || e.id : (e) => e.id ); } diff --git a/demo/data/ReportViewer.js b/demo/data/ReportViewer.js index 54c6fb8e..e484f57e 100644 --- a/demo/data/ReportViewer.js +++ b/demo/data/ReportViewer.js @@ -40,8 +40,7 @@ const LOGS_JSON = { }, { taskKey: 'postLoading', - defaultName: - 'Post loading process on network CC${numNetworkCc} SC${numNetworkSc}', + defaultName: 'Post loading process on network CC${numNetworkCc} SC${numNetworkSc}', taskValues: { numNetworkCc: { value: 0, @@ -154,8 +153,7 @@ const LOGS_JSON = { }, { reportKey: 'NoMismatchDistribution', - defaultMessage: - 'Iteration ${iteration}: already balanced', + defaultMessage: 'Iteration ${iteration}: already balanced', values: { reportSeverity: { value: 'FATAL', @@ -194,8 +192,7 @@ const LOGS_JSON = { reports: [ { reportKey: 'NoMismatchDistribution', - defaultMessage: - 'Iteration ${iteration}: already balanced', + defaultMessage: 'Iteration ${iteration}: already balanced', values: { reportSeverity: { value: 'WARN', diff --git a/demo/src/FlatParametersTab.jsx b/demo/src/FlatParametersTab.jsx index 405380e1..91453da0 100644 --- a/demo/src/FlatParametersTab.jsx +++ b/demo/src/FlatParametersTab.jsx @@ -219,9 +219,7 @@ function FlatParametersTab() { onChange={onChange} variant="standard" showSeparator - selectionWithDialog={(param) => - param?.possibleValues?.length > 10 - } + selectionWithDialog={(param) => param?.possibleValues?.length > 10} /> diff --git a/demo/src/InputsTab.jsx b/demo/src/InputsTab.jsx index 180c835a..3dcd1c0e 100644 --- a/demo/src/InputsTab.jsx +++ b/demo/src/InputsTab.jsx @@ -68,12 +68,7 @@ const options = [ { id: 'ibra', label: 'inputs/ibra' }, ]; -const basicOptions = [ - 'Kylian Mbappe', - 'Neymar', - 'Lionel Messi', - 'Zlatan Ibrahimovic', -]; +const basicOptions = ['Kylian Mbappe', 'Neymar', 'Lionel Messi', 'Zlatan Ibrahimovic']; const gridSize = 4; @@ -141,20 +136,10 @@ function InputsTab() { /> - + - + - + - + - + - + ({ // https://github.com/bvaughn/react-virtualized/issues/454 '& .ReactVirtualized__Table__headerRow': { flip: false, - paddingRight: - theme.direction === 'rtl' ? '0 !important' : undefined, + paddingRight: theme.direction === 'rtl' ? '0 !important' : undefined, }, }, '& .tableRow': { @@ -88,18 +80,13 @@ const stylesVirtualizedTable = (theme) => ({ }); const stylesEmotion = ({ theme }) => - toNestedGlobalSelectors( - stylesVirtualizedTable(theme), - generateMuiVirtualizedTableClass - ); + toNestedGlobalSelectors(stylesVirtualizedTable(theme), generateMuiVirtualizedTableClass); const StyledVirtualizedTable = styled(MuiVirtualizedTable)(stylesEmotion); function TableTab() { const [usesCustomStyles, setUsesCustomStyles] = useState(true); - const VirtualizedTable = usesCustomStyles - ? StyledVirtualizedTable - : MuiVirtualizedTable; + const VirtualizedTable = usesCustomStyles ? StyledVirtualizedTable : MuiVirtualizedTable; const columns = useMemo( () => [ @@ -174,20 +161,12 @@ function TableTab() { ); const sort = useCallback( (dataKey, reverse, isNumeric) => { - let filtered = rows - .map((r, i) => [r, i]) - .filter(([r]) => !filter || filter(r)); + let filtered = rows.map((r, i) => [r, i]).filter(([r]) => !filter || filter(r)); if (dataKey) { filtered = filtered .map(([r, j]) => [r[dataKey], j]) - .map(([r, j]) => [ - isNumeric ? r : Number(r.replace(/[^0-9.]/g, '')), - j, - ]); // for demo, extract any number from a string.. - filtered.sort( - ([a], [b]) => - evenThenOddOrderingKey(b) - evenThenOddOrderingKey(a) - ); + .map(([r, j]) => [isNumeric ? r : Number(r.replace(/[^0-9.]/g, '')), j]); // for demo, extract any number from a string.. + filtered.sort(([a], [b]) => evenThenOddOrderingKey(b) - evenThenOddOrderingKey(a)); if (reverse) { filtered = filtered.reverse(); } @@ -226,18 +205,10 @@ function TableTab() { function renderParams() { return ( - {mkSwitch( - 'Custom theme (emotion)', - usesCustomStyles, - setUsesCustomStyles - )} + {mkSwitch('Custom theme (emotion)', usesCustomStyles, setUsesCustomStyles)} {mkSwitch('Sortable', sortable, setSortable)} {mkSwitch('Instance renewal', recreates, setRecreates)} - {mkSwitch( - 'Uses external indexer', - isIndexerExternal, - setIndexerIsExternal - )} + {mkSwitch('Uses external indexer', isIndexerExternal, setIndexerIsExternal)} - {mkSwitch( - 'External sort (even then odds)', - doesSort, - setDoesSort - )} + {mkSwitch('External sort (even then odds)', doesSort, setDoesSort)} - {mkSwitch( - 'Defer filter changes', - defersFilterChanges, - setDefersFilterChanges - )} + {mkSwitch('Defer filter changes', defersFilterChanges, setDefersFilterChanges)} console.log('onRowClick', args)} onClick={(...args) => console.log('onClick', args)} onCellClick={(...args) => console.log('onCellClick', args)} diff --git a/demo/src/TreeViewFinderConfig.jsx b/demo/src/TreeViewFinderConfig.jsx index 9dcf5432..dbce87da 100644 --- a/demo/src/TreeViewFinderConfig.jsx +++ b/demo/src/TreeViewFinderConfig.jsx @@ -6,15 +6,7 @@ */ import PropTypes from 'prop-types'; -import { - Checkbox, - FormControl, - FormControlLabel, - FormGroup, - FormLabel, - Radio, - RadioGroup, -} from '@mui/material'; +import { Checkbox, FormControl, FormControlLabel, FormGroup, FormLabel, Radio, RadioGroup } from '@mui/material'; /** * TreeViewFinderConfig documentation: @@ -66,69 +58,39 @@ function TreeViewFinderConfig(props) { }} >
- - Data Format - + Data Format - } - label="Tree" - /> - } - label="List" - /> + } label="Tree" /> + } label="List" />
- - Data update - + Data update - } - label="static" - /> - } - label="dynamic" - /> + } label="static" /> + } label="dynamic" />
- - Selection Type - + Selection Type - } - label="single selection" - /> - } - label="multiselect" - /> + } label="single selection" /> + } label="multiselect" />
@@ -136,11 +98,7 @@ function TreeViewFinderConfig(props) { + } label="Only leaves selection" /> diff --git a/demo/src/app.jsx b/demo/src/app.jsx index 6ad017b2..3a30de0a 100644 --- a/demo/src/app.jsx +++ b/demo/src/app.jsx @@ -76,10 +76,7 @@ import PowsyblLogo from '../images/powsybl_logo.svg?react'; import AppPackage from '../../package.json'; import ReportViewerDialog from '../../src/components/ReportViewerDialog'; -import { - TreeViewFinder, - generateTreeViewFinderClass, -} from '../../src/components/TreeViewFinder'; +import { TreeViewFinder, generateTreeViewFinderClass } from '../../src/components/TreeViewFinder'; import TreeViewFinderConfig from './TreeViewFinderConfig'; import { @@ -182,13 +179,8 @@ const TreeViewFinderCustomStyles = (theme) => ({ }); const TreeViewFinderCustomStylesEmotion = ({ theme }) => - toNestedGlobalSelectors( - TreeViewFinderCustomStyles(theme), - generateTreeViewFinderClass - ); -const CustomTreeViewFinder = styled(TreeViewFinder)( - TreeViewFinderCustomStylesEmotion -); + toNestedGlobalSelectors(TreeViewFinderCustomStyles(theme), generateTreeViewFinderClass); +const CustomTreeViewFinder = styled(TreeViewFinder)(TreeViewFinderCustomStylesEmotion); function Crasher() { const [crash, setCrash] = useState(false); @@ -309,12 +301,8 @@ function AppContent({ language, onLanguageClick }) { error: null, }); const [user, setUser] = useState(null); - const [authenticationRouterError, setAuthenticationRouterError] = - useState(null); - const [ - showAuthenticationRouterLoginState, - setShowAuthenticationRouterLoginState, - ] = useState(false); + const [authenticationRouterError, setAuthenticationRouterError] = useState(null); + const [showAuthenticationRouterLoginState, setShowAuthenticationRouterLoginState] = useState(false); const [theme, setTheme] = useState(LIGHT_THEME); @@ -323,17 +311,11 @@ function AppContent({ language, onLanguageClick }) { const [equipmentLabelling, setEquipmentLabelling] = useState(false); const [openReportViewer, setOpenReportViewer] = useState(false); - const [openTreeViewFinderDialog, setOpenTreeViewFinderDialog] = - useState(false); - const [ - openTreeViewFinderDialogCustomDialog, - setOpenTreeViewFinderDialogCustomDialog, - ] = useState(false); + const [openTreeViewFinderDialog, setOpenTreeViewFinderDialog] = useState(false); + const [openTreeViewFinderDialogCustomDialog, setOpenTreeViewFinderDialogCustomDialog] = useState(false); // Can't use lazy initializer because useMatch is a hook - const [initialMatchSilentRenewCallbackUrl] = useState( - useMatch('/silent-renew-callback') - ); + const [initialMatchSilentRenewCallbackUrl] = useState(useMatch('/silent-renew-callback')); // TreeViewFinder data const [nodesTree, setNodesTree] = useState(testDataTree); @@ -382,9 +364,7 @@ function AppContent({ language, onLanguageClick }) { if (equipment != null) { equipment.type === EQUIPMENT_TYPE.SUBSTATION.name ? alert(`Equipment ${equipment.label} found !`) - : alert( - `Equipment ${equipment.label} (${equipment.voltageLevelLabel}) found !` - ); + : alert(`Equipment ${equipment.label} (${equipment.voltageLevelLabel}) found !`); } }; const [searchTermDisableReason] = useState('search disabled'); @@ -402,9 +382,7 @@ function AppContent({ language, onLanguageClick }) { } else if (e.type === 'RESET_AUTHENTICATION_ROUTER_ERROR') { setAuthenticationRouterError(null); } else if (e.type === 'SHOW_AUTH_INFO_LOGIN') { - setShowAuthenticationRouterLoginState( - e.showAuthenticationRouterLogin - ); + setShowAuthenticationRouterLoginState(e.showAuthenticationRouterLogin); } }; @@ -428,11 +406,7 @@ function AppContent({ language, onLanguageClick }) { ]; useEffect(() => { - initializeAuthenticationDev( - dispatch, - initialMatchSilentRenewCallbackUrl != null, - validateUser - ) + initializeAuthenticationDev(dispatch, initialMatchSilentRenewCallbackUrl != null, validateUser) .then((userManager) => { setUserManager({ instance: userManager, @@ -471,21 +445,14 @@ function AppContent({ language, onLanguageClick }) { return a.name.localeCompare(b.name); } - const handleToggleDisableSearch = useCallback( - () => setSearchDisabled((oldState) => !oldState), - [] - ); + const handleToggleDisableSearch = useCallback(() => setSearchDisabled((oldState) => !oldState), []); const aboutTimerVersion = useRef(); const aboutTimerCmpnt = useRef(); function simulateGetGlobalVersion() { console.log('getGlobalVersion() called'); return new Promise( - (resolve, reject) => - (aboutTimerVersion.current = window.setTimeout( - () => resolve('1.0.0-demo'), - 1250 - )) + (resolve, reject) => (aboutTimerVersion.current = window.setTimeout(() => resolve('1.0.0-demo'), 1250)) ); } function simulateGetAdditionalComponents() { @@ -619,21 +586,11 @@ function AppContent({ language, onLanguageClick }) { multiSelect={multiSelect} onlyLeaves={onlyLeaves} sortedAlphabetically={sortedAlphabetically} - onDynamicDataChange={(event) => - setDynamicData(event.target.value === 'dynamic') - } - onDataFormatChange={(event) => - setDataFormat(event.target.value) - } - onSelectionTypeChange={(event) => - setMultiSelect(event.target.value === 'multiselect') - } - onOnlyLeavesChange={(event) => - setOnlyLeaves(event.target.checked) - } - onSortedAlphabeticallyChange={(event) => - setSortedAlphabetically(event.target.checked) - } + onDynamicDataChange={(event) => setDynamicData(event.target.value === 'dynamic')} + onDataFormatChange={(event) => setDataFormat(event.target.value)} + onSelectionTypeChange={(event) => setMultiSelect(event.target.value === 'multiselect')} + onOnlyLeavesChange={(event) => setOnlyLeaves(event.target.checked)} + onSortedAlphabeticallyChange={(event) => setSortedAlphabetically(event.target.checked)} /> @@ -766,10 +717,7 @@ function AppContent({ language, onLanguageClick }) { onChange={() => { setSearchTermDisabled(!searchTermDisabled); // TO TEST search activation after some times - setTimeout( - () => setSearchTermDisabled(false), - 4000 - ); + setTimeout(() => setSearchTermDisabled(false), 4000); }} name="search-disabled" /> @@ -794,21 +742,15 @@ function AppContent({ language, onLanguageClick }) { appColor="#808080" appLogo={} onParametersClick={() => console.log('settings')} - onLogoutClick={() => - logout(dispatch, userManager.instance) - } + onLogoutClick={() => logout(dispatch, userManager.instance)} onLogoClick={() => console.log('logo')} onThemeClick={handleThemeClick} theme={theme} appVersion={AppPackage.version} appLicense={AppPackage.license} globalVersionPromise={simulateGetGlobalVersion} - additionalModulesPromise={ - simulateGetAdditionalComponents - } - onEquipmentLabellingClick={ - handleEquipmentLabellingClick - } + additionalModulesPromise={simulateGetAdditionalComponents} + onEquipmentLabellingClick={handleEquipmentLabellingClick} equipmentLabelling={equipmentLabelling} withElementsSearch searchingLabel={intl.formatMessage({ @@ -821,11 +763,7 @@ function AppContent({ language, onLanguageClick }) { searchTermDisableReason={searchTermDisableReason} elementsFound={equipmentsFound} renderElement={(props) => ( - + )} onLanguageClick={onLanguageClick} language={language} @@ -849,12 +787,7 @@ function AppContent({ language, onLanguageClick }) { {user !== null ? (
- - setTabIndex(newTabIndex) - } - > + setTabIndex(newTabIndex)}> @@ -869,12 +802,8 @@ function AppContent({ language, onLanguageClick }) { - - + + ); diff --git a/demo/src/equipment-search.tsx b/demo/src/equipment-search.tsx index eca1e660..771ce301 100644 --- a/demo/src/equipment-search.tsx +++ b/demo/src/equipment-search.tsx @@ -8,13 +8,7 @@ import { useState } from 'react'; import { Button, TextField } from '@mui/material'; import { Search } from '@mui/icons-material'; import { useIntl } from 'react-intl'; -import { - ElementSearchDialog, - EquipmentItem, - equipmentStyles, - EquipmentType, - useElementSearch, -} from '../../src/index'; +import { ElementSearchDialog, EquipmentItem, equipmentStyles, EquipmentType, useElementSearch } from '../../src/index'; interface AnyElementInterface { id: string; @@ -49,10 +43,9 @@ const searchEquipmentPromise = () => { export function EquipmentSearchDialog() { const [isSearchOpen, setIsSearchOpen] = useState(false); - const { elementsFound, isLoading, searchTerm, updateSearchTerm } = - useElementSearch({ - fetchElements: searchEquipmentPromise, - }); + const { elementsFound, isLoading, searchTerm, updateSearchTerm } = useElementSearch({ + fetchElements: searchEquipmentPromise, + }); const intl = useIntl(); @@ -68,18 +61,12 @@ export function EquipmentSearchDialog() { }} elementsFound={elementsFound} renderElement={(props: any) => ( - + )} searchTerm={searchTerm} loading={isLoading} getOptionLabel={(option) => option.label} - isOptionEqualToValue={(option1, option2) => - option1.id === option2.id - } + isOptionEqualToValue={(option1, option2) => option1.id === option2.id} renderInput={(displayedValue, params) => ( ( - + )} searchTerm={searchTerm} loading={isLoading} getOptionLabel={(option) => option.label} - isOptionEqualToValue={(option1, option2) => - option1.id === option2.id - } + isOptionEqualToValue={(option1, option2) => option1.id === option2.id} renderInput={(displayedValue, params) => ( >( - (props, ref) => -); +const SvgrMock = forwardRef>((props, ref) => ); export default SvgrMock; diff --git a/src/components/AuthenticationRouter/AuthenticationRouter.tsx b/src/components/AuthenticationRouter/AuthenticationRouter.tsx index 2772b73d..204345ef 100644 --- a/src/components/AuthenticationRouter/AuthenticationRouter.tsx +++ b/src/components/AuthenticationRouter/AuthenticationRouter.tsx @@ -6,23 +6,12 @@ */ import { Dispatch, useCallback } from 'react'; -import { - Location, - Navigate, - NavigateFunction, - Route, - Routes, -} from 'react-router-dom'; +import { Location, Navigate, NavigateFunction, Route, Routes } from 'react-router-dom'; import { Alert, AlertTitle, Grid } from '@mui/material'; import { FormattedMessage } from 'react-intl'; import { UserManager } from 'oidc-client'; import SignInCallbackHandler from '../SignInCallbackHandler'; -import { - handleSigninCallback, - handleSilentRenewCallback, - login, - logout, -} from '../../utils/AuthService'; +import { handleSigninCallback, handleSilentRenewCallback, login, logout } from '../../utils/AuthService'; import SilentRenewCallbackHandler from '../SilentRenewCallbackHandler'; import Login from '../Login'; import Logout from '../Login/Logout'; @@ -71,15 +60,8 @@ function AuthenticationRouter({ } }, [userManager.instance]); return ( - - {userManager.error !== null && ( -

Error : Getting userManager; {userManager.error}

- )} + + {userManager.error !== null &&

Error : Getting userManager; {userManager.error}

} {signInCallbackError !== null && (

Error : SignIn Callback Error; @@ -101,9 +83,7 @@ function AuthenticationRouter({ element={ } /> @@ -115,9 +95,7 @@ function AuthenticationRouter({ authenticationRouterError == null && ( - login(location, userManager.instance) - } + onLoginClick={() => login(location, userManager.instance)} /> ) } @@ -129,9 +107,7 @@ function AuthenticationRouter({ - logout(dispatch, userManager.instance) - } + onLogoutClick={() => logout(dispatch, userManager.instance)} /> @@ -143,20 +119,13 @@ function AuthenticationRouter({ -

- { - authenticationRouterError.logoutError - .error.message - } -

+

{authenticationRouterError.logoutError.error.message}

)} - {authenticationRouterError?.userValidationError != - null && ( + {authenticationRouterError?.userValidationError != null && ( @@ -164,20 +133,13 @@ function AuthenticationRouter({ -

- { - authenticationRouterError - .userValidationError.error.message - } -

+

{authenticationRouterError.userValidationError.error.message}

)} - {authenticationRouterError?.unauthorizedUserInfo != - null && ( + {authenticationRouterError?.unauthorizedUserInfo != null && ( @@ -185,8 +147,7 @@ function AuthenticationRouter({ diff --git a/src/components/CardErrorBoundary/card-error-boundary.tsx b/src/components/CardErrorBoundary/card-error-boundary.tsx index 71494f9f..c3f86a50 100644 --- a/src/components/CardErrorBoundary/card-error-boundary.tsx +++ b/src/components/CardErrorBoundary/card-error-boundary.tsx @@ -9,10 +9,7 @@ // https://reactjs.org/docs/error-boundaries.html // https://mui.com/material-ui/react-card/#complex-interaction -import { - ExpandMore as ExpandMoreIcon, - Replay as ReplayIcon, -} from '@mui/icons-material'; +import { ExpandMore as ExpandMoreIcon, Replay as ReplayIcon } from '@mui/icons-material'; import { Box, Card, @@ -59,10 +56,7 @@ type CardErrorBoundaryStateSuccess = { hasError: false; }; -type CardErrorBoundaryState = ( - | CardErrorBoundaryStateError - | CardErrorBoundaryStateSuccess -) & { +type CardErrorBoundaryState = (CardErrorBoundaryStateError | CardErrorBoundaryStateSuccess) & { expanded: boolean; }; @@ -126,10 +120,7 @@ class CardErrorBoundary extends Component { - + { - + - - {error.message} - + {error.message} diff --git a/src/components/CustomAGGrid/custom-aggrid.style.ts b/src/components/CustomAGGrid/custom-aggrid.style.ts index bb1613bd..9ad9c15d 100644 --- a/src/components/CustomAGGrid/custom-aggrid.style.ts +++ b/src/components/CustomAGGrid/custom-aggrid.style.ts @@ -16,8 +16,7 @@ export const styles = { position: 'relative', [`&.${CUSTOM_AGGRID_THEME}`]: { - '--ag-value-change-value-highlight-background-color': - theme.aggrid.valueChangeHighlightBackgroundColor, + '--ag-value-change-value-highlight-background-color': theme.aggrid.valueChangeHighlightBackgroundColor, '--ag-selected-row-background-color': theme.aggrid.highlightColor, '--ag-row-hover-color': theme.aggrid.highlightColor, }, diff --git a/src/components/CustomAGGrid/custom-aggrid.tsx b/src/components/CustomAGGrid/custom-aggrid.tsx index abb55ee5..c26f2b5d 100644 --- a/src/components/CustomAGGrid/custom-aggrid.tsx +++ b/src/components/CustomAGGrid/custom-aggrid.tsx @@ -36,60 +36,52 @@ const onColumnResized = (params: ColumnResizedEvent) => { } }; -const CustomAGGrid = React.forwardRef( - (props, ref) => { - const { - shouldHidePinnedHeaderRightBorder = false, - overlayNoRowsTemplate, - loadingOverlayComponent, - loadingOverlayComponentParams, - showOverlay = false, - } = props; - const theme = useTheme(); - const intl = useIntl(); +const CustomAGGrid = React.forwardRef((props, ref) => { + const { + shouldHidePinnedHeaderRightBorder = false, + overlayNoRowsTemplate, + loadingOverlayComponent, + loadingOverlayComponentParams, + showOverlay = false, + } = props; + const theme = useTheme(); + const intl = useIntl(); - const GRID_PREFIX = 'grid.'; + const GRID_PREFIX = 'grid.'; - const getLocaleText = useCallback( - (params: GetLocaleTextParams) => { - const key = GRID_PREFIX + params.key; - return intl.formatMessage({ - id: key, - defaultMessage: params.defaultValue, - }); - }, - [intl] - ); + const getLocaleText = useCallback( + (params: GetLocaleTextParams) => { + const key = GRID_PREFIX + params.key; + return intl.formatMessage({ + id: key, + defaultMessage: params.defaultValue, + }); + }, + [intl] + ); - return ( - - - - ); - } -); + return ( + + + + ); +}); export default CustomAGGrid; diff --git a/src/components/DirectoryItemSelector/directory-item-selector.tsx b/src/components/DirectoryItemSelector/directory-item-selector.tsx index 7416858b..f47e09c4 100644 --- a/src/components/DirectoryItemSelector/directory-item-selector.tsx +++ b/src/components/DirectoryItemSelector/directory-item-selector.tsx @@ -10,16 +10,9 @@ import { SxProps, Theme } from '@mui/material'; import { UUID } from 'crypto'; import getFileIcon from '../../utils/ElementIcon'; import { ElementType } from '../../utils/ElementType'; -import TreeViewFinder, { - TreeViewFinderNodeProps, - TreeViewFinderProps, -} from '../TreeViewFinder/TreeViewFinder'; +import TreeViewFinder, { TreeViewFinderNodeProps, TreeViewFinderProps } from '../TreeViewFinder/TreeViewFinder'; import { useSnackMessage } from '../../hooks/useSnackMessage'; -import { - fetchDirectoryContent, - fetchElementsInfos, - fetchRootFolders, -} from '../../services'; +import { fetchDirectoryContent, fetchElementsInfos, fetchRootFolders } from '../../services'; const styles = { icon: (theme: Theme) => ({ @@ -44,10 +37,7 @@ function flattenDownNodes(n: any, cef: (n: any) => any[]): any[] { if (subs.length === 0) { return [n]; } - return Array.prototype.concat( - [n], - ...subs.map((sn: any) => flattenDownNodes(sn, cef)) - ); + return Array.prototype.concat([n], ...subs.map((sn: any) => flattenDownNodes(sn, cef))); } function refreshedUpNodes(m: any[], nn: any): any[] { @@ -58,9 +48,7 @@ function refreshedUpNodes(m: any[], nn: any): any[] { return [nn]; } const parent = m[nn.parentUuid]; - const nextChildren = parent.children.map((c: any) => - c.elementUuid === nn.elementUuid ? nn : c - ); + const nextChildren = parent.children.map((c: any) => (c.elementUuid === nn.elementUuid ? nn : c)); const nextParent = { ...parent, children: nextChildren }; return [nn, ...refreshedUpNodes(m, nextParent)]; } @@ -72,12 +60,7 @@ function refreshedUpNodes(m: any[], nn: any): any[] { * @param nodeId uuid of the node to update children, may be null or undefined (means root) * @param children new value of the node children (shallow nodes) */ -function updatedTree( - prevRoots: any[], - prevMap: any, - nodeId: UUID | null, - children: any[] -) { +function updatedTree(prevRoots: any[], prevMap: any, nodeId: UUID | null, children: any[]) { const nextChildren = children .sort((a, b) => a.elementName.localeCompare(b.elementName)) .map((n: any) => { @@ -113,12 +96,8 @@ function updatedTree( return [prevRoots, prevMap]; } - const nextUuids = new Set( - children ? children.map((n) => n.elementUuid) : [] - ); - const prevUuids = prevChildren - ? prevChildren.map((n: any) => n.elementUuid) - : []; + const nextUuids = new Set(children ? children.map((n) => n.elementUuid) : []); + const prevUuids = prevChildren ? prevChildren.map((n: any) => n.elementUuid) : []; const mayNodeId = nodeId ? [nodeId] : []; const nonCopyUuids = new Set([ @@ -127,11 +106,7 @@ function updatedTree( ...Array.prototype.concat( ...prevUuids .filter((u: UUID) => !nextUuids.has(u)) - .map((u: UUID) => - flattenDownNodes(prevMap[u], (n) => n.children).map( - (n) => n.elementUuid - ) - ) + .map((u: UUID) => flattenDownNodes(prevMap[u], (n) => n.children).map((n) => n.elementUuid)) ), ]); @@ -150,10 +125,7 @@ function updatedTree( ...refreshedUpNodes(prevMap, nextNode).map((n) => [n.elementUuid, n]), ]); - const nextRoots = - nodeId === null - ? nextChildren - : prevRoots.map((r) => nextMap[r.elementUuid]); + const nextRoots = nodeId === null ? nextChildren : prevRoots.map((r) => nextMap[r.elementUuid]); return [nextRoots, nextMap]; } @@ -175,10 +147,7 @@ interface DirectoryItemSelectorProps extends TreeViewFinderProps { expanded?: UUID[]; } -function sortHandlingDirectories( - a: TreeViewFinderNodeProps, - b: TreeViewFinderNodeProps -): number { +function sortHandlingDirectories(a: TreeViewFinderNodeProps, b: TreeViewFinderNodeProps): number { // If children property is set it means it's a directory, they are handled differently in order to keep them at the top of the list if (a.children && !b.children) { return -1; @@ -206,10 +175,7 @@ function DirectoryItemSelector({ const rootsRef = useRef([]); rootsRef.current = rootDirectories; const { snackError } = useSnackMessage(); - const contentFilter = useCallback( - () => new Set([ElementType.DIRECTORY, ...types]), - [types] - ); + const contentFilter = useCallback(() => new Set([ElementType.DIRECTORY, ...types]), [types]); const convertChildren = useCallback((children: any[]): any[] => { return children.map((e) => { @@ -218,14 +184,8 @@ function DirectoryItemSelector({ name: e.elementName, specificMetadata: e.specificMetadata, icon: getFileIcon(e.type, styles.icon as SxProps), - children: - e.type === ElementType.DIRECTORY - ? convertChildren(e.children) - : undefined, - childrenCount: - e.type === ElementType.DIRECTORY - ? e.subdirectoriesCount - : undefined, + children: e.type === ElementType.DIRECTORY ? convertChildren(e.children) : undefined, + childrenCount: e.type === ElementType.DIRECTORY ? e.subdirectoriesCount : undefined, }; }); }, []); @@ -239,14 +199,9 @@ function DirectoryItemSelector({ icon: getFileIcon(e.type, styles.icon as SxProps), children: e.type === ElementType.DIRECTORY - ? convertChildren( - nodeMap.current[e.elementUuid].children - ) - : undefined, - childrenCount: - e.type === ElementType.DIRECTORY - ? e.subdirectoriesCount + ? convertChildren(nodeMap.current[e.elementUuid].children) : undefined, + childrenCount: e.type === ElementType.DIRECTORY ? e.subdirectoriesCount : undefined, }; }); }, @@ -255,12 +210,7 @@ function DirectoryItemSelector({ const addToDirectory = useCallback( (nodeId: UUID, content: any[]) => { - const [nrs, mdr] = updatedTree( - rootsRef.current, - nodeMap.current, - nodeId, - content - ); + const [nrs, mdr] = updatedTree(rootsRef.current, nodeMap.current, nodeId, content); setRootDirectories(nrs); nodeMap.current = mdr; setData(convertRoots(nrs)); @@ -271,12 +221,7 @@ function DirectoryItemSelector({ const updateRootDirectories = useCallback(() => { fetchRootFolders(types) .then((newData) => { - const [nrs, mdr] = updatedTree( - rootsRef.current, - nodeMap.current, - null, - newData - ); + const [nrs, mdr] = updatedTree(rootsRef.current, nodeMap.current, null, newData); setRootDirectories(nrs); nodeMap.current = mdr; setData(convertRoots(nrs)); @@ -294,15 +239,9 @@ function DirectoryItemSelector({ const typeList = types.includes(ElementType.DIRECTORY) ? [] : types; fetchDirectoryContent(nodeId, typeList) .then((children) => { - const childrenMatchedTypes = children.filter((item: any) => - contentFilter().has(item.type) - ); + const childrenMatchedTypes = children.filter((item: any) => contentFilter().has(item.type)); - if ( - childrenMatchedTypes.length > 0 && - equipmentTypes && - equipmentTypes.length > 0 - ) { + if (childrenMatchedTypes.length > 0 && equipmentTypes && equipmentTypes.length > 0) { fetchElementsInfos( childrenMatchedTypes.map((e: any) => e.elementUuid), types, @@ -327,9 +266,7 @@ function DirectoryItemSelector({ } }) .catch((error) => { - console.warn( - `Could not update subs (and content) of '${nodeId}' : ${error.message}` - ); + console.warn(`Could not update subs (and content) of '${nodeId}' : ${error.message}`); }); }, [types, equipmentTypes, itemFilter, contentFilter, addToDirectory] diff --git a/src/components/ElementSearchDialog/element-search-dialog.tsx b/src/components/ElementSearchDialog/element-search-dialog.tsx index c3bdbdde..6b7bdc9c 100644 --- a/src/components/ElementSearchDialog/element-search-dialog.tsx +++ b/src/components/ElementSearchDialog/element-search-dialog.tsx @@ -7,13 +7,9 @@ import { useCallback } from 'react'; import { Dialog, DialogContent } from '@mui/material'; -import { - ElementSearchInput, - ElementSearchInputProps, -} from './element-search-input'; +import { ElementSearchInput, ElementSearchInputProps } from './element-search-input'; -export interface ElementSearchDialogProps - extends ElementSearchInputProps { +export interface ElementSearchDialogProps extends ElementSearchInputProps { onClose?: () => void; open: boolean; } @@ -27,18 +23,9 @@ export function ElementSearchDialog(props: ElementSearchDialogProps) { }, [onSearchTermChange, onClose]); return ( - + - + ); diff --git a/src/components/ElementSearchDialog/element-search-input.tsx b/src/components/ElementSearchDialog/element-search-input.tsx index f1653b7b..d547d69c 100644 --- a/src/components/ElementSearchDialog/element-search-input.tsx +++ b/src/components/ElementSearchDialog/element-search-input.tsx @@ -4,11 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - Autocomplete, - AutocompleteProps, - AutocompleteRenderInputParams, -} from '@mui/material'; +import { Autocomplete, AutocompleteProps, AutocompleteRenderInputParams } from '@mui/material'; import { HTMLAttributes, ReactNode, useMemo } from 'react'; import { useIntl } from 'react-intl'; @@ -20,13 +16,7 @@ export type RenderElementProps = HTMLAttributes & { export interface ElementSearchInputProps extends Pick< AutocompleteProps, - | 'sx' - | 'size' - | 'loadingText' - | 'loading' - | 'disableClearable' - | 'getOptionDisabled' - | 'PaperComponent' + 'sx' | 'size' | 'loadingText' | 'loading' | 'disableClearable' | 'getOptionDisabled' | 'PaperComponent' > { searchTerm: string; onSearchTermChange: (searchTerm: string) => void; @@ -35,18 +25,13 @@ export interface ElementSearchInputProps isOptionEqualToValue: (option1: T, option2: T) => boolean; elementsFound: T[]; renderElement: (props: RenderElementProps) => ReactNode; - renderInput: ( - searchTerm: string, - props: AutocompleteRenderInputParams - ) => ReactNode; + renderInput: (searchTerm: string, props: AutocompleteRenderInputParams) => ReactNode; searchTermDisabled?: boolean; searchTermDisableReason?: string; showResults?: boolean; } -export function ElementSearchInput( - props: Readonly> -) { +export function ElementSearchInput(props: Readonly>) { const { elementsFound, loading, @@ -99,11 +84,7 @@ export function ElementSearchInput( }} onChange={(_event, newValue, reason) => { // when calling this method with reason == "selectOption", newValue can't be null or of type "string", since an option has been clicked on - if ( - newValue != null && - typeof newValue !== 'string' && - reason === 'selectOption' - ) { + if (newValue != null && typeof newValue !== 'string' && reason === 'selectOption') { onSelectionChange(newValue); } }} @@ -121,9 +102,7 @@ export function ElementSearchInput( inputValue, }) } - renderInput={(params: AutocompleteRenderInputParams) => - renderInput(displayedValue, params) - } + renderInput={(params: AutocompleteRenderInputParams) => renderInput(displayedValue, params)} getOptionLabel={(option) => { if (typeof option === 'string') { return option; diff --git a/src/components/ElementSearchDialog/equipment-item.tsx b/src/components/ElementSearchDialog/equipment-item.tsx index 249f4123..ec534ee0 100644 --- a/src/components/ElementSearchDialog/equipment-item.tsx +++ b/src/components/ElementSearchDialog/equipment-item.tsx @@ -50,25 +50,14 @@ export function EquipmentItem({ /* override li.key otherwise it will use label which could be duplicated */ return (
  • - + {!showsJustText && ( - + )} ); } diff --git a/src/components/ElementSearchDialog/use-element-search.tsx b/src/components/ElementSearchDialog/use-element-search.tsx index 8d2f6881..a29f2d81 100644 --- a/src/components/ElementSearchDialog/use-element-search.tsx +++ b/src/components/ElementSearchDialog/use-element-search.tsx @@ -87,10 +87,7 @@ const useElementSearch = ( [fetchElements, snackError] ); - const debouncedSearchMatchingElements = useDebounce( - searchMatchingElements, - SEARCH_FETCH_TIMEOUT_MILLIS - ); + const debouncedSearchMatchingElements = useDebounce(searchMatchingElements, SEARCH_FETCH_TIMEOUT_MILLIS); const updateSearchTerm = useCallback( (newSearchTerm: string) => { diff --git a/src/components/ExpandableGroup/expandable-group.tsx b/src/components/ExpandableGroup/expandable-group.tsx index 320b1e9c..a7bb1fe0 100644 --- a/src/components/ExpandableGroup/expandable-group.tsx +++ b/src/components/ExpandableGroup/expandable-group.tsx @@ -4,13 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - Accordion, - AccordionDetails, - AccordionSummary, - Theme, - Typography, -} from '@mui/material'; +import { Accordion, AccordionDetails, AccordionSummary, Theme, Typography } from '@mui/material'; import { PropsWithChildren, ReactNode, useState } from 'react'; import { ExpandCircleDown, ExpandMore } from '@mui/icons-material'; import { FormattedMessage } from 'react-intl'; @@ -69,9 +63,7 @@ function ExpandableGroup({ renderHeader, children }: ExpandableGroupProps) { renderHeader )} - - {children} - + {children} ); } diff --git a/src/components/FlatParameters/FlatParameters.tsx b/src/components/FlatParameters/FlatParameters.tsx index 25914205..0ed0915c 100644 --- a/src/components/FlatParameters/FlatParameters.tsx +++ b/src/components/FlatParameters/FlatParameters.tsx @@ -81,9 +81,7 @@ function longestCommonPrefix(stringList: string[]) { if (!stringList?.length) { return ''; } - let prefix = stringList.reduce((acc: string, str: string) => - str.length < acc.length ? str : acc - ); + let prefix = stringList.reduce((acc: string, str: string) => (str.length < acc.length ? str : acc)); stringList.forEach((str) => { while (!str.startsWith(prefix)) { @@ -188,11 +186,7 @@ export function FlatParameters({ } if (onChange) { if (param.type === 'STRING_LIST') { - onChange( - paramName, - value ? value.toString() : null, - isInEdition - ); + onChange(paramName, value ? value.toString() : null, isInEdition); } else { onChange(paramName, value, isInEdition); } @@ -230,9 +224,7 @@ export function FlatParameters({ if (initValues && Object.hasOwn(initValues, param.name)) { if (param.type === 'BOOLEAN') { // on the server side, we only store String, so we eventually need to convert before - return initValues[param.name] === 'false' - ? false - : initValues[param.name]; // 'true' is truthly + return initValues[param.name] === 'false' ? false : initValues[param.name]; // 'true' is truthly } if (param.type !== 'STRING_LIST') { return initValues[param.name]; @@ -256,10 +248,7 @@ export function FlatParameters({ return value?.replace(',', '.') || ''; }; - const getStringListValue = ( - allValues: string[], - selectValues: string[] - ) => { + const getStringListValue = (allValues: string[], selectValues: string[]) => { if (!selectValues || !selectValues.length) { return intl.formatMessage({ id: 'flat_parameters/none' }); } @@ -275,18 +264,11 @@ export function FlatParameters({ const fieldValue = mixInitAndDefault(param); switch (param.type) { case 'BOOLEAN': - return ( - onFieldChange(e.target.checked, param)} - /> - ); + return onFieldChange(e.target.checked, param)} />; case 'DOUBLE': { const err = Number.isNaN(fieldValue) || - (typeof fieldValue !== 'number' && - !!fieldValue && - Number.isNaN(fieldValue - 0)); + (typeof fieldValue !== 'number' && !!fieldValue && Number.isNaN(fieldValue - 0)); return ( { const m = FloatRE.exec(e.target.value); if (m) { - onFieldChange( - outputTransformFloatString(e.target.value), - param - ); + onFieldChange(outputTransformFloatString(e.target.value), param); } }} error={err} @@ -329,30 +308,20 @@ export function FlatParameters({ ); case 'STRING_LIST': if (param.possibleValues) { - const allOptions = sortPossibleValues( - param.name, - param.possibleValues - ).map(({ id }) => id); + const allOptions = sortPossibleValues(param.name, param.possibleValues).map(({ id }) => id); const withDialog = selectionWithDialog(param); if (withDialog) { return ( <> - setOpenSelector(true) - } - > + setOpenSelector(true)}> ), @@ -362,9 +331,7 @@ export function FlatParameters({ options={allOptions} titleId={getSelectionDialogName(param.name)} open={openSelector} - getOptionLabel={(option) => - getTranslatedValue(param.name, option) - } + getOptionLabel={(option) => getTranslatedValue(param.name, option)} selectedOptions={fieldValue} handleClose={() => setOpenSelector(false)} handleValidate={(selectedOptions) => { @@ -380,29 +347,16 @@ export function FlatParameters({ fullWidth multiple size="small" - options={sortPossibleValues( - param.name, - param.possibleValues - ).map((v) => v.id)} - getOptionLabel={(option) => - getTranslatedValue(param.name, option) - } + options={sortPossibleValues(param.name, param.possibleValues).map((v) => v.id)} + getOptionLabel={(option) => getTranslatedValue(param.name, option)} onChange={(e, value) => onFieldChange(value, param)} value={fieldValue} renderTags={(values, getTagProps) => { return values.map((value, index) => ( - + )); }} - renderInput={(inputProps) => ( - - )} + renderInput={(inputProps) => } /> ); } @@ -419,17 +373,10 @@ export function FlatParameters({ value={fieldValue} renderTags={(values, getTagProps) => { return values.map((value, index) => ( - + )); }} - renderInput={(inputProps) => ( - - )} + renderInput={(inputProps) => } /> ); @@ -447,10 +394,7 @@ export function FlatParameters({ sx={{ minWidth: '4em' }} variant={variant} > - {sortPossibleValues( - param.name, - param.possibleValues - ).map((value) => ( + {sortPossibleValues(param.name, param.possibleValues).map((value) => ( {value.message} @@ -480,29 +424,17 @@ export function FlatParameters({ - } + title={} enterDelay={1200} key={param.name} > - + {renderField(param)} - {showSeparator && index !== paramsAsArray.length - 1 && ( - - )} + {showSeparator && index !== paramsAsArray.length - 1 && } ))} diff --git a/src/components/Login/Login.tsx b/src/components/Login/Login.tsx index 82df44a1..4d4121f5 100644 --- a/src/components/Login/Login.tsx +++ b/src/components/Login/Login.tsx @@ -4,15 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - Avatar, - Box, - Button, - Container, - Link, - Theme, - Typography, -} from '@mui/material'; +import { Avatar, Box, Button, Container, Link, Theme, Typography } from '@mui/material'; import { LockOutlined as LockOutlinedIcon } from '@mui/icons-material'; import { FormattedMessage } from 'react-intl'; @@ -50,29 +42,15 @@ function Login({ onLoginClick, disabled }: LoginProps) { - {' '} - ? + ? - - + {'Copyright © '} {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */} diff --git a/src/components/Login/Logout.tsx b/src/components/Login/Logout.tsx index 2a7c095b..8ea21e29 100644 --- a/src/components/Login/Logout.tsx +++ b/src/components/Login/Logout.tsx @@ -5,15 +5,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - Avatar, - Box, - Button, - Container, - Link, - Theme, - Typography, -} from '@mui/material'; +import { Avatar, Box, Button, Container, Link, Theme, Typography } from '@mui/material'; import { LogoutOutlined as LogoutOutlinedIcon } from '@mui/icons-material'; import { FormattedMessage } from 'react-intl'; @@ -60,24 +52,11 @@ function Logout({ onLogoutClick, disabled }: LogoutProps) { - {' '} - ? + ? - diff --git a/src/components/MuiVirtualizedTable/ColumnHeader.tsx b/src/components/MuiVirtualizedTable/ColumnHeader.tsx index c5b4f517..5517ee97 100644 --- a/src/components/MuiVirtualizedTable/ColumnHeader.tsx +++ b/src/components/MuiVirtualizedTable/ColumnHeader.tsx @@ -5,16 +5,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - ComponentProps, - forwardRef, - MouseEvent, - ReactNode, - useCallback, - useMemo, - useRef, - useState, -} from 'react'; +import { ComponentProps, forwardRef, MouseEvent, ReactNode, useCallback, useMemo, useRef, useState } from 'react'; import { ArrowDownward as ArrowDownwardIcon, @@ -77,16 +68,10 @@ interface SortButtonProps { // so lesser values are at top, so the upward arrow function SortButton({ signedRank = 0, ...props }: SortButtonProps) { const sortRank = Math.abs(signedRank); - const visibilityStyle = - (!signedRank || undefined) && - (props.headerHovered ? styles.hovered : styles.transparent); + const visibilityStyle = (!signedRank || undefined) && (props.headerHovered ? styles.hovered : styles.transparent); return ( - {signedRank >= 0 ? ( - - ) : ( - - )} + {signedRank >= 0 ? : } {sortRank > 1 && !props.hovered && {sortRank}} ); @@ -100,8 +85,7 @@ interface FilterButtonProps { function FilterButton(props: FilterButtonProps) { const { filterLevel, headerHovered, onClick } = props; - const visibilityStyle = - !filterLevel && (headerHovered ? styles.hovered : styles.transparent); + const visibilityStyle = !filterLevel && (headerHovered ? styles.hovered : styles.transparent); return ( ( - (props, ref) => { - const { - className, - label, - numeric, - sortSignedRank, - filterLevel, - onSortClick, - onFilterClick, - onContextMenu, - style, - } = props; +export const ColumnHeader = forwardRef((props, ref) => { + const { className, label, numeric, sortSignedRank, filterLevel, onSortClick, onFilterClick, onContextMenu, style } = + props; - const [hovered, setHovered] = useState(false); - const onHover = useCallback((evt: Event) => { - setHovered(evt.type === 'mouseenter'); - }, []); + const [hovered, setHovered] = useState(false); + const onHover = useCallback((evt: Event) => { + setHovered(evt.type === 'mouseenter'); + }, []); - const topmostDiv = useRef(); + const topmostDiv = useRef(); - const handleFilterClick = useMemo(() => { - if (!onFilterClick) { - return undefined; - } - return (evt: MouseEvent) => { - onFilterClick(evt); - }; - }, [onFilterClick]); + const handleFilterClick = useMemo(() => { + if (!onFilterClick) { + return undefined; + } + return (evt: MouseEvent) => { + onFilterClick(evt); + }; + }, [onFilterClick]); - return ( - // @ts-ignore it does not let us define Box with onMouseEnter/onMouseLeave attributes with 'div' I think, not sure though - - {/* we cheat here to get the _variable_ height */} - - {label} - - {onSortClick && ( - - )} - {handleFilterClick && ( - - )} + return ( + // @ts-ignore it does not let us define Box with onMouseEnter/onMouseLeave attributes with 'div' I think, not sure though + + {/* we cheat here to get the _variable_ height */} + + {label} - ); - } -); + {onSortClick && } + {handleFilterClick && ( + + )} + + ); +}); export default styled(ColumnHeader)({}); diff --git a/src/components/MuiVirtualizedTable/KeyedColumnsRowIndexer.tsx b/src/components/MuiVirtualizedTable/KeyedColumnsRowIndexer.tsx index ff9cb5c0..1517d50d 100644 --- a/src/components/MuiVirtualizedTable/KeyedColumnsRowIndexer.tsx +++ b/src/components/MuiVirtualizedTable/KeyedColumnsRowIndexer.tsx @@ -61,11 +61,7 @@ export const noOpHelper = Object.freeze({ maintainsStats: false, initStat: () => undefined, updateStat: (colStat: ColStat, value: number) => {}, - accepts: ( - value: any, - userParams: any[] | undefined, - outerParams: any[] | undefined - ) => { + accepts: (value: any, userParams: any[] | undefined, outerParams: any[] | undefined) => { return true; }, }); @@ -77,26 +73,14 @@ const numericHelper = Object.freeze({ return { imin: null, imax: null }; }, updateStat: (colStat: ColStat, value: number) => { - if ( - colStat.imin === undefined || - colStat.imin === null || - colStat.imin > value - ) { + if (colStat.imin === undefined || colStat.imin === null || colStat.imin > value) { colStat.imin = value; } - if ( - colStat.imax === undefined || - colStat.imax === null || - colStat.imax < value - ) { + if (colStat.imax === undefined || colStat.imax === null || colStat.imax < value) { colStat.imax = value; } }, - accepts: ( - value: number, - userParams: any[] | undefined, - outerParams: any[] | undefined - ) => { + accepts: (value: number, userParams: any[] | undefined, outerParams: any[] | undefined) => { return true; }, }); @@ -115,11 +99,7 @@ export const collectibleHelper = Object.freeze({ m[cellValue] += 1; } }, - accepts: ( - value: number, - userParams: any[] | undefined, - outerParams: any[] | undefined - ) => { + accepts: (value: number, userParams: any[] | undefined, outerParams: any[] | undefined) => { return !userParams || userParams.some((v) => v === value); }, }); @@ -326,21 +306,19 @@ const groupAndSort = ( // @ts-ignore I don't know how to fix this one const groups = groupRows(groupingColumnsCount, columns, indexedArray); - const interGroupSortingComparator = - makeCompositeComparatorFromCodedColumns( - codedColumns, - columns, - (ar) => ar[0][0] - ); + const interGroupSortingComparator = makeCompositeComparatorFromCodedColumns( + codedColumns, + columns, + (ar) => ar[0][0] + ); groups.sort(interGroupSortingComparator); - const intraGroupSortingComparator = - makeCompositeComparatorFromCodedColumns( - codedColumns, - columns, - // @ts-ignore I don't know how to fix this one - (ar) => ar[0] - ); + const intraGroupSortingComparator = makeCompositeComparatorFromCodedColumns( + codedColumns, + columns, + // @ts-ignore I don't know how to fix this one + (ar) => ar[0] + ); indexedArray = []; groups.forEach((group: any) => { @@ -363,19 +341,11 @@ export class KeyedColumnsRowIndexer { versionSetter: ((version: number) => void) | null; - byColFilter: Record< - string, - { userParams?: any[]; outerParams?: any[] } - > | null; + byColFilter: Record | null; byRowFilter: ((row: RowProps) => boolean) | null; - delegatorCallback: - | (( - instance: KeyedColumnsRowIndexer, - callback: (input: any) => void - ) => void) - | null; + delegatorCallback: ((instance: KeyedColumnsRowIndexer, callback: (input: any) => void) => void) | null; filterVersion: number; @@ -544,24 +514,14 @@ export class KeyedColumnsRowIndexer { // Does not mutate any internal // returns an array of indexes in rows given to preFilter - makeGroupAndSortIndirector = ( - preFilteredRowPairs: FilteredRows | null, - columns: CustomColumnProps[] - ) => { + makeGroupAndSortIndirector = (preFilteredRowPairs: FilteredRows | null, columns: CustomColumnProps[]) => { if (!preFilteredRowPairs) { return null; } - const codedColumns = !this.sortingState - ? null - : codedColumnsFromKeyAndDirection(this.sortingState, columns); + const codedColumns = !this.sortingState ? null : codedColumnsFromKeyAndDirection(this.sortingState, columns); const groupingColumnsCount = this.groupingCount; - const indexedArray = groupAndSort( - preFilteredRowPairs, - codedColumns, - groupingColumnsCount, - columns - ); + const indexedArray = groupAndSort(preFilteredRowPairs, codedColumns, groupingColumnsCount, columns); return !indexedArray ? null : indexedArray.map((k) => k[1]); }; @@ -598,8 +558,7 @@ export class KeyedColumnsRowIndexer { this.lastUsedRank = 1; } else { const wasAtIdx = keyAndDirections.findIndex((p) => p[0] === colKey); - const wasFuzzyDir = - wasAtIdx < 0 ? 0 : keyAndDirections[wasAtIdx][1]; + const wasFuzzyDir = wasAtIdx < 0 ? 0 : keyAndDirections[wasAtIdx][1]; const wasSignDir = giveDirSignFor(wasFuzzyDir); if (change_way === ChangeWays.SIMPLE) { @@ -616,10 +575,7 @@ export class KeyedColumnsRowIndexer { this.sortingState?.splice(wasAtIdx, 1); } const nextSign = wasSignDir ? -wasSignDir : 1; - const nextKD: [string, string | undefined] = [ - colKey, - canonicalForSign(nextSign), - ]; + const nextKD: [string, string | undefined] = [colKey, canonicalForSign(nextSign)]; this.sortingState?.unshift(nextKD); } } else if (change_way === ChangeWays.TAIL) { @@ -629,9 +585,7 @@ export class KeyedColumnsRowIndexer { return false; } else if (!(this.isThreeState && wasSignDir === -1)) { // @ts-ignore could be null but hard to handle with such accesses - this.sortingState[wasAtIdx][1] = canonicalForSign( - -wasSignDir - ); + this.sortingState[wasAtIdx][1] = canonicalForSign(-wasSignDir); } else { this.sortingState?.splice(wasAtIdx, 1); } @@ -643,10 +597,7 @@ export class KeyedColumnsRowIndexer { ) { return false; } - this.sortingState?.splice(this.lastUsedRank - 1, 0, [ - colKey, - canonicalForSign(1), - ]); + this.sortingState?.splice(this.lastUsedRank - 1, 0, [colKey, canonicalForSign(1)]); } else if (!(this.isThreeState && wasSignDir === -1)) { // @ts-ignore could be null but hard to handle with such accesses this.sortingState[wasAtIdx][1] = canonicalForSign(-wasSignDir); @@ -700,11 +651,7 @@ export class KeyedColumnsRowIndexer { return colFilter[isForUser ? 'userParams' : 'outerParams']; }; - setColFilterParams = ( - colKey: string | null, - params: any[] | null, - isForUser: boolean - ) => { + setColFilterParams = (colKey: string | null, params: any[] | null, isForUser: boolean) => { if (!colKey) { if (params) { throw new Error('column key has to be defined'); @@ -718,8 +665,7 @@ export class KeyedColumnsRowIndexer { if (!this.byColFilter) { this.byColFilter = {}; } - let colFilter: { userParams?: any[]; outerParams?: any[] } = - this.byColFilter[colKey]; + let colFilter: { userParams?: any[]; outerParams?: any[] } = this.byColFilter[colKey]; if (!colFilter) { colFilter = {}; this.byColFilter[colKey] = colFilter; diff --git a/src/components/MuiVirtualizedTable/MuiVirtualizedTable.tsx b/src/components/MuiVirtualizedTable/MuiVirtualizedTable.tsx index ed434e3a..5dcc6b88 100644 --- a/src/components/MuiVirtualizedTable/MuiVirtualizedTable.tsx +++ b/src/components/MuiVirtualizedTable/MuiVirtualizedTable.tsx @@ -8,49 +8,18 @@ /** * This class has been taken from 'Virtualized Table' example at https://material-ui.com/components/tables/ */ -import { - createRef, - PureComponent, - ReactElement, - ReactNode, - MouseEvent, - KeyboardEvent, - MutableRefObject, -} from 'react'; +import { createRef, PureComponent, ReactElement, ReactNode, MouseEvent, KeyboardEvent, MutableRefObject } from 'react'; import { FormattedMessage } from 'react-intl'; import clsx from 'clsx'; import memoize from 'memoize-one'; -import { - Autocomplete, - Chip, - IconButton, - Popover, - SxProps, - TableCell, - TextField, -} from '@mui/material'; +import { Autocomplete, Chip, IconButton, Popover, SxProps, TableCell, TextField } from '@mui/material'; import { styled } from '@mui/system'; import { GetApp as GetAppIcon } from '@mui/icons-material'; -import { - AutoSizer, - Column, - ColumnProps, - RowMouseEventHandlerParams, - Table, - TableCellProps, -} from 'react-virtualized'; +import { AutoSizer, Column, ColumnProps, RowMouseEventHandlerParams, Table, TableCellProps } from 'react-virtualized'; import CsvDownloader from 'react-csv-downloader'; import { OverflowableText } from '../OverflowableText/overflowable-text'; -import { - makeComposeClasses, - toNestedGlobalSelectors, -} from '../../utils/styles'; -import { - ChangeWays, - collectibleHelper, - getHelper, - KeyedColumnsRowIndexer, -} from './KeyedColumnsRowIndexer'; +import { makeComposeClasses, toNestedGlobalSelectors } from '../../utils/styles'; +import { ChangeWays, collectibleHelper, getHelper, KeyedColumnsRowIndexer } from './KeyedColumnsRowIndexer'; import { ColumnHeader } from './ColumnHeader'; function getTextWidth(text: any): number { @@ -126,8 +95,7 @@ const defaultTooltipSx = { }; //TODO do we need to export this to clients (index.js) ? -export const generateMuiVirtualizedTableClass = (className: string) => - `MuiVirtualizedTable-${className}`; +export const generateMuiVirtualizedTableClass = (className: string) => `MuiVirtualizedTable-${className}`; const composeClasses = makeComposeClasses(generateMuiVirtualizedTableClass); interface AmongChooserProps { @@ -156,14 +124,7 @@ const AmongChooser = (props: AmongChooserProps) => { renderInput={(props) => } renderTags={(val, getTagsProps) => { return val.map((code, index) => { - return ( - - ); + return ; }); }} /> @@ -208,10 +169,7 @@ export interface RowProps { notClickable?: boolean; } -const initIndexer = ( - props: CustomColumnProps, - versionSetter: (version: number) => void -) => { +const initIndexer = (props: CustomColumnProps, versionSetter: (version: number) => void) => { if (!props.sortable) { return null; } @@ -254,9 +212,7 @@ const reorderIndex = memoize( }; } - const highestCodedColumn = !indexer - ? 0 - : indexer.highestCodedColumn(columns); + const highestCodedColumn = !indexer ? 0 : indexer.highestCodedColumn(columns); if (sortFromProps && highestCodedColumn) { const colIdx = Math.abs(highestCodedColumn) - 1; let reorderedIndex = sortFromProps( @@ -279,17 +235,8 @@ const reorderIndex = memoize( } } if (indexer) { - const prefiltered = preFilterData( - columns, - rows, - filterFromProps, - indexer, - indirectionVersion - ); - const reorderedIndex = indexer.makeGroupAndSortIndirector( - prefiltered, - columns - ); + const prefiltered = preFilterData(columns, rows, filterFromProps, indexer, indirectionVersion); + const reorderedIndex = indexer.makeGroupAndSortIndirector(prefiltered, columns); return makeIndexRecord(reorderedIndex, rows); } if (filterFromProps) { @@ -333,10 +280,7 @@ export interface MuiVirtualizedTableState { }; } -class MuiVirtualizedTable extends PureComponent< - MuiVirtualizedTableProps, - MuiVirtualizedTableState -> { +class MuiVirtualizedTable extends PureComponent { static defaultProps = { headerHeight: DEFAULT_HEADER_HEIGHT, rowHeight: DEFAULT_ROW_HEIGHT, @@ -363,10 +307,7 @@ class MuiVirtualizedTable extends PureComponent< rootMargin: '0px', threshold: 0.1, }; - this.observer = new IntersectionObserver( - this._computeHeaderSize, - options - ); + this.observer = new IntersectionObserver(this._computeHeaderSize, options); this.dropDownVisible = false; this.state = { headerHeight: this.props.headerHeight, @@ -383,10 +324,7 @@ class MuiVirtualizedTable extends PureComponent< }; componentDidUpdate(oldProps: MuiVirtualizedTableProps) { - if ( - oldProps.indexer !== this.props.indexer || - oldProps.sortable !== this.props.sortable - ) { + if (oldProps.indexer !== this.props.indexer || oldProps.sortable !== this.props.sortable) { this.setState((state) => { return { indexer: initIndexer(this.props, this.setVersion), @@ -433,10 +371,7 @@ class MuiVirtualizedTable extends PureComponent< /* calculate the header (and min size if exists) * NB : ignores the possible icons */ - let size = Math.max( - col.minWidth || 0, - this.computeDataWidth(col.label) - ); + let size = Math.max(col.minWidth || 0, this.computeDataWidth(col.label)); /* calculate for each row the width, and keep the max */ for (let i = 0; i < rows.length; ++i) { const gotRow = rowGetter(i); @@ -481,8 +416,7 @@ class MuiVirtualizedTable extends PureComponent< popoverAnchorEl: null, popoverColKey: null, deferredFilterChange: null, - indirectionVersion: - state.indirectionVersion + (bumpsVersion ? 1 : 0), + indirectionVersion: state.indirectionVersion + (bumpsVersion ? 1 : 0), }; }); }; @@ -525,9 +459,7 @@ class MuiVirtualizedTable extends PureComponent< setValue={(newVal) => { this.onFilterParamsChange(newVal, colKey); }} - onDropDownVisibility={(visible) => - (this.dropDownVisible = visible) - } + onDropDownVisibility={(visible) => (this.dropDownVisible = visible)} /> ); }; @@ -553,9 +485,7 @@ class MuiVirtualizedTable extends PureComponent< this.setState({ deferredFilterChange: { newVal: newVal, colKey }, }); - } else if ( - this.state.indexer?.setColFilterUserParams(colKey, nonEmpty) - ) { + } else if (this.state.indexer?.setColFilterUserParams(colKey, nonEmpty)) { this.setState({ indirectionVersion: this.state.indirectionVersion + 1, }); @@ -587,11 +517,7 @@ class MuiVirtualizedTable extends PureComponent< } }; - filterClickHandler = ( - _: MouseEvent, - target: Element | undefined, - columnIndex: number - ) => { + filterClickHandler = (_: MouseEvent, target: Element | undefined, columnIndex: number) => { // ColumnHeader to (header) TableCell const retargeted = target?.parentNode ?? target; @@ -600,13 +526,7 @@ class MuiVirtualizedTable extends PureComponent< this.openPopover(retargeted, colKey); }; - sortableHeader = ({ - label, - columnIndex, - }: { - label: string; - columnIndex: number; - }) => { + sortableHeader = ({ label, columnIndex }: { label: string; columnIndex: number }) => { const { columns } = this.props; const indexer = this.state.indexer; const colKey = columns[columnIndex].dataKey; @@ -614,22 +534,14 @@ class MuiVirtualizedTable extends PureComponent< const userParams = indexer?.getColFilterUserParams(colKey); const numeric = columns[columnIndex].numeric; - const prefiltered = preFilterData( - columns, - this.props.rows, - this.props.filter, - indexer, - indexer?.filterVersion - ); + const prefiltered = preFilterData(columns, this.props.rows, this.props.filter, indexer, indexer?.filterVersion); const colStat = prefiltered?.colsStats?.[colKey]; let filterLevel = 0; if (userParams?.length) { filterLevel += 1; if (!colStat?.seen) { filterLevel += 2; - } else if ( - userParams.filter((v: string) => !colStat.seen[v]).length - ) { + } else if (userParams.filter((v: string) => !colStat.seen[v]).length) { filterLevel += 2; } } @@ -651,10 +563,7 @@ class MuiVirtualizedTable extends PureComponent< sortSignedRank={signedRank} filterLevel={filterLevel} numeric={numeric ?? false} - onSortClick={( - ev: MouseEvent, - name?: Element - ) => { + onSortClick={(ev: MouseEvent, name?: Element) => { this.sortClickHandler(ev, name, columnIndex); }} onFilterClick={onFilterClick} @@ -687,64 +596,45 @@ class MuiVirtualizedTable extends PureComponent< composeClasses(classes, cssFlexContainer), index % 2 === 0 && composeClasses(classes, cssRowBackgroundDark), index % 2 !== 0 && composeClasses(classes, cssRowBackgroundLight), - rowGetter(index)?.notClickable === true && - composeClasses(classes, cssNoClick), // Allow to define a row as not clickable + rowGetter(index)?.notClickable === true && composeClasses(classes, cssNoClick), // Allow to define a row as not clickable { - [composeClasses(classes, cssTableRowHover)]: - index !== -1 && onRowClick != null, + [composeClasses(classes, cssTableRowHover)]: index !== -1 && onRowClick != null, } ); }; onClickableRowClick = (event: RowMouseEventHandlerParams) => { - if ( - event.rowData?.notClickable !== true || - event.event?.shiftKey || - event.event?.ctrlKey - ) { + if (event.rowData?.notClickable !== true || event.event?.shiftKey || event.event?.ctrlKey) { //@ts-ignore onRowClick is possibly undefined this.props.onRowClick(event); } }; cellRenderer = ({ cellData, columnIndex, rowIndex }: TableCellProps) => { - const { columns, classes, rowHeight, onCellClick, rows, tooltipSx } = - this.props; + const { columns, classes, rowHeight, onCellClick, rows, tooltipSx } = this.props; - let displayedValue = this.getDisplayValue( - columns[columnIndex], - cellData - ); + let displayedValue = this.getDisplayValue(columns[columnIndex], cellData); return ( { if ( onCellClick && @@ -772,10 +662,7 @@ class MuiVirtualizedTable extends PureComponent< displayedValue = cellData; } else if (isNaN(cellData)) { displayedValue = ''; - } else if ( - column.fractionDigits === undefined || - column.fractionDigits === 0 - ) { + } else if (column.fractionDigits === undefined || column.fractionDigits === 0) { displayedValue = Math.round(cellData); } else { displayedValue = Number(cellData).toFixed(column.fractionDigits); @@ -823,9 +710,7 @@ class MuiVirtualizedTable extends PureComponent< )} variant="head" style={{ height: this.state.headerHeight }} - align={ - columns[columnIndex].numeric || false ? 'right' : 'left' - } + align={columns[columnIndex].numeric || false ? 'right' : 'left'} ref={(e: Element) => this._registerObserver(e)} > {this.props.sortable && this.state.indexer @@ -867,23 +752,15 @@ class MuiVirtualizedTable extends PureComponent< this.onClickableRowClick } rowCount={reorderedIndex?.length ?? otherProps.rows.length} - rowClassName={({ index }) => - this.getRowClassName({ index, rowGetter }) - } + rowClassName={({ index }) => this.getRowClassName({ index, rowGetter })} rowGetter={({ index }) => rowGetter(index)} > {otherProps.columns.map(({ dataKey, ...other }, index) => { return ( { let tempHeaders: { displayName: string; id: string }[] = []; columns.forEach((col: CustomColumnProps) => { - if ( - exportCSVDataKeys !== undefined && - exportCSVDataKeys.find((el: string) => el === col.dataKey) - ) { + if (exportCSVDataKeys !== undefined && exportCSVDataKeys.find((el: string) => el === col.dataKey)) { tempHeaders.push({ displayName: col.label, id: col.dataKey, @@ -962,15 +835,8 @@ class MuiVirtualizedTable extends PureComponent< this.props.sort ); - const sizes = this.sizes( - this.props.columns, - this.props.rows, - rowGetter - ); - const csvHeaders = this.csvHeaders( - this.props.columns, - this.props.exportCSVDataKeys - ); + const sizes = this.sizes(this.props.columns, this.props.rows, rowGetter); + const csvHeaders = this.csvHeaders(this.props.columns, this.props.exportCSVDataKeys); return (
    - - + + @@ -1006,15 +865,7 @@ class MuiVirtualizedTable extends PureComponent< )}
    - {({ height, width }) => - this.makeSizedTable( - height, - width, - sizes, - viewIndexToModel, - rowGetter - ) - } + {({ height, width }) => this.makeSizedTable(height, width, sizes, viewIndexToModel, rowGetter)}
    {this.state.popoverAnchorEl && ( @@ -1041,9 +892,6 @@ class MuiVirtualizedTable extends PureComponent< } } -const nestedGlobalSelectorsStyles = toNestedGlobalSelectors( - defaultStyles, - generateMuiVirtualizedTableClass -); +const nestedGlobalSelectorsStyles = toNestedGlobalSelectors(defaultStyles, generateMuiVirtualizedTableClass); export default styled(MuiVirtualizedTable)(nestedGlobalSelectorsStyles); diff --git a/src/components/MuiVirtualizedTable/index.ts b/src/components/MuiVirtualizedTable/index.ts index e9eee2f3..f238d56d 100644 --- a/src/components/MuiVirtualizedTable/index.ts +++ b/src/components/MuiVirtualizedTable/index.ts @@ -5,8 +5,5 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -export { - default as MuiVirtualizedTable, - generateMuiVirtualizedTableClass, -} from './MuiVirtualizedTable'; +export { default as MuiVirtualizedTable, generateMuiVirtualizedTableClass } from './MuiVirtualizedTable'; export { KeyedColumnsRowIndexer, ChangeWays } from './KeyedColumnsRowIndexer'; diff --git a/src/components/MultipleSelectionDialog/MultipleSelectionDialog.tsx b/src/components/MultipleSelectionDialog/MultipleSelectionDialog.tsx index f2dce50e..1c1bb248 100644 --- a/src/components/MultipleSelectionDialog/MultipleSelectionDialog.tsx +++ b/src/components/MultipleSelectionDialog/MultipleSelectionDialog.tsx @@ -62,18 +62,11 @@ function MultipleSelectionDialog({ - } + label={} control={ } @@ -90,14 +83,8 @@ function MultipleSelectionDialog({ label={label} control={ - handleOptionSelection( - optionId - ) - } + checked={selectedIds.includes(optionId)} + onChange={() => handleOptionSelection(optionId)} /> } /> diff --git a/src/components/OverflowableText/overflowable-text.tsx b/src/components/OverflowableText/overflowable-text.tsx index cf313425..78847d72 100644 --- a/src/components/OverflowableText/overflowable-text.tsx +++ b/src/components/OverflowableText/overflowable-text.tsx @@ -4,14 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - ReactElement, - useCallback, - useLayoutEffect, - useMemo, - useRef, - useState, -} from 'react'; +import { ReactElement, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { Box, BoxProps, SxProps, Theme, Tooltip, styled } from '@mui/material'; import { Style } from 'node:util'; @@ -57,10 +50,7 @@ export const OverflowableText = styled( }: OverflowableTextProps) => { const element = useRef(); - const isMultiLine = useMemo( - () => maxLineCount && maxLineCount > 1, - [maxLineCount] - ); + const isMultiLine = useMemo(() => maxLineCount && maxLineCount > 1, [maxLineCount]); const [overflowed, setOverflowed] = useState(false); @@ -70,13 +60,9 @@ export const OverflowableText = styled( } if (isMultiLine) { - setOverflowed( - element.current.scrollHeight > element.current.clientHeight - ); + setOverflowed(element.current.scrollHeight > element.current.clientHeight); } else { - setOverflowed( - element.current.scrollWidth > element.current.clientWidth - ); + setOverflowed(element.current.scrollWidth > element.current.clientWidth); } }, [isMultiLine, setOverflowed, element]); @@ -114,11 +100,7 @@ export const OverflowableText = styled( {...props} ref={element} className={className} - sx={ - isMultiLine - ? multilineOverflowStyle(maxLineCount) - : overflowStyle.overflow - } + sx={isMultiLine ? multilineOverflowStyle(maxLineCount) : overflowStyle.overflow} > {children || text} diff --git a/src/components/ReportViewer/filter-button.tsx b/src/components/ReportViewer/filter-button.tsx index 14613766..1071b654 100644 --- a/src/components/ReportViewer/filter-button.tsx +++ b/src/components/ReportViewer/filter-button.tsx @@ -30,9 +30,7 @@ const styles = { export interface FilterButtonProps { selectedItems: Record; - setSelectedItems: ( - func: (items: Record) => Record - ) => void; + setSelectedItems: (func: (items: Record) => Record) => void; } /** @@ -42,10 +40,7 @@ export interface FilterButtonProps { * @param {Function} setSelectedItems - Setter needed to update the list underlying data */ -export function FilterButton({ - selectedItems, - setSelectedItems, -}: FilterButtonProps) { +export function FilterButton({ selectedItems, setSelectedItems }: FilterButtonProps) { const [initialState] = useState(selectedItems); const [anchorEl, setAnchorEl] = useState(null); @@ -67,9 +62,7 @@ export function FilterButton({ }; const isInitialStateModified = useMemo(() => { - return Object.keys(selectedItems).some( - (key) => initialState[key] !== selectedItems[key] - ); + return Object.keys(selectedItems).some((key) => initialState[key] !== selectedItems[key]); }, [initialState, selectedItems]); return ( diff --git a/src/components/ReportViewer/log-report-item.ts b/src/components/ReportViewer/log-report-item.ts index 37a7e068..f3a05614 100644 --- a/src/components/ReportViewer/log-report-item.ts +++ b/src/components/ReportViewer/log-report-item.ts @@ -16,35 +16,22 @@ export default class LogReportItem { log: string; - static resolveTemplateMessage( - templateMessage: string, - templateValues: Record - ) { + static resolveTemplateMessage(templateMessage: string, templateValues: Record) { const templateVars: Record = {}; Object.entries(templateValues).forEach(([key, value]) => { templateVars[key] = value.value; }); - return templateMessage.replace( - /\${([^{}]*)}/g, - function resolveTemplate(a, b) { - const r = templateVars[b]; - return typeof r === 'string' || typeof r === 'number' - ? r.toString() - : a; - } - ); + return templateMessage.replace(/\${([^{}]*)}/g, function resolveTemplate(a, b) { + const r = templateVars[b]; + return typeof r === 'string' || typeof r === 'number' ? r.toString() : a; + }); } constructor(jsonReport: SubReport, reportId: string) { this.key = jsonReport.reportKey; - this.log = LogReportItem.resolveTemplateMessage( - jsonReport.defaultMessage, - jsonReport.values - ); + this.log = LogReportItem.resolveTemplateMessage(jsonReport.defaultMessage, jsonReport.values); this.reportId = reportId; - this.severity = LogReportItem.initSeverity( - jsonReport.values.reportSeverity as unknown as ReportValue - ); + this.severity = LogReportItem.initSeverity(jsonReport.values.reportSeverity as unknown as ReportValue); } getLog() { @@ -78,9 +65,7 @@ export default class LogReportItem { } Object.values(LogSeverities).some((value) => { - const severityFound = (jsonSeverity.value as string).includes( - value.name - ); + const severityFound = (jsonSeverity.value as string).includes(value.name); if (severityFound) { severity = value; } diff --git a/src/components/ReportViewer/log-report.ts b/src/components/ReportViewer/log-report.ts index cbffeb9b..c10b0111 100644 --- a/src/components/ReportViewer/log-report.ts +++ b/src/components/ReportViewer/log-report.ts @@ -27,10 +27,7 @@ export default class LogReport { constructor(jsonReporter: Report, parentReportId?: string) { this.id = uuid4(); this.key = jsonReporter.taskKey; - this.title = LogReportItem.resolveTemplateMessage( - jsonReporter.defaultName, - jsonReporter.taskValues - ); + this.title = LogReportItem.resolveTemplateMessage(jsonReporter.defaultName, jsonReporter.taskValues); this.subReports = []; this.logs = []; this.parentReportId = parentReportId; @@ -54,23 +51,16 @@ export default class LogReport { } getAllLogs(): LogReportItem[] { - return this.getLogs().concat( - this.getSubReports().flatMap((r) => r.getAllLogs()) - ); + return this.getLogs().concat(this.getSubReports().flatMap((r) => r.getAllLogs())); } init(jsonReporter: Report) { - jsonReporter.subReporters.map((value) => - this.subReports.push(new LogReport(value, this.id)) - ); - jsonReporter.reports.map((value) => - this.logs.push(new LogReportItem(value, this.id)) - ); + jsonReporter.subReporters.map((value) => this.subReports.push(new LogReport(value, this.id))); + jsonReporter.reports.map((value) => this.logs.push(new LogReportItem(value, this.id))); } getHighestSeverity(currentSeverity = LogSeverities.UNKNOWN): LogSeverity { - const reduceFct = (p: LogSeverity, c: LogSeverity) => - p.level < c.level ? c : p; + const reduceFct = (p: LogSeverity, c: LogSeverity) => (p.level < c.level ? c : p); const highestSeverity = this.getLogs() .map((r) => r.getSeverity()) diff --git a/src/components/ReportViewer/log-table.tsx b/src/components/ReportViewer/log-table.tsx index 86945628..49335a32 100644 --- a/src/components/ReportViewer/log-table.tsx +++ b/src/components/ReportViewer/log-table.tsx @@ -26,8 +26,7 @@ const styles = { // https://github.com/bvaughn/react-virtualized/issues/454 '& .ReactVirtualized__Table__headerRow': { flip: false, - paddingRight: - theme.direction === 'rtl' ? '0 !important' : undefined, + paddingRight: theme.direction === 'rtl' ? '0 !important' : undefined, }, }), header: { variant: 'header' }, @@ -39,17 +38,10 @@ export interface LogTableProps { logs: LogReportItem[]; onRowClick: (data: any) => void; selectedSeverity: Record; - setSelectedSeverity: ( - func: (items: Record) => Record - ) => void; + setSelectedSeverity: (func: (items: Record) => Record) => void; } -function LogTable({ - logs, - onRowClick, - selectedSeverity, - setSelectedSeverity, -}: LogTableProps) { +function LogTable({ logs, onRowClick, selectedSeverity, setSelectedSeverity }: LogTableProps) { const intl = useIntl(); const theme = useTheme(); @@ -75,26 +67,17 @@ function LogTable({ const COLUMNS_DEFINITIONS = [ { - label: intl - .formatMessage({ id: 'report_viewer/severity' }) - .toUpperCase(), + label: intl.formatMessage({ id: 'report_viewer/severity' }).toUpperCase(), id: 'severity', dataKey: 'severity', width: SEVERITY_COLUMN_FIXED_WIDTH, maxWidth: SEVERITY_COLUMN_FIXED_WIDTH, minWidth: SEVERITY_COLUMN_FIXED_WIDTH, cellRenderer: severityCellRender, - extra: ( - - ), + extra: , }, { - label: intl - .formatMessage({ id: 'report_viewer/message' }) - .toUpperCase(), + label: intl.formatMessage({ id: 'report_viewer/message' }).toUpperCase(), id: 'message', dataKey: 'message', width: SEVERITY_COLUMN_FIXED_WIDTH, @@ -142,10 +125,7 @@ function LogTable({ const filter = useCallback( (row: { severity: any }) => { return ( - row.severity && - Object.entries(selectedSeverity).some( - ([key, value]) => key === row.severity && value - ) + row.severity && Object.entries(selectedSeverity).some(([key, value]) => key === row.severity && value) ); }, [selectedSeverity] diff --git a/src/components/ReportViewer/multi-select-list.tsx b/src/components/ReportViewer/multi-select-list.tsx index 2522cc3a..8a061b91 100644 --- a/src/components/ReportViewer/multi-select-list.tsx +++ b/src/components/ReportViewer/multi-select-list.tsx @@ -5,14 +5,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - Checkbox, - CheckboxProps, - FormControlLabel, - Menu, - MenuItem, - MenuProps, -} from '@mui/material'; +import { Checkbox, CheckboxProps, FormControlLabel, Menu, MenuItem, MenuProps } from '@mui/material'; const styles = { label: { @@ -40,12 +33,7 @@ export interface MultiSelectListProps { * @param {Object} anchor - Determines where the menu will appear on screen */ -export function MultiSelectList({ - selectedItems, - handleChange, - handleClose, - anchor, -}: MultiSelectListProps) { +export function MultiSelectList({ selectedItems, handleChange, handleClose, anchor }: MultiSelectListProps) { const open = Boolean(anchor); return ( @@ -53,13 +41,7 @@ export function MultiSelectList({ return ( - } + control={} label={key} sx={styles.label} /> diff --git a/src/components/ReportViewer/report-item.tsx b/src/components/ReportViewer/report-item.tsx index d65bbf3b..c320bbf2 100644 --- a/src/components/ReportViewer/report-item.tsx +++ b/src/components/ReportViewer/report-item.tsx @@ -34,19 +34,16 @@ const styles = { color: 'var(--tree-view-color)', }, // same as mui v4 behavior on label text only right after clicking in contrast to after moving away with arrow keys. - '&.Mui-selected .MuiTreeItem-label:hover, &.Mui-selected.Mui-focused .MuiTreeItem-label': - { - borderRadius: theme.spacing(2), - backgroundColor: alpha( - theme.palette.primary.main, - theme.palette.action.selectedOpacity + - theme.palette.action.hoverOpacity - ), - }, - '&.Mui-focused .MuiTreeItem-label, &:hover .MuiTreeItem-label, &Mui-selected .MuiTreeItem-label': - { - backgroundColor: 'transparent', - }, + '&.Mui-selected .MuiTreeItem-label:hover, &.Mui-selected.Mui-focused .MuiTreeItem-label': { + borderRadius: theme.spacing(2), + backgroundColor: alpha( + theme.palette.primary.main, + theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity + ), + }, + '&.Mui-focused .MuiTreeItem-label, &:hover .MuiTreeItem-label, &Mui-selected .MuiTreeItem-label': { + backgroundColor: 'transparent', + }, }), group: (theme: Theme) => ({ marginLeft: '10px', @@ -108,13 +105,7 @@ function ReportItem(props: PropsWithChildren) { '& .MuiTreeItem-label': styles.label, }} label={ - +
  • diff --git a/src/components/dialogs/description-modification-dialog.tsx b/src/components/dialogs/description-modification-dialog.tsx index da796f36..2db39941 100644 --- a/src/components/dialogs/description-modification-dialog.tsx +++ b/src/components/dialogs/description-modification-dialog.tsx @@ -20,16 +20,11 @@ export interface IDescriptionModificationDialog { description: string; open: boolean; onClose: () => void; - updateElement: ( - uuid: string, - data: Record - ) => Promise; + updateElement: (uuid: string, data: Record) => Promise; } const schema = yup.object().shape({ - [FieldConstants.DESCRIPTION]: yup - .string() - .max(500, 'descriptionLimitError'), + [FieldConstants.DESCRIPTION]: yup.string().max(500, 'descriptionLimitError'), }); function DescriptionModificationDialog({ @@ -62,8 +57,7 @@ function DescriptionModificationDialog({ const onSubmit = useCallback( (data: { description: string }) => { updateElement(elementUuid, { - [FieldConstants.DESCRIPTION]: - data[FieldConstants.DESCRIPTION].trim(), + [FieldConstants.DESCRIPTION]: data[FieldConstants.DESCRIPTION].trim(), }).catch((error: any) => { snackError({ messageTxt: error.message, diff --git a/src/components/dialogs/modify-element-selection.tsx b/src/components/dialogs/modify-element-selection.tsx index dee56b09..3a873683 100644 --- a/src/components/dialogs/modify-element-selection.tsx +++ b/src/components/dialogs/modify-element-selection.tsx @@ -47,11 +47,7 @@ function ModifyElementSelection(props: ModifyElementSelectionProps) { useEffect(() => { if (directory) { fetchDirectoryElementPath(directory).then((res: any) => { - setActiveDirectoryName( - res - .map((element: any) => element.elementName.trim()) - .join('/') - ); + setActiveDirectoryName(res.map((element: any) => element.elementName.trim()).join('/')); }); } }, [directory]); diff --git a/src/components/dialogs/popup-confirmation-dialog.tsx b/src/components/dialogs/popup-confirmation-dialog.tsx index 26ed036d..a3166667 100644 --- a/src/components/dialogs/popup-confirmation-dialog.tsx +++ b/src/components/dialogs/popup-confirmation-dialog.tsx @@ -30,13 +30,8 @@ function PopupConfirmationDialog({ handlePopupConfirmation, }: PopupConfirmationDialogProps) { return ( - - - Confirmation - + + Confirmation diff --git a/src/components/filter/criteria-based/criteria-based-filter-edition-dialog.tsx b/src/components/filter/criteria-based/criteria-based-filter-edition-dialog.tsx index bb86f2e1..d3e2b1bf 100644 --- a/src/components/filter/criteria-based/criteria-based-filter-edition-dialog.tsx +++ b/src/components/filter/criteria-based/criteria-based-filter-edition-dialog.tsx @@ -5,21 +5,12 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - Dispatch, - SetStateAction, - useCallback, - useEffect, - useState, -} from 'react'; +import { Dispatch, SetStateAction, useCallback, useEffect, useState } from 'react'; import { useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import { UUID } from 'crypto'; import FieldConstants from '../../../utils/field-constants'; -import { - backToFrontTweak, - frontToBackTweak, -} from './criteria-based-filter-utils'; +import { backToFrontTweak, frontToBackTweak } from './criteria-based-filter-utils'; import CustomMuiDialog from '../../dialogs/custom-mui-dialog'; import { useSnackMessage } from '../../../hooks/useSnackMessage'; import { criteriaBasedFilterSchema } from './criteria-based-filter-form'; @@ -63,9 +54,7 @@ interface CriteriaBasedFilterEditionDialogProps { broadcastChannel: BroadcastChannel; getFilterById: (id: string) => Promise; selectionForCopy: SelectionCopy; - setSelelectionForCopy: ( - selection: SelectionCopy - ) => Dispatch>; + setSelelectionForCopy: (selection: SelectionCopy) => Dispatch>; activeDirectory?: UUID; elementExists?: ElementExistsType; language?: string; @@ -110,8 +99,7 @@ function CriteriaBasedFilterEditionDialog({ setDataFetchStatus(FetchStatus.FETCH_SUCCESS); reset({ [FieldConstants.NAME]: name, - [FieldConstants.FILTER_TYPE]: - FilterType.CRITERIA_BASED.id, + [FieldConstants.FILTER_TYPE]: FilterType.CRITERIA_BASED.id, ...backToFrontTweak(response), }); }) @@ -127,10 +115,7 @@ function CriteriaBasedFilterEditionDialog({ const onSubmit = useCallback( (filterForm: any) => { - saveFilter( - frontToBackTweak(id, filterForm), - filterForm[FieldConstants.NAME] - ) + saveFilter(frontToBackTweak(id, filterForm), filterForm[FieldConstants.NAME]) .then(() => { if (selectionForCopy.sourceItemUuid === id) { setSelelectionForCopy(noSelectionForCopy); @@ -145,13 +130,7 @@ function CriteriaBasedFilterEditionDialog({ }); }); }, - [ - broadcastChannel, - id, - selectionForCopy.sourceItemUuid, - snackError, - setSelelectionForCopy, - ] + [broadcastChannel, id, selectionForCopy.sourceItemUuid, snackError, setSelelectionForCopy] ); const isDataReady = dataFetchStatus === FetchStatus.FETCH_SUCCESS; @@ -169,12 +148,7 @@ function CriteriaBasedFilterEditionDialog({ isDataFetching={dataFetchStatus === FetchStatus.FETCHING} language={language} > - {isDataReady && ( - - )} + {isDataReady && } ); } diff --git a/src/components/filter/criteria-based/criteria-based-filter-form.tsx b/src/components/filter/criteria-based/criteria-based-filter-form.tsx index ab9ca4fa..f21b7481 100644 --- a/src/components/filter/criteria-based/criteria-based-filter-form.tsx +++ b/src/components/filter/criteria-based/criteria-based-filter-form.tsx @@ -5,16 +5,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Grid from '@mui/material/Grid'; -import FilterProperties, { - filterPropertiesYupSchema, -} from './filter-properties'; +import FilterProperties, { filterPropertiesYupSchema } from './filter-properties'; import FieldConstants from '../../../utils/field-constants'; import yup from '../../../utils/yup-config'; import CriteriaBasedForm from './criteria-based-form'; -import { - getCriteriaBasedFormData, - getCriteriaBasedSchema, -} from './criteria-based-filter-utils'; +import { getCriteriaBasedFormData, getCriteriaBasedSchema } from './criteria-based-filter-utils'; import { FILTER_EQUIPMENTS } from '../utils/filter-form-utils'; import { FreePropertiesTypes } from './filter-free-properties'; @@ -34,11 +29,7 @@ function CriteriaBasedFilterForm() { diff --git a/src/components/filter/criteria-based/criteria-based-filter-utils.ts b/src/components/filter/criteria-based/criteria-based-filter-utils.ts index a1e9a1f4..05c0eb27 100644 --- a/src/components/filter/criteria-based/criteria-based-filter-utils.ts +++ b/src/components/filter/criteria-based/criteria-based-filter-utils.ts @@ -6,12 +6,7 @@ */ import FieldConstants from '../../../utils/field-constants'; -import { - PROPERTY_NAME, - PROPERTY_VALUES, - PROPERTY_VALUES_1, - PROPERTY_VALUES_2, -} from './filter-property'; +import { PROPERTY_NAME, PROPERTY_VALUES, PROPERTY_VALUES_1, PROPERTY_VALUES_2 } from './filter-property'; import { FilterType } from '../constants/filter-constants'; import { PredefinedProperties } from '../../../utils/types'; import yup from '../../../utils/yup-config'; @@ -34,36 +29,26 @@ export const getCriteriaBasedSchema = (extraFields: any) => ({ ...extraFields, }), }); -export const getCriteriaBasedFormData = ( - criteriaValues: any, - extraFields: any -) => ({ +export const getCriteriaBasedFormData = (criteriaValues: any, extraFields: any) => ({ [FieldConstants.CRITERIA_BASED]: { - [FieldConstants.COUNTRIES]: - criteriaValues?.[FieldConstants.COUNTRIES] ?? [], - [FieldConstants.COUNTRIES_1]: - criteriaValues?.[FieldConstants.COUNTRIES_1] ?? [], - [FieldConstants.COUNTRIES_2]: - criteriaValues?.[FieldConstants.COUNTRIES_2] ?? [], + [FieldConstants.COUNTRIES]: criteriaValues?.[FieldConstants.COUNTRIES] ?? [], + [FieldConstants.COUNTRIES_1]: criteriaValues?.[FieldConstants.COUNTRIES_1] ?? [], + [FieldConstants.COUNTRIES_2]: criteriaValues?.[FieldConstants.COUNTRIES_2] ?? [], ...getRangeInputDataForm( FieldConstants.NOMINAL_VOLTAGE, - criteriaValues?.[FieldConstants.NOMINAL_VOLTAGE] ?? - DEFAULT_RANGE_VALUE + criteriaValues?.[FieldConstants.NOMINAL_VOLTAGE] ?? DEFAULT_RANGE_VALUE ), ...getRangeInputDataForm( FieldConstants.NOMINAL_VOLTAGE_1, - criteriaValues?.[FieldConstants.NOMINAL_VOLTAGE_1] ?? - DEFAULT_RANGE_VALUE + criteriaValues?.[FieldConstants.NOMINAL_VOLTAGE_1] ?? DEFAULT_RANGE_VALUE ), ...getRangeInputDataForm( FieldConstants.NOMINAL_VOLTAGE_2, - criteriaValues?.[FieldConstants.NOMINAL_VOLTAGE_2] ?? - DEFAULT_RANGE_VALUE + criteriaValues?.[FieldConstants.NOMINAL_VOLTAGE_2] ?? DEFAULT_RANGE_VALUE ), ...getRangeInputDataForm( FieldConstants.NOMINAL_VOLTAGE_3, - criteriaValues?.[FieldConstants.NOMINAL_VOLTAGE_3] ?? - DEFAULT_RANGE_VALUE + criteriaValues?.[FieldConstants.NOMINAL_VOLTAGE_3] ?? DEFAULT_RANGE_VALUE ), ...extraFields, }, @@ -127,55 +112,33 @@ export const backToFrontTweak = (response: any) => { }); const ret = { - [FieldConstants.EQUIPMENT_TYPE]: - response[FieldConstants.EQUIPMENT_TYPE], + [FieldConstants.EQUIPMENT_TYPE]: response[FieldConstants.EQUIPMENT_TYPE], ...getCriteriaBasedFormData(response.equipmentFilterForm, { - [FieldConstants.ENERGY_SOURCE]: - response.equipmentFilterForm[FieldConstants.ENERGY_SOURCE], - [FreePropertiesTypes.SUBSTATION_FILTER_PROPERTIES]: - filterSubstationProperties, + [FieldConstants.ENERGY_SOURCE]: response.equipmentFilterForm[FieldConstants.ENERGY_SOURCE], + [FreePropertiesTypes.SUBSTATION_FILTER_PROPERTIES]: filterSubstationProperties, [FreePropertiesTypes.FREE_FILTER_PROPERTIES]: filterFreeProperties, }), }; return ret; }; -function isNominalVoltageEmpty( - nominalVoltage: Record -): boolean { - return ( - nominalVoltage[FieldConstants.VALUE_1] === null && - nominalVoltage[FieldConstants.VALUE_2] === null - ); +function isNominalVoltageEmpty(nominalVoltage: Record): boolean { + return nominalVoltage[FieldConstants.VALUE_1] === null && nominalVoltage[FieldConstants.VALUE_2] === null; } // The server expect them to be null if the user don't fill them, unlike contingency list function cleanNominalVoltages(formValues: any) { const cleanedFormValues = { ...formValues }; - if ( - isNominalVoltageEmpty(cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE]) - ) { + if (isNominalVoltageEmpty(cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE])) { cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE] = null; } - if ( - isNominalVoltageEmpty( - cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_1] - ) - ) { + if (isNominalVoltageEmpty(cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_1])) { cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_1] = null; } - if ( - isNominalVoltageEmpty( - cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_2] - ) - ) { + if (isNominalVoltageEmpty(cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_2])) { cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_2] = null; } - if ( - isNominalVoltageEmpty( - cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_3] - ) - ) { + if (isNominalVoltageEmpty(cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_3])) { cleanedFormValues[FieldConstants.NOMINAL_VOLTAGE_3] = null; } return cleanedFormValues; @@ -194,9 +157,7 @@ function cleanNominalVoltages(formValues: any) { */ export const frontToBackTweak = (id?: string, filter?: any) => { const filterSubstationProperties = - filter[FieldConstants.CRITERIA_BASED][ - FreePropertiesTypes.SUBSTATION_FILTER_PROPERTIES - ]; + filter[FieldConstants.CRITERIA_BASED][FreePropertiesTypes.SUBSTATION_FILTER_PROPERTIES]; const ret = { id, type: FilterType.CRITERIA_BASED.id, @@ -230,10 +191,7 @@ export const frontToBackTweak = (id?: string, filter?: any) => { eff.freeProperties1 = props1; eff.freeProperties2 = props2; - const filterFreeProperties = - filter[FieldConstants.CRITERIA_BASED][ - FreePropertiesTypes.FREE_FILTER_PROPERTIES - ]; + const filterFreeProperties = filter[FieldConstants.CRITERIA_BASED][FreePropertiesTypes.FREE_FILTER_PROPERTIES]; // in the back end we store everything in a field called equipmentFilterForm delete eff[FreePropertiesTypes.FREE_FILTER_PROPERTIES]; const freeProps: any = {}; diff --git a/src/components/filter/criteria-based/criteria-based-form.tsx b/src/components/filter/criteria-based/criteria-based-form.tsx index c60be383..7746dc1e 100644 --- a/src/components/filter/criteria-based/criteria-based-form.tsx +++ b/src/components/filter/criteria-based/criteria-based-form.tsx @@ -19,10 +19,7 @@ export interface CriteriaBasedFormProps { defaultValues: Record; } -function CriteriaBasedForm({ - equipments, - defaultValues, -}: CriteriaBasedFormProps) { +function CriteriaBasedForm({ equipments, defaultValues }: CriteriaBasedFormProps) { const { getValues, setValue } = useFormContext(); const { snackError } = useSnackMessage(); @@ -39,18 +36,12 @@ function CriteriaBasedForm({ }, [snackError, equipments, watchEquipmentType]); const openConfirmationPopup = () => { - return ( - JSON.stringify(getValues(FieldConstants.CRITERIA_BASED)) !== - JSON.stringify(defaultValues) - ); + return JSON.stringify(getValues(FieldConstants.CRITERIA_BASED)) !== JSON.stringify(defaultValues); }; const handleResetOnConfirmation = () => { Object.keys(defaultValues).forEach((field) => - setValue( - `${FieldConstants.CRITERIA_BASED}.${field}`, - defaultValues[field] - ) + setValue(`${FieldConstants.CRITERIA_BASED}.${field}`, defaultValues[field]) ); }; @@ -70,17 +61,15 @@ function CriteriaBasedForm({
    {watchEquipmentType && equipments[watchEquipmentType] && - equipments[watchEquipmentType].fields.map( - (equipment: any, index: number) => { - const EquipmentForm = equipment.renderer; - const uniqueKey = `${watchEquipmentType}-${index}`; - return ( - - - - ); - } - )} + equipments[watchEquipmentType].fields.map((equipment: any, index: number) => { + const EquipmentForm = equipment.renderer; + const uniqueKey = `${watchEquipmentType}-${index}`; + return ( + + + + ); + })} ); } diff --git a/src/components/filter/criteria-based/filter-free-properties.tsx b/src/components/filter/criteria-based/filter-free-properties.tsx index 18bac83f..0bb11fc8 100644 --- a/src/components/filter/criteria-based/filter-free-properties.tsx +++ b/src/components/filter/criteria-based/filter-free-properties.tsx @@ -33,16 +33,12 @@ interface FilterFreePropertiesProps { predefined: PredefinedProperties; } -function FilterFreeProperties({ - freePropertiesType, - predefined, -}: FilterFreePropertiesProps) { +function FilterFreeProperties({ freePropertiesType, predefined }: FilterFreePropertiesProps) { const watchEquipmentType = useWatch({ name: FieldConstants.EQUIPMENT_TYPE, }); const isForLineOrHvdcLineSubstation = - (watchEquipmentType === Line.type || - watchEquipmentType === Hvdc.type) && + (watchEquipmentType === Line.type || watchEquipmentType === Hvdc.type) && freePropertiesType === FreePropertiesTypes.SUBSTATION_FILTER_PROPERTIES; const fieldName = `${FieldConstants.CRITERIA_BASED}.${freePropertiesType}`; @@ -75,17 +71,13 @@ function FilterFreeProperties({ : [{ name: PROPERTY_VALUES, label: 'PropertyValues' }]; const title = useMemo(() => { - return freePropertiesType === FreePropertiesTypes.FREE_FILTER_PROPERTIES - ? 'FreeProps' - : 'SubstationFreeProps'; + return freePropertiesType === FreePropertiesTypes.FREE_FILTER_PROPERTIES ? 'FreeProps' : 'SubstationFreeProps'; }, [freePropertiesType]); return ( <> - - {(formattedTitle) =>

    {formattedTitle}

    } -
    + {(formattedTitle) =>

    {formattedTitle}

    }
    {filterProperties.map((prop, index) => ( diff --git a/src/components/filter/criteria-based/filter-properties.tsx b/src/components/filter/criteria-based/filter-properties.tsx index 7bcf089d..ebd98780 100644 --- a/src/components/filter/criteria-based/filter-properties.tsx +++ b/src/components/filter/criteria-based/filter-properties.tsx @@ -22,15 +22,8 @@ import { import { areArrayElementsUnique } from '../../../utils/functions'; import FieldConstants from '../../../utils/field-constants'; import yup from '../../../utils/yup-config'; -import FilterFreeProperties, { - FreePropertiesTypes, -} from './filter-free-properties'; -import { - PROPERTY_NAME, - PROPERTY_VALUES, - PROPERTY_VALUES_1, - PROPERTY_VALUES_2, -} from './filter-property'; +import FilterFreeProperties, { FreePropertiesTypes } from './filter-free-properties'; +import { PROPERTY_NAME, PROPERTY_VALUES, PROPERTY_VALUES_1, PROPERTY_VALUES_2 } from './filter-property'; import usePredefinedProperties from '../../../hooks/predefined-properties-hook'; import { FilterType } from '../constants/filter-constants'; @@ -47,8 +40,7 @@ function propertyValuesTest( return true; } const equipmentType = rootLevelForm.value[FieldConstants.EQUIPMENT_TYPE]; - const isForLineOrHvdcLine = - equipmentType === Line.type || equipmentType === Hvdc.type; + const isForLineOrHvdcLine = equipmentType === Line.type || equipmentType === Hvdc.type; if (doublePropertyValues) { return isForLineOrHvdcLine ? values?.length! > 0 : true; } @@ -64,50 +56,36 @@ export const filterPropertiesYupSchema = { [PROPERTY_VALUES]: yup .array() .of(yup.string()) - .test( - 'can not be empty if not line', - 'YupRequired', - (values, context) => - propertyValuesTest(values, context, false) + .test('can not be empty if not line', 'YupRequired', (values, context) => + propertyValuesTest(values, context, false) ), [PROPERTY_VALUES_1]: yup .array() .of(yup.string()) - .test( - 'can not be empty if line', - 'YupRequired', - (values, context) => - propertyValuesTest(values, context, true) + .test('can not be empty if line', 'YupRequired', (values, context) => + propertyValuesTest(values, context, true) ), [PROPERTY_VALUES_2]: yup .array() .of(yup.string()) - .test( - 'can not be empty if line', - 'YupRequired', - (values, context) => - propertyValuesTest(values, context, true) + .test('can not be empty if line', 'YupRequired', (values, context) => + propertyValuesTest(values, context, true) ), }) ) - .test( - 'distinct names', - 'filterPropertiesNameUniquenessError', - (properties, context) => { - // with context.from[length - 1], we can access to the root fields of the form - const rootLevelForm = context.from![context.from!.length - 1]; - const filterType = - rootLevelForm.value[FieldConstants.FILTER_TYPE]; - if (filterType !== FilterType.CRITERIA_BASED.id) { - // we don't test if we are not in a criteria based form - return true; - } - const names = properties! // never null / undefined - .filter((prop) => !!prop[PROPERTY_NAME]) - .map((prop) => prop[PROPERTY_NAME]); - return areArrayElementsUnique(names); + .test('distinct names', 'filterPropertiesNameUniquenessError', (properties, context) => { + // with context.from[length - 1], we can access to the root fields of the form + const rootLevelForm = context.from![context.from!.length - 1]; + const filterType = rootLevelForm.value[FieldConstants.FILTER_TYPE]; + if (filterType !== FilterType.CRITERIA_BASED.id) { + // we don't test if we are not in a criteria based form + return true; } - ), + const names = properties! // never null / undefined + .filter((prop) => !!prop[PROPERTY_NAME]) + .map((prop) => prop[PROPERTY_NAME]); + return areArrayElementsUnique(names); + }), [FreePropertiesTypes.FREE_FILTER_PROPERTIES]: yup .array() .of( @@ -116,42 +94,32 @@ export const filterPropertiesYupSchema = { [PROPERTY_VALUES]: yup .array() .of(yup.string()) - .test( - 'can not be empty if not line', - 'YupRequired', - (values, context) => - propertyValuesTest(values, context, false) + .test('can not be empty if not line', 'YupRequired', (values, context) => + propertyValuesTest(values, context, false) ), }) ) - .test( - 'distinct names', - 'filterPropertiesNameUniquenessError', - (properties, context) => { - // with context.from[length - 1], we can access to the root fields of the form - const rootLevelForm = context.from![context.from!.length - 1]; - const filterType = - rootLevelForm.value[FieldConstants.FILTER_TYPE]; - if (filterType !== FilterType.CRITERIA_BASED.id) { - // we don't test if we are not in a criteria based form - return true; - } - const names = properties! // never null / undefined - .filter((prop) => !!prop[PROPERTY_NAME]) - .map((prop) => prop[PROPERTY_NAME]); - return areArrayElementsUnique(names); + .test('distinct names', 'filterPropertiesNameUniquenessError', (properties, context) => { + // with context.from[length - 1], we can access to the root fields of the form + const rootLevelForm = context.from![context.from!.length - 1]; + const filterType = rootLevelForm.value[FieldConstants.FILTER_TYPE]; + if (filterType !== FilterType.CRITERIA_BASED.id) { + // we don't test if we are not in a criteria based form + return true; } - ), + const names = properties! // never null / undefined + .filter((prop) => !!prop[PROPERTY_NAME]) + .map((prop) => prop[PROPERTY_NAME]); + return areArrayElementsUnique(names); + }), }; function FilterProperties() { const watchEquipmentType = useWatch({ name: FieldConstants.EQUIPMENT_TYPE, }); - const [equipmentPredefinedProps, setEquipmentType] = - usePredefinedProperties(watchEquipmentType); - const [substationPredefinedProps, setSubstationType] = - usePredefinedProperties(null); + const [equipmentPredefinedProps, setEquipmentType] = usePredefinedProperties(watchEquipmentType); + const [substationPredefinedProps, setSubstationType] = usePredefinedProperties(null); const displayEquipmentProperties = useMemo(() => { return ( @@ -167,10 +135,7 @@ function FilterProperties() { }, [watchEquipmentType]); const displaySubstationProperties = useMemo(() => { - return ( - watchEquipmentType !== Substation.type && - watchEquipmentType !== null - ); + return watchEquipmentType !== Substation.type && watchEquipmentType !== null; }, [watchEquipmentType]); useEffect(() => { @@ -188,22 +153,16 @@ function FilterProperties() { watchEquipmentType && ( - - {(txt) =>

    {txt}

    } -
    + {(txt) =>

    {txt}

    }
    {displayEquipmentProperties && ( )} {displaySubstationProperties && ( )} diff --git a/src/components/filter/criteria-based/filter-property.tsx b/src/components/filter/criteria-based/filter-property.tsx index fb9182ed..140f8269 100644 --- a/src/components/filter/criteria-based/filter-property.tsx +++ b/src/components/filter/criteria-based/filter-property.tsx @@ -29,8 +29,7 @@ interface FilterPropertyProps { } function FilterProperty(props: FilterPropertyProps) { - const { propertyType, index, predefined, valuesFields, handleDelete } = - props; + const { propertyType, index, predefined, valuesFields, handleDelete } = props; const { setValue } = useFormContext(); const watchName = useWatch({ @@ -52,10 +51,7 @@ function FilterProperty(props: FilterPropertyProps) { // We reset values when name change const onNameChange = useCallback(() => { valuesFields.forEach((valuesField) => - setValue( - `${FieldConstants.CRITERIA_BASED}.${propertyType}[${index}].${valuesField.name}`, - [] - ) + setValue(`${FieldConstants.CRITERIA_BASED}.${propertyType}[${index}].${valuesField.name}`, []) ); }, [setValue, index, valuesFields, propertyType]); diff --git a/src/components/filter/expert/expert-filter-constants.ts b/src/components/filter/expert/expert-filter-constants.ts index 3a2655d2..3d21a5e8 100644 --- a/src/components/filter/expert/expert-filter-constants.ts +++ b/src/components/filter/expert/expert-filter-constants.ts @@ -6,12 +6,7 @@ */ import { Field } from 'react-querybuilder'; -import { - CombinatorType, - DataType, - FieldType, - OperatorType, -} from './expert-filter.type'; +import { CombinatorType, DataType, FieldType, OperatorType } from './expert-filter.type'; export enum RULES { EMPTY_RULE = 'emptyRule', @@ -1042,12 +1037,7 @@ export const FIELDS_OPTIONS = { }; export const fields: Record = { - SUBSTATION: [ - FIELDS_OPTIONS.ID, - FIELDS_OPTIONS.NAME, - FIELDS_OPTIONS.COUNTRY, - FIELDS_OPTIONS.PROPERTY, - ], + SUBSTATION: [FIELDS_OPTIONS.ID, FIELDS_OPTIONS.NAME, FIELDS_OPTIONS.COUNTRY, FIELDS_OPTIONS.PROPERTY], VOLTAGE_LEVEL: [ FIELDS_OPTIONS.ID, FIELDS_OPTIONS.NAME, diff --git a/src/components/filter/expert/expert-filter-edition-dialog.tsx b/src/components/filter/expert/expert-filter-edition-dialog.tsx index 41a839b1..967c291e 100644 --- a/src/components/filter/expert/expert-filter-edition-dialog.tsx +++ b/src/components/filter/expert/expert-filter-edition-dialog.tsx @@ -88,11 +88,8 @@ function ExpertFilterEditionDialog({ reset({ [FieldConstants.NAME]: name, [FieldConstants.FILTER_TYPE]: FilterType.EXPERT.id, - [FieldConstants.EQUIPMENT_TYPE]: - response[FieldConstants.EQUIPMENT_TYPE], - [EXPERT_FILTER_QUERY]: importExpertRules( - response[EXPERT_FILTER_QUERY] - ), + [FieldConstants.EQUIPMENT_TYPE]: response[FieldConstants.EQUIPMENT_TYPE], + [EXPERT_FILTER_QUERY]: importExpertRules(response[EXPERT_FILTER_QUERY]), }); }) .catch((error: { message: any }) => { @@ -129,14 +126,7 @@ function ExpertFilterEditionDialog({ }); } }, - [ - broadcastChannel, - id, - onClose, - selectionForCopy.sourceItemUuid, - snackError, - setSelectionForCopy, - ] + [broadcastChannel, id, onClose, selectionForCopy.sourceItemUuid, snackError, setSelectionForCopy] ); const isDataReady = dataFetchStatus === FetchStatus.FETCH_SUCCESS; @@ -154,12 +144,7 @@ function ExpertFilterEditionDialog({ isDataFetching={dataFetchStatus === FetchStatus.FETCHING} language={language} > - {isDataReady && ( - - )} + {isDataReady && } ); } diff --git a/src/components/filter/expert/expert-filter-form.tsx b/src/components/filter/expert/expert-filter-form.tsx index 1083dc2c..133d2fce 100644 --- a/src/components/filter/expert/expert-filter-form.tsx +++ b/src/components/filter/expert/expert-filter-form.tsx @@ -71,8 +71,7 @@ export const expertFilterSchema = { is: FilterType.EXPERT.id, then: (schema: yup.Schema) => schema.when([FieldConstants.EQUIPMENT_TYPE], { - is: (equipmentType: string) => - isSupportedEquipmentType(equipmentType), + is: (equipmentType: string) => isSupportedEquipmentType(equipmentType), then: rqbQuerySchemaValidator, }), }), @@ -139,13 +138,9 @@ function ExpertFilterForm() { validateButtonLabel="button.changeType" />
    - {watchEquipmentType && - isSupportedEquipmentType(watchEquipmentType) && ( - - )} + {watchEquipmentType && isSupportedEquipmentType(watchEquipmentType) && ( + + )}
    ); } diff --git a/src/components/filter/expert/expert-filter-utils.ts b/src/components/filter/expert/expert-filter-utils.ts index 6b6ad0e9..5c53e41b 100644 --- a/src/components/filter/expert/expert-filter-utils.ts +++ b/src/components/filter/expert/expert-filter-utils.ts @@ -30,16 +30,8 @@ import { RuleGroupTypeExport, RuleTypeExport, } from './expert-filter.type'; -import { - FIELDS_OPTIONS, - OPERATOR_OPTIONS, - RULES, -} from './expert-filter-constants'; -import { - isBlankOrEmpty, - microUnitToUnit, - unitToMicroUnit, -} from '../../../utils/conversion-utils'; +import { FIELDS_OPTIONS, OPERATOR_OPTIONS, RULES } from './expert-filter-constants'; +import { isBlankOrEmpty, microUnitToUnit, unitToMicroUnit } from '../../../utils/conversion-utils'; const microUnits = [ FieldType.SHUNT_CONDUCTANCE_1, @@ -86,18 +78,14 @@ const getFieldData = (fieldName: string) => { */ const getDataType = (fieldName: string, operator: string) => { // particular case => set dataType to FILTER_UUID when exporting rule with operator IS_PART_OF or IS_NOT_PART_OF - if ( - operator === OPERATOR_OPTIONS.IS_PART_OF.name || - operator === OPERATOR_OPTIONS.IS_NOT_PART_OF.name - ) { + if (operator === OPERATOR_OPTIONS.IS_PART_OF.name || operator === OPERATOR_OPTIONS.IS_NOT_PART_OF.name) { return DataType.FILTER_UUID; } // particular case => set dataType to BOOLEAN when exporting composite rule REMOTE_REGULATED_TERMINAL with operator EXISTS or NOT_EXISTS if ( fieldName === FieldType.REMOTE_REGULATED_TERMINAL && - (operator === OPERATOR_OPTIONS.EXISTS.name || - operator === OPERATOR_OPTIONS.NOT_EXISTS.name) + (operator === OPERATOR_OPTIONS.EXISTS.name || operator === OPERATOR_OPTIONS.NOT_EXISTS.name) ) { return DataType.BOOLEAN; } @@ -109,9 +97,7 @@ const getDataType = (fieldName: string, operator: string) => { }; export const getOperators = (fieldName: string, intl: IntlShape) => { - const field = Object.values(FIELDS_OPTIONS).find( - (fieldOption) => fieldOption.name === fieldName - ); + const field = Object.values(FIELDS_OPTIONS).find((fieldOption) => fieldOption.name === fieldName); switch (field?.dataType) { case DataType.STRING: { @@ -138,9 +124,7 @@ export const getOperators = (fieldName: string, intl: IntlShape) => { if (field.name === FieldType.ID) { // When the ID is selected, the operators EXISTS and NOT_EXISTS must be removed. stringOperators = stringOperators.filter( - (operator) => - operator !== OPERATOR_OPTIONS.EXISTS && - operator !== OPERATOR_OPTIONS.NOT_EXISTS + (operator) => operator !== OPERATOR_OPTIONS.EXISTS && operator !== OPERATOR_OPTIONS.NOT_EXISTS ); } return stringOperators.map((operator) => ({ @@ -171,10 +155,7 @@ export const getOperators = (fieldName: string, intl: IntlShape) => { // particular case if (field.name === FieldType.AUTOMATE) { // take only EXISTS and NOT_EXISTS - booleanOperators = [ - OPERATOR_OPTIONS.EXISTS, - OPERATOR_OPTIONS.NOT_EXISTS, - ]; + booleanOperators = [OPERATOR_OPTIONS.EXISTS, OPERATOR_OPTIONS.NOT_EXISTS]; } return booleanOperators.map((operator) => ({ name: operator.name, @@ -193,9 +174,7 @@ export const getOperators = (fieldName: string, intl: IntlShape) => { field.name === FieldType.SVAR_REGULATION_MODE ) { // When one of above field is selected, the operator IN must be removed. - enumOperators = enumOperators.filter( - (operator) => operator !== OPERATOR_OPTIONS.IN - ); + enumOperators = enumOperators.filter((operator) => operator !== OPERATOR_OPTIONS.IN); } return enumOperators.map((operator) => ({ name: operator.name, @@ -239,9 +218,7 @@ function changeValueUnit(value: any, field: FieldType) { } export function exportExpertRules(query: RuleGroupType): RuleGroupTypeExport { - function transformRule( - rule: RuleType - ): RuleTypeExport | RuleGroupTypeExport { + function transformRule(rule: RuleType): RuleTypeExport | RuleGroupTypeExport { const isValueAnArray = Array.isArray(rule.value); const dataType = getDataType(rule.field, rule.operator) as DataType; @@ -257,9 +234,8 @@ export function exportExpertRules(query: RuleGroupType): RuleGroupTypeExport { field: rule.field as FieldType, operator: dataType !== DataType.PROPERTY - ? (Object.values(OPERATOR_OPTIONS).find( - (operator) => operator.name === rule.operator - )?.customName as OperatorType) + ? (Object.values(OPERATOR_OPTIONS).find((operator) => operator.name === rule.operator) + ?.customName as OperatorType) : rule.value.propertyOperator, value: !isValueAnArray && @@ -273,29 +249,20 @@ export function exportExpertRules(query: RuleGroupType): RuleGroupTypeExport { ? changeValueUnit(rule.value, rule.field as FieldType) : undefined, dataType, - propertyName: - dataType === DataType.PROPERTY - ? rule.value.propertyName - : undefined, - propertyValues: - dataType === DataType.PROPERTY - ? rule.value.propertyValues - : undefined, + propertyName: dataType === DataType.PROPERTY ? rule.value.propertyName : undefined, + propertyValues: dataType === DataType.PROPERTY ? rule.value.propertyValues : undefined, }; } - function transformCompositeRule( - compositeRule: RuleType - ): RuleGroupTypeExport { + function transformCompositeRule(compositeRule: RuleType): RuleGroupTypeExport { const compositeGroup = compositeRule.value as CompositeGroup; - const transformedRules = Object.entries(compositeGroup.rules).map( - ([field, rule]) => - transformRule({ - ...rule, - field, - operator: rule.operator, - value: rule.value, - }) + const transformedRules = Object.entries(compositeGroup.rules).map(([field, rule]) => + transformRule({ + ...rule, + field, + operator: rule.operator, + value: rule.value, + }) ); return { @@ -304,9 +271,8 @@ export function exportExpertRules(query: RuleGroupType): RuleGroupTypeExport { dataType: DataType.COMBINATOR, rules: transformedRules, // two additional attributes to distinct a composite rule from a normal rule group - operator: Object.values(OPERATOR_OPTIONS).find( - (operator) => operator.name === compositeRule.operator - )?.customName as OperatorType, + operator: Object.values(OPERATOR_OPTIONS).find((operator) => operator.name === compositeRule.operator) + ?.customName as OperatorType, field: compositeRule.field as FieldType, }; } @@ -346,17 +312,13 @@ export function importExpertRules(query: RuleGroupTypeExport): RuleGroupType { return rule.values .map((value) => parseFloat(value as string)) .map((numberValue) => { - return microUnits.includes(rule.field) - ? unitToMicroUnit(numberValue)! - : numberValue; + return microUnits.includes(rule.field) ? unitToMicroUnit(numberValue)! : numberValue; }) .sort((a, b) => a - b); } return rule.values.sort(); } - return microUnits.includes(rule.field) - ? unitToMicroUnit(parseFloat(rule.value as string)) - : rule.value; + return microUnits.includes(rule.field) ? unitToMicroUnit(parseFloat(rule.value as string)) : rule.value; } function transformRule(rule: RuleTypeExport): RuleType { @@ -365,9 +327,8 @@ export function importExpertRules(query: RuleGroupTypeExport): RuleGroupType { field: rule.field, operator: rule.dataType !== DataType.PROPERTY - ? (Object.values(OPERATOR_OPTIONS).find( - (operator) => operator.customName === rule.operator - )?.name as string) + ? (Object.values(OPERATOR_OPTIONS).find((operator) => operator.customName === rule.operator) + ?.name as string) : OPERATOR_OPTIONS.IS.name, value: parseValue(rule), }; @@ -390,9 +351,8 @@ export function importExpertRules(query: RuleGroupTypeExport): RuleGroupType { return { id: group.id, field: group.field as FieldType, - operator: Object.values(OPERATOR_OPTIONS).find( - (operator) => operator.customName === group.operator - )?.name as string, + operator: Object.values(OPERATOR_OPTIONS).find((operator) => operator.customName === group.operator) + ?.name as string, value: { combinator: group.combinator, rules: transformedRules, @@ -431,11 +391,7 @@ export function countRules(query: RuleGroupTypeAny): number { if ('rules' in query) { const group = query as RuleGroupType; - return group.rules.reduce( - (sum, ruleOrGroup) => - sum + countRules(ruleOrGroup as RuleGroupTypeAny), - 0 - ); + return group.rules.reduce((sum, ruleOrGroup) => sum + countRules(ruleOrGroup as RuleGroupTypeAny), 0); } return 1; } @@ -457,8 +413,7 @@ export const queryValidator: QueryValidator = (query) => { if ( rule.id && - (rule.operator === OPERATOR_OPTIONS.EXISTS.name || - rule.operator === OPERATOR_OPTIONS.NOT_EXISTS.name) + (rule.operator === OPERATOR_OPTIONS.EXISTS.name || rule.operator === OPERATOR_OPTIONS.NOT_EXISTS.name) ) { // In the case of (NOT_)EXISTS operator, because we do not have a second value to evaluate, we force a valid result. result[rule.id] = { @@ -471,10 +426,7 @@ export const queryValidator: QueryValidator = (query) => { valid: false, reasons: [RULES.EMPTY_RULE], }; - } else if ( - Number.isNaN(parseFloat(rule.value[0])) || - Number.isNaN(parseFloat(rule.value[1])) - ) { + } else if (Number.isNaN(parseFloat(rule.value[0])) || Number.isNaN(parseFloat(rule.value[1]))) { result[rule.id] = { valid: false, reasons: [RULES.INCORRECT_RULE], @@ -485,29 +437,17 @@ export const queryValidator: QueryValidator = (query) => { reasons: [RULES.BETWEEN_RULE], }; } - } else if ( - rule.id && - rule.operator === OPERATOR_OPTIONS.IN.name && - !rule.value?.length - ) { + } else if (rule.id && rule.operator === OPERATOR_OPTIONS.IN.name && !rule.value?.length) { result[rule.id] = { valid: false, reasons: [RULES.EMPTY_RULE], }; - } else if ( - rule.id && - isStringInput && - (rule.value || '').trim() === '' - ) { + } else if (rule.id && isStringInput && (rule.value || '').trim() === '') { result[rule.id] = { valid: false, reasons: [RULES.EMPTY_RULE], }; - } else if ( - rule.id && - isNumberInput && - Number.isNaN(parseFloat(rule.value)) - ) { + } else if (rule.id && isNumberInput && Number.isNaN(parseFloat(rule.value))) { result[rule.id] = { valid: false, reasons: [RULES.INCORRECT_RULE], @@ -535,9 +475,7 @@ export const queryValidator: QueryValidator = (query) => { }; } else if (rule.id && dataType === DataType.COMBINATOR) { // based on FIELDS_OPTIONS configuration and composite group, validate for each children composite rule in a composite group - const childrenFields = Object.keys( - getFieldData(rule.field).children ?? {} - ); + const childrenFields = Object.keys(getFieldData(rule.field).children ?? {}); const compositeGroup = rule.value as CompositeGroup; // call validate recursively @@ -599,15 +537,9 @@ export function getNumberOfSiblings(path: number[], query: RuleGroupTypeAny) { } // Remove a rule or group and its parents if they become empty -export function recursiveRemove( - query: RuleGroupTypeAny, - path: number[] -): RuleGroupTypeAny { +export function recursiveRemove(query: RuleGroupTypeAny, path: number[]): RuleGroupTypeAny { // If it's an only child, we also need to remove and check the parent group (but not the root) - if ( - getNumberOfSiblings(path, query) === 1 && - path.toString() !== [0].toString() - ) { + if (getNumberOfSiblings(path, query) === 1 && path.toString() !== [0].toString()) { return recursiveRemove(query, getParentPath(path)); } // Otherwise, we can safely remove it diff --git a/src/components/filter/expert/styles-expert-filter.css b/src/components/filter/expert/styles-expert-filter.css index c8099ab3..6b57ecd7 100644 --- a/src/components/filter/expert/styles-expert-filter.css +++ b/src/components/filter/expert/styles-expert-filter.css @@ -58,10 +58,11 @@ position: relative; } -.queryBuilder-branches .rule::before, .queryBuilder-branches .rule::after, +.queryBuilder-branches .rule::before, +.queryBuilder-branches .rule::after, .queryBuilder-branches .ruleGroup .ruleGroup::before, .queryBuilder-branches .ruleGroup .ruleGroup::after { - content: ""; + content: ''; width: 0.5rem; left: calc(-0.5rem - 1px); border-color: #969696; @@ -94,7 +95,8 @@ display: none; } -.queryBuilder-branches .ruleGroup .ruleGroup::before, .queryBuilder-branches .ruleGroup .ruleGroup::after { +.queryBuilder-branches .ruleGroup .ruleGroup::before, +.queryBuilder-branches .ruleGroup .ruleGroup::after { left: calc(calc(-0.5rem - 1px) - 1px); } @@ -133,25 +135,33 @@ } /* DnD section, copied from original, just 'border-bottom-color: lightgrey' change */ -[data-inlinecombinators=disabled] .dndOver.rule, [data-inlinecombinators=disabled] .dndOver.ruleGroup-header { +[data-inlinecombinators='disabled'] .dndOver.rule, +[data-inlinecombinators='disabled'] .dndOver.ruleGroup-header { border-bottom-width: 2px; border-bottom-style: dashed; border-bottom-color: lightgrey; padding-bottom: 0.5rem; } -[data-inlinecombinators=disabled] .dndOver.rule.dndCopy, [data-inlinecombinators=disabled] .dndOver.ruleGroup-header.dndCopy { +[data-inlinecombinators='disabled'] .dndOver.rule.dndCopy, +[data-inlinecombinators='disabled'] .dndOver.ruleGroup-header.dndCopy { border-bottom-color: #669933; } -[data-inlinecombinators=enabled] .dndOver.rule:last-child, [data-inlinecombinators=enabled] .dndOver.ruleGroup-header, [data-inlinecombinators=enabled] .dndOver.rule + .betweenRules, [data-inlinecombinators=enabled] .dndOver.betweenRules { +[data-inlinecombinators='enabled'] .dndOver.rule:last-child, +[data-inlinecombinators='enabled'] .dndOver.ruleGroup-header, +[data-inlinecombinators='enabled'] .dndOver.rule + .betweenRules, +[data-inlinecombinators='enabled'] .dndOver.betweenRules { border-bottom-width: 2px; border-bottom-style: dashed; border-bottom-color: lightgrey; padding-bottom: 0.5rem; } -[data-inlinecombinators=enabled] .dndOver.rule:last-child.dndCopy, [data-inlinecombinators=enabled] .dndOver.ruleGroup-header.dndCopy, [data-inlinecombinators=enabled] .dndOver.rule + .betweenRules.dndCopy, [data-inlinecombinators=enabled] .dndOver.betweenRules.dndCopy { +[data-inlinecombinators='enabled'] .dndOver.rule:last-child.dndCopy, +[data-inlinecombinators='enabled'] .dndOver.ruleGroup-header.dndCopy, +[data-inlinecombinators='enabled'] .dndOver.rule + .betweenRules.dndCopy, +[data-inlinecombinators='enabled'] .dndOver.betweenRules.dndCopy { border-bottom-color: #669933; } @@ -165,4 +175,4 @@ cursor: move; } -/* end DnD section */ \ No newline at end of file +/* end DnD section */ diff --git a/src/components/filter/explicit-naming/explicit-naming-filter-edition-dialog.tsx b/src/components/filter/explicit-naming/explicit-naming-filter-edition-dialog.tsx index 67220d88..7933b862 100644 --- a/src/components/filter/explicit-naming/explicit-naming-filter-edition-dialog.tsx +++ b/src/components/filter/explicit-naming/explicit-naming-filter-edition-dialog.tsx @@ -15,10 +15,7 @@ import { saveExplicitNamingFilter } from '../utils/filter-api'; import { useSnackMessage } from '../../../hooks/useSnackMessage'; import CustomMuiDialog from '../../dialogs/custom-mui-dialog'; import yup from '../../../utils/yup-config'; -import { - explicitNamingFilterSchema, - FILTER_EQUIPMENTS_ATTRIBUTES, -} from './explicit-naming-filter-form'; +import { explicitNamingFilterSchema, FILTER_EQUIPMENTS_ATTRIBUTES } from './explicit-naming-filter-form'; import FieldConstants from '../../../utils/field-constants'; import FilterForm from '../filter-form'; @@ -90,13 +87,9 @@ function ExplicitNamingFilterEditionDialog({ setDataFetchStatus(FetchStatus.FETCH_SUCCESS); reset({ [FieldConstants.NAME]: name, - [FieldConstants.FILTER_TYPE]: - FilterType.EXPLICIT_NAMING.id, - [FieldConstants.EQUIPMENT_TYPE]: - response[FieldConstants.EQUIPMENT_TYPE], - [FILTER_EQUIPMENTS_ATTRIBUTES]: response[ - FILTER_EQUIPMENTS_ATTRIBUTES - ].map((row: any) => ({ + [FieldConstants.FILTER_TYPE]: FilterType.EXPLICIT_NAMING.id, + [FieldConstants.EQUIPMENT_TYPE]: response[FieldConstants.EQUIPMENT_TYPE], + [FILTER_EQUIPMENTS_ATTRIBUTES]: response[FILTER_EQUIPMENTS_ATTRIBUTES].map((row: any) => ({ [FieldConstants.AG_GRID_ROW_UUID]: uuid4(), ...row, })), @@ -135,14 +128,7 @@ function ExplicitNamingFilterEditionDialog({ }); } }, - [ - broadcastChannel, - id, - selectionForCopy, - onClose, - snackError, - setSelectionForCopy, - ] + [broadcastChannel, id, selectionForCopy, onClose, snackError, setSelectionForCopy] ); const isDataReady = dataFetchStatus === FetchStatus.FETCH_SUCCESS; @@ -160,12 +146,7 @@ function ExplicitNamingFilterEditionDialog({ isDataFetching={dataFetchStatus === FetchStatus.FETCHING} language={language} > - {isDataReady && ( - - )} + {isDataReady && } ); } diff --git a/src/components/filter/explicit-naming/explicit-naming-filter-form.tsx b/src/components/filter/explicit-naming/explicit-naming-filter-form.tsx index 129974ad..40bb181e 100644 --- a/src/components/filter/explicit-naming/explicit-naming-filter-form.tsx +++ b/src/components/filter/explicit-naming/explicit-naming-filter-form.tsx @@ -45,46 +45,24 @@ export const explicitNamingFilterSchema = { }) ) // we remove empty lines - .compact( - (row) => !row[DISTRIBUTION_KEY] && !row[FieldConstants.EQUIPMENT_ID] - ) + .compact((row) => !row[DISTRIBUTION_KEY] && !row[FieldConstants.EQUIPMENT_ID]) .when([FieldConstants.FILTER_TYPE], { is: FilterType.EXPLICIT_NAMING.id, then: (schema) => - schema - .min(1, 'emptyFilterError') - .when([FieldConstants.EQUIPMENT_TYPE], { - is: (equipmentType: string) => - isGeneratorOrLoad(equipmentType), - then: (innerSchema) => - innerSchema - .test( - 'noKeyWithoutId', - 'distributionKeyWithMissingIdError', - (array) => { - return !array!.some( - (row) => - !row[ - FieldConstants.EQUIPMENT_ID - ] - ); - } - ) - .test( - 'ifOneKeyThenKeyEverywhere', - 'missingDistributionKeyError', - (array) => { - return !( - array!.some( - (row) => row[DISTRIBUTION_KEY] - ) && - array!.some( - (row) => !row[DISTRIBUTION_KEY] - ) - ); - } - ), - }), + schema.min(1, 'emptyFilterError').when([FieldConstants.EQUIPMENT_TYPE], { + is: (equipmentType: string) => isGeneratorOrLoad(equipmentType), + then: (innerSchema) => + innerSchema + .test('noKeyWithoutId', 'distributionKeyWithMissingIdError', (array) => { + return !array!.some((row) => !row[FieldConstants.EQUIPMENT_ID]); + }) + .test('ifOneKeyThenKeyEverywhere', 'missingDistributionKeyError', (array) => { + return !( + array!.some((row) => row[DISTRIBUTION_KEY]) && + array!.some((row) => !row[DISTRIBUTION_KEY]) + ); + }), + }), }), }; @@ -121,9 +99,7 @@ interface ExplicitNamingFilterFormProps { sourceFilterForExplicitNamingConversion?: FilterForExplicitConversionProps; } -function ExplicitNamingFilterForm({ - sourceFilterForExplicitNamingConversion, -}: ExplicitNamingFilterFormProps) { +function ExplicitNamingFilterForm({ sourceFilterForExplicitNamingConversion }: ExplicitNamingFilterFormProps) { const intl = useIntl(); const { snackError } = useSnackMessage(); @@ -134,10 +110,7 @@ function ExplicitNamingFilterForm({ }); useEffect(() => { - if ( - watchEquipmentType && - !((watchEquipmentType as EquipmentType) in FILTER_EQUIPMENTS) - ) { + if (watchEquipmentType && !((watchEquipmentType as EquipmentType) in FILTER_EQUIPMENTS)) { snackError({ headerId: 'obsoleteFilter', }); @@ -148,10 +121,7 @@ function ExplicitNamingFilterForm({ useEffect(() => { if (sourceFilterForExplicitNamingConversion) { - setValue( - FieldConstants.EQUIPMENT_TYPE, - sourceFilterForExplicitNamingConversion.equipmentType - ); + setValue(FieldConstants.EQUIPMENT_TYPE, sourceFilterForExplicitNamingConversion.equipmentType); } }, [sourceFilterForExplicitNamingConversion, setValue]); @@ -165,8 +135,7 @@ function ExplicitNamingFilterForm({ field: FieldConstants.EQUIPMENT_ID, editable: true, singleClickEdit: true, - valueParser: (params: ValueParserParams) => - params.newValue?.trim() ?? null, + valueParser: (params: ValueParserParams) => params.newValue?.trim() ?? null, }, ]; if (forGeneratorOrLoad) { @@ -190,13 +159,9 @@ function ExplicitNamingFilterForm({ ); const csvFileHeaders = useMemo(() => { - const newCsvFileHeaders = [ - intl.formatMessage({ id: FieldConstants.EQUIPMENT_ID }), - ]; + const newCsvFileHeaders = [intl.formatMessage({ id: FieldConstants.EQUIPMENT_ID })]; if (forGeneratorOrLoad) { - newCsvFileHeaders.push( - intl.formatMessage({ id: DISTRIBUTION_KEY }) - ); + newCsvFileHeaders.push(intl.formatMessage({ id: DISTRIBUTION_KEY })); } return newCsvFileHeaders; }, [intl, forGeneratorOrLoad]); @@ -216,8 +181,7 @@ function ExplicitNamingFilterForm({ const openConfirmationPopup = () => { return getValues(FILTER_EQUIPMENTS_ATTRIBUTES).some( - (row: FilterTableRow) => - row[DISTRIBUTION_KEY] || row[FieldConstants.EQUIPMENT_ID] + (row: FilterTableRow) => row[DISTRIBUTION_KEY] || row[FieldConstants.EQUIPMENT_ID] ); }; diff --git a/src/components/filter/filter-creation-dialog.tsx b/src/components/filter/filter-creation-dialog.tsx index 61edd14b..b9fa4fc8 100644 --- a/src/components/filter/filter-creation-dialog.tsx +++ b/src/components/filter/filter-creation-dialog.tsx @@ -9,11 +9,7 @@ import { useCallback } from 'react'; import { Resolver, useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import { UUID } from 'crypto'; -import { - saveCriteriaBasedFilter, - saveExpertFilter, - saveExplicitNamingFilter, -} from './utils/filter-api'; +import { saveCriteriaBasedFilter, saveExpertFilter, saveExplicitNamingFilter } from './utils/filter-api'; import { useSnackMessage } from '../../hooks/useSnackMessage'; import CustomMuiDialog from '../dialogs/custom-mui-dialog'; import { @@ -28,11 +24,7 @@ import { import FieldConstants from '../../utils/field-constants'; import yup from '../../utils/yup-config'; import FilterForm from './filter-form'; -import { - EXPERT_FILTER_QUERY, - expertFilterSchema, - getExpertFilterEmptyFormData, -} from './expert/expert-filter-form'; +import { EXPERT_FILTER_QUERY, expertFilterSchema, getExpertFilterEmptyFormData } from './expert/expert-filter-form'; import { FilterType } from './constants/filter-constants'; import { ElementExistsType } from '../../utils/ElementType'; @@ -51,9 +43,7 @@ const formSchema = yup .object() .shape({ [FieldConstants.NAME]: yup.string().trim().required('nameEmpty'), - [FieldConstants.DESCRIPTION]: yup - .string() - .max(500, 'descriptionLimitError'), + [FieldConstants.DESCRIPTION]: yup.string().max(500, 'descriptionLimitError'), [FieldConstants.FILTER_TYPE]: yup.string().required(), [FieldConstants.EQUIPMENT_TYPE]: yup.string().required(), ...criteriaBasedFilterSchema, @@ -98,10 +88,7 @@ function FilterCreationDialog({ const onSubmit = useCallback( (filterForm: any) => { - if ( - filterForm[FieldConstants.FILTER_TYPE] === - FilterType.EXPLICIT_NAMING.id - ) { + if (filterForm[FieldConstants.FILTER_TYPE] === FilterType.EXPLICIT_NAMING.id) { saveExplicitNamingFilter( filterForm[FILTER_EQUIPMENTS_ATTRIBUTES], true, @@ -117,23 +104,13 @@ function FilterCreationDialog({ onClose, activeDirectory ); - } else if ( - filterForm[FieldConstants.FILTER_TYPE] === - FilterType.CRITERIA_BASED.id - ) { - saveCriteriaBasedFilter( - filterForm, - activeDirectory, - onClose, - (error: any) => { - snackError({ - messageTxt: error, - }); - } - ); - } else if ( - filterForm[FieldConstants.FILTER_TYPE] === FilterType.EXPERT.id - ) { + } else if (filterForm[FieldConstants.FILTER_TYPE] === FilterType.CRITERIA_BASED.id) { + saveCriteriaBasedFilter(filterForm, activeDirectory, onClose, (error: any) => { + snackError({ + messageTxt: error, + }); + }); + } else if (filterForm[FieldConstants.FILTER_TYPE] === FilterType.EXPERT.id) { saveExpertFilter( null, filterForm[EXPERT_FILTER_QUERY], @@ -161,11 +138,7 @@ function FilterCreationDialog({ onSave={onSubmit} formSchema={formSchema} formMethods={formMethods} - titleId={ - sourceFilterForExplicitNamingConversion - ? 'convertIntoExplicitNamingFilter' - : 'createNewFilter' - } + titleId={sourceFilterForExplicitNamingConversion ? 'convertIntoExplicitNamingFilter' : 'createNewFilter'} removeOptional disabledSave={!!nameError || !!isValidating} language={language} @@ -174,9 +147,7 @@ function FilterCreationDialog({ creation activeDirectory={activeDirectory} elementExists={elementExists} - sourceFilterForExplicitNamingConversion={ - sourceFilterForExplicitNamingConversion - } + sourceFilterForExplicitNamingConversion={sourceFilterForExplicitNamingConversion} /> ); diff --git a/src/components/filter/filter-form.tsx b/src/components/filter/filter-form.tsx index 0d15f979..fcc3f23c 100644 --- a/src/components/filter/filter-form.tsx +++ b/src/components/filter/filter-form.tsx @@ -31,21 +31,13 @@ interface FilterFormProps { } function FilterForm(props: FilterFormProps) { - const { - sourceFilterForExplicitNamingConversion, - creation, - activeDirectory, - elementExists, - } = props; + const { sourceFilterForExplicitNamingConversion, creation, activeDirectory, elementExists } = props; const { setValue } = useFormContext(); const filterType = useWatch({ name: FieldConstants.FILTER_TYPE }); // We do this because setValue don't set the field dirty - const handleChange = ( - _event: React.ChangeEvent, - value: string - ) => { + const handleChange = (_event: React.ChangeEvent, value: string) => { setValue(FieldConstants.FILTER_TYPE, value); }; @@ -90,14 +82,10 @@ function FilterForm(props: FilterFormProps) { )} )} - {filterType === FilterType.CRITERIA_BASED.id && ( - - )} + {filterType === FilterType.CRITERIA_BASED.id && } {filterType === FilterType.EXPLICIT_NAMING.id && ( )} {filterType === FilterType.EXPERT.id && } diff --git a/src/components/filter/utils/filter-api.ts b/src/components/filter/utils/filter-api.ts index 3178e8d0..663dcda8 100644 --- a/src/components/filter/utils/filter-api.ts +++ b/src/components/filter/utils/filter-api.ts @@ -27,8 +27,7 @@ export const saveExplicitNamingFilter = ( ) => { // we remove unnecessary fields from the table let cleanedTableValues; - const isGeneratorOrLoad = - equipmentType === Generator.type || equipmentType === Load.type; + const isGeneratorOrLoad = equipmentType === Generator.type || equipmentType === Load.type; if (isGeneratorOrLoad) { cleanedTableValues = tableValues.map((row) => ({ [FieldConstants.EQUIPMENT_ID]: row[FieldConstants.EQUIPMENT_ID], @@ -85,13 +84,7 @@ export const saveCriteriaBasedFilter = ( token?: string ) => { const filterForBack = frontToBackTweak(undefined, filter); // no need ID for creation - createFilter( - filterForBack, - filter[FieldConstants.NAME], - filter[FieldConstants.DESCRIPTION], - activeDirectory, - token - ) + createFilter(filterForBack, filter[FieldConstants.NAME], filter[FieldConstants.DESCRIPTION], activeDirectory, token) .then(() => { onClose(); }) diff --git a/src/components/inputs/react-hook-form/ExpandingTextField.tsx b/src/components/inputs/react-hook-form/ExpandingTextField.tsx index 9022a05c..e749ca35 100644 --- a/src/components/inputs/react-hook-form/ExpandingTextField.tsx +++ b/src/components/inputs/react-hook-form/ExpandingTextField.tsx @@ -63,30 +63,18 @@ function ExpandingTextField({ resize: 'none', // or 'horizontal' for horizontal resizing }, }, - helperText: ( - {descriptionCounter} - ), + helperText: {descriptionCounter}, FormHelperTextProps: { sx: { ml: 'auto', - color: (theme: Theme) => - isOverTheLimit - ? theme.palette.error.main - : theme.palette.text.secondary, + color: (theme: Theme) => (isOverTheLimit ? theme.palette.error.main : theme.palette.text.secondary), }, }, ...(rowsToDisplay && { rows: rowsToDisplay }), ...(sx && { sx }), ...textFieldFormProps, }; - return ( - - ); + return ; } export default ExpandingTextField; diff --git a/src/components/inputs/react-hook-form/ag-grid-table/bottom-right-buttons.tsx b/src/components/inputs/react-hook-form/ag-grid-table/bottom-right-buttons.tsx index d661d1f2..a6d706a7 100644 --- a/src/components/inputs/react-hook-form/ag-grid-table/bottom-right-buttons.tsx +++ b/src/components/inputs/react-hook-form/ag-grid-table/bottom-right-buttons.tsx @@ -56,9 +56,7 @@ function BottomRightButtons({ {csvProps && ( - setUploaderOpen(true)} - > + setUploaderOpen(true)}> )} - + - + - + - + diff --git a/src/components/inputs/react-hook-form/ag-grid-table/cell-editors/numericEditor.ts b/src/components/inputs/react-hook-form/ag-grid-table/cell-editors/numericEditor.ts index 144747c5..e114920a 100644 --- a/src/components/inputs/react-hook-form/ag-grid-table/cell-editors/numericEditor.ts +++ b/src/components/inputs/react-hook-form/ag-grid-table/cell-editors/numericEditor.ts @@ -44,10 +44,7 @@ class NumericEditor implements ICellEditorComp { if (event.preventDefault) { event.preventDefault(); } - } else if ( - NumericEditor.isNavigationKey(event) || - NumericEditor.isBackspace(event) - ) { + } else if (NumericEditor.isNavigationKey(event) || NumericEditor.isBackspace(event)) { event.stopPropagation(); } }); @@ -55,9 +52,7 @@ class NumericEditor implements ICellEditorComp { // only start edit if key pressed is a number, not a letter // FM : I added ',' and '.' const isNotANumber = - params.eventKey && - params.eventKey.length === 1 && - '1234567890,.'.indexOf(params.eventKey) < 0; + params.eventKey && params.eventKey.length === 1 && '1234567890,.'.indexOf(params.eventKey) < 0; this.cancelBeforeStart = !!isNotANumber; } diff --git a/src/components/inputs/react-hook-form/ag-grid-table/csv-uploader/csv-uploader.tsx b/src/components/inputs/react-hook-form/ag-grid-table/csv-uploader/csv-uploader.tsx index 7b668501..f4c7e96d 100644 --- a/src/components/inputs/react-hook-form/ag-grid-table/csv-uploader/csv-uploader.tsx +++ b/src/components/inputs/react-hook-form/ag-grid-table/csv-uploader/csv-uploader.tsx @@ -53,8 +53,7 @@ function CsvUploader({ const intl = useIntl(); const { CSVReader } = useCSVReader(); const [importedData, setImportedData] = useState([]); - const [isConfirmationPopupOpen, setIsConfirmationPopupOpen] = - useState(false); + const [isConfirmationPopupOpen, setIsConfirmationPopupOpen] = useState(false); const data = useMemo(() => { const newData = [...[fileHeaders]]; @@ -77,9 +76,7 @@ function CsvUploader({ // validate the headers for (let i = 0; i < fileHeaders.length; i++) { if (fileHeaders[i] !== '' && rows[0][i] !== fileHeaders[i]) { - setCreateError( - intl.formatMessage({ id: 'wrongCsvHeadersError' }) - ); + setCreateError(intl.formatMessage({ id: 'wrongCsvHeadersError' })); return false; } } @@ -126,15 +123,8 @@ function CsvUploader({ (val) => val && Object.keys(val) - .filter( - (key) => key !== FieldConstants.AG_GRID_ROW_UUID - ) - .some( - (e) => - val[e] !== undefined && - val[e] !== null && - String(val[e]).trim().length > 0 - ) + .filter((key) => key !== FieldConstants.AG_GRID_ROW_UUID) + .some((e) => val[e] !== undefined && val[e] !== null && String(val[e]).trim().length > 0) ); if (isValuesInTable && getResultsFromImportedData().length > 0) { @@ -160,30 +150,17 @@ function CsvUploader({ }; const renderConfirmationCsvData = () => { return ( - - - Confirmation - + + Confirmation - - {intl.formatMessage({ id: 'keepCSVDataMessage' })} - + {intl.formatMessage({ id: 'keepCSVDataMessage' })} - - @@ -200,11 +177,7 @@ function CsvUploader({ - + @@ -219,21 +192,12 @@ function CsvUploader({ }} config={{ // We use | for multi values in one cell, then we remove it from the default value for this config, to avoid delimiter autodetection - delimitersToGuess: [ - ',', - ' ', - ';', - RECORD_SEP, - UNIT_SEP, - ], + delimitersToGuess: [',', ' ', ';', RECORD_SEP, UNIT_SEP], }} > {({ getRootProps, acceptedFile }: any) => ( - - {createError !== '' && ( - {createError} - )} + {createError !== '' && {createError}}

    diff --git a/src/components/inputs/react-hook-form/ag-grid-table/custom-ag-grid-table.tsx b/src/components/inputs/react-hook-form/ag-grid-table/custom-ag-grid-table.tsx index 564f33ca..97ae5c87 100644 --- a/src/components/inputs/react-hook-form/ag-grid-table/custom-ag-grid-table.tsx +++ b/src/components/inputs/react-hook-form/ag-grid-table/custom-ag-grid-table.tsx @@ -12,11 +12,7 @@ import 'ag-grid-community/styles/ag-grid.css'; import 'ag-grid-community/styles/ag-theme-alpine.css'; import { Grid, useTheme } from '@mui/material'; import { useIntl } from 'react-intl'; -import { - CellEditingStoppedEvent, - ColumnState, - SortChangedEvent, -} from 'ag-grid-community'; +import { CellEditingStoppedEvent, ColumnState, SortChangedEvent } from 'ag-grid-community'; import BottomRightButtons from './bottom-right-buttons'; import FieldConstants from '../../../../utils/field-constants'; @@ -79,8 +75,7 @@ const style = (customProps: any) => ({ }, '& .Mui-focused .MuiOutlinedInput-root': { // borders moves row height - outline: - 'var(--ag-borders-input) var(--ag-input-focus-border-color)', + outline: 'var(--ag-borders-input) var(--ag-input-focus-border-color)', outlineOffset: '-1px', backgroundColor: theme.agGridBackground.color, }, @@ -132,19 +127,12 @@ function CustomAgGridTable({ const rowData = watch(name); const isFirstSelected = Boolean( - rowData?.length && - gridApi?.api - .getRowNode(rowData[0][FieldConstants.AG_GRID_ROW_UUID]) - ?.isSelected() + rowData?.length && gridApi?.api.getRowNode(rowData[0][FieldConstants.AG_GRID_ROW_UUID])?.isSelected() ); const isLastSelected = Boolean( rowData?.length && - gridApi?.api - .getRowNode( - rowData[rowData.length - 1][FieldConstants.AG_GRID_ROW_UUID] - ) - ?.isSelected() + gridApi?.api.getRowNode(rowData[rowData.length - 1][FieldConstants.AG_GRID_ROW_UUID])?.isSelected() ); const noRowSelected = selectedRows.length === 0; @@ -152,9 +140,7 @@ function CustomAgGridTable({ const getIndex = useCallback( (val: any) => { return getValues(name).findIndex( - (row: any) => - row[FieldConstants.AG_GRID_ROW_UUID] === - val[FieldConstants.AG_GRID_ROW_UUID] + (row: any) => row[FieldConstants.AG_GRID_ROW_UUID] === val[FieldConstants.AG_GRID_ROW_UUID] ); }, [getValues, name] @@ -244,20 +230,13 @@ function CustomAgGridTable({ ); const onSortChanged = useCallback((event: SortChangedEvent) => { - const isAnycolumnhasSort = event.api - .getColumnState() - .some((col: ColumnState) => col.sort); + const isAnycolumnhasSort = event.api.getColumnState().some((col: ColumnState) => col.sort); setIsSortApplied(isAnycolumnhasSort); }, []); return ( - + - move(getIndex(e.node.data), e.overIndex) - } + onRowDragEnd={(e) => move(getIndex(e.node.data), e.overIndex)} suppressBrowserResizeObserver columnDefs={columnDefs} detailRowAutoHeight onSelectionChanged={() => { setSelectedRows(gridApi.api.getSelectedRows()); }} - onRowDataUpdated={ - newRowAdded ? onRowDataUpdated : undefined - } + onRowDataUpdated={newRowAdded ? onRowDataUpdated : undefined} onCellEditingStopped={onCellEditingStopped} onSortChanged={onSortChanged} - getRowId={(row) => - row.data[FieldConstants.AG_GRID_ROW_UUID] - } + getRowId={(row) => row.data[FieldConstants.AG_GRID_ROW_UUID]} pagination={pagination} paginationPageSize={paginationPageSize} suppressRowClickSelection={suppressRowClickSelection} alwaysShowVerticalScroll={alwaysShowVerticalScroll} - stopEditingWhenCellsLoseFocus={ - stopEditingWhenCellsLoseFocus - } + stopEditingWhenCellsLoseFocus={stopEditingWhenCellsLoseFocus} {...props} /> diff --git a/src/components/inputs/react-hook-form/autocomplete-inputs/autocomplete-input.tsx b/src/components/inputs/react-hook-form/autocomplete-inputs/autocomplete-input.tsx index 45d0f15a..97a2f6f4 100644 --- a/src/components/inputs/react-hook-form/autocomplete-inputs/autocomplete-input.tsx +++ b/src/components/inputs/react-hook-form/autocomplete-inputs/autocomplete-input.tsx @@ -5,31 +5,16 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - Autocomplete, - AutocompleteProps, - TextField, - TextFieldProps, -} from '@mui/material'; +import { Autocomplete, AutocompleteProps, TextField, TextFieldProps } from '@mui/material'; import { useController } from 'react-hook-form'; -import { - genHelperError, - genHelperPreviousValue, - identity, - isFieldRequired, -} from '../utils/functions'; +import { genHelperError, genHelperPreviousValue, identity, isFieldRequired } from '../utils/functions'; import FieldLabel from '../utils/field-label'; import useCustomFormContext from '../provider/use-custom-form-context'; import { Option } from '../../../../utils/types'; export interface AutocompleteInputProps extends Omit< - AutocompleteProps< - Option, - boolean | undefined, - boolean | undefined, - boolean | undefined - >, + AutocompleteProps, // we already defined them in our custom Autocomplete 'value' | 'onChange' | 'renderInput' > { @@ -42,10 +27,7 @@ export interface AutocompleteInputProps previousValue?: string; allowNewValue?: boolean; onChangeCallback?: () => void; - formProps?: Omit< - TextFieldProps, - 'value' | 'onChange' | 'inputRef' | 'inputProps' | 'InputProps' - >; + formProps?: Omit; } function AutocompleteInput({ @@ -61,8 +43,7 @@ function AutocompleteInput({ formProps, ...props }: AutocompleteInputProps) { - const { validationSchema, getValues, removeOptional } = - useCustomFormContext(); + const { validationSchema, getValues, removeOptional } = useCustomFormContext(); const { field: { onChange, value, ref }, fieldState: { error }, @@ -77,10 +58,7 @@ function AutocompleteInput({ } // otherwise, we check if user input matches with one of the options - const matchingOption = options.find( - (option: Option) => - typeof option !== 'string' && option.id === newValue - ); + const matchingOption = options.find((option: Option) => typeof option !== 'string' && option.id === newValue); // if it does, we send the matching option to react hook form if (matchingOption) { onChange(outputTransform(matchingOption)); @@ -111,11 +89,7 @@ function AutocompleteInput({ label: FieldLabel({ label, optional: - !isFieldRequired( - name, - validationSchema, - getValues() - ) && + !isFieldRequired(name, validationSchema, getValues()) && !props?.disabled && !removeOptional, }), diff --git a/src/components/inputs/react-hook-form/autocomplete-inputs/multiple-autocomplete-input.tsx b/src/components/inputs/react-hook-form/autocomplete-inputs/multiple-autocomplete-input.tsx index b00d55cd..8e1f1545 100644 --- a/src/components/inputs/react-hook-form/autocomplete-inputs/multiple-autocomplete-input.tsx +++ b/src/components/inputs/react-hook-form/autocomplete-inputs/multiple-autocomplete-input.tsx @@ -28,9 +28,7 @@ function MultipleAutocompleteInput({ name, ...props }: any) { const outputTransform = (values: any[]) => { const newValues = values.map((val) => val.trim()); - return newValues.filter( - (val, index) => newValues.indexOf(val) === index - ); + return newValues.filter((val, index) => newValues.indexOf(val) === index); }; return ( @@ -42,9 +40,7 @@ function MultipleAutocompleteInput({ name, ...props }: any) { clearOnBlur disableClearable outputTransform={outputTransform} - onInputChange={(_: unknown, val: string) => - setUnsavedInput(val.trim() ?? '') - } + onInputChange={(_: unknown, val: string) => setUnsavedInput(val.trim() ?? '')} onBlur={handleOnBlur} blurOnSelect={false} multiple diff --git a/src/components/inputs/react-hook-form/booleans/boolean-input.tsx b/src/components/inputs/react-hook-form/booleans/boolean-input.tsx index 060518f0..f972f08e 100644 --- a/src/components/inputs/react-hook-form/booleans/boolean-input.tsx +++ b/src/components/inputs/react-hook-form/booleans/boolean-input.tsx @@ -34,9 +34,7 @@ function BooleanInput({ name, label, formProps, Input }: BooleanInputProps) { const CustomInput = ( ) => - handleChangeValue(e) - } + onChange={(e: ChangeEvent) => handleChangeValue(e)} inputRef={ref} inputProps={{ 'aria-label': 'primary checkbox', @@ -46,12 +44,7 @@ function BooleanInput({ name, label, formProps, Input }: BooleanInputProps) { ); if (label) { - return ( - - ); + return ; } return CustomInput; diff --git a/src/components/inputs/react-hook-form/booleans/checkbox-input.tsx b/src/components/inputs/react-hook-form/booleans/checkbox-input.tsx index c5b7d56f..fad14f08 100644 --- a/src/components/inputs/react-hook-form/booleans/checkbox-input.tsx +++ b/src/components/inputs/react-hook-form/booleans/checkbox-input.tsx @@ -15,14 +15,7 @@ export interface CheckboxInputProps { } function CheckboxInput({ name, label, formProps }: CheckboxInputProps) { - return ( - - ); + return ; } export default CheckboxInput; diff --git a/src/components/inputs/react-hook-form/booleans/switch-input.tsx b/src/components/inputs/react-hook-form/booleans/switch-input.tsx index eb24b1b8..a075e52a 100644 --- a/src/components/inputs/react-hook-form/booleans/switch-input.tsx +++ b/src/components/inputs/react-hook-form/booleans/switch-input.tsx @@ -15,14 +15,7 @@ export interface SwitchInputProps { } function SwitchInput({ name, label, formProps }: SwitchInputProps) { - return ( - - ); + return ; } export default SwitchInput; diff --git a/src/components/inputs/react-hook-form/directory-items-input.tsx b/src/components/inputs/react-hook-form/directory-items-input.tsx index e7e523e5..372e1ba5 100644 --- a/src/components/inputs/react-hook-form/directory-items-input.tsx +++ b/src/components/inputs/react-hook-form/directory-items-input.tsx @@ -5,14 +5,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - Chip, - FormControl, - Grid, - IconButton, - Theme, - Tooltip, -} from '@mui/material'; +import { Chip, FormControl, Grid, IconButton, Theme, Tooltip } from '@mui/material'; import FolderIcon from '@mui/icons-material/Folder'; import { useCallback, useMemo, useState } from 'react'; import { useController, useFieldArray } from 'react-hook-form'; @@ -94,8 +87,7 @@ function DirectoryItemsInput({ const [expanded, setExpanded] = useState([]); const [multiSelect, setMultiSelect] = useState(true); const types = useMemo(() => [elementType], [elementType]); - const [directoryItemSelectorOpen, setDirectoryItemSelectorOpen] = - useState(false); + const [directoryItemSelectorOpen, setDirectoryItemSelectorOpen] = useState(false); const { fields: elements, append, @@ -121,22 +113,14 @@ function DirectoryItemsInput({ // if we select a chip and return a new values, we remove it to be replaced if (selected?.length > 0 && values?.length > 0) { selected.forEach((chip) => { - remove( - getValues(name).findIndex( - (item: any) => item.id === chip - ) - ); + remove(getValues(name).findIndex((item: any) => item.id === chip)); }); } values.forEach((value) => { const { icon, children, ...otherElementAttributes } = value; // Check if the element is already present - if ( - getValues(name).find( - (v: any) => v?.id === otherElementAttributes.id - ) !== undefined - ) { + if (getValues(name).find((v: any) => v?.id === otherElementAttributes.id) !== undefined) { snackError({ messageTxt: '', headerId: 'directory_items_input/ElementAlreadyUsed', @@ -150,16 +134,7 @@ function DirectoryItemsInput({ setDirectoryItemSelectorOpen(false); setSelected([]); }, - [ - append, - getValues, - snackError, - name, - onRowChanged, - onChange, - selected, - remove, - ] + [append, getValues, snackError, name, onRowChanged, onChange, selected, remove] ); const removeElements = useCallback( @@ -177,9 +152,7 @@ function DirectoryItemsInput({ const chip = chips.at(index)?.id; if (chip) { fetchDirectoryElementPath(chip).then((response: any[]) => { - const path = response - .filter((e) => e.elementUuid !== chip) - .map((e) => e.elementUuid); + const path = response.filter((e) => e.elementUuid !== chip).map((e) => e.elementUuid); setExpanded(path); setSelected([chip]); @@ -204,14 +177,7 @@ function DirectoryItemsInput({ {elements?.length === 0 && label && ( )} {elements?.length > 0 && ( @@ -224,11 +190,7 @@ function DirectoryItemsInput({ onClick={() => handleChipClick(index)} label={ - } + text={} sx={{ width: '100%' }} /> } @@ -256,9 +218,7 @@ function DirectoryItemsInput({ - {!hideErrorMessage && ( - - )} + {!hideErrorMessage && } React.ReactNode; + InputField: ({ message }: { message: string | React.ReactNode }) => React.ReactNode; } function ErrorInput({ name, InputField }: ErrorInputProps) { diff --git a/src/components/inputs/react-hook-form/numbers/integer-input.tsx b/src/components/inputs/react-hook-form/numbers/integer-input.tsx index c6d93728..41001789 100644 --- a/src/components/inputs/react-hook-form/numbers/integer-input.tsx +++ b/src/components/inputs/react-hook-form/numbers/integer-input.tsx @@ -12,10 +12,7 @@ function IntegerInput(props: TextInputProps) { if (value === '-') { return value; } - return value === null || - (typeof value === 'number' && Number.isNaN(value)) - ? '' - : value.toString(); + return value === null || (typeof value === 'number' && Number.isNaN(value)) ? '' : value.toString(); }; const outputTransform = (value: string) => { diff --git a/src/components/inputs/react-hook-form/provider/custom-form-provider.tsx b/src/components/inputs/react-hook-form/provider/custom-form-provider.tsx index a4b6beb8..f9f99737 100644 --- a/src/components/inputs/react-hook-form/provider/custom-form-provider.tsx +++ b/src/components/inputs/react-hook-form/provider/custom-form-provider.tsx @@ -16,8 +16,7 @@ type CustomFormContextProps = { language?: string; }; -export type MergedFormContextProps = UseFormReturn & - CustomFormContextProps; +export type MergedFormContextProps = UseFormReturn & CustomFormContextProps; type CustomFormProviderProps = PropsWithChildren; @@ -28,13 +27,7 @@ export const CustomFormContext = createContext({ }); function CustomFormProvider(props: CustomFormProviderProps) { - const { - validationSchema, - removeOptional, - language, - children, - ...formMethods - } = props; + const { validationSchema, removeOptional, language, children, ...formMethods } = props; return ( diff --git a/src/components/inputs/react-hook-form/provider/use-custom-form-context.ts b/src/components/inputs/react-hook-form/provider/use-custom-form-context.ts index 75b6efcc..62d395a2 100644 --- a/src/components/inputs/react-hook-form/provider/use-custom-form-context.ts +++ b/src/components/inputs/react-hook-form/provider/use-custom-form-context.ts @@ -7,10 +7,7 @@ import { useFormContext } from 'react-hook-form'; import { useContext } from 'react'; -import { - CustomFormContext, - MergedFormContextProps, -} from './custom-form-provider'; +import { CustomFormContext, MergedFormContextProps } from './custom-form-provider'; const useCustomFormContext = (): MergedFormContextProps => { const formMethods = useFormContext(); diff --git a/src/components/inputs/react-hook-form/radio-input.tsx b/src/components/inputs/react-hook-form/radio-input.tsx index 830abc13..9352662e 100644 --- a/src/components/inputs/react-hook-form/radio-input.tsx +++ b/src/components/inputs/react-hook-form/radio-input.tsx @@ -5,14 +5,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -import { - FormControl, - FormControlLabel, - FormLabel, - Radio, - RadioGroup, - RadioGroupProps, -} from '@mui/material'; +import { FormControl, FormControlLabel, FormLabel, Radio, RadioGroup, RadioGroupProps } from '@mui/material'; import { FormattedMessage } from 'react-intl'; import { useController } from 'react-hook-form'; import FieldLabel from './utils/field-label'; @@ -42,13 +35,7 @@ function RadioInput({ name, label, id, options, formProps }: RadioInputProps) { )} - + {options.map((option) => ( } diff --git a/src/components/inputs/react-hook-form/range-input.tsx b/src/components/inputs/react-hook-form/range-input.tsx index 67f91900..175a91ce 100644 --- a/src/components/inputs/react-hook-form/range-input.tsx +++ b/src/components/inputs/react-hook-form/range-input.tsx @@ -17,8 +17,7 @@ import FieldConstants from '../../../utils/field-constants'; const style = { inputLegend: (theme: any) => ({ - backgroundImage: - 'linear-gradient(rgba(255, 255, 255, 0.16), rgba(255, 255, 255, 0.16))', + backgroundImage: 'linear-gradient(rgba(255, 255, 255, 0.16), rgba(255, 255, 255, 0.16))', backgroundColor: theme.palette.background.paper, padding: '0 8px 0 8px', }), @@ -46,22 +45,16 @@ export const getRangeInputSchema = (name: string) => ({ [name]: yup.object().shape( { [FieldConstants.OPERATION_TYPE]: yup.string(), - [FieldConstants.VALUE_1]: yup - .number() - .when([FieldConstants.OPERATION_TYPE, FieldConstants.VALUE_2], { - is: (operationType: string, value2: unknown) => - operationType === RangeType.RANGE.id && value2 !== null, - then: (schema) => schema.required(), - otherwise: (schema) => schema.nullable(), - }), - [FieldConstants.VALUE_2]: yup - .number() - .when([FieldConstants.OPERATION_TYPE, FieldConstants.VALUE_1], { - is: (operationType: string, value1: unknown) => - operationType === RangeType.RANGE.id && value1 !== null, - then: (schema) => schema.required(), - otherwise: (schema) => schema.nullable(), - }), + [FieldConstants.VALUE_1]: yup.number().when([FieldConstants.OPERATION_TYPE, FieldConstants.VALUE_2], { + is: (operationType: string, value2: unknown) => operationType === RangeType.RANGE.id && value2 !== null, + then: (schema) => schema.required(), + otherwise: (schema) => schema.nullable(), + }), + [FieldConstants.VALUE_2]: yup.number().when([FieldConstants.OPERATION_TYPE, FieldConstants.VALUE_1], { + is: (operationType: string, value1: unknown) => operationType === RangeType.RANGE.id && value1 !== null, + then: (schema) => schema.required(), + otherwise: (schema) => schema.nullable(), + }), }, [[FieldConstants.VALUE_1, FieldConstants.VALUE_2]] ), @@ -77,10 +70,7 @@ function RangeInput({ name, label }: RangeInputProps) { name: `${name}.${FieldConstants.OPERATION_TYPE}`, }); - const isOperationTypeRange = useMemo( - () => watchOperationType === RangeType.RANGE.id, - [watchOperationType] - ); + const isOperationTypeRange = useMemo(() => watchOperationType === RangeType.RANGE.id, [watchOperationType]); const firstValueField = ( val.map((code: string, index: number) => ( - + )) } /> diff --git a/src/components/inputs/react-hook-form/select-inputs/mui-select-input.tsx b/src/components/inputs/react-hook-form/select-inputs/mui-select-input.tsx index 27f74a55..cacac0c4 100644 --- a/src/components/inputs/react-hook-form/select-inputs/mui-select-input.tsx +++ b/src/components/inputs/react-hook-form/select-inputs/mui-select-input.tsx @@ -15,11 +15,7 @@ interface MuiSelectInputProps { } // This input use Mui select instead of Autocomplete which can be needed some time (like in FormControl) -function MuiSelectInput({ - name, - options, - ...props -}: MuiSelectInputProps & SelectProps) { +function MuiSelectInput({ name, options, ...props }: MuiSelectInputProps & SelectProps) { const { field: { value, onChange }, } = useController({ @@ -29,10 +25,7 @@ function MuiSelectInput({ return ( - {(fieldData.operators as OperatorOption[])?.map( - (option) => ( - - {intl.formatMessage({ id: option.label })} - - ) - )} + {(fieldData.operators as OperatorOption[])?.map((option) => ( + + {intl.formatMessage({ id: option.label })} + + ))} diff --git a/src/components/inputs/react-query-builder/custom-react-query-builder.tsx b/src/components/inputs/react-query-builder/custom-react-query-builder.tsx index ea98d503..78c49e5d 100644 --- a/src/components/inputs/react-query-builder/custom-react-query-builder.tsx +++ b/src/components/inputs/react-query-builder/custom-react-query-builder.tsx @@ -10,13 +10,7 @@ import { QueryBuilderDnD } from '@react-querybuilder/dnd'; import * as ReactDnD from 'react-dnd'; import * as ReactDndHtml5Backend from 'react-dnd-html5-backend'; import { QueryBuilderMaterial } from '@react-querybuilder/material'; -import { - ActionWithRulesAndAddersProps, - Field, - formatQuery, - QueryBuilder, - RuleGroupTypeAny, -} from 'react-querybuilder'; +import { ActionWithRulesAndAddersProps, Field, formatQuery, QueryBuilder, RuleGroupTypeAny } from 'react-querybuilder'; import { useIntl } from 'react-intl'; import { useFormContext } from 'react-hook-form'; import { useCallback, useMemo } from 'react'; @@ -28,11 +22,7 @@ import ValueSelector from './value-selector'; import { COMBINATOR_OPTIONS } from '../../filter/expert/expert-filter-constants'; import ErrorInput from '../react-hook-form/error-management/error-input'; import FieldErrorAlert from '../react-hook-form/error-management/field-error-alert'; -import { - countRules, - getOperators, - queryValidator, -} from '../../filter/expert/expert-filter-utils'; +import { countRules, getOperators, queryValidator } from '../../filter/expert/expert-filter-utils'; import RemoveButton from './remove-button'; interface CustomReactQueryBuilderProps { @@ -67,13 +57,11 @@ function CustomReactQueryBuilder(props: CustomReactQueryBuilderProps) { (newQuery: RuleGroupTypeAny) => { const oldQuery = getValues(name); const hasQueryChanged = - formatQuery(oldQuery, 'json_without_ids') !== - formatQuery(newQuery, 'json_without_ids'); + formatQuery(oldQuery, 'json_without_ids') !== formatQuery(newQuery, 'json_without_ids'); const hasAddedRules = countRules(newQuery) > countRules(oldQuery); setValue(name, newQuery, { shouldDirty: hasQueryChanged, - shouldValidate: - isSubmitted && hasQueryChanged && !hasAddedRules, + shouldValidate: isSubmitted && hasQueryChanged && !hasAddedRules, }); }, [getValues, setValue, isSubmitted, name] @@ -90,18 +78,14 @@ function CustomReactQueryBuilder(props: CustomReactQueryBuilderProps) { <> - + - getOperators(fieldName, intl) - } + getOperators={(fieldName) => getOperators(fieldName, intl)} validator={queryValidator} controlClassnames={{ queryBuilder: 'queryBuilder-branches', diff --git a/src/components/inputs/react-query-builder/element-value-editor.tsx b/src/components/inputs/react-query-builder/element-value-editor.tsx index 9c249f99..e189d4f8 100644 --- a/src/components/inputs/react-query-builder/element-value-editor.tsx +++ b/src/components/inputs/react-query-builder/element-value-editor.tsx @@ -23,16 +23,7 @@ interface ElementValueEditorProps { } function ElementValueEditor(props: ElementValueEditorProps) { - const { - defaultValue, - name, - elementType, - equipmentTypes, - titleId, - hideErrorMessage, - itemFilter, - onChange, - } = props; + const { defaultValue, name, elementType, equipmentTypes, titleId, hideErrorMessage, itemFilter, onChange } = props; const { setValue } = useCustomFormContext(); useEffect(() => { diff --git a/src/components/inputs/react-query-builder/property-value-editor.tsx b/src/components/inputs/react-query-builder/property-value-editor.tsx index f4d37bf1..5f85fa0f 100644 --- a/src/components/inputs/react-query-builder/property-value-editor.tsx +++ b/src/components/inputs/react-query-builder/property-value-editor.tsx @@ -28,11 +28,9 @@ function PropertyValueEditor(props: ExpertFilterPropertyProps) { const valid = useValid(valueEditorProps); const intl = useIntl(); - const { propertyName, propertyOperator, propertyValues } = - valueEditorProps?.value ?? {}; + const { propertyName, propertyOperator, propertyValues } = valueEditorProps?.value ?? {}; - const [equipmentPredefinedProps, setEquipmentType] = - usePredefinedProperties(equipmentType); + const [equipmentPredefinedProps, setEquipmentType] = usePredefinedProperties(equipmentType); useEffect(() => { setEquipmentType(equipmentType); @@ -43,8 +41,7 @@ function PropertyValueEditor(props: ExpertFilterPropertyProps) { }, [equipmentPredefinedProps]); const predefinedValues = useMemo(() => { - const predefinedForName: string[] = - equipmentPredefinedProps?.[propertyName]; + const predefinedForName: string[] = equipmentPredefinedProps?.[propertyName]; if (!predefinedForName) { return []; @@ -57,8 +54,7 @@ function PropertyValueEditor(props: ExpertFilterPropertyProps) { let updatedValue = { ...valueEditorProps?.value, [FieldConstants.PROPERTY_OPERATOR]: - valueEditorProps?.value?.propertyOperator ?? - PROPERTY_VALUE_OPERATORS[0].customName, + valueEditorProps?.value?.propertyOperator ?? PROPERTY_VALUE_OPERATORS[0].customName, [field]: value, }; // Reset the property values when the property name changes @@ -82,9 +78,7 @@ function PropertyValueEditor(props: ExpertFilterPropertyProps) { freeSolo autoSelect forcePopupIcon - renderInput={(params) => ( - - )} + renderInput={(params) => } onChange={(event, value: any) => { onChange(FieldConstants.PROPERTY_NAME, value); }} @@ -92,10 +86,7 @@ function PropertyValueEditor(props: ExpertFilterPropertyProps) {