From 93fb8f1c2ed787cedbe31545483460e76fbf972d Mon Sep 17 00:00:00 2001 From: "Elf M. Sternberg" Date: Sun, 17 Nov 2024 10:20:54 -0800 Subject: [PATCH] This is gonna need some cleanup, but it now correctly positions, repositions, reports, and maintains the position of the target *and* the pointer. --- src/lit-draggable.ts | 44 +++++++++++--------------------------------- 1 file changed, 11 insertions(+), 33 deletions(-) diff --git a/src/lit-draggable.ts b/src/lit-draggable.ts index bb181d3..e8ae049 100644 --- a/src/lit-draggable.ts +++ b/src/lit-draggable.ts @@ -1,4 +1,5 @@ import { ReactiveControllerHost, ReactiveController } from "lit"; +import { LitDragStart, LitDragging, LitDragEnd } from "./lit-events.js"; export type DragBoundaries = { top: number; @@ -15,37 +16,6 @@ export type DragAxes = "x" | "y" | "both" | "none"; export type DragBounds = HTMLElement | Partial | "parent" | "body" | (string & Record); -export interface LitDragEvent extends Event { - offsetX: number; - offsetY: number; - node: HTMLElement; -} - -function makeLitDragEvent(name: string): LitDragEvent { - class _LitDragEvent extends Event implements LitDragEvent { - static readonly eventName = name; - offsetX: number = 0; - offsetY: number = 0; - node: HTMLElement; - // container: HTMLElement; - constructor(source: LitDraggable) { - super(_LitDragEvent.eventName, { bubbles: true, composed: true }); - this.offsetX = source.translateX; - this.offsetY = source.translateY; - this.node = source.host; - // this.container = source.container; - } - } - - return _LitDragEvent as unknown as LitDragEvent; -} - -export const LitDragStart = makeLitDragEvent("lit-drag-start"); - -export const LitDragging = makeLitDragEvent("lit-dragging"); - -export const LitDragEnd: LitDragEvent = makeLitDragEvent("lit-drag-end"); - const defaultOptions: DragOptions = { preventSelect: true, }; @@ -61,6 +31,9 @@ export class LitDraggable implements ReactiveController { initialX = 0; initialY = 0; + handleOffsetX = 0; + handleOffsetY = 0; + dragging = false; currentSelect?: string; @@ -107,8 +80,12 @@ export class LitDraggable implements ReactiveController { document.body.style.userSelect = "none"; } + const hostRect = this.host.getBoundingClientRect(); + this.initialX = ev.clientX; this.initialY = ev.clientY; + this.handleOffsetX = this.initialX - hostRect.left; + this.handleOffsetY = this.initialY - hostRect.top; this.host.dataset.litDrag = "true"; this.host.dispatchEvent(new LitDragStart(this)); } @@ -142,8 +119,9 @@ export class LitDraggable implements ReactiveController { document.body.style.userSelect = this.currentSelect; this.currentSelect = undefined; } - this.initialX = this.translateX; - this.initialY = this.translateY; + + this.initialX = ev.clientX - this.handleOffsetX; + this.initialY = ev.clientY - this.handleOffsetY; this.host.dispatchEvent(new LitDragEnd(this)); this.host.style.removeProperty("transform"); }