All files / src/list SortableList.ts

89.37% Statements 673/753
88.78% Branches 95/107
95.83% Functions 23/24
89.37% Lines 673/753

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 75493x 124x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 32x 32x 32x 32x 32x 32x 232x 232x 232x 232x 232x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 93x 140x 140x 140x 140x 421x 421x 421x 140x 140x 93x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 14x 14x 19x 14x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x                                                 11x 11x 11x 11x 11x 11x 11x 11x 19x 19x 19x 19x 19x 19x 19x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 30x 5x 5x 5x 5x 30x 5x 5x 5x 5x 16x 16x 16x 5x   5x 5x 5x 5x 19x 14x       14x 14x 14x 14x 14x 18x 18x 18x 18x 18x 16x 16x 18x 2x 2x 2x 2x 14x 14x 14x     14x 11x       11x 11x 11x 11x 11x 11x 11x 93x 93x 83x 83x 83x 83x 83x 83x 83x 83x 93x 55x 55x 133x 133x 133x 133x 55x 55x 55x 55x 55x 23x 45x 45x 45x 45x 45x 45x 45x 45x 45x       45x 45x 45x 45x 6x 6x 6x 6x 6x 55x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 1x 32x 31x 31x 93x 93x 93x 66x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 93x 93x 93x 93x 93x 93x 93x 93x 55x 55x 55x 55x 55x 55x 55x 37x 37x 37x 37x 55x 18x 18x 18x 18x 93x 22x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 93x 93x 93x 93x 93x 93x 93x 93x 17x       17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 93x 17x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x                       93x 93x 93x 93x 93x 93x 65x 65x 65x 16x 16x 12x 12x 65x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 11x 8x 8x 8x 8x 8x 8x 8x 8x 8x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 11x 11x 11x 11x 65x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 19x 60x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 60x 58x 58x 58x 58x 17x 17x 17x 58x 1x 1x 1x 1x 1x 1x 60x 55x 55x 55x 54x 54x 54x 54x 54x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 23x 23x 23x 23x 23x 23x 55x 55x 16x 16x 16x 16x 16x 16x 55x 55x 55x 55x 55x 55x                     5x 93x 93x 93x 93x 93x 93x 93x 65x 65x 65x 65x 93x 93x                 93x 93x 93x 93x 93x 93x 93x 93x 16x 16x 16x 16x 16x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 9x 9x 9x 9x 9x 9x 9x 9x 4x 4x 4x 4x 4x 4x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 93x 16x 16x 10x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x                         93x 93x 93x 93x 93x 93x 93x 93x 93x  
import { css, html, TemplateResult } from 'lit';
import { property } from 'lit/decorators.js';
import { CustomEventType } from '../interfaces';
import { RapidElement } from '../RapidElement';
 
/**
 * A simple list that can be sorted by dragging
 */
 
// how far we have to drag before it starts
const DRAG_THRESHOLD = 2;
 
// padding around container for external drag detection
const EXTERNAL_DRAG_PADDING = 50;
 
export class SortableList extends RapidElement {
  originalDownDisplay: string;
  static get styles() {
    return css`
      :host {
        margin: auto;
      }
 
      .container {
        user-select: none;
        position: relative;
        display: grid;
        grid-template-columns: 1fr;
      }
 
      .container.horizontal {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
      }
 
      .dragging {
        background: var(--color-selection);
      }
 
      .slot {
        flex-grow: 1;
      }
 
      slot > * {
        user-select: none;
        touch-action: none;
      }
 
      temba-icon {
        opacity: 0.1;
        padding: 0.2em 0.5em;
        transition: all 300ms ease-in-out;
      }
    `;
  }
 
  @property({ type: String })
  draggingId: string;
 
  @property({ type: Boolean })
  horizontal: boolean = false;
 
  @property({ type: String })
  dropTargetId: string;
 
  @property({ type: String })
  dragHandle: string;
 
  @property({ type: String })
  gap: string = '0em';
 
  @property({ type: Boolean })
  externalDrag: boolean = false;
 
  /**
   * Optional callback to allow parent components to customize the ghost node.
   * Called after the ghost node is cloned but before it is appended to the DOM.
   */
  @property({ attribute: false })
  prepareGhost?: (ghost: HTMLElement) => void;
 
