All files / actions scroll-to.ts

100% Statements 43/43
72.22% Branches 13/18
100% Functions 12/12
100% Lines 43/43

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                94x 94x       94x 94x 94x   94x   94x                                                                                                                                                             94x                                       188x     3x             3x                     5x 5x 5x 5x   5x 4x 4x 4x   4x 4x     5x 4x 4x             4x       5x 4x   4x 4x       4x   2x 2x         4x                 4x   4x     2x 2x                                                                               94x 3x 3x 3x     3x 2x        
/**
 * @module Actions
 *
 * @categoryDescription Scrolling
 * {@link ScrollTo} scrolls to the given element or to the previous scroll
 * position.
 */
 
import * as MH from "@lisn/globals/minification-helpers";
import * as MC from "@lisn/globals/minification-constants";
 
import { CoordinateOffset } from "@lisn/globals/types";
 
import { waitForReferenceElement } from "@lisn/utils/dom-search";
import { omitKeys } from "@lisn/utils/misc";
import { validateNumber } from "@lisn/utils/validation";
 
import { ScrollWatcher } from "@lisn/watchers/scroll-watcher";
 
import { Action, registerAction } from "@lisn/actions/action";
 
import { WidgetConfigValidatorFunc } from "@lisn/widgets/widget";
 
/**
 * Scrolls to the given element or to the previous scroll position.
 *
 * -------
 *
 * To use with auto-widgets (HTML API) as part of a trigger specification:
 * - Action name: "scroll-to".
 * - Arguments: none
 * - Options (see {@link ScrollToConfig}):
 *   - `offsetX`: A number.
 *   - `offsetY`: A number.
 *   - `duration`: A number.
 *   - `scrollable`: A string element specification for an element (see
 *     {@link Utils.getReferenceElement | getReferenceElement}). Note that,
 *     unless it's a DOM ID, the specification is parsed relative to the
 *     element being acted on and not the element the trigger is defined on (in
 *     case you've used the `act-on` trigger option).
 *
 * **NOTE:** Do not place a + sign in front of the offset values (just omit it
 * if you want a positive offset). Otherwise it will be interpreted as a
 * trigger option.
 *
 * @example
 * When the user clicks the button (click target), scroll the main scrolling
 * element to position of the element (on which the trigger is defined):
 *
 * ```html
 * <button id="btn">Scroll to/back</button>
 * <div data-lisn-on-click="@scroll-to +target=#btn"></div>
 * ```
 *
 * @example
 * When the user clicks the button (click target), scroll the main scrolling
 * element to position of the element (on which the trigger is defined) +10px
 * down:
 *
 * ```html
 * <button id="btn">Scroll to/back</button>
 * <div data-lisn-on-click="@scroll-to: offsetY=10 +target=#btn"></div>
 * ```
 *
 * @example
 * When the user clicks the button (click target), scroll the main scrolling
 * element to position of the element (on which the trigger is defined) plus
 * 10px _down_ and 50px _left_, with a duration of 200ms:
 *
 * ```html
 * <button id="btn">Scroll to/back</button>
 * <div data-lisn-on-click="@scroll-to: offsetY=10, offsetX=-50, duration=200 +target=#btn"></div>
 * ```
 *
 * @example
 * When the user clicks the button (click target), scroll the closest parent
 * element with class `scrollable` to the position of the element (on which the
 * trigger is defined):
 *
 * ```html
 * <button id="btn">Scroll to/back</button>
 * <div class="scrollable">
 *   <div data-lisn-on-click="@scroll-to: scrollable=this.scrollable +target=#btn"></div>
 * </div>
 * ```
 *
 * @example
 * As above, but using `data-lisn-ref` attribute instead of class selector.
 *
 * ```html
 * <button id="btn">Scroll to/back</button>
 * <div data-lisn-ref="scrollable">
 *   <div data-lisn-on-click="@scroll-to: scrollable=this-scrollable +target=#btn"></div>
 * </div>
 * ```
 *
 * @category Scrolling
 */
