All files / widgets sortable.ts

84.57% Statements 148/175
70.31% Branches 45/64
86.66% Functions 26/30
85.46% Lines 147/172

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        94x 94x   94x                   94x 94x 94x 94x           94x 94x   94x   94x                                                                                                                           94x                                                                                                                                       30x 30x 6x   24x       94x     3x 3x                         22x 22x   22x 22x 19x             19x 17x   17x 17x         22x 2x     20x   20x 20x 1x     19x     20x 20x 20x 20x 20x   20x 179x                                                                               94x 94x 94x         94x 94x   94x       94x     94x   3x     94x   94x 10x   94x           19x 19x 19x 19x   19x   19x 10x   10x         7x 7x   7x             7x             7x       7x 7x         19x 10x         10x 7x 7x   7x             7x             19x                                                                         19x 10x 10x   10x           7x       19x 19x 63x   63x   63x   63x 63x   63x   63x 63x   63x 63x           19x 63x 63x     19x   19x 3x 12x   12x   12x   12x 12x   12x   12x 12x 12x 12x       19x 3x 12x 12x       19x     94x         20x   20x 20x   20x 366x   20x 87x   20x 76x   20x 7x 7x         7x 7x     20x 4x 4x         4x 4x     20x 4x       20x 1x     20x 7x 1x   6x             7x 1x       20x                    
/**
 * @module Widgets
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import {
  addClasses,
  removeClasses,
  getBooleanData,
  setBooleanData,
  unsetBooleanData,
  delData,
  copyStyle,
  setNumericStyleJsVars,
} from "@lisn/utils/css-alter";
import { moveElement, swapElements, cloneElement } from "@lisn/utils/dom-alter";
import { waitForMeasureTime } from "@lisn/utils/dom-optimize";
import { getVisibleContentChildren } from "@lisn/utils/dom-query";
import {
  addEventListenerTo,
  removeEventListenerFrom,
  preventSelect,
  undoPreventSelect,
} from "@lisn/utils/event";
import { toInt } from "@lisn/utils/math";
import { validateString } from "@lisn/utils/validation";
 
import { wrapCallback } from "@lisn/modules/callback";
 
import {
  Widget,
  WidgetConfigValidatorObject,
  WidgetCallback,
  WidgetHandler,
  registerWidget,
  getDefaultWidgetSelector,
} from "@lisn/widgets/widget";
 
/**
 * Configures the given element as a {@link Sortable} widget.
 *
 * The Sortable widget allows the user to reorder elements by dragging and
 * dropping. It works on touch devices as well. However, it does not yet
 * support automatic scrolling when dragging beyond edge of screen on mobile
 * devices. For this, you may want to use
 * {@link https://github.com/SortableJS/Sortable | SortableJS} instead.
 *
 * The widget should have more than one draggable item.
 *
 * **IMPORTANT:** You should not instantiate more than one {@link Sortable}
 * widget on a given element. Use {@link Sortable.get} to get an existing
 * instance if any. If there is already a widget instance, it will be destroyed!
 *
 * -----
 *
 * You can use the following dynamic attributes or CSS properties in your
 * stylesheet:
 *
 * The following dynamic attributes are set on each item element:
 * - `data-lisn-is-draggable`: `"true"` or `"false"` (false if the item is disabled)
 *
 * -----
 *
 * To use with auto-widgets (HTML API) (see
 * {@link Settings.settings.autoWidgets | settings.autoWidgets}), the following
 * CSS classes or data attributes are recognized:
 * - `lisn-sortable` class or `data-lisn-sortable` attribute set on the
 *   container element that constitutes the sortable container.
 * - `lisn-sortable-item` class or `data-lisn-sortable-item` attribute set on
 *   elements that should act as the items.
 *
 * When using auto-widgets, the elements that will be used as items are
 * discovered in the following way:
 * 1. The top-level element that constitutes the widget is searched for any
 *    elements that contain the `lisn-sortable-item` class or
 *    `data-lisn-sortable-item` attribute. They do not have to be immediate
 *    children of the root element.
 * 2. If there are no such elements, all of the immediate children of the
 *    widget element (other than `script` and `style` elements) are taken as
 *    the items.
 *
 * @example
 * ```html
 * <div class="lisn-sortable">
 *   <div class="box">Item 1</div>
 *   <div class="box">Item 2</div>
 *   <div class="box">Item 3</div>
 *   <div class="box">Item 4</div>
 * </div>
 * ```
 */
export class Sortable extends Widget {
  /**
   * Disables the given item number. Note that item numbers start at 1.
   *
   * @param currentOrder If false (default), the item numbers refer to the
   *                     original order. If true, they refer to the current
   *                     document order.
   */
  readonly disableItem: (
    itemNum: number,
    currentOrder?: boolean,
  ) => Promise<void>;
 
