Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions tests/repl.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { expect, test, type Page } from "@playwright/test";

test.setTimeout(60_000);

async function openReplConsole(page: Page, code: string, evaluate: boolean) {
const response = await page.goto(
`/repl#?evaluate=${evaluate}&code=${encodeURIComponent(code)}`,
{ waitUntil: "domcontentloaded" }
);
expect(response?.status()).toBe(200);

await page
.locator(".pills__item", { hasText: /^console$/ })
.click({ timeout: 30_000 });
}

test("repl console shows the output of the evaluated code", async ({
page,
}) => {
await openReplConsole(
page,
[
'console.log("answer:", { value: 42, list: [1, "two"] });',
'console.warn("%s is deprecated", "foo");',
"setTimeout(() => { throw new Error('async'); });",
"throw new TypeError('sync');",
].join("\n"),
true
);

const entries = page.getByRole("log").locator("pre");
await expect(entries).toHaveText(
[
'answer: { value: 42, list: [ 1, "two" ] }',
"foo is deprecated",
"Uncaught TypeError: sync",
"Uncaught Error: async",
],
{ timeout: 30_000 }
);
});

test("repl console asks to enable evaluation", async ({ page }) => {
await openReplConsole(page, 'console.log("hello");', false);

await expect(
page.getByText('Enable "Evaluate" in the settings')
).toBeVisible();
});
40 changes: 40 additions & 0 deletions website/src/components/repl/ConsolePanel.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
@import "./lib/styles.css";

.console {
flex: 1;
min-height: 0;
overflow: auto;
font-family: var(--ifm-font-family-monospace);
font-size: 13px;
line-height: 18px;
-webkit-overflow-scrolling: touch;
}

.placeholder {
padding: 0.5rem 0.75rem;
color: var(--colors-foregroundLight);
}

.entry {
margin: 0;
padding: 0.25rem 0.75rem;
border-radius: 0;
border-bottom: 1px solid var(--ifm-scrollbar-track-background-color);
background: transparent;
color: inherit;
font: inherit;
white-space: pre-wrap;
overflow-wrap: anywhere;
}

.warn {
background-color: var(--colors-infoBackground);
border-bottom-color: var(--colors-infoBorder);
color: var(--colors-infoForeground);
}

.error {
background-color: var(--colors-errorBackground);
border-bottom-color: var(--colors-errorBorder);
color: var(--colors-errorForeground);
}
54 changes: 54 additions & 0 deletions website/src/components/repl/ConsolePanel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React, { useEffect, useRef } from "react";

import styles from "./ConsolePanel.module.css";

import type { ConsoleEntry, ConsoleLevel } from "./lib/types";

type Props = {
entries: ReadonlyArray<ConsoleEntry>;
isEvaluateEnabled: boolean;
};

const levelClassNames: Partial<Record<ConsoleLevel, string>> = {
warn: styles.warn,
error: styles.error,
};