  ghostElement: HTMLDivElement = null;
  downEle: HTMLDivElement = null;
  originalElementRect: DOMRect = null; // Store viewport dimensions for ghost
  originalLayoutSize: { width: number; height: number } = null; // Store layout dimensions for placeholders
  originalDragIndex: number = -1; // Store original index before moving element
  xOffset = 0;
  yOffset = 0;
  yDown = 0;
  xDown = 0;
 
  draggingIdx = -1;
  draggingEle = null;
  dropPlaceholder: HTMLDivElement = null;
  pendingDropIndex = -1;
  pendingTargetElement: HTMLElement = null;
  pendingInsertAfter: boolean = null;
  isExternalDrag = false;
 
  private clickBlocker: ((e: MouseEvent) => void) | null = null;
 
  public constructor() {
    super();
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.handleMouseUp = this.handleMouseUp.bind(this);
    this.handleMouseDown = this.handleMouseDown.bind(this);
    this.handleTouchMove = this.handleTouchMove.bind(this);
    this.handleTouchEnd = this.handleTouchEnd.bind(this);
    this.handleTouchStart = this.handleTouchStart.bind(this);
  }
 
  private getSortableElements(): Element[] {
    const eles = this.shadowRoot
      .querySelector('slot')
      .assignedElements()
      .filter(
        (ele) =>
          ele.classList.contains('sortable') &&
          !ele.classList.contains('drop-placeholder')
      );
    return eles;
  }
 
  private isMouseOverContainer(mouseX: number, mouseY: number): boolean {
    const container = this.shadowRoot.querySelector('.container');
    if (!container) return false;
 
    const rect = container.getBoundingClientRect();
    // add some padding to make it easier to stay within the container
    return (
      mouseX >= rect.left - EXTERNAL_DRAG_PADDING &&
      mouseX <= rect.right + EXTERNAL_DRAG_PADDING &&
      mouseY >= rect.top - EXTERNAL_DRAG_PADDING &&
      mouseY <= rect.bottom + EXTERNAL_DRAG_PADDING
    );
  }
 
  private cloneElementWithState(element: HTMLElement): HTMLElement {
    // First create a basic clone
    const clone = element.cloneNode(true) as HTMLElement;
 
    // Helper function to copy form element values recursively
    const copyFormValues = (original: HTMLElement, cloned: HTMLElement) => {
      try {
        // Copy input values
        const originalInputs = original.querySelectorAll(
          'input, textarea, select'
        );
        const clonedInputs = cloned.querySelectorAll('input, textarea, select');
 
        originalInputs.forEach((originalInput, index) => {
          const clonedInput = clonedInputs[index] as
            | HTMLInputElement
            | HTMLTextAreaElement
            | HTMLSelectElement;
          if (clonedInput) {
            if (originalInput instanceof HTMLInputElement) {
              const originalHtmlInput = originalInput as HTMLInputElement;
              const clonedHtmlInput = clonedInput as HTMLInputElement;

              if (
                originalHtmlInput.type === 'checkbox' ||
                originalHtmlInput.type === 'radio'
              ) {
                clonedHtmlInput.checked = originalHtmlInput.checked;
              } else {
                clonedHtmlInput.value = originalHtmlInput.value;
              }
            } else if (originalInput instanceof HTMLTextAreaElement) {
              (clonedInput as HTMLTextAreaElement).value = originalInput.value;
            } else if (originalInput instanceof HTMLSelectElement) {
              (clonedInput as HTMLSelectElement).selectedIndex =
                originalInput.selectedIndex;
            }
          }
        });

        // Copy properties from all custom elements that might have a value property
        const allOriginalElements = Array.from(original.querySelectorAll('*'));
        const allClonedElements = Array.from(cloned.querySelectorAll('*'));

        allOriginalElements.forEach((originalEl, index) => {
          const clonedEl = allClonedElements[index];
          if (clonedEl && originalEl) {
            // Special handling for temba components
            if (
              originalEl.tagName &&
              originalEl.tagName.toLowerCase().startsWith('temba-')
            ) {
              try {
                // Copy common temba component properties
                const tembaProps = [
                  'value',
                  'values',
                  'selectedValue',
                  'checked',
                  'selected',
                  'textContent'
                ];
                tembaProps.forEach((prop) => {
                  if (
                    prop in originalEl &&
                    (originalEl as any)[prop] !== undefined
                  ) {
                    (clonedEl as any)[prop] = (originalEl as any)[prop];
                  }
                });
 
                // Copy all attributes for temba components to preserve state
                Array.from(originalEl.attributes).forEach((attr) => {
                  clonedEl.setAttribute(attr.name, attr.value);
                });
              } catch (e) {
                // Ignore errors when copying temba properties
              }
            } else {
              // Try to copy value property for other elements
              try {
                if (
                  'value' in originalEl &&
                  (originalEl as any).value !== undefined
                ) {
                  (clonedEl as any).value = (originalEl as any).value;
                }
              } catch (e) {
                // Ignore errors when copying properties
              }
 
              // Copy data attributes that might contain state
              try {
                Array.from(originalEl.attributes).forEach((attr) => {
                  if (
                    attr.name.startsWith('data-') ||
                    attr.name.startsWith('aria-')
                  ) {
                    clonedEl.setAttribute(attr.name, attr.value);
                  }
                });
              } catch (e) {
                // Ignore errors when copying attributes
              }
            }
          }
        });
      } catch (e) {
        // If anything fails, just return the basic clone
        console.warn('Failed to copy form values in cloneElementWithState:', e);
      }
    };
 
    // Copy form values for the root element and all descendants
    copyFormValues(element, clone);
 
    return clone;
  }

