Skip to content
Merged
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
3 changes: 2 additions & 1 deletion apps/ppp/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@
"force_stop": "force stop",
"execution_timeout": "execution timeout (ms)",
"execution_timeout_description": "use zero to disable",
"untranslated_content": "this content has not yet been translated into your language."
"untranslated_content": "this content has not yet been translated into your language.",
"input_mode": "input mode"
}
3 changes: 2 additions & 1 deletion apps/ppp/messages/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@
"forceStop": "Остановить принудительно",
"executionTimeout": "Таймаут выполнения (мс)",
"executionTimeoutDescription": "Используйте ноль для отключения",
"currently_untranslated_problem": "Данная проблема пока не переведена для вашего языка"
"currently_untranslated_problem": "Данная проблема пока не переведена для вашего языка",
"input_mode": "режим ввода"
}
1 change: 1 addition & 0 deletions apps/ppp/src/lib/components/editor/controls/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as CheckBox } from "./checkbox.svelte";
export { default as Number } from "./number.svelte";
export { default as Select } from './select.svelte';
31 changes: 31 additions & 0 deletions apps/ppp/src/lib/components/editor/controls/select.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<script lang="ts">
import type { Snippet } from 'svelte';

interface Props {
title: string;
alt?: string;
value: string
options: string[];
label?: Snippet<[string]>;
}

let { value = $bindable(), options, label, title, alt }: Props = $props()
</script>

<fieldset class="fieldset">
<legend class="fieldset-legend">{title}</legend>
<select class="select" bind:value>
{#each options as option (option)}
<option value={option}>
{#if label}
{@render label(option)}
{:else}
{option}
{/if}
</option>
{/each}
</select>
{#if alt}
<span class="label">{alt}</span>
{/if}
</fieldset>
169 changes: 85 additions & 84 deletions apps/ppp/src/lib/components/editor/terminal.ts
Original file line number Diff line number Diff line change
@@ -1,93 +1,94 @@
import { onDestroy } from "svelte";
import { FitAddon } from "@xterm/addon-fit";
import { Terminal, type ITheme } from "@xterm/xterm";
import type { Streams, Writer } from "libs/io";
import { BACKSPACE, makeErrorWriter } from "libs/logger";
import { FitAddon } from '@xterm/addon-fit';
import { Terminal, type IDisposable, type ITheme } from '@xterm/xterm';

export function makeTerminalTheme(): ITheme {
return {
background: "oklch(22.648% 0 0)",
};
return {
background: 'oklch(22.648% 0 0)'
};
}

export interface TerminalConfig {
theme?: ITheme;
theme?: ITheme;
}

export function createTerminal({
theme = makeTerminalTheme(),
}: TerminalConfig = {}) {
const terminal = new Terminal({
theme,
fontFamily: "monospace",
convertEol: true,
rows: 1,
});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
return { terminal, fitAddon };
export enum InputMode {
Line = 'line',
Raw = 'raw'
}

export function createStreams(terminal: Terminal): Streams {
const out: Writer = {
write(data) {
terminal.write(data);
},
};
const handlers = new Set<(data: Uint8Array) => void>();
function handleData(data: Uint8Array) {
for (const handler of handlers) {
handler(data);
}
}
const encoder = new TextEncoder();
let buffer = new Uint8Array(1024);
let offset = 0;
const emptyArray = new Uint8Array();
const disposable = terminal.onData((data) => {
if (data === "\r") {
terminal.write("\r\n");
handleData(emptyArray);
return;
}
// Backspace
if (data === "\x7f") {
terminal.write("\b \b");
if (offset > 0) {
offset--;
}
handleData(BACKSPACE);
return;
}
terminal.write(data);
const input = encoder.encode(data);
if (offset + input.length > buffer.length) {
const next = new Uint8Array((offset + input.length) * 2);
next.set(buffer);
buffer = next;
}
buffer.set(input, offset);
offset += input.length;
handleData(input);
});
onDestroy(() => disposable.dispose());
return {
out,
err: makeErrorWriter(out),
in: {
read() {
const chunk = buffer.subarray(0, offset);
offset = 0;
return chunk;
},
onData(handler) {
handlers.add(handler);
return {
[Symbol.dispose]() {
handlers.delete(handler);
},
};
},
},
};
}
export const INPUT_MODS = Object.values(InputMode)

export function createTerminal({ theme = makeTerminalTheme() }: TerminalConfig = {}) {
const terminal = new Terminal({
theme,
fontFamily: 'monospace',
convertEol: true,
rows: 1
});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
return { terminal, fitAddon };
}

export function createReadableStream(terminal: Terminal) {
let disposable: IDisposable;
return new ReadableStream<string>({
start(controller) {
disposable = terminal.onData((data) => {
controller.enqueue(data);
});
},
cancel() {
console.log("CANCEL")
disposable.dispose();
}
});
}

const EMPTY_UINT8_ARRAY = new Uint8Array();
const TEXT_ENCODER = new TextEncoder();

export function createRawInputMode(terminal: Terminal) {
return new TransformStream<string, Uint8Array>({
transform(chunk, controller) {
if (chunk === '\x04') {
terminal.write('<EOF>');
controller.enqueue(EMPTY_UINT8_ARRAY);
return;
}
terminal.write(chunk);
controller.enqueue(TEXT_ENCODER.encode(chunk));
}
});
}

export function createLineInputMode(terminal: Terminal) {
const buffer: string[] = [];
function flush(controller: TransformStreamDefaultController<Uint8Array>) {
if (buffer.length > 0) {
controller.enqueue(TEXT_ENCODER.encode(buffer.join('')));
buffer.length = 0;
}
}
return new TransformStream<string, Uint8Array>({
transform(chunk, controller) {
if (chunk === '\r') {
terminal.write('\r\n');
flush(controller);
// EOF
controller.enqueue(EMPTY_UINT8_ARRAY);
return;
}
// Backspace
if (chunk === '\x7f') {
if (buffer.pop() !== undefined) {
terminal.write('\b \b');
}
return;
}
terminal.write(chunk);
buffer.push(chunk);
},
flush
});
}
37 changes: 27 additions & 10 deletions apps/ppp/src/lib/problem/editor.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { createLogger } from 'libs/logger';
import { createContext, createRecoverableContext, withCancel, withTimeout } from 'libs/context';
import { runTests, type TestCase, type TestCompiler } from 'libs/testing';
import type { ReadableStreamOfBytes } from 'libs/io';
import LucideInfo from '~icons/lucide/info';
import LucideCircleX from '~icons/lucide/circle-x';
import LucideCircleCheck from '~icons/lucide/circle-check';
Expand All @@ -32,7 +33,11 @@
EditorContext,
setEditorContext,
type ProcessStatus,
createStreams
createReadableStream,
createLineInputMode,
INPUT_MODS,
InputMode,
createRawInputMode,
} from '$lib/components/editor';
import {
Panel,
Expand All @@ -42,7 +47,7 @@
TerminalTab,
TabContent
} from '$lib/components/editor/panel';
import { CheckBox, Number } from '$lib/components/editor/controls';
import { CheckBox, Number, Select } from '$lib/components/editor/controls';
import { m } from '$lib/paraglide/messages';
import EditorProvider from '$lib/editor-provider.svelte';

Expand Down Expand Up @@ -120,12 +125,6 @@
};
});