export default function ConsolePanel({ entries, isEvaluateEnabled }: Props) {
const container = useRef<HTMLDivElement>(null);

useEffect(() => {
// Keep the latest messages visible.
container.current.scrollTop = container.current.scrollHeight;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should only scroll down when the view is already at or near the bottom: Every time new messages arrive, this effect scrolls the panel to the very bottom. It doesn't check where user were looking, so it pulls down even if user had scrolled up.

}, [entries]);

let placeholder: string | null = null;
if (!isEvaluateEnabled) {
placeholder =
'Enable "Evaluate" in the settings to run the compiled code and see its console output here';
} else if (entries.length === 0) {
placeholder = "Console output will be shown here";
}

return (
<div
ref={container}
className={styles.console}
role="log"
aria-label="Console output"
>
{placeholder ? (
<div className={styles.placeholder}>{placeholder}</div>
) : (
entries.map((entry, index) => (
<pre
key={index}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When console entries reach the MAX_CONSOLE_ENTRIES limit, every key will points to different content on every batch. Because we have role="log" here, an accessibility screen reader may announce them again. Consider use a stable id for each message.

className={`${styles.entry} ${levelClassNames[entry.level] ?? ""}`}
>
{entry.message}
</pre>
))
)}
</div>
);
}
24 changes: 23 additions & 1 deletion website/src/components/repl/Repl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import React, { type ChangeEvent } from "react";
import { prettySize, compareVersions } from "./lib/utils";
import ErrorBoundary from "./ErrorBoundary";
import { load as loadMonaco, Monaco } from "./Monaco";
import ConsolePanel from "./ConsolePanel";
import ReplOptions from "./ReplOptions";
import StorageService from "./lib/storageService";
import UriUtils from "./lib/uriUtils";
Expand Down Expand Up @@ -42,6 +43,7 @@ import { toCamelCase, hasOwnProperty } from "./lib/utils";
import type {
BabelState,
BabelPlugin,
ConsoleEntry,
EnvState,
ShippedProposalsState,
EnvConfig,
Expand All @@ -66,6 +68,7 @@ type State = {
inputAst: File;
astSelectedRange: [number, number] | null;
compileErrorMessage: string | undefined | null;
consoleEntries: ReadonlyArray<ConsoleEntry>;
envConfig: EnvConfig;
envPresetState: EnvState;
shippedProposalsState: ShippedProposalsState;
Expand Down Expand Up @@ -132,6 +135,7 @@ class Repl extends React.Component<Props, State> {
astSelectedRange: null,
pluginSearch: "",
compileErrorMessage: null,
consoleEntries: [],
presetsOptions,
envConfig,
envPresetState: persistedStateToEnvState(
Expand Down Expand Up @@ -173,6 +177,14 @@ class Repl extends React.Component<Props, State> {
this._setupBabel(defaultPresets);
}

componentDidMount() {
scopedEval.setConsoleListener(this._onConsoleChange);
}

componentWillUnmount() {
scopedEval.setConsoleListener(null);
}

_configToState = (configObject: any) => {
const state = this.state;
const newState: Pick<State, keyof State> = {} as any;
Expand Down Expand Up @@ -402,7 +414,7 @@ class Repl extends React.Component<Props, State> {
<div className={styles.codePanel}>
<Tabs
current={state.rightTab}
labels={["output", "input AST"]}
labels={["output", "input AST", "console"]}
onClick={(rightTab) => {
this.setState({ rightTab });
}}
Expand All @@ -427,6 +439,12 @@ class Repl extends React.Component<Props, State> {
value={this.state.inputAst}
/>
)}
{state.rightTab === "console" && (
<ConsolePanel
entries={state.consoleEntries}
isEvaluateEnabled={state.runtimePolyfillState.isEnabled}
/>
)}
</div>
</div>
{state.timeTravel && (
Expand Down Expand Up @@ -754,6 +772,10 @@ class Repl extends React.Component<Props, State> {
);
};

_onConsoleChange = (consoleEntries: ReadonlyArray<ConsoleEntry>) => {
this.setState({ consoleEntries });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is from claude:

Consider use useSyncExternalStore to let ConsolePanel subscribes to itself rather than trigger the re-render of the REPL component whenever there is new console entries:

// scopedEval.ts
const listeners = new Set<() => void>();
let snapshot: ReadonlyArray<ConsoleEntry> = [];

function notifyConsoleListeners() {
  isNotifyScheduled = false;
  snapshot = consoleEntries.slice();
  listeners.forEach(l => l());
}

export function subscribeConsole(l: () => void) {
  listeners.add(l);
  return () => listeners.delete(l);
}
export const getConsoleSnapshot = () => snapshot;
// ConsolePanel.tsx
const entries = useSyncExternalStore(subscribeConsole, getConsoleSnapshot);

};

_onIsSidebarExpandedChange = (isExpanded: boolean) => {
this.setState(
{
Expand Down
Loading
Loading