Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
217 changes: 217 additions & 0 deletions airflow-core/src/airflow/ui/src/hooks/useNearViewport.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
/*!
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { act, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";

import { useNearViewport } from "./useNearViewport";

type MockObserver = {
callback: IntersectionObserverCallback;
} & IntersectionObserver;

const observers: Array<MockObserver> = [];

const createEntry = (target: Element, isIntersecting: boolean): IntersectionObserverEntry => ({
boundingClientRect: target.getBoundingClientRect(),
intersectionRatio: isIntersecting ? 1 : 0,
intersectionRect: target.getBoundingClientRect(),
isIntersecting,
rootBounds: null,
target,
time: 0,
});

const takeNoRecords = () => [];

const MockIntersectionObserver = function MockIntersectionObserver(
callback: IntersectionObserverCallback,
options?: IntersectionObserverInit,
): IntersectionObserver {
const observer = {
callback,
disconnect: vi.fn(),
observe: vi.fn(),
root: options?.root ?? null,
rootMargin: options?.rootMargin ?? "0px",
scrollMargin: options?.scrollMargin ?? "0px",
takeRecords: vi.fn(takeNoRecords),
thresholds: [0],
unobserve: vi.fn(),
} satisfies MockObserver;

observers.push(observer);

return observer;
};

const installIntersectionObserver = () => {
vi.stubGlobal("IntersectionObserver", MockIntersectionObserver);
};

const TestCard = ({ name }: { readonly name: string }) => {
const { isNearViewport, ref } = useNearViewport<HTMLDivElement>();

return (
<div data-testid={`${name}-shell`} ref={ref}>
{name}
{isNearViewport ? <span>{`${name} controls`}</span> : <span>{`${name} placeholder`}</span>}
</div>
);
};

afterEach(() => {
observers.length = 0;
vi.unstubAllGlobals();
});

describe("useNearViewport", () => {
it("mounts deferred content when its shell approaches the viewport and keeps it mounted", () => {
installIntersectionObserver();
render(<TestCard name="first" />);

expect(screen.getByTestId("first-shell")).toBeInTheDocument();
expect(screen.getByText("first placeholder")).toBeInTheDocument();
expect(screen.queryByText("first controls")).not.toBeInTheDocument();
expect(observers).toHaveLength(1);
expect(observers[0]?.rootMargin).toBe("600px 0px");
expect(observers[0]?.scrollMargin).toBe("0px");

const [observer] = observers;
const shell = screen.getByTestId("first-shell");

if (observer === undefined) {
throw new Error("Expected an IntersectionObserver");
}

act(() => {
observer.callback([createEntry(shell, true)], observer);
});

expect(screen.getByText("first controls")).toBeInTheDocument();
expect(screen.queryByText("first placeholder")).not.toBeInTheDocument();
expect(observer.unobserve).toHaveBeenCalledWith(shell);

act(() => {
observer.callback([createEntry(shell, false)], observer);
});

expect(screen.getByText("first controls")).toBeInTheDocument();
});

it("shares one observer across multiple shells", () => {
installIntersectionObserver();
render(
<>
<TestCard name="first" />
<TestCard name="second" />
</>,
);

expect(observers).toHaveLength(1);
expect(observers[0]?.observe).toHaveBeenCalledTimes(2);

const [observer] = observers;
const secondShell = screen.getByTestId("second-shell");

if (observer === undefined) {
throw new Error("Expected an IntersectionObserver");
}

act(() => {
observer.callback([createEntry(secondShell, true)], observer);
});

expect(screen.getByText("first placeholder")).toBeInTheDocument();
expect(screen.getByText("second controls")).toBeInTheDocument();
});

it("uses the nearest scroll container as the preload root", () => {
installIntersectionObserver();
render(
<div
data-testid="scroll-root"
ref={(element) => {
if (element !== null) {
Object.defineProperties(element, {
clientHeight: { configurable: true, value: 100 },
scrollHeight: { configurable: true, value: 1000 },
});
}
}}
style={{ overflowY: "auto" }}
>
<TestCard name="first" />
</div>,
);

expect(observers).toHaveLength(1);
expect(observers[0]?.root).toBe(screen.getByTestId("scroll-root"));
expect(observers[0]?.rootMargin).toBe("600px 0px");
});

it("skips an overflow wrapper that does not actually scroll", () => {
installIntersectionObserver();
render(
<div
data-testid="scroll-root"
ref={(element) => {
if (element !== null) {
Object.defineProperties(element, {
clientHeight: { configurable: true, value: 100 },
scrollHeight: { configurable: true, value: 1000 },
});
}
}}
style={{ overflowY: "auto" }}
>
<div data-testid="overflow-wrapper" style={{ overflowY: "auto" }}>
<TestCard name="first" />
</div>
</div>,
);

expect(observers).toHaveLength(1);
expect(observers[0]?.root).toBe(screen.getByTestId("scroll-root"));
expect(observers[0]?.root).not.toBe(screen.getByTestId("overflow-wrapper"));
});

it("unobserves a pending shell and releases the shared observer on unmount", () => {
installIntersectionObserver();
const { unmount } = render(<TestCard name="first" />);

const [observer] = observers;
const shell = screen.getByTestId("first-shell");

if (observer === undefined) {
throw new Error("Expected an IntersectionObserver");
}

unmount();

expect(observer.unobserve).toHaveBeenCalledWith(shell);
expect(observer.disconnect).toHaveBeenCalledOnce();
});

it("mounts content when IntersectionObserver is unavailable", async () => {
vi.stubGlobal("IntersectionObserver", undefined);
render(<TestCard name="first" />);

expect(await screen.findByText("first controls")).toBeInTheDocument();
});
});
148 changes: 148 additions & 0 deletions airflow-core/src/airflow/ui/src/hooks/useNearViewport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*!
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { startTransition, useCallback, useEffect, useRef, useState, type RefObject } from "react";

const NEAR_VIEWPORT_MARGIN = "600px 0px";

type ObserverState = {
readonly listeners: Map<Element, () => void>;
readonly observer: IntersectionObserver;
};

const observerStates = new Map<Element | null, ObserverState>();

const getScrollRoot = (element: Element): Element | null => {
let ancestor = element.parentElement;
let overflowAncestor: Element | null = null;

// Use the nearest ancestor that actually scrolls, falling back to the nearest
// overflow container when its content currently fits without scrolling.
while (ancestor !== null) {
const { overflowY } = globalThis.getComputedStyle(ancestor);

if (/^(?:auto|overlay|scroll)$/u.test(overflowY)) {
overflowAncestor ??= ancestor;

if (ancestor.scrollHeight > ancestor.clientHeight) {
return ancestor;
}
}

ancestor = ancestor.parentElement;
}
Comment thread
shivaam marked this conversation as resolved.

return overflowAncestor;
};

const releaseObserverWhenIdle = (root: Element | null, state: ObserverState) => {
if (state.listeners.size === 0) {
state.observer.disconnect();

if (observerStates.get(root) === state) {
observerStates.delete(root);
}
}
};

const getSharedObserver = (observerConstructor: typeof IntersectionObserver, root: Element | null) => {
const currentState = observerStates.get(root);

if (currentState !== undefined) {
return currentState;
}

const listeners = new Map<Element, () => void>();
const observer = new observerConstructor(
(entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
return;
}

const listener = listeners.get(entry.target);

if (listener !== undefined) {
listeners.delete(entry.target);
observer.unobserve(entry.target);
listener();
}
});
const observerState = observerStates.get(root);

if (observerState !== undefined) {
releaseObserverWhenIdle(root, observerState);
}
},
{ root, rootMargin: NEAR_VIEWPORT_MARGIN },
);

const state = { listeners, observer };

observerStates.set(root, state);

return state;
};

const observeNearViewport = (element: Element, listener: () => void) => {
const observerConstructor = (globalThis as { IntersectionObserver?: typeof IntersectionObserver })
.IntersectionObserver;

// If observation is unavailable, we immediately call the listener.
if (observerConstructor === undefined) {
listener();

return undefined;
}

const root = getScrollRoot(element);
const state = getSharedObserver(observerConstructor, root);

state.listeners.set(element, listener);
state.observer.observe(element);

return () => {
state.listeners.delete(element);
state.observer.unobserve(element);
releaseObserverWhenIdle(root, state);
};
};

export const useNearViewport = <TElement extends Element>(): {
readonly isNearViewport: boolean;
readonly ref: RefObject<TElement | null>;
readonly showContent: () => void;
} => {
const ref = useRef<TElement>(null);
const [isNearViewport, setIsNearViewport] = useState(false);
const showContent = useCallback(() => setIsNearViewport(true), []);

useEffect(() => {
const element = ref.current;

if (isNearViewport || element === null) {
return undefined;
}

return observeNearViewport(element, () => {
startTransition(showContent);
});
}, [isNearViewport, showContent]);

return { isNearViewport, ref, showContent };
};
Loading
Loading