Skip to content

Commit 4db892e

Browse files
authored
Progressively load interactive elements of Dag Card (#69806)
* Render DAG card content near the viewport * Preload DAG cards from their scroll root * Explain DAG card scroll root selection
1 parent b6cc81c commit 4db892e

5 files changed

Lines changed: 564 additions & 35 deletions

File tree

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
/*!
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
import { act, render, screen } from "@testing-library/react";
20+
import { afterEach, describe, expect, it, vi } from "vitest";
21+
22+
import { useNearViewport } from "./useNearViewport";
23+
24+
type MockObserver = {
25+
callback: IntersectionObserverCallback;
26+
} & IntersectionObserver;
27+
28+
const observers: Array<MockObserver> = [];
29+
30+
const createEntry = (target: Element, isIntersecting: boolean): IntersectionObserverEntry => ({
31+
boundingClientRect: target.getBoundingClientRect(),
32+
intersectionRatio: isIntersecting ? 1 : 0,
33+
intersectionRect: target.getBoundingClientRect(),
34+
isIntersecting,
35+
rootBounds: null,
36+
target,
37+
time: 0,
38+
});
39+
40+
const takeNoRecords = () => [];
41+
42+
const MockIntersectionObserver = function MockIntersectionObserver(
43+
callback: IntersectionObserverCallback,
44+
options?: IntersectionObserverInit,
45+
): IntersectionObserver {
46+
const observer = {
47+
callback,
48+
disconnect: vi.fn(),
49+
observe: vi.fn(),
50+
root: options?.root ?? null,
51+
rootMargin: options?.rootMargin ?? "0px",
52+
scrollMargin: options?.scrollMargin ?? "0px",
53+
takeRecords: vi.fn(takeNoRecords),
54+
thresholds: [0],
55+
unobserve: vi.fn(),
56+
} satisfies MockObserver;
57+
58+
observers.push(observer);
59+
60+
return observer;
61+
};
62+
63+
const installIntersectionObserver = () => {
64+
vi.stubGlobal("IntersectionObserver", MockIntersectionObserver);
65+
};
66+
67+
const TestCard = ({ name }: { readonly name: string }) => {
68+
const { isNearViewport, ref } = useNearViewport<HTMLDivElement>();
69+
70+
return (
71+
<div data-testid={`${name}-shell`} ref={ref}>
72+
{name}
73+
{isNearViewport ? <span>{`${name} controls`}</span> : <span>{`${name} placeholder`}</span>}
74+
</div>
75+
);
76+
};
77+
78+
afterEach(() => {
79+
observers.length = 0;
80+
vi.unstubAllGlobals();
81+
});
82+
83+
describe("useNearViewport", () => {
84+
it("mounts deferred content when its shell approaches the viewport and keeps it mounted", () => {
85+
installIntersectionObserver();
86+
render(<TestCard name="first" />);
87+
88+
expect(screen.getByTestId("first-shell")).toBeInTheDocument();
89+
expect(screen.getByText("first placeholder")).toBeInTheDocument();
90+
expect(screen.queryByText("first controls")).not.toBeInTheDocument();
91+
expect(observers).toHaveLength(1);
92+
expect(observers[0]?.rootMargin).toBe("600px 0px");
93+
expect(observers[0]?.scrollMargin).toBe("0px");
94+
95+
const [observer] = observers;
96+
const shell = screen.getByTestId("first-shell");
97+
98+
if (observer === undefined) {
99+
throw new Error("Expected an IntersectionObserver");
100+
}
101+
102+
act(() => {
103+
observer.callback([createEntry(shell, true)], observer);
104+
});
105+
106+
expect(screen.getByText("first controls")).toBeInTheDocument();
107+
expect(screen.queryByText("first placeholder")).not.toBeInTheDocument();
108+
expect(observer.unobserve).toHaveBeenCalledWith(shell);
109+
110+
act(() => {
111+
observer.callback([createEntry(shell, false)], observer);
112+
});
113+
114+
expect(screen.getByText("first controls")).toBeInTheDocument();
115+
});
116+
117+
it("shares one observer across multiple shells", () => {
118+
installIntersectionObserver();
119+
render(
120+
<>
121+
<TestCard name="first" />
122+
<TestCard name="second" />
123+
</>,
124+
);
125+
126+
expect(observers).toHaveLength(1);
127+
expect(observers[0]?.observe).toHaveBeenCalledTimes(2);
128+
129+
const [observer] = observers;
130+
const secondShell = screen.getByTestId("second-shell");
131+
132+
if (observer === undefined) {
133+
throw new Error("Expected an IntersectionObserver");
134+
}
135+
136+
act(() => {
137+
observer.callback([createEntry(secondShell, true)], observer);
138+
});
139+
140+
expect(screen.getByText("first placeholder")).toBeInTheDocument();
141+
expect(screen.getByText("second controls")).toBeInTheDocument();
142+
});
143+
144+
it("uses the nearest scroll container as the preload root", () => {
145+
installIntersectionObserver();
146+
render(
147+
<div
148+
data-testid="scroll-root"
149+
ref={(element) => {
150+
if (element !== null) {
151+
Object.defineProperties(element, {
152+
clientHeight: { configurable: true, value: 100 },
153+
scrollHeight: { configurable: true, value: 1000 },
154+
});
155+
}
156+
}}
157+
style={{ overflowY: "auto" }}
158+
>
159+
<TestCard name="first" />
160+
</div>,
161+
);
162+
163+
expect(observers).toHaveLength(1);
164+
expect(observers[0]?.root).toBe(screen.getByTestId("scroll-root"));
165+
expect(observers[0]?.rootMargin).toBe("600px 0px");
166+
});
167+
168+
it("skips an overflow wrapper that does not actually scroll", () => {
169+
installIntersectionObserver();
170+
render(
171+
<div
172+
data-testid="scroll-root"
173+
ref={(element) => {
174+
if (element !== null) {
175+
Object.defineProperties(element, {
176+
clientHeight: { configurable: true, value: 100 },
177+
scrollHeight: { configurable: true, value: 1000 },
178+
});
179+
}
180+
}}
181+
style={{ overflowY: "auto" }}
182+
>
183+
<div data-testid="overflow-wrapper" style={{ overflowY: "auto" }}>
184+
<TestCard name="first" />
185+
</div>
186+
</div>,
187+
);
188+
189+
expect(observers).toHaveLength(1);
190+
expect(observers[0]?.root).toBe(screen.getByTestId("scroll-root"));
191+
expect(observers[0]?.root).not.toBe(screen.getByTestId("overflow-wrapper"));
192+
});
193+
194+
it("unobserves a pending shell and releases the shared observer on unmount", () => {
195+
installIntersectionObserver();
196+
const { unmount } = render(<TestCard name="first" />);
197+
198+
const [observer] = observers;
199+
const shell = screen.getByTestId("first-shell");
200+
201+
if (observer === undefined) {
202+
throw new Error("Expected an IntersectionObserver");
203+
}
204+
205+
unmount();
206+
207+
expect(observer.unobserve).toHaveBeenCalledWith(shell);
208+
expect(observer.disconnect).toHaveBeenCalledOnce();
209+
});
210+
211+
it("mounts content when IntersectionObserver is unavailable", async () => {
212+
vi.stubGlobal("IntersectionObserver", undefined);
213+
render(<TestCard name="first" />);
214+
215+
expect(await screen.findByText("first controls")).toBeInTheDocument();
216+
});
217+
});
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
/*!
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
import { startTransition, useCallback, useEffect, useRef, useState, type RefObject } from "react";
20+
21+
const NEAR_VIEWPORT_MARGIN = "600px 0px";
22+
23+
type ObserverState = {
24+
readonly listeners: Map<Element, () => void>;
25+
readonly observer: IntersectionObserver;
26+
};
27+
28+
const observerStates = new Map<Element | null, ObserverState>();
29+
30+
const getScrollRoot = (element: Element): Element | null => {
31+
let ancestor = element.parentElement;
32+
let overflowAncestor: Element | null = null;
33+
34+
// Use the nearest ancestor that actually scrolls, falling back to the nearest
35+
// overflow container when its content currently fits without scrolling.
36+
while (ancestor !== null) {
37+
const { overflowY } = globalThis.getComputedStyle(ancestor);
38+
39+
if (/^(?:auto|overlay|scroll)$/u.test(overflowY)) {
40+
overflowAncestor ??= ancestor;
41+
42+
if (ancestor.scrollHeight > ancestor.clientHeight) {
43+
return ancestor;
44+
}
45+
}
46+
47+
ancestor = ancestor.parentElement;
48+
}
49+
50+
return overflowAncestor;
51+
};
52+
53+
const releaseObserverWhenIdle = (root: Element | null, state: ObserverState) => {
54+
if (state.listeners.size === 0) {
55+
state.observer.disconnect();
56+
57+
if (observerStates.get(root) === state) {
58+
observerStates.delete(root);
59+
}
60+
}
61+
};
62+
63+
const getSharedObserver = (observerConstructor: typeof IntersectionObserver, root: Element | null) => {
64+
const currentState = observerStates.get(root);
65+
66+
if (currentState !== undefined) {
67+
return currentState;
68+
}
69+
70+
const listeners = new Map<Element, () => void>();
71+
const observer = new observerConstructor(
72+
(entries) => {
73+
entries.forEach((entry) => {
74+
if (!entry.isIntersecting) {
75+
return;
76+
}
77+
78+
const listener = listeners.get(entry.target);
79+
80+
if (listener !== undefined) {
81+
listeners.delete(entry.target);
82+
observer.unobserve(entry.target);
83+
listener();
84+
}
85+
});
86+
const observerState = observerStates.get(root);
87+
88+
if (observerState !== undefined) {
89+
releaseObserverWhenIdle(root, observerState);
90+
}
91+
},
92+
{ root, rootMargin: NEAR_VIEWPORT_MARGIN },
93+
);
94+
95+
const state = { listeners, observer };
96+
97+
observerStates.set(root, state);
98+
99+
return state;
100+
};
101+
102+
const observeNearViewport = (element: Element, listener: () => void) => {
103+
const observerConstructor = (globalThis as { IntersectionObserver?: typeof IntersectionObserver })
104+
.IntersectionObserver;
105+
106+
// If observation is unavailable, we immediately call the listener.
107+
if (observerConstructor === undefined) {
108+
listener();
109+
110+
return undefined;
111+
}
112+
113+
const root = getScrollRoot(element);
114+
const state = getSharedObserver(observerConstructor, root);
115+
116+
state.listeners.set(element, listener);
117+
state.observer.observe(element);
118+
119+
return () => {
120+
state.listeners.delete(element);
121+
state.observer.unobserve(element);
122+
releaseObserverWhenIdle(root, state);
123+
};
124+
};
125+
126+
export const useNearViewport = <TElement extends Element>(): {
127+
readonly isNearViewport: boolean;
128+
readonly ref: RefObject<TElement | null>;
129+
readonly showContent: () => void;
130+
} => {
131+
const ref = useRef<TElement>(null);
132+
const [isNearViewport, setIsNearViewport] = useState(false);
133+
const showContent = useCallback(() => setIsNearViewport(true), []);
134+
135+
useEffect(() => {
136+
const element = ref.current;
137+
138+
if (isNearViewport || element === null) {
139+
return undefined;
140+
}
141+
142+
return observeNearViewport(element, () => {
143+
startTransition(showContent);
144+
});
145+
}, [isNearViewport, showContent]);
146+
147+
return { isNearViewport, ref, showContent };
148+
};

0 commit comments

Comments
 (0)