All files / triggers view-trigger.ts

75% Statements 45/60
60% Branches 21/35
91.66% Functions 11/12
75.43% Lines 43/57

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                    94x 94x       94x 94x 94x 94x 94x         94x             94x 94x   94x   94x               94x                                                                                                                                                                                                                                                         94x       188x     9x                                     11x 11x   11x           11x   11x       11x           11x 11x 11x   11x 11x         11x 11x 11x         11x 11x 11x                 11x     11x                                                                                                                             94x 9x   9x     1x     9x 1x     9x       94x                                                  
/**
 * @module Triggers
 *
 * @categoryDescription View
 * {@link ViewTrigger} allows you to run actions when the viewport's scroll
 * position relative to a given target or offset from top/bottom/left/right is
 * one of the matching "views" (at/above/below/left/right), and undo those
 * actions when the viewport's "view" is not matching.
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { ViewTarget, View, CommaSeparatedStr } from "@lisn/globals/types";
 
import { hasClass } from "@lisn/utils/css-alter";
import { insertGhostClone, tryWrap } from "@lisn/utils/dom-alter";
import { waitForReferenceElement } from "@lisn/utils/dom-search";
import { formatAsString } from "@lisn/utils/text";
import {
  validateStrList,
  validateString,
  validateNumList,
} from "@lisn/utils/validation";
import {
  getOppositeViews,
  isValidView,
  isValidScrollOffset,
} from "@lisn/utils/views";
 
import { Action } from "@lisn/actions/action";
import { Animate } from "@lisn/actions/animate";
import { AnimatePlay } from "@lisn/actions/animate-play";
 
import { ViewWatcher } from "@lisn/watchers/view-watcher";
 
import {
  registerTrigger,
  Trigger,
  TriggerConfig,
} from "@lisn/triggers/trigger";
 
import { WidgetConfigValidatorFunc } from "@lisn/widgets/widget";
 
import debug from "@lisn/debug/debug";
 
/**
 * {@link ViewTrigger} allows you to run actions when the viewport's scroll
 * position relative to a given target or offset from top/bottom/left/right is
 * one of the matching "views" (at/above/below/left/right), and undo those
 * actions when the viewport's "view" is not matching.
 *
 * -------
 *
 * To use with auto-widgets (HTML API), see {@link registerTrigger} for the
 * specification.
 *
 * - Arguments (optional): One or more (comma-separated)
 *   {@link ViewTriggerConfig.views | views}. Default is "at".
 *
 * - Additional trigger options (see {@link ViewTriggerConfig}):
 *   - `target`: A string element specification for an element (see
 *     {@link Utils.getReferenceElement | getReferenceElement}) or a
 *     {@link Types.ScrollOffsetSpec | ScrollOffsetSpec}.
 *   - `root`: A string element specification. See
 *     {@link Utils.getReferenceElement | getReferenceElement}.
 *   - `rootMargin`: A string, a (comma or space-separated) list of margins.
 *   - `threshold`: A number or a (comma-separated) list of numbers.
 *
 * @example
 * Show the element when it's in the viewport, hide otherwise.
 *
 * ```html
 * <div data-lisn-on-view="at @show"></div>
 * ```
 *
 * @example
 * Same as above. "views" is optional and defaults to "at".
 *
 * ```html
 * <div data-lisn-on-view="@show"></div>
 * ```
 *
 * @example
 * As above but using a CSS class instead of data attribute:
 *
 * ```html
 * <div class="lisn-on-view--@show"></div>
 * ```
 *
 * @example
 * Show the element 1000ms after the first time it enters the viewport.
 *
 * ```html
 * <div data-lisn-on-view="@show +once +delay=1000"></div>
 * ```
 *
 * @example
 * Add class `seen` the first time the element enters the viewport, and play
 * the animations defined on it 1000ms after each time it enters the viewport,
 * reverse the animations as soon as it goes out of view.
 *
 * ```html
 * <div data-lisn-on-view="@add-class: seen +once ;
 *                         @animate +do-delay=1000"
 * ></div>
 * ```
 *
 * @example
 * Add class `seen` when the viewport is at or below the element (element
 * above viewport), remove it when the viewport is above the element.
 * Element going to the left or right of the viewport will not trigger the
 * action. See {@link getOppositeViews}:
 *
 * ```html
 * <div data-lisn-on-view="at,below @add-class: seen"></div>
 * ```
 *
 * @example
 * Add class `cls` when the viewport is above or to the left the element
 * (element below or to the right of the viewport), remove it when the
 * viewport is either at, below or to the right of the element.
 *
 * ```html
 * <div data-lisn-on-view="above,left @add-class: cls"></div>
 * ```
 *
 * @example
 * Hide the element when the viewport is above the next element with class
 * `section`, show it when the viewport is below or at the target element.
 *
 * ```html
 * <div data-lisn-on-view="above @hide +target=next.section"></div>
 * <div class="section"></div>
 * ```
 *
 * @example
 * As above, but using `data-lisn-ref` attribute instead of class selector.
 *
 * ```html
 * <div data-lisn-on-view="above @hide +target=next-section"></div>
 * <div data-lisn-ref="section"></div>
 * ```
 *
 * @example
 * Open the {@link Widgets.Openable | Openable} widget configured for this
 * element when the viewport is 75% down from the top of the page.
 *
 * ```html
 * <div data-lisn-on-view="@open +target=top:75%"></div>
 * ```
 *
 * @example
 * As above but using a custom {@link Watchers/ViewWatcher.ViewWatcherConfig.root | root},
 * {@link Watchers/ViewWatcher.ViewWatcherConfig.rootMargin | rootMargin} and
 * {@link Watchers/ViewWatcher.ViewWatcherConfig.threshold | threshold} for the
 * {@link ViewWatcher}.
 *
 * ```html
 * <div data-lisn-on-view="@open
 *                         +target=top:75%
 *                         +root=#root
 *                         +root-margin=10% 20% 10% 20%
 *                         +threshold=0.3"
 * ></div>
 * ```
 *
 * @category View
 */
export class ViewTrigger extends Trigger {
  readonly getConfig: () => ViewTriggerConfig;
 
  static register() {
    registerTrigger(
      "view",
      (element, args, actions, config) => {
        return new ViewTrigger(
          element,
          actions,
          MH.assign(config, {
            views: validateStrList("views", args, isValidView),
          } as const),
        );
      },
      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?: ViewTriggerConfig) {
    config ??= {};
    super(element, actions, config);
 
    const logger = debug
      ? new debug.Logger({
          name: `ViewTrigger-${formatAsString(element)}`,
        })
      : null;
 
    this.getConfig = () => MH.copyObject(config);
 
    Iif (!MH.lengthOf(actions)) {
      return;
    }
 
    const watcher = ViewWatcher.reuse({
      root: config.root,
      rootMargin: config.rootMargin?.replace(/,/g, " "),
      threshold: config.threshold,
    });
 
    const target = config.target ?? element;
    const views = config.views || MC.S_AT;
    const oppositeViews = getOppositeViews(views);
 
    const setupWatcher = (target: ViewTarget) => {
      Iif (!MH.lengthOf(oppositeViews)) {
        debug: logger?.debug6("Trigger can never be reversed, running now");
        // The action is never undone
        this.run();
      } else {
        debug: logger?.debug6("Setting up trigger", views, oppositeViews);
        watcher.onView(target, this.run, { views });
        watcher.onView(target, this.reverse, { views: oppositeViews });
      }
    };
 
    // See comment in globals/settings under contentWrappingAllowed
    let willAnimate = false;
    for (const action of actions) {
      Iif (
        MH.isInstanceOf(action, Animate) ||
        MH.isInstanceOf(action, AnimatePlay)
      ) {
        willAnimate = true;
        break;
      }
    }
 
    Iif (willAnimate) {
      setupRepresentative(element).then(setupWatcher);
    } else {
      setupWatcher(target);
    }
  }
}
 
/**
 * @category View
 * @interface
 */
export type ViewTriggerConfig = TriggerConfig & {
  /**
   * The {@link View} to use as the trigger.
   * See also {@link Watchers/ViewWatcher.OnViewOptions | OnViewOptions}
   *
   * Actions will be "done" when the view matches the given spec and "undone"
   * otherwise. What the opposite views are depends on the given view. E.g. for
   * "at", opposites are all the other ones;  for "above", the opposite ones
   * are "at" and "below"; for "at,above" opposite is "below", etc.
   *
   * @defaultValue "at"
   */
  views?: CommaSeparatedStr<View> | View[];
 
  /**
   * The target to use for the ViewWatcher. It can be a string offset
   * specification.
   * See {@link Watchers/ViewWatcher.OnViewOptions | OnViewOptions}
   *
   * @defaultValue The element on which the {@link ViewTrigger} is defined
   */
  target?: ViewTarget;
 
  /**
   * The root to pass to the {@link ViewWatcher}.
   * See also {@link Watchers/ViewWatcher.ViewWatcherConfig | ViewWatcherConfig}
   *
   * @defaultValue {@link ViewWatcher} default
   */
  root?: Element | null;
 
  /**
   * The root margin to pass to the {@link ViewWatcher}.
   * See also {@link Watchers/ViewWatcher.ViewWatcherConfig | ViewWatcherConfig}
   *
   * It can be either space-separated or comma-separated.
   *
   * @defaultValue {@link ViewWatcher} default
   */
  rootMargin?: string;
 
  /**
   * The threshold to pass to the {@link ViewWatcher}.
   * See also {@link Watchers/ViewWatcher.ViewWatcherConfig | ViewWatcherConfig}
   *
   * @defaultValue {@link ViewWatcher} default
   */
  threshold?: number | number[];
};
 
// ----------
 
const newConfigValidator: WidgetConfigValidatorFunc<
  Omit<ViewTriggerConfig, "views">
> = (element) => {
  return {
    target: (key, value) =>
      MH.isLiteralString(value) && isValidScrollOffset(value)
        ? value
        : MH.isLiteralString(value)
          ? waitForReferenceElement(value, element).then((v) => v ?? undefined) // ugh, typescript...
          : undefined,
    root: (key, value) =>
      MH.isLiteralString(value)
        ? waitForReferenceElement(value, element).then((v) => v ?? undefined) // ugh, typescript...
        : undefined,
    rootMargin: validateString,
    threshold: (key, value) => validateNumList(key, value),
  };
};
 
const setupRepresentative = async (element: Element): Promise<Element> => {
  let target: Element | null = await tryWrap(element);
  Iif (!target) {
    // Not allowed to wrap. Create a dummy hidden clone that's not animated and
    // position it absolutely in a wrapper of size 0 that's inserted just
    // before the actual element, so that the hidden clone overlaps the actual
    // element's regular (pre-transformed) position.
 
    const prev = element.previousElementSibling;
    const prevChild = MH.childrenOf(prev)[0];
    if (
      prev &&
      hasClass(prev, MC.PREFIX_WRAPPER) &&
      prevChild &&
      hasClass(prevChild, MC.PREFIX_GHOST)
    ) {
      // Already cloned by a previous animate action?
      target = prevChild;
    } else {
      target = (await insertGhostClone(element))._clone;
    }
  }
 
  return target;
};