toRoute method

void toRoute(
  1. int slotId,
  2. RegExp routeExp, {
  3. bool? lazy,
})

Mounts the widget in the specified slot.

Implementation

void toRoute(int slotId, RegExp routeExp, {bool? lazy}) {
  bool hrefContainsRoute() => routeExp.hasMatch(window.location.href);

  Element? slot = document.querySelector(slotQuery + slotId.toString());
  if (slot == null) return;

  Element? slotParent = slot.parent;
  if (slotParent == null) return;

  int slotPosition = slotParent.children.indexOf(slot);
  if (slotPosition < 0) return;

  if (hrefContainsRoute()) {
    if (lazy == true) {
      initializeLazyLoading(slot);
    } else {
      initialize(slot, true);
    }
  }

  void controlState() {
    if (hrefContainsRoute()) {
      if (slotParent.children.contains(slot) == true) {
        // By default, each widget should have
        // its own slot to initialize the widget.
        if (lazy == true) {
          initializeLazyLoading(slot);
        } else {
          initialize(slot, true);
        }
      }
    } else {
      if (slotPosition >= slotParent.children.length) {
        // The slot position cannot be equal to or greater than
        // the number of children. If this has happened it is
        // likely that a slot has been removed
        // or an external critical situation has been created.
        return;
      }

      Element currentElement = slotParent.children[slotPosition];

      if (currentElement != slot) {
        // If the current element is not a slot.
        // You need a widget for destroying it, not a slot.
        currentElement.replaceWith(slot);
        destroy();
      }
    }
  }

  onRoute(controlState);
  onPopState(controlState);
}