The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Prefetch a code-split page when a link to it scrolls into view (#79688)
Romeo Van Snick2a3f535c392b
diff --git a/frontend/src/metabase/common/components/Link/BaseLink.tsx b/frontend/src/metabase/common/components/Link/BaseLink.tsxindex 0b33690febb..2031e1aad7a 100644--- a/frontend/src/metabase/common/components/Link/BaseLink.tsx+++ b/frontend/src/metabase/common/components/Link/BaseLink.tsx@@ -1,3 +1,4 @@+import { useMergedRef } from "@mantine/hooks";import {type CSSProperties,type HTMLProps,@@ -13,6 +14,7 @@ import {type To,prefetchPage,useInRouterContext,+ usePrefetchOnVisible,} from "metabase/router";const INACTIVE: NavLinkRenderProps = {@@ -97,9 +99,18 @@ export const BaseLink = forwardRef<HTMLAnchorElement, BaseLinkProps>({ to, innerRef, className, style, end, onMouseEnter, onFocus, ...rest },ref,) {- const linkRef = ref ?? innerRef;+ const forwardedRef = ref ?? innerRef;const inRouter = useInRouterContext();+ // A touch device never fires the hover below, so watch the link instead and+ // start the fetch when it comes into view. `usePrefetchOnVisible` decides+ // whether that applies; on a device with a pointer it does nothing.+ const hasTarget = to != null && to !== "";+ const visibleRef = usePrefetchOnVisible(+ inRouter && hasTarget ? hrefFor(anchorTarget(to)) : null,+ );+ const linkRef = useMergedRef(forwardedRef, visibleRef);+// A link with no destination (`to` null or `""`) is used as a button: it// navigates through its `onClick`. A real `<Link>` would additionally// navigate on click (an empty `to` resolves to the current route, or `/`diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.tsindex c0982afb8f9..23461eb1531 100644--- a/frontend/src/metabase/router/index.ts+++ b/frontend/src/metabase/router/index.ts@@ -15,6 +15,7 @@ export {} from "react-router";export * from "./use-navigate";export * from "./prefetch";+export * from "./use-prefetch-on-visible";export * from "./redirect";export * from "./to-route-objects";export * from "./location-change";diff --git a/frontend/src/metabase/router/prefetch-on-visible.unit.spec.ts b/frontend/src/metabase/router/prefetch-on-visible.unit.spec.tsnew file mode 100644index 00000000000..8d91bf005bd--- /dev/null+++ b/frontend/src/metabase/router/prefetch-on-visible.unit.spec.ts@@ -0,0 +1,114 @@+import { observeLinkForPrefetch, registerPagePrefetch } from "./prefetch";++let nextId = 0;+const uniquePath = () => `/prefetch-visible-spec-${nextId++}`;++type Callback = (+ entries: { target: Element; isIntersecting: boolean }[],+) => void;++let observed: Element[] = [];+let unobserved: Element[] = [];+let fire: Callback = () => undefined;++function mockHover(hasHover: boolean) {+ // Only `matches` is read, so the stub does not implement the rest of+ // `MediaQueryList`.+ window.matchMedia = ((query: string) => ({+ matches: query === "(hover: hover)" ? hasHover : false,+ media: query,+ addEventListener: () => undefined,+ removeEventListener: () => undefined,+ })) as unknown as typeof window.matchMedia;+}++beforeEach(() => {+ observed = [];+ unobserved = [];+ // Only the three methods used here are implemented, so the stub is not a+ // structural `IntersectionObserver`.+ globalThis.IntersectionObserver = class {+ constructor(callback: Callback) {+ fire = callback;+ }+ observe(element: Element) {+ observed.push(element);+ }+ unobserve(element: Element) {+ unobserved.push(element);+ }+ disconnect() {}+ } as unknown as typeof IntersectionObserver;+});++describe("observeLinkForPrefetch", () => {+ it("loads the page when the link comes into view", () => {+ mockHover(false);+ const path = uniquePath();+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ const element = document.createElement("a");+ observeLinkForPrefetch(element, path);+ expect(load).not.toHaveBeenCalled();++ fire([{ target: element, isIntersecting: true }]);++ expect(load).toHaveBeenCalledTimes(1);+ });++ it("does nothing until the link is actually intersecting", () => {+ mockHover(false);+ const path = uniquePath();+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ const element = document.createElement("a");+ observeLinkForPrefetch(element, path);+ fire([{ target: element, isIntersecting: false }]);++ expect(load).not.toHaveBeenCalled();+ });++ // Hovering is a better signal of intent, and a device with a pointer already+ // prefetches on it. Watching there would fetch pages nobody asked for.+ it("does not watch anything on a device that can hover", () => {+ mockHover(true);+ const path = uniquePath();+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ observeLinkForPrefetch(document.createElement("a"), path);++ expect(observed).toEqual([]);+ expect(load).not.toHaveBeenCalled();+ });++ it("stops watching a link once it has been seen", () => {+ mockHover(false);+ const path = uniquePath();+ registerPagePrefetch(path, jest.fn().mockResolvedValue(undefined));++ const element = document.createElement("a");+ observeLinkForPrefetch(element, path);+ fire([{ target: element, isIntersecting: true }]);++ expect(unobserved).toContain(element);+ });++ // The point of watching every link on screen: a list of many links to the+ // same page still costs one fetch, because `prefetchPage` starts each+ // registered page once.+ it("loads a shared target once however many links are seen", () => {+ mockHover(false);+ const path = uniquePath();+ const load = jest.fn().mockResolvedValue(undefined);+ registerPagePrefetch(path, load);++ const links = [0, 1, 2].map(() => document.createElement("a"));+ links.forEach((element) => observeLinkForPrefetch(element, path));+ fire(links.map((target) => ({ target, isIntersecting: true })));++ expect(load).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/metabase/router/prefetch.ts b/frontend/src/metabase/router/prefetch.tsindex 2662bb9daae..b9e4bfd397d 100644--- a/frontend/src/metabase/router/prefetch.ts+++ b/frontend/src/metabase/router/prefetch.ts@@ -45,3 +45,86 @@ export function prefetchPage(path: string): void {});}}++type NetworkInformation = { saveData?: boolean; effectiveType?: string };++function getConnection(): NetworkInformation | undefined {+ // `navigator.connection` is not in the DOM lib, and this is the only place+ // that reads it.+ return (navigator as Navigator & { connection?: NetworkInformation })+ .connection;+}++/**+ * Whether a link coming into view should start its fetch.+ *+ * Only where hovering cannot: a device with a pointer already prefetches on+ * hover, which is a far better signal of intent than a link merely being on+ * screen. This covers the touch devices that never fire one.+ *+ * Not on a metered or slow connection, where guessing wrong is most expensive+ * and the pages being guessed at are the largest chunks the app has.+ */+function shouldPrefetchOnVisible(): boolean {+ if (typeof window === "undefined" || !("IntersectionObserver" in window)) {+ return false;+ }++ if (window.matchMedia("(hover: hover)").matches) {+ return false;+ }++ const connection = getConnection();+ return !connection?.saveData && !/2g/.test(connection?.effectiveType ?? "");+}++const observedPaths = new WeakMap<Element, string>();+let observer: IntersectionObserver | null = null;++function getObserver(): IntersectionObserver {+ observer ??= new IntersectionObserver((entries) => {+ for (const entry of entries) {+ if (!entry.isIntersecting) {+ continue;+ }++ const path = observedPaths.get(entry.target);+ if (path != null) {+ prefetchPage(path);+ }++ // One look is enough: `prefetchPage` starts each page once, so there is+ // nothing to gain from watching this link again.+ getObserver().unobserve(entry.target);+ observedPaths.delete(entry.target);+ }+ });++ return observer;+}++/**+ * Start `path`'s fetch when `element` comes into view.+ *+ * A list of fifty links to the same page costs one fetch, not fifty, because+ * `prefetchPage` starts each registered page once however often it is asked.+ * That is what makes watching every link on screen affordable here.+ *+ * Returns a function that stops watching.+ */+export function observeLinkForPrefetch(+ element: Element,+ path: string,+): () => void {+ if (!shouldPrefetchOnVisible()) {+ return () => undefined;+ }++ observedPaths.set(element, path);+ getObserver().observe(element);++ return () => {+ getObserver().unobserve(element);+ observedPaths.delete(element);+ };+}diff --git a/frontend/src/metabase/router/use-prefetch-on-visible.ts b/frontend/src/metabase/router/use-prefetch-on-visible.tsnew file mode 100644index 00000000000..e75f85ba1f3--- /dev/null+++ b/frontend/src/metabase/router/use-prefetch-on-visible.ts@@ -0,0 +1,26 @@+import { useEffect, useState } from "react";++import { observeLinkForPrefetch } from "./prefetch";++/**+ * Watch a link so its target starts loading when it comes into view.+ *+ * Returns a ref callback. Pass `null` for a link with no target, or one that+ * should not be watched.+ *+ * The element is held in state rather than a ref so the effect runs when the+ * node mounts, which a ref alone would not trigger.+ */+export function usePrefetchOnVisible(path: string | null) {+ const [element, setElement] = useState<HTMLElement | null>(null);++ useEffect(() => {+ if (element == null || path == null) {+ return;+ }++ return observeLinkForPrefetch(element, path);+ }, [element, path]);++ return setElement;+}