  public getIds() {
    return this.getSortableElements().map((ele) => ele.id);
  }

  private getRowIndex(id: string): number {
    return this.getSortableElements().findIndex((ele) => ele.id === id);
  }
 
  private getDropTargetInfo(
    mouseX: number,
    mouseY: number
  ): { element: HTMLDivElement; insertAfter: boolean } | null {
    const elements = this.getSortableElements().filter(
      (ele) => ele.id !== this.draggingEle?.id
    );
 
    if (elements.length === 0) return null;
 
    if (this.horizontal) {
      // For horizontal (possibly wrapping) layouts, compare in reading order:
      // row first (Y), then column (X).  Items in DOM order may span
      // multiple rows when the container uses flex-wrap.
      for (let i = 0; i < elements.length; i++) {
        const ele = elements[i];
        const rect = ele.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
 
        // Mouse is on a row above this element — insert before it
        if (mouseY < rect.top) {
          return { element: ele as HTMLDivElement, insertAfter: false };
        }
 
        // Mouse is on the same row — compare X within the row
        if (mouseY < rect.bottom) {
          if (mouseX < centerX) {
            return { element: ele as HTMLDivElement, insertAfter: false };
          }
        }
        // Mouse is below this element's row — continue to next element
      }
      // If we're past all elements, insert after the last one
      return {
        element: elements[elements.length - 1] as HTMLDivElement,
        insertAfter: true
      };
    } else {
      // For vertical layout, find the insertion point based on mouse Y position
      for (let i = 0; i < elements.length; i++) {
        const ele = elements[i];
        const rect = ele.getBoundingClientRect();
        const centerY = rect.top + rect.height / 2;
 
        if (mouseY < centerY) {
          // Insert before this element
          return { element: ele as HTMLDivElement, insertAfter: false };
        }
      }
      // If we're past all elements, insert after the last one
      return {
        element: elements[elements.length - 1] as HTMLDivElement,
        insertAfter: true
      };
    }
  }
 
  /**
   * Creates the persistent placeholder element (once per drag).
   */
  private ensurePlaceholder() {
    if (this.dropPlaceholder) return;
 
    this.dropPlaceholder = document.createElement('div');
    this.dropPlaceholder.className = 'drop-placeholder sortable';
 
    if (this.originalLayoutSize) {
      const size = this.originalLayoutSize;
      this.dropPlaceholder.style.width = size.width + 'px';
      this.dropPlaceholder.style.height = size.height + 'px';
      this.dropPlaceholder.style.minHeight = size.height + 'px';
      this.dropPlaceholder.style.borderRadius = 'var(--curvature)';
      this.dropPlaceholder.style.flexShrink = '0';
      this.dropPlaceholder.style.background = '#f3f4f6';
      this.dropPlaceholder.style.outline = '2px dashed #d1d5db';
      this.dropPlaceholder.style.outlineOffset = '-2px';
    }
  }
 
  /**
   * Inserts the placeholder adjacent to targetElement.
   * Reuses the existing element — insertAdjacentElement atomically
   * moves it if it is already in the DOM.
   */
  private insertPlaceholder(targetElement: HTMLElement, insertAfter: boolean) {
    if (!targetElement || !this.draggingEle) return;
    if (targetElement === this.draggingEle) return;
 
    this.ensurePlaceholder();
 
    if (insertAfter) {
      targetElement.insertAdjacentElement('afterend', this.dropPlaceholder);
    } else {
      targetElement.insertAdjacentElement('beforebegin', this.dropPlaceholder);
    }
  }
 