  /**
   * Re-enables the given item number. Note that item numbers start at 1.
   *
   * @param currentOrder If false (default), the item numbers refer to the
   *                     original order. If true, they refer to the current
   *                     document order.
   */
  readonly enableItem: (
    itemNum: number,
    currentOrder?: boolean,
  ) => Promise<void>;
 
  /**
   * Re-enables the given item number if it is disabled, otherwise disables it.
   * Note that item numbers start at 1.
   *
   * @param currentOrder If false (default), the item numbers refer to the
   *                     original order. If true, they refer to the current
   *                     document order.
   */
  readonly toggleItem: (
    itemNum: number,
    currentOrder?: boolean,
  ) => Promise<void>;
 
  /**
   * Returns true if the given item number is disabled. Note that item numbers
   * start at 1.
   *
   * @param currentOrder If false (default), the item numbers refer to the
   *                     original order. If true, they refer to the current
   *                     document order.
   */
  readonly isItemDisabled: (itemNum: number, currentOrder?: boolean) => boolean;
 
  /**
   * The given handler will be called whenever the user moves an item to
   * another position. It will be called after the item is moved so
   * {@link getItems} called with `currentOrder = true` will return the updated
   * order.
   *
   * If the handler returns a promise, it will be awaited upon.
   */
  readonly onMove: (handler: WidgetHandler) => void;
 
  /**
   * Returns the item elements.
   *
   * @param currentOrder If false (default), returns the items in the
   *                     original order. If true, they are returned in the
   *                     current document order.
   */
  readonly getItems: (currentOrder?: boolean) => Element[];
 
  static get(element: Element): Sortable | null {
    const instance = super.get(element, DUMMY_ID);
    if (MH.isInstanceOf(instance, Sortable)) {
      return instance;
    }
    return null;
  }
 
  static register() {
    registerWidget(
      WIDGET_NAME,
      (element, config) => {
        if (!Sortable.get(element)) {
          return new Sortable(element, config);
        }
        return null;
      },
      configValidator,
    );
  }
 
  /**
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If there are less than 2 items given or found.
   */
  constructor(element: Element, config?: SortableConfig) {
    const destroyPromise = Sortable.get(element)?.destroy();
    super(element, { id: DUMMY_ID });
 
    const items = config?.items || [];
    if (!MH.lengthOf(items)) {
      items.push(
        ...MH.querySelectorAll(
          element,
          getDefaultWidgetSelector(PREFIX_ITEM__FOR_SELECT),
        ),
      );
 
      if (!MH.lengthOf(items)) {
        items.push(...MH.querySelectorAll(element, `[${MC.S_DRAGGABLE}]`));
 
        if (!MH.lengthOf(items)) {
          items.push(...getVisibleContentChildren(element));
        }
      }
    }
 
    if (MH.lengthOf(items) < 2) {
      throw MH.usageError("Sortable must have more than 1 item");
    }
 
    const methods = getMethods(this, items, config);
 
    (destroyPromise || MH.promiseResolve()).then(() => {
      if (this.isDestroyed()) {
        return;
      }
 
      init(this, element, items, methods);
    });
 
    this.disableItem = methods._disableItem;
    this.enableItem = methods._enableItem;
    this.toggleItem = methods._toggleItem;
    this.isItemDisabled = methods._isItemDisabled;
    this.onMove = methods._onMove;
 
    this.getItems = (currentOrder = false) =>
      currentOrder ? methods._getSortedItems() : [...items];
  }
}
 
/**
 * @interface
 */
export type SortableConfig = {
  /**
   * The elements that will be used as the draggable items.
   *
   * The widget should have more than one draggable item.
   *
   * If this is not specified, then
   * 1. The top-level element that constitutes the widget is searched for any
   *    elements that contain the `lisn-sortable-item` class or the
   *    `data-lisn-sortable-item` attribute. They do not have to be immediate
   *    children of the root element.
   * 2. If there are no such elements, all of the immediate children of the
   *    widget element (other than `script` and `style` elements) are taken as
   *    the items.
   */
  items?: Element[];
 
  /**
   * Whether to move the dragged item to before/after the drop target, or swap
   * it with the drop target.
   *
   * Note that the moving/swapping action is being done as the user is dragging
   * as soon as they drag over another item, so in order to achieve a swap
   * effect, the user needs to be able to drag an item from one location to
   * another without the path of the mouse crossing over all in-between items.
   *
   * @defaultValue "move";
   */
  mode?: "move" | "swap";
};
 
// --------------------
 
const WIDGET_NAME = "sortable";
const PREFIXED_NAME = MH.prefixName(WIDGET_NAME);
const PREFIX_IS_DRAGGABLE = MH.prefixName("is-draggable");
 
