bobbai00 commented on code in PR #9278:
URL: https://github.com/apache/texera/pull/9278#discussion_r4626632152


##########
frontend/src/app/workspace/service/workflow-graph/model/joint-graph-wrapper.ts:
##########
@@ -601,9 +601,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<string, readonly 
string[]> = new Map()): void {

Review Comment:
   **Must fix:**
   
   The agent has its own copy of this layout, and it still moves operators 
without their anchored comments. 
[`autoLayoutWorkflow`](https://github.com/apache/texera/blob/cb2f856fdc574735428e4d1f09809065908ca18e/agent-service/src/agent/util/auto-layout.ts#L23-L67)
 runs after every agent `add_operator`, and the canvas then reloads the result 
([`agent-chat.component.ts:287`](https://github.com/apache/texera/blob/cb2f856fdc574735428e4d1f09809065908ca18e/frontend/src/app/workspace/component/agent/agent-panel/agent-chat/agent-chat.component.ts#L287)).
 Each anchored comment comes back at its old spot, still anchored, with its 
connector stretched to the moved operator: the "comment stays behind" case from 
#9274. I'd shift anchored boxes by their operator's displacement there (its 
[`CommentBox`](https://github.com/apache/texera/blob/cb2f856fdc574735428e4d1f09809065908ca18e/agent-service/src/types/workflow.ts#L98-L105)
 type needs the saved shape); a linked follow-up also works, but then drop "N
 othing outside the frontend reads comment boxes" from the description.



##########
frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts:
##########
@@ -433,6 +451,135 @@ 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);
+  }
+
+  /**
+   * The operator a comment box would anchor to if it were dropped where it is 
now: the nearest
+   * operator within <code>COMMENT_BOX_SNAP_DISTANCE</code> 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);
+    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;
+  }
+
+  /**
+   * Settles a comment box's anchor after the user drops it: dropped next to 
an operator, it anchors to
+   * that operator; dropped beyond <code>COMMENT_BOX_DETACH_DISTANCE</code> 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)) >

Review Comment:
   **Must fix:**
   
   This also detaches a comment that was already beyond 
`COMMENT_BOX_DETACH_DISTANCE` when the drag began, so a 5px nudge detaches it, 
against "a small nudge changes nothing" at line 505. Comments get that far 
without being dragged away: dragged along with another operator, or moved by 
the agent's layout or an older build. In a probe, a 5px nudge detached a 
comment that a group drag had left 240px away, the case you called unintended 
in 
[r4500466032](https://github.com/apache/texera/pull/9278#discussion_r4500466032).
 I'd skip the detach for boxes that were already out of reach at pointerdown.



##########
frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts:
##########
@@ -1483,6 +1485,100 @@ export class WorkflowEditorComponent implements OnInit, 
AfterViewInit, OnDestroy
       });
   }
 
+  /**
+   * 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";
+    const texeraGraph = this.workflowActionService.getTexeraGraph();
+    // 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<string, Point> } | 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 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))
+      .subscribe(event => {
+        const pressedID = event[0].model.id.toString();
+        drag =
+          this.interactive &&
+          texeraGraph.hasCommentBox(pressedID) &&
+          this.wrapper.getCurrentHighlightedOperatorIDs().length === 0
+            ? {
+                pressedID,
+                starts: new Map(
+                  _.union([pressedID], 
this.wrapper.getCurrentHighlightedCommentBoxIDs()).map(commentBoxID => [
+                    commentBoxID,
+                    this.wrapper.getElementPosition(commentBoxID),
+                  ])
+                ),
+              }
+            : undefined;
+      });
+
+    fromJointPaperEvent(this.paper, "element:pointermove")
+      .pipe(
+        filter(() => drag !== undefined),
+        untilDestroyed(this)
+      )
+      .subscribe(() =>
+        setTargets(
+          _.uniq(
+            movedCommentBoxIDs()
+              .map(commentBoxID => 
this.workflowActionService.findCommentBoxAnchorTarget(commentBoxID))
+              .filter(isDefined)
+          )
+        )
+      );
+
+    fromJointPaperEvent(this.paper, "element:pointerup")
+      .pipe(untilDestroyed(this))
+      .subscribe(() => {
+        setTargets([]);
+        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 = movedCommentBoxIDs();

Review Comment:
   **Must fix:**
   
   A shift-dragged selected comment gets its anchor saved but not its move. The 
shift-press deselects it ([line 
1170](https://github.com/apache/texera/blob/cb2f856fdc574735428e4d1f09809065908ca18e/frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.ts#L1169-L1170)),
 and `handleJointElementDrag` only syncs selected elements 
([`workflow-action.service.ts:1344`](https://github.com/apache/texera/blob/cb2f856fdc574735428e4d1f09809065908ca18e/frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts#L1344-L1349)),
 but this drop still settles it. In a probe, a box shift-dragged from (400, 
400) to the operator came out anchored while its saved position stayed (400, 
400). Co-editors and the next load then see it anchored 340px away, so I'd 
settle only the boxes still selected at drop.



##########
frontend/src/app/workspace/service/workflow-graph/model/workflow-action.service.ts:
##########
@@ -433,6 +451,135 @@ 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);
+  }
+
+  /**
+   * The operator a comment box would anchor to if it were dropped where it is 
now: the nearest
+   * operator within <code>COMMENT_BOX_SNAP_DISTANCE</code> 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);
+    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,

Review Comment:
   **Advisory:**
   
   This runs on every pointermove, and `getAllOperators()` builds each 
operator's JSON just to read its ID. 
[`getAllOperatorIDs()`](https://github.com/apache/texera/blob/cb2f856fdc574735428e4d1f09809065908ca18e/frontend/src/app/workspace/service/workflow-graph/model/workflow-graph.ts#L671-L678)
 exists for per-update paths like this. In a yjs micro-benchmark with 300 
operators it took 0.01 ms versus 0.6 ms.
   ```suggestion
         .getAllOperatorIDs()
         .map(operatorID => {
           const operatorBBox = this.getElementBBox(operatorID);
           return {
             operatorID,
             distance: distanceBetween(commentBoxBBox, operatorBBox),
             isAnchor: operatorID === anchoredOperatorID,
   ```



##########
frontend/src/app/workspace/component/workflow-editor/workflow-editor.component.spec.ts:
##########
@@ -1593,6 +1593,121 @@ 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, event = 
new MouseEvent("mousedown")): () => void {
+        const view = component.paper.findViewByModel(elementID);
+        (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("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);
+        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.

Review Comment:
   **Polish:**
   
   The menu item now requires the comment to be within reach 
(`canAnchorCommentBoxes`), so only `anchorCommentBox` can anchor from here.
   ```suggestion
           // Anchored far from its operator (anchorCommentBox sets no distance 
limit), then only clicked.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to