/ src / lib / utils / on-click-goto.ts
on-click-goto.ts
 1  import { goto } from '$app/navigation';
 2  
 3  /**
 4   * Function used to simulate the behavior of a proper `a` element for a
 5   * navigation link, if for whatever reason using `a` isnĘžt possible, and
 6   * some other element type needs to be used with an `onclick` handler.
 7   * Takes a `path` and `MouseEvent`, and either triggers `goto` or opens a
 8   * new tab if the `meta` or `ctrl` keys were pressed during the click.
 9   * @param path The path to navigate to.
10   * @param event The mouse event that triggered the interaction.
11   */
12  export default function (path: string, event: PointerEvent | MouseEvent) {
13    if (event.metaKey || event.ctrlKey || event.button === 1) {
14      // Prevent handling if the event has already previoulsy hit an `a` element.
15      if (event.composedPath().find((e) => e instanceof HTMLAnchorElement)) return;
16  
17      window?.open(path, '_blank');
18    } else {
19      goto(path);
20    }
21  }