Skip to content

An open source design system that's fully customizable and agent ready

TypeScript
7.7 KB
Raw Blame
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
 * @file nativeScroll.ts
 * @input An element a touch landed on
 * @output Exports createNativeScrollProbe (the NativeScrollProbe a host gives
 *   each touch, and each wheel gesture without the touch-action narrowing)
 *   and parseTouchAction
 * @position DOM half of the scroll coordination in packages/core/src/gestures
 *
 * Answers one question for a recognizer without letting it touch the DOM:
 * would the browser scroll something if this finger moved that way?
 *
 * The browser scrolls the innermost scroller that has room, then chains
 * outward, so the answer is "yes" while ANY scroller under the touch can
 * still move in that direction, with three narrowings that match the
 * browser's own:
 *
 * - `touch-action` between the touch target and a scroller must allow the
 *   axis, or the browser will not pan that scroller with a finger;
 * - an `overscroll-behavior` other than `auto` on the axis stops the chain at
 *   that scroller (a sheet body with `contain` never scrolls the page);
 * - a finger moving down scrolls content toward its START (scrollTop
 *   decreasing), and horizontally the range follows the writing direction
 *   (RTL `scrollLeft` runs from minus the overflow to zero).
 *
 * Styles are read once per touch, on the first question; scroll offsets are
 * read fresh on every question, since a native scroll moves them.
 */

import {isRtlElement} from '../hooks/isRtlElement';
import type {NativeScrollProbe} from './types';
import {parentAcrossShadow} from '../utils/flatTree';
import {
  isInsideScrollView,
  parseTouchAction,
  rootOverflow,
  SCROLLABLE_OVERFLOW as SCROLLABLE,
  type AllowedPans,
} from '../utils/scrollView';
import {isElement} from '../utils/nodeType';

export {parentAcrossShadow};

export {parseTouchAction};
export type {AllowedPans};

interface ChainEntry {
  readonly element: Element;
  readonly x: boolean;
  readonly y: boolean;
  readonly isRtl: boolean;
  readonly stopsX: boolean;
  readonly stopsY: boolean;
}

const EDGE_TOLERANCE = 1;

interface Chain {
  readonly entries: ChainEntry[];
  /** touch-action allows some pan all the way up. */
  readonly allowsPan: boolean;
}

function buildChain(target: Element, readsTouchAction: boolean): Chain {
  const doc = target.ownerDocument;
  const view = doc.defaultView;
  if (view == null) {
    return {entries: [], allowsPan: false};
  }
  const root = doc.scrollingElement ?? doc.documentElement;
  const chain: ChainEntry[] = [];
  let allowX = true;
  let allowY = true;
  let reachedRoot = false;
  for (
    let node: Node | null = target;
    node != null;
    node = parentAcrossShadow(node)
  ) {
    if (!isElement(node)) {
      continue;
    }
    const style = view.getComputedStyle(node);
    if (readsTouchAction) {
      const pans = parseTouchAction(style.touchAction || 'auto');
      allowX &&= pans.x;
      allowY &&= pans.y;
    }
    const isRoot = node === root || node === doc.documentElement;
    if (isRoot) {
      reachedRoot = true;
    }
    const overflowX = isRoot ? rootOverflow(doc, 'x') : style.overflowX;
    const overflowY = isRoot ? rootOverflow(doc, 'y') : style.overflowY;
    const scrollsX = SCROLLABLE.has(overflowX);
    const scrollsY = SCROLLABLE.has(overflowY);
    if (scrollsX || scrollsY) {
      const element = isRoot ? root : node;
      const [behaviorX, behaviorY] = overscrollBehavior(style);
      chain.push({
        element,
        x: scrollsX && allowX,
        y: scrollsY && allowY,
        // The writing direction through core's one helper.
        isRtl: isRtlElement(element as HTMLElement),
        stopsX: behaviorX !== 'auto',
        stopsY: behaviorY !== 'auto',
      });
    }
    if (isRoot) {
      break;
    }
  }
  if (!reachedRoot && isElement(root)) {
    chain.push({
      element: root,
      x: allowX && SCROLLABLE.has(rootOverflow(doc, 'x')),
      y: allowY && SCROLLABLE.has(rootOverflow(doc, 'y')),
      isRtl: false,
      stopsX: false,
      stopsY: false,
    });
  }
  return {entries: chain, allowsPan: allowX || allowY};
}