// Use different classes for styling items to the one used for auto-discovering
// them, so that re-creating existing widgets can correctly find the items to
// be used by the new widget synchronously before the current one is destroyed.
const PREFIX_ITEM = `${PREFIXED_NAME}__item`;
const PREFIX_ITEM__FOR_SELECT = `${PREFIXED_NAME}-item`;
 
const PREFIX_FLOATING_CLONE = `${PREFIXED_NAME}__ghost`;
 
// Only one Sortable widget per element is allowed, but Widget requires a
// non-blank ID.
const DUMMY_ID = PREFIXED_NAME;
 
// For HTML API only
const configValidator: WidgetConfigValidatorObject<SortableConfig> = {
  mode: (key, value) =>
    validateString(key, value, (v) => v === "swap" || v === "move"),
};
 
const touchMoveOptions = { passive: false, capture: true };
 
const isItemDraggable = (item: Element) =>
  getBooleanData(item, PREFIX_IS_DRAGGABLE);
 
const init = (
  widget: Sortable,
  element: Element,
  items: Element[],
  methods: ReturnType<typeof getMethods>,
) => {
  let currentDraggedItem: Element | null = null;
  let floatingClone: Element | null = null;
  let ignoreCancel = false;
  let grabOffset = [0, 0];
 
  const setIgnoreCancel = () => (ignoreCancel = true);
 
  const onDragStart = (event: Event) => {
    const currTarget = MH.currentTargetOf(event);
 
    if (
      MH.isElement(currTarget) &&
      isItemDraggable(currTarget) &&
      MH.isMouseEvent(event)
    ) {
      currentDraggedItem = currTarget;
      MH.setAttr(currTarget, MC.S_DRAGGABLE);
 
      Iif (MH.isTouchPointerEvent(event)) {
        const target = MH.targetOf(event);
        Iif (MH.isElement(target)) {
          target.releasePointerCapture(event.pointerId);
        }
      }
 
      addEventListenerTo(
        MH.getDoc(),
        MC.S_TOUCHMOVE,
        onTouchMove,
        touchMoveOptions,
      );
 
      waitForMeasureTime().then(() => {
        // Get pointer offset relative to the current item being dragged
        // regardless of what the event target is and what transforms is has
        // applied.
        const rect = MH.getBoundingClientRect(currTarget);
        grabOffset = [event.clientX - rect.left, event.clientY - rect.top];
      });
    }
  };
 
  const onDragEnd = (event: Event) => {
    Iif (ignoreCancel && event.type === MC.S_POINTERCANCEL) {
      ignoreCancel = false;
      return;
    }
 
    if (currentDraggedItem) {
      MH.unsetAttr(currentDraggedItem, MC.S_DRAGGABLE);
      currentDraggedItem = null;
 
      removeEventListenerFrom(
        MH.getDoc(),
        MC.S_TOUCHMOVE,
        onTouchMove,
        touchMoveOptions,
      );
 
      Iif (floatingClone) {
        moveElement(floatingClone);
        floatingClone = null;
      }
    }
  };
 
  const onTouchMove = (event: Event) => {
    Iif (MH.isTouchEvent(event) && MH.lengthOf(event.touches) === 1) {
      const parentEl = MH.parentOf(currentDraggedItem);
      Iif (parentEl && currentDraggedItem) {
        MH.preventDefault(event);
 
        const touch = event.touches[0];
        const clientX = touch.clientX;
        const clientY = touch.clientY;
 
        Iif (!floatingClone) {
          floatingClone = cloneElement(currentDraggedItem);
          addClasses(floatingClone, PREFIX_FLOATING_CLONE);
          copyStyle(currentDraggedItem, floatingClone, [
            "width",
            "height",
          ]).then(() => {
            Iif (floatingClone) {
              moveElement(floatingClone, { to: parentEl });
            }
          });
        }
 
        Iif (floatingClone) {
          setNumericStyleJsVars(
            floatingClone,
            {
              clientX: clientX - grabOffset[0],
              clientY: clientY - grabOffset[1],
            },
            { _units: "px" },
          );
        }
      }
    }
  };
 
  const onDragEnter = (event: Event) => {
    const currTarget = MH.currentTargetOf(event);
    const dragged = currentDraggedItem;
 
    if (
      (MH.isTouchPointerEvent(event) || event.type === MC.S_DRAGENTER) &&
      dragged &&
      MH.isElement(currTarget) &&
      currTarget !== dragged
    ) {
      methods._dragItemOnto(dragged, currTarget); // no need to await
    }
  };
 
  const setupEvents = () => {
    for (const item of items) {
      preventSelect(item);
 
      addEventListenerTo(item, MC.S_POINTERDOWN, onDragStart);
 
      addEventListenerTo(item, MC.S_DRAGSTART, setIgnoreCancel); // non-touch
 
      addEventListenerTo(item, MC.S_POINTERENTER, onDragEnter); // touch
      addEventListenerTo(item, MC.S_DRAGENTER, onDragEnter); // non-touch
 
      addEventListenerTo(item, MC.S_DRAGOVER, MH.preventDefault); // non-touch
 
      addEventListenerTo(item, MC.S_DRAGEND, onDragEnd); // non-touch
      addEventListenerTo(item, MC.S_DROP, onDragEnd); // non-touch
 
      addEventListenerTo(MH.getDoc(), MC.S_POINTERUP, onDragEnd);
      addEventListenerTo(MH.getDoc(), MC.S_POINTERCANCEL, onDragEnd);
    }
  };
 
  // SETUP ------------------------------
 
  for (const item of items) {
    addClasses(item, PREFIX_ITEM);
    setBooleanData(item, PREFIX_IS_DRAGGABLE);
  }
 
  widget.onEnable(setupEvents);
 
  widget.onDisable(() => {
    for (const item of items) {
      undoPreventSelect(item);
 
      removeEventListenerFrom(item, MC.S_POINTERDOWN, onDragStart);
 
      removeEventListenerFrom(item, MC.S_DRAGSTART, setIgnoreCancel);
 
      removeEventListenerFrom(item, MC.S_POINTERENTER, onDragEnter);
      removeEventListenerFrom(item, MC.S_DRAGENTER, onDragEnter);
 
      removeEventListenerFrom(item, MC.S_DRAGOVER, MH.preventDefault);
 
      removeEventListenerFrom(item, MC.S_POINTERUP, onDragEnd);
      removeEventListenerFrom(item, MC.S_POINTERCANCEL, onDragEnd);
      removeEventListenerFrom(item, MC.S_DRAGEND, onDragEnd);
      removeEventListenerFrom(item, MC.S_DROP, onDragEnd);
    }
  });
 
  widget.onDestroy(async () => {
    for (const item of items) {
      await removeClasses(item, PREFIX_ITEM);
      await delData(item, PREFIX_IS_DRAGGABLE);
    }
  });
 
  setupEvents();
};
 
