All files / widgets scroll-to-top.ts

95.23% Statements 100/105
80.55% Branches 29/36
90% Functions 18/20
95.19% Lines 99/104

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        94x 94x       94x                           94x             94x 94x 94x 94x 94x 94x   94x 94x   94x                                                                                                                                                                                                                                                               94x           20x 1x     19x 19x 4x   15x       94x     3x 3x                         1x 1x 1x             1x 1x 1x       1x 1x       11x 11x     11x   11x 11x   11x       11x 11x       11x 2x       11x   11x 12x     11x 12x         11x 11x       11x 11x 1x     10x   2x 2x                   2x       2x             2x     10x 10x 10x 10x 10x   10x   10x   10x   10x       10x       10x 3x     10x 1x     10x 2x 2x   2x 2x 2x 2x 2x   2x 2x     2x   1x     2x   1x     2x 2x                                                                                 94x 94x     94x 94x 94x 94x   94x     94x     3x 3x   3x   3x          
/**
 * @module Widgets
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { ScrollOffsetSpec } from "@lisn/globals/types";
 
import {
  showElement,
  hideElement,
  displayElement,
  displayElementNow,
  undisplayElement,
  disableInitialTransition,
  addClassesNow,
  removeClassesNow,
  setDataNow,
  setBooleanDataNow,
  delDataNow,
  getParentFlexDirection,
} from "@lisn/utils/css-alter";
import {
  replaceElementNow,
  wrapElementNow,
  moveElement,
  moveElementNow,
  insertArrow,
} from "@lisn/utils/dom-alter";
import { waitForElement } from "@lisn/utils/dom-events";
import { waitForMutateTime } from "@lisn/utils/dom-optimize";
import { waitForReferenceElement } from "@lisn/utils/dom-search";
import { addEventListenerTo, removeEventListenerFrom } from "@lisn/utils/event";
import { validateString } from "@lisn/utils/validation";
import { isValidScrollOffset } from "@lisn/utils/views";
 
import { ScrollWatcher } from "@lisn/watchers/scroll-watcher";
import { ViewWatcher } from "@lisn/watchers/view-watcher";
 
import {
  Widget,
  WidgetConfigValidatorFunc,
  registerWidget,
} from "@lisn/widgets/widget";
 
/**
 * Configures the given element as a {@link ScrollToTop} widget.
 *
 * The ScrollToTop widget adds a scroll-to-top button in the lower right corder
 * of the screen (can be changed to bottom left) which scrolls smoothly (and
 * more slowly than the native scroll) back to the top.
 *
 * The button is only shown when the scroll offset from the top is more than a
 * given configurable amount.
 *
 * **IMPORTANT:** When configuring an existing element as the button (i.e. using
 * `new ScrollToTop` or auto-widgets, rather than {@link ScrollToTop.enableMain}):
 * - if using
 *   {@link Settings.settings.mainScrollableElementSelector | the main scrolling element}
 *   as the scrollable, the button element will have it's CSS position set to `fixed`;
 * - otherwise, if using a custom scrollable element, the button element may be
 *   moved in the DOM tree in order to position it on top of the scrollable
 * If you don't want the button element changed in any way, then consider using
 * the {@link Triggers.ClickTrigger | ClickTrigger} with a
 * {@link Actions.ScrollTo | ScrollTo} action.
 *
 * **IMPORTANT:** You should not instantiate more than one {@link ScrollToTop}
 * widget on a given element. Use {@link ScrollToTop.get} to get an existing
 * instance if any. If there is already a widget instance, it will be destroyed!
 *
 * -----
 *
 * You can use the following dynamic attributes or CSS properties in your
 * stylesheet:
 *
 * The following dynamic attributes are set on the element:
 * - `data-lisn-place`: `"left"` or `"right"`
 *
 * -----
 *
 * To use with auto-widgets (HTML API) (see
 * {@link Settings.settings.autoWidgets | settings.autoWidgets}), the following
 * CSS classes or data attributes are recognized:
 * - `lisn-scroll-to-top` class or `data-lisn-scroll-to-top` attribute set on
 *   the element that constitutes the widget. The element should be empty.
 *
 * See below examples for what values you can use set for the data attributes
 * in order to modify the configuration of the automatically created widget.
 *
 * @example
 * This will create a scroll-to-top button using the JavaScript API.
 *
 * This will work even if
 * {@link Settings.settings.autoWidgets | settings.autoWidgets}) is false.
 *
 * ```html
 * <!-- LISN should be loaded beforehand -->
 * <script>
 *   LISN.widgets.ScrollToTop.enableMain({
 *     position: "left",
 *     offset: "top: 300vh"
 *   });
 * </script>
 * ```
 *
 * You can customise the offset show/hide trigger via CSS as well as long as
 * {@link ScrollToTopConfig.offset} is left at its default value which uses
 * this CSS property:
 *
 * ```html
 * <style type="text/css" media="screen">
 *   :root {
 *     --lisn-scroll-to-top--offset: 300vh;
 *   }
 * </style>
 * ```
 *
 * @example
 * This will configure the given element as a scroll-to-top button for the main
 * scrolling element using an existing element for the button with default
 * {@link ScrollToTopConfig}.
 *
 * ```html
 * <button class="lisn-scroll-to-top"></button>
 * ```
 * @example
 * As above but with custom settings.
 *
 * ```html
 * <button data-lisn-scroll-to-top="position=left | offset=top:300vh"></button>
 * ```
 *
 * @example
 * This will configure the given element as a scroll-to-top button for a custom
 * scrolling element (i.e. one with overflow "auto" or "scroll").
 *
 * ```html
 * <div id="scrollable">
 *   <!-- content here... -->
 * </div>
 * <button data-lisn-scroll-to-top="scrollable=#scrollable"></button>
 * ```
 *
 * @example
 * As above, but using a reference specification with a class name to find the
 * scrollable.
 *
 * ```html
 * <div class="scrollable">
 *   <!-- content here... -->
 * </div>
 * <button data-lisn-scroll-to-top="scrollable=prev.scrollable"></button>
 * ```
 *
 * @example
 * As above but with all custom settings.
 *
 * ```html
 * <div class="scrollable">
 *   <!-- content here... -->
 * </div>
 * <button data-lisn-scroll-to-top="scrollable=prev.scrollable
 *                               | position=left
 *                               | offset=top:300vh
 * "></button>
 * ```
 */
