From fa911f8a4996a8e3684c9afda61a6bc5a799d5a4 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Fri, 13 Nov 2026 12:20:02 +0100 Subject: [PATCH 01/13] feat: highlight nearest 2D signal crossing with circle and crosshairs --- src/component/2d/SVGContent2D.tsx | 2 + src/component/2d/SignalDeltaLine.tsx | 10 +- src/component/2d/useNearestSignalCrossing.ts | 65 +++++++++++ src/component/2d/utilities/signalCrossings.ts | 102 ++++++++++++++++++ .../2d/zones/SignalCrossingIndicator.tsx | 43 ++++++++ 5 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 src/component/2d/useNearestSignalCrossing.ts create mode 100644 src/component/2d/utilities/signalCrossings.ts create mode 100644 src/component/2d/zones/SignalCrossingIndicator.tsx diff --git a/src/component/2d/SVGContent2D.tsx b/src/component/2d/SVGContent2D.tsx index d338165de..68f6f0e43 100644 --- a/src/component/2d/SVGContent2D.tsx +++ b/src/component/2d/SVGContent2D.tsx @@ -7,6 +7,7 @@ import IndirectAxis2D from './IndirectAxis2D.tsx'; import { FidContainer } from './fid/FidContainer.js'; import { FTContainer } from './ft/FTContainer.js'; import type { Spectrum1DTraces } from './useTracesSpectra.js'; +import { SignalCrossingIndicator } from './zones/SignalCrossingIndicator.js'; import { SignalsGuideLines } from './zones/SignalsGuideLines.js'; import Zones from './zones/Zones.js'; import ZonesAssignmentsLabels from './zones/ZonesAssignmentsLabels.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 ( { + 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); + return buildCandidates({ + xSignals: signalsX, + ySignals: signalsY, + linkedSignals, + domains: { xDomain, yDomain }, + }); + }, [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/signalCrossings.ts b/src/component/2d/utilities/signalCrossings.ts new file mode 100644 index 000000000..e2acadb46 --- /dev/null +++ b/src/component/2d/utilities/signalCrossings.ts @@ -0,0 +1,102 @@ +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; +} + +interface Position { + x: number; + y: number; +} + +function inDomain(value: number, domain: number[]) { + const [min, max] = domain; + return value >= Math.min(min, max) && value <= Math.max(min, max); +} + +export function buildCandidates({ + xSignals, + ySignals, + linkedSignals, + domains, +}: 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: [x.assignment, y.assignment].filter(Boolean).join(','), + }); + } + } + 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/zones/SignalCrossingIndicator.tsx b/src/component/2d/zones/SignalCrossingIndicator.tsx new file mode 100644 index 000000000..0ad06056a --- /dev/null +++ b/src/component/2d/zones/SignalCrossingIndicator.tsx @@ -0,0 +1,43 @@ +import type { Spectrum2D } from '@zakodium/nmr-types'; +import { isSpectrum2DFt } from '@zakodium/nmrium-core'; + +import useSpectrum from '../../hooks/useSpectrum.js'; +import SignalDeltaLine from '../SignalDeltaLine.js'; +import { useNearestSignalCrossing } from '../useNearestSignalCrossing.js'; +import { useScale2DX, useScale2DY } from '../utilities/scale.js'; + +export function SignalCrossingIndicator() { + const spectrum = useSpectrum(); + + if (!isSpectrum2DFt(spectrum) || !spectrum.display.isVisible) return null; + + return ( + + ); +} + +function SignalCrossingIndicatorInner({ + linkedSignals, +}: Pick) { + const { nearest } = useNearestSignalCrossing({ linkedSignals }); + const scaleX = useScale2DX(); + const scaleY = useScale2DY(); + + if (!nearest) return null; + + return ( + + + + + + ); +} From f24e58e3d5a13a06b0734c59e0b3f03372d365bd Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Mon, 16 Nov 2026 11:22:47 +0100 Subject: [PATCH 02/13] feat(UI): add signal linking tool --- .../tanstack_general_settings/tabs/tools_tab.tsx | 3 +++ .../validation/tools_tab_validation.ts | 1 + src/component/toolbar/ToolTypes.ts | 15 +++++++++++++++ src/component/toolbar/nmr_toolbar.tsx | 8 ++++++++ src/component/workspaces/assignment.ts | 1 + src/component/workspaces/basic.ts | 1 + src/component/workspaces/embedded.ts | 1 + src/component/workspaces/prediction.ts | 1 + .../workspaces/workspaceDefaultProperties.ts | 1 + 9 files changed, 32 insertions(+) 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/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..b0b924c8d 100644 --- a/src/component/toolbar/nmr_toolbar.tsx +++ b/src/component/toolbar/nmr_toolbar.tsx @@ -254,6 +254,14 @@ export default function NMRToolbar() { link: 'https://docs.nmrium.org/30_2d-spectra/zones', }, }, + { + id: 'signalLinking', + tooltip: { + title: options.signalLinking.label, + description: + '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, From 1916d2a12934a5fd913be78d4b06247888c30bf0 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Mon, 16 Nov 2026 11:48:04 +0100 Subject: [PATCH 03/13] refactor: extract assignment label link path utility --- .../utilities/useAssignmentLabelLinkPath.ts | 138 ++++++++++++++ .../2d/zones/ZonesAssignmentsLabels.tsx | 172 +----------------- 2 files changed, 140 insertions(+), 170 deletions(-) create mode 100644 src/component/2d/utilities/useAssignmentLabelLinkPath.ts 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/ZonesAssignmentsLabels.tsx b/src/component/2d/zones/ZonesAssignmentsLabels.tsx index fd32b1021..76cdd17c8 100644 --- a/src/component/2d/zones/ZonesAssignmentsLabels.tsx +++ b/src/component/2d/zones/ZonesAssignmentsLabels.tsx @@ -11,7 +11,6 @@ import { useGlobal } from '../../context/GlobalContext.js'; import { useShareData } from '../../context/ShareDataContext.js'; import { SVGButton } from '../../elements/SVGButton.js'; import { SVGGroup } from '../../elements/SVGGroup.js'; -import type { Position } from '../../elements/draggable/useDraggable.js'; import useDraggable from '../../elements/draggable/useDraggable.js'; import { useHighlight } from '../../highlight/index.js'; import { useActiveSpectrumZonesViewState } from '../../hooks/useActiveSpectrumZonesViewState.js'; @@ -20,6 +19,7 @@ import type { GetTracesSpectraOptions } from '../useTracesSpectra.js'; import { getTracesSpectra } from '../useTracesSpectra.js'; import { getClosestSignal } from '../utilities/extractSpectrumSignals.js'; import { useScale2DX, useScale2DY } from '../utilities/scale.js'; +import { useAssignmentLabelLinkPath } from '../utilities/useAssignmentLabelLinkPath.js'; interface ZonesInnerProps { zones: ZonesType; @@ -34,174 +34,6 @@ const distance = 30; const iconSize = 16; const LabelBoxPadding = { left: 35, right: 0, top: 15, bottom: 15 }; -interface TargetBoundary { - x1: number; - x2: number; - y1: number; - y2: number; -} - -function getDistance(x1: number, y1: number, x2: number, y2: number) { - const deltaX = x2 - x1; - const deltaY = y2 - y1; - return Math.hypot(deltaX, deltaY); -} - -function radiansToDegrees(radians: number) { - return radians * (180 / Math.PI); -} -function getAngleFromSides(a: number, b: number, c: number) { - const radians = Math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)); - return radiansToDegrees(radians); -} - -interface FindBestLinkResult { - sourcePoint: { a: Position; b: Position }; - targetPoint: Position; - distance: number; - angle: number; -} - -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]; -} - -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, From d136cc8825fde31fbba99cccc3bb217f42e05615 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Tue, 17 Nov 2026 10:55:07 +0100 Subject: [PATCH 04/13] feat: add linked signal assignment label editing and positioning - Support editing, removing, and dragging assignment labels - Highlight links on hover and allow delete link with backspace --- src/component/2d/SVGContent2D.tsx | 4 +- .../2d/linked-signals/LinkedSignal.tsx | 66 ++++++ .../LinkedSignalAssignmentLabel.tsx | 197 ++++++++++++++++++ .../2d/linked-signals/LinkedSignals.tsx | 56 +++++ .../SignalCrossingIndicator.tsx | 43 ++-- src/component/2d/utilities/signalCrossings.ts | 33 +++ src/component/2d/zones/SignalsGuideLines.tsx | 11 +- src/component/context/DispatchContext.tsx | 2 + src/component/reducer/Reducer.ts | 15 ++ .../reducer/actions/LinkedSignalsActions.ts | 127 +++++++++++ src/data/data2d/Spectrum2D/initiateDatum2D.ts | 1 + 11 files changed, 537 insertions(+), 18 deletions(-) create mode 100644 src/component/2d/linked-signals/LinkedSignal.tsx create mode 100644 src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx create mode 100644 src/component/2d/linked-signals/LinkedSignals.tsx rename src/component/2d/{zones => linked-signals}/SignalCrossingIndicator.tsx (52%) create mode 100644 src/component/reducer/actions/LinkedSignalsActions.ts diff --git a/src/component/2d/SVGContent2D.tsx b/src/component/2d/SVGContent2D.tsx index 68f6f0e43..085ceee0d 100644 --- a/src/component/2d/SVGContent2D.tsx +++ b/src/component/2d/SVGContent2D.tsx @@ -6,8 +6,8 @@ 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 { SignalCrossingIndicator } from './zones/SignalCrossingIndicator.js'; import { SignalsGuideLines } from './zones/SignalsGuideLines.js'; import Zones from './zones/Zones.js'; import ZonesAssignmentsLabels from './zones/ZonesAssignmentsLabels.js'; @@ -27,7 +27,7 @@ export function SVGContent2D({ spectra }: Chart2DProps) { - + diff --git a/src/component/2d/linked-signals/LinkedSignal.tsx b/src/component/2d/linked-signals/LinkedSignal.tsx new file mode 100644 index 000000000..c535daead --- /dev/null +++ b/src/component/2d/linked-signals/LinkedSignal.tsx @@ -0,0 +1,66 @@ +import styled from '@emotion/styled'; +import type { KeyboardEvent } from 'react'; + +import { useDispatch } from '../../context/DispatchContext.js'; +import { useShareData } from '../../context/ShareDataContext.js'; +import { useScale2DX, useScale2DY } from '../utilities/scale.js'; +import type { PositionedLinkedSignal } from '../utilities/signalCrossings.js'; + +import { LinkedSignalAssignmentLabel } from './LinkedSignalAssignmentLabel.js'; + +const SignalCircle = styled.circle` + &:hover, + &:focus-visible { + fill: green; + stroke-width: 3; + } +`; + +interface LinkedSignalProps { + signal: PositionedLinkedSignal; +} + +export function LinkedSignal({ signal }: LinkedSignalProps) { + const scaleX = useScale2DX(); + const scaleY = useScale2DY(); + const dispatch = useDispatch(); + const { data: newLabel, setData } = useShareData(); + const id = `${signal.xSignalId}:${signal.ySignalId}`; + + 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 ( + + event.currentTarget.focus()} + onMouseLeave={(event) => event.currentTarget.blur()} + onKeyDown={handleKeyDown} + 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..fa5b3b154 --- /dev/null +++ b/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx @@ -0,0 +1,197 @@ +import styled from '@emotion/styled'; +import { useLayoutEffect, useRef, useState } from 'react'; +import { PiTextTSlash } from 'react-icons/pi'; + +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 { useActiveSpectrum } from '../../hooks/useActiveSpectrum.js'; +import { useScale2DX, useScale2DY } from '../utilities/scale.js'; +import type { PositionedLinkedSignal } 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; +} + +export function LinkedSignalAssignmentLabel({ + signal, +}: LinkedSignalAssignmentLabelProps) { + const { xSignalId, ySignalId, assignment } = signal; + const id = `${xSignalId}:${ySignalId}`; + const scaleX = useScale2DX(); + const scaleY = useScale2DY(); + const dispatch = useDispatch(); + 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 }, + }); + } + + return ( + + + + 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 = useActiveSpectrum(); + 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/zones/SignalCrossingIndicator.tsx b/src/component/2d/linked-signals/SignalCrossingIndicator.tsx similarity index 52% rename from src/component/2d/zones/SignalCrossingIndicator.tsx rename to src/component/2d/linked-signals/SignalCrossingIndicator.tsx index 0ad06056a..94c9abbde 100644 --- a/src/component/2d/zones/SignalCrossingIndicator.tsx +++ b/src/component/2d/linked-signals/SignalCrossingIndicator.tsx @@ -1,29 +1,41 @@ import type { Spectrum2D } from '@zakodium/nmr-types'; -import { isSpectrum2DFt } from '@zakodium/nmrium-core'; +import type { MouseEvent } from 'react'; -import useSpectrum from '../../hooks/useSpectrum.js'; +import { useDispatch } from '../../context/DispatchContext.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() { - const spectrum = useSpectrum(); - - if (!isSpectrum2DFt(spectrum) || !spectrum.display.isVisible) return null; - - return ( - - ); -} - -function SignalCrossingIndicatorInner({ +export function SignalCrossingIndicator({ linkedSignals, }: Pick) { const { nearest } = useNearestSignalCrossing({ linkedSignals }); const scaleX = useScale2DX(); const scaleY = useScale2DY(); + const dispatch = useDispatch(); + const { setData } = useShareData(); + + if (!nearest || nearest.isLinked) return null; + + const { xSignalId, ySignalId, assignment } = nearest; + + function handleClick(event: MouseEvent) { + event.stopPropagation(); + + dispatch({ + type: 'ADD_2D_SIGNAL_LINK', + payload: { + xSignalId, + ySignalId, + assignment, + }, + }); - if (!nearest) return null; + if (!assignment) { + setData(`${xSignalId}:${ySignalId}`); + } + } return ( @@ -37,6 +49,9 @@ function SignalCrossingIndicatorInner({ stroke="#ff0000" strokeWidth={2} pointerEvents="all" + data-self-control="true" + onClick={handleClick} + style={{ cursor: 'pointer' }} /> ); diff --git a/src/component/2d/utilities/signalCrossings.ts b/src/component/2d/utilities/signalCrossings.ts index e2acadb46..102dedcbd 100644 --- a/src/component/2d/utilities/signalCrossings.ts +++ b/src/component/2d/utilities/signalCrossings.ts @@ -30,6 +30,39 @@ interface Position { y: number; } +export type PositionedLinkedSignal = Spectrum2D['linkedSignals'][number] & { + xDelta: number; + yDelta: number; +}; + +export function getLinkedSignalPositions({ + xSignals, + ySignals, + linkedSignals, +}: Omit): PositionedLinkedSignal[] { + + if (!linkedSignals?.length) return []; + + const xDeltaBySignalId = new Map( + xSignals.map((signal) => [signal.id, signal.delta]), + ); + const yDeltaBySignalId = new Map( + ySignals.map((signal) => [signal.id, signal.delta]), + ); + const positionedSignals: PositionedLinkedSignal[] = []; + + for (const link of linkedSignals) { + const xDelta = xDeltaBySignalId.get(link.xSignalId); + const yDelta = yDeltaBySignalId.get(link.ySignalId); + + if (xDelta === undefined || yDelta === undefined) continue; + + positionedSignals.push({ ...link, xDelta, yDelta }); + } + + return positionedSignals; +} + function inDomain(value: number, domain: number[]) { const [min, max] = domain; return value >= Math.min(min, max) && value <= Math.max(min, max); 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 ( , 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..8acc62e6f --- /dev/null +++ b/src/component/reducer/actions/LinkedSignalsActions.ts @@ -0,0 +1,127 @@ +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 } +>; +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: false, + }); +} + +export function handleChangeLinkedSignalAssignment( + draft: Draft, + action: ChangeLinkedSignalAssignmentAction, +) { + const linkedSignal = getLinkedSignal(draft, action.payload.id); + if (!linkedSignal) { + return; + } + const { link } = linkedSignal; + link.assignment = action.payload.value; + link.isAutoAssignment = false; +} + +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/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 From 941f8cb3aa4f7f5f43a1365d5e33a1e994d52a31 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Tue, 17 Nov 2026 14:40:06 +0100 Subject: [PATCH 05/13] feat: display linked 2D assignments by experiment in assignment table --- .../MoleculeAssignmentTable.tsx | 51 ++++++--- .../utilities/exportAssignments.ts | 11 ++ .../getLinkedAssignmentsByExperiment.ts | 106 ++++++++++++++++++ 3 files changed, 155 insertions(+), 13 deletions(-) create mode 100644 src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts diff --git a/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx b/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx index eb4518b66..eba715fa2 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( @@ -103,19 +111,19 @@ export function MoleculeAssignmentTable(props: MoleculeAssignmentTableProps) { }, ...(showAtomNumbers ? columnHelper.columns([ - { - header: 'Atom numbers', - accessorKey: 'atomNumbers', - enableSorting: false, - cell: ({ row }) => ( - - ), - }, - ]) + { + header: 'Atom numbers', + accessorKey: 'atomNumbers', + enableSorting: false, + cell: ({ row }) => ( + + ), + }, + ]) : []), { header: 'Atom labels', @@ -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..a6ebf652e --- /dev/null +++ b/src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts @@ -0,0 +1,106 @@ +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(', '); +} From ae9d36eb17ad423e9bf84f26fe226dfa734f5f0f Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Tue, 17 Nov 2026 14:48:55 +0100 Subject: [PATCH 06/13] chore: fix prettier --- src/component/2d/utilities/signalCrossings.ts | 1 - .../MoleculeAssignmentTable.tsx | 26 +++++++++---------- .../getLinkedAssignmentsByExperiment.ts | 1 - 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/component/2d/utilities/signalCrossings.ts b/src/component/2d/utilities/signalCrossings.ts index 102dedcbd..2766ccf7f 100644 --- a/src/component/2d/utilities/signalCrossings.ts +++ b/src/component/2d/utilities/signalCrossings.ts @@ -40,7 +40,6 @@ export function getLinkedSignalPositions({ ySignals, linkedSignals, }: Omit): PositionedLinkedSignal[] { - if (!linkedSignals?.length) return []; const xDeltaBySignalId = new Map( diff --git a/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx b/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx index eba715fa2..602645fc2 100644 --- a/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx +++ b/src/component/panels/assignment-summary/MoleculeAssignmentTable.tsx @@ -111,19 +111,19 @@ export function MoleculeAssignmentTable(props: MoleculeAssignmentTableProps) { }, ...(showAtomNumbers ? columnHelper.columns([ - { - header: 'Atom numbers', - accessorKey: 'atomNumbers', - enableSorting: false, - cell: ({ row }) => ( - - ), - }, - ]) + { + header: 'Atom numbers', + accessorKey: 'atomNumbers', + enableSorting: false, + cell: ({ row }) => ( + + ), + }, + ]) : []), { header: 'Atom labels', diff --git a/src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts b/src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts index a6ebf652e..c8dfe2df7 100644 --- a/src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts +++ b/src/component/panels/assignment-summary/utilities/getLinkedAssignmentsByExperiment.ts @@ -58,7 +58,6 @@ export function getLinkedAssignmentsByExperiment( // }, // } for (const link of spectrum.linkedSignals ?? []) { - const { xSignalId, ySignalId, assignment } = link; if (!assignment) continue; From d0a929418d4672334a1e3dfbe7ce499b8bf37bf0 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Wed, 18 Nov 2026 08:59:51 +0100 Subject: [PATCH 07/13] fix: assignment label handling for homonuclear signals --- src/component/2d/useNearestSignalCrossing.ts | 3 ++ src/component/2d/utilities/signalCrossings.ts | 31 +++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/component/2d/useNearestSignalCrossing.ts b/src/component/2d/useNearestSignalCrossing.ts index a2983a07e..e383593e2 100644 --- a/src/component/2d/useNearestSignalCrossing.ts +++ b/src/component/2d/useNearestSignalCrossing.ts @@ -36,11 +36,14 @@ export function useNearestSignalCrossing({ 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]); diff --git a/src/component/2d/utilities/signalCrossings.ts b/src/component/2d/utilities/signalCrossings.ts index 2766ccf7f..67ce87cfb 100644 --- a/src/component/2d/utilities/signalCrossings.ts +++ b/src/component/2d/utilities/signalCrossings.ts @@ -23,6 +23,7 @@ interface BuildCandidatesOptions extends Pick { xSignals: Signal1D[]; ySignals: Signal1D[]; domains: CrossingDomains; + hasSameNucleus: boolean; } interface Position { @@ -39,7 +40,10 @@ export function getLinkedSignalPositions({ xSignals, ySignals, linkedSignals, -}: Omit): PositionedLinkedSignal[] { +}: Omit< + BuildCandidatesOptions, + 'domains' | 'hasSameNucleus' +>): PositionedLinkedSignal[] { if (!linkedSignals?.length) return []; const xDeltaBySignalId = new Map( @@ -67,11 +71,30 @@ function inDomain(value: number, domain: number[]) { return value >= Math.min(min, max) && value <= Math.max(min, max); } +interface CrossingAssignmentLabelOptions { + xAssignment?: string; + yAssignment?: string; + hasSameNucleus: boolean; +} + +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}`), @@ -92,7 +115,11 @@ export function buildCandidates({ xDelta: x.delta, yDelta: y.delta, isLinked: linked.has(`${x.id}:${y.id}`), - assignment: [x.assignment, y.assignment].filter(Boolean).join(','), + assignment: getCrossingAssignmentLabel({ + xAssignment: x.assignment, + yAssignment: y.assignment, + hasSameNucleus, + }), }); } } From 57bdc81e6a88e31fb48600f2b702cfd6b61eecc3 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Wed, 18 Nov 2026 09:02:03 +0100 Subject: [PATCH 08/13] refactor: change signal assignment separator to arrow --- src/component/2d/utilities/signalCrossings.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/component/2d/utilities/signalCrossings.ts b/src/component/2d/utilities/signalCrossings.ts index 67ce87cfb..c5ee4747b 100644 --- a/src/component/2d/utilities/signalCrossings.ts +++ b/src/component/2d/utilities/signalCrossings.ts @@ -86,7 +86,7 @@ function getCrossingAssignmentLabel({ return xAssignment || ''; } - return [xAssignment, yAssignment].filter(Boolean).join('-'); + return [xAssignment, yAssignment].filter(Boolean).join('→'); } export function buildCandidates({ From 251d0613c747714235d6475aaa6f3fc478c38c46 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Wed, 18 Nov 2026 09:39:06 +0100 Subject: [PATCH 09/13] refactor: allow deleting signal links from assignment labels --- .../2d/linked-signals/LinkedSignal.tsx | 18 +++++++----------- .../LinkedSignalAssignmentLabel.tsx | 3 +++ 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/component/2d/linked-signals/LinkedSignal.tsx b/src/component/2d/linked-signals/LinkedSignal.tsx index c535daead..a977fd3e9 100644 --- a/src/component/2d/linked-signals/LinkedSignal.tsx +++ b/src/component/2d/linked-signals/LinkedSignal.tsx @@ -8,11 +8,10 @@ import type { PositionedLinkedSignal } from '../utilities/signalCrossings.js'; import { LinkedSignalAssignmentLabel } from './LinkedSignalAssignmentLabel.js'; -const SignalCircle = styled.circle` - &:hover, - &:focus-visible { +const Wrapper = styled.g` + &:hover > circle:first-of-type { fill: green; - stroke-width: 3; + stroke-width: 5; } `; @@ -27,7 +26,7 @@ export function LinkedSignal({ signal }: LinkedSignalProps) { const { data: newLabel, setData } = useShareData(); const id = `${signal.xSignalId}:${signal.ySignalId}`; - function handleKeyDown(event: KeyboardEvent) { + function handleKeyDown(event: KeyboardEvent) { if (event.key === 'Backspace' || event.key === 'Delete') { event.preventDefault(); event.stopPropagation(); @@ -39,21 +38,18 @@ export function LinkedSignal({ signal }: LinkedSignalProps) { } return ( - - + event.currentTarget.focus()} onMouseLeave={(event) => event.currentTarget.blur()} - onKeyDown={handleKeyDown} onClick={(event) => { event.stopPropagation(); setData(id); @@ -61,6 +57,6 @@ export function LinkedSignal({ signal }: LinkedSignalProps) { /> - + ); } diff --git a/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx b/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx index fa5b3b154..124716b23 100644 --- a/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx +++ b/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx @@ -112,6 +112,9 @@ export function LinkedSignalAssignmentLabel({ isMoving={dragPosition !== null} data-self-control="true" {...disableMouseTrackingProps} + tabIndex={0} + onMouseEnter={(event) => event.currentTarget.focus()} + onMouseLeave={(event) => event.currentTarget.blur()} > From 83b52c3ca2c7b234ed34df6a6fc2e4df51c48bda Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Wed, 18 Nov 2026 10:27:26 +0100 Subject: [PATCH 10/13] feat: highlight assigned atoms on linked signal hover --- .../2d/linked-signals/LinkedSignal.tsx | 5 ++++- src/component/2d/utilities/signalCrossings.ts | 22 ++++++++++--------- src/component/highlight/index.tsx | 1 + .../hooks/useAtomAssignment.tsx | 5 ++++- 4 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/component/2d/linked-signals/LinkedSignal.tsx b/src/component/2d/linked-signals/LinkedSignal.tsx index a977fd3e9..34e276f34 100644 --- a/src/component/2d/linked-signals/LinkedSignal.tsx +++ b/src/component/2d/linked-signals/LinkedSignal.tsx @@ -3,6 +3,7 @@ import type { KeyboardEvent } from 'react'; import { useDispatch } from '../../context/DispatchContext.js'; import { useShareData } from '../../context/ShareDataContext.js'; +import { useHighlight } from '../../highlight/index.js'; import { useScale2DX, useScale2DY } from '../utilities/scale.js'; import type { PositionedLinkedSignal } from '../utilities/signalCrossings.js'; @@ -24,6 +25,8 @@ export function LinkedSignal({ signal }: LinkedSignalProps) { const scaleY = useScale2DY(); const dispatch = useDispatch(); const { data: newLabel, setData } = useShareData(); + const { diaIDs } = signal; + const { show, hide } = useHighlight(diaIDs, { type: 'LINKED_SIGNAL' }); const id = `${signal.xSignalId}:${signal.ySignalId}`; function handleKeyDown(event: KeyboardEvent) { @@ -38,7 +41,7 @@ export function LinkedSignal({ signal }: LinkedSignalProps) { } return ( - + ): PositionedLinkedSignal[] { if (!linkedSignals?.length) return []; - const xDeltaBySignalId = new Map( - xSignals.map((signal) => [signal.id, signal.delta]), - ); - const yDeltaBySignalId = new Map( - ySignals.map((signal) => [signal.id, signal.delta]), - ); + 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 xDelta = xDeltaBySignalId.get(link.xSignalId); - const yDelta = yDeltaBySignalId.get(link.ySignalId); + const xSignal = xSignalsById.get(link.xSignalId); + const ySignal = ySignalsById.get(link.ySignalId); - if (xDelta === undefined || yDelta === undefined) continue; + if (xSignal === undefined || ySignal === undefined) continue; - positionedSignals.push({ ...link, xDelta, yDelta }); + positionedSignals.push({ + ...link, + xDelta: xSignal.delta, + yDelta: ySignal.delta, + diaIDs: [...(xSignal.diaIDs ?? []), ...(ySignal.diaIDs ?? [])], + }); } return positionedSignals; 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/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; } From 15fa469bc06cfec0cb3ac52fa06ffbccce4400e1 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Thu, 19 Nov 2026 12:51:44 +0100 Subject: [PATCH 11/13] refactor: support actions in the field editor --- src/component/1d-2d/FieldEdition.tsx | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) 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' ? ( ) : ( - + ) } From c280a32b0d30cca5f2b6518a5b255ddad7629545 Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Thu, 19 Nov 2026 12:55:56 +0100 Subject: [PATCH 12/13] feat: add automatic assignemnt for linked 2d assignment label --- .../2d/linked-signals/LinkedSignal.tsx | 2 +- .../LinkedSignalAssignmentLabel.tsx | 49 +++++++++++++++++-- src/component/2d/utilities/signalCrossings.ts | 14 ++++-- .../reducer/actions/LinkedSignalsActions.ts | 11 +++-- 4 files changed, 62 insertions(+), 14 deletions(-) diff --git a/src/component/2d/linked-signals/LinkedSignal.tsx b/src/component/2d/linked-signals/LinkedSignal.tsx index 34e276f34..de4d5154d 100644 --- a/src/component/2d/linked-signals/LinkedSignal.tsx +++ b/src/component/2d/linked-signals/LinkedSignal.tsx @@ -25,7 +25,7 @@ export function LinkedSignal({ signal }: LinkedSignalProps) { const scaleY = useScale2DY(); const dispatch = useDispatch(); const { data: newLabel, setData } = useShareData(); - const { diaIDs } = signal; + const diaIDs = [...signal.xDiaIDs, ...signal.yDiaIDs]; const { show, hide } = useHighlight(diaIDs, { type: 'LINKED_SIGNAL' }); const id = `${signal.xSignalId}:${signal.ySignalId}`; diff --git a/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx b/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx index 124716b23..f18e0fcb8 100644 --- a/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx +++ b/src/component/2d/linked-signals/LinkedSignalAssignmentLabel.tsx @@ -1,6 +1,8 @@ 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'; @@ -11,9 +13,11 @@ 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 { useActiveSpectrum } from '../../hooks/useActiveSpectrum.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 }>` @@ -35,11 +39,13 @@ interface LinkedSignalAssignmentLabelProps { export function LinkedSignalAssignmentLabel({ signal, }: LinkedSignalAssignmentLabelProps) { - const { xSignalId, ySignalId, assignment } = signal; + 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 @@ -107,6 +113,30 @@ export function LinkedSignalAssignmentLabel({ }); } + 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 ( + } PopoverProps={{ placement: 'top', targetTagName: 'g', @@ -181,7 +224,7 @@ function useLinkedSignalAssignmentLabelPosition({ }: UseLinkedSignalAssignmentLabelPositionOptions) { const scaleX = useScale2DX(); const scaleY = useScale2DY(); - const spectrum = useActiveSpectrum(); + const spectrum = useSpectrum(); const { view } = useChartData(); const externalPosition = spectrum && view.assignmentsLabelsCoordinates?.[spectrum.id]?.[id]; diff --git a/src/component/2d/utilities/signalCrossings.ts b/src/component/2d/utilities/signalCrossings.ts index 5ba22ae1a..178d734ff 100644 --- a/src/component/2d/utilities/signalCrossings.ts +++ b/src/component/2d/utilities/signalCrossings.ts @@ -31,11 +31,14 @@ interface Position { y: number; } -export type PositionedLinkedSignal = Spectrum2D['linkedSignals'][number] & { +type LinkedSignal = Spectrum2D['linkedSignals'][number]; + +export interface PositionedLinkedSignal extends LinkedSignal { xDelta: number; yDelta: number; - diaIDs: string[]; -}; + xDiaIDs: string[]; + yDiaIDs: string[]; +} export function getLinkedSignalPositions({ xSignals, @@ -61,7 +64,8 @@ export function getLinkedSignalPositions({ ...link, xDelta: xSignal.delta, yDelta: ySignal.delta, - diaIDs: [...(xSignal.diaIDs ?? []), ...(ySignal.diaIDs ?? [])], + xDiaIDs: xSignal.diaIDs ?? [], + yDiaIDs: ySignal.diaIDs ?? [], }); } @@ -79,7 +83,7 @@ interface CrossingAssignmentLabelOptions { hasSameNucleus: boolean; } -function getCrossingAssignmentLabel({ +export function getCrossingAssignmentLabel({ xAssignment, yAssignment, hasSameNucleus, diff --git a/src/component/reducer/actions/LinkedSignalsActions.ts b/src/component/reducer/actions/LinkedSignalsActions.ts index 8acc62e6f..4b83f5daf 100644 --- a/src/component/reducer/actions/LinkedSignalsActions.ts +++ b/src/component/reducer/actions/LinkedSignalsActions.ts @@ -18,7 +18,7 @@ type Delete2DSignalLinkAction = ActionType< >; type ChangeLinkedSignalAssignmentAction = ActionType< 'CHANGE_LINKED_SIGNAL_ASSIGNMENT_LABEL', - { id: string; value: string } + { id: string; value: string; isAutoAssignment?: boolean } >; type SetLinkedSignalLabelCoordinationAction = ActionType< 'SET_LINKED_SIGNAL_ASSIGNMENT_LABEL_COORDINATION', @@ -72,7 +72,7 @@ export function handleAdd2DSignalLink( xSignalId, ySignalId, assignment, - isAutoAssignment: false, + isAutoAssignment: true, }); } @@ -80,13 +80,14 @@ export function handleChangeLinkedSignalAssignment( draft: Draft, action: ChangeLinkedSignalAssignmentAction, ) { - const linkedSignal = getLinkedSignal(draft, action.payload.id); + const { isAutoAssignment = false, value, id } = action.payload; + const linkedSignal = getLinkedSignal(draft, id); if (!linkedSignal) { return; } const { link } = linkedSignal; - link.assignment = action.payload.value; - link.isAutoAssignment = false; + link.assignment = value; + link.isAutoAssignment = isAutoAssignment; } export function handleDelete2DSignalLink( From d9065198c267d02f5e0e3b09e4f7dee4b6eaa15a Mon Sep 17 00:00:00 2001 From: hamed musallam Date: Thu, 19 Nov 2026 13:28:56 +0100 Subject: [PATCH 13/13] feat: update 2d linked assignment labels on atom custom label changes --- .../hooks/useSignalAssignmentUpdates.ts | 78 +++++++++++- src/component/reducer/Reducer.ts | 10 +- .../reducer/actions/MoleculeActions.ts | 118 +++++++++++++++++- .../reducer/actions/RangesActions.ts | 63 +--------- 4 files changed, 196 insertions(+), 73 deletions(-) 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/reducer/Reducer.ts b/src/component/reducer/Reducer.ts index 5b26739f2..5231df6d0 100644 --- a/src/component/reducer/Reducer.ts +++ b/src/component/reducer/Reducer.ts @@ -712,6 +712,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': @@ -783,11 +788,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); 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,