  private hideDropPlaceholder() {
    if (this.dropPlaceholder) {
      this.dropPlaceholder.remove();
      this.dropPlaceholder = null;
    }
  }
 
  private showInitialPlaceholder() {
    if (!this.downEle || !this.originalElementRect) return;
 
    this.ensurePlaceholder();
 
    // Insert the placeholder right after the hidden original element
    this.downEle.insertAdjacentElement('afterend', this.dropPlaceholder);
  }
 
  /**
   * Shared drag-start logic for both mouse and touch.
   * Returns true if a drag target was found and state was initialised.
   */
  private beginDrag(
    target: HTMLElement,
    clientX: number,
    clientY: number
  ): boolean {
    // if we have a drag handle, only allow dragging from that element
    if (this.dragHandle) {
      if (!target.classList.contains(this.dragHandle)) {
        return false;
      }
    }
 
    const ele = target.closest('.sortable') as HTMLDivElement;
    if (!ele) return false;
 
    this.downEle = ele;
    this.draggingId = ele.id;
    this.draggingIdx = this.getRowIndex(ele.id);
    this.draggingEle = ele;

    const rect = ele.getBoundingClientRect();
    this.originalElementRect = rect;
    this.originalLayoutSize = {
      width: ele.offsetWidth,
      height: ele.offsetHeight
    };
    this.xOffset = clientX - rect.left;
    this.yOffset = clientY - rect.top;
    this.yDown = clientY;
    this.xDown = clientX;
 
    return true;
  }
 
  private handleMouseDown(event: MouseEvent) {
    if (
      this.beginDrag(event.target as HTMLElement, event.clientX, event.clientY)
    ) {
      event.preventDefault();
      event.stopPropagation();
      document.addEventListener('mousemove', this.handleMouseMove);
      document.addEventListener('mouseup', this.handleMouseUp);
    }
  }
 
  /* c8 ignore start -- touch-only handlers */
  private handleTouchStart(event: TouchEvent) {
    const touch = event.touches[0];
    if (!touch) return;
    if (
      this.beginDrag(event.target as HTMLElement, touch.clientX, touch.clientY)
    ) {
      event.stopPropagation();
      document.addEventListener('touchmove', this.handleTouchMove, {
        passive: false
      });
      document.addEventListener('touchend', this.handleTouchEnd);
      document.addEventListener('touchcancel', this.handleTouchEnd);
    }
  }
  /* c8 ignore stop */

