diff --git a/src/component/1d-2d/FieldEdition.tsx b/src/component/1d-2d/FieldEdition.tsx
index 54a3b601a..da7b4b8e8 100644
--- a/src/component/1d-2d/FieldEdition.tsx
+++ b/src/component/1d-2d/FieldEdition.tsx
@@ -2,7 +2,7 @@ import type { PopoverNextProps } from '@blueprintjs/core';
import { PopoverNext } from '@blueprintjs/core';
import styled from '@emotion/styled';
import { revalidateLogic } from '@tanstack/react-form';
-import type { ReactNode } from 'react';
+import type { ReactElement, ReactNode } from 'react';
import { useMemo, useState } from 'react';
import { AppForm, coerceNumberInput, useForm } from 'react-science/ui';
import { match } from 'ts-pattern';
@@ -20,6 +20,7 @@ interface FieldProps {
value: number | string;
inputType?: InputType;
onChange: (value: string) => void;
+ rightElement?: ReactElement;
}
interface FieldEditionsProps extends FieldProps {
@@ -43,7 +44,16 @@ export function FieldEdition(props: FieldEditionsProps) {
onClose={() => setIsOpen(false)}
onInteraction={() => setIsOpen(true)}
content={
-
+ setIsOpen(false)}>{props.rightElement}
+ )
+ }
+ />
}
{...PopoverProps}
>
@@ -70,7 +80,7 @@ function validationSchema(
}
function Field(props: FieldProps) {
- const { value, inputType = 'text', onChange } = props;
+ const { value, inputType = 'text', onChange, rightElement } = props;
const validation = useMemo(() => {
return validationSchema(inputType).transform(({ value }) => {
@@ -99,7 +109,7 @@ function Field(props: FieldProps) {
inputType === 'number' ? (
) : (
-
+
)
}
diff --git a/src/component/2d/SVGContent2D.tsx b/src/component/2d/SVGContent2D.tsx
index d338165de..085ceee0d 100644
--- a/src/component/2d/SVGContent2D.tsx
+++ b/src/component/2d/SVGContent2D.tsx
@@ -6,6 +6,7 @@ import DirectAxis2D from './DirectAxis2D.tsx';
import IndirectAxis2D from './IndirectAxis2D.tsx';
import { FidContainer } from './fid/FidContainer.js';
import { FTContainer } from './ft/FTContainer.js';
+import { LinkedSignals } from './linked-signals/LinkedSignals.js';
import type { Spectrum1DTraces } from './useTracesSpectra.js';
import { SignalsGuideLines } from './zones/SignalsGuideLines.js';
import Zones from './zones/Zones.js';
@@ -26,6 +27,7 @@ export function SVGContent2D({ spectra }: Chart2DProps) {
+
diff --git a/src/component/2d/SignalDeltaLine.tsx b/src/component/2d/SignalDeltaLine.tsx
index 7e8f2e5b4..c1c92794c 100644
--- a/src/component/2d/SignalDeltaLine.tsx
+++ b/src/component/2d/SignalDeltaLine.tsx
@@ -1,5 +1,6 @@
import styled from '@emotion/styled';
import { assert } from '@zakodium/utils';
+import type { CSSProperties } from 'react';
import { useChartData } from '../context/ChartContext.js';
@@ -7,7 +8,6 @@ import { useScale2DX, useScale2DY } from './utilities/scale.js';
const SignalLine = styled.line`
opacity: 0.5;
- stroke: green;
stroke-width: 2;
`;
@@ -15,10 +15,12 @@ interface SignalDeltaLineProps {
delta: number;
axis: 'X' | 'Y';
show: boolean;
+ color?: string;
+ style?: CSSProperties;
}
function SignalDeltaLine(props: SignalDeltaLineProps) {
- const { delta, axis, show } = props;
+ const { delta, axis, show, color = 'green', style } = props;
const { xDomain, yDomain } = useChartData();
const scaleX = useScale2DX();
const scaleY = useScale2DY();
@@ -29,6 +31,8 @@ function SignalDeltaLine(props: SignalDeltaLineProps) {
return (
`
+ &:hover > circle:first-of-type {
+ fill: ${(props) => props.color};
+ stroke-width: 5;
+ }
+`;
+
+interface LinkedSignalProps {
+ signal: PositionedLinkedSignal;
+}
+export function LinkedSignal({ signal }: LinkedSignalProps) {
+ const scaleX = useScale2DX();
+ const scaleY = useScale2DY();
+ const dispatch = useDispatch();
+ const { data: newLabel, setData } = useShareData();
+ const diaIDs = [...signal.xDiaIDs, ...signal.yDiaIDs];
+ const { onHover } = useHighlight(diaIDs, { type: 'LINKED_SIGNAL' });
+ const id = `${signal.xSignalId}:${signal.ySignalId}`;
+ const { color } = useClassifyCorrelation(signal.xDiaIDs, signal.yDiaIDs);
+
+ function handleKeyDown(event: KeyboardEvent) {
+ if (event.key === 'Backspace' || event.key === 'Delete') {
+ event.preventDefault();
+ event.stopPropagation();
+ dispatch({ type: 'DELETE_2D_SIGNAL_LINK', payload: { id } });
+ if (newLabel === id) {
+ setData(null);
+ }
+ }
+ }
+
+ return (
+
+ {
+ if (newLabel !== id) event.currentTarget.focus();
+ }}
+ onMouseLeave={(event) => event.currentTarget.blur()}
+ onClick={(event) => {
+ event.stopPropagation();
+ setData(id);
+ }}
+ />
+
+
+
+ );
+}
diff --git a/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx b/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx
new file mode 100644
index 000000000..14ce1908d
--- /dev/null
+++ b/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx
@@ -0,0 +1,247 @@
+import styled from '@emotion/styled';
+import { isSpectrum2D } from '@zakodium/nmrium-core';
+import { useLayoutEffect, useRef, useState } from 'react';
+import { PiTextTSlash } from 'react-icons/pi';
+import { Button } from 'react-science/ui';
+
+import { FieldEdition } from '../../1d-2d/FieldEdition.js';
+import { disableMouseTrackingProps } from '../../EventsTrackers/MouseTracker.js';
+import { useChartData } from '../../context/ChartContext.js';
+import { useDispatch } from '../../context/DispatchContext.js';
+import { useGlobal } from '../../context/GlobalContext.js';
+import { useShareData } from '../../context/ShareDataContext.js';
+import { SVGButton } from '../../elements/SVGButton.js';
+import type { Position } from '../../elements/draggable/useDraggable.js';
+import useDraggable from '../../elements/draggable/useDraggable.js';
+import useSpectrum from '../../hooks/useSpectrum.js';
+import { useExtractAtomAssignmentLabel } from '../../panels/MoleculesPanel/hooks/useExtractAtomAssignmentLabel.js';
+import { useScale2DX, useScale2DY } from '../utilities/scale.js';
+import type { PositionedLinkedSignal } from '../utilities/signalCrossings.js';
+import { getCrossingAssignmentLabel } from '../utilities/signalCrossings.js';
+import { useAssignmentLabelLinkPath } from '../utilities/useAssignmentLabelLinkPath.js';
+
+const LabelContainer = styled.g<{ isMoving: boolean }>`
+ pointer-events: bounding-box;
+
+ .controls {
+ visibility: ${({ isMoving }) => (isMoving ? 'visible' : 'hidden')};
+ }
+
+ &:hover .controls {
+ visibility: visible;
+ }
+`;
+
+interface LinkedSignalAssignmentLabelProps {
+ signal: PositionedLinkedSignal;
+ color: string;
+}
+
+export function LinkedSignalAssignmentLabel({
+ signal,
+ color,
+}: LinkedSignalAssignmentLabelProps) {
+ const { xSignalId, ySignalId, assignment, isAutoAssignment } = signal;
+ const id = `${xSignalId}:${ySignalId}`;
+ const hasLink = signal.xDiaIDs.length > 0 || signal.yDiaIDs.length > 0;
+ const scaleX = useScale2DX();
+ const scaleY = useScale2DY();
+ const dispatch = useDispatch();
+ const { getAssignmentLabelByDiaIDs } = useExtractAtomAssignmentLabel();
+ const { viewerRef } = useGlobal();
+ const { data: newLabel, setData: setNewLabel } = useShareData<
+ string | null
+ >();
+ const [dragPosition, setDragPosition] = useState(null);
+ const textRef = useRef(null);
+ const [labelBoundary, setLabelBoundary] = useState({ width: 0, height: 0 });
+ const moveOffset = { x: labelBoundary.width / 2 + 24, y: 18 };
+
+ useLayoutEffect(() => {
+ if (textRef.current) {
+ const { width, height } = textRef.current.getBBox();
+ setLabelBoundary({ width, height });
+ }
+ }, [assignment]);
+
+ const { coordinate, position, path, spectrum } =
+ useLinkedSignalAssignmentLabelPosition({
+ id,
+ signal,
+ dragPosition,
+ labelBoundary,
+ });
+ const isNewLabel = newLabel === id;
+ const { onPointerDown } = useDraggable({
+ position: coordinate,
+ parentElement: viewerRef,
+ onChange: ({ action, position }) => {
+ if (action === 'start') {
+ setDragPosition(coordinate);
+ } else if (action === 'move' || action === 'end') {
+ const nextPosition = {
+ x: position.x + moveOffset.x,
+ y: position.y + moveOffset.y,
+ };
+ if (action === 'move') {
+ setDragPosition(nextPosition);
+ } else {
+ if (!spectrum) return;
+
+ dispatch({
+ type: 'SET_LINKED_SIGNAL_ASSIGNMENT_LABEL_COORDINATION',
+ payload: {
+ spectrumId: spectrum.id,
+ id,
+ coordination: {
+ x: scaleX.invert(nextPosition.x),
+ y: scaleY.invert(nextPosition.y),
+ },
+ },
+ });
+ setDragPosition(null);
+ }
+ }
+ },
+ });
+
+ if (!assignment && !isNewLabel) return null;
+
+ function handleChange(value: string) {
+ if (isNewLabel) setNewLabel(null);
+ dispatch({
+ type: 'CHANGE_LINKED_SIGNAL_ASSIGNMENT_LABEL',
+ payload: { id, value },
+ });
+ }
+
+ function handleAssignmentLabel() {
+ if (!hasLink) return;
+
+ const isAutoAssignment = !signal.isAutoAssignment;
+ let value = signal.assignment ?? '';
+
+ if (isAutoAssignment) {
+ const autoLabel = getCrossingAssignmentLabel({
+ xAssignment: getAssignmentLabelByDiaIDs(signal.xDiaIDs),
+ yAssignment: getAssignmentLabelByDiaIDs(signal.yDiaIDs),
+ hasSameNucleus:
+ isSpectrum2D(spectrum) &&
+ spectrum.info.nucleus[0] === spectrum.info.nucleus[1],
+ });
+ if (!autoLabel) return;
+ value = autoLabel;
+ }
+
+ dispatch({
+ type: 'CHANGE_LINKED_SIGNAL_ASSIGNMENT_LABEL',
+ payload: { id, value, isAutoAssignment },
+ });
+ }
+
+ return (
+ {
+ if (!isNewLabel) event.currentTarget.focus();
+ }}
+ onMouseLeave={(event) => event.currentTarget.blur()}
+ >
+
+
+
+ }
+ PopoverProps={{
+ placement: 'top',
+ targetTagName: 'g',
+ ...(isNewLabel && {
+ isOpen: true,
+ onClose: () => setNewLabel(null),
+ }),
+ }}
+ >
+
+ {assignment}
+
+
+
+
+ }
+ backgroundColor="red"
+ onClick={() => handleChange('')}
+ />
+
+
+
+ );
+}
+
+interface UseLinkedSignalAssignmentLabelPositionOptions {
+ id: string;
+ signal: PositionedLinkedSignal;
+ dragPosition: Position | null;
+ labelBoundary: { width: number; height: number };
+}
+
+function useLinkedSignalAssignmentLabelPosition({
+ id,
+ signal: { xDelta, yDelta },
+ dragPosition,
+ labelBoundary,
+}: UseLinkedSignalAssignmentLabelPositionOptions) {
+ const scaleX = useScale2DX();
+ const scaleY = useScale2DY();
+ const spectrum = useSpectrum();
+ const { view } = useChartData();
+ const externalPosition =
+ spectrum && view.assignmentsLabelsCoordinates?.[spectrum.id]?.[id];
+
+ const coordinate = externalPosition
+ ? { x: scaleX(externalPosition.x), y: scaleY(externalPosition.y) }
+ : { x: scaleX(xDelta) + 20, y: scaleY(yDelta) - 30 };
+ const position = dragPosition ?? coordinate;
+ const path = useAssignmentLabelLinkPath(
+ position,
+ { x1: xDelta, x2: xDelta, y1: yDelta, y2: yDelta },
+ labelBoundary,
+ );
+
+ return { coordinate, position, path, spectrum };
+}
diff --git a/src/component/2d/linked-signals/LinkedSignals.tsx b/src/component/2d/linked-signals/LinkedSignals.tsx
new file mode 100644
index 000000000..0c2133f72
--- /dev/null
+++ b/src/component/2d/linked-signals/LinkedSignals.tsx
@@ -0,0 +1,56 @@
+import type { Spectrum2D } from '@zakodium/nmr-types';
+import { isSpectrum2DFt } from '@zakodium/nmrium-core';
+import { useMemo } from 'react';
+
+import { useChartData } from '../../context/ChartContext.js';
+import { ShareDataProvider } from '../../context/ShareDataContext.js';
+import useSpectrum from '../../hooks/useSpectrum.js';
+import { useTracesSpectra } from '../useTracesSpectra.js';
+import { extractSpectrumSignals } from '../utilities/extractSpectrumSignals.js';
+import { getLinkedSignalPositions } from '../utilities/signalCrossings.js';
+
+import { LinkedSignal } from './LinkedSignal.js';
+import { SignalCrossingIndicator } from './SignalCrossingIndicator.js';
+
+export function LinkedSignals() {
+ const spectrum = useSpectrum();
+ if (!isSpectrum2DFt(spectrum) || !spectrum.display.isVisible) return null;
+
+ return (
+
+
+
+ );
+}
+
+function LinkedSignalsInner({
+ linkedSignals,
+}: Pick) {
+ const traces = useTracesSpectra();
+ const {
+ toolOptions: { selectedTool },
+ } = useChartData();
+ const signals = useMemo(() => {
+ if (!traces.x || !traces.y) return [];
+
+ return getLinkedSignalPositions({
+ xSignals: extractSpectrumSignals(traces.x),
+ ySignals: extractSpectrumSignals(traces.y),
+ linkedSignals,
+ });
+ }, [traces.x, traces.y, linkedSignals]);
+
+ return (
+
+ {signals.map((signal) => (
+
+ ))}
+ {selectedTool === 'signalLinking' && (
+
+ )}
+
+ );
+}
diff --git a/src/component/2d/linked-signals/SignalCrossingIndicator.tsx b/src/component/2d/linked-signals/SignalCrossingIndicator.tsx
new file mode 100644
index 000000000..39a32c167
--- /dev/null
+++ b/src/component/2d/linked-signals/SignalCrossingIndicator.tsx
@@ -0,0 +1,62 @@
+import type { Spectrum2D } from '@zakodium/nmr-types';
+import type { MouseEvent } from 'react';
+
+import { useDispatch } from '../../context/DispatchContext.js';
+import { useIsPrimaryKeyActivated } from '../../context/KeyModifierContext.js';
+import { useShareData } from '../../context/ShareDataContext.js';
+import SignalDeltaLine from '../SignalDeltaLine.js';
+import { useNearestSignalCrossing } from '../useNearestSignalCrossing.js';
+import { useScale2DX, useScale2DY } from '../utilities/scale.js';
+
+export function SignalCrossingIndicator({
+ linkedSignals,
+}: Pick) {
+ const { nearest } = useNearestSignalCrossing({ linkedSignals });
+ const scaleX = useScale2DX();
+ const scaleY = useScale2DY();
+ const dispatch = useDispatch();
+ const { setData } = useShareData();
+ const isPrimary = useIsPrimaryKeyActivated();
+
+ if (!isPrimary || !nearest || nearest.isLinked) return null;
+
+ const { xSignalId, ySignalId, assignment } = nearest;
+
+ function handleClick(event: MouseEvent) {
+ if (event.button !== 0) return;
+
+ event.stopPropagation();
+
+ dispatch({
+ type: 'ADD_2D_SIGNAL_LINK',
+ payload: {
+ xSignalId,
+ ySignalId,
+ assignment,
+ },
+ });
+
+ if (!assignment) {
+ setData(`${xSignalId}:${ySignalId}`);
+ }
+ }
+
+ return (
+
+
+
+
+
+ );
+}
diff --git a/src/component/2d/linked-signals/useClassifyCorrelation.ts b/src/component/2d/linked-signals/useClassifyCorrelation.ts
new file mode 100644
index 000000000..293106612
--- /dev/null
+++ b/src/component/2d/linked-signals/useClassifyCorrelation.ts
@@ -0,0 +1,24 @@
+import { useTopicMolecule } from '../../context/TopicMoleculeContext.js';
+import useSpectrum from '../../hooks/useSpectrum.js';
+
+import {
+ CORRELATION_COLORS,
+ getCorrelationColor,
+} from './utilities/getCorrelationColor.js';
+import { getCouplingLength } from './utilities/getCouplingLength.js';
+
+export function useClassifyCorrelation(xDiaIDs: string[], yDiaIDs: string[]) {
+ const topicMolecules = useTopicMolecule();
+ const spectrum = useSpectrum();
+
+ let color = CORRELATION_COLORS.unknown;
+
+ const couplingLength = getCouplingLength(topicMolecules, xDiaIDs, yDiaIDs);
+ const experiment = spectrum?.info.experiment;
+
+ if (couplingLength !== null && experiment) {
+ color = getCorrelationColor(experiment, couplingLength);
+ }
+
+ return { couplingLength, color };
+}
diff --git a/src/component/2d/linked-signals/utilities/getCorrelationColor.ts b/src/component/2d/linked-signals/utilities/getCorrelationColor.ts
new file mode 100644
index 000000000..8ad0ca54a
--- /dev/null
+++ b/src/component/2d/linked-signals/utilities/getCorrelationColor.ts
@@ -0,0 +1,46 @@
+type CorrelationStatus = 'normal' | 'suspicious' | 'unexpected' | 'unknown';
+
+export const CORRELATION_COLORS: Record = {
+ normal: 'green',
+ suspicious: 'orange',
+ unexpected: 'red',
+ unknown: 'grey',
+};
+interface Rule {
+ min?: number;
+ max?: number;
+ correlationStatus: CorrelationStatus;
+}
+
+const RULES: Record = {
+ cosy: [
+ { max: 3, correlationStatus: 'normal' },
+ { min: 4, max: 4, correlationStatus: 'suspicious' },
+ { min: 6, correlationStatus: 'unexpected' },
+ ],
+ hsqc: [
+ { min: 1, max: 1, correlationStatus: 'normal' },
+ { correlationStatus: 'unexpected' },
+ ],
+ hmbc: [
+ { max: 3, correlationStatus: 'normal' },
+ { min: 4, max: 4, correlationStatus: 'suspicious' },
+ { min: 5, correlationStatus: 'unexpected' },
+ ],
+};
+export function getCorrelationColor(
+ experiment: string,
+ distance: number,
+): string {
+ experiment = experiment.toLowerCase();
+
+ const rule = RULES[experiment].find(
+ ({ min, max }) =>
+ (min === undefined || distance >= min) &&
+ (max === undefined || distance <= max),
+ );
+
+ return rule
+ ? CORRELATION_COLORS[rule.correlationStatus]
+ : CORRELATION_COLORS.unknown;
+}
diff --git a/src/component/2d/linked-signals/utilities/getCouplingLength.ts b/src/component/2d/linked-signals/utilities/getCouplingLength.ts
new file mode 100644
index 000000000..4446ef5fb
--- /dev/null
+++ b/src/component/2d/linked-signals/utilities/getCouplingLength.ts
@@ -0,0 +1,58 @@
+import type { TopicMolecule } from 'openchemlib-utils';
+
+export function getCouplingLength(
+ topicMolecules: Record,
+ xDiaIDs: string[],
+ yDiaIDs: string[],
+): number | null {
+ const candidates = getCouplingCandidates(topicMolecules, xDiaIDs, yDiaIDs);
+ if (candidates.length === 0) return null;
+ return Math.min(...candidates.map((c) => c.distance));
+}
+
+interface CouplingCandidate {
+ moleculeId: string;
+ xDiaID: string;
+ yDiaID: string;
+ xAtom: number;
+ yAtom: number;
+ distance: number;
+}
+
+function getCouplingCandidates(
+ topicMolecules: Record,
+ xDiaIDs: string[],
+ yDiaIDs: string[],
+): CouplingCandidate[] {
+ const couplingCandidate: CouplingCandidate[] = [];
+ if (xDiaIDs.length === 0 || yDiaIDs.length === 0) return couplingCandidate;
+
+ for (const [moleculeId, topicMolecule] of Object.entries(topicMolecules)) {
+ const diaIDsObject = topicMolecule.getDiaIDsObject();
+ for (const x of xDiaIDs) {
+ const xGroup = diaIDsObject[x];
+ if (!xGroup) continue;
+ for (const y of yDiaIDs) {
+ const yGroup = diaIDsObject[y];
+ if (!yGroup) continue;
+
+ for (const xAtom of xGroup.atoms) {
+ for (const yAtom of yGroup.atoms) {
+ const distance = topicMolecule.distanceMatrix[xAtom][yAtom];
+ if (distance >= 0) {
+ couplingCandidate.push({
+ moleculeId,
+ xDiaID: x,
+ yDiaID: y,
+ xAtom,
+ yAtom,
+ distance,
+ });
+ }
+ }
+ }
+ }
+ }
+ }
+ return couplingCandidate;
+}
diff --git a/src/component/2d/useNearestSignalCrossing.ts b/src/component/2d/useNearestSignalCrossing.ts
new file mode 100644
index 000000000..e383593e2
--- /dev/null
+++ b/src/component/2d/useNearestSignalCrossing.ts
@@ -0,0 +1,68 @@
+import type { Spectrum2D } from '@zakodium/nmr-types';
+import { useMemo } from 'react';
+
+import { useMouseTracker } from '../EventsTrackers/MouseTracker.js';
+import { useChartData } from '../context/ChartContext.js';
+
+import { useTracesSpectra } from './useTracesSpectra.js';
+import { extractSpectrumSignals } from './utilities/extractSpectrumSignals.js';
+import { useScale2DX, useScale2DY } from './utilities/scale.js';
+import {
+ buildCandidates,
+ findNearestCrossing,
+} from './utilities/signalCrossings.js';
+
+interface UseNearestSignalCrossingOptions extends Pick<
+ Spectrum2D,
+ 'linkedSignals'
+> {
+ radius?: number;
+}
+
+/**
+ * Returns the nearest visible crossing within the pixel radius, or null
+ */
+export function useNearestSignalCrossing({
+ linkedSignals,
+ radius = 10,
+}: UseNearestSignalCrossingOptions) {
+ const traces = useTracesSpectra();
+ const mouse = useMouseTracker();
+ const scaleX = useScale2DX();
+ const scaleY = useScale2DY();
+ const { width, height, margin, xDomain, yDomain } = useChartData();
+ const candidates = useMemo(() => {
+ if (!traces.x || !traces.y) return [];
+
+ const signalsX = extractSpectrumSignals(traces.x);
+ const signalsY = extractSpectrumSignals(traces.y);
+ const hasSameNucleus = traces.x.info.nucleus === traces.y.info.nucleus;
+
+ return buildCandidates({
+ xSignals: signalsX,
+ ySignals: signalsY,
+ linkedSignals,
+ domains: { xDomain, yDomain },
+ hasSameNucleus,
+ });
+ }, [traces.x, traces.y, linkedSignals, xDomain, yDomain]);
+
+ if (
+ !mouse ||
+ mouse.x < margin.left ||
+ mouse.x > width - margin.right ||
+ mouse.y < margin.top ||
+ mouse.y > height - margin.bottom
+ ) {
+ return { candidates, nearest: null };
+ }
+
+ const nearest = findNearestCrossing(
+ mouse,
+ candidates,
+ { x: scaleX, y: scaleY },
+ radius,
+ );
+
+ return { candidates, nearest };
+}
diff --git a/src/component/2d/utilities/getCorrelationColor.ts b/src/component/2d/utilities/getCorrelationColor.ts
new file mode 100644
index 000000000..0ac8d043b
--- /dev/null
+++ b/src/component/2d/utilities/getCorrelationColor.ts
@@ -0,0 +1,35 @@
+type CorrelationColor = 'green' | 'orange' | 'red' | 'grey';
+
+interface Rule {
+ min?: number;
+ max?: number;
+ color: CorrelationColor;
+}
+
+const RULES: Record = {
+ cosy: [
+ { max: 3, color: 'green' },
+ { min: 4, max: 4, color: 'orange' },
+ { min: 6, color: 'red' },
+ ],
+ hsqc: [{ min: 1, max: 1, color: 'green' }, { color: 'red' }],
+ hmbc: [
+ { max: 3, color: 'green' },
+ { min: 4, max: 4, color: 'orange' },
+ { min: 5, color: 'red' },
+ ],
+};
+export function getCorrelationColor(
+ experiment: string,
+ distance: number,
+): CorrelationColor {
+ experiment = experiment?.toLowerCase();
+
+ const rule = RULES[experiment].find(
+ ({ min, max }) =>
+ (min === undefined || distance >= min) &&
+ (max === undefined || distance <= max),
+ );
+
+ return rule?.color ?? 'grey';
+}
diff --git a/src/component/2d/utilities/getCouplingLength.ts b/src/component/2d/utilities/getCouplingLength.ts
new file mode 100644
index 000000000..4446ef5fb
--- /dev/null
+++ b/src/component/2d/utilities/getCouplingLength.ts
@@ -0,0 +1,58 @@
+import type { TopicMolecule } from 'openchemlib-utils';
+
+export function getCouplingLength(
+ topicMolecules: Record,
+ xDiaIDs: string[],
+ yDiaIDs: string[],
+): number | null {
+ const candidates = getCouplingCandidates(topicMolecules, xDiaIDs, yDiaIDs);
+ if (candidates.length === 0) return null;
+ return Math.min(...candidates.map((c) => c.distance));
+}
+
+interface CouplingCandidate {
+ moleculeId: string;
+ xDiaID: string;
+ yDiaID: string;
+ xAtom: number;
+ yAtom: number;
+ distance: number;
+}
+
+function getCouplingCandidates(
+ topicMolecules: Record,
+ xDiaIDs: string[],
+ yDiaIDs: string[],
+): CouplingCandidate[] {
+ const couplingCandidate: CouplingCandidate[] = [];
+ if (xDiaIDs.length === 0 || yDiaIDs.length === 0) return couplingCandidate;
+
+ for (const [moleculeId, topicMolecule] of Object.entries(topicMolecules)) {
+ const diaIDsObject = topicMolecule.getDiaIDsObject();
+ for (const x of xDiaIDs) {
+ const xGroup = diaIDsObject[x];
+ if (!xGroup) continue;
+ for (const y of yDiaIDs) {
+ const yGroup = diaIDsObject[y];
+ if (!yGroup) continue;
+
+ for (const xAtom of xGroup.atoms) {
+ for (const yAtom of yGroup.atoms) {
+ const distance = topicMolecule.distanceMatrix[xAtom][yAtom];
+ if (distance >= 0) {
+ couplingCandidate.push({
+ moleculeId,
+ xDiaID: x,
+ yDiaID: y,
+ xAtom,
+ yAtom,
+ distance,
+ });
+ }
+ }
+ }
+ }
+ }
+ }
+ return couplingCandidate;
+}
diff --git a/src/component/2d/utilities/signalCrossings.ts b/src/component/2d/utilities/signalCrossings.ts
new file mode 100644
index 000000000..178d734ff
--- /dev/null
+++ b/src/component/2d/utilities/signalCrossings.ts
@@ -0,0 +1,167 @@
+import type { Signal1D, Spectrum2D } from '@zakodium/nmr-types';
+
+export interface Candidate {
+ xSignalId: string;
+ ySignalId: string;
+ xDelta: number;
+ yDelta: number;
+ isLinked: boolean;
+ assignment: string;
+}
+
+export interface CrossingScales {
+ x: (ppm: number) => number;
+ y: (ppm: number) => number;
+}
+
+interface CrossingDomains {
+ xDomain: number[];
+ yDomain: number[];
+}
+
+interface BuildCandidatesOptions extends Pick {
+ xSignals: Signal1D[];
+ ySignals: Signal1D[];
+ domains: CrossingDomains;
+ hasSameNucleus: boolean;
+}
+
+interface Position {
+ x: number;
+ y: number;
+}
+
+type LinkedSignal = Spectrum2D['linkedSignals'][number];
+
+export interface PositionedLinkedSignal extends LinkedSignal {
+ xDelta: number;
+ yDelta: number;
+ xDiaIDs: string[];
+ yDiaIDs: string[];
+}
+
+export function getLinkedSignalPositions({
+ xSignals,
+ ySignals,
+ linkedSignals,
+}: Omit<
+ BuildCandidatesOptions,
+ 'domains' | 'hasSameNucleus'
+>): PositionedLinkedSignal[] {
+ if (!linkedSignals?.length) return [];
+
+ const xSignalsById = new Map(xSignals.map((signal) => [signal.id, signal]));
+ const ySignalsById = new Map(ySignals.map((signal) => [signal.id, signal]));
+ const positionedSignals: PositionedLinkedSignal[] = [];
+
+ for (const link of linkedSignals) {
+ const xSignal = xSignalsById.get(link.xSignalId);
+ const ySignal = ySignalsById.get(link.ySignalId);
+
+ if (xSignal === undefined || ySignal === undefined) continue;
+
+ positionedSignals.push({
+ ...link,
+ xDelta: xSignal.delta,
+ yDelta: ySignal.delta,
+ xDiaIDs: xSignal.diaIDs ?? [],
+ yDiaIDs: ySignal.diaIDs ?? [],
+ });
+ }
+
+ return positionedSignals;
+}
+
+function inDomain(value: number, domain: number[]) {
+ const [min, max] = domain;
+ return value >= Math.min(min, max) && value <= Math.max(min, max);
+}
+
+interface CrossingAssignmentLabelOptions {
+ xAssignment?: string;
+ yAssignment?: string;
+ hasSameNucleus: boolean;
+}
+
+export function getCrossingAssignmentLabel({
+ xAssignment,
+ yAssignment,
+ hasSameNucleus,
+}: CrossingAssignmentLabelOptions): string {
+ if (hasSameNucleus && xAssignment === yAssignment) {
+ return xAssignment || '';
+ }
+
+ return [xAssignment, yAssignment].filter(Boolean).join('→');
+}
+
+export function buildCandidates({
+ xSignals,
+ ySignals,
+ linkedSignals,
+ domains,
+ hasSameNucleus,
+}: BuildCandidatesOptions): Candidate[] {
+ const linked = new Set(
+ linkedSignals?.map((link) => `${link.xSignalId}:${link.ySignalId}`),
+ );
+ const xs = xSignals.filter((signal) =>
+ inDomain(signal.delta, domains.xDomain),
+ );
+ const ys = ySignals.filter((signal) =>
+ inDomain(signal.delta, domains.yDomain),
+ );
+ const candidates: Candidate[] = [];
+
+ for (const x of xs) {
+ for (const y of ys) {
+ candidates.push({
+ xSignalId: x.id,
+ ySignalId: y.id,
+ xDelta: x.delta,
+ yDelta: y.delta,
+ isLinked: linked.has(`${x.id}:${y.id}`),
+ assignment: getCrossingAssignmentLabel({
+ xAssignment: x.assignment,
+ yAssignment: y.assignment,
+ hasSameNucleus,
+ }),
+ });
+ }
+ }
+ return candidates;
+}
+
+function distance(
+ candidate: Candidate,
+ mouse: Position,
+ scales: CrossingScales,
+) {
+ return Math.hypot(
+ scales.x(candidate.xDelta) - mouse.x,
+ scales.y(candidate.yDelta) - mouse.y,
+ );
+}
+
+export function findNearestCrossing(
+ mouse: Position,
+ candidates: Candidate[],
+ scales: CrossingScales,
+ radius = 14,
+): Candidate | null {
+ let best: Candidate | null = null;
+ let bestDistance = Infinity;
+
+ for (const candidate of candidates) {
+ const candidateDistance = distance(candidate, mouse, scales);
+ if (candidateDistance < bestDistance) {
+ bestDistance = candidateDistance;
+ best = candidate;
+ }
+ }
+
+ //return null if the nearest crossing is outside the cursor's pixel radius.
+ if (!best || bestDistance > radius) return null;
+
+ return best;
+}
diff --git a/src/component/2d/utilities/useAssignmentLabelLinkPath.ts b/src/component/2d/utilities/useAssignmentLabelLinkPath.ts
new file mode 100644
index 000000000..7bfe8f290
--- /dev/null
+++ b/src/component/2d/utilities/useAssignmentLabelLinkPath.ts
@@ -0,0 +1,138 @@
+import type { Position } from '../../elements/draggable/useDraggable.js';
+
+import { useScale2DX, useScale2DY } from './scale.js';
+
+interface TargetBoundary {
+ x1: number;
+ x2: number;
+ y1: number;
+ y2: number;
+}
+
+interface Boundary {
+ width: number;
+ height: number;
+}
+
+interface FindBestLinkResult {
+ sourcePoint: { a: Position; b: Position };
+ targetPoint: Position;
+ distance: number;
+ angle: number;
+}
+
+function getDistance(x1: number, y1: number, x2: number, y2: number) {
+ return Math.hypot(x2 - x1, y2 - y1);
+}
+
+function getAngleFromSides(a: number, b: number, c: number) {
+ const radians = Math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c));
+ return radians * (180 / Math.PI);
+}
+
+function findBestLink(
+ sourcePoints: Array<{ a: Position; b: Position }>,
+ targetPoints: Position[],
+): FindBestLinkResult {
+ const result: FindBestLinkResult[] = [];
+
+ for (const sourcePoint of sourcePoints) {
+ const { a, b } = sourcePoint;
+ for (const targetPoint of targetPoints) {
+ const { x, y } = targetPoint;
+ const aLength = getDistance(a.x, a.y, x, y);
+ const bLength = getDistance(b.x, b.y, x, y);
+ const deltaLength = getDistance(a.x, a.y, b.x, b.y);
+ const distance = Math.min(aLength, bLength);
+ const angle = Number(
+ getAngleFromSides(deltaLength, aLength, bLength).toFixed(1),
+ );
+ result.push({ distance, angle, targetPoint, sourcePoint });
+ }
+ }
+
+ result.sort((a, b) => {
+ if (a.angle !== b.angle) return b.angle - a.angle;
+ return a.distance - b.distance;
+ });
+ return result[0];
+}
+
+export function useAssignmentLabelLinkPath(
+ currentPosition: Position,
+ targetBoundary: TargetBoundary,
+ sourceElementBoundary: Boundary,
+ options: { sideLength?: number; shift?: number } = {},
+) {
+ const { sideLength = 6, shift = 5 } = options;
+ const { x1, x2, y1, y2 } = targetBoundary;
+ const { x, y } = currentPosition;
+ const scaleX = useScale2DX();
+ const scaleY = useScale2DY();
+ const { width, height } = sourceElementBoundary;
+ const centerX = width / 2;
+ const centerY = height / 2;
+ const leftX = x - centerX - shift;
+ const rightX = x + centerX + shift;
+ const topY = y - height;
+ const bottomY = y + shift;
+ const targetWidth = scaleX(x2) - scaleX(x1);
+ const targetHeight = scaleY(y2) - scaleY(y1);
+ const targetXCenter = scaleX(x1) + targetWidth / 2;
+ const targetYCenter = scaleY(y1) + targetHeight / 2;
+
+ const sourcePoints: Array<{ a: Position; b: Position }> = [
+ {
+ a: { x, y: bottomY },
+ b: { x: x + sideLength, y: bottomY },
+ },
+ {
+ a: { x, y: topY },
+ b: { x: x + sideLength, y: topY },
+ },
+ {
+ a: { x: leftX, y: y - centerY - sideLength / 2 },
+ b: { x: leftX, y: y - centerY + sideLength / 2 },
+ },
+ {
+ a: { x: rightX, y: y - centerY - sideLength / 2 },
+ b: { x: rightX, y: y - centerY + sideLength / 2 },
+ },
+ ];
+
+ /**
+ * Coordination
+ * xMid= x2-x1/2;
+ * yMid= y2-y1/2;
+ * (x1,y1) ---------- (xMid,y1) ---------- (x2,y1)
+ * | |
+ * | |
+ * (x1,yMid) (x2,yMid)
+ * | |
+ * | |
+ * (x1,y2) ---------- (xMid,y2) ---------- (x2,y2)
+ *
+ */
+ const targetPoints: Position[] = [
+ //Left Top
+
+ { x: scaleX(x1), y: scaleY(y1) },
+ //Center Top
+ { x: targetXCenter, y: scaleY(y1) },
+ //Right Top
+ { x: scaleX(x2), y: scaleY(y1) },
+ //Right Center
+ { x: scaleX(x2), y: targetYCenter },
+ //Right Bottom
+ { x: scaleX(x2), y: scaleY(y2) },
+ //Center Bottom
+ { x: targetXCenter, y: scaleY(y2) },
+ //Left Bottom
+ { x: scaleX(x1), y: scaleY(y2) },
+ //Left Center
+ { x: scaleX(x1), y: targetYCenter },
+ ];
+ const link = findBestLink(sourcePoints, targetPoints);
+
+ return `${link.sourcePoint.a.x},${link.sourcePoint.a.y} ${link.sourcePoint.b.x},${link.sourcePoint.b.y} ${link.targetPoint.x},${link.targetPoint.y}`;
+}
diff --git a/src/component/2d/zones/SignalsGuideLines.tsx b/src/component/2d/zones/SignalsGuideLines.tsx
index ced70fd4a..92e94b5e3 100644
--- a/src/component/2d/zones/SignalsGuideLines.tsx
+++ b/src/component/2d/zones/SignalsGuideLines.tsx
@@ -196,7 +196,12 @@ function IndicationLine(props: IndicationLineProps) {
const { id: rangeId } = range;
const highlightColor = useHighlightColor();
const isSignalAssigned = isRangeSignalAssigned({ range, diaIDs, nbAtoms });
- const { margin, width, height } = useChartData();
+ const {
+ margin,
+ width,
+ height,
+ toolOptions: { selectedTool },
+ } = useChartData();
const { setData: addNewAssignmentLabel } = useShareData();
const dispatch = useDispatch();
@@ -297,10 +302,12 @@ function IndicationLine(props: IndicationLineProps) {
];
const isOpen = isAssignBtnTrigged.current ? isAssignmentActive : undefined;
+ const isLinking = selectedTool === 'signalLinking';
return (
,
- targetPoints: Position[],
-): FindBestLinkResult {
- const result: FindBestLinkResult[] = [];
-
- for (const sourcePoint of sourcePoints) {
- const { a, b } = sourcePoint;
- for (const targetPoint of targetPoints) {
- const { x, y } = targetPoint;
- const aLength = getDistance(a.x, a.y, x, y);
- const bLength = getDistance(b.x, b.y, x, y);
- const deltaLength = getDistance(a.x, a.y, b.x, b.y);
-
- const distance = Math.min(aLength, bLength);
- const angle = Number(
- getAngleFromSides(deltaLength, aLength, bLength).toFixed(1),
- );
-
- result.push({ distance, angle, targetPoint, sourcePoint });
- }
- }
-
- result.sort((a, b) => {
- if (a.angle !== b.angle) {
- return b.angle - a.angle;
- }
- return a.distance - b.distance;
- });
- return result[0];
-}
-
-function useLinkPath(
- currentPosition: Position,
- targetBoundary: TargetBoundary,
- sourceElementBoundary: Boundary,
- options: { sideLength?: number; shift?: number } = {},
-) {
- const { sideLength = 6, shift = 5 } = options;
-
- const { x1, x2, y1, y2 } = targetBoundary;
- const { x, y } = currentPosition;
- const scaleX = useScale2DX();
- const scaleY = useScale2DY();
-
- const { width, height } = sourceElementBoundary;
- const centerX = width / 2;
- const centerY = height / 2;
- const leftX = x - centerX - shift;
- const rightX = x + centerX + shift;
- const topY = y - height;
- const bottomY = y + shift;
-
- const targetWidth = scaleX(x2) - scaleX(x1);
- const targetHeight = scaleY(y2) - scaleY(y1);
- const targetXCenter = scaleX(x1) + targetWidth / 2;
- const targetYCenter = scaleY(y1) + targetHeight / 2;
-
- const sourcePoints: Array<{ a: Position; b: Position }> = [
- {
- a: { x, y: bottomY },
- b: { x: x + sideLength, y: bottomY },
- },
- {
- a: { x, y: topY },
- b: { x: x + sideLength, y: topY },
- },
- {
- a: { x: leftX, y: y - centerY - sideLength / 2 },
- b: { x: leftX, y: y - centerY + sideLength / 2 },
- },
- {
- a: { x: rightX, y: y - centerY - sideLength / 2 },
- b: { x: rightX, y: y - centerY + sideLength / 2 },
- },
- ];
-
- /**
- * Zone coordination
- * xMid= x2-x1/2;
- * yMid= y2-y1/2;
- * (x1,y1) ---------- (xMid,y1) ---------- (x2,y1)
- * | |
- * | |
- * (x1,yMid) (x2,yMid)
- * | |
- * | |
- * (x1,y2) ---------- (xMid,y2) ---------- (x2,y2)
- *
- */
-
- const targetPoints: Position[] = [
- {
- //Left Top
- x: scaleX(x1),
- y: scaleY(y1),
- },
- {
- //Center Top
- x: targetXCenter,
- y: scaleY(y1),
- },
- {
- //Right Top
- x: scaleX(x2),
- y: scaleY(y1),
- },
- {
- //Right Center
- x: scaleX(x2),
- y: targetYCenter,
- },
- {
- //Right Bottom
- x: scaleX(x2),
- y: scaleY(y2),
- },
- {
- //Center Bottom
- x: targetXCenter,
- y: scaleY(y2),
- },
-
- {
- //Left Bottom
- x: scaleX(x1),
- y: scaleY(y2),
- },
- {
- //Left Center
- x: scaleX(x1),
- y: targetYCenter,
- },
- ];
-
- const link = findBestLink(sourcePoints, targetPoints);
-
- return `${link.sourcePoint.a.x},${link.sourcePoint.a.y} ${link.sourcePoint.b.x},${link.sourcePoint.b.y} ${link.targetPoint.x},${link.targetPoint.y}`;
-}
-
const GroupContainer = styled.g<{ isMoveActive: boolean }>(
({ isMoveActive }) =>
!isMoveActive
@@ -376,7 +208,7 @@ function AssignmentLabel(props: AssignmentLabelProps) {
},
parentElement: viewerRef,
});
- const path = useLinkPath(
+ const path = useAssignmentLabelLinkPath(
currentPosition,
{ x1: x.to, x2: x.from, y1: y.from, y2: y.to },
labelBoundary,
diff --git a/src/component/context/DispatchContext.tsx b/src/component/context/DispatchContext.tsx
index 9ecb38fa6..3b1e2fc26 100644
--- a/src/component/context/DispatchContext.tsx
+++ b/src/component/context/DispatchContext.tsx
@@ -8,6 +8,7 @@ import type { DomainActions } from '../reducer/actions/DomainActions.js';
import type { FiltersActions } from '../reducer/actions/FiltersActions.js';
import type { InsetsActions } from '../reducer/actions/InsetActions.js';
import type { IntegralsActions } from '../reducer/actions/IntegralsActions.js';
+import type { LinkedSignalsActions } from '../reducer/actions/LinkedSignalsActions.js';
import type { LoadAction } from '../reducer/actions/LoadAction.js';
import type { MoleculeActions } from '../reducer/actions/MoleculeActions.js';
import type { PeaksActions } from '../reducer/actions/PeaksActions.js';
@@ -25,6 +26,7 @@ export type Action =
| SpectrumActions
| LoadAction
| IntegralsActions
+ | LinkedSignalsActions
| RangesActions
| DatabaseActions
| DimensionsActions
diff --git a/src/component/highlight/index.tsx b/src/component/highlight/index.tsx
index 87995d3b9..f5dd5a886 100644
--- a/src/component/highlight/index.tsx
+++ b/src/component/highlight/index.tsx
@@ -37,6 +37,7 @@ interface HighlightEventSourceMap {
DATABASE: { ranges: Range[]; jcampURL: string; baseURL: string };
ATOM: never;
ASSIGNMENT_TABLE: never;
+ LINKED_SIGNAL: never;
UNKNOWN: never;
}
diff --git a/src/component/modal/setting/tanstack_general_settings/tabs/tools_tab.tsx b/src/component/modal/setting/tanstack_general_settings/tabs/tools_tab.tsx
index a3f158b8a..5dd4dadea 100644
--- a/src/component/modal/setting/tanstack_general_settings/tabs/tools_tab.tsx
+++ b/src/component/modal/setting/tanstack_general_settings/tabs/tools_tab.tsx
@@ -128,6 +128,9 @@ const Spectra2DManipulationTools = withFieldGroup({
return (
+
+ {({ Checkbox }) => }
+
{({ Checkbox }) => }
diff --git a/src/component/modal/setting/tanstack_general_settings/validation/tools_tab_validation.ts b/src/component/modal/setting/tanstack_general_settings/validation/tools_tab_validation.ts
index 1b0a7bfe8..80d3a29b4 100644
--- a/src/component/modal/setting/tanstack_general_settings/validation/tools_tab_validation.ts
+++ b/src/component/modal/setting/tanstack_general_settings/validation/tools_tab_validation.ts
@@ -12,6 +12,7 @@ export const toolbarButtonsValidation = z
peakPicking: z.boolean().optional(),
integral: z.boolean().optional(),
zonePicking: z.boolean().optional(),
+ signalLinking: z.boolean().optional(),
slicing: z.boolean().optional(),
rangePicking: z.boolean().optional(),
zeroFilling: z.boolean().optional(),
diff --git a/src/component/panels/MoleculesPanel/hooks/useAtomAssignment.tsx b/src/component/panels/MoleculesPanel/hooks/useAtomAssignment.tsx
index 78d4b41ae..6fd404ba5 100644
--- a/src/component/panels/MoleculesPanel/hooks/useAtomAssignment.tsx
+++ b/src/component/panels/MoleculesPanel/hooks/useAtomAssignment.tsx
@@ -102,7 +102,10 @@ export default function useAtomAssignment() {
const currentDiaIDsToHighlight = useMemo(() => {
const { highlighted, sourceData } = highlightData.highlight;
- if (sourceData?.type === 'ASSIGNMENT_TABLE') {
+ if (
+ sourceData?.type === 'ASSIGNMENT_TABLE' ||
+ sourceData?.type === 'LINKED_SIGNAL'
+ ) {
return highlighted;
}
diff --git a/src/component/panels/MoleculesPanel/hooks/useSignalAssignmentUpdates.ts b/src/component/panels/MoleculesPanel/hooks/useSignalAssignmentUpdates.ts
index 48e283202..84cbf14de 100644
--- a/src/component/panels/MoleculesPanel/hooks/useSignalAssignmentUpdates.ts
+++ b/src/component/panels/MoleculesPanel/hooks/useSignalAssignmentUpdates.ts
@@ -1,18 +1,32 @@
+import type { Signal1D } from '@zakodium/nmr-types';
import type { Spectrum1D, Spectrum2D } from '@zakodium/nmrium-core';
import { isSpectrum1D } from '@zakodium/nmrium-core';
import type { DiaIDAndInfo } from 'openchemlib-utils';
import type { StateMoleculeExtended } from '../../../../data/molecules/Molecule.js';
+import { getCrossingAssignmentLabel } from '../../../2d/utilities/signalCrossings.js';
import { useChartData } from '../../../context/ChartContext.js';
import { useExtractAtomAssignmentLabel } from './useExtractAtomAssignmentLabel.js';
-export interface SignalAssignmentUpdate {
+interface BaseAssignmentUpdate {
spectrumId: string;
- signalId: string;
assignment: string;
}
+interface RangeOrZoneAssignmentUpdate extends BaseAssignmentUpdate {
+ signalId: string;
+ linkedSignalId?: never;
+}
+
+interface LinkedSignalAssignmentUpdate extends BaseAssignmentUpdate {
+ linkedSignalId: string;
+ signalId?: never;
+}
+
+export type SignalAssignmentUpdate =
+ RangeOrZoneAssignmentUpdate | LinkedSignalAssignmentUpdate;
+
function hasChangedDiaID(diaIDs: string[], changedDiaIDs: Set) {
return diaIDs.some((diaID) => changedDiaIDs.has(diaID));
}
@@ -42,8 +56,19 @@ export function useSignalAssignmentUpdates() {
...diaObject.attachedHydrogensIDCodes,
]);
const updatedAssignments: SignalAssignmentUpdate[] = [];
+ const signalsById = new Map();
+
+ for (const spectrum of spectra) {
+ if (!isSpectrum1D(spectrum)) continue;
+
+ for (const range of spectrum.ranges.values) {
+ for (const signal of range.signals) {
+ signalsById.set(signal.id, signal);
+ }
+ }
+ }
- // #2 Recalculate assignments only for affected range and zone signals.
+ // #2 Recalculate assignments only for affected range, zone and linked signals.
function getRangeSignalUpdates(spectrum: Spectrum1D) {
const signalUpdates: SignalAssignmentUpdate[] = [];
@@ -108,11 +133,56 @@ export function useSignalAssignmentUpdates() {
return signalUpdates;
}
+ function getLinkedSignalUpdates(spectrum: Spectrum2D) {
+ const signalUpdates: SignalAssignmentUpdate[] = [];
+
+ for (const link of spectrum.linkedSignals) {
+ const xDiaIDs = signalsById.get(link.xSignalId)?.diaIDs ?? [];
+ const yDiaIDs = signalsById.get(link.ySignalId)?.diaIDs ?? [];
+ const diaIDs = [...xDiaIDs, ...yDiaIDs];
+ if (!isAffectedSignal(link, diaIDs, changedDiaIDs)) {
+ continue;
+ }
+
+ const xAssignment = getAssignmentLabelByDiaIDsForMolecule(
+ xDiaIDs,
+ molecule.id,
+ molecule.molfile,
+ );
+
+ const yAssignment = getAssignmentLabelByDiaIDsForMolecule(
+ yDiaIDs,
+ molecule.id,
+ molecule.molfile,
+ );
+
+ const [xNucleus, yNucleus] = spectrum.info.nucleus;
+ const hasSameNucleus = xNucleus === yNucleus;
+
+ const assignment = getCrossingAssignmentLabel({
+ xAssignment,
+ yAssignment,
+ hasSameNucleus,
+ });
+
+ signalUpdates.push({
+ spectrumId: spectrum.id,
+ linkedSignalId: `${link.xSignalId}:${link.ySignalId}`,
+ assignment,
+ });
+ }
+
+ return signalUpdates;
+ }
+
for (const spectrum of spectra) {
if (isSpectrum1D(spectrum)) {
updatedAssignments.push(...getRangeSignalUpdates(spectrum));
} else {
- updatedAssignments.push(...getZoneSignalUpdates(spectrum));
+ updatedAssignments.push(
+ ...getZoneSignalUpdates(spectrum),
+ ...getLinkedSignalUpdates(spectrum),
+ );
}
}
diff --git a/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx b/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx
index eb4518b66..602645fc2 100644
--- a/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx
+++ b/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx
@@ -20,6 +20,10 @@ import {
getVisibleAssignmentRows,
} from './utilities/atomGroupsToAssignmentRows.js';
import { getAssignedAtomCounts } from './utilities/getAssignedAtomCounts.js';
+import {
+ formatLinkedAssignments,
+ getLinkedAssignmentsByExperiment,
+} from './utilities/getLinkedAssignmentsByExperiment.js';
import { getSignalsByNucleus } from './utilities/getSignalsByNucleus.js';
import type { SignalsByOclID } from './utilities/types.js';
@@ -76,6 +80,10 @@ export function MoleculeAssignmentTable(props: MoleculeAssignmentTableProps) {
// Build once per data change.
// headers and cells share the same nucleus lookup.
const signalsByNucleus = useMemo(() => getSignalsByNucleus(data), [data]);
+ const linkedAssignmentsByExperiment = useMemo(
+ () => getLinkedAssignmentsByExperiment(data),
+ [data],
+ );
// Keep the complete hierarchy for assignments.
// Expansion Only hides rows.
const allRows = useMemo(
@@ -154,12 +162,29 @@ export function MoleculeAssignmentTable(props: MoleculeAssignmentTableProps) {
},
]),
),
+ ...Array.from(linkedAssignmentsByExperiment).flatMap(
+ ([experiment, assignmentsByOclID]) =>
+ columnHelper.columns([
+ {
+ header: experiment,
+ id: experiment,
+ enableSorting: false,
+ cell: ({ row }) =>
+ formatLinkedAssignments(
+ row.original,
+ assignmentsByOclID,
+ hydrogenIDsByParent,
+ ),
+ },
+ ]),
+ ),
]);
}, [
groups,
onToggleRow,
showAtomNumbers,
signalsByNucleus,
+ linkedAssignmentsByExperiment,
hydrogenIDsByParent,
]);
diff --git a/src/component/panels/assignment-summary/utilities/exportAssignments.ts b/src/component/panels/assignment-summary/utilities/exportAssignments.ts
index a0c70bf2c..b17af2cc1 100644
--- a/src/component/panels/assignment-summary/utilities/exportAssignments.ts
+++ b/src/component/panels/assignment-summary/utilities/exportAssignments.ts
@@ -12,6 +12,10 @@ import {
import { formatAssignmentACS } from './formatAssignmentACS.js';
import { formatAssignmentShifts } from './formatAssignmentShifts.js';
import { getAssignmentSignals } from './getAssignmentSignals.js';
+import {
+ formatLinkedAssignments,
+ getLinkedAssignmentsByExperiment,
+} from './getLinkedAssignmentsByExperiment.js';
import { getSignalsByNucleus } from './getSignalsByNucleus.js';
import type { GetAssignmentSignalsOptions } from './types.js';
@@ -49,6 +53,9 @@ export function exportAssignments(options: ExportAssignmentsOptions): string {
rowMode === 'current' ? expandedGroups : new Set(),
);
const hydrogenIDsByParent = getHydrogenIDsByParent(allRows);
+ const linkedAssignmentsByExperiment = Array.from(
+ getLinkedAssignmentsByExperiment(spectra),
+ );
const nuclei = Array.from(
getSignalsByNucleus(spectra),
([nucleus, signals]) => ({
@@ -63,6 +70,7 @@ export function exportAssignments(options: ExportAssignmentsOptions): string {
'Atom numbers',
'Atom labels',
...nuclei.map(({ nucleus }) => nucleus),
+ ...linkedAssignmentsByExperiment.map(([experiment]) => experiment),
];
const data = rows.map((row) => [
row.atomLabel,
@@ -84,6 +92,9 @@ export function exportAssignments(options: ExportAssignmentsOptions): string {
acs,
}),
),
+ ...linkedAssignmentsByExperiment.map(([, assignmentsByOclID]) =>
+ formatLinkedAssignments(row, assignmentsByOclID, hydrogenIDsByParent),
+ ),
]);
return papa.unparse({ fields, data }, { delimiter, escapeFormulae: true });
diff --git a/src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts b/src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts
new file mode 100644
index 000000000..c8dfe2df7
--- /dev/null
+++ b/src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts
@@ -0,0 +1,105 @@
+import type { Spectrum } from '@zakodium/nmrium-core';
+import { isSpectrum1D, isSpectrum2DFt } from '@zakodium/nmrium-core';
+
+import { sortAssignmentLabels } from '../../MoleculesPanel/utilities/sortAssignmentLabels.js';
+
+import type { AssignmentListRow } from './atomGroupsToAssignmentRows.js';
+
+export type LinkedAssignmentsByOclID = Map>;
+
+function getOclIDsBySignalId(spectra: Spectrum[]): Map {
+ const oclIDsBySignalId = new Map();
+
+ for (const spectrum of spectra) {
+ if (!isSpectrum1D(spectrum)) continue;
+
+ for (const range of spectrum.ranges.values) {
+ for (const signal of range.signals) {
+ oclIDsBySignalId.set(signal.id, signal.diaIDs ?? []);
+ }
+ }
+ }
+
+ return oclIDsBySignalId;
+}
+
+/**
+ * Group saved link text by experiment and atom group.
+ * The 1D signals only identify which atom groups receive that text.
+ */
+export function getLinkedAssignmentsByExperiment(
+ spectra: Spectrum[],
+): Map {
+ // 1. Map 1D signal IDs to the atom group IDs used by table rows.
+ // Map {
+ // 'signal-h1' => ['atom-H1'],
+ // 'signal-c2' => ['atom-C2'],
+ // }
+ const oclIDsBySignalId = getOclIDsBySignalId(spectra);
+ const assignmentsByExperiment = new Map();
+
+ for (const spectrum of spectra) {
+ if (!isSpectrum2DFt(spectrum)) continue;
+
+ // 2. Create or reuse the atom lookup for this experiment's table column.
+ const experiment = spectrum.info.experiment?.toUpperCase() || '2D';
+ let assignmentsByOclID = assignmentsByExperiment.get(experiment);
+ if (!assignmentsByOclID) {
+ assignmentsByOclID = new Map();
+ assignmentsByExperiment.set(experiment, assignmentsByOclID);
+ }
+
+ // 3. Associate the saved assignment with atom groups on each axis.
+ // Example link: signal-h1 -> signal-c2, assignment: 'H1,C2'.
+ // Output: Map {
+ // 'HSQC' => Map {
+ // 'atom-H1' => Set { 'H1,C2' },
+ // 'atom-C2' => Set { 'H1,C2' },
+ // },
+ // }
+ for (const link of spectrum.linkedSignals ?? []) {
+ const { xSignalId, ySignalId, assignment } = link;
+
+ if (!assignment) continue;
+
+ const xOclIDs = oclIDsBySignalId.get(xSignalId) ?? [];
+ const yOclIDs = oclIDsBySignalId.get(ySignalId) ?? [];
+ addAssignmentToAtoms(assignmentsByOclID, xOclIDs, assignment);
+ addAssignmentToAtoms(assignmentsByOclID, yOclIDs, assignment);
+ }
+ }
+
+ return assignmentsByExperiment;
+}
+
+function addAssignmentToAtoms(
+ assignmentsByOclID: LinkedAssignmentsByOclID,
+ oclIDs: string[],
+ assignment: string,
+) {
+ for (const oclID of oclIDs) {
+ const assignments = assignmentsByOclID.get(oclID);
+ if (assignments) {
+ assignments.add(assignment);
+ } else {
+ assignmentsByOclID.set(oclID, new Set([assignment]));
+ }
+ }
+}
+
+export function formatLinkedAssignments(
+ row: AssignmentListRow,
+ assignmentsByOclID: LinkedAssignmentsByOclID,
+ hydrogenIDsByParent: ReadonlyMap,
+): string {
+ const oclIDs = [row.id, ...(hydrogenIDsByParent.get(row.id) ?? [])];
+ const assignments = new Set();
+
+ for (const oclID of oclIDs) {
+ for (const assignment of assignmentsByOclID.get(oclID) ?? []) {
+ assignments.add(assignment);
+ }
+ }
+
+ return sortAssignmentLabels(Array.from(assignments)).join(', ');
+}
diff --git a/src/component/reducer/Reducer.ts b/src/component/reducer/Reducer.ts
index 0d8854c4d..3fa07c31d 100644
--- a/src/component/reducer/Reducer.ts
+++ b/src/component/reducer/Reducer.ts
@@ -26,6 +26,7 @@ import * as DomainActions from './actions/DomainActions.js';
import * as FiltersActions from './actions/FiltersActions.js';
import * as InsetActions from './actions/InsetActions.js';
import * as IntegralsActions from './actions/IntegralsActions.js';
+import * as LinkedSignalsActions from './actions/LinkedSignalsActions.js';
import { LoadActions } from './actions/LoadAction.js';
import * as MoleculeActions from './actions/MoleculeActions.js';
import * as PeaksActions from './actions/PeaksActions.js';
@@ -120,6 +121,7 @@ export function getDefaultViewState(): ViewState {
units1D: {},
units2D: {},
insets: {},
+ slicingScaleRatio: 1,
};
}
export const getInitialState = (): State => ({
@@ -711,6 +713,11 @@ function innerSpectrumReducer(draft: Draft, action: Action) {
return MoleculeActions.handleAddMolecules(draft, action);
case 'SET_MOLECULE':
return MoleculeActions.handleSetMolecule(draft, action);
+ case 'CHANGE_ASSIGNMENT_LABEL_BY_DIAIDS':
+ return MoleculeActions.handleChangeAssignmentLabelsByDiaIds(
+ draft,
+ action,
+ );
case 'CHANGE_MOLECULE_LABEL':
return MoleculeActions.handleChangeMoleculeLabel(draft, action);
case 'DELETE_MOLECULE':
@@ -782,11 +789,6 @@ function innerSpectrumReducer(draft: Draft, action: Action) {
draft,
action,
);
- case 'CHANGE_ASSIGNMENT_LABEL_BY_DIAIDS':
- return RangesActions.handleChangeRangesAssignmentLabelsByDiaIds(
- draft,
- action,
- );
case 'CHANGE_SIGNAL_DELTA':
return RangesActions.handleChangeSignalDelta(draft, action);
@@ -801,6 +803,20 @@ function innerSpectrumReducer(draft: Draft, action: Action) {
return ZonesActions.handleChangeZonesFactor(draft, action);
case 'ADD_2D_ZONE':
return ZonesActions.handleAdd2dZone(draft, action);
+ case 'ADD_2D_SIGNAL_LINK':
+ return LinkedSignalsActions.handleAdd2DSignalLink(draft, action);
+ case 'DELETE_2D_SIGNAL_LINK':
+ return LinkedSignalsActions.handleDelete2DSignalLink(draft, action);
+ case 'CHANGE_LINKED_SIGNAL_ASSIGNMENT_LABEL':
+ return LinkedSignalsActions.handleChangeLinkedSignalAssignment(
+ draft,
+ action,
+ );
+ case 'SET_LINKED_SIGNAL_ASSIGNMENT_LABEL_COORDINATION':
+ return LinkedSignalsActions.handleSetLinkedSignalLabelCoordination(
+ draft,
+ action,
+ );
case 'DELETE_2D_ZONE':
return ZonesActions.handleDeleteZone(draft, action);
case 'DELETE_2D_SIGNAL':
diff --git a/src/component/reducer/actions/LinkedSignalsActions.ts b/src/component/reducer/actions/LinkedSignalsActions.ts
new file mode 100644
index 000000000..4b83f5daf
--- /dev/null
+++ b/src/component/reducer/actions/LinkedSignalsActions.ts
@@ -0,0 +1,128 @@
+import type { Spectrum2D } from '@zakodium/nmr-types';
+import { isSpectrum2DFt } from '@zakodium/nmrium-core';
+import type { Draft } from 'immer';
+
+import type { State } from '../Reducer.js';
+import { getSpectrum } from '../helper/getSpectrum.js';
+import type { ActionType } from '../types/ActionType.js';
+
+type LinkedSignal = Spectrum2D['linkedSignals'][number];
+
+type Add2DSignalLinkAction = ActionType<
+ 'ADD_2D_SIGNAL_LINK',
+ Pick
+>;
+type Delete2DSignalLinkAction = ActionType<
+ 'DELETE_2D_SIGNAL_LINK',
+ { id: string }
+>;
+type ChangeLinkedSignalAssignmentAction = ActionType<
+ 'CHANGE_LINKED_SIGNAL_ASSIGNMENT_LABEL',
+ { id: string; value: string; isAutoAssignment?: boolean }
+>;
+type SetLinkedSignalLabelCoordinationAction = ActionType<
+ 'SET_LINKED_SIGNAL_ASSIGNMENT_LABEL_COORDINATION',
+ { spectrumId: string; id: string; coordination: { x: number; y: number } }
+>;
+
+export type LinkedSignalsActions =
+ | Add2DSignalLinkAction
+ | Delete2DSignalLinkAction
+ | ChangeLinkedSignalAssignmentAction
+ | SetLinkedSignalLabelCoordinationAction;
+
+function getLinkedSignal(draft: Draft, id: string) {
+ const spectrum = getSpectrum(draft);
+
+ if (!isSpectrum2DFt(spectrum)) {
+ return;
+ }
+
+ const link = spectrum.linkedSignals?.find(
+ (link) => `${link.xSignalId}:${link.ySignalId}` === id,
+ );
+
+ if (!link) {
+ return;
+ }
+
+ return { spectrum, link };
+}
+
+export function handleAdd2DSignalLink(
+ draft: Draft,
+ action: Add2DSignalLinkAction,
+) {
+ const spectrum = getSpectrum(draft);
+ const { xSignalId, ySignalId, assignment } = action.payload;
+
+ if (!xSignalId || !ySignalId || !isSpectrum2DFt(spectrum)) {
+ return;
+ }
+
+ const isLined = spectrum.linkedSignals.some(
+ (link) => link.xSignalId === xSignalId && link.ySignalId === ySignalId,
+ );
+
+ if (isLined) {
+ return;
+ }
+
+ spectrum.linkedSignals.push({
+ xSignalId,
+ ySignalId,
+ assignment,
+ isAutoAssignment: true,
+ });
+}
+
+export function handleChangeLinkedSignalAssignment(
+ draft: Draft,
+ action: ChangeLinkedSignalAssignmentAction,
+) {
+ const { isAutoAssignment = false, value, id } = action.payload;
+ const linkedSignal = getLinkedSignal(draft, id);
+ if (!linkedSignal) {
+ return;
+ }
+ const { link } = linkedSignal;
+ link.assignment = value;
+ link.isAutoAssignment = isAutoAssignment;
+}
+
+export function handleDelete2DSignalLink(
+ draft: Draft,
+ action: Delete2DSignalLinkAction,
+) {
+ const { id } = action.payload;
+ const linkedSignal = getLinkedSignal(draft, id);
+
+ if (!linkedSignal) {
+ return;
+ }
+
+ const { spectrum } = linkedSignal;
+ spectrum.linkedSignals = spectrum.linkedSignals.filter(
+ (signal) => `${signal.xSignalId}:${signal.ySignalId}` !== id,
+ );
+
+ delete draft.view.assignmentsLabelsCoordinates?.[spectrum.id]?.[id];
+}
+
+export function handleSetLinkedSignalLabelCoordination(
+ draft: Draft,
+ action: SetLinkedSignalLabelCoordinationAction,
+) {
+ const { spectrumId, id, coordination } = action.payload;
+
+ if (!draft.view.assignmentsLabelsCoordinates) {
+ draft.view.assignmentsLabelsCoordinates = {};
+ }
+
+ const coordinates = draft.view.assignmentsLabelsCoordinates;
+ if (!coordinates[spectrumId]) {
+ coordinates[spectrumId] = {};
+ }
+
+ coordinates[spectrumId][id] = coordination;
+}
diff --git a/src/component/reducer/actions/MoleculeActions.ts b/src/component/reducer/actions/MoleculeActions.ts
index 7a217c304..d507a6642 100644
--- a/src/component/reducer/actions/MoleculeActions.ts
+++ b/src/component/reducer/actions/MoleculeActions.ts
@@ -1,5 +1,14 @@
-import type { MoleculeView, StateMolecule } from '@zakodium/nmrium-core';
-import { isSpectrum1D, isSpectrum2D } from '@zakodium/nmrium-core';
+import type { Range, Zone } from '@zakodium/nmr-types';
+import type {
+ MoleculeView,
+ Spectrum2D,
+ StateMolecule,
+} from '@zakodium/nmrium-core';
+import {
+ isSpectrum1D,
+ isSpectrum2D,
+ isSpectrum2DFt,
+} from '@zakodium/nmrium-core';
import type { Logger } from 'cheminfo-types';
import type { FifoLogger } from 'fifo-logger';
import type { Draft } from 'immer';
@@ -20,6 +29,7 @@ import { DRAGGABLE_STRUCTURE_INITIAL_BOUNDING_REACT } from '../../../data/molecu
import * as MoleculeManager from '../../../data/molecules/MoleculeManager.js';
import { generateColor } from '../../../data/utilities/generateColor.js';
import { convertPixelToPercent } from '../../hooks/useSVGUnitConverter.js';
+import type { SignalAssignmentUpdate } from '../../panels/MoleculesPanel/hooks/useSignalAssignmentUpdates.js';
import { extractFromAtom } from '../../panels/MoleculesPanel/utilities/extractFromAtom.js';
import nucleusToString from '../../utility/nucleusToString.js';
import type { State } from '../Reducer.js';
@@ -95,6 +105,12 @@ type ChangeMoleculeLabelAction = ActionType<
'CHANGE_MOLECULE_LABEL',
{ id: string; label: string }
>;
+type ChangeAssignmentLabelsByDiaIdsAction = ActionType<
+ 'CHANGE_ASSIGNMENT_LABEL_BY_DIAIDS',
+ {
+ assignments: SignalAssignmentUpdate[];
+ }
+>;
export type MoleculeActions =
| AddMoleculeAction
@@ -106,6 +122,7 @@ export type MoleculeActions =
| ChangeFloatMoleculePositionAction
| ChangeMoleculeLabelAction
| ChangeMoleculeAnnotationAction
+ | ChangeAssignmentLabelsByDiaIdsAction
| ToggleMoleculeLabelAction;
export function addMolecule(draft: Draft, props: AddMoleculeProps) {
@@ -186,6 +203,103 @@ export function handleSetMolecule(
setMolecule(draft, action.payload);
}
+interface UpdateRangeSignalsAssignmentParams {
+ ranges: Range[];
+ signalId?: string;
+ assignment: string;
+}
+
+function updateRangeSignalsAssignment(
+ options: UpdateRangeSignalsAssignmentParams,
+) {
+ const { ranges, signalId, assignment } = options;
+ if (signalId === undefined) return;
+
+ for (const range of ranges) {
+ const signal = range.signals.find((item) => item.id === signalId);
+ if (signal?.isAutoAssignment) {
+ signal.assignment = assignment;
+ break;
+ }
+ }
+}
+
+interface UpdateZoneAssignmentsParams {
+ zones: Zone[];
+ signalId?: string;
+ assignment: string;
+}
+function updateZoneAssignments(options: UpdateZoneAssignmentsParams) {
+ const { zones, signalId, assignment } = options;
+ if (signalId === undefined) return;
+
+ for (const zone of zones) {
+ const signal = zone.signals.find((item) => item.id === signalId);
+ if (signal?.isAutoAssignment) {
+ signal.assignment = assignment;
+ break;
+ }
+ }
+}
+
+interface UpdateLinkedSignalAssignmentParams extends Pick<
+ Spectrum2D,
+ 'linkedSignals'
+> {
+ linkedSignalId?: string;
+ assignment: string;
+}
+
+function updateLinkedSignalAssignment(
+ options: UpdateLinkedSignalAssignmentParams,
+) {
+ const { linkedSignals, linkedSignalId, assignment } = options;
+ if (linkedSignalId === undefined) return;
+
+ const link = linkedSignals.find(
+ (item) => `${item.xSignalId}:${item.ySignalId}` === linkedSignalId,
+ );
+ if (!link?.isAutoAssignment) return;
+
+ link.assignment = assignment;
+}
+
+export function handleChangeAssignmentLabelsByDiaIds(
+ draft: Draft,
+ action: ChangeAssignmentLabelsByDiaIdsAction,
+) {
+ for (const spectrum of draft.data) {
+ const assignments = action.payload.assignments.filter(
+ (update) => update.spectrumId === spectrum.id,
+ );
+
+ if (isSpectrum1D(spectrum)) {
+ for (const { signalId, assignment } of assignments) {
+ if (signalId === undefined) continue;
+
+ updateRangeSignalsAssignment({
+ ranges: spectrum.ranges.values,
+ signalId,
+ assignment,
+ });
+ }
+ } else if (isSpectrum2DFt(spectrum)) {
+ for (const { signalId, linkedSignalId, assignment } of assignments) {
+ updateZoneAssignments({
+ zones: spectrum.zones.values,
+ signalId,
+ assignment,
+ });
+ updateLinkedSignalAssignment({
+ linkedSignals: spectrum.linkedSignals,
+ linkedSignalId,
+ assignment,
+ });
+ }
+ }
+ }
+}
+
function clearDiaIDs(
obj: Partial<{ diaIDs?: string[]; nbAtoms?: number }>,
options: {
diff --git a/src/component/reducer/actions/RangesActions.ts b/src/component/reducer/actions/RangesActions.ts
index 6025156cd..efaac6388 100644
--- a/src/component/reducer/actions/RangesActions.ts
+++ b/src/component/reducer/actions/RangesActions.ts
@@ -1,4 +1,4 @@
-import type { Range, Signal1D, SignalKind, Zone } from '@zakodium/nmr-types';
+import type { Range, Signal1D, SignalKind } from '@zakodium/nmr-types';
import type {
BoundingBox,
RangesViewState,
@@ -100,16 +100,6 @@ type Assign1DSignalAction = ActionType<
spectrumId?: string;
} & Required>
>;
-type ChangeRangesAssignmentsLabelsByDiaIdsAction = ActionType<
- 'CHANGE_ASSIGNMENT_LABEL_BY_DIAIDS',
- {
- assignments: Array<{
- spectrumId: string;
- signalId: string;
- assignment: string;
- }>;
- }
->;
type ResizeRangeAction = ActionType<
'RESIZE_RANGE',
{
@@ -207,7 +197,6 @@ export type RangesActions =
| DeleteRangePeakAction
| Change1DSignalAssignmentLabelAction
| ChangeRangesViewFloatingBoxBoundingAction
- | ChangeRangesAssignmentsLabelsByDiaIdsAction
| ChangeSignalDeltaAction
| ActionType<
| 'AUTO_RANGES_SPECTRA_PICKING'
@@ -510,55 +499,6 @@ function handleAssign1DSignal(
signal.nbAtoms = nbAtoms + (signal.nbAtoms || 0);
}
-function updateRangeSignalsAssignment(
- ranges: Range[],
- signalId: string,
- assignment: string,
-) {
- for (const range of ranges) {
- const signal = range.signals.find((item) => item.id === signalId);
- if (signal?.isAutoAssignment) {
- signal.assignment = assignment;
- break;
- }
- }
-}
-
-function updateZoneAssignments(
- zones: Zone[],
- signalId: string,
- assignment: string,
-) {
- for (const zone of zones) {
- const signal = zone.signals.find((item) => item.id === signalId);
- if (signal?.isAutoAssignment) {
- signal.assignment = assignment;
- break;
- }
- }
-}
-
-//action
-function handleChangeRangesAssignmentLabelsByDiaIds(
- draft: Draft,
- action: ChangeRangesAssignmentsLabelsByDiaIdsAction,
-) {
- for (const { spectrumId, signalId, assignment } of action.payload
- .assignments) {
- const spectrum = draft.data.find((item) => item.id === spectrumId);
- if (!spectrum) continue;
-
- if (isSpectrum1D(spectrum)) {
- updateRangeSignalsAssignment(
- spectrum.ranges.values,
- signalId,
- assignment,
- );
- } else {
- updateZoneAssignments(spectrum.zones.values, signalId, assignment);
- }
- }
-}
//action
function handleResizeRange(draft: Draft, action: ResizeRangeAction) {
const { range, spectrumKey } = action.payload;
@@ -833,7 +773,6 @@ export {
handleChangeRangeSignalKind,
handleChangeRangeSignalValue,
handleChangeRangeSum,
- handleChangeRangesAssignmentLabelsByDiaIds,
handleChangeRangesSumFlag,
handleChangeRangesViewFloatingBoxBounding,
handleChangeSignalDelta,
diff --git a/src/component/toolbar/ToolTypes.ts b/src/component/toolbar/ToolTypes.ts
index c509b0d2e..1aab0f43e 100644
--- a/src/component/toolbar/ToolTypes.ts
+++ b/src/component/toolbar/ToolTypes.ts
@@ -26,6 +26,7 @@ import {
FaICursor,
} from 'react-icons/fa';
import { GrShift } from 'react-icons/gr';
+import { LuLink } from 'react-icons/lu';
import { PiKnifeBold, PiSelectionPlusDuotone } from 'react-icons/pi';
import { TbZoom } from 'react-icons/tb';
@@ -159,6 +160,20 @@ export const options: RecordOptions = {
],
isToggle: true,
},
+ signalLinking: {
+ id: 'signalLinking',
+ label: 'Link signals',
+ icon: LuLink,
+ hasOptionPanel: false,
+ isFilter: false,
+ mode: '2D',
+ spectraFilter: [
+ {
+ info: [{ key: 'isFt', value: true }],
+ },
+ ],
+ isToggle: true,
+ },
slicing: {
id: 'slicing',
label: 'Slicing tool',
diff --git a/src/component/toolbar/nmr_toolbar.tsx b/src/component/toolbar/nmr_toolbar.tsx
index 317b5d44f..d673752de 100644
--- a/src/component/toolbar/nmr_toolbar.tsx
+++ b/src/component/toolbar/nmr_toolbar.tsx
@@ -254,6 +254,13 @@ export default function NMRToolbar() {
link: 'https://docs.nmrium.org/30_2d-spectra/zones',
},
},
+ {
+ id: 'signalLinking',
+ tooltip: {
+ title: options.signalLinking.label,
+ description: `${!invert ? 'SHIFT + click' : 'Click'} a highlighted crossing of the two 1D traces to add a link to the active 2D spectrum.`,
+ },
+ },
{
id: 'slicing',
tooltip: {
diff --git a/src/component/workspaces/assignment.ts b/src/component/workspaces/assignment.ts
index 11f177f71..daec4cf7b 100644
--- a/src/component/workspaces/assignment.ts
+++ b/src/component/workspaces/assignment.ts
@@ -22,6 +22,7 @@ export const assignment: InnerWorkspace = {
spectraCenterAlignments: true,
realImaginary: true,
zonePicking: true,
+ signalLinking: true,
rangePicking: true,
slicing: true,
apodization: true,
diff --git a/src/component/workspaces/basic.ts b/src/component/workspaces/basic.ts
index 225eb01cf..80211b974 100644
--- a/src/component/workspaces/basic.ts
+++ b/src/component/workspaces/basic.ts
@@ -26,6 +26,7 @@ export const basic: InnerWorkspace = {
peakPicking: true,
integral: true,
zonePicking: true,
+ signalLinking: true,
rangePicking: true,
slicing: true,
apodization: true,
diff --git a/src/component/workspaces/embedded.ts b/src/component/workspaces/embedded.ts
index 539efa2aa..6e499fe3d 100644
--- a/src/component/workspaces/embedded.ts
+++ b/src/component/workspaces/embedded.ts
@@ -41,6 +41,7 @@ export const embedded: InnerWorkspace = {
apodization: true,
zeroFilling: true,
zonePicking: true,
+ signalLinking: true,
zoomOut: true,
zoom: true,
autoRangeAndZonePicking: true,
diff --git a/src/component/workspaces/prediction.ts b/src/component/workspaces/prediction.ts
index c0497707e..05d65d12f 100644
--- a/src/component/workspaces/prediction.ts
+++ b/src/component/workspaces/prediction.ts
@@ -49,6 +49,7 @@ export const prediction: InnerWorkspace = {
apodization: true,
zeroFilling: true,
zonePicking: true,
+ signalLinking: true,
zoomOut: true,
zoom: true,
autoRangeAndZonePicking: true,
diff --git a/src/component/workspaces/workspaceDefaultProperties.ts b/src/component/workspaces/workspaceDefaultProperties.ts
index 1d3a91111..018992e6f 100644
--- a/src/component/workspaces/workspaceDefaultProperties.ts
+++ b/src/component/workspaces/workspaceDefaultProperties.ts
@@ -60,6 +60,7 @@ export const workspaceDefaultProperties: RequiredWorkspacePreferences = {
apodization: false,
zeroFilling: false,
zonePicking: false,
+ signalLinking: false,
zoomOut: false,
zoom: false,
peakPicking: false,
diff --git a/src/data/data2d/Spectrum2D/initiateDatum2D.ts b/src/data/data2d/Spectrum2D/initiateDatum2D.ts
index 7a29607a5..ad45427b6 100644
--- a/src/data/data2d/Spectrum2D/initiateDatum2D.ts
+++ b/src/data/data2d/Spectrum2D/initiateDatum2D.ts
@@ -50,6 +50,7 @@ export function initiateDatum2D(
id: spectrum.id || crypto.randomUUID(),
display: initiateDisplay(spectrum, { usedColors, colors }),
info: initiateInfo(spectrum),
+ linkedSignals: spectrum.linkedSignals ?? [],
};
// Now, processings can happen before loading in component