export class ScrollToTop extends Widget {
  /**
   * If element is omitted, returns the instance created by {@link enableMain}
   * if any.
   */
  static get(element?: Element): ScrollToTop | null {
    if (!element) {
      return mainWidget;
    }
 
    const instance = super.get(element, DUMMY_ID);
    if (MH.isInstanceOf(instance, ScrollToTop)) {
      return instance;
    }
    return null;
  }
 
  static register() {
    registerWidget(
      WIDGET_NAME,
      (element, config) => {
        if (!ScrollToTop.get(element)) {
          return new ScrollToTop(element, config);
        }
        return null;
      },
      newConfigValidator,
    );
  }
 
  /**
   * Creates a new button element, inserts it into the document body and
   * configures it as a {@link ScrollToTop}.
   */
  static enableMain(config?: ScrollToTopConfig) {
    const button = MH.createButton("Back to top");
    const widget = new ScrollToTop(button, config);
    widget.onDestroy(() => {
      Iif (mainWidget === widget) {
        mainWidget = null;
      }
      return moveElement(button);
    });
 
    waitForElement(MH.getBody).then((body) => {
      if (!widget.isDestroyed()) {
        moveElement(button, { to: body });
      }
    });
 
    mainWidget = widget;
    return widget;
  }
 
  constructor(element: Element, config?: ScrollToTopConfig) {
    const destroyPromise = ScrollToTop.get(element)?.destroy();
    super(element, { id: DUMMY_ID });
 
    const offset: ScrollOffsetSpec =
      config?.offset ||
      `${MC.S_TOP}: var(${MH.prefixCssVar("scroll-to-top--offset")}, 200vh)`;
    const position: "left" | "right" = config?.position || MC.S_RIGHT;
    const scrollable = config?.scrollable;
    const hasCustomScrollable =
      scrollable &&
      scrollable !== MH.getDocElement() &&
      scrollable !== MH.getBody();
 
    const scrollWatcher = ScrollWatcher.reuse();
    const viewWatcher = ViewWatcher.reuse(
      hasCustomScrollable ? { root: scrollable } : {},
    );
 
    const clickListener = () =>
      scrollWatcher.scrollTo({ top: 0, left: 0 }, { scrollable });
 
    let arrow: Element;
    let placeholder: Element;
    let root = element;
 
    const showIt = () => {
      showElement(root);
    };
 
    const hideIt = () => {
      hideElement(root);
    };
 
    // SETUP ------------------------------
 
    (destroyPromise || MH.promiseResolve()).then(async () => {
      const flexDirection = scrollable
        ? await getParentFlexDirection(scrollable)
        : null;
 
      await waitForMutateTime();
      if (this.isDestroyed()) {
        return;
      }
 
      if (hasCustomScrollable) {
        // Add a placeholder to restore its position on destroy.
        placeholder = MH.createElement("div");
        moveElementNow(placeholder, {
          to: element,
          position: "before",
          ignoreMove: true,
        });
 
        // Then move it to immediately after the scrollable.
        // If the parent is a horizontal flexbox and position is left, then
        // we need to insert it before the scrollable.
        const shouldInsertBefore =
          flexDirection === "column-reverse" ||
          (position === MC.S_LEFT && flexDirection === "row") ||
          (position === MC.S_RIGHT && flexDirection === "row-reverse");
 
        moveElementNow(element, {
          to: scrollable,
          position: shouldInsertBefore ? "before" : "after",
          ignoreMove: true,
        });
 
        // Wrap the button.
        root = wrapElementNow(element, { wrapper: "div", ignoreMove: true });
      }
 
      disableInitialTransition(root);
      addClassesNow(root, PREFIX_ROOT);
      addClassesNow(element, PREFIX_BTN);
      setBooleanDataNow(root, PREFIX_FIXED, !hasCustomScrollable);
      setDataNow(root, MC.PREFIX_PLACE, position);
 
      arrow = insertArrow(element, MC.S_UP);
 
      hideIt(); // initial
 
      addEventListenerTo(element, MC.S_CLICK, clickListener);
 
      viewWatcher.onView(offset, showIt, {
        views: [MC.S_AT, MC.S_BELOW],
      });
 
      viewWatcher.onView(offset, hideIt, {
        views: [MC.S_ABOVE],
      });
 
      this.onDisable(() => {
        undisplayElement(root);
      });
 
      this.onEnable(() => {
        displayElement(root);
      });
 
      this.onDestroy(async () => {
        await waitForMutateTime();
        removeEventListenerFrom(element, MC.S_CLICK, clickListener);
 
        removeClassesNow(root, PREFIX_ROOT);
        removeClassesNow(element, PREFIX_BTN);
        delDataNow(root, PREFIX_FIXED);
        delDataNow(root, MC.PREFIX_PLACE);
        displayElementNow(root); // revert undisplay by onDisable
 
        if (arrow) {
          moveElementNow(arrow); // remove
        }
 
        if (root !== element) {
          // Unwrap the button.
          replaceElementNow(root, element, { ignoreMove: true });
        }
 
        if (placeholder) {
          // Move it back into its original position.
          replaceElementNow(placeholder, element, { ignoreMove: true });
        }
 
        viewWatcher.offView(offset, showIt);
        viewWatcher.offView(offset, hideIt);
      });
    });
  }
}
 