  /**
   * Shared drag-move logic for both mouse and touch.
   */
  private processDragMove(clientX: number, clientY: number) {
    if (
      !this.ghostElement &&
      this.downEle &&
      (Math.abs(clientY - this.yDown) > DRAG_THRESHOLD ||
        Math.abs(clientX - this.xDown) > DRAG_THRESHOLD)
    ) {
      this.fireCustomEvent(CustomEventType.DragStart, {
        id: this.downEle.id
      });
 
      // Capture the original index BEFORE hiding the element
      this.originalDragIndex = this.getRowIndex(this.downEle.id);
 
      // Create a clone of the element to use as the ghost
      this.ghostElement = this.cloneElementWithState(
        this.downEle
      ) as HTMLDivElement;
 
      // Hide the original element during dragging using inline styles
      this.originalDownDisplay = this.downEle.style.display;
      this.downEle.style.display = 'none';
 
      // Style the clone as a ghost
      this.ghostElement.classList.add('ghost');
 
      // Detect ancestor scale transform (e.g. zoom) by comparing viewport
      // to layout dimensions, so the ghost renders content at the right scale
      const rect = this.originalElementRect;
      const layoutSize = this.originalLayoutSize;
      const ancestorScale =
        layoutSize.width > 0 ? rect.width / layoutSize.width : 1;
      const hasAncestorScale = Math.abs(ancestorScale - 1) > 0.001;
 
      this.ghostElement.style.position = 'fixed';
      this.ghostElement.style.left = clientX - this.xOffset + 'px';
      this.ghostElement.style.top = clientY - this.yOffset + 'px';
      this.ghostElement.style.zIndex = '99999';
      this.ghostElement.style.opacity = '0.8';
 
      if (hasAncestorScale) {
        // Use layout dimensions with ancestor scale so content renders correctly
        this.ghostElement.style.width = layoutSize.width + 'px';
        this.ghostElement.style.height = layoutSize.height + 'px';
        this.ghostElement.style.transform = `scale(${ancestorScale * 1.03})`;
        this.ghostElement.style.transformOrigin = '0 0';
      } else {
        this.ghostElement.style.width = rect.width + 'px';
        this.ghostElement.style.height = rect.height + 'px';
        this.ghostElement.style.transform = 'scale(1.03)';
      }
 
      // allow component to customize the ghost node
      if (this.prepareGhost) {
        this.prepareGhost(this.ghostElement);
      }
 
      // Add the clone to document.body for dragging
      document.body.appendChild(this.ghostElement);
 
      // Show initial placeholder in the original position to maintain layout
      this.showInitialPlaceholder();
 
      // Add global click blocker when drag starts
      if (!this.clickBlocker) {
        this.clickBlocker = (e: MouseEvent) => {
          e.stopPropagation();
          e.preventDefault();
        };
        // Use capture phase to intercept clicks before they reach any elements
        document.addEventListener('click', this.clickBlocker, true);
      }
    }
 
    if (this.ghostElement) {
      this.ghostElement.style.left = clientX - this.xOffset + 'px';
      this.ghostElement.style.top = clientY - this.yOffset + 'px';
 
      // check if the drag is over the container (only if external dragging is allowed)
      const isOverContainer = this.externalDrag
        ? this.isMouseOverContainer(clientX, clientY)
        : true; // always consider "over container" if external drag is disabled
 
      // detect transition between internal and external drag (only if allowed)
      if (this.externalDrag && !isOverContainer && !this.isExternalDrag) {
        // transitioning to external drag
        this.isExternalDrag = true;
        this.hideDropPlaceholder();
 
        // hide the ghost element when dragging externally
        if (this.ghostElement) {
          this.ghostElement.style.display = 'none';
        }
 
        this.fireCustomEvent(CustomEventType.DragExternal, {
          id: this.downEle.id,
          mouseX: clientX,
          mouseY: clientY
        });
      } else if (this.externalDrag && isOverContainer && this.isExternalDrag) {
        // transitioning back to internal drag
        this.isExternalDrag = false;
 
        // show the ghost element again when dragging internally
        if (this.ghostElement) {
          this.ghostElement.style.display = 'block';
        }
 
        this.fireCustomEvent(CustomEventType.DragInternal, {
          id: this.downEle.id
        });
      }
 
      // only show drop placeholder and calculate drop position if internal drag
      if (!this.isExternalDrag) {
        // Detach the placeholder before measuring so its presence cannot
        // shift element positions (e.g. flex-wrap reflow) and feed back
        // into the calculation, which would cause oscillation.
        if (this.dropPlaceholder) {
          this.dropPlaceholder.remove();
        }
 
        const targetInfo = this.getDropTargetInfo(clientX, clientY);
        if (targetInfo) {
          const { element: targetElement, insertAfter } = targetInfo;
          const targetIdx = this.getRowIndex(targetElement.id);
 
          // Use the original drag index we captured before moving the element
          const originalDragIdx = this.originalDragIndex;
 
          // Calculate where the dragged element will end up in the final array
          // targetIdx is the position of target element in current DOM (missing dragged element)
 
          let dropIdx;
          if (targetIdx < originalDragIdx) {
            // Target is before the original drag position - moving backward
            dropIdx = insertAfter ? targetIdx + 1 : targetIdx;
          } else {
            // Target was originally after the drag position - moving forward
            dropIdx = insertAfter ? targetIdx : targetIdx - 1;
          }
 
          // Only update state when the logical position changes
          if (dropIdx !== this.pendingDropIndex) {
            this.dropTargetId = targetElement.id;
            this.pendingDropIndex = dropIdx;
            this.pendingTargetElement = targetElement;
            this.pendingInsertAfter = insertAfter;
          }
 
          // Re-insert placeholder at the (possibly unchanged) position.
          // insertPlaceholder reuses the same DOM element so there is
          // no destroy/create flash.
          this.insertPlaceholder(
            this.pendingTargetElement,
            this.pendingInsertAfter
          );
        } else {
          this.hideDropPlaceholder();
          this.dropTargetId = null;
          this.pendingDropIndex = -1;
          this.pendingTargetElement = null;
          this.pendingInsertAfter = null;
        }
      } else {
        // external drag - continue firing external drag events with updated position
        this.fireCustomEvent(CustomEventType.DragExternal, {
          id: this.downEle.id,
          mouseX: clientX,
          mouseY: clientY
        });
      }
    }
  }

