All files / triggers scroll-trigger.ts

90.32% Statements 28/31
54.54% Branches 6/11
100% Functions 7/7
90% Lines 27/30

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                  94x 94x               94x       94x 94x       94x   94x                                                                                                                                                                                 94x       188x     5x                                             10x   10x 10x         10x 10x   10x       10x 10x 10x   10x       9x           9x 9x                                                                                         94x 5x   5x 1x          
/**
 * @module Triggers
 *
 * @categoryDescription Scroll
 * {@link ScrollTrigger} allows you to run actions when the user scrolls a
 * target element (or the main scrollable element) in a given direction, and
 * undo those actions when they scroll in the opposite direction.
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import {
  XYDirection,
  CommaSeparatedStr,
  ScrollTarget,
} from "@lisn/globals/types";
 
import {
  getOppositeXYDirections,
  isValidXYDirection,
} from "@lisn/utils/directions";
import { waitForReferenceElement } from "@lisn/utils/dom-search";
import { validateStrList, validateNumber } from "@lisn/utils/validation";
 
import { Action } from "@lisn/actions/action";
 
import { ScrollWatcher } from "@lisn/watchers/scroll-watcher";
 
import {
  registerTrigger,
  Trigger,
  TriggerConfig,
} from "@lisn/triggers/trigger";
 
import { WidgetConfigValidatorFunc } from "@lisn/widgets/widget";
 
/**
 * {@link ScrollTrigger} allows you to run actions when the user scrolls a
 * target element (or the main scrollable element) in a given direction, and
 * undo those actions when they scroll in the opposite direction.
 *
 * -------
 *
 * To use with auto-widgets (HTML API), see {@link registerTrigger} for the
 * specification.
 *
 * - Arguments (optional): One or more (comma-separated)
 *   {@link ScrollTriggerConfig.directions | scroll directions}.
 *   Note that if you do not specify any directions, then the trigger will just
 *   run once, on the first scroll in any direction.
 *
 * - Additional trigger options (see {@link ScrollTriggerConfig}):
 *   - `scrollable`: A string element specification.
 *      See {@link Utils.getReferenceElement | getReferenceElement}.
 *   - `threshold`: A number.
 *
 * @example
 * Show the element when the user scrolls the page up, hide when scrolling
 * down. User scrolling left or right not trigger the action. See
 * {@link getOppositeXYDirections}:
 *
 * ```html
 * <div data-lisn-on-scroll="up @show"></div>
 * ```
 *
 * @example
 * As above, but using a CSS class instead of data attribute:
 *
 * ```html
 * <div class="lisn-on-scroll--up@show"></div>
 * ```
 *
 * @example
 * Show the element 1000ms after the first time the user scrolls the page up:
 *
 * ```html
 * <div data-lisn-on-scroll="up @show +once +delay=1000"></div>
 * ```
 *
 * @example
 * Add class `scrolled` the first time the user scrolls the page in any
 * direction (note that the `once` option is implied here), and show the
 * element 1000ms after each time the user scrolls the page up, hide it as soon
 * as they scroll down:
 *
 * ```html
 * <div data-lisn-on-scroll="@add-class: scrolled ;
 *                           up @show +do-delay=1000"
 * ></div>
 * ```
 *
 * @example
 * When the user scrolls up or down the closest ancestor with class `section`,
 * then add classes `c1` and `c2` and enable trigger `my-trigger` defined on
 * this same element; undo all of that when scrolling right or left:
 *
 * ```html
 * <div class="section">
 *   <div data-lisn-on-scroll="up,down @add-class: c1,c2 @enable: my-trigger +scrollable=this.section"
 *      data-lisn-on-run="@show +id=my-trigger"
 *   ></div>
 *</div>
 * ```
 *
 * @example
 * As above, but using `data-lisn-ref` attribute instead of class selector.
 *
 * ```html
 * <div data-lisn-ref="section">
 *   <div data-lisn-on-scroll="up,down @add-class: c1,c2 @enable: my-trigger +scrollable=this-section"
 *      data-lisn-on-run="@show +id=my-trigger"
 *   ></div>
 *</div>
 * ```
 *
 * @category Scroll
 */
export class ScrollTrigger extends Trigger {
  readonly getConfig: () => ScrollTriggerConfig;
 
  static register() {
    registerTrigger(
      MC.S_SCROLL,
      (element, args, actions, config) => {
        return new ScrollTrigger(
          element,
          actions,
          MH.assign(config, {
            directions: validateStrList("directions", args, isValidXYDirection),
          }),
        );
      },
      newConfigValidator,
    );
  }
 
  /**
   * If no actions are supplied, nothing is done.
   *
   * @throws {@link Errors.LisnUsageError | LisnUsageError}
   *                If the config is invalid.
   */
  constructor(
    element: Element,
    actions: Action[],
    config?: ScrollTriggerConfig,
  ) {
    config ??= {};
 
    let directions = config.directions;
    Iif (!directions) {
      config.once = true;
      directions = [MC.S_UP, MC.S_DOWN, MC.S_LEFT, MC.S_RIGHT];
    }
 
    super(element, actions, config);
    this.getConfig = () => MH.copyObject(config);
 
    Iif (!MH.lengthOf(actions)) {
      return;
    }
 
    const watcher = ScrollWatcher.reuse();
    const scrollable = config.scrollable;
    const threshold = config.threshold;
 
    const oppositeDirections = directions
      ? getOppositeXYDirections(directions)
      : [];
 
    watcher.onScroll(this.run, {
      directions,
      scrollable,
      threshold,
    });
 
    if (MH.lengthOf(oppositeDirections)) {
      watcher.onScroll(this.reverse, {
        directions: oppositeDirections,
        scrollable,
        threshold,
      });
    }
  }
}
 
/**
 * @category Scroll
 * @interface
 */
export type ScrollTriggerConfig = TriggerConfig & {
  /**
   * The {@link XYDirection}s to use as the trigger.
   * See also {@link Watchers/ScrollWatcher.OnScrollOptions | OnScrollOptions}
   *
   * Actions will be "done" when the scroll direction is one of the given ones
   * and "undone" when it's the opposite direction. E.g. for "up" the opposite
   * is "down".
   */
  directions?: CommaSeparatedStr<XYDirection> | XYDirection[];
 
  /**
   * The scrolling element target to use for the ScrollWatcher.
   * See {@link Watchers/ScrollWatcher.OnScrollOptions | OnScrollOptions}
   *
   * @defaultValue {@link ScrollWatcher} default, the main scrolling element
   */
  scrollable?: ScrollTarget;
 
  /**
   * The scroll threshold to pass to the {@link ScrollWatcher}.
   * See also {@link Watchers/ScrollWatcher.OnScrollOptions | OnScrollOptions}
   *
   * @defaultValue {@link ScrollWatcher} default
   */
  threshold?: number;
};
 
// --------------------
 
const newConfigValidator: WidgetConfigValidatorFunc<
  Omit<ScrollTriggerConfig, "directions">
> = (element) => {
  return {
    scrollable: (key, value) =>
      MH.isLiteralString(value)
        ? waitForReferenceElement(value, element).then((v) => v ?? undefined) // ugh, typescript...
        : undefined,
    threshold: validateNumber,
  };
};