/** `overscroll-behavior` per axis, from the longhands or the shorthand. */
function overscrollBehavior(style: CSSStyleDeclaration): [string, string] {
  const x = style.overscrollBehaviorX;
  const y = style.overscrollBehaviorY;
  if (x !== '' && y !== '' && x != null && y != null) {
    return [x, y];
  }
  const [first = 'auto', second = first] = (
    style.getPropertyValue('overscroll-behavior') || 'auto'
  )
    .trim()
    .split(/\s+/);
  return [x || first, y || second];
}

function canMoveY(element: Element, dy: number): boolean {
  if (element.scrollHeight - element.clientHeight <= EDGE_TOLERANCE) {
    return false;
  }
  return dy > 0
    ? element.scrollTop > EDGE_TOLERANCE - 0.5
    : element.scrollTop <
        element.scrollHeight - element.clientHeight - EDGE_TOLERANCE + 0.5;
}

function canMoveX(
  entry: Pick<ChainEntry, 'element' | 'isRtl'>,
  dx: number,
): boolean {
  const {element} = entry;
  const overflow = element.scrollWidth - element.clientWidth;
  if (overflow <= EDGE_TOLERANCE) {
    return false;
  }
  const min = entry.isRtl ? -overflow : 0;
  const max = entry.isRtl ? 0 : overflow;
  // A finger moving right drags the content right: scrollLeft decreases.
  return dx > 0
    ? element.scrollLeft > min + EDGE_TOLERANCE - 0.5
    : element.scrollLeft < max - EDGE_TOLERANCE + 0.5;
}

/**
 * Whether `element` itself scrolls natively now for a finger moving by
 * (dx, dy). It uses the probe's own test of each scroller: overflow that
 * scrolls on that axis, and room past the edge tolerance. The position must
 * also be short of the end it moves toward, a right-to-left range included.
 * A wheel moves the content the other way, so pass its deltas negated.
 */
export function canElementScroll(
  element: Element,
  dx: number,
  dy: number,
): boolean {
  const view = element.ownerDocument.defaultView;
  if (view == null) {
    return false;
  }
  const style = view.getComputedStyle(element);
  if (dy !== 0 && SCROLLABLE.has(style.overflowY) && canMoveY(element, dy)) {
    return true;
  }
  return (
    dx !== 0 &&
    SCROLLABLE.has(style.overflowX) &&
    canMoveX({element, isRtl: isRtlElement(element as HTMLElement)}, dx)
  );
}

/**
 * A probe of the native scrollers under `target`. A wheel scrolls whatever
 * `touch-action` says, which narrows only a finger's pan: a wheel's probe
 * passes `readsTouchAction: false`.
 */
export function createNativeScrollProbe(
  target: unknown,
  {readsTouchAction = true}: {readsTouchAction?: boolean} = {},
): NativeScrollProbe {
  let chain: Chain | null = null;
  const getChain = (): ChainEntry[] => {
    chain ??= isElement(target)
      ? buildChain(target, readsTouchAction)
      : {entries: [], allowsPan: false};
    return chain.entries;
  };
  return {
    canScroll(dx: number, dy: number): boolean {
      const ax = Math.abs(dx);
      const ay = Math.abs(dy);
      // The minor axis of a mostly-straight drag is the hand's wobble, not
      // a direction: the browser locks to the major one.
      const considerX = ax > 0 && ax >= ay / 2;
      const considerY = ay > 0 && ay >= ax / 2;
      for (const entry of getChain()) {
        if (considerY && entry.y && canMoveY(entry.element, dy)) {
          return true;
        }
        if (considerX && entry.x && canMoveX(entry, dx)) {
          return true;
        }
        const stops =
          (!considerX || entry.stopsX) && (!considerY || entry.stopsY);
        if (stops && (entry.stopsX || entry.stopsY)) {
          return false;
        }
      }
      return false;
    },
    get allowsNativePan(): boolean {
      getChain();
      return chain?.allowsPan === true;
    },
    get isInsideScroller(): boolean {
      return (
        isElement(target) && isInsideScrollView(target, {readsTouchAction})
      );
    },
  };
}