export class ScrollTo implements Action {
  /**
   * Scrolls the main scrolling element to the element's position.
   */
  readonly do: () => Promise<void>;
 
  /**
   * Scrolls the main scrolling element to the last scroll position before the
   * action was {@link do}ne. If the action had never been done, does nothing.
   */
  readonly undo: () => Promise<void>;
 
  /**
   * Scrolls the main scrolling element to the element's position, if it's not
   * already there, or otherwise scrolls the main scrolling element to the
   * previous saved scroll position.
   */
  readonly toggle: () => Promise<void>;
 
  static register() {
    registerAction(
      "scroll-to",
      (element, args, config) => {
        const offset = config
          ? {
              left: config.offsetX,
              top: config.offsetY,
            }
          : undefined;
 
        return new ScrollTo(element, {
          offset,
          duration: config?.duration,
          scrollable: config?.scrollable,
        });
      },
      newConfigValidator,
    );
  }
 
  constructor(element: Element, config?: ScrollToConfig) {
    const watcher = ScrollWatcher.reuse();
    const { scrollable } = config ?? {};
    let prevScrollTop = -1,
      prevScrollLeft = -1;
 
    this.do = async () => {
      const current = await watcher.fetchCurrentScroll(scrollable);
      prevScrollTop = current[MC.S_SCROLL_TOP];
      prevScrollLeft = current[MC.S_SCROLL_LEFT];
 
      const action = await watcher.scrollTo(element, config);
      await action?.waitFor();
    };
 
    this.undo = async () => {
      if (prevScrollTop !== -1) {
        const action = await watcher.scrollTo(
          {
            top: prevScrollTop,
            left: prevScrollLeft,
          },
          omitKeys(config ?? {}, { offset: true }), // no offset when undoing
        );
        await action?.waitFor();
      }
    };
 
    this[MC.S_TOGGLE] = async () => {
      const start = await watcher.fetchCurrentScroll(scrollable);
 
      const canReverse = prevScrollTop !== -1;
      let hasReversed = false;
 
      // Try to scroll to the element, but if we're already close to it, then
      // reverse to previous position if any.
      const altTarget = {
        top: () => {
          hasReversed = true; // detect if we have reversed
          return prevScrollTop;
        },
        left: prevScrollLeft,
      };
 
      const action = await watcher.scrollTo(
        element,
        MH.merge(
          config,
          canReverse
            ? { altTarget } // no altOffset when reversing
            : {},
        ),
      );
      await action?.waitFor();
 
      if (!hasReversed) {
        // We've scrolled to the element, so save the starting position as the
        // previous one.
        prevScrollTop = start[MC.S_SCROLL_TOP];
        prevScrollLeft = start[MC.S_SCROLL_LEFT];
      }
    };
  }
}
 
/**
 * @interface
 * @category Scrolling
 */
export type ScrollToConfig = {
  /**
   * See {@link Utils.ScrollToOptions.offset}.
   *
   * @defaultValue undefined // none
   */
  offset?: CoordinateOffset;
 
  /**
   * The duration in milliseconds of the scroll animation.
   *
   * @defaultValue {@link ScrollWatcher} default
   */
  duration?: number;
 
  /**
   * The element that should be scrolled.
   *
   * @defaultValue {@link ScrollWatcher} default
   */
  scrollable?: Element;
};
 
// --------------------
 
const newConfigValidator: WidgetConfigValidatorFunc<{
  offsetX: number;
  offsetY: number;
  duration: number | undefined;
  scrollable?: Element;
}> = (element) => {
  return {
    offsetX: (key, value) => validateNumber(key, value) ?? 0,
    offsetY: (key, value) => validateNumber(key, value) ?? 0,
    duration: validateNumber,
    scrollable: (key, value) =>
      MH.isLiteralString(value)
        ? waitForReferenceElement(value, element).then((v) => v ?? undefined) // ugh, typescript...
        : undefined,
  };
};