From 51e42bf315729651986a44ad21dc13502768355a Mon Sep 17 00:00:00 2001 From: Suryaa Charan <122703005+sshiv012@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:55:51 -0800 Subject: [PATCH 1/5] feat(frontend): anchor comment boxes to operators A comment box can now be anchored to an operator from the canvas context menu ("anchor to operator" / "detach from operator"). Anchored comments follow the operator when it is dragged and keep their offset through auto-layout, which sizes each operator together with its anchored comments so nothing overlaps. Anchored comments get a dashed blue outline; unanchored comments float as before. Deleting an operator detaches its comments instead of deleting them. Also fixes: - auto-layout never persisted comment box positions, so they jumped back on reload; - dragging a selection persisted selected comments' positions before they moved; - calculateTopLeftOperatorPosition() returned early on an empty workflow with joint-command listening still off, so every later drag on a new workflow went unsynced until reload. Co-Authored-By: Claude Opus 5.5 --- .../context-menu/context-menu.component.html | 21 ++ .../context-menu.component.spec.ts | 100 +++++++ .../context-menu/context-menu.component.ts | 56 ++++ .../service/joint-ui/joint-ui.service.ts | 11 + .../model/joint-graph-wrapper.ts | 59 ++++- .../model/shared-model-change-handler.ts | 6 + .../model/workflow-action.service.spec.ts | 245 ++++++++++++++++++ .../model/workflow-action.service.ts | 85 ++++-- .../workflow-graph/model/workflow-graph.ts | 29 +++ .../types/workflow-common.interface.ts | 5 + 10 files changed, 598 insertions(+), 19 deletions(-) diff --git a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.html b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.html index db7f5c746ac..1dbc89adc13 100644 --- a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.html +++ b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.html @@ -155,6 +155,27 @@ >delete +
  • + anchor to operator +
  • +
  • + detach from operator +
  • +
  • { hasLinkWithID: vi.fn(), bundleActions: vi.fn(), getSubDAG: vi.fn(), + getCommentBox: vi.fn(), + hasCommentBox: vi.fn(), }; const workflowActionServiceSpy = { @@ -89,6 +91,8 @@ describe("ContextMenuComponent", () => { getWorkflowMetadata: vi.fn(), getTexeraGraph: vi.fn(), deleteLinkWithID: vi.fn(), + anchorCommentBox: vi.fn(), + detachCommentBox: vi.fn(), }; workflowActionServiceSpy.getJointGraphWrapper.mockReturnValue(jointGraphWrapperSpy); workflowActionServiceSpy.getWorkflowModificationEnabledStream.mockReturnValue(of(true)); @@ -796,6 +800,102 @@ describe("ContextMenuComponent", () => { expect(spy).toHaveBeenCalledTimes(1); }); }); + describe("comment box anchoring", () => { + const norm = (s: string | null) => (s ?? "").replace(/\s+/g, " ").trim().toLowerCase(); + const ANCHOR = "anchor to operator"; + const DETACH = "detach from operator"; + let anchors: Record; + + function renderedLabels(): string[] { + return fixture.debugElement.queryAll(By.css("li[nz-menu-item]")).map(li => norm(li.nativeElement.textContent)); + } + + function clickItem(label: string): void { + const item = fixture.debugElement + .queryAll(By.css("li[nz-menu-item]")) + .find(li => norm(li.nativeElement.textContent) === label); + if (!item) throw new Error(`menu item "${label}" not rendered; present: [${renderedLabels().join(" | ")}]`); + item.nativeElement.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); + } + + function select(operatorIDs: string[], commentBoxIDs: string[]): void { + jointGraphWrapperSpy.getCurrentHighlightedOperatorIDs.mockReturnValue(operatorIDs); + jointGraphWrapperSpy.getCurrentHighlightedCommentBoxIDs.mockReturnValue(commentBoxIDs); + highlightedOperatorsSubject.next(operatorIDs); + highlightedCommentBoxesSubject.next(commentBoxIDs); + fixture.detectChanges(); + } + + beforeEach(() => { + anchors = { "box-floating": undefined, "box-anchored": "op1" }; + // "execute to this operator" renders beside the anchoring items for a lone selected operator. + validationWorkflowService.validateOperator.mockReturnValue({ isValid: true }); + (workflowActionService.getTexeraGraph().hasCommentBox as any).mockImplementation((id: string) => id in anchors); + (workflowActionService.getTexeraGraph().getCommentBox as any).mockImplementation((id: string) => ({ + ...mockCommentBox, + commentBoxID: id, + anchoredOperatorID: anchors[id], + })); + component.isWorkflowModifiable = true; + }); + + it("anchors every selected comment box to the one selected operator, in one bundled action", () => { + select(["op2"], ["box-floating", "box-anchored"]); + const bundle = workflowActionService.getTexeraGraph().bundleActions as any; + bundle.mockClear(); + + clickItem(ANCHOR); + + expect(bundle).toHaveBeenCalledTimes(1); + expect(workflowActionService.anchorCommentBox).toHaveBeenCalledWith("box-floating", "op2"); + expect(workflowActionService.anchorCommentBox).toHaveBeenCalledWith("box-anchored", "op2"); + }); + + it("offers no anchor without exactly one operator and at least one comment box selected", () => { + select(["op1", "op2"], ["box-floating"]); + expect(renderedLabels()).not.toContain(ANCHOR); + select(["op1"], []); + expect(renderedLabels()).not.toContain(ANCHOR); + select([], ["box-floating"]); + expect(renderedLabels()).not.toContain(ANCHOR); + }); + + it("offers no anchor or detach while the workflow cannot be modified", () => { + component.isWorkflowModifiable = false; + select(["op1"], ["box-anchored"]); + expect(renderedLabels()).not.toContain(ANCHOR); + select([], ["box-anchored"]); + expect(renderedLabels()).not.toContain(DETACH); + }); + + it("offers no anchor or detach under a structure lock", () => { + component.structureLocked = true; + select(["op1"], ["box-anchored"]); + expect(renderedLabels()).not.toContain(ANCHOR); + select([], ["box-anchored"]); + expect(renderedLabels()).not.toContain(DETACH); + }); + + it("detaches only the anchored comment boxes among the selection", () => { + select([], ["box-floating", "box-anchored"]); + + clickItem(DETACH); + + expect(workflowActionService.detachCommentBox).toHaveBeenCalledTimes(1); + expect(workflowActionService.detachCommentBox).toHaveBeenCalledWith("box-anchored"); + }); + + it("offers no detach when every selected comment box floats", () => { + select([], ["box-floating"]); + expect(renderedLabels()).not.toContain(DETACH); + }); + + it("ignores a selected comment box that has just been deleted", () => { + select([], ["box-deleted"]); + expect(renderedLabels()).not.toContain(DETACH); + expect(workflowActionService.getTexeraGraph().getCommentBox).not.toHaveBeenCalledWith("box-deleted"); + }); + }); }); describe("ContextMenuComponent onDelete with real WorkflowActionService", () => { diff --git a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts index 6d645a533e4..60d13ebdfd0 100644 --- a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts +++ b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts @@ -173,6 +173,62 @@ export class ContextMenuComponent { }); } + /** Anchoring takes the selected comment boxes and exactly one selected operator to anchor them to. */ + public canAnchorCommentBoxes(): boolean { + return ( + this.canModify && + this.highlightedOperatorIds.length === 1 && + this.highlightedCommentBoxIds.length > 0 && + !this.hasHighlightedLinks() + ); + } + + /** Anchors every selected comment box to the selected operator. */ + public onAnchorCommentBoxes(): void { + if (!this.canAnchorCommentBoxes()) { + return; + } + const operatorID = this.highlightedOperatorIds[0]; + const commentBoxIDs = Array.from(this.highlightedCommentBoxIds); + this.workflowActionService + .getTexeraGraph() + .bundleActions(() => + commentBoxIDs.forEach(commentBoxID => this.workflowActionService.anchorCommentBox(commentBoxID, operatorID)) + ); + } + + private getSelectedAnchoredCommentBoxIDs(): string[] { + const texeraGraph = this.workflowActionService.getTexeraGraph(); + // The highlight stream can still name a comment box that has just been deleted. + return this.highlightedCommentBoxIds.filter( + commentBoxID => + texeraGraph.hasCommentBox(commentBoxID) && + texeraGraph.getCommentBox(commentBoxID).anchoredOperatorID !== undefined + ); + } + + public canDetachCommentBoxes(): boolean { + return ( + this.canModify && + this.highlightedOperatorIds.length === 0 && + !this.hasHighlightedLinks() && + this.getSelectedAnchoredCommentBoxIDs().length > 0 + ); + } + + /** Detaches the selected anchored comment boxes, so they float again. */ + public onDetachCommentBoxes(): void { + if (!this.canDetachCommentBoxes()) { + return; + } + const commentBoxIDs = this.getSelectedAnchoredCommentBoxIDs(); + this.workflowActionService + .getTexeraGraph() + .bundleActions(() => + commentBoxIDs.forEach(commentBoxID => this.workflowActionService.detachCommentBox(commentBoxID)) + ); + } + private registerWorkflowModifiableChangedHandler() { this.workflowActionService .getWorkflowModificationEnabledStream() diff --git a/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts b/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts index 7d51e3a6199..05398a3e6a1 100644 --- a/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts +++ b/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts @@ -598,8 +598,19 @@ export class JointUIService { attrs: JointUIService.getCustomCommentStyleAttrs(), }); commentElement.set("id", commentBox.commentBoxID); + commentElement.attr("rect", JointUIService.getCommentBoxAnchorAttrs(commentBox.anchoredOperatorID !== undefined)); return commentElement; } + + /** + * The outline that tells an anchored comment box from a floating one: dashed for anchored, none for floating. + * @param anchored whether the comment box is anchored to an operator + */ + public static getCommentBoxAnchorAttrs(anchored: boolean): joint.attributes.SVGAttributes { + return anchored + ? { stroke: "#1890FF", "stroke-width": 2, "stroke-dasharray": "4 2" } + : { stroke: "#CED4D9", "stroke-width": 0, "stroke-dasharray": "none" }; + } /** * This function converts a Texera source and target OperatorPort to * a JointJS link cell that could be added to the JointJS. diff --git a/frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts b/frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts index acb31c4917f..2074094b38c 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts @@ -586,9 +586,44 @@ export class JointGraphWrapper { return this.zoomRatio; } - public autoLayoutJoint(): void { + /** + * Lays out the graph left to right with dagre. + * + * Comment boxes anchored to an operator are not laid out on their own: the operator is laid out as + * the bounding box of itself and its anchored comment boxes, so that nothing is placed on top of + * them, and the comment boxes are then put back at their offsets from the operator. + * + * @param anchoredCommentBoxIDs the IDs of the comment boxes anchored to each operator, by operator ID + */ + public autoLayoutJoint(anchoredCommentBoxIDs: ReadonlyMap = new Map()): void { + const getElement = (id: string) => this.jointGraph.getCell(id) as joint.dia.Element; + const anchored = new Set(Array.from(anchoredCommentBoxIDs.values()).flat()); + // For each operator with anchored comment boxes: the bounding box of the group, and the + // operator's and each comment box's offset within it, so the group is laid out as one node. + const groups = new Map(); + anchoredCommentBoxIDs.forEach((commentBoxIDs, operatorID) => { + const operator = getElement(operatorID); + const bbox = commentBoxIDs + .map(commentBoxID => getElement(commentBoxID).getBBox()) + .reduce((union, box) => union.union(box), operator.getBBox()); + const operatorPosition = operator.position(); + groups.set(operatorID, { + size: { width: bbox.width, height: bbox.height }, + operatorOffset: { x: operatorPosition.x - bbox.x, y: operatorPosition.y - bbox.y }, + commentOffsets: commentBoxIDs.map(commentBoxID => { + const position = getElement(commentBoxID).position(); + return { x: position.x - operatorPosition.x, y: position.y - operatorPosition.y }; + }), + }); + }); + joint.layout.DirectedGraph.layout( - [...this.jointGraph.getElements().filter(el => el.attributes.type !== "region"), ...this.jointGraph.getLinks()], + [ + ...this.jointGraph + .getElements() + .filter(el => el.attributes.type !== "region" && !anchored.has(el.id.toString())), + ...this.jointGraph.getLinks(), + ], { dagre: dagre, graphlib: graphlib, @@ -598,8 +633,28 @@ export class JointGraphWrapper { ranker: "tight-tree", rankDir: "LR", resizeClusters: true, + exportElement: element => groups.get(element.id.toString())?.size ?? element.size(), + setPosition: (element, glNode) => { + const offset = groups.get(element.id.toString())?.operatorOffset ?? { x: 0, y: 0 }; + element.set("position", { + x: glNode.x - glNode.width / 2 + offset.x, + y: glNode.y - glNode.height / 2 + offset.y, + }); + }, } ); + + groups.forEach(({ commentOffsets }, operatorID) => { + const operatorPosition = getElement(operatorID).position(); + anchoredCommentBoxIDs + .get(operatorID) + ?.forEach((commentBoxID, i) => + getElement(commentBoxID).position( + operatorPosition.x + commentOffsets[i].x, + operatorPosition.y + commentOffsets[i].y + ) + ); + }); } /** diff --git a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts index e5eab7a812e..e3f7438328a 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts @@ -468,6 +468,7 @@ export class SharedModelChangeHandler { * - adding comments * - deleting comments * - editing comments (processed as deleting and then adding in-place) + * - anchoring the box to an operator, or detaching it * @private */ private handleCommentBoxDeep(): void { @@ -475,6 +476,11 @@ export class SharedModelChangeHandler { events.forEach(event => { if (event.target !== this.texeraGraph.sharedModel.commentBoxMap) { const commentBox: CommentBox = this.texeraGraph.getCommentBox(event.path[0] as string); + if (event.path.length === 1 && event.changes.keys.has("anchoredOperatorID")) { + this.jointGraph + .getCell(commentBox.commentBoxID) + ?.attr("rect", JointUIService.getCommentBoxAnchorAttrs(commentBox.anchoredOperatorID !== undefined)); + } if (event.path.length === 2 && event.path[event.path.length - 1] === "comments") { const addedComments = Array.from(event.changes.added.values()); const deletedComments = Array.from(event.changes.deleted.values()); diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts index 984ff04ff9c..865dd61ad5b 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts @@ -367,6 +367,244 @@ describe("WorkflowActionService", () => { // expect(resultOpPos).toEqual(mockPoint); }); + // A comment box either floats on the canvas or is anchored to an operator, like a comment anchored to + // text in a document: an anchored box keeps its offset from the operator whenever the operator moves, + // whether a user drags it or auto-layout re-spaces the graph. + describe("comment box anchoring", () => { + const anchoredID = "commentBox-anchored"; + const floatingID = "commentBox-floating"; + + function boundingBox(elementID: string): { x: number; y: number; width: number; height: number } { + const cell = jointGraph.getCell(elementID) as joint.dia.Element; + return { ...cell.position(), ...cell.size() }; + } + + function overlaps(a: ReturnType, b: ReturnType): boolean { + return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; + } + + function addComment(commentBoxID: string, position: { x: number; y: number }): void { + service.addCommentBox({ ...mockCommentBox, commentBoxID, commentBoxPosition: position }); + } + + function offsetFrom(elementID: string, operatorID: string): { x: number; y: number } { + const element = service.getJointGraphWrapper().getElementPosition(elementID); + const operator = service.getJointGraphWrapper().getElementPosition(operatorID); + return { x: element.x - operator.x, y: element.y - operator.y }; + } + + it("anchors a comment box to an operator and detaches it again", () => { + service.addOperator(mockScanPredicate, mockPoint); + addComment(anchoredID, { x: 0, y: 0 }); + + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toEqual(mockScanPredicate.operatorID); + expect(texeraGraph.getCommentBoxesAnchoredTo(mockScanPredicate.operatorID)).toEqual([anchoredID]); + + service.detachCommentBox(anchoredID); + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toBeUndefined(); + expect(texeraGraph.getCommentBoxesAnchoredTo(mockScanPredicate.operatorID)).toEqual([]); + }); + + it("re-anchoring moves the anchor rather than adding a second one", () => { + service.addOperator(mockScanPredicate, mockPoint); + service.addOperator(mockResultPredicate, mockPoint); + addComment(anchoredID, { x: 0, y: 0 }); + + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + service.anchorCommentBox(anchoredID, mockResultPredicate.operatorID); + + expect(texeraGraph.getCommentBoxesAnchoredTo(mockScanPredicate.operatorID)).toEqual([]); + expect(texeraGraph.getCommentBoxesAnchoredTo(mockResultPredicate.operatorID)).toEqual([anchoredID]); + }); + + it("rejects an anchor to an operator or from a comment box that does not exist", () => { + service.addOperator(mockScanPredicate, mockPoint); + addComment(anchoredID, { x: 0, y: 0 }); + + expect(() => service.anchorCommentBox(anchoredID, "no-such-operator")).toThrowError(/no-such-operator/); + expect(() => service.anchorCommentBox("no-such-box", mockScanPredicate.operatorID)).toThrowError(/no-such-box/); + expect(() => service.detachCommentBox("no-such-box")).toThrowError(/no-such-box/); + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toBeUndefined(); + }); + + it("detaching a floating comment box is a no-op", () => { + addComment(floatingID, { x: 0, y: 0 }); + expect(() => service.detachCommentBox(floatingID)).not.toThrow(); + expect(texeraGraph.getCommentBox(floatingID).anchoredOperatorID).toBeUndefined(); + }); + + it("keeps the comment box, floating, when its operator is deleted", () => { + service.addOperator(mockScanPredicate, mockPoint); + addComment(anchoredID, { x: 0, y: 0 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.deleteOperator(mockScanPredicate.operatorID); + + expect(texeraGraph.hasCommentBox(anchoredID)).toBe(true); + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toBeUndefined(); + }); + + it("moves an anchored comment box along with its dragged operator, and leaves a floating one", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 110, y: 40 }); + addComment(floatingID, { x: 400, y: 400 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.highlightOperators(false, mockScanPredicate.operatorID); + service.getJointGraphWrapper().setAbsolutePosition(mockScanPredicate.operatorID, 300, 250); + + const moved = { x: 310, y: 190 }; + expect(service.getJointGraphWrapper().getElementPosition(anchoredID)).toEqual(moved); + // Both the shared-editing position and the persisted position follow. + expect(texeraGraph.sharedModel.elementPositionMap.get(anchoredID)).toEqual(moved); + expect(texeraGraph.getCommentBox(anchoredID).commentBoxPosition).toEqual(moved); + expect(service.getJointGraphWrapper().getElementPosition(floatingID)).toEqual({ x: 400, y: 400 }); + }); + + it("moves an anchored comment box once when it is dragged together with its operator", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 110, y: 40 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.highlightOperators(false, mockScanPredicate.operatorID); + service.highlightCommentBoxes(true, anchoredID); + service.getJointGraphWrapper().setAbsolutePosition(mockScanPredicate.operatorID, 300, 250); + + expect(service.getJointGraphWrapper().getElementPosition(anchoredID)).toEqual({ x: 310, y: 190 }); + }); + + it("keeps the anchor when the comment box itself is dragged, with the new offset", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 110, y: 40 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.highlightCommentBoxes(false, anchoredID); + service.getJointGraphWrapper().setAbsolutePosition(anchoredID, 100, 200); + expect(service.getJointGraphWrapper().getElementPosition(mockScanPredicate.operatorID)).toEqual({ + x: 100, + y: 100, + }); + + service.highlightOperators(false, mockScanPredicate.operatorID); + service.getJointGraphWrapper().setAbsolutePosition(mockScanPredicate.operatorID, 150, 150); + expect(service.getJointGraphWrapper().getElementPosition(anchoredID)).toEqual({ x: 150, y: 250 }); + }); + + it("auto-layout moves anchored comment boxes with their operators, keeping their offsets", () => { + service.addOperator(mockScanPredicate, { x: 0, y: 0 }); + service.addOperator(mockResultPredicate, { x: 0, y: 0 }); + service.addLink(mockScanResultLink); + addComment("commentBox-scan", { x: 10, y: -50 }); + addComment("commentBox-result", { x: 10, y: -50 }); + service.anchorCommentBox("commentBox-scan", mockScanPredicate.operatorID); + service.anchorCommentBox("commentBox-result", mockResultPredicate.operatorID); + + service.autoLayoutWorkflow(); + + const scan = service.getJointGraphWrapper().getElementPosition(mockScanPredicate.operatorID); + const result = service.getJointGraphWrapper().getElementPosition(mockResultPredicate.operatorID); + expect(scan.x).toBeLessThan(result.x); + expect(offsetFrom("commentBox-scan", mockScanPredicate.operatorID)).toEqual({ x: 10, y: -50 }); + expect(offsetFrom("commentBox-result", mockResultPredicate.operatorID)).toEqual({ x: 10, y: -50 }); + // Same offsets, so the comments are spaced exactly as evenly as the operators they annotate. + const scanComment = service.getJointGraphWrapper().getElementPosition("commentBox-scan"); + const resultComment = service.getJointGraphWrapper().getElementPosition("commentBox-result"); + expect(resultComment.x - scanComment.x).toEqual(result.x - scan.x); + expect(resultComment.y - scanComment.y).toEqual(result.y - scan.y); + // Synced and persisted, so a co-editor and a reload see the laid-out positions. + expect(texeraGraph.sharedModel.elementPositionMap.get("commentBox-scan")).toEqual(scanComment); + expect(texeraGraph.getCommentBox("commentBox-scan").commentBoxPosition).toEqual(scanComment); + }); + + it("auto-layout leaves room for anchored comment boxes so they overlap no other operator", () => { + service.addOperator(mockScanPredicate, { x: 0, y: 0 }); + service.addOperator(mockSentimentPredicate, { x: 0, y: 0 }); + service.addOperator(mockResultPredicate, { x: 0, y: 0 }); + service.addLink(mockScanResultLink); + service.addLink(mockSentimentResultLink); + // Far enough above and below scan that, laid out as a bare operator, either box would land on + // sentiment, which shares scan's rank. + addComment("commentBox-above", { x: 0, y: -150 }); + addComment("commentBox-below", { x: 0, y: 150 }); + service.anchorCommentBox("commentBox-above", mockScanPredicate.operatorID); + service.anchorCommentBox("commentBox-below", mockScanPredicate.operatorID); + + service.autoLayoutWorkflow(); + + expect(offsetFrom("commentBox-above", mockScanPredicate.operatorID)).toEqual({ x: 0, y: -150 }); + expect(offsetFrom("commentBox-below", mockScanPredicate.operatorID)).toEqual({ x: 0, y: 150 }); + for (const commentBoxID of ["commentBox-above", "commentBox-below"]) { + for (const operatorID of [mockSentimentPredicate.operatorID, mockResultPredicate.operatorID]) { + expect(overlaps(boundingBox(commentBoxID), boundingBox(operatorID))).toBe(false); + } + } + }); + + it("auto-layout still lays out floating comment boxes and tolerates an anchor to a missing operator", () => { + const workflow: Workflow = { + ...DEFAULT_WORKFLOW, + content: { + operators: [mockScanPredicate], + operatorPositions: { [mockScanPredicate.operatorID]: mockPoint }, + links: [], + commentBoxes: [ + { ...mockCommentBox, commentBoxID: "commentBox-dangling", anchoredOperatorID: "no-such-operator" }, + ], + settings: { dataTransferBatchSize: 100, executionMode: ExecutionMode.PIPELINED }, + }, + }; + service.reloadWorkflow(workflow); + + expect(() => service.autoLayoutWorkflow()).not.toThrow(); + expect(overlaps(boundingBox("commentBox-dangling"), boundingBox(mockScanPredicate.operatorID))).toBe(false); + }); + + it("round-trips the anchor through the saved workflow content", () => { + service.addOperator(mockScanPredicate, mockPoint); + addComment(anchoredID, { x: 0, y: 0 }); + addComment(floatingID, { x: 50, y: 50 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + const content = service.getWorkflowContent(); + expect(content.commentBoxes.find(c => c.commentBoxID === anchoredID)?.anchoredOperatorID).toEqual( + mockScanPredicate.operatorID + ); + expect(content.commentBoxes.find(c => c.commentBoxID === floatingID)?.anchoredOperatorID).toBeUndefined(); + + service.reloadWorkflow({ ...DEFAULT_WORKFLOW, content }); + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toEqual(mockScanPredicate.operatorID); + }); + + it("outlines an anchored comment box, for this editor and on reload, and clears it on detach", () => { + service.addOperator(mockScanPredicate, mockPoint); + addComment(anchoredID, { x: 0, y: 0 }); + const dash = () => jointGraph.getCell(anchoredID).attr("rect/stroke-dasharray"); + expect(dash()).toEqual("none"); + + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + expect(dash()).toEqual("4 2"); + + service.reloadWorkflow({ ...DEFAULT_WORKFLOW, content: service.getWorkflowContent() }); + expect(dash()).toEqual("4 2"); + + service.detachCommentBox(anchoredID); + expect(dash()).toEqual("none"); + }); + + it("undoes an anchor", () => { + service.addOperator(mockScanPredicate, mockPoint); + addComment(anchoredID, { x: 0, y: 0 }); + // Edits within the capture timeout merge into one undo step; keep the anchor a step of its own. + texeraGraph.sharedModel.undoManager.stopCapturing(); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + undoRedo.undoAction(); + + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toBeUndefined(); + }); + }); + it("should reload a workflow, repopulating the graph and clearing the undo/redo stacks", () => { const settings: WorkflowSettings = { dataTransferBatchSize: 250, @@ -685,6 +923,13 @@ describe("WorkflowActionService", () => { expect(service.getCenterPoint()).toEqual({ x: 0, y: 0 }); }); + it("should keep listening to joint commands after computing the top-left of an empty workflow", () => { + service.calculateTopLeftOperatorPosition(); + + // Left off, every later drag would be dropped by handleJointElementDrag and never synced. + expect(undoRedo.listenJointCommand).toBe(true); + }); + it("should toggle the workflow-modification lock and emit each state on the stream", () => { const emitted: boolean[] = []; service.getWorkflowModificationEnabledStream().subscribe(v => emitted.push(v)); diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts index f73b97c89af..2c4667639a9 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts @@ -329,6 +329,10 @@ export class WorkflowActionService { .filter(link => link.source.operatorID === operatorID || link.target.operatorID === operatorID) .forEach(link => this.deleteLinkWithID(link.linkID)); this.texeraGraph.assertOperatorExists(operatorID); + // Comments outlive the operator they annotate; they go back to floating where they are. + this.texeraGraph + .getCommentBoxesAnchoredTo(operatorID) + .forEach(commentBoxID => this.texeraGraph.setCommentBoxAnchor(commentBoxID, undefined)); this.texeraGraph.deleteOperator(operatorID); if (this.texeraGraph.sharedModel.elementPositionMap.has(operatorID)) this.texeraGraph.sharedModel.elementPositionMap.delete(operatorID); @@ -435,6 +439,36 @@ export class WorkflowActionService { this.texeraGraph.deleteCommentBox(commentBoxID); } + /** + * Anchors a comment box to an operator, so that it keeps its current offset from the operator + * whenever the operator is dragged or auto-layout moves it. Replaces any previous anchor. + * @param commentBoxID + * @param operatorID + */ + public anchorCommentBox(commentBoxID: string, operatorID: string): void { + this.texeraGraph.setCommentBoxAnchor(commentBoxID, operatorID); + } + + /** + * Detaches a comment box from the operator it is anchored to, so it floats again. A no-op on a + * comment box that already floats. + * @param commentBoxID + */ + public detachCommentBox(commentBoxID: string): void { + this.texeraGraph.setCommentBoxAnchor(commentBoxID, undefined); + } + + /** + * Writes a comment box's current JointJS position to the shared model: elementPositionMap + * syncs it to co-editors, commentBoxPosition persists it. + * @param commentBoxID + */ + private syncCommentBoxPosition(commentBoxID: string): void { + const position = this.jointGraphWrapper.getElementPosition(commentBoxID); + this.texeraGraph.sharedModel.elementPositionMap.set(commentBoxID, position); + this.texeraGraph.sharedModel.commentBoxMap.get(commentBoxID)?.set("commentBoxPosition", position); + } + /** * Deletes given operators and links from the workflow graph. * @param operatorIDs @@ -464,7 +498,18 @@ export class WorkflowActionService { // This also changes element positions, but we handle this separately. this.texeraGraph.bundleActions(() => { this.undoRedoService.setListenJointCommand(false); - this.jointGraphWrapper.autoLayoutJoint(); + const anchoredCommentBoxIDs = new Map(); + for (const commentBox of this.texeraGraph.getAllCommentBoxes()) { + const operatorID = commentBox.anchoredOperatorID; + // An anchor to an operator that is gone (e.g. from an older save) is treated as floating. + if (operatorID !== undefined && this.texeraGraph.hasOperator(operatorID)) { + anchoredCommentBoxIDs.set(operatorID, [ + ...(anchoredCommentBoxIDs.get(operatorID) ?? []), + commentBox.commentBoxID, + ]); + } + } + this.jointGraphWrapper.autoLayoutJoint(anchoredCommentBoxIDs); for (const operator of this.texeraGraph.getAllOperators()) { const operatorID = operator.operatorID; const newPosition = this.jointGraphWrapper.getElementPosition(operatorID); @@ -473,11 +518,7 @@ export class WorkflowActionService { } } for (const commentBox of this.texeraGraph.getAllCommentBoxes()) { - const commentBoxID = commentBox.commentBoxID; - const newPosition = this.jointGraphWrapper.getElementPosition(commentBoxID); - if (this.texeraGraph.sharedModel.elementPositionMap.get(commentBoxID) !== newPosition) { - this.texeraGraph.sharedModel.elementPositionMap.set(commentBoxID, newPosition); - } + this.syncCommentBoxPosition(commentBox.commentBoxID); } this.undoRedoService.setListenJointCommand(true); }); @@ -488,9 +529,10 @@ export class WorkflowActionService { */ public calculateTopLeftOperatorPosition(): void { this.texeraGraph.bundleActions(() => { - this.undoRedoService.setListenJointCommand(false); const allOperators = this.getTexeraGraph().getAllOperators(); + // Checked before listening is turned off, so returning early cannot leave it off. if (allOperators.length === 0) return; + this.undoRedoService.setListenJointCommand(false); let minX = Infinity; let minY = Infinity; @@ -1217,16 +1259,6 @@ export class WorkflowActionService { const offsetY = movedElement.newPosition.y - movedElement.oldPosition.y; this.jointGraphWrapper.setListenPositionChange(false); this.undoRedoService.setListenJointCommand(false); - // Persistence and shared-editing syncing for comment boxes have different interfaces. - // Setting positions inside commentBoxes here only for persistence. - // Syncing uses elementPositionMap. - selectedElements - .filter(elementID => elementID.includes("commentBox")) - .forEach(elementID => { - this.texeraGraph.sharedModel.commentBoxMap - .get(elementID) - ?.set("commentBoxPosition", this.jointGraphWrapper.getElementPosition(elementID)); - }); // Move other highlighted operators. selectedElements .filter(elementID => elementID !== movedElement.elementID) @@ -1237,6 +1269,25 @@ export class WorkflowActionService { this.jointGraphWrapper.getElementPosition(elementID) ); }); + // Comment boxes anchored to a moved operator follow it, unless selected (then moved above). + selectedElements + .filter(elementID => this.texeraGraph.hasOperator(elementID)) + .flatMap(operatorID => this.texeraGraph.getCommentBoxesAnchoredTo(operatorID)) + .filter(commentBoxID => !selectedElements.includes(commentBoxID)) + .forEach(commentBoxID => { + this.jointGraphWrapper.setElementPosition(commentBoxID, offsetX, offsetY); + this.syncCommentBoxPosition(commentBoxID); + }); + // Persistence and shared-editing syncing for comment boxes have different interfaces. + // Setting positions inside commentBoxes here only for persistence, once every box has moved. + // Syncing uses elementPositionMap. + selectedElements + .filter(elementID => elementID.includes("commentBox")) + .forEach(elementID => { + this.texeraGraph.sharedModel.commentBoxMap + .get(elementID) + ?.set("commentBoxPosition", this.jointGraphWrapper.getElementPosition(elementID)); + }); this.jointGraphWrapper.setListenPositionChange(true); this.undoRedoService.setListenJointCommand(true); } diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts index a0e5deeb87e..46f165b2cfa 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts @@ -369,6 +369,35 @@ export class WorkflowGraph { this.sharedModel.operatorIDMap.delete(operatorID); } + /** + * Anchors the comment box to an operator, replacing any previous anchor, or detaches it (making it + * float) when operatorID is undefined. + * @param commentBoxID + * @param operatorID + */ + public setCommentBoxAnchor(commentBoxID: string, operatorID: string | undefined): void { + this.assertCommentBoxExists(commentBoxID); + const commentBox = this.sharedModel.commentBoxMap.get(commentBoxID) as YType; + if (operatorID === undefined) { + if (commentBox.has("anchoredOperatorID")) { + (commentBox as unknown as Y.Map).delete("anchoredOperatorID"); + } + return; + } + this.assertOperatorExists(operatorID); + commentBox.set("anchoredOperatorID", new Y.Text(operatorID)); + } + + /** + * Returns the IDs of the comment boxes anchored to the given operator. + * @param operatorID + */ + public getCommentBoxesAnchoredTo(operatorID: string): string[] { + return this.getAllCommentBoxes() + .filter(commentBox => commentBox.anchoredOperatorID === operatorID) + .map(commentBox => commentBox.commentBoxID); + } + /** * Deletes the comment box from the model's {@link commentBoxMap}. * @param commentBoxID diff --git a/frontend/src/app/workspace/types/workflow-common.interface.ts b/frontend/src/app/workspace/types/workflow-common.interface.ts index 3fb3aaa3d4b..37e6c1cf564 100644 --- a/frontend/src/app/workspace/types/workflow-common.interface.ts +++ b/frontend/src/app/workspace/types/workflow-common.interface.ts @@ -90,6 +90,11 @@ export interface CommentBox { commentBoxID: string; comments: Comment[]; commentBoxPosition: Point; + /** + * The operator this comment box is anchored to, if any. An anchored box keeps its offset from the + * operator when the operator is dragged or auto-layout moves it; without one, the box floats. + */ + anchoredOperatorID?: string; } export interface OperatorLink From 2a154ff62ef039867581e224e038b3bee361660f Mon Sep 17 00:00:00 2001 From: Suryaa Charan <122703005+sshiv012@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:20:09 -0800 Subject: [PATCH 2/5] feat(frontend): drag comment boxes onto operators to anchor them Anchoring no longer needs a multi-selection and a context-menu item: - Dragging a comment box next to an operator (within 40px) anchors it; the operator it will anchor to is outlined while dragging. Dropping an anchored box more than 160px from its operator detaches it; in between, a nudge keeps the anchor. - "add comment" on an operator's context menu adds a comment box beside it, already anchored, as one undoable action. - An anchored comment box draws a dashed connector line to the nearest edge of its operator, redrawn whenever either moves, including moves from auto-layout and co-editors. The "anchor to operator" / "detach from operator" menu items stay as a fallback. Co-Authored-By: Claude Opus 5.5 --- .../context-menu/context-menu.component.html | 10 + .../context-menu.component.spec.ts | 26 +++ .../context-menu/context-menu.component.ts | 18 ++ .../workflow-editor.component.ts | 70 ++++++- .../service/joint-ui/joint-ui.service.ts | 33 ++++ .../model/shared-model-change-handler.ts | 35 ++++ .../model/workflow-action.service.spec.ts | 172 ++++++++++++++++++ .../model/workflow-action.service.ts | 81 +++++++++ 8 files changed, 444 insertions(+), 1 deletion(-) diff --git a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.html b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.html index 1dbc89adc13..b208b578c45 100644 --- a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.html +++ b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.html @@ -155,6 +155,16 @@ >delete
  • +
  • + add comment +
  • { deleteLinkWithID: vi.fn(), anchorCommentBox: vi.fn(), detachCommentBox: vi.fn(), + addCommentBoxToOperator: vi.fn(), }; workflowActionServiceSpy.getJointGraphWrapper.mockReturnValue(jointGraphWrapperSpy); workflowActionServiceSpy.getWorkflowModificationEnabledStream.mockReturnValue(of(true)); @@ -804,6 +805,7 @@ describe("ContextMenuComponent", () => { const norm = (s: string | null) => (s ?? "").replace(/\s+/g, " ").trim().toLowerCase(); const ANCHOR = "anchor to operator"; const DETACH = "detach from operator"; + const ADD_COMMENT = "add comment"; let anchors: Record; function renderedLabels(): string[] { @@ -895,6 +897,30 @@ describe("ContextMenuComponent", () => { expect(renderedLabels()).not.toContain(DETACH); expect(workflowActionService.getTexeraGraph().getCommentBox).not.toHaveBeenCalledWith("box-deleted"); }); + + it("adds a comment box to the one selected operator", () => { + select(["op1"], []); + + clickItem(ADD_COMMENT); + + expect(workflowActionService.addCommentBoxToOperator).toHaveBeenCalledTimes(1); + expect(workflowActionService.addCommentBoxToOperator).toHaveBeenCalledWith("op1"); + }); + + it("offers adding a comment only for exactly one selected operator and nothing else", () => { + select(["op1", "op2"], []); + expect(renderedLabels()).not.toContain(ADD_COMMENT); + select(["op1"], ["box-floating"]); + expect(renderedLabels()).not.toContain(ADD_COMMENT); + select([], ["box-floating"]); + expect(renderedLabels()).not.toContain(ADD_COMMENT); + }); + + it("offers adding a comment only while the workflow can be modified", () => { + component.isWorkflowModifiable = false; + select(["op1"], []); + expect(renderedLabels()).not.toContain(ADD_COMMENT); + }); }); }); diff --git a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts index 60d13ebdfd0..107c41aee97 100644 --- a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts +++ b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts @@ -173,6 +173,24 @@ export class ContextMenuComponent { }); } + /** A comment box is added to exactly one selected operator, with nothing else selected. */ + public canAddCommentBoxToOperator(): boolean { + return ( + this.canModify && + this.highlightedOperatorIds.length === 1 && + this.highlightedCommentBoxIds.length === 0 && + !this.hasHighlightedLinks() + ); + } + + /** Adds a comment box beside the selected operator, anchored to it. */ + public onAddCommentBoxToOperator(): void { + if (!this.canAddCommentBoxToOperator()) { + return; + } + this.workflowActionService.addCommentBoxToOperator(this.highlightedOperatorIds[0]); + } + /** Anchoring takes the selected comment boxes and exactly one selected operator to anchor them to. */ public canAnchorCommentBoxes(): boolean { return ( diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts index 1fac6beeba3..c240c985f8e 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts @@ -36,7 +36,7 @@ import { rawMetricForView, } from "../../service/heatmap/heatmap-scoring"; import { ExecutionState, OperatorState } from "../../types/execute-workflow.interface"; -import { LogicalPort, OperatorLink, OperatorPredicate } from "../../types/workflow-common.interface"; +import { LogicalPort, OperatorLink, OperatorPredicate, Point } from "../../types/workflow-common.interface"; import { auditTime, filter, map, takeUntil, withLatestFrom } from "rxjs/operators"; import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy"; import { UndoRedoService } from "../../service/undo-redo/undo-redo.service"; @@ -244,6 +244,7 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy this.handlePortClick(); this.handlePaperPan(); this.handleOperatorSelectionEvents(); + this.handleCommentBoxDragToAnchor(); this.handlePortHighlightEvent(); this.registerPortDisplayNameChangeHandler(); this.handleOperatorStatusUpdate(); @@ -1263,6 +1264,73 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy }); } + /** + * Anchors a comment box by dragging it: while a comment box is dragged on its own, the operator it + * would anchor to is outlined, and dropping it there anchors it (see anchorCommentBoxOnDrop, which + * also detaches a box dropped far from its operator). Dragging it along with operators changes nothing. + */ + private handleCommentBoxDragToAnchor(): void { + const TARGET_HIGHLIGHT_ID = "commentBoxAnchorTarget"; + let drag: { commentBoxID: string; start: Point } | undefined; + let targetOperatorID: string | undefined; + const setTarget = (operatorID: string | undefined) => { + if (operatorID === targetOperatorID) { + return; + } + const previousView = targetOperatorID === undefined ? undefined : this.paper.findViewByModel(targetOperatorID); + if (previousView) { + joint.highlighters.mask.remove(previousView, TARGET_HIGHLIGHT_ID); + } + const nextView = operatorID === undefined ? undefined : this.paper.findViewByModel(operatorID); + if (nextView) { + joint.highlighters.mask.add(nextView, "rect.body", TARGET_HIGHLIGHT_ID, { + padding: 6, + rx: 5, + ry: 5, + attrs: { "stroke-width": 2, stroke: "#1890FF", "stroke-dasharray": "4 2" }, + }); + } + targetOperatorID = operatorID; + }; + const isSoloCommentBoxDrag = (elementID: string) => + this.interactive && + this.workflowActionService.getTexeraGraph().hasCommentBox(elementID) && + this.wrapper.getCurrentHighlightedOperatorIDs().length === 0; + + fromJointPaperEvent(this.paper, "element:pointerdown") + .pipe(untilDestroyed(this)) + .subscribe(event => { + const elementID = event[0].model.id.toString(); + drag = isSoloCommentBoxDrag(elementID) + ? { commentBoxID: elementID, start: this.wrapper.getElementPosition(elementID) } + : undefined; + }); + + fromJointPaperEvent(this.paper, "element:pointermove") + .pipe( + filter(() => drag !== undefined), + untilDestroyed(this) + ) + .subscribe(() => setTarget(this.workflowActionService.findCommentBoxAnchorTarget(drag!.commentBoxID))); + + fromJointPaperEvent(this.paper, "element:pointerup") + .pipe(untilDestroyed(this)) + .subscribe(() => { + setTarget(undefined); + const finished = drag; + drag = undefined; + if ( + finished === undefined || + !isSoloCommentBoxDrag(finished.commentBoxID) || + _.isEqual(this.wrapper.getElementPosition(finished.commentBoxID), finished.start) + ) { + // A click, not a drag: leave the anchor alone. + return; + } + this.workflowActionService.anchorCommentBoxOnDrop(finished.commentBoxID); + }); + } + /** * Handles the event where the Delete button is clicked for a Link, * and call workflowAction to delete the corresponding link. diff --git a/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts b/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts index 05398a3e6a1..544ea96ed6a 100644 --- a/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts +++ b/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts @@ -181,6 +181,7 @@ class TexeraCustomJointElement extends joint.shapes.devs.Model { class TexeraCustomCommentElement extends joint.shapes.devs.Model { markup = ` + ${deleteButtonSVG} @@ -611,6 +612,31 @@ export class JointUIService { ? { stroke: "#1890FF", "stroke-width": 2, "stroke-dasharray": "4 2" } : { stroke: "#CED4D9", "stroke-width": 0, "stroke-dasharray": "none" }; } + + /** + * The line that ties an anchored comment box to its operator, in the comment box's own coordinates: + * from the comment box's center to the nearest point on the operator's edge. Hidden for a floating one. + * @param commentBox the comment box's bounding box + * @param operator the bounding box of the operator it is anchored to, undefined if it floats + */ + public static getCommentBoxConnectorAttrs( + commentBox: joint.g.Rect, + operator: joint.g.Rect | undefined + ): joint.attributes.SVGAttributes { + if (operator === undefined) { + return { display: "none" }; + } + const centerX = commentBox.x + commentBox.width / 2; + const centerY = commentBox.y + commentBox.height / 2; + const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max); + return { + display: "inline", + x1: commentBox.width / 2, + y1: commentBox.height / 2, + x2: clamp(centerX, operator.x, operator.x + operator.width) - commentBox.x, + y2: clamp(centerY, operator.y, operator.y + operator.height) - commentBox.y, + }; + } /** * This function converts a Texera source and target OperatorPort to * a JointJS link cell that could be added to the JointJS. @@ -1049,6 +1075,13 @@ export class JointUIService { fill: "#D8656A", event: "element:delete", }, + ".anchor-connector": { + display: "none", + stroke: "#1890FF", + "stroke-width": 1.5, + "stroke-dasharray": "4 3", + "pointer-events": "none", + }, }; } diff --git a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts index e3f7438328a..2b944cf9218 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts @@ -57,6 +57,7 @@ export class SharedModelChangeHandler { this.handleCommentBoxAddAndDelete(); this.handleOperatorDeep(); this.handleCommentBoxDeep(); + this.handleCommentBoxConnectors(); this.texeraGraph.newYDocLoadedSubject.subscribe(_ => { this.handleOperatorAddAndDelete(); this.handleLinkAddAndDelete(); @@ -463,6 +464,39 @@ export class SharedModelChangeHandler { this.texeraGraph.portAddedOrDeletedSubject.next({ newOperator: operator }); } + /** + * Keeps each anchored comment box's connector line on its operator: redrawn whenever the comment box + * or the operator is added to the joint graph or moves, wherever the move came from. + * Listens on the joint graph itself, which outlives every shared model, so it is registered once. + * @private + */ + private handleCommentBoxConnectors(): void { + this.jointGraph.on("add change:position", (cell: joint.dia.Cell) => { + const elementID = cell.id.toString(); + if (this.texeraGraph.hasCommentBox(elementID)) { + this.refreshCommentBoxConnector(elementID); + } else if (this.texeraGraph.hasOperator(elementID)) { + this.texeraGraph + .getCommentBoxesAnchoredTo(elementID) + .forEach(commentBoxID => this.refreshCommentBoxConnector(commentBoxID)); + } + }); + } + + private refreshCommentBoxConnector(commentBoxID: string): void { + const commentElement = this.jointGraph.getCell(commentBoxID) as joint.dia.Element | undefined; + if (commentElement === undefined) { + return; + } + const operatorID = this.texeraGraph.getCommentBox(commentBoxID).anchoredOperatorID; + const operatorElement = + operatorID === undefined ? undefined : (this.jointGraph.getCell(operatorID) as joint.dia.Element | undefined); + commentElement.attr( + ".anchor-connector", + JointUIService.getCommentBoxConnectorAttrs(commentElement.getBBox(), operatorElement?.getBBox()) + ); + } + /** * Syncs changes that are on nested-structures of comment boxes, including changes of: * - adding comments @@ -480,6 +514,7 @@ export class SharedModelChangeHandler { this.jointGraph .getCell(commentBox.commentBoxID) ?.attr("rect", JointUIService.getCommentBoxAnchorAttrs(commentBox.anchoredOperatorID !== undefined)); + this.refreshCommentBoxConnector(commentBox.commentBoxID); } if (event.path.length === 2 && event.path[event.path.length - 1] === "comments") { const addedComments = Array.from(event.changes.added.values()); diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts index 865dd61ad5b..edefce1c9a2 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts @@ -603,6 +603,178 @@ describe("WorkflowActionService", () => { expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toBeUndefined(); }); + + describe("on drop", () => { + // Operators are 60x60 and comment boxes 32x32; the scan operator spans x 100..160, y 100..160. + beforeEach(() => service.addOperator(mockScanPredicate, { x: 100, y: 100 })); + + it("anchors a floating comment box dropped next to an operator", () => { + addComment(floatingID, { x: 170, y: 100 }); + + expect(service.findCommentBoxAnchorTarget(floatingID)).toEqual(mockScanPredicate.operatorID); + service.anchorCommentBoxOnDrop(floatingID); + + expect(texeraGraph.getCommentBox(floatingID).anchoredOperatorID).toEqual(mockScanPredicate.operatorID); + }); + + it("leaves a comment box dropped away from every operator floating", () => { + addComment(floatingID, { x: 400, y: 400 }); + + expect(service.findCommentBoxAnchorTarget(floatingID)).toBeUndefined(); + service.anchorCommentBoxOnDrop(floatingID); + + expect(texeraGraph.getCommentBox(floatingID).anchoredOperatorID).toBeUndefined(); + }); + + it("anchors to the nearest operator when several are in reach", () => { + service.addOperator(mockResultPredicate, { x: 200, y: 100 }); + // 1px from the scan operator's right edge, 7px from the result operator's left edge. + addComment(floatingID, { x: 161, y: 110 }); + + service.anchorCommentBoxOnDrop(floatingID); + + expect(texeraGraph.getCommentBox(floatingID).anchoredOperatorID).toEqual(mockScanPredicate.operatorID); + }); + + it("re-anchors an anchored comment box dropped next to another operator", () => { + service.addOperator(mockResultPredicate, { x: 500, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.getJointGraphWrapper().setAbsolutePosition(anchoredID, 570, 100); + service.anchorCommentBoxOnDrop(anchoredID); + + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toEqual(mockResultPredicate.operatorID); + }); + + it("keeps the anchor of a comment box dropped a little beyond snapping reach", () => { + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + // 100px from the operator: too far to snap a floating box on, too near to pull an anchored one off. + service.getJointGraphWrapper().setAbsolutePosition(anchoredID, 260, 100); + service.anchorCommentBoxOnDrop(anchoredID); + + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toEqual(mockScanPredicate.operatorID); + }); + + it("detaches an anchored comment box dropped far from its operator", () => { + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.getJointGraphWrapper().setAbsolutePosition(anchoredID, 600, 600); + service.anchorCommentBoxOnDrop(anchoredID); + + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toBeUndefined(); + }); + }); + + describe("adding a comment box to an operator", () => { + it("adds a comment box beside the operator, already anchored to it", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + + const commentBoxID = service.addCommentBoxToOperator(mockScanPredicate.operatorID); + + expect(texeraGraph.getCommentBox(commentBoxID).anchoredOperatorID).toEqual(mockScanPredicate.operatorID); + expect(overlaps(boundingBox(commentBoxID), boundingBox(mockScanPredicate.operatorID))).toBe(false); + // Within snapping reach, so a nudge of the new box does not pull it off its operator. + expect(service.findCommentBoxAnchorTarget(commentBoxID)).toEqual(mockScanPredicate.operatorID); + expect(texeraGraph.getCommentBox(commentBoxID).commentBoxPosition).toEqual( + service.getJointGraphWrapper().getElementPosition(commentBoxID) + ); + }); + + it("undoes the added comment box in one step", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + texeraGraph.sharedModel.undoManager.stopCapturing(); + + const commentBoxID = service.addCommentBoxToOperator(mockScanPredicate.operatorID); + undoRedo.undoAction(); + + expect(texeraGraph.hasCommentBox(commentBoxID)).toBe(false); + expect(texeraGraph.hasOperator(mockScanPredicate.operatorID)).toBe(true); + }); + + it("rejects an operator that does not exist", () => { + expect(() => service.addCommentBoxToOperator("no-such-operator")).toThrowError(/no-such-operator/); + expect(texeraGraph.getAllCommentBoxes()).toEqual([]); + }); + }); + + describe("connector line", () => { + const connector = (commentBoxID: string) => + (jointGraph.getCell(commentBoxID) as joint.dia.Element).attr(".anchor-connector"); + + it("runs from an anchored comment box's center to the nearest edge of its operator", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + expect(connector(anchoredID).display).toEqual("none"); + + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + // In the comment box's own coordinates: its center (16, 16) to the operator's right edge at x 160. + expect(connector(anchoredID)).toEqual(expect.objectContaining({ display: "inline", x1: 16, y1: 16 })); + expect(connector(anchoredID)).toEqual(expect.objectContaining({ x2: -10, y2: 16 })); + }); + + it("follows the comment box when it moves", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.highlightCommentBoxes(false, anchoredID); + service.getJointGraphWrapper().setAbsolutePosition(anchoredID, 100, 200); + + // Center (116, 216) now sits below the operator, whose bottom edge is at y 160. + expect(connector(anchoredID)).toEqual(expect.objectContaining({ x2: 16, y2: -40 })); + }); + + it("follows the operator when it moves on its own", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + // Unselected, so the comment box stays put while the operator moves, as when a co-editor drags it. + service.getJointGraphWrapper().setAbsolutePosition(mockScanPredicate.operatorID, 100, 300); + + // Center (186, 116) now sits above the operator, whose top edge is at y 300, right edge at x 160. + expect(connector(anchoredID)).toEqual(expect.objectContaining({ x2: -10, y2: 200 })); + }); + + it("is hidden again once the comment box is detached", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.detachCommentBox(anchoredID); + + expect(connector(anchoredID).display).toEqual("none"); + }); + + it("is drawn for anchored comment boxes of a reloaded workflow", () => { + const workflow: Workflow = { + ...DEFAULT_WORKFLOW, + content: { + settings: service.getWorkflowSettings(), + operators: [mockScanPredicate], + operatorPositions: { [mockScanPredicate.operatorID]: { x: 100, y: 100 } }, + links: [], + commentBoxes: [ + { + ...mockCommentBox, + commentBoxID: anchoredID, + commentBoxPosition: { x: 170, y: 100 }, + anchoredOperatorID: mockScanPredicate.operatorID, + }, + ], + }, + }; + + service.reloadWorkflow(workflow); + + expect(connector(anchoredID)).toEqual(expect.objectContaining({ display: "inline", x2: -10, y2: 16 })); + }); + }); }); it("should reload a workflow, repopulating the graph and clearing the undo/redo stacks", () => { diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts index 2c4667639a9..8da2026f895 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts @@ -72,6 +72,20 @@ export const DEFAULT_WORKFLOW = { readonly: false, }; +/** How close (px, edge to edge) a dropped comment box has to be to an operator to anchor to it. */ +export const COMMENT_BOX_SNAP_DISTANCE = 40; +/** How far (px, edge to edge) an anchored comment box has to be dropped from its operator to detach. */ +export const COMMENT_BOX_DETACH_DISTANCE = 160; +/** The gap between an operator and a comment box added to it. */ +const COMMENT_BOX_GAP = 12; + +/** The shortest distance between two boxes, 0 when they touch or overlap. */ +function distanceBetween(a: joint.g.Rect, b: joint.g.Rect): number { + const dx = Math.max(0, a.x - (b.x + b.width), b.x - (a.x + a.width)); + const dy = Math.max(0, a.y - (b.y + b.height), b.y - (a.y + a.height)); + return Math.hypot(dx, dy); +} + /** * * WorkflowActionService exposes functions (actions) to modify the workflow graph model of Texera, @@ -458,6 +472,73 @@ export class WorkflowActionService { this.texeraGraph.setCommentBoxAnchor(commentBoxID, undefined); } + /** + * The operator a comment box would anchor to if it were dropped where it is now: the nearest + * operator within COMMENT_BOX_SNAP_DISTANCE of it, or undefined if none is that close. + * @param commentBoxID + */ + public findCommentBoxAnchorTarget(commentBoxID: string): string | undefined { + const commentBoxBBox = this.getElementBBox(commentBoxID); + let nearest: { operatorID: string; distance: number } | undefined; + for (const operator of this.texeraGraph.getAllOperators()) { + const distance = distanceBetween(commentBoxBBox, this.getElementBBox(operator.operatorID)); + if (distance <= COMMENT_BOX_SNAP_DISTANCE && (nearest === undefined || distance < nearest.distance)) { + nearest = { operatorID: operator.operatorID, distance }; + } + } + return nearest?.operatorID; + } + + /** + * Settles a comment box's anchor after the user drops it: dropped next to an operator, it anchors to + * that operator; dropped beyond COMMENT_BOX_DETACH_DISTANCE of the operator it is anchored + * to, it detaches. In between it keeps whatever anchor it had, so a small nudge changes nothing. + * @param commentBoxID + */ + public anchorCommentBoxOnDrop(commentBoxID: string): void { + const targetOperatorID = this.findCommentBoxAnchorTarget(commentBoxID); + const anchoredOperatorID = this.texeraGraph.getCommentBox(commentBoxID).anchoredOperatorID; + if (targetOperatorID !== undefined) { + if (targetOperatorID !== anchoredOperatorID) { + this.anchorCommentBox(commentBoxID, targetOperatorID); + } + } else if ( + anchoredOperatorID !== undefined && + (!this.texeraGraph.hasOperator(anchoredOperatorID) || + distanceBetween(this.getElementBBox(commentBoxID), this.getElementBBox(anchoredOperatorID)) > + COMMENT_BOX_DETACH_DISTANCE) + ) { + this.detachCommentBox(commentBoxID); + } + } + + /** + * Adds a new comment box beside an operator, already anchored to it, as a single undoable action. + * @param operatorID + * @returns the ID of the new comment box + */ + public addCommentBoxToOperator(operatorID: string): string { + this.texeraGraph.assertOperatorExists(operatorID); + const operatorPosition = this.jointGraphWrapper.getElementPosition(operatorID); + const commentBox: CommentBox = { + ...this.workflowUtilService.getNewCommentBox(), + // Right of the operator's top-right corner, clear of its delete button. + commentBoxPosition: { + x: operatorPosition.x + JointUIService.DEFAULT_OPERATOR_WIDTH + COMMENT_BOX_GAP, + y: operatorPosition.y - JointUIService.DEFAULT_COMMENT_HEIGHT / 2, + }, + }; + this.texeraGraph.bundleActions(() => { + this.addCommentBox(commentBox); + this.anchorCommentBox(commentBox.commentBoxID, operatorID); + }); + return commentBox.commentBoxID; + } + + private getElementBBox(elementID: string): joint.g.Rect { + return (this.jointGraph.getCell(elementID) as joint.dia.Element).getBBox(); + } + /** * Writes a comment box's current JointJS position to the shared model: elementPositionMap * syncs it to co-editors, commentBoxPosition persists it. From 567c0445104d855d48ed4bee1bb53584c0ea0dd3 Mon Sep 17 00:00:00 2001 From: Suryaa Charan <122703005+sshiv012@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:02:58 -0800 Subject: [PATCH 3/5] fix(frontend): keep comment anchors through paste, multi-drag and co-editing - Paste re-anchors a comment to the pasted copy of its operator at the same offset, and pastes it floating when the operator wasn't copied. - Dragging several selected comment boxes anchors or detaches each one by where it lands, in a single undo step. - Apply "add" events from the shared position map so a comment box's first move reaches co-editors. - Add pointer-event, paste, co-editor convergence, boundary and tie-break tests. Co-Authored-By: Claude Opus 5.5 --- .../workflow-editor.component.spec.ts | 103 +++++++++++ .../workflow-editor.component.ts | 102 ++++++----- .../operator-menu.service.spec.ts | 49 ++++++ .../operator-menu/operator-menu.service.ts | 29 +++- .../model/shared-model-change-handler.ts | 4 +- .../model/workflow-action.service.spec.ts | 161 +++++++++++++++++- .../model/workflow-action.service.ts | 28 ++- 7 files changed, 424 insertions(+), 52 deletions(-) diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts index 3b419e683a3..d5ec55c64c6 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts @@ -1257,6 +1257,109 @@ describe("WorkflowEditorComponent", () => { }); }); + /** + * Drag-to-anchor through the paper's own pointer events, in the order JointJS fires them for a + * drag: cell:pointerdown (selection) and element:pointerdown, the element moving (which drags the + * rest of the selection along), element:pointermove, element:pointerup. + */ + describe("dragging comment boxes onto operators", () => { + // The scan operator spans x 100..160, y 100..160; comment boxes are 32x32. + const operatorID = mockScanPredicate.operatorID; + + function addComment(commentBoxID: string, x: number, y: number): void { + workflowActionService.addCommentBox({ ...mockCommentBox, commentBoxID, commentBoxPosition: { x, y } }); + } + + function anchorOf(commentBoxID: string): string | undefined { + return workflowActionService.getTexeraGraph().getCommentBox(commentBoxID).anchoredOperatorID; + } + + /** Presses on an element, drags it to (x, y), and returns a function that releases it. */ + function pressAndDrag(elementID: string, x: number, y: number): () => void { + const view = component.paper.findViewByModel(elementID); + const event = new MouseEvent("mousedown"); + (component.paper as any).trigger("cell:pointerdown", view, event, 0, 0); + (component.paper as any).trigger("element:pointerdown", view, event, 0, 0); + workflowActionService.getJointGraphWrapper().setAbsolutePosition(elementID, x, y); + (component.paper as any).trigger("element:pointermove", view, new MouseEvent("mousemove"), x, y); + return () => (component.paper as any).trigger("element:pointerup", view, new MouseEvent("mouseup"), x, y); + } + + function targetOutlined(): boolean { + const view = component.paper.findViewByModel(operatorID); + return joint.highlighters.mask.get(view).some(highlighter => highlighter.id === "commentBoxAnchorTarget"); + } + + beforeEach(() => workflowActionService.addOperator(mockScanPredicate, { x: 100, y: 100 })); + + it("anchors a comment box dragged on its own next to an operator", () => { + addComment("box-a", 400, 400); + + pressAndDrag("box-a", 170, 100)(); + + expect(anchorOf("box-a")).toEqual(operatorID); + }); + + it("outlines the operator a dragged comment box would anchor to until it is dropped", () => { + addComment("box-a", 400, 400); + + const release = pressAndDrag("box-a", 170, 100); + expect(targetOutlined()).toBe(true); + release(); + + expect(targetOutlined()).toBe(false); + }); + + it("anchors every comment box dragged together, each by where it lands", () => { + addComment("box-a", 400, 100); + addComment("box-b", 400, 130); + addComment("box-c", 400, 400); + workflowActionService.highlightCommentBoxes(true, "box-a", "box-b", "box-c"); + + // a lands 10px right of the operator, b lands beside it too, c stays far below. + pressAndDrag("box-a", 170, 100)(); + + expect(anchorOf("box-a")).toEqual(operatorID); + expect(anchorOf("box-b")).toEqual(operatorID); + expect(anchorOf("box-c")).toBeUndefined(); + }); + + it("detaches every anchored comment box dragged together far away", () => { + addComment("box-a", 170, 100); + addComment("box-b", 170, 130); + workflowActionService.anchorCommentBox("box-a", operatorID); + workflowActionService.anchorCommentBox("box-b", operatorID); + workflowActionService.highlightCommentBoxes(true, "box-a", "box-b"); + + pressAndDrag("box-a", 700, 700)(); + + expect(anchorOf("box-a")).toBeUndefined(); + expect(anchorOf("box-b")).toBeUndefined(); + }); + + it("leaves anchors alone when comment boxes are dragged along with an operator", () => { + addComment("box-a", 400, 400); + workflowActionService.highlightOperators(false, operatorID); + workflowActionService.highlightCommentBoxes(true, "box-a"); + + // Dropped right beside the operator, but as part of a selection that holds it. + pressAndDrag("box-a", 170, 100)(); + + expect(anchorOf("box-a")).toBeUndefined(); + expect(targetOutlined()).toBe(false); + }); + + it("leaves the anchor alone on a click that does not move the comment box", () => { + // Anchored far from its operator (as the anchor menu item allows), then only clicked. + addComment("box-a", 700, 700); + workflowActionService.anchorCommentBox("box-a", operatorID); + + pressAndDrag("box-a", 700, 700)(); + + expect(anchorOf("box-a")).toEqual(operatorID); + }); + }); + /** * The editor's non-rendering logic: connection validation, the clipboard * handlers, and the delete / select-all paths that the keyboard tests above diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts index c240c985f8e..66ceb24fefb 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts @@ -37,6 +37,7 @@ import { } from "../../service/heatmap/heatmap-scoring"; import { ExecutionState, OperatorState } from "../../types/execute-workflow.interface"; import { LogicalPort, OperatorLink, OperatorPredicate, Point } from "../../types/workflow-common.interface"; +import { isDefined } from "../../../common/util/predicate"; import { auditTime, filter, map, takeUntil, withLatestFrom } from "rxjs/operators"; import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy"; import { UndoRedoService } from "../../service/undo-redo/undo-redo.service"; @@ -1265,45 +1266,54 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy } /** - * Anchors a comment box by dragging it: while a comment box is dragged on its own, the operator it - * would anchor to is outlined, and dropping it there anchors it (see anchorCommentBoxOnDrop, which - * also detaches a box dropped far from its operator). Dragging it along with operators changes nothing. + * Anchors comment boxes by dragging them: while comment boxes are dragged without any operator, the + * operators they would anchor to are outlined, and on drop each dragged box settles its own anchor + * by where it landed (see anchorCommentBoxOnDrop, which also detaches a box dropped far from its + * operator). Dragging them along with operators changes nothing. */ private handleCommentBoxDragToAnchor(): void { const TARGET_HIGHLIGHT_ID = "commentBoxAnchorTarget"; - let drag: { commentBoxID: string; start: Point } | undefined; - let targetOperatorID: string | undefined; - const setTarget = (operatorID: string | undefined) => { - if (operatorID === targetOperatorID) { - return; - } - const previousView = targetOperatorID === undefined ? undefined : this.paper.findViewByModel(targetOperatorID); - if (previousView) { - joint.highlighters.mask.remove(previousView, TARGET_HIGHLIGHT_ID); - } - const nextView = operatorID === undefined ? undefined : this.paper.findViewByModel(operatorID); - if (nextView) { - joint.highlighters.mask.add(nextView, "rect.body", TARGET_HIGHLIGHT_ID, { - padding: 6, - rx: 5, - ry: 5, - attrs: { "stroke-width": 2, stroke: "#1890FF", "stroke-dasharray": "4 2" }, - }); - } - targetOperatorID = operatorID; + const texeraGraph = this.workflowActionService.getTexeraGraph(); + // The comment box under the pointer, and every comment box the drag moves (the whole selection). + let drag: { pressedID: string; start: Point; commentBoxIDs: string[] } | undefined; + let targetOperatorIDs: string[] = []; + const setTargets = (operatorIDs: string[]) => { + targetOperatorIDs + .filter(operatorID => !operatorIDs.includes(operatorID)) + .map(operatorID => this.paper.findViewByModel(operatorID)) + .forEach(view => view && joint.highlighters.mask.remove(view, TARGET_HIGHLIGHT_ID)); + operatorIDs + .filter(operatorID => !targetOperatorIDs.includes(operatorID)) + .map(operatorID => this.paper.findViewByModel(operatorID)) + .forEach( + view => + view && + joint.highlighters.mask.add(view, "rect.body", TARGET_HIGHLIGHT_ID, { + padding: 6, + rx: 5, + ry: 5, + attrs: { "stroke-width": 2, stroke: "#1890FF", "stroke-dasharray": "4 2" }, + }) + ); + targetOperatorIDs = operatorIDs; }; - const isSoloCommentBoxDrag = (elementID: string) => - this.interactive && - this.workflowActionService.getTexeraGraph().hasCommentBox(elementID) && - this.wrapper.getCurrentHighlightedOperatorIDs().length === 0; + const draggedCommentBoxIDs = () => + drag!.commentBoxIDs.filter(commentBoxID => texeraGraph.hasCommentBox(commentBoxID)); fromJointPaperEvent(this.paper, "element:pointerdown") .pipe(untilDestroyed(this)) .subscribe(event => { - const elementID = event[0].model.id.toString(); - drag = isSoloCommentBoxDrag(elementID) - ? { commentBoxID: elementID, start: this.wrapper.getElementPosition(elementID) } - : undefined; + const pressedID = event[0].model.id.toString(); + drag = + this.interactive && + texeraGraph.hasCommentBox(pressedID) && + this.wrapper.getCurrentHighlightedOperatorIDs().length === 0 + ? { + pressedID, + start: this.wrapper.getElementPosition(pressedID), + commentBoxIDs: _.union([pressedID], this.wrapper.getCurrentHighlightedCommentBoxIDs()), + } + : undefined; }); fromJointPaperEvent(this.paper, "element:pointermove") @@ -1311,23 +1321,35 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy filter(() => drag !== undefined), untilDestroyed(this) ) - .subscribe(() => setTarget(this.workflowActionService.findCommentBoxAnchorTarget(drag!.commentBoxID))); + .subscribe(() => + setTargets( + _.uniq( + draggedCommentBoxIDs() + .map(commentBoxID => this.workflowActionService.findCommentBoxAnchorTarget(commentBoxID)) + .filter(isDefined) + ) + ) + ); fromJointPaperEvent(this.paper, "element:pointerup") .pipe(untilDestroyed(this)) .subscribe(() => { - setTarget(undefined); - const finished = drag; - drag = undefined; + setTargets([]); if ( - finished === undefined || - !isSoloCommentBoxDrag(finished.commentBoxID) || - _.isEqual(this.wrapper.getElementPosition(finished.commentBoxID), finished.start) + drag === undefined || + !this.interactive || + !texeraGraph.hasCommentBox(drag.pressedID) || + _.isEqual(this.wrapper.getElementPosition(drag.pressedID), drag.start) ) { - // A click, not a drag: leave the anchor alone. + // Not a comment box drag, or a click that moved nothing: leave the anchors alone. + drag = undefined; return; } - this.workflowActionService.anchorCommentBoxOnDrop(finished.commentBoxID); + const commentBoxIDs = draggedCommentBoxIDs(); + drag = undefined; + texeraGraph.bundleActions(() => + commentBoxIDs.forEach(commentBoxID => this.workflowActionService.anchorCommentBoxOnDrop(commentBoxID)) + ); }); } diff --git a/frontend/src/app/workspace/service/operator-menu/operator-menu.service.spec.ts b/frontend/src/app/workspace/service/operator-menu/operator-menu.service.spec.ts index 987ddf47e69..c399e6cc34e 100644 --- a/frontend/src/app/workspace/service/operator-menu/operator-menu.service.spec.ts +++ b/frontend/src/app/workspace/service/operator-menu/operator-menu.service.spec.ts @@ -414,6 +414,55 @@ describe("OperatorMenuService", () => { expect(texeraGraph.getAllCommentBoxes()[0].commentBoxID).not.toBe(mockCommentBox.commentBoxID); }); + it("anchors a pasted comment box to the pasted copy of its operator, at the same offset", async () => { + const clipboard = { + operators: [mockScanPredicate], + operatorPositions: { [mockScanPredicate.operatorID]: { x: 100, y: 100 } }, + links: [], + commentBoxes: [ + { + ...mockCommentBox, + commentBoxPosition: { x: 170, y: 90 }, + anchoredOperatorID: mockScanPredicate.operatorID, + }, + ], + }; + readText.mockResolvedValue(JSON.stringify(clipboard)); + const texeraGraph = workflowActionService.getTexeraGraph(); + const wrapper = workflowActionService.getJointGraphWrapper(); + + service.performPasteOperation(); + await flushAsync(); + + const [pastedOperator] = texeraGraph.getAllOperators(); + const [pastedCommentBox] = texeraGraph.getAllCommentBoxes(); + expect(pastedCommentBox.anchoredOperatorID).toEqual(pastedOperator.operatorID); + const operatorPosition = wrapper.getElementPosition(pastedOperator.operatorID); + expect(wrapper.getElementPosition(pastedCommentBox.commentBoxID)).toEqual({ + x: operatorPosition.x + 70, + y: operatorPosition.y - 10, + }); + }); + + it("pastes a comment box as floating when its operator was not copied with it", async () => { + // The operator is on the canvas, but only the comment box was copied. + workflowActionService.addOperator(mockScanPredicate, { x: 100, y: 100 }); + const clipboard = { + operators: [], + operatorPositions: {}, + links: [], + commentBoxes: [{ ...mockCommentBox, anchoredOperatorID: mockScanPredicate.operatorID }], + }; + readText.mockResolvedValue(JSON.stringify(clipboard)); + const texeraGraph = workflowActionService.getTexeraGraph(); + + service.performPasteOperation(); + await flushAsync(); + + const [pastedCommentBox] = texeraGraph.getAllCommentBoxes(); + expect(pastedCommentBox.anchoredOperatorID).toBeUndefined(); + }); + it("notifies the user when the clipboard holds no pasteable elements", async () => { readText.mockResolvedValue("{}"); const notificationService = TestBed.inject(NotificationService); diff --git a/frontend/src/app/workspace/service/operator-menu/operator-menu.service.ts b/frontend/src/app/workspace/service/operator-menu/operator-menu.service.ts index a5f9224a522..6687db06e1c 100644 --- a/frontend/src/app/workspace/service/operator-menu/operator-menu.service.ts +++ b/frontend/src/app/workspace/service/operator-menu/operator-menu.service.ts @@ -298,6 +298,8 @@ export class OperatorMenuService { let copiedOps: OperatorPredicate[] = elementsInClipboard.get("operators") as OperatorPredicate[]; let linksCopy: LinkWithID = {}; + // each copied operator's pasted copy, so that a comment box anchored to it can follow + const pastedOperators = new Map(); copiedOps.forEach(copiedOperator => { // copyOperator assigns a new randomly generated operator ID to the new operator const newOperator = this.copyOperator(copiedOperator); @@ -346,6 +348,10 @@ export class OperatorMenuService { pos: newOperatorPosition, }); positions.push(newOperatorPosition); + pastedOperators.set(copiedOperator.operatorID, { + operatorID: newOperator.operatorID, + offset: { x: newOperatorPosition.x - position.x, y: newOperatorPosition.y - position.y }, + }); }); const links = Object.values(linksCopy); @@ -363,8 +369,22 @@ export class OperatorMenuService { let commentBoxesCopy: CommentBox[] = elementsInClipboard.get("commentBoxes") as CommentBox[]; commentBoxesCopy.forEach(commentBoxCopy => { const commentBoxPosition: Point = commentBoxCopy.commentBoxPosition as Point; + // anchored to an operator pasted along with it: anchor to that copy, moved as far as it was. + // Anchored to one that was not copied: the copy floats. + const pastedOperator = + commentBoxCopy.anchoredOperatorID === undefined + ? undefined + : pastedOperators.get(commentBoxCopy.anchoredOperatorID); + const anchorTo = + pastedOperator !== undefined && + this.workflowActionService.getTexeraGraph().hasOperator(pastedOperator.operatorID) + ? pastedOperator + : undefined; positions.push(commentBoxPosition); - const newCommentBoxPosition = this.calcOperatorPosition(commentBoxPosition, positions); + const newCommentBoxPosition = + anchorTo === undefined + ? this.calcOperatorPosition(commentBoxPosition, positions) + : { x: commentBoxPosition.x + anchorTo.offset.x, y: commentBoxPosition.y + anchorTo.offset.y }; positions.push(newCommentBoxPosition); const newCommentBoxID = this.workflowUtilService.getCommentBoxRandomUUID(); const newCommentBox: CommentBox = { @@ -372,7 +392,12 @@ export class OperatorMenuService { comments: commentBoxCopy.comments, commentBoxPosition: newCommentBoxPosition, }; - this.workflowActionService.addCommentBox(newCommentBox); + this.workflowActionService.getTexeraGraph().bundleActions(() => { + this.workflowActionService.addCommentBox(newCommentBox); + if (anchorTo !== undefined) { + this.workflowActionService.anchorCommentBox(newCommentBoxID, anchorTo.operatorID); + } + }); }); }, // if the Promise returned from readText rejects, the read clipboard permission is not granted, and we send a warning to the user diff --git a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts index 2b944cf9218..b6a69bdc89d 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts @@ -233,12 +233,14 @@ export class SharedModelChangeHandler { /** * Syncs element positions. Will temporarily block local updates. + * An "add" counts too when the element is already on the canvas: a comment box enters the + * position map only when it first moves, so its first move arrives as an add. * @private */ private handleElementPositionChange(): void { this.texeraGraph.sharedModel.elementPositionMap?.observe((event: Y.YMapEvent) => { event.changes.keys.forEach((change, key) => { - if (change.action === "update") { + if (change.action === "update" || (change.action === "add" && this.jointGraph.getCell(key) !== undefined)) { this.texeraGraph.setSyncTexeraGraph(false); const newPosition = this.texeraGraph.sharedModel.elementPositionMap?.get(key); if (newPosition) { diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts index edefce1c9a2..c814bbbaae6 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts @@ -38,10 +38,17 @@ import { import { inject, TestBed } from "@angular/core/testing"; import * as Y from "yjs"; -import { DEFAULT_WORKFLOW, DEFAULT_WORKFLOW_NAME, WorkflowActionService } from "./workflow-action.service"; +import { + COMMENT_BOX_DETACH_DISTANCE, + COMMENT_BOX_SNAP_DISTANCE, + DEFAULT_WORKFLOW, + DEFAULT_WORKFLOW_NAME, + WorkflowActionService, +} from "./workflow-action.service"; import { LogicalPort, OperatorPredicate } from "../../../types/workflow-common.interface"; import { WorkflowUtilService } from "../util/workflow-util.service"; import { commonTestProviders } from "../../../../common/testing/test-utils"; +import { GuiConfigService } from "../../../../common/service/gui-config.service"; import { ExecutionMode, FormBindingConfig, @@ -667,6 +674,50 @@ describe("WorkflowActionService", () => { expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toBeUndefined(); }); + + it("snaps at exactly the snap distance, and not a pixel beyond", () => { + // The operator's right edge is at x 160. + addComment(floatingID, { x: 160 + COMMENT_BOX_SNAP_DISTANCE, y: 100 }); + expect(service.findCommentBoxAnchorTarget(floatingID)).toEqual(mockScanPredicate.operatorID); + + service.getJointGraphWrapper().setAbsolutePosition(floatingID, 160 + COMMENT_BOX_SNAP_DISTANCE + 1, 100); + expect(service.findCommentBoxAnchorTarget(floatingID)).toBeUndefined(); + }); + + it("keeps the anchor at exactly the detach distance, and detaches a pixel beyond", () => { + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.getJointGraphWrapper().setAbsolutePosition(anchoredID, 160 + COMMENT_BOX_DETACH_DISTANCE, 100); + service.anchorCommentBoxOnDrop(anchoredID); + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toEqual(mockScanPredicate.operatorID); + + service.getJointGraphWrapper().setAbsolutePosition(anchoredID, 160 + COMMENT_BOX_DETACH_DISTANCE + 1, 100); + service.anchorCommentBoxOnDrop(anchoredID); + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toBeUndefined(); + }); + + it("keeps its current operator when dropped as close to another one", () => { + // The result operator spans x 212..272: a box at x 170..202 is 10px from both operators. + service.addOperator(mockResultPredicate, { x: 212, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockResultPredicate.operatorID); + + service.anchorCommentBoxOnDrop(anchoredID); + + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toEqual(mockResultPredicate.operatorID); + }); + + it("breaks a tie between equally near operators by the nearer center", () => { + // Both operators are 10px from the box's edges; the result operator sits higher, so its + // center is farther from the box's. Added before the scan operator, so order cannot decide. + service.deleteOperator(mockScanPredicate.operatorID); + service.addOperator(mockResultPredicate, { x: 212, y: 60 }); + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(floatingID, { x: 170, y: 100 }); + + expect(service.findCommentBoxAnchorTarget(floatingID)).toEqual(mockScanPredicate.operatorID); + }); }); describe("adding a comment box to an operator", () => { @@ -701,6 +752,114 @@ describe("WorkflowActionService", () => { }); }); + /** + * A second editor in the same room: its own WorkflowActionService, graph, joint graph and + * change handler, with the two shared documents relaying every update to each other the way + * the collaboration server does. What one editor does reaches the other as a remote change. + */ + describe("with a co-editor", () => { + let peer: WorkflowActionService; + let disconnect: () => void; + + function connect(): () => void { + const local = texeraGraph.sharedModel.yDoc; + // Reached the same way as this editor's graph above: getTexeraGraph() hides the shared model. + const remote = ((peer as any).texeraGraph as WorkflowGraph).sharedModel.yDoc; + const relay = (to: Y.Doc) => (update: Uint8Array, origin: unknown) => { + if (origin !== "relay") Y.applyUpdate(to, update, "relay"); + }; + const toRemote = relay(remote); + const toLocal = relay(local); + local.on("update", toRemote); + remote.on("update", toLocal); + // Catch up on whatever either side did while apart, as a reconnecting client does. + Y.applyUpdate(remote, Y.encodeStateAsUpdate(local, Y.encodeStateVector(remote)), "relay"); + Y.applyUpdate(local, Y.encodeStateAsUpdate(remote, Y.encodeStateVector(local)), "relay"); + return () => { + local.off("update", toRemote); + remote.off("update", toLocal); + }; + } + + function onBothCanvases(elementID: string): [joint.dia.Element, joint.dia.Element] { + return [ + jointGraph.getCell(elementID) as joint.dia.Element, + peer.getJointGraph().getCell(elementID) as joint.dia.Element, + ]; + } + + beforeEach(() => { + peer = new WorkflowActionService( + TestBed.inject(OperatorMetadataService), + TestBed.inject(JointUIService), + new UndoRedoService(), + TestBed.inject(WorkflowUtilService), + TestBed.inject(GuiConfigService) + ); + disconnect = connect(); + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + }); + + afterEach(() => disconnect()); + + it("shows the first move of a floating comment box on the other canvas", () => { + // The box's first move is the first time its position enters the shared position map. + service.highlightCommentBoxes(false, anchoredID); + service.getJointGraphWrapper().setAbsolutePosition(anchoredID, 400, 300); + + expect(peer.getJointGraphWrapper().getElementPosition(anchoredID)).toEqual({ x: 400, y: 300 }); + }); + + it("shows an anchor made by the other editor, with its outline and connector line", () => { + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + expect(peer.getTexeraGraph().getCommentBox(anchoredID).anchoredOperatorID).toEqual( + mockScanPredicate.operatorID + ); + const [mine, theirs] = onBothCanvases(anchoredID); + expect(theirs.attr("rect/stroke-dasharray")).toEqual("4 2"); + expect(theirs.attr(".anchor-connector")).toEqual(mine.attr(".anchor-connector")); + expect(theirs.attr(".anchor-connector/display")).toEqual("inline"); + }); + + it("moves an anchored comment box on the other canvas when its operator is dragged", () => { + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + service.highlightOperators(false, mockScanPredicate.operatorID); + service.getJointGraphWrapper().setAbsolutePosition(mockScanPredicate.operatorID, 300, 250); + + expect(peer.getJointGraphWrapper().getElementPosition(mockScanPredicate.operatorID)).toEqual({ + x: 300, + y: 250, + }); + expect(peer.getJointGraphWrapper().getElementPosition(anchoredID)).toEqual({ x: 370, y: 250 }); + const [mine, theirs] = onBothCanvases(anchoredID); + expect(theirs.attr(".anchor-connector")).toEqual(mine.attr(".anchor-connector")); + }); + + it("converges when one editor anchors a comment box while the other moves it", () => { + disconnect(); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + peer.highlightCommentBoxes(false, anchoredID); + peer.getJointGraphWrapper().setAbsolutePosition(anchoredID, 100, 200); + + disconnect = connect(); + + for (const editor of [service, peer]) { + expect(editor.getTexeraGraph().getCommentBox(anchoredID).anchoredOperatorID).toEqual( + mockScanPredicate.operatorID + ); + expect(editor.getJointGraphWrapper().getElementPosition(anchoredID)).toEqual({ x: 100, y: 200 }); + expect(editor.getTexeraGraph().getCommentBox(anchoredID).commentBoxPosition).toEqual({ x: 100, y: 200 }); + } + const [mine, theirs] = onBothCanvases(anchoredID); + // Center (116, 216), below the operator's bottom edge at y 160. + expect(mine.attr(".anchor-connector")).toEqual(expect.objectContaining({ display: "inline", x2: 16, y2: -40 })); + expect(theirs.attr(".anchor-connector")).toEqual(mine.attr(".anchor-connector")); + }); + }); + describe("connector line", () => { const connector = (commentBoxID: string) => (jointGraph.getCell(commentBoxID) as joint.dia.Element).attr(".anchor-connector"); diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts index 8da2026f895..4dca9ee7db7 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts @@ -475,18 +475,30 @@ export class WorkflowActionService { /** * The operator a comment box would anchor to if it were dropped where it is now: the nearest * operator within COMMENT_BOX_SNAP_DISTANCE of it, or undefined if none is that close. + * Among equally near operators, the one it is anchored to wins, so a drop does not flip its anchor; + * otherwise the one whose center is nearest. * @param commentBoxID */ public findCommentBoxAnchorTarget(commentBoxID: string): string | undefined { const commentBoxBBox = this.getElementBBox(commentBoxID); - let nearest: { operatorID: string; distance: number } | undefined; - for (const operator of this.texeraGraph.getAllOperators()) { - const distance = distanceBetween(commentBoxBBox, this.getElementBBox(operator.operatorID)); - if (distance <= COMMENT_BOX_SNAP_DISTANCE && (nearest === undefined || distance < nearest.distance)) { - nearest = { operatorID: operator.operatorID, distance }; - } - } - return nearest?.operatorID; + const anchoredOperatorID = this.texeraGraph.getCommentBox(commentBoxID).anchoredOperatorID; + const candidates = this.texeraGraph + .getAllOperators() + .map(operator => { + const operatorBBox = this.getElementBBox(operator.operatorID); + return { + operatorID: operator.operatorID, + distance: distanceBetween(commentBoxBBox, operatorBBox), + isAnchor: operator.operatorID === anchoredOperatorID, + centerDistance: commentBoxBBox.center().distance(operatorBBox.center()), + }; + }) + .filter(candidate => candidate.distance <= COMMENT_BOX_SNAP_DISTANCE); + candidates.sort( + (a, b) => + a.distance - b.distance || Number(b.isAnchor) - Number(a.isAnchor) || a.centerDistance - b.centerDistance + ); + return candidates[0]?.operatorID; } /** From ca7e052fe39a574cab07c60ac4b0473c8d43ccea Mon Sep 17 00:00:00 2001 From: Suryaa Charan <122703005+sshiv012@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:06:36 -0800 Subject: [PATCH 4/5] fix(frontend): draw comments anchored to a missing operator as floating An editor that predates anchoring can delete an operator without detaching its comment boxes. Style the outline by whether the anchored operator is on the canvas, and refresh it when an operator is removed. Co-Authored-By: Claude Opus 5.5 --- .../model/shared-model-change-handler.ts | 15 +++++----- .../model/workflow-action.service.spec.ts | 30 +++++++++++++++++++ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts index b6a69bdc89d..789d1c4cbd3 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts @@ -467,17 +467,20 @@ export class SharedModelChangeHandler { } /** - * Keeps each anchored comment box's connector line on its operator: redrawn whenever the comment box - * or the operator is added to the joint graph or moves, wherever the move came from. + * Keeps each anchored comment box's outline and connector line on its operator: redrawn whenever the + * comment box or the operator is added to the joint graph, moves, or the operator is removed. + * An anchor to an operator that is not on the canvas (e.g. deleted by an editor that predates anchoring) + * is drawn as floating. * Listens on the joint graph itself, which outlives every shared model, so it is registered once. * @private */ private handleCommentBoxConnectors(): void { - this.jointGraph.on("add change:position", (cell: joint.dia.Cell) => { + this.jointGraph.on("add remove change:position", (cell: joint.dia.Cell) => { const elementID = cell.id.toString(); if (this.texeraGraph.hasCommentBox(elementID)) { this.refreshCommentBoxConnector(elementID); - } else if (this.texeraGraph.hasOperator(elementID)) { + } else { + // A removed operator is already gone from the texera graph, so look up its comment boxes by ID alone. this.texeraGraph .getCommentBoxesAnchoredTo(elementID) .forEach(commentBoxID => this.refreshCommentBoxConnector(commentBoxID)); @@ -493,6 +496,7 @@ export class SharedModelChangeHandler { const operatorID = this.texeraGraph.getCommentBox(commentBoxID).anchoredOperatorID; const operatorElement = operatorID === undefined ? undefined : (this.jointGraph.getCell(operatorID) as joint.dia.Element | undefined); + commentElement.attr("rect", JointUIService.getCommentBoxAnchorAttrs(operatorElement !== undefined)); commentElement.attr( ".anchor-connector", JointUIService.getCommentBoxConnectorAttrs(commentElement.getBBox(), operatorElement?.getBBox()) @@ -513,9 +517,6 @@ export class SharedModelChangeHandler { if (event.target !== this.texeraGraph.sharedModel.commentBoxMap) { const commentBox: CommentBox = this.texeraGraph.getCommentBox(event.path[0] as string); if (event.path.length === 1 && event.changes.keys.has("anchoredOperatorID")) { - this.jointGraph - .getCell(commentBox.commentBoxID) - ?.attr("rect", JointUIService.getCommentBoxAnchorAttrs(commentBox.anchoredOperatorID !== undefined)); this.refreshCommentBoxConnector(commentBox.commentBoxID); } if (event.path.length === 2 && event.path[event.path.length - 1] === "comments") { diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts index c814bbbaae6..4adfa4494eb 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts @@ -599,6 +599,24 @@ describe("WorkflowActionService", () => { expect(dash()).toEqual("none"); }); + it("doesn't outline a comment box anchored to an operator that is gone", () => { + const workflow: Workflow = { + ...DEFAULT_WORKFLOW, + content: { + operators: [mockScanPredicate], + operatorPositions: { [mockScanPredicate.operatorID]: mockPoint }, + links: [], + commentBoxes: [ + { ...mockCommentBox, commentBoxID: "commentBox-dangling", anchoredOperatorID: "no-such-operator" }, + ], + settings: service.getWorkflowSettings(), + }, + }; + service.reloadWorkflow(workflow); + + expect(jointGraph.getCell("commentBox-dangling").attr("rect/stroke-dasharray")).toEqual("none"); + }); + it("undoes an anchor", () => { service.addOperator(mockScanPredicate, mockPoint); addComment(anchoredID, { x: 0, y: 0 }); @@ -823,6 +841,18 @@ describe("WorkflowActionService", () => { expect(theirs.attr(".anchor-connector/display")).toEqual("inline"); }); + it("drops the outline when an older editor deletes the operator but leaves the anchor", () => { + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + + // An editor from before anchoring deletes the operator without detaching its comment boxes. + ((peer as any).texeraGraph as WorkflowGraph).deleteOperator(mockScanPredicate.operatorID); + + expect(texeraGraph.getCommentBox(anchoredID).anchoredOperatorID).toEqual(mockScanPredicate.operatorID); + const mine = jointGraph.getCell(anchoredID) as joint.dia.Element; + expect(mine.attr("rect/stroke-dasharray")).toEqual("none"); + expect(mine.attr(".anchor-connector/display")).toEqual("none"); + }); + it("moves an anchored comment box on the other canvas when its operator is dragged", () => { service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); From 5b2454019975c38241910b6a21a3900d351c5527 Mon Sep 17 00:00:00 2001 From: Suryaa Charan <122703005+sshiv012@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:27:21 -0800 Subject: [PATCH 5/5] fix(frontend): address review of comment anchoring - Undoing a comment box's first move (e.g. an operator drag that took an anchored comment along) returns it to its saved position. - "anchor to operator" is offered only for comment boxes within the detach distance, so the next drop does not detach them again. - "add comment" places the new box above the operator's delete and chat buttons instead of on top of them. - A drop settles only the comment boxes the drag actually moved. - Anchor changes, including undo and redo, now count as workflow changes, so they are autosaved. - Correct the auto-layout comment on what comment offsets are relative to. Co-Authored-By: Claude Opus 5.5 --- .../context-menu.component.spec.ts | 13 ++++ .../context-menu/context-menu.component.ts | 10 ++- .../workflow-editor.component.spec.ts | 16 ++++- .../workflow-editor.component.ts | 34 +++++----- .../service/joint-ui/joint-ui.service.ts | 6 +- .../model/joint-graph-wrapper.ts | 4 +- .../model/shared-model-change-handler.ts | 15 ++++- .../model/workflow-action.service.spec.ts | 62 +++++++++++++++++++ .../model/workflow-action.service.ts | 25 +++++++- .../workflow-graph/model/workflow-graph.ts | 12 +++- 10 files changed, 171 insertions(+), 26 deletions(-) diff --git a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.spec.ts b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.spec.ts index b9cf1f08b2c..b2bb6ef2f6d 100644 --- a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.spec.ts +++ b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.spec.ts @@ -94,6 +94,7 @@ describe("ContextMenuComponent", () => { anchorCommentBox: vi.fn(), detachCommentBox: vi.fn(), addCommentBoxToOperator: vi.fn(), + isCommentBoxWithinAnchorReach: vi.fn(), }; workflowActionServiceSpy.getJointGraphWrapper.mockReturnValue(jointGraphWrapperSpy); workflowActionServiceSpy.getWorkflowModificationEnabledStream.mockReturnValue(of(true)); @@ -838,9 +839,21 @@ describe("ContextMenuComponent", () => { commentBoxID: id, anchoredOperatorID: anchors[id], })); + workflowActionService.isCommentBoxWithinAnchorReach.mockReturnValue(true); component.isWorkflowModifiable = true; }); + it("offers no anchor when a selected comment box is too far from the operator to stay anchored", () => { + workflowActionService.isCommentBoxWithinAnchorReach.mockImplementation( + (commentBoxID: string) => commentBoxID !== "box-anchored" + ); + select(["op2"], ["box-floating", "box-anchored"]); + expect(renderedLabels()).not.toContain(ANCHOR); + select(["op2"], ["box-floating"]); + expect(renderedLabels()).toContain(ANCHOR); + expect(workflowActionService.isCommentBoxWithinAnchorReach).toHaveBeenCalledWith("box-floating", "op2"); + }); + it("anchors every selected comment box to the one selected operator, in one bundled action", () => { select(["op2"], ["box-floating", "box-anchored"]); const bundle = workflowActionService.getTexeraGraph().bundleActions as any; diff --git a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts index 107c41aee97..13c0efb1271 100644 --- a/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts +++ b/frontend/src/app/workspace/component/workflow-editor/context-menu/context-menu/context-menu.component.ts @@ -191,13 +191,19 @@ export class ContextMenuComponent { this.workflowActionService.addCommentBoxToOperator(this.highlightedOperatorIds[0]); } - /** Anchoring takes the selected comment boxes and exactly one selected operator to anchor them to. */ + /** + * Anchoring takes the selected comment boxes and exactly one selected operator to anchor them to, + * each box close enough to the operator that its next drop does not detach it again. + */ public canAnchorCommentBoxes(): boolean { return ( this.canModify && this.highlightedOperatorIds.length === 1 && this.highlightedCommentBoxIds.length > 0 && - !this.hasHighlightedLinks() + !this.hasHighlightedLinks() && + this.highlightedCommentBoxIds.every(commentBoxID => + this.workflowActionService.isCommentBoxWithinAnchorReach(commentBoxID, this.highlightedOperatorIds[0]) + ) ); } diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts index d5ec55c64c6..5ae37f2a87a 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts @@ -1275,9 +1275,8 @@ describe("WorkflowEditorComponent", () => { } /** Presses on an element, drags it to (x, y), and returns a function that releases it. */ - function pressAndDrag(elementID: string, x: number, y: number): () => void { + function pressAndDrag(elementID: string, x: number, y: number, event = new MouseEvent("mousedown")): () => void { const view = component.paper.findViewByModel(elementID); - const event = new MouseEvent("mousedown"); (component.paper as any).trigger("cell:pointerdown", view, event, 0, 0); (component.paper as any).trigger("element:pointerdown", view, event, 0, 0); workflowActionService.getJointGraphWrapper().setAbsolutePosition(elementID, x, y); @@ -1310,6 +1309,19 @@ describe("WorkflowEditorComponent", () => { expect(targetOutlined()).toBe(false); }); + it("leaves a selected comment box alone when the drag does not move it", () => { + // b floats 10px right of the operator, where a drop would anchor it. + addComment("box-a", 400, 400); + addComment("box-b", 170, 100); + workflowActionService.highlightCommentBoxes(true, "box-a", "box-b"); + + // Shift-pressing a selected box deselects it, so it is dragged alone. + pressAndDrag("box-a", 400, 500, new MouseEvent("mousedown", { shiftKey: true }))(); + + expect(workflowActionService.getJointGraphWrapper().getElementPosition("box-b")).toEqual({ x: 170, y: 100 }); + expect(anchorOf("box-b")).toBeUndefined(); + }); + it("anchors every comment box dragged together, each by where it lands", () => { addComment("box-a", 400, 100); addComment("box-b", 400, 130); diff --git a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts index 66ceb24fefb..46965e1ed22 100644 --- a/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts +++ b/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts @@ -1274,8 +1274,10 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy private handleCommentBoxDragToAnchor(): void { const TARGET_HIGHLIGHT_ID = "commentBoxAnchorTarget"; const texeraGraph = this.workflowActionService.getTexeraGraph(); - // The comment box under the pointer, and every comment box the drag moves (the whole selection). - let drag: { pressedID: string; start: Point; commentBoxIDs: string[] } | undefined; + // The comment box under the pointer, and where each comment box the drag may move (the pressed one + // and the rest of the selection) started. A selected box can stay put: shift-pressing a selected box + // deselects it, and it is then dragged alone. + let drag: { pressedID: string; starts: Map } | undefined; let targetOperatorIDs: string[] = []; const setTargets = (operatorIDs: string[]) => { targetOperatorIDs @@ -1297,8 +1299,13 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy ); targetOperatorIDs = operatorIDs; }; - const draggedCommentBoxIDs = () => - drag!.commentBoxIDs.filter(commentBoxID => texeraGraph.hasCommentBox(commentBoxID)); + const movedCommentBoxIDs = () => + Array.from(drag!.starts) + .filter( + ([commentBoxID, start]) => + texeraGraph.hasCommentBox(commentBoxID) && !_.isEqual(this.wrapper.getElementPosition(commentBoxID), start) + ) + .map(([commentBoxID]) => commentBoxID); fromJointPaperEvent(this.paper, "element:pointerdown") .pipe(untilDestroyed(this)) @@ -1310,8 +1317,12 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy this.wrapper.getCurrentHighlightedOperatorIDs().length === 0 ? { pressedID, - start: this.wrapper.getElementPosition(pressedID), - commentBoxIDs: _.union([pressedID], this.wrapper.getCurrentHighlightedCommentBoxIDs()), + starts: new Map( + _.union([pressedID], this.wrapper.getCurrentHighlightedCommentBoxIDs()).map(commentBoxID => [ + commentBoxID, + this.wrapper.getElementPosition(commentBoxID), + ]) + ), } : undefined; }); @@ -1324,7 +1335,7 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy .subscribe(() => setTargets( _.uniq( - draggedCommentBoxIDs() + movedCommentBoxIDs() .map(commentBoxID => this.workflowActionService.findCommentBoxAnchorTarget(commentBoxID)) .filter(isDefined) ) @@ -1335,17 +1346,12 @@ export class WorkflowEditorComponent implements OnInit, AfterViewInit, OnDestroy .pipe(untilDestroyed(this)) .subscribe(() => { setTargets([]); - if ( - drag === undefined || - !this.interactive || - !texeraGraph.hasCommentBox(drag.pressedID) || - _.isEqual(this.wrapper.getElementPosition(drag.pressedID), drag.start) - ) { + if (drag === undefined || !this.interactive || !movedCommentBoxIDs().includes(drag.pressedID)) { // Not a comment box drag, or a click that moved nothing: leave the anchors alone. drag = undefined; return; } - const commentBoxIDs = draggedCommentBoxIDs(); + const commentBoxIDs = movedCommentBoxIDs(); drag = undefined; texeraGraph.bundleActions(() => commentBoxIDs.forEach(commentBoxID => this.workflowActionService.anchorCommentBoxOnDrop(commentBoxID)) diff --git a/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts b/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts index 544ea96ed6a..45e2036f20f 100644 --- a/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts +++ b/frontend/src/app/workspace/service/joint-ui/joint-ui.service.ts @@ -212,6 +212,8 @@ export class JointUIService { public static readonly DEFAULT_GROUP_MARGIN_BOTTOM = 40; public static readonly DEFAULT_COMMENT_WIDTH = 32; public static readonly DEFAULT_COMMENT_HEIGHT = 32; + /** How far above the operator its delete and chat buttons are drawn. */ + public static readonly OPERATOR_BUTTON_Y = -20; public static readonly MAX_OPERATOR_NAME_PIXELS = 200; private static readonly OPERATOR_NAME_FONT = "14px sans-serif"; private static measureCtx: CanvasRenderingContext2D | null = null; @@ -924,7 +926,7 @@ export class JointUIService { }, ".delete-button": { x: 60, - y: -20, + y: JointUIService.OPERATOR_BUTTON_Y, cursor: "pointer", fill: "#D8656A", event: "element:delete", @@ -932,7 +934,7 @@ export class JointUIService { }, ".chat-button": { x: 85, - y: -20, + y: JointUIService.OPERATOR_BUTTON_Y, cursor: "pointer", fill: "#1890ff", event: "element:chat", diff --git a/frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts b/frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts index 2074094b38c..fabbb8a9079 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts @@ -598,8 +598,8 @@ export class JointGraphWrapper { public autoLayoutJoint(anchoredCommentBoxIDs: ReadonlyMap = new Map()): void { const getElement = (id: string) => this.jointGraph.getCell(id) as joint.dia.Element; const anchored = new Set(Array.from(anchoredCommentBoxIDs.values()).flat()); - // For each operator with anchored comment boxes: the bounding box of the group, and the - // operator's and each comment box's offset within it, so the group is laid out as one node. + // For each operator with anchored comment boxes: the bounding box of the group, the operator's + // offset within it, and each comment box's offset from the operator, so the group is laid out as one node. const groups = new Map(); anchoredCommentBoxIDs.forEach((commentBoxIDs, operatorID) => { const operator = getElement(operatorID); diff --git a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts index 789d1c4cbd3..9112c35e92e 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/shared-model-change-handler.ts @@ -240,7 +240,19 @@ export class SharedModelChangeHandler { private handleElementPositionChange(): void { this.texeraGraph.sharedModel.elementPositionMap?.observe((event: Y.YMapEvent) => { event.changes.keys.forEach((change, key) => { - if (change.action === "update" || (change.action === "add" && this.jointGraph.getCell(key) !== undefined)) { + if (change.action === "delete" && this.texeraGraph.hasCommentBox(key) && this.jointGraph.getCell(key)) { + // Undoing a comment box's first move removes it from the position map again; its saved + // position has been undone with it, so that is where it goes back to. + const savedPosition = this.texeraGraph.getCommentBox(key).commentBoxPosition; + this.texeraGraph.setSyncTexeraGraph(false); + this.jointGraphWrapper.setListenPositionChange(false); + this.jointGraphWrapper.setAbsolutePosition(key, savedPosition.x, savedPosition.y); + this.jointGraphWrapper.setListenPositionChange(true); + this.texeraGraph.setSyncTexeraGraph(true); + } else if ( + change.action === "update" || + (change.action === "add" && this.jointGraph.getCell(key) !== undefined) + ) { this.texeraGraph.setSyncTexeraGraph(false); const newPosition = this.texeraGraph.sharedModel.elementPositionMap?.get(key); if (newPosition) { @@ -518,6 +530,7 @@ export class SharedModelChangeHandler { const commentBox: CommentBox = this.texeraGraph.getCommentBox(event.path[0] as string); if (event.path.length === 1 && event.changes.keys.has("anchoredOperatorID")) { this.refreshCommentBoxConnector(commentBox.commentBoxID); + this.texeraGraph.commentBoxAnchorChangedSubject.next({ commentBox }); } if (event.path.length === 2 && event.path[event.path.length - 1] === "comments") { const addedComments = Array.from(event.changes.added.values()); diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts index 4adfa4494eb..0e33ce5260f 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.spec.ts @@ -617,6 +617,51 @@ describe("WorkflowActionService", () => { expect(jointGraph.getCell("commentBox-dangling").attr("rect/stroke-dasharray")).toEqual("none"); }); + it("returns an anchored comment box to its place when its operator's drag is undone", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + texeraGraph.sharedModel.undoManager.stopCapturing(); + // The drag is the comment box's first move, the first time it enters the shared position map. + service.highlightOperators(false, mockScanPredicate.operatorID); + service.getJointGraphWrapper().setAbsolutePosition(mockScanPredicate.operatorID, 300, 250); + texeraGraph.sharedModel.undoManager.stopCapturing(); + + undoRedo.undoAction(); + + expect(service.getJointGraphWrapper().getElementPosition(anchoredID)).toEqual({ x: 170, y: 100 }); + expect(texeraGraph.getCommentBox(anchoredID).commentBoxPosition).toEqual({ x: 170, y: 100 }); + }); + + it("tells whether a comment box is within reach of an operator to stay anchored to it", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + // The operator's right edge is at x 160. + addComment(anchoredID, { x: 160 + COMMENT_BOX_DETACH_DISTANCE, y: 100 }); + addComment(floatingID, { x: 160 + COMMENT_BOX_DETACH_DISTANCE + 1, y: 100 }); + + expect(service.isCommentBoxWithinAnchorReach(anchoredID, mockScanPredicate.operatorID)).toBe(true); + expect(service.isCommentBoxWithinAnchorReach(floatingID, mockScanPredicate.operatorID)).toBe(false); + // The menu can still name a comment box that has just been deleted. + expect(service.isCommentBoxWithinAnchorReach("no-such-box", mockScanPredicate.operatorID)).toBe(false); + }); + + it("reports anchoring, detaching and their undo as workflow changes, so they are autosaved", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + addComment(anchoredID, { x: 170, y: 100 }); + texeraGraph.sharedModel.undoManager.stopCapturing(); + let changes = 0; + const subscription = service.workflowChanged().subscribe(() => changes++); + + service.anchorCommentBox(anchoredID, mockScanPredicate.operatorID); + expect(changes).toEqual(1); + texeraGraph.sharedModel.undoManager.stopCapturing(); + service.detachCommentBox(anchoredID); + expect(changes).toEqual(2); + undoRedo.undoAction(); + expect(changes).toEqual(3); + subscription.unsubscribe(); + }); + it("undoes an anchor", () => { service.addOperator(mockScanPredicate, mockPoint); addComment(anchoredID, { x: 0, y: 0 }); @@ -753,6 +798,23 @@ describe("WorkflowActionService", () => { ); }); + it("places the comment box clear of the operator's delete and chat buttons", () => { + service.addOperator(mockScanPredicate, { x: 100, y: 100 }); + const operator = jointGraph.getCell(mockScanPredicate.operatorID) as joint.dia.Element; + // The buttons are drawn relative to the operator; their sizes come from the operator's markup. + const button = (selector: string, size: number) => ({ + x: 100 + operator.attr(`${selector}/x`), + y: 100 + operator.attr(`${selector}/y`), + width: size, + height: size, + }); + + const commentBoxID = service.addCommentBoxToOperator(mockScanPredicate.operatorID); + + expect(overlaps(boundingBox(commentBoxID), button(".delete-button", 24))).toBe(false); + expect(overlaps(boundingBox(commentBoxID), button(".chat-button", 20))).toBe(false); + }); + it("undoes the added comment box in one step", () => { service.addOperator(mockScanPredicate, { x: 100, y: 100 }); texeraGraph.sharedModel.undoManager.stopCapturing(); diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts index 4dca9ee7db7..41df45a6b2f 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts @@ -524,6 +524,21 @@ export class WorkflowActionService { } } + /** + * Whether a comment box is close enough to an operator to stay anchored to it: anchored from farther + * than COMMENT_BOX_DETACH_DISTANCE, its next drop would detach it again. False when either + * is not on the canvas. + * @param commentBoxID + * @param operatorID + */ + public isCommentBoxWithinAnchorReach(commentBoxID: string, operatorID: string): boolean { + return ( + this.jointGraph.getCell(commentBoxID) !== undefined && + this.jointGraph.getCell(operatorID) !== undefined && + distanceBetween(this.getElementBBox(commentBoxID), this.getElementBBox(operatorID)) <= COMMENT_BOX_DETACH_DISTANCE + ); + } + /** * Adds a new comment box beside an operator, already anchored to it, as a single undoable action. * @param operatorID @@ -534,10 +549,15 @@ export class WorkflowActionService { const operatorPosition = this.jointGraphWrapper.getElementPosition(operatorID); const commentBox: CommentBox = { ...this.workflowUtilService.getNewCommentBox(), - // Right of the operator's top-right corner, clear of its delete button. + // Off the operator's top-right corner, above its delete and chat buttons (which the right-click + // that opens the menu reveals) and clear of the links leaving its output ports on the right. commentBoxPosition: { x: operatorPosition.x + JointUIService.DEFAULT_OPERATOR_WIDTH + COMMENT_BOX_GAP, - y: operatorPosition.y - JointUIService.DEFAULT_COMMENT_HEIGHT / 2, + y: + operatorPosition.y + + JointUIService.OPERATOR_BUTTON_Y - + COMMENT_BOX_GAP - + JointUIService.DEFAULT_COMMENT_HEIGHT, }, }; this.texeraGraph.bundleActions(() => { @@ -983,6 +1003,7 @@ export class WorkflowActionService { this.getTexeraGraph().getCommentBoxAddCommentStream(), this.getTexeraGraph().getCommentBoxDeleteCommentStream(), this.getTexeraGraph().getCommentBoxEditCommentStream(), + this.getTexeraGraph().getCommentBoxAnchorChangedStream(), this.getTexeraGraph().getViewResultOperatorsChangedStream(), this.getTexeraGraph().getReuseCacheOperatorsChangedStream(), this.getTexeraGraph().getOperatorDisplayNameChangedStream(), diff --git a/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts b/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts index 46f165b2cfa..8015648e974 100644 --- a/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts +++ b/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts @@ -58,7 +58,8 @@ type restrictedMethods = | "commentBoxDeleteSubject" | "commentBoxAddCommentSubject" | "commentBoxDeleteCommentSubject" - | "commentBoxEditCommentSubject"; + | "commentBoxEditCommentSubject" + | "commentBoxAnchorChangedSubject"; /** * WorkflowGraphReadonly is a type that only contains the readonly methods of WorkflowGraph. @@ -136,6 +137,7 @@ export class WorkflowGraph { public readonly commentBoxAddCommentSubject = new Subject<{ addedComment: Comment; commentBox: CommentBox }>(); public readonly commentBoxDeleteCommentSubject = new Subject<{ commentBox: CommentBox }>(); public readonly commentBoxEditCommentSubject = new Subject<{ commentBox: CommentBox }>(); + public readonly commentBoxAnchorChangedSubject = new Subject<{ commentBox: CommentBox }>(); public readonly portDisplayNameChangedSubject = new Subject<{ operatorID: string; @@ -954,6 +956,14 @@ export class WorkflowGraph { return this.commentBoxEditCommentSubject.asObservable(); } + /** + * Emits when a comment box is anchored to an operator or detached, however the change came about: + * this editor, a co-editor, or undo and redo. + */ + public getCommentBoxAnchorChangedStream(): Observable<{ commentBox: CommentBox }> { + return this.commentBoxAnchorChangedSubject.asObservable(); + } + public getViewResultOperatorsChangedStream(): Observable<{ newViewResultOps: ReadonlyArray; newUnviewResultOps: ReadonlyArray;