const getMethods = (
  widget: Sortable,
  items: Element[],
  config: SortableConfig | undefined,
) => {
  const doSwap = config?.mode === "swap";
 
  const disabledItems: Record<number, boolean> = {};
  const callbacks = MH.newSet<WidgetCallback>();
 
  const getSortedItems = () =>
    [...items].sort((a, b) => (MH.isNodeBAfterA(a, b) ? -1 : 1));
 
  const getOrigItemNumber = (itemNum: number, currentOrder = false) =>
    currentOrder ? items.indexOf(getSortedItems()[itemNum - 1]) + 1 : itemNum;
 
  const isItemDisabled = (itemNum: number, currentOrder = false) =>
    disabledItems[getOrigItemNumber(itemNum, currentOrder)] === true;
 
  const disableItem = async (itemNum: number, currentOrder = false) => {
    itemNum = getOrigItemNumber(toInt(itemNum), currentOrder);
    Iif (widget.isDisabled() || itemNum < 1 || itemNum > MH.lengthOf(items)) {
      return;
    }
 
    // set immediately for toggle to work without awaiting on it
    disabledItems[itemNum] = true;
    await unsetBooleanData(items[itemNum - 1], PREFIX_IS_DRAGGABLE);
  };
 
  const enableItem = async (itemNum: number, currentOrder = false) => {
    itemNum = getOrigItemNumber(toInt(itemNum), currentOrder);
    Iif (widget.isDisabled() || !isItemDisabled(itemNum)) {
      return;
    }
 
    // set immediately for toggle to work without awaiting on it
    disabledItems[itemNum] = false;
    await setBooleanData(items[itemNum - 1], PREFIX_IS_DRAGGABLE);
  };
 
  const toggleItem = (itemNum: number, currentOrder = false) =>
    isItemDisabled(itemNum, currentOrder)
      ? enableItem(itemNum, currentOrder)
      : disableItem(itemNum, currentOrder);
 
  const onMove = (handler: WidgetHandler) =>
    callbacks.add(wrapCallback(handler));
 
  // This is internal only for now...
  const dragItemOnto = async (dragged: Element, draggedOver: Element) => {
    if (doSwap) {
      await swapElements(dragged, draggedOver, { ignoreMove: true });
    } else {
      await moveElement(dragged, {
        to: draggedOver,
        position: MH.isNodeBAfterA(dragged, draggedOver) ? "after" : "before",
        ignoreMove: true,
      });
    }
 
    for (const callback of callbacks) {
      await callback.invoke(widget);
    }
  };
 
  return {
    _getSortedItems: getSortedItems,
    _disableItem: disableItem,
    _enableItem: enableItem,
    _toggleItem: toggleItem,
    _isItemDisabled: isItemDisabled,
    _onMove: onMove,
    _dragItemOnto: dragItemOnto,
  };
};