diff --git a/demo/src/ha-demo.ts b/demo/src/ha-demo.ts index 3672b17ff5..6eb383eb22 100644 --- a/demo/src/ha-demo.ts +++ b/demo/src/ha-demo.ts @@ -17,6 +17,7 @@ import { mockMediaPlayer } from "./stubs/media_player"; import { HomeAssistant } from "../../src/types"; import { mockFrontend } from "./stubs/frontend"; import { mockPersistentNotification } from "./stubs/persistent_notification"; +import { isNavigationClick } from "../../src/common/dom/is-navigation-click"; class HaDemo extends HomeAssistantAppEl { protected async _initialize() { @@ -60,49 +61,14 @@ class HaDemo extends HomeAssistantAppEl { document.body.addEventListener( "click", (e) => { - if ( - e.defaultPrevented || - e.button !== 0 || - e.metaKey || - e.ctrlKey || - e.shiftKey - ) { - return; - } + const href = isNavigationClick(e); - const anchor = e - .composedPath() - .filter((n) => (n as HTMLElement).tagName === "A")[0] as - | HTMLAnchorElement - | undefined; - if ( - !anchor || - anchor.target || - anchor.hasAttribute("download") || - anchor.getAttribute("rel") === "external" - ) { - return; - } - - let href = anchor.href; - if (!href || href.indexOf("mailto:") !== -1) { - return; - } - - const location = window.location; - const origin = - location.origin || location.protocol + "//" + location.host; - if (href.indexOf(origin) !== 0) { - return; - } - href = href.substr(origin.length); - - if (href === "#") { + if (!href) { return; } e.preventDefault(); - navigate(this as any, href); + navigate(this, href); }, { capture: true } ); diff --git a/src/common/dom/is-navigation-click.ts b/src/common/dom/is-navigation-click.ts new file mode 100644 index 0000000000..3ab515b778 --- /dev/null +++ b/src/common/dom/is-navigation-click.ts @@ -0,0 +1,45 @@ +export const isNavigationClick = (e: MouseEvent) => { + // Taken from polymer/pwa-helpers. BSD-3 licensed + if ( + e.defaultPrevented || + e.button !== 0 || + e.metaKey || + e.ctrlKey || + e.shiftKey + ) { + return; + } + + const anchor = e + .composedPath() + .filter((n) => (n as HTMLElement).tagName === "A")[0] as + | HTMLAnchorElement + | undefined; + if ( + !anchor || + anchor.target || + anchor.hasAttribute("download") || + anchor.getAttribute("rel") === "external" + ) { + return; + } + + let href = anchor.href; + if (!href || href.indexOf("mailto:") !== -1) { + return; + } + + const location = window.location; + const origin = location.origin || location.protocol + "//" + location.host; + if (href.indexOf(origin) !== 0) { + return; + } + href = href.substr(origin.length); + + if (href === "#") { + return; + } + + e.preventDefault(); + return href; +};