Skip to content

Commit

Permalink
Refactor and move canvas scroll calculations to getMouseRelativeCanvas
Browse files Browse the repository at this point in the history
  • Loading branch information
mohamedsalem401 committed Feb 3, 2025
1 parent 0c87fb7 commit 2ffbffd
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
7 changes: 6 additions & 1 deletion packages/core/src/canvas/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,12 @@ export default class CanvasModule extends Module<CanvasConfig> {
*/
getMouseRelativeCanvas(ev: MouseEvent | { clientX: number; clientY: number }, opts: any) {
const zoom = this.getZoomDecimal();
const { top = 0, left = 0 } = this.getCanvasView().getPosition(opts) ?? {};
const canvasPos = this.getCanvasView().getPosition(opts) ?? { top: 0, left: 0 };
const canvasScroll = this.getCanvasView().getCanvasScroll();
const { top, left } = {
top: canvasPos.top + canvasScroll.scrollTop,
left: canvasPos.left + canvasScroll.scrollLeft,
};

return {
y: ev.clientY * zoom + top,
Expand Down
31 changes: 18 additions & 13 deletions packages/core/src/canvas/view/CanvasView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,19 +459,7 @@ export default class CanvasView extends ModuleView<Canvas> {
const frame = this.frame?.el;
const winEl = el?.ownerDocument.defaultView;
const frEl = winEl ? (winEl.frameElement as HTMLElement) : frame;
const frmOff = this.offset(frEl || frame);
const canvasScroll = this.config.scrollableCanvas
? {
scrollTop: this.el.scrollTop,
scrollLeft: this.el.scrollLeft,
}
: { scrollTop: 0, scrollLeft: 0 };

this.frmOff = {
...frmOff,
top: frmOff.top + canvasScroll.scrollTop,
left: frmOff.left + canvasScroll.scrollLeft,
};
this.frmOff = this.offset(frEl || frame);
}

return this.frmOff;
Expand Down Expand Up @@ -575,6 +563,23 @@ export default class CanvasView extends ModuleView<Canvas> {
};
}

/**
* Returns the scroll position of the canvas.
*
* If the canvas is scrollable, returns the current `scrollTop` and `scrollLeft` values.
* Otherwise, returns an object with `scrollTop` and `scrollLeft` both set to 0.
*
* @returns An object containing the vertical and horizontal scroll positions.
*/
getCanvasScroll(): { scrollTop: number; scrollLeft: number } {
return this.config.scrollableCanvas
? {
scrollTop: this.el.scrollTop,
scrollLeft: this.el.scrollLeft,
}
: { scrollTop: 0, scrollLeft: 0 };
}

/**
* Update javascript of a specific component passed by its View
* @param {ModuleView} view Component's View
Expand Down

0 comments on commit 2ffbffd

Please sign in to comment.