Extract is navigation click (#3432)

This commit is contained in:
Paulus Schoutsen 2019-07-26 14:55:08 -07:00 committed by GitHub
parent a91bb3cdbb
commit 54ea6176aa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 38 deletions

View File

@ -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 }
);

View File

@ -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;
};