Skip to content

Commit dea8872

Browse files
committed
feat: intersection handling
1 parent 0b81f3e commit dea8872

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

src/index.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ const CoCreateEvents = {
4040
this.initPrefix("selected", ["click"]);
4141
this.initPrefix("onload", ["onload"]);
4242
this.initPrefix("observe", ["observer"]);
43+
this.initPrefix("intersection", ["intersection"]);
4344
this.initPrefix("resize", ["onload", "resize"]);
4445
this.initPrefix("localstorage", ["onload"]);
4546
this.initPrefix("focus", ["focus"]);
@@ -211,10 +212,68 @@ const CoCreateEvents = {
211212
resizeObserver.observe(el);
212213
}
213214

215+
if (events.includes("intersection")) {
216+
const rootSelector = el.getAttribute(`${prefix}-root`);
217+
const rootMargin =
218+
el.getAttribute(`${prefix}-root-margin`) || "0px";
219+
const threshold = el.getAttribute(`${prefix}-threshold`)
220+
? JSON.parse(el.getAttribute(`${prefix}-threshold`))
221+
: [0];
222+
const trigger = el.getAttribute(`${prefix}-trigger`) || "both"; // Default to "both"
223+
224+
// Resolve root from the selector or use null for viewport
225+
const root = rootSelector
226+
? document.querySelector(rootSelector)
227+
: null;
228+
229+
// Validate and filter threshold values
230+
const validThreshold = Array.isArray(threshold)
231+
? threshold.filter((value) => value >= 0 && value <= 1)
232+
: [0];
233+
234+
// Create IntersectionObserver
235+
const intersectionObserver = new IntersectionObserver(
236+
(entries) => {
237+
entries.forEach((entry) => {
238+
const isVisible = entry.isIntersecting;
239+
240+
// Determine if __updateElements should be called based on trigger
241+
// if (
242+
// (trigger === "visible" && isVisible) ||
243+
// (trigger === "not-visible" && !isVisible) ||
244+
// trigger === "both"
245+
// ) {
246+
if (isVisible) {
247+
// Set an attribute to reflect visibility state
248+
el.setAttribute(
249+
`${prefix}-is-visible`,
250+
isVisible ? "true" : "false"
251+
);
252+
253+
// Call __updateElements
254+
self.__updateElements(
255+
el,
256+
prefix
257+
// {
258+
// isVisible,
259+
// intersectionRatio:
260+
// entry.intersectionRatio
261+
// }
262+
);
263+
}
264+
});
265+
},
266+
{ root, rootMargin, threshold: validThreshold }
267+
);
268+
269+
intersectionObserver.observe(el);
270+
}
271+
214272
for (let i = 0; i < events.length; i++) {
215273
if (
216274
events[i] !== "onload" &&
217275
events[i] !== "observer" &&
276+
events[i] !== "intersection" &&
218277
events[i] !== "resize"
219278
) {
220279
el.removeEventListener(events[i], eventFunction);

0 commit comments

Comments
 (0)