toRoute method

void toRoute(
  1. int slotId, {
  2. List<String>? staticPath,
  3. List<String>? dynamicPath,
})

Mounts the widget in the specified slot. staticPath - A strictly specified path to anything. dynamicPath - A regular expression that allows you to set your targets.

Implementation

void toRoute(int slotId,
    {List<String>? staticPath, List<String>? dynamicPath}) {
  Element? slot = document.querySelector(slotQuery + slotId.toString());
  if (slot == null) return;

  if (staticPath == null && dynamicPath == null) {
    return initialize(slot, true);
  }

  slotParent = slot.parent;
  slotPosition = slotParent?.children.indexOf(slot);
  slotBackup = slot;

  void initializeWidget() {
    if (slotParent?.children.contains(slot) == true) {
      initialize(slot, true);
    }
  }

  void destroyWidget() {
    if (slotBackup == null) return;

    Element currentElement = slotParent!.children[slotPosition!];

    if (currentElement != slotBackup) {
      currentElement.replaceWith(slotBackup!);
      destroy();
    }
  }

  if (staticPath != null) {
    for (String path in staticPath) {
      void function() {
        if (window.location.href.endsWith(path)) {
          initializeWidget();
        } else {
          destroyWidget();
        }
      }

      if (window.location.href.endsWith(path)) {
        initialize(slot, true);
      } else {
        onRoute(function);
        onPopState(function);
      }
    }
  }

  if (dynamicPath != null) {
    for (String path in dynamicPath) {
      void function() {
        RegExp regularPath = RegExp(path);
        if (regularPath.hasMatch(window.location.href)) {
          initializeWidget();
        } else {
          destroyWidget();
        }
      }

      RegExp regularPath = RegExp(path);
      if (regularPath.hasMatch(window.location.href)) {
        initialize(slot, true);
      } else {
        onRoute(function);
        onPopState(function);
      }
    }
  }
}