const { terminal, fitAddon } = createTerminal();
const streams = createStreams(terminal);

const editorContext = new EditorContext(model, terminal, fitAddon);
setEditorContext(editorContext);

const editorWidthStorage = createSyncStorage(
localStorage,
'test-editor-width',
Expand Down Expand Up @@ -177,7 +176,23 @@
let executionTimeout = $state(executionTimeoutStorage.load());
debouncedSave(executionTimeoutStorage, () => executionTimeout, 100);

const terminalLogger = createLogger(streams.out);
const inputModeStorage = createSyncStorage(localStorage, "test-editor-input-mode", InputMode.Line)
let inputMode = $state(inputModeStorage.load())
immediateSave(inputModeStorage, () => inputMode)

const { terminal, fitAddon } = createTerminal();
let lastInput: ReadableStreamOfBytes | undefined
const input = $derived.by(() => {
lastInput?.cancel()
return lastInput = createReadableStream(terminal).pipeThrough(
(inputMode === InputMode.Line ? createLineInputMode : createRawInputMode)(terminal)
)
})
const terminalLogger = createLogger(terminal);

const editorContext = new EditorContext(model, terminal, fitAddon);
setEditorContext(editorContext);

let testCompilerFactory = $derived(runtime.factory);
let status = $state<ProcessStatus>('stopped');
let lastTestId = $state(-1);
Expand All @@ -189,6 +204,7 @@
});
$effect(() => () => compilerCtx[Symbol.dispose]());
$effect(() => {
inputMode;
testCompilerFactory;
compilerCtx.cancel();
status = 'stopped';
Expand All @@ -206,7 +222,7 @@
terminal.reset();
try {
if (testCompiler === null) {
testCompiler = await testCompilerFactory(compilerCtx.ref, streams);
testCompiler = await testCompilerFactory(compilerCtx.ref, { input, output: terminal });
}
const testProgram = await testCompiler.compile(programCtxWithTimeout, [
{
Expand Down Expand Up @@ -345,6 +361,7 @@
alt={m.execution_timeout_description()}
bind:value={executionTimeout}
/>
<Select bind:value={inputMode} title={m.input_mode()} options={INPUT_MODS} />
</div>
</TabContent>
</div>
Expand Down
3 changes: 2 additions & 1 deletion apps/ppp/src/lib/problem/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { TestCompilerFactory } from 'libs/testing';

import { m } from '$lib/paraglide/messages';
import type { Locale } from '$lib/paraglide/runtime';
import type { RemoteCompilerFactoryOptions } from 'libs/compiler/actor';

export interface Problem {
titles: Record<Locale, string>
Expand All @@ -19,7 +20,7 @@ export const PROBLEM_CATEGORY_TO_LABEL: Record<ProblemCategory, () => string> =

export interface Runtime<I, O> {
code: string;
factory: TestCompilerFactory<I, O>;
factory: TestCompilerFactory<RemoteCompilerFactoryOptions, I, O>;
}

export const EDITOR_MIN_WIDTH = 5;
Expand Down
Loading