Skip to content

Commit

Permalink
Autoscroll to bottom of output log
Browse files Browse the repository at this point in the history
  • Loading branch information
rameshvarun committed Sep 8, 2023
1 parent 5b66728 commit e28906c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 21 deletions.
45 changes: 25 additions & 20 deletions src/blog-cells.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,29 +57,30 @@ class Cell extends React.Component<
kernel: Kernel;
onMount?: () => void;
},
any
{
kind: "ready" | "running" | "re-runnable";
output: { type: string; line: string }[];
hidden: boolean;
}
> {
codeMirror: EditorView | null = null;
editor: React.RefObject<HTMLDivElement> = React.createRef();
outputRef: React.RefObject<HTMLPreElement> = React.createRef();

running: boolean;
mounted: boolean;

constructor(props) {
super(props);
this.state = { kind: "ready", output: [] };
this.state = {
kind: "ready",
output: [],
hidden: props.hideable === true,
};

this.running = false;
this.mounted = false;

if (props.hideable) {
// @ts-ignore
this.state.hidden = true;
} else {
// @ts-ignore
this.state.hidden = false;
}

if (props.autoRun) {
this.run(props.code);
}
Expand Down Expand Up @@ -114,7 +115,7 @@ class Cell extends React.Component<
<div ref={this.editor}></div>
{this.state.output.length > 0 ? (
<div>
<pre className="snippet-output">
<pre ref={this.outputRef} className="snippet-output">
{this.state.output.map((output, i) => (
<div className={"output-" + output.type} key={i}>
{output.line}
Expand Down Expand Up @@ -183,6 +184,12 @@ class Cell extends React.Component<
}
}

componentDidUpdate(prevProps, prevState) {
if (this.state.output.length > prevState.output.length) {
this.outputRef.current!.scrollTop = this.outputRef.current!.scrollHeight;
}
}

async run(code) {
if (this.running) return;

Expand All @@ -205,8 +212,9 @@ class Cell extends React.Component<
// Run the code.
await this.props.kernel.run(code, (line) => {
this.setState((state) => {
state.output.push(line);
return state;
return {
output: [...state.output, line],
};
});
});

Expand All @@ -216,13 +224,10 @@ class Cell extends React.Component<
// Mark as not running.
this.running = false;

// Update the state.
this.setState((state) => {
state.kind = "re-runnable";
if (state.output.length === 0)
state.output.push({ type: "log", line: "Done." });
return state;
});
this.setState({ kind: "re-runnable" });
if (this.state.output.length === 0) {
this.setState({ output: [{ type: "log", line: "Done." }] });
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ export abstract class Kernel {

getSyntaxHighlighter(): LanguageSupport | null {
return null;
};
}
}

0 comments on commit e28906c

Please sign in to comment.