Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed two exceptions on cvat-canvas often occuring on app.cvat.ai #8067

Merged
merged 6 commits into from
Jun 24, 2024

Conversation

bsekachev
Copy link
Member

@bsekachev bsekachev commented Jun 21, 2024

Motivation and context

  • this.el.node.getScreenCTM() is null
  • Edge's nodeFrom M or nodeTo N do not to refer to any node

Additionally, strongly reduced code duplication

How has this been tested?

Checklist

  • I submit my changes into the develop branch
  • I have created a changelog fragment
  • I have updated the documentation accordingly
  • I have added tests to cover my changes
  • I have linked related issues (see GitHub docs)
  • I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • Bug Fixes

    • Resolved an exception in Firefox related to window resizing during skeleton dragging or resizing.
  • New Features

    • Improved drag and resize functionality for shapes on the canvas, ensuring smoother and more reliable interactions.

@bsekachev bsekachev requested a review from nmanovic as a code owner June 21, 2024 10:37
Copy link
Contributor

coderabbitai bot commented Jun 21, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The recent update resolves a Firefox-specific issue involving exceptions during window resizing while dragging or resizing shapes on the canvas. To achieve this, new private properties and methods have been introduced to the CanvasViewImpl class, enhancing the management of draggable and resizable shapes without altering any exported or public entity declarations.

Changes

File Path Change Summary
changelog.d/20240621_133156_sekachev... Documented the fix for Firefox exceptions during window resizing while dragging/resizing shapes.
cvat-canvas/src/typescript/canvasView.ts Introduced draggableShape and resizableShape private properties and corresponding private methods to enhance drag and resize functionality.

Poem

In the code of canvas bright,
Shapes now move with graceful might,
Firefox bugs, we've set to flight,
Draggable, resizable, all just right.
A world of code, renewed delight,
Day and night, our lines ignite.
Here's to changes, pure and spright! ✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 933fbb3 and c6812d9.

Files selected for processing (3)
  • changelog.d/20240621_133156_sekachev.bs_fixed_two_issues_canvas.md (1 hunks)
  • changelog.d/20240621_133257_sekachev.bs_fixed_two_issues_canvas.md (1 hunks)
  • cvat-canvas/src/typescript/canvasView.ts (11 hunks)
Files skipped from review due to trivial changes (2)
  • changelog.d/20240621_133156_sekachev.bs_fixed_two_issues_canvas.md
  • changelog.d/20240621_133257_sekachev.bs_fixed_two_issues_canvas.md
Additional comments not posted (1)
cvat-canvas/src/typescript/canvasView.ts (1)

86-87: Addition of private properties for draggable and resizable shapes.

The new properties draggableShape and resizableShape have been correctly declared as private with appropriate types. This encapsulation ensures that these properties are only accessible within the CanvasViewImpl class, which is a good practice for maintaining the integrity of the object's state.

