Skip to content

Commit 6d7869c

Browse files
committed
fix: new add item should be observed
1 parent 7f66ec7 commit 6d7869c

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

package/index.ts

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export const escapeWhenUpPlugin: Plugin<{
7171
* @param {Object} options - The config options for the autoScroll function.
7272
* @param {string} options.selector - The selector for the container element. (example: '#container')
7373
* @param {Context[]} [options.plugins] - The plugins for the life cycle hooks of the autoScroll function. [escapeHook,onMount,onUnmount]
74-
* @param {number} [options.throttleTime=100] - The throttle time in milliseconds.
74+
* @param {number} [options.throttleTime=100] - The throttle time in milliseconds. default is 100. 0 for no throttle.
7575
* @param {number} [options.offset=0] - The offset for the scroll position based on the container.scrollHeight.
7676
*
7777
* @return {function} The unObserverCallback function.
@@ -101,32 +101,45 @@ export default function autoScroll({
101101
.filter((result) => typeof result === "function") as OnUnmount[];
102102

103103
// main auto down scroll hook
104-
const [scrollHook] = throttle(() => {
104+
const onResize = () => {
105105
if (!!plugins.find((plugin) => plugin?.escapeHook?.(container) === true))
106106
return false;
107107
// use requestAnimationFrame for escape ResizeObserver loop
108108
requestAnimationFrame(() => {
109-
container.scrollTop = container.scrollHeight + offset;
109+
// console.log("scrollHook", container.scrollHeight - offset);
110+
container.scrollTo({
111+
top: container.scrollHeight - offset,
112+
behavior: "smooth",
113+
});
110114
});
111115
return true;
112-
}, throttleTime);
116+
};
117+
const [scrollHook] =
118+
throttleTime > 0 ? throttle(onResize, throttleTime) : [onResize];
113119

114120
// observers
115121
const resizeObserver = new ResizeObserver(() => {
122+
// console.log("ResizeObserver");
116123
scrollHook();
117124
});
125+
118126
const mutationObserver = new MutationObserver(() => {
127+
// console.log("MutationObserver");
128+
observeChildren(); // re-observe the children when the child is new added or removed
119129
scrollHook();
120130
});
121131

122132
// observe the children size change
123-
for (const child of container.children) {
124-
resizeObserver.observe(child);
125-
}
133+
const observeChildren = () => {
134+
resizeObserver.disconnect(); // clean the previous observer
135+
for (const child of container.children) {
136+
resizeObserver.observe(child);
137+
}
138+
};
139+
observeChildren();
126140

127141
// observe the subtree child list length change
128142
mutationObserver.observe(container, {
129-
subtree: true,
130143
childList: true,
131144
});
132145

0 commit comments

Comments
 (0)