From 5f0e1ef46a03c299b8507e4f7f9015f471ce2f53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Zasso?= Date: Wed, 19 Feb 2025 18:09:26 +0100 Subject: [PATCH] refactor: use dlv or pure JS instead of lodash/get --- eslint.config.js | 2 +- package-lock.json | 15 ++++++ package.json | 2 + .../1d-2d/components/SpectrumInfoBlock.tsx | 4 +- src/component/1d/SpectraLegends.tsx | 6 +-- .../1d/multiplicityTree/generateTreeNodes.ts | 4 +- src/component/2d/ft/Contours.tsx | 4 +- src/component/context/SortSpectraContext.tsx | 6 +-- .../hooks/useActiveSpectrumStyleOptions.ts | 6 +-- .../hooks/useCheckToolsVisibility.ts | 9 ++-- .../hooks/useFormatNumberByNucleus.ts | 6 ++- src/component/hooks/useTableSortBy.tsx | 10 ++-- .../signal-tabs/SignalJCouplingsTable.tsx | 4 +- .../panels/IntegralsPanel/IntegralPanel.tsx | 6 +-- .../panels/IntegralsPanel/IntegralTable.tsx | 6 +-- .../panels/PeaksPanel/PeaksTable.tsx | 4 +- .../panels/RangesPanel/RangesHeader.tsx | 37 ++++++++++----- .../panels/RangesPanel/RangesPanel.tsx | 46 ++++++------------- .../panels/RangesPanel/RangesTableRow.tsx | 20 +++----- .../TableColumns/CouplingColumn.tsx | 13 +++--- .../TableColumns/SignalAssignmentsColumn.tsx | 4 +- .../panels/SpectraPanel/SpectraTable.tsx | 4 +- .../panels/SpectraPanel/base/RenderAsHTML.tsx | 4 +- .../SummaryPanel/utilities/Utilities.ts | 10 ++-- .../TableColumns/SignalDeltaColumn.tsx | 11 +++-- .../panels/ZonesPanel/ZonesTableRow.tsx | 11 +++-- .../panels/databasePanel/DatabaseTable.tsx | 4 +- .../panels/extra/preferences/ColumnsHelper.ts | 10 +--- .../panels/hooks/useGetPanelOptions.ts | 8 +--- src/component/panels/hooks/useTogglePanel.ts | 4 +- .../multipleAnalysisPanel/AnalysisChart.tsx | 22 +++------ .../reducer/actions/SpectraActions.ts | 4 +- src/component/utility/LocalStorage.ts | 9 ++-- src/component/utility/export.ts | 4 +- src/data/data1d/multipleSpectraAnalysis.ts | 4 +- src/data/parseMeta/linkMetaWithSpectra.ts | 8 ++-- src/data/utilities/getCustomColor.ts | 4 +- 37 files changed, 156 insertions(+), 179 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index a7dc73b4d..00f1fb14c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -41,7 +41,7 @@ export default [ { name: 'lodash', message: - "Use a deep import instead, like for example 'lodash/get.js'", + "Use a deep import instead, like for example 'lodash/merge.js'", }, { name: '@simbathesailor/use-what-changed', diff --git a/package-lock.json b/package-lock.json index 388dfb0ea..daefb8dc0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,6 +20,7 @@ "clipboard-polyfill": "^4.1.1", "convert-to-jcamp": "^5.4.11", "d3": "^7.9.0", + "dlv": "^1.1.3", "eventemitter3": "^5.0.1", "fifo-logger": "^1.0.0", "file-saver": "^2.0.5", @@ -75,6 +76,7 @@ "@playwright/test": "^1.50.1", "@simbathesailor/use-what-changed": "^2.0.0", "@types/d3": "^7.4.3", + "@types/dlv": "^1.1.5", "@types/lodash": "^4.17.15", "@types/node": "^22.13.4", "@types/papaparse": "^5.3.15", @@ -3349,6 +3351,13 @@ "@types/d3-selection": "*" } }, + "node_modules/@types/dlv": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@types/dlv/-/dlv-1.1.5.tgz", + "integrity": "sha512-JHOWNfiWepAhfwlSw17kiWrWrk6od2dEQgHltJw9AS0JPFoLZJBge5+Dnil2NfdjAvJ/+vGSX60/BRW20PpUXw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", @@ -5896,6 +5905,12 @@ "node": ">=8" } }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "license": "MIT" + }, "node_modules/doctrine": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", diff --git a/package.json b/package.json index 5a406342d..a1eab4dbc 100644 --- a/package.json +++ b/package.json @@ -68,6 +68,7 @@ "clipboard-polyfill": "^4.1.1", "convert-to-jcamp": "^5.4.11", "d3": "^7.9.0", + "dlv": "^1.1.3", "eventemitter3": "^5.0.1", "fifo-logger": "^1.0.0", "file-saver": "^2.0.5", @@ -123,6 +124,7 @@ "@playwright/test": "^1.50.1", "@simbathesailor/use-what-changed": "^2.0.0", "@types/d3": "^7.4.3", + "@types/dlv": "^1.1.5", "@types/lodash": "^4.17.15", "@types/node": "^22.13.4", "@types/papaparse": "^5.3.15", diff --git a/src/component/1d-2d/components/SpectrumInfoBlock.tsx b/src/component/1d-2d/components/SpectrumInfoBlock.tsx index b0094564f..ab21c8052 100644 --- a/src/component/1d-2d/components/SpectrumInfoBlock.tsx +++ b/src/component/1d-2d/components/SpectrumInfoBlock.tsx @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { Spectrum } from 'nmr-load-save'; import type { CSSProperties } from 'react'; import { useState } from 'react'; @@ -42,7 +42,7 @@ function getInfoValue( field: { jpath: string[]; format: string }, ) { const { jpath, format } = field; - const value = lodashGet(spectrum, jpath, ''); + const value = dlv(spectrum, jpath, ''); switch (typeof value) { case 'number': diff --git a/src/component/1d/SpectraLegends.tsx b/src/component/1d/SpectraLegends.tsx index ce27a2800..7ed59bc87 100644 --- a/src/component/1d/SpectraLegends.tsx +++ b/src/component/1d/SpectraLegends.tsx @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import { xFindClosestIndex } from 'ml-spectra-processing'; import type { JpathLegendField, @@ -9,7 +9,7 @@ import type { } from 'nmr-load-save'; import type { CSSProperties } from 'react'; -import { get1DDataXY } from '../../data/data1d/Spectrum1D/get1DDataXY.js'; +import { get1DDataXY } from '../../data/data1d/Spectrum1D/index.js'; import { useMouseTracker } from '../EventsTrackers/MouseTracker.js'; import { useChartData } from '../context/ChartContext.js'; import { useScale } from '../context/ScaleContext.js'; @@ -99,7 +99,7 @@ function InnerSpectraLegends({ ); default: { const jpath = (field as JpathLegendField).jpath; - const value = lodashGet(spectrum, jpath, ''); + const value = dlv(spectrum, jpath, ''); return ( 0 && spectraReferenceMap.has(spectrum.id)) { sortedSpectra.push({ spectrum, - sortValue: lodashGet(spectraReferenceMap.get(spectrum.id), path), + sortValue: dlv(spectraReferenceMap.get(spectrum.id), path), }); originIndexes.push(index); } diff --git a/src/component/hooks/useActiveSpectrumStyleOptions.ts b/src/component/hooks/useActiveSpectrumStyleOptions.ts index 2fd4d4166..1ccd6eeb6 100644 --- a/src/component/hooks/useActiveSpectrumStyleOptions.ts +++ b/src/component/hooks/useActiveSpectrumStyleOptions.ts @@ -1,4 +1,3 @@ -import get from 'lodash/get.js'; import { useMemo } from 'react'; import { usePreferences } from '../context/PreferencesContext.js'; @@ -26,10 +25,11 @@ export default function useActiveSpectrumStyleOptions( false; const isActive = - !!(activeSpectra?.length === 0 || index !== -1) || isNoneSelected; + activeSpectra?.length === 0 || index !== -1 || isNoneSelected; const opacity = isActive ? 1 - : get(preferences.current, 'general.dimmedSpectraOpacity', 0.1); + : // TODO: make sure preferences are not a lie and remove the optional chaining. + (preferences?.current?.general?.dimmedSpectraOpacity ?? 0.1); return { isActive, opacity }; }, [activeSpectra, id, preferences]); } diff --git a/src/component/hooks/useCheckToolsVisibility.ts b/src/component/hooks/useCheckToolsVisibility.ts index 54278e21c..bde21176f 100644 --- a/src/component/hooks/useCheckToolsVisibility.ts +++ b/src/component/hooks/useCheckToolsVisibility.ts @@ -1,4 +1,3 @@ -import lodashGet from 'lodash/get.js'; import type { Info1D, Info2D } from 'nmr-processing'; import { useCallback } from 'react'; @@ -37,11 +36,9 @@ export function useCheckToolsVisibility(): ( const { spectraOptions, mode, isExperimental } = options[toolKey]; - const flag = lodashGet( - preferences.current, - `display.toolBarButtons.${toolKey}`, - false, - ); + // TODO: make sure preferences are not a lie and remove the optional chaining. + const flag = + preferences?.current?.display?.toolBarButtons?.[toolKey] ?? false; const modeFlag = !checkMode || (checkMode && (!mode || displayerMode === mode)); diff --git a/src/component/hooks/useFormatNumberByNucleus.ts b/src/component/hooks/useFormatNumberByNucleus.ts index cb03af918..d999866c3 100644 --- a/src/component/hooks/useFormatNumberByNucleus.ts +++ b/src/component/hooks/useFormatNumberByNucleus.ts @@ -1,4 +1,3 @@ -import lodashGet from 'lodash/get.js'; import { useMemo } from 'react'; import { usePreferences } from '../context/PreferencesContext.js'; @@ -11,11 +10,14 @@ export type ReturnFunction = ( suffix?: string, ) => string; +const defaultNuclei = []; + export function useFormatNumberByNucleus(nucleus?: string[]): ReturnFunction[]; export function useFormatNumberByNucleus(nucleus?: string): ReturnFunction; export function useFormatNumberByNucleus(nucleus?: string | string[]) { const preferences = usePreferences(); - const nucleiPreferences = lodashGet(preferences.current, `nuclei`, []); + // TODO: make sure preferences are not a lie and remove the optional chaining. + const nucleiPreferences = preferences?.current?.nuclei ?? defaultNuclei; return useMemo(() => { function formatFun(n: string) { diff --git a/src/component/hooks/useTableSortBy.tsx b/src/component/hooks/useTableSortBy.tsx index 613930aac..44a0ca5a4 100644 --- a/src/component/hooks/useTableSortBy.tsx +++ b/src/component/hooks/useTableSortBy.tsx @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import { useCallback, useMemo, useState } from 'react'; export enum SortType { @@ -19,13 +19,9 @@ export default function useTableSortBy(items, config = null) { if (sortConfig !== null) { sortableItems.sort((a, b) => { if (sortConfig.direction === SortType.ASCENDING) { - return ( - lodashGet(a, sortConfig.key, 0) - lodashGet(b, sortConfig.key, 0) - ); + return dlv(a, sortConfig.key, 0) - dlv(b, sortConfig.key, 0); } else if (sortConfig.direction === SortType.DESCENDING) { - return ( - lodashGet(b, sortConfig.key, 0) - lodashGet(a, sortConfig.key, 0) - ); + return dlv(b, sortConfig.key, 0) - dlv(a, sortConfig.key, 0); } return 0; }); diff --git a/src/component/modal/editRange/forms/components/signal-tabs/SignalJCouplingsTable.tsx b/src/component/modal/editRange/forms/components/signal-tabs/SignalJCouplingsTable.tsx index 6b0da60bb..521e9f982 100644 --- a/src/component/modal/editRange/forms/components/signal-tabs/SignalJCouplingsTable.tsx +++ b/src/component/modal/editRange/forms/components/signal-tabs/SignalJCouplingsTable.tsx @@ -1,5 +1,5 @@ import { Button, Callout, Classes } from '@blueprintjs/core'; -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { Jcoupling, Peak1D } from 'nmr-processing'; import { translateMultiplet } from 'nmr-processing'; import type { CSSProperties } from 'react'; @@ -46,7 +46,7 @@ function getJCouplingKey( } function getCouplingMinErrorMessage(errors, index) { - return lodashGet(errors, `signals.${index}.js.root.message`); + return dlv(errors, `signals.${index}.js.root.message`); } export function SignalJCouplingsTable(props: SignalJCouplingsTableProps) { diff --git a/src/component/panels/IntegralsPanel/IntegralPanel.tsx b/src/component/panels/IntegralsPanel/IntegralPanel.tsx index 023dde0cc..59027001d 100644 --- a/src/component/panels/IntegralsPanel/IntegralPanel.tsx +++ b/src/component/panels/IntegralsPanel/IntegralPanel.tsx @@ -1,5 +1,4 @@ import { SvgNmrIntegrate } from 'cheminfo-font'; -import lodashGet from 'lodash/get.js'; import type { Spectrum1D } from 'nmr-load-save'; import type { Info1D, Integrals } from 'nmr-processing'; import { memo, useCallback, useMemo, useRef, useState } from 'react'; @@ -70,9 +69,8 @@ function IntegralPanelInner({ [dispatch], ); - const currentSum = useMemo(() => { - return lodashGet(integrals, 'options.sum', null); - }, [integrals]); + // TODO: make sure currentSum is not a lie and remove the optional chaining. + const currentSum = integrals?.options?.sum ?? null; const settingsPanelHandler = useCallback(() => { setFlipStatus(!isFlipped); diff --git a/src/component/panels/IntegralsPanel/IntegralTable.tsx b/src/component/panels/IntegralsPanel/IntegralTable.tsx index 385603314..11b03545a 100644 --- a/src/component/panels/IntegralsPanel/IntegralTable.tsx +++ b/src/component/panels/IntegralsPanel/IntegralTable.tsx @@ -1,10 +1,10 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { Info1D, Integral } from 'nmr-processing'; +import { checkIntegralKind } from 'nmr-processing'; import { memo, useCallback, useMemo } from 'react'; import { FaRegTrashAlt } from 'react-icons/fa'; import { SIGNAL_KINDS } from '../../../data/constants/signalsKinds.js'; -import { checkIntegralKind } from '../../../data/data1d/Spectrum1D/index.js'; import { useDispatch } from '../../context/DispatchContext.js'; import { EditableColumn } from '../../elements/EditableColumn.js'; import { EmptyText } from '../../elements/EmptyText.js'; @@ -167,7 +167,7 @@ function IntegralTable({ activeTab, data, info }: IntegralTableProps) { const columns: Array> = []; for (const col of COLUMNS) { const { showWhen, ...colParams } = col; - if (lodashGet(integralsPreferences, showWhen)) { + if (dlv(integralsPreferences, showWhen)) { addCustomColumn(columns, colParams); } } diff --git a/src/component/panels/PeaksPanel/PeaksTable.tsx b/src/component/panels/PeaksPanel/PeaksTable.tsx index bad6fc5ad..5d5ddc12e 100644 --- a/src/component/panels/PeaksPanel/PeaksTable.tsx +++ b/src/component/panels/PeaksPanel/PeaksTable.tsx @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { Info1D, Peak1D } from 'nmr-processing'; import { memo, useCallback, useMemo, useState } from 'react'; import { FaEdit, FaRegTrashAlt } from 'react-icons/fa'; @@ -190,7 +190,7 @@ function PeaksTable({ activeTab, data, info }: PeaksTableProps) { const columns: Array> = []; for (const col of COLUMNS) { const { showWhen, ...colParams } = col; - if (lodashGet(peaksPreferences, showWhen)) { + if (dlv(peaksPreferences, showWhen)) { addCustomColumn(columns, colParams); } } diff --git a/src/component/panels/RangesPanel/RangesHeader.tsx b/src/component/panels/RangesPanel/RangesHeader.tsx index 67badb64a..268b0124c 100644 --- a/src/component/panels/RangesPanel/RangesHeader.tsx +++ b/src/component/panels/RangesPanel/RangesHeader.tsx @@ -4,8 +4,8 @@ import { SvgNmrPeaksTopLabels, } from 'cheminfo-font'; import fileSaver from 'file-saver'; -import lodashGet from 'lodash/get.js'; import type { RangesViewState } from 'nmr-load-save'; +import type { Info1D, Ranges } from 'nmr-processing'; import { rangesToACS, rangesToTSV } from 'nmr-processing'; import { useState } from 'react'; import { @@ -58,22 +58,35 @@ const EXPORT_MENU: ExportItem[] = [ }, ] as const; -function RangesHeader({ - ranges, - info, - onUnlink, - onFilterActivated, - onSettingClick, - isFilterActive, - filterCounter, - activeTab, -}) { +interface RangesHeaderProps { + ranges: Ranges; + info: Info1D; + activeTab: string; + isFilterActive: boolean; + onUnlink: () => void; + onFilterActivated: () => void; + onSettingClick: () => void; + filterCounter: number; +} + +function RangesHeader(props: RangesHeaderProps) { + const { + ranges, + info, + activeTab, + isFilterActive, + onUnlink, + onFilterActivated, + onSettingClick, + filterCounter, + } = props; const dispatch = useDispatch(); const alert = useAlert(); const toaster = useToaster(); const assignmentData = useAssignmentData(); - const currentSum = lodashGet(ranges, 'options.sum', null); + // TODO: make sure ranges are not a lie and remove the optional chaining. + const currentSum = ranges?.options?.sum ?? null; const rangesPreferences = usePanelPreferences('ranges', activeTab); const [acs, setACS] = useState(); diff --git a/src/component/panels/RangesPanel/RangesPanel.tsx b/src/component/panels/RangesPanel/RangesPanel.tsx index 69c85573a..dc72e2159 100644 --- a/src/component/panels/RangesPanel/RangesPanel.tsx +++ b/src/component/panels/RangesPanel/RangesPanel.tsx @@ -5,7 +5,6 @@ import type { Info1D, Ranges } from 'nmr-processing'; import { memo, useCallback, useMemo, useRef, useState } from 'react'; import { FaCopy } from 'react-icons/fa'; -import type { StateMoleculeExtended } from '../../../data/molecules/Molecule.js'; import { ClipboardFallbackModal } from '../../../utils/clipboard/clipboardComponents.js'; import { useClipboard } from '../../../utils/clipboard/clipboardHooks.js'; import { useAssignmentData } from '../../assignment/AssignmentsContext.js'; @@ -30,25 +29,21 @@ const rangesContextMenuOptions: BaseContextMenuProps['options'] = [ ]; interface RangesTablePanelInnerProps { - id: string; ranges: Ranges; data: NmrData1D; info: Info1D; xDomain: number[]; activeTab: string; - molecules: StateMoleculeExtended[]; preferences: WorkSpacePanelPreferences['ranges']; } function RangesTablePanelInner({ - id, ranges, data, info, xDomain, preferences, activeTab, - molecules, }: RangesTablePanelInnerProps) { const [isFilterActive, setFilterIsActive] = useState(false); const assignmentData = useAssignmentData(); @@ -70,7 +65,7 @@ function RangesTablePanelInner({ ); }; - const getFilteredRanges = (ranges) => { + const getFilteredRanges = (ranges: Ranges['values']) => { return ranges.filter((range) => isInView(range.from, range.to)); }; @@ -90,19 +85,15 @@ function RangesTablePanelInner({ return []; }, [isFilterActive, ranges.values, xDomain]); - const unlinkRangeHandler = useCallback( - (rangeData, signalIndex = -1) => { - dispatch({ - type: 'UNLINK_RANGE', - payload: { - range: rangeData, - assignmentData, - signalIndex, - }, - }); - }, - [assignmentData, dispatch], - ); + const unlinkRangeHandler = useCallback(() => { + dispatch({ + type: 'UNLINK_RANGE', + payload: { + assignmentData, + signalIndex: -1, + }, + }); + }, [assignmentData, dispatch]); const { rawWriteWithType, shouldFallback, cleanShouldFallback, text } = useClipboard(); @@ -154,14 +145,10 @@ function RangesTablePanelInner({ {!isFlipped && ( ); diff --git a/src/component/panels/RangesPanel/RangesTableRow.tsx b/src/component/panels/RangesPanel/RangesTableRow.tsx index 9a03d7993..b534f66ed 100644 --- a/src/component/panels/RangesPanel/RangesTableRow.tsx +++ b/src/component/panels/RangesPanel/RangesTableRow.tsx @@ -1,8 +1,7 @@ -import lodashGet from 'lodash/get.js'; import type { WorkSpacePanelPreferences } from 'nmr-load-save'; import type { Info1D } from 'nmr-processing'; -import type { MouseEvent, CSSProperties } from 'react'; -import { useMemo, useCallback } from 'react'; +import type { CSSProperties, MouseEvent } from 'react'; +import { useCallback, useMemo } from 'react'; import type { AssignmentsData } from '../../assignment/AssignmentsContext.js'; import { @@ -104,9 +103,7 @@ function RangesTableRow({ const rowSpanTags: any = useMemo(() => { return { rowSpan: rowData.tableMetaInfo.rowSpan, - style: lodashGet(rowData.tableMetaInfo, 'hide', false) - ? { display: 'none' } - : undefined, + style: rowData.tableMetaInfo.hide ? { display: 'none' } : undefined, }; }, [rowData.tableMetaInfo]); @@ -122,10 +119,7 @@ function RangesTableRow({ onUnlink(rowData); assignmentRange.removeAll('x'); } else { - onUnlink( - rowData, - lodashGet(rowData, 'tableMetaInfo.signalIndex', undefined), - ); + onUnlink(rowData, rowData.tableMetaInfo.signalIndex); assignmentSignal.removeAll('x'); } } @@ -183,7 +177,7 @@ function RangesTableRow({ const trStyle = useMemo(() => { return highlightRange.isActive || assignmentRange.isActive ? HighlightedRowStyle - : lodashGet(rowData, 'tableMetaInfo.isConstantlyHighlighted', false) + : rowData.tableMetaInfo.isConstantlyHighlighted ? ConstantlyHighlightedRowStyle : undefined; }, [assignmentRange.isActive, highlightRange.isActive, rowData]); @@ -262,9 +256,7 @@ function RangesTableRow({ )} {preferences.showMultiplicity && ( - {!rowData?.tableMetaInfo?.signal - ? 'm' - : lodashGet(rowData, 'tableMetaInfo.signal.multiplicity', '')} + {rowData.tableMetaInfo.signal?.multiplicity ?? 'm'} )} diff --git a/src/component/panels/RangesPanel/TableColumns/CouplingColumn.tsx b/src/component/panels/RangesPanel/TableColumns/CouplingColumn.tsx index bf3219b87..311135832 100644 --- a/src/component/panels/RangesPanel/TableColumns/CouplingColumn.tsx +++ b/src/component/panels/RangesPanel/TableColumns/CouplingColumn.tsx @@ -1,12 +1,15 @@ -import lodashGet from 'lodash/get.js'; - import { formatNumber } from '../../../utility/formatNumber.js'; import type { BaseRangeColumnProps, OnHoverEvent } from '../RangesTableRow.js'; type CouplingColumnProps = BaseRangeColumnProps & OnHoverEvent; -function CouplingColumn({ row, onHover, format }: CouplingColumnProps) { - const result = lodashGet(row, 'tableMetaInfo.signal.js'); +export default function CouplingColumn({ + row, + onHover, + format, +}: CouplingColumnProps) { + // TODO: make sure row is not a lie and remove the optional chaining. + const result = row?.tableMetaInfo?.signal?.js; return ( {result @@ -19,5 +22,3 @@ function CouplingColumn({ row, onHover, format }: CouplingColumnProps) { ); } - -export default CouplingColumn; diff --git a/src/component/panels/RangesPanel/TableColumns/SignalAssignmentsColumn.tsx b/src/component/panels/RangesPanel/TableColumns/SignalAssignmentsColumn.tsx index 402188640..bad6f1eec 100644 --- a/src/component/panels/RangesPanel/TableColumns/SignalAssignmentsColumn.tsx +++ b/src/component/panels/RangesPanel/TableColumns/SignalAssignmentsColumn.tsx @@ -1,4 +1,3 @@ -import lodashGet from 'lodash/get.js'; import type { CSSProperties, MouseEvent } from 'react'; import { memo } from 'react'; @@ -25,7 +24,8 @@ function SignalAssignmentsColumn({ onLink, onUnlink, }: SignalAssignmentsColumnProps) { - const diaIDs = lodashGet(row, 'tableMetaInfo.signal.diaIDs', []); + // TODO: make sure row is not a lie and remove the optional chaining. + const diaIDs = row?.tableMetaInfo?.signal?.diaIDs ?? []; const tdCss: CSSProperties = assignment.isActive || highlight.isActive diff --git a/src/component/panels/SpectraPanel/SpectraTable.tsx b/src/component/panels/SpectraPanel/SpectraTable.tsx index 57957a48f..5e35db98f 100644 --- a/src/component/panels/SpectraPanel/SpectraTable.tsx +++ b/src/component/panels/SpectraPanel/SpectraTable.tsx @@ -1,5 +1,5 @@ +import dlv from 'dlv'; import fileSaver from 'file-saver'; -import lodashGet from 'lodash/get.js'; import type { ActiveSpectrum, JpathTableColumn, @@ -445,7 +445,7 @@ function pathToString(path: string[]) { } function getValue(row, path) { - const value = lodashGet(row, path, ''); + const value = dlv(row, path, ''); const pathString = pathToString(path); if ( diff --git a/src/component/panels/SpectraPanel/base/RenderAsHTML.tsx b/src/component/panels/SpectraPanel/base/RenderAsHTML.tsx index 792472e41..c5a450e48 100644 --- a/src/component/panels/SpectraPanel/base/RenderAsHTML.tsx +++ b/src/component/panels/SpectraPanel/base/RenderAsHTML.tsx @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { Spectrum } from 'nmr-load-save'; interface RenderAsHTMLProps { @@ -16,7 +16,7 @@ function formatValueAsHTML(value) { export function RenderAsHTML(props: RenderAsHTMLProps) { const { data, jpath } = props; - const value = lodashGet(data, jpath); + const value = dlv(data, jpath); if (!value) { return null; diff --git a/src/component/panels/SummaryPanel/utilities/Utilities.ts b/src/component/panels/SummaryPanel/utilities/Utilities.ts index ab89a139a..2cad5caab 100644 --- a/src/component/panels/SummaryPanel/utilities/Utilities.ts +++ b/src/component/panels/SummaryPanel/utilities/Utilities.ts @@ -1,6 +1,6 @@ import type { FromTo } from 'cheminfo-types'; +import dlv from 'dlv'; import lodashCloneDeep from 'lodash/cloneDeep.js'; -import lodashGet from 'lodash/get.js'; import type { Correlation, Link } from 'nmr-correlation'; import { addLink, @@ -26,18 +26,14 @@ function getAtomType(nucleus: string): string { } function getLabelColor(correlationData, correlation) { - const error = lodashGet( - correlationData, - `state.${correlation.atomType}.error`, - null, - ); + const error = correlationData?.state?.[correlation.atomType]?.error ?? null; if (error) { for (const { key, color } of ErrorColors) { if ( key !== 'incomplete' && // do not consider this for a single atom type (key === 'notAttached' || key === 'ambiguousAttachment') && - lodashGet(error, key, []).some( + dlv(error, key, []).some( (index) => correlationData.values[index].id === correlation.id, ) ) { diff --git a/src/component/panels/ZonesPanel/TableColumns/SignalDeltaColumn.tsx b/src/component/panels/ZonesPanel/TableColumns/SignalDeltaColumn.tsx index 853abab06..c07c6efa1 100644 --- a/src/component/panels/ZonesPanel/TableColumns/SignalDeltaColumn.tsx +++ b/src/component/panels/ZonesPanel/TableColumns/SignalDeltaColumn.tsx @@ -1,4 +1,3 @@ -import lodashGet from 'lodash/get.js'; import type { Zones1DNucleusPreferences } from 'nmr-load-save'; import { useDispatch } from '../../../context/DispatchContext.js'; @@ -28,9 +27,13 @@ function SignalDeltaColumn({ rowData, nucleus }: SignalDeltaColumnProps) { const { handleOnMouseEnter, handleOnMouseLeave } = useSignalHighlight(rowData); - const signalDeltaX = lodashGet(rowData, 'tableMetaInfo.signal.x.delta', null); - const signalDeltaY = lodashGet(rowData, 'tableMetaInfo.signal.y.delta', null); - const id = lodashGet(rowData, 'tableMetaInfo.signal.id', undefined); + // TODO: fix type of tableMetaInfo. + // @ts-expect-error Type is wrong. + const signalDeltaX = rowData.tableMetaInfo.signal.x.delta ?? null; + // @ts-expect-error Type is wrong. + const signalDeltaY = rowData.tableMetaInfo.signal.y.delta ?? null; + // @ts-expect-error Type is wrong. + const id = rowData.tableMetaInfo.signal.id; function saveXHandler(event) { const value = Number(event.target.value); diff --git a/src/component/panels/ZonesPanel/ZonesTableRow.tsx b/src/component/panels/ZonesPanel/ZonesTableRow.tsx index 652661e13..04f3b0837 100644 --- a/src/component/panels/ZonesPanel/ZonesTableRow.tsx +++ b/src/component/panels/ZonesPanel/ZonesTableRow.tsx @@ -1,4 +1,3 @@ -import lodashGet from 'lodash/get.js'; import type { Zones2DNucleusPreferences } from 'nmr-load-save'; import type { CSSProperties, MouseEvent } from 'react'; @@ -67,9 +66,9 @@ function ZonesTableRow({ const rowSpanTags = { rowSpan: rowData.tableMetaInfo.rowSpan, - style: lodashGet(rowData, 'tableMetaInfo.hide', false) - ? { display: 'none' } - : null, + // TODO: fix type of tableMetaInfo. + // @ts-expect-error Type is wrong. + style: rowData.tableMetaInfo.hide ? { display: 'none' } : null, }; function unlinkHandler( @@ -115,7 +114,9 @@ function ZonesTableRow({ style={ highlightZone.isActive || assignmentZone.isActive ? (HighlightedRowStyle as any) - : lodashGet(rowData, 'tableMetaInfo.isConstantlyHighlighted', false) + : // TODO: fix type of tableMetaInfo. + // @ts-expect-error Type is wrong. + rowData.tableMetaInfo.isConstantlyHighlighted ? ConstantlyHighlightedRowStyle : null } diff --git a/src/component/panels/databasePanel/DatabaseTable.tsx b/src/component/panels/databasePanel/DatabaseTable.tsx index 1cbd742ad..1c0d0d0a9 100644 --- a/src/component/panels/databasePanel/DatabaseTable.tsx +++ b/src/component/panels/databasePanel/DatabaseTable.tsx @@ -1,5 +1,5 @@ import { Classes } from '@blueprintjs/core'; -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { CSSProperties } from 'react'; import { memo, useMemo } from 'react'; import { ResponsiveChart } from 'react-d3-utils'; @@ -219,7 +219,7 @@ function DatabaseTable({ const columns = [...initialColumns]; for (const col of databaseTableColumns(databasePreferences)) { const { showWhen, ...colParams } = col; - if (lodashGet(databasePreferences, showWhen, false)) { + if (dlv(databasePreferences, showWhen, false)) { addCustomColumn(columns, colParams); } } diff --git a/src/component/panels/extra/preferences/ColumnsHelper.ts b/src/component/panels/extra/preferences/ColumnsHelper.ts index b4643e2a0..b6a64967d 100644 --- a/src/component/panels/extra/preferences/ColumnsHelper.ts +++ b/src/component/panels/extra/preferences/ColumnsHelper.ts @@ -1,5 +1,3 @@ -import lodashGet from 'lodash/get.js'; - import { formatNumber } from '../../../utility/formatNumber.js'; export default class ColumnsHelper { @@ -12,13 +10,11 @@ export default class ColumnsHelper { } public checkPreferences(preferencesToCheck, key) { - const val = !!( + return ( preferencesToCheck === undefined || Object.keys(preferencesToCheck).length === 0 || (preferencesToCheck && preferencesToCheck[key] === true) ); - - return val; } public setCustomColumn(array, index, columnLabel, cellHandler) { @@ -70,7 +66,3 @@ export default class ColumnsHelper { } } } - -export function isColumnVisible(preferences, key) { - return lodashGet(preferences, key, false); -} diff --git a/src/component/panels/hooks/useGetPanelOptions.ts b/src/component/panels/hooks/useGetPanelOptions.ts index 21a2be09c..123a0cc1e 100644 --- a/src/component/panels/hooks/useGetPanelOptions.ts +++ b/src/component/panels/hooks/useGetPanelOptions.ts @@ -1,4 +1,3 @@ -import lodashGet from 'lodash/get.js'; import type { PanelPreferencesType } from 'nmr-load-save'; import { useCallback } from 'react'; @@ -26,11 +25,8 @@ export function useGetPanelOptions(): ( }; } - return lodashGet( - preferences.current, - `display.panels.${item.id}`, - defaultValue, - ); + // TODO: make sure preferences are not a lie and remove the optional chaining. + return preferences?.current?.display?.panels?.[item.id] ?? defaultValue; }, [preferences], ); diff --git a/src/component/panels/hooks/useTogglePanel.ts b/src/component/panels/hooks/useTogglePanel.ts index b382987c8..1f5497a9f 100644 --- a/src/component/panels/hooks/useTogglePanel.ts +++ b/src/component/panels/hooks/useTogglePanel.ts @@ -1,4 +1,3 @@ -import lodashGet from 'lodash/get.js'; import type { NMRiumPanelPreferences } from 'nmr-load-save'; import { usePreferences } from '../../context/PreferencesContext.js'; @@ -9,7 +8,8 @@ export function useTogglePanel() { const { setPanelOpenState } = usePanelOpenState(); function togglePanel(id: keyof NMRiumPanelPreferences) { - const flag = lodashGet(current, `display.panels.${id}.display`); + // TODO: make sure current is not a lie and remove the optional chaining. + const flag = current?.display?.panels?.[id]?.display; if (typeof flag === 'boolean') { setPanelOpenState(id, !flag); } diff --git a/src/component/panels/multipleAnalysisPanel/AnalysisChart.tsx b/src/component/panels/multipleAnalysisPanel/AnalysisChart.tsx index 8e5a9ae14..8c36b116f 100644 --- a/src/component/panels/multipleAnalysisPanel/AnalysisChart.tsx +++ b/src/component/panels/multipleAnalysisPanel/AnalysisChart.tsx @@ -1,6 +1,6 @@ import type { ButtonProps } from '@blueprintjs/core'; import { css } from '@emotion/react'; -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { JpathTableColumn, Spectrum, @@ -20,8 +20,8 @@ import { useSortSpectra } from '../../context/SortSpectraContext.js'; import { useToaster } from '../../context/ToasterContext.js'; import { Input2 } from '../../elements/Input2.js'; import Label from '../../elements/Label.js'; -import { ToolbarPopoverItem } from '../../elements/ToolbarPopoverItem.js'; import type { ToolbarPopoverMenuItem } from '../../elements/ToolbarPopoverItem.js'; +import { ToolbarPopoverItem } from '../../elements/ToolbarPopoverItem.js'; import { usePanelPreferences } from '../../hooks/usePanelPreferences.js'; import useSpectraByActiveNucleus from '../../hooks/useSpectraPerNucleus.js'; import { copyPNGToClipboard } from '../../utility/export.js'; @@ -110,17 +110,13 @@ export function getPlotDataAsString( for (const col of spectraPanelPreferences.columns) { if (col.visible && 'jpath' in col) { const jpath = (col as JpathTableColumn)?.jpath; - const value = lodashGet(spectrum, jpath, `null`); + const value = dlv(spectrum, jpath, `null`); cellsValues.push(value); } } - const x = xData - ? xData[spectrum.id] - : lodashGet(spectrum, xPathKeys, index); - const y = yData - ? yData[spectrum.id] - : lodashGet(spectrum, yPathKeys, index); + const x = xData ? xData[spectrum.id] : dlv(spectrum, xPathKeys, index); + const y = yData ? yData[spectrum.id] : dlv(spectrum, yPathKeys, index); cellsValues.push(x, y); @@ -165,12 +161,8 @@ function usePlotData( plotOption, ); return spectra.map((spectrum, index) => { - const x = xData - ? xData[spectrum.id] - : lodashGet(spectrum, xPathKeys, index); - const y = yData - ? yData[spectrum.id] - : lodashGet(spectrum, yPathKeys, index); + const x = xData ? xData[spectrum.id] : dlv(spectrum, xPathKeys, index); + const y = yData ? yData[spectrum.id] : dlv(spectrum, yPathKeys, index); return { x, y, diff --git a/src/component/reducer/actions/SpectraActions.ts b/src/component/reducer/actions/SpectraActions.ts index d848dd9de..928c26442 100644 --- a/src/component/reducer/actions/SpectraActions.ts +++ b/src/component/reducer/actions/SpectraActions.ts @@ -1,7 +1,7 @@ import type { NmrData2DFid, NmrData2DFt } from 'cheminfo-types'; +import dlv from 'dlv'; import type { Draft } from 'immer'; import { original } from 'immer'; -import lodashGet from 'lodash/get.js'; import type { Color2D, Display1D, @@ -596,7 +596,7 @@ function handleToggleSpectraLegend(draft: Draft) { function groupSpectraByClass(spectra: Spectrum[], jpath: string | string[]) { const spectraByClass: Record = {}; for (const spectrum of spectra) { - const key = String(lodashGet(spectrum, jpath, '')) + const key = String(dlv(spectrum, jpath, '')) .toLowerCase() .trim() .replace(/\r?\n|\r/, ''); diff --git a/src/component/utility/LocalStorage.ts b/src/component/utility/LocalStorage.ts index e1dc8202e..7bcbcbea1 100644 --- a/src/component/utility/LocalStorage.ts +++ b/src/component/utility/LocalStorage.ts @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import lodashSet from 'lodash/set.js'; import { useCallback, useEffect, useMemo, useState } from 'react'; @@ -24,10 +24,7 @@ export function useStateWithLocalStorage(localStorageKey, key?: string) { ); return useMemo(() => { - return [ - key ? lodashGet(JSON.parse(value), key, {}) : JSON.parse(value), - setData, - ]; + return [key ? dlv(JSON.parse(value), key, {}) : JSON.parse(value), setData]; }, [key, setData, value]); } @@ -45,5 +42,5 @@ export function removeData(localStorageKey) { } export function getValue(object, keyPath, defaultValue: any = null) { - return lodashGet(object, keyPath, defaultValue); + return dlv(object, keyPath, defaultValue); } diff --git a/src/component/utility/export.ts b/src/component/utility/export.ts index f120106b1..0e4c6bae8 100644 --- a/src/component/utility/export.ts +++ b/src/component/utility/export.ts @@ -1,7 +1,7 @@ import type { SerializedStyles } from '@emotion/react'; +import dlv from 'dlv'; import fileSaver from 'file-saver'; import JSZip from 'jszip'; -import lodashGet from 'lodash/get.js'; import type { JpathTableColumn, SpectraTableColumn } from 'nmr-load-save'; /** @@ -74,7 +74,7 @@ function exportAsMatrix( for (const col of spectraColumns) { if (col.visible && 'jpath' in col) { const jpath = (col as JpathTableColumn)?.jpath; - cellsValues.push(lodashGet(spectrum, jpath, `null`)); + cellsValues.push(dlv(spectrum, jpath, `null`)); } } for (const value of re) { diff --git a/src/data/data1d/multipleSpectraAnalysis.ts b/src/data/data1d/multipleSpectraAnalysis.ts index 625341cfd..61d3cb02b 100644 --- a/src/data/data1d/multipleSpectraAnalysis.ts +++ b/src/data/data1d/multipleSpectraAnalysis.ts @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { AnalysisColumnsValuesKeys, AnalysisOptions, @@ -304,7 +304,7 @@ export function getDataAsString( for (const col of spectraPanelPreferences.columns) { if (col.visible && 'jpath' in col) { const jpath = (col as JpathTableColumn)?.jpath; - const value = lodashGet(spectrum, jpath, `null`); + const value = dlv(spectrum, jpath, `null`); cellsValues.push(value); } } diff --git a/src/data/parseMeta/linkMetaWithSpectra.ts b/src/data/parseMeta/linkMetaWithSpectra.ts index b6f958edd..809b8410f 100644 --- a/src/data/parseMeta/linkMetaWithSpectra.ts +++ b/src/data/parseMeta/linkMetaWithSpectra.ts @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { Spectrum } from 'nmr-load-save'; import type { ParseResult } from 'papaparse'; @@ -28,7 +28,7 @@ function linkMetaWithSpectra(options: { } = parseMetaFileResult; if (!autolink) { - if (target && !lodashGet(spectra[0], target)) { + if (target && !dlv(spectra[0], target)) { throw new TargetPathError(target); } @@ -39,7 +39,7 @@ function linkMetaWithSpectra(options: { if (autolink) { for (const sourceField of fields) { - if (lodashGet(spectra[0], sourceField, null)) { + if (dlv(spectra[0], sourceField, null)) { source = sourceField; target = sourceField; break; @@ -53,7 +53,7 @@ function linkMetaWithSpectra(options: { if (source && target) { for (const spectrum of spectra) { - const value = lodashGet(spectrum, target); + const value = dlv(spectrum, target); if (['string', 'number'].includes(typeof value)) { const val = prepareKey(value); diff --git a/src/data/utilities/getCustomColor.ts b/src/data/utilities/getCustomColor.ts index aeb2cd181..2006c257e 100644 --- a/src/data/utilities/getCustomColor.ts +++ b/src/data/utilities/getCustomColor.ts @@ -1,4 +1,4 @@ -import lodashGet from 'lodash/get.js'; +import dlv from 'dlv'; import type { Color2D, Spectrum1D, @@ -12,7 +12,7 @@ type ReturnColor = ColorType extends SpectrumOneDimensionColor : Color2D; function getValue(spectrum: Spectrum1D | Spectrum2D, jpath: string[]) { - const value = lodashGet(spectrum, jpath); + const value = dlv(spectrum, jpath); if (typeof value === 'string') { return value;