/**
 * @interface
 */
export type ScrollToTopConfig = {
  /**
   * The button will be shown when the scroll top offset of the page is below
   * the given value, and hidden otherwise. Accepts a colon-separated key:value
   * string where the key is "top" or "bottom" (or if your page scrolls
   * horizontally, then use "left" or "right"), and the value can be any valid
   * CSS length specification, e.g. "top: 200vh" or "top: var(--offset, 50%)".
   *
   * Alternatively, you set the `--lisn-scroll-to-top--offset` CSS variable on
   * the document root, which is used by the default value.
   *
   * @defaultValue "top: var(--lisn-scroll-to-top--offset, 200vh)"
   */
  offset?: ScrollOffsetSpec;
 
  /**
   * The horizontal position of the scroll-to-top button.
   *
   * @defaultValue "right"
   */
  position?: "left" | "right";
 
  /**
   * The element that should be scrolled.
   *
   * @defaultValue {@link ScrollWatcher} default
   */
  scrollable?: Element;
};
 
// --------------------
 
const WIDGET_NAME = "scroll-to-top";
const PREFIXED_NAME = MH.prefixName(WIDGET_NAME);
// Only one ScrollToTop widget per element is allowed, but Widget requires a
// non-blank ID.
const DUMMY_ID = PREFIXED_NAME;
const PREFIX_ROOT = `${PREFIXED_NAME}__root`;
const PREFIX_BTN = `${PREFIXED_NAME}__btn`;
const PREFIX_FIXED = MH.prefixName("fixed");
 
let mainWidget: ScrollToTop | null = null;
 
// For HTML API only
const newConfigValidator: WidgetConfigValidatorFunc<ScrollToTopConfig> = (
  element,
) => {
  return {
    offset: (key, value) => validateString(key, value, isValidScrollOffset),
    position: (key, value) =>
      validateString(key, value, (v) => v === MC.S_LEFT || v === MC.S_RIGHT),
    scrollable: (key, value) =>
      MH.isLiteralString(value)
        ? waitForReferenceElement(value, element).then((v) => v ?? undefined) // ugh, typescript...
        : undefined,
  };
};