Skip to content

Commit

Permalink
コンソールの自動スクロール機能を改善し、サブツリーの変更も監視するように修正。スロットリング機能を追加。
Browse files Browse the repository at this point in the history
  • Loading branch information
todays-mitsui committed Jan 28, 2025
1 parent 250f6a0 commit 95ac4ff
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
30 changes: 18 additions & 12 deletions mogul/src/components/Console.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@ import {
import styles from "./Console.module.css";
import { ReduceRow } from "./ReduceRow";
import { renderExpr } from "~/service/unlambda";
import { throttle } from "~/lib/throttle";

interface Props {
interface ConsoleProps {
class?: string;
}

export default function Console(props: Props): JSX.Element {
export default function Console(props: ConsoleProps): JSX.Element {
let wrapper: HTMLDivElement | undefined;
createEffect(() => {
if (wrapper == null) return;
Expand All @@ -41,29 +42,34 @@ export default function Console(props: Props): JSX.Element {
onClick={() => sideTools.closeAll()}
ref={wrapper}
>
<Index each={consoleOut()} fallback={<div>Loading...</div>}>
{(item) => <ConsoleUnit {...item()} />}
</Index>
<Index each={consoleOut()}>{(item) => <ConsoleUnit {...item()} />}</Index>
</div>
);
}

/**
* コンソールへの要素追加を監視して自動で最下部へスクロールする
*/
function createObserver(wrapper: HTMLDivElement): MutationObserver {
const scrollTo = throttle(() => {
setTimeout(() => {
wrapper.scrollTo({
top: wrapper.scrollHeight,
behavior: "smooth",
});
}, 100);
}, 100);

const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
setTimeout(() => {
wrapper.scrollTo({
top: wrapper.scrollHeight,
behavior: "smooth",
});
}, 100);
scrollTo();
}
}
});
observer.observe(wrapper, {
childList: true, // 子要素の追加や削除を監視
subtree: false, // 子孫要素は監視しない
subtree: true, // 子孫要素も監視する
});
return observer;
}
Expand Down
14 changes: 14 additions & 0 deletions mogul/src/lib/throttle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export function throttle<T extends (...args: any[]) => any>(
func: T,
wait: number,
): (...args: Parameters<T>) => void {
let lastTime = 0;

return function (this: any, ...args: Parameters<T>): void {
const now = Date.now();
if (now - lastTime >= wait) {
lastTime = now;
func.apply(this, args);
}
};
}

0 comments on commit 95ac4ff

Please sign in to comment.