  private handleMouseMove(event: MouseEvent) {
    this.processDragMove(event.clientX, event.clientY);
  }
 
  /* c8 ignore next 6 -- touch-only */
  private handleTouchMove(event: TouchEvent) {
    const touch = event.touches[0];
    if (!touch) return;
    event.preventDefault();
    this.processDragMove(touch.clientX, touch.clientY);
  }
 
  /**
   * Shared drag-end logic for both mouse and touch.
   */
  private processDragEnd(clientX: number, clientY: number) {
    if (this.draggingId && this.ghostElement) {
      // Remove the ghost clone from document.body
      if (this.ghostElement) {
        this.ghostElement.remove();
      }

      // Restore visibility of the original element by clearing inline styles
      if (this.downEle) {
        this.downEle.style.display = this.originalDownDisplay;
      }
 
      // Clear visual effects before firing events
      this.hideDropPlaceholder();
 
      // fire the order changed event only when dropped if we have a valid drop position
      if (
        !this.isExternalDrag &&
        this.pendingDropIndex >= 0 &&
        this.pendingTargetElement
      ) {
        // Use the original drag index we captured before hiding the element
        const originalDragIdx = this.originalDragIndex;
 
        // use swap-based logic - report which indexes need to be swapped
        const fromIdx = originalDragIdx;
        const toIdx = this.pendingDropIndex;
 
        // only fire if the position actually changed AND this is not an external drag
        // External drags are handled by external drop handlers
        if (fromIdx !== toIdx && !this.isExternalDrag) {
          this.fireCustomEvent(CustomEventType.OrderChanged, {
            swap: [fromIdx, toIdx]
          });
        }
      }
 
      this.fireCustomEvent(CustomEventType.DragStop, {
        id: this.draggingId,
        isExternal: this.isExternalDrag,
        mouseX: clientX,
        mouseY: clientY
      });
 
      this.draggingId = null;
      this.dropTargetId = null;
      this.downEle = null;
      this.originalElementRect = null;
      this.originalDragIndex = -1;
      this.pendingDropIndex = -1;
      this.pendingTargetElement = null;
      this.pendingInsertAfter = null;
      this.isExternalDrag = false;
 
      // Clear the ghost reference since we removed it
      this.ghostElement = null;
 
      this.hideDropPlaceholder();
 
      // Keep the click blocker active for a short time after drop
      if (this.clickBlocker) {
        // We'll clean it up after a timeout
        setTimeout(() => {
          if (this.clickBlocker) {
            document.removeEventListener('click', this.clickBlocker, true);
            this.clickBlocker = null;
          }
        }, 100);
      }
    }
  }
 
  private handleMouseUp(evt: MouseEvent) {
    if (this.draggingId && this.ghostElement) {
      evt.preventDefault();
      evt.stopPropagation();
    }
    this.processDragEnd(evt.clientX, evt.clientY);
    document.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('mouseup', this.handleMouseUp);
    this.dispatchEvent(new Event('change'));
  }
 
  /* c8 ignore start -- touch-only */
  private handleTouchEnd(evt: TouchEvent) {
    const touch = evt.changedTouches[0];
    const clientX = touch?.clientX ?? 0;
    const clientY = touch?.clientY ?? 0;
    this.processDragEnd(clientX, clientY);
    document.removeEventListener('touchmove', this.handleTouchMove);
    document.removeEventListener('touchend', this.handleTouchEnd);
    document.removeEventListener('touchcancel', this.handleTouchEnd);
    this.dispatchEvent(new Event('change'));
  }
  /* c8 ignore stop */

  /** Show or hide the original element that is being dragged. */
  public setOriginalVisible(visible: boolean): void {
    if (!this.downEle) return;
    this.downEle.style.display = visible ? this.originalDownDisplay : 'none';
  }

  public render(): TemplateResult {
    return html`
      <div
        class="container ${this.horizontal ? 'horizontal' : ''}"
        style="gap: ${this.gap}"
      >
        <slot
          @mousedown=${this.handleMouseDown}
          @touchstart=${this.handleTouchStart}
        ></slot>
      </div>
    `;
  }
}