Comment on lines 1188 to 1389
}
})
.on('resizedone', (): void => {
if (aborted) {
return;
}

onResizeEnd();
this.resizableShape = null;
if (state.shapeType === 'skeleton') {
let { rotation } = (shape as SVG.G).transform();
// be sure, that rotation in range [0; 360]
while (rotation < 0) rotation += 360;
rotation %= 360;
this.mode = Mode.IDLE;

if (resized) {
if (rotation) {
this.onEditDone(state, state.points, rotation);
} else {
const points: number[] = [];

state.elements.forEach((element: any) => {
const elementShape = (shape as SVG.G).children()
.find((child: SVG.Shape) => (
child.id() === `cvat_canvas_shape_${element.clientID}`
));

if (elementShape) {
points.push(...this.translateFromCanvas(
readPointsFromShape(elementShape),
));
}
});

this.onEditDone(state, points, rotation);
}

this.canvas.dispatchEvent(
new CustomEvent('canvas.resizeshape', {
bubbles: false,
cancelable: true,
detail: {
id: state.clientID,
},
}),
);
}

return;
}

if (resized) {
let rotation = shape.transform().rotation || 0;

// be sure, that rotation in range [0; 360]
while (rotation < 0) rotation += 360;
rotation %= 360;

// these points does not take into account possible transformations, applied on the element
// so, if any (like rotation) we need to map them to canvas coordinate space
let points = readPointsFromShape(shape);

// let's keep current points, but they could be rewritten in updateObjects
this.drawnStates[state.clientID].points = this.translateFromCanvas(points);
this.drawnStates[state.clientID].rotation = rotation;
if (rotation) {
points = this.translatePointsFromRotatedShape(shape, points);
}

this.onEditDone(state, this.translateFromCanvas(points), rotation);
this.canvas.dispatchEvent(
new CustomEvent('canvas.resizeshape', {
bubbles: false,
cancelable: true,
detail: {
id: state.clientID,
},
}),
);
}
}).on('resizeabort', () => {
onResizeEnd();
aborted = true;
this.resizableShape = null;
// disable internal drag events of SVG.js
window.dispatchEvent(new MouseEvent('mouseup'));
});
} else {
if (this.resizableShape === shape) {
resizableInstance.fire('resizeabort');
}

(shape as any).off('resizestart');
(shape as any).off('resizing');
(shape as any).off('resizedone');
(shape as any).off('resizeabort');
(shape as any).resize('stop');
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the resizable method implementation.

The resizable method is designed to manage the resize functionality of shapes. Similar to the draggable method, it is well-implemented but could benefit from the following improvements:

  1. Refactoring for clarity: The method is lengthy and handles multiple responsibilities. Refactoring into smaller methods could enhance clarity and maintainability.
  2. Consistency in error handling: As with the draggable method, adding error handling could prevent runtime errors from unhandled exceptions.
  3. Use of hard-coded values: The method uses hard-coded values for snapToGrid and snapToAngle. These could be externalized as configurable parameters.
+ // Suggest breaking down into smaller methods
+ private initializeResizableInstance() {...}
+ private handleResizeStart() {...}
+ private handleResizing() {...}
+ private handleResizeEnd() {...}

+ // Add error handling
+ try {
+     // existing code
+ } catch (error) {
+     console.error("Failed to handle resize event:", error);
+ }

Committable suggestion was skipped due to low confidence.

Comment on lines 1064 to 1186
}).on('dragmove', (e: CustomEvent): void => {
onDragMove();
if (state.shapeType === 'skeleton') {
const { instance } = e.target as any;
const [x, y] = [instance.x(), instance.y()];
const prevXtl = +draggableInstance.attr('data-xtl');
const prevYtl = +draggableInstance.attr('data-ytl');

for (const child of (shape as SVG.G).children()) {
if (child.type === 'circle') {
const childClientID = child.attr('data-client-id');
if (state.elements.find((el: any) => el.clientID === childClientID).lock || false) {
continue;
}
child.center(child.cx() - prevXtl + x, child.cy() - prevYtl + y);
}
}

draggableInstance.attr('data-xtl', x);
draggableInstance.attr('data-ytl', y);
draggableInstance.attr('data-xbr', x + instance.width());
draggableInstance.attr('data-ybr', y + instance.height());

setupSkeletonEdges(shape as SVG.G, makeSVGFromTemplate(state.label.structure.svg));
}
}).on('dragend', (e: CustomEvent): void => {
if (aborted) {
return;
}

onDragEnd();
this.draggableShape = null;
const p1 = e.detail.handler.startPoints.point;
const p2 = e.detail.p;
const dx2 = (p1.x - p2.x) ** 2;
const dy2 = (p1.y - p2.y) ** 2;
if (Math.sqrt(dx2 + dy2) > 0) {
if (state.shapeType === 'mask') {
const { points } = state;
const x = Math.trunc(shape.x()) - this.geometry.offset;
const y = Math.trunc(shape.y()) - this.geometry.offset;
points.splice(-4);
points.push(x, y, x + shape.width() - 1, y + shape.height() - 1);
this.onEditDone(state, points);
} else if (state.shapeType === 'skeleton') {
const points = [];
state.elements.forEach((element: any) => {
const elementShape = (shape as SVG.G).children()
.find((child: SVG.Shape) => (
child.id() === `cvat_canvas_shape_${element.clientID}`
));

if (elementShape) {
points.push(...this.translateFromCanvas(readPointsFromShape(elementShape)));
}
});
this.onEditDone(state, points);
} else {
// these points does not take into account possible transformations, applied on the element
// so, if any (like rotation) we need to map them to canvas coordinate space
let points = readPointsFromShape(shape);
const { rotation } = shape.transform();
if (rotation) {
points = this.translatePointsFromRotatedShape(shape, points);
}

this.onEditDone(state, this.translateFromCanvas(points));
}

this.canvas.dispatchEvent(
new CustomEvent('canvas.dragshape', {
bubbles: false,
cancelable: true,
detail: {
id: state.clientID,
},
}),
);
}
}).on('dragabort', (): void => {
onDragEnd();
this.draggableShape = null;
aborted = true;
// disable internal drag events of SVG.js
window.dispatchEvent(new MouseEvent('mouseup'));
});
} else {
shape.removeClass('cvat_canvas_shape_draggable');

if (this.draggableShape === shape) {
draggableInstance.fire('dragabort');
}

draggableInstance.off('dragstart');
draggableInstance.off('dragmove');
draggableInstance.off('dragend');
draggableInstance.off('dragabort');
(draggableInstance as any).draggable(false);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the draggable method implementation.

The draggable method has been added to handle the drag functionality. This method is well-structured and covers various scenarios including different shape types and drag events. However, there are a few points to consider:

  1. Error handling: There is no error handling for the operations within the event listeners. Adding error handling could improve robustness.
  2. Complexity: The method is quite long and handles multiple aspects of the drag functionality. Consider breaking it down into smaller, more focused methods to improve readability and maintainability.
  3. Hard-coded values: The method contains hard-coded values (e.g., snapToGrid: 1). It might be beneficial to define these as constants or configurable properties to enhance flexibility.
+ // Consider adding error handling inside event listeners
+ try {
+     // existing code
+ } catch (error) {
+     console.error("Failed to handle drag event:", error);
+ }

+ // Suggest breaking down into smaller methods
+ private initializeDraggableInstance() {...}
+ private handleDragStart() {...}
+ private handleDragMove() {...}
+ private handleDragEnd() {...}

Committable suggestion was skipped due to low confidence.

Copy link

sonarcloud bot commented Jun 21, 2024

@bsekachev bsekachev merged commit 1dcb84a into develop Jun 24, 2024
33 checks passed
@bsekachev bsekachev deleted the bs/fixed_two_issues_canvas branch June 24, 2024 06:02
@cvat-bot cvat-bot bot mentioned this pull request Jul 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant