All files / triggers pointer-trigger.ts

97.77% Statements 44/45
82.35% Branches 14/17
100% Functions 16/16
97.61% Lines 41/42

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                                    94x 94x   94x 94x 94x   94x             94x                                                                                                                                                                           94x       188x     4x                               7x 7x 7x   7x                                                                                                                                                                       94x       188x     4x                               7x 7x 7x   7x                                                                                                                                                                 94x       188x     4x                               7x 7x 7x   7x                                                                 94x     12x   12x 3x             94x             21x       21x 21x             21x 7x   14x 14x     21x                        
/**
 * @module Triggers
 *
 * @categoryDescription Pointer
 * {@link ClickTrigger} allows you to run actions when a user clicks a target
 * element (first time and every other time, i.e. odd number of click), and undo
 * those actions when a user clicks the target element again (or every even
 * number of clicks). It always acts as a toggle.
 *
 * {@link PressTrigger} allows you to run actions when the user presses and
 * holds a pointing device (or their finger) on a target element, and undo those
 * actions when they release their pointing device or lift their finger off.
 *
 * {@link HoverTrigger} allows you to run actions when the user hovers overs a
 * target element, and undo those actions when their pointing device moves off
 * the target. On touch devices it acts just like {@link PressTrigger}.
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { waitForReferenceElement } from "@lisn/utils/dom-search";
import { omitKeys } from "@lisn/utils/misc";
import { validateBoolean } from "@lisn/utils/validation";
 
import {
  PointerWatcher,
  OnPointerHandler,
} from "@lisn/watchers/pointer-watcher";
 
import { Action } from "@lisn/actions/action";
 
import {
  registerTrigger,
  Trigger,
  TriggerConfig,
} from "@lisn/triggers/trigger";
 
import { WidgetConfigValidatorFunc } from "@lisn/widgets/widget";
 
/**
 * {@link ClickTrigger} allows you to run actions when a user clicks a target
 * element (first time and every other time, i.e. odd number of click), and
 * undo them when a user clicks the target element again (or every even number
 * of clicks). It always acts as a toggle.
 *
 * -------
 *
 * To use with auto-widgets (HTML API), see {@link registerTrigger} for the
 * specification.
 *
 * - Arguments: none
 * - Additional trigger options (see {@link PointerTriggerConfig}):
 *   - `target`: A string element specification.
 *     See {@link Utils.getReferenceElement | getReferenceElement}.
 *   - `prevent-default`: A boolean.
 *   - `prevent-select`: A boolean.
 *
 * @example
 * Add classes `active` and `toggled-on` when the user clicks the element
 * (first time and every other time, i.e. odd number of click), remove them
 * when clicked again (or even number of click);
 *
 * ```html
 * <div data-lisn-on-click="@add-class: active,toggled-on"></div>
 * ```
 *
 * @example
 * As above, but using a CSS class instead of data attribute:
 *
 * ```html
 * <div class="lisn-on-click--@add-class: active,toggled-on"></div>
 * ```
 *
 * @example
 * Play the animations on the element 1000ms after the first time the user
 * clicks it.
 *
 * ```html
 * <div data-lisn-on-click="@animate +once +delay=1000"></div>
 * ```
 *
 * @example
 * Add class `visited` the first time the user clicks the element, and play or
 * reverse the animations on the element 1000ms after each time the user clicks
 * it.
 *
 * ```html
 * <div data-lisn-on-click="@add-class: visited +once ;
 *                          @animate +delay=1000"
 * ></div>
 * ```
 *
 * @example
 * When the user clicks the next element with class `box` then add classes `c1`
 * and `c2` to the element (that the trigger is defined on) and enable trigger
 * `my-trigger` defined on this same element; undo all of that on even number
 * of clicks on the reference box element.
 *
 * ```html
 * <div data-lisn-on-click="@add-class: c1,c2 @enable: my-trigger +target=next.box"
 *      data-lisn-on-run="@show +id=my-trigger"
 * ></div>
 * <div class="box"></div>
 * ```
 *
 * @example
 * As above, but using `data-lisn-ref` attribute instead of class selector.
 *
 * ```html
 * <div data-lisn-on-click="@add-class: c1,c2 @enable: my-trigger +target=next-box"
 *      data-lisn-on-run="@show +id=my-trigger"
 * ></div>
 * <div data-lisn-ref="box"></div>
 * ```
 *
 * @category Pointer
 */
export class ClickTrigger extends Trigger {
  readonly getConfig: () => PointerTriggerConfig;
 
  static register() {
    registerTrigger(
      MC.S_CLICK,
      (element, args, actions, config) =>
        new ClickTrigger(element, actions, config),
      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?: PointerTriggerConfig,
  ) {
    config ??= {};
    super(element, actions, config);
    this.getConfig = () => MH.copyObject(config);
 
    setupWatcher(this, element, actions, config, MC.S_CLICK);
  }
}
 
/**
 * {@link PressTrigger} allows you to run actions when the user presses and
 * holds a pointing device (or their finger) on a target element, and undo
 * those actions when they release their pointing device or lift their finger
 * off.
 *
 * -------
 *
 * To use with auto-widgets (HTML API), see {@link registerTrigger} for the
 * specification.
 *
 * - Arguments: none
 * - Additional trigger options (see {@link PointerTriggerConfig}):
 *   - `target`: A string element specification.
 *     See {@link Utils.getReferenceElement | getReferenceElement}.
 *   - `prevent-default`: boolean
 *   - `prevent-select`: boolean
 *
 * @example
 * Add classes `active` and `pressed` when the user presses and holds (with
 * mouse, finger or any pointer) the element, remove them when they release
 * the mouse.
 *
 * ```html
 * <div data-lisn-on-press="@add-class: active,pressed"></div>
 * ```
 *
 * @example
 * As above, but using a CSS class instead of data attribute:
 *
 * ```html
 * <div class="lisn-on-press--@add-class: active,pressed"></div>
 * ```
 *
 * @example
 * Play the animations on the element 1000ms after the first time the user
 * presses on the element it.
 *
 * ```html
 * <div data-lisn-on-press="@animate +once +delay=1000"></div>
 * ```
 *
 * @example
 * Add class `pressed` the first time the user presses on the element, and
 * play the animations on the element while the user is pressing on the element
 * with a delay of 100ms, reverse the animations as soon as the user releases
 * the mouse.
 *
 * ```html
 * <div data-lisn-on-click="@add-class: pressed +once ;
 *                          @animate +do-delay=100"
 * ></div>
 * ```
 *
 * @example
 * When the user presses and holds the next element with class `box` then add
 * classes `c1` and `c2` to the element (that the trigger is defined on) and
 * enable trigger `my-trigger` defined on this same element; undo all of that
 * when they release the mouse (or lift their finger/pointer device) from the
 * reference box element.
 *
 * ```html
 * <div data-lisn-on-press="@add-class: c1,c2 @enable: my-trigger +target=next.box"
 *      data-lisn-on-run="@show +id=my-trigger"
 * ></div>
 * <div class="box"></div>
 * ```
 *
 * @example
 * As above, but using `data-lisn-ref` attribute instead of class selector.
 *
 * ```html
 * <div data-lisn-on-press="@add-class: c1,c2 @enable: my-trigger +target=next-box"
 *      data-lisn-on-run="@show +id=my-trigger"
 * ></div>
 * <div data-lisn-ref="box"></div>
 * ```
 *
 * @category Pointer
 */
export class PressTrigger extends Trigger {
  readonly getConfig: () => PointerTriggerConfig;
 
  static register() {
    registerTrigger(
      MC.S_PRESS,
      (element, args, actions, config) =>
        new PressTrigger(element, actions, config),
      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?: PointerTriggerConfig,
  ) {
    config ??= {};
    super(element, actions, config);
    this.getConfig = () => MH.copyObject(config);
 
    setupWatcher(this, element, actions, config, MC.S_PRESS);
  }
}
 
/**
 * {@link HoverTrigger} allows you to run actions when the user hovers overs
 * a target element, and undo those actions when their pointing device moves
 * off the target. On touch devices it acts just like {@link PressTrigger}.
 *
 * -------
 *
 * To use with auto-widgets (HTML API), see {@link registerTrigger} for the
 * specification.
 *
 * - Arguments: none
 * - Additional trigger options (see {@link PointerTriggerConfig}):
 *   - `target`: A string element specification.
 *     See {@link Utils.getReferenceElement | getReferenceElement}.
 *   - `prevent-default`: boolean
 *   - `prevent-select`: boolean
 *
 * @example
 * Add classes `active` and `hovered` when the user hovers over the element,
 * remove them otherwise.
 *
 * ```html
 * <div data-lisn-on-hover="@add-class: active,hovered"></div>
 * ```
 *
 * @example
 * As above, but using a CSS class instead of data attribute:
 *
 * ```html
 * <div class="lisn-on-press--@add-class: active,hovered"></div>
 * ```
 *
 * @example
 * Play the animations on the element 1000ms after the first time the user
 * hovers over the element it.
 *
 * ```html
 * <div data-lisn-on-hover="@animate +once +delay=1000"></div>
 * ```
 *
 * @example
 * Add class `hovered` the first time the user hovers over the element, and
 * play the animations on the element while the user is hovering over the
 * element with a delay of 100ms, reverse the animations as soon as the user
 * mouse leaves the element.
 *
 * ```html
 * <div data-lisn-on-click="@add-class: hovered +once ;
 *                          @animate +do-delay=100"
 * ></div>
 * ```
 *
 * @example
 * When the user hovers over the next element with class `box` then add classes
 * `c1` and `c2` to the element (that the trigger is defined on) and enable
 * trigger `my-trigger` defined on this same element; undo all of that when
 * their pointing device (or finger) moves off the reference element.
 *
 * ```html
 * <div data-lisn-on-hover="@add-class: c1,c2 @enable: my-trigger +target=next.box"
 *      data-lisn-on-run="@show +id=my-trigger"
 * ></div>
 * <div class="box"></div>
 * ```
 *
 * @example
 * As above, but using `data-lisn-ref` attribute instead of class selector.
 *
 * ```html
 * <div data-lisn-on-hover="@add-class: c1,c2 @enable: my-trigger +target=next-box"
 *      data-lisn-on-run="@show +id=my-trigger"
 * ></div>
 * <div data-lisn-ref="box"></div>
 * ```
 *
 * @category Pointer
 */
export class HoverTrigger extends Trigger {
  readonly getConfig: () => PointerTriggerConfig;
 
  static register() {
    registerTrigger(
      MC.S_HOVER,
      (element, args, actions, config) =>
        new HoverTrigger(element, actions, config),
      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?: PointerTriggerConfig,
  ) {
    config ??= {};
    super(element, actions, config);
    this.getConfig = () => MH.copyObject(config);
 
    setupWatcher(this, element, actions, config, MC.S_HOVER);
  }
}
 
/**
 * @category Pointer
 * @interface
 */
export type PointerTriggerConfig = TriggerConfig & {
  /**
   * The target to use for the hover action.
   *
   * @defaultValue The element on which the {@link Trigger} is defined
   */
  target?: Element;
 
  /**
   * See {@link Watchers/PointerWatcher.OnPointerOptions | OnPointerOptions}.
   *
   * @defaultValue {@link PointerWatcher} default, false
   */
  preventDefault?: boolean;
 
  /**
   * See {@link Watchers/PointerWatcher.OnPointerOptions | OnPointerOptions}.
   *
   * @defaultValue {@link PointerWatcher} default, true
   */
  preventSelect?: boolean;
};
 
// --------------------
 
const newConfigValidator: WidgetConfigValidatorFunc<PointerTriggerConfig> = (
  element,
) => {
  return {
    target: (key, value) =>
      MH.isLiteralString(value)
        ? waitForReferenceElement(value, element).then((v) => v ?? undefined) // ugh, typescript...
        : undefined,
    preventDefault: validateBoolean,
    preventSelect: validateBoolean,
  };
};
 
const setupWatcher = (
  widget: ClickTrigger | HoverTrigger | PressTrigger,
  element: Element,
  actions: Action[],
  config: PointerTriggerConfig,
  action: "click" | "hover" | "press",
) => {
  Iif (!MH.lengthOf(actions)) {
    return;
  }
 
  config ??= {};
  const target = MH.targetOf(config) ?? element;
 
  // For clicks use the trigger's own toggle function so that it remembers ITS
  // state rather than the odd/even clicks. Otherwise if the trigger is
  // disabled, then clicking will "swap" the state.
  let startHandler: OnPointerHandler;
  let endHandler: OnPointerHandler;
  if (action === MC.S_CLICK) {
    startHandler = endHandler = widget[MC.S_TOGGLE];
  } else {
    startHandler = widget.run;
    endHandler = widget.reverse;
  }
 
  PointerWatcher.reuse().onPointer(
    target,
    startHandler,
    endHandler,
    MH.merge(
      {
        actions: action,
      },
      omitKeys(config, { target: null }),
    ),
  );
};