-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
342 lines (307 loc) · 10.2 KB
/
app.js
File metadata and controls
342 lines (307 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import { compileCToWasm } from "./compiler.js";
import { createGameHost } from "./game.js";
const SAMPLE_PROGRAMS = [
{ id: "jump", label: "Jump", path: "./samples/jump.c" },
{ id: "move", label: "Move", path: "./samples/move.c" },
{ id: "runner", label: "Runner", path: "./samples/runner.c" },
];
const editor = document.querySelector("#editor");
const lineNumbers = document.querySelector("#line-numbers");
const errorLineHighlight = document.querySelector("#error-line-highlight");
const currentLineHighlight = document.querySelector("#current-line-highlight");
const outputText = document.querySelector("#output-text");
const outputJump = document.querySelector("#output-jump");
const sampleSelect = document.querySelector("#sample-select");
const startButton = document.querySelector("#start-overlay");
const stopButton = document.querySelector("#stop");
const canvas = document.querySelector("#screen");
const screenDim = document.querySelector("#screen-dim");
const gamepad = document.querySelector(".gamepad");
const AUTO_RUN_DELAY_MS = 500;
let compiledWasmBytes = null;
let autoRunTimer = 0;
let runSequence = 0;
let errorLine = null;
let errorLocation = null;
let currentSampleId = SAMPLE_PROGRAMS[0].id;
let sampleLoadSequence = 0;
populateSampleSelect();
editor.value = "";
syncLineNumbers();
syncCurrentLineHighlight();
const host = createGameHost(canvas, startButton, screenDim, gamepad);
sampleSelect.addEventListener("change", () => {
void selectSample(sampleSelect.value);
});
editor.addEventListener("input", () => {
syncLineNumbers();
scheduleRunCode();
});
editor.addEventListener("scroll", syncLineNumbersScroll);
editor.addEventListener("scroll", syncEditorHighlights);
editor.addEventListener("click", syncCurrentLineHighlight);
editor.addEventListener("keydown", handleEditorKeydown);
editor.addEventListener("keyup", syncCurrentLineHighlight);
editor.addEventListener("focus", syncCurrentLineHighlight);
editor.addEventListener("select", syncCurrentLineHighlight);
outputJump.addEventListener("click", () => {
if (!errorLocation) return;
focusEditorPosition(errorLocation.line, errorLocation.col);
});
startButton.addEventListener("click", async () => {
if (!compiledWasmBytes) {
renderOutput("コンパイルエラーを直してください。");
return;
}
await startProgram();
});
stopButton.addEventListener("click", () => {
clearScheduledRun();
host.stop("stopped");
});
void init();
function populateSampleSelect() {
sampleSelect.innerHTML = SAMPLE_PROGRAMS.map((sample) => (
`<option value="${sample.id}">${sample.label}</option>`
)).join("");
sampleSelect.value = currentSampleId;
}
async function init() {
await selectSample(currentSampleId);
}
async function selectSample(sampleId) {
const sample = SAMPLE_PROGRAMS.find((item) => item.id === sampleId) ?? SAMPLE_PROGRAMS[0];
const currentLoad = ++sampleLoadSequence;
currentSampleId = sample.id;
sampleSelect.value = sample.id;
clearScheduledRun();
host.stop("idle");
clearErrorLineHighlight();
renderOutput(`Loading ${sample.label}...`);
try {
const source = await fetchSampleSource(sample);
if (currentLoad !== sampleLoadSequence) return;
applySampleSource(sample, source);
scheduleRunCode({ immediate: true, jumpToError: false });
} catch (error) {
if (currentLoad !== sampleLoadSequence) return;
compiledWasmBytes = null;
renderOutput(error instanceof Error ? error.message : String(error));
}
}
async function fetchSampleSource(sample) {
const response = await fetch(sample.path);
if (!response.ok) {
throw new Error(`サンプル ${sample.label} の読み込みに失敗しました: ${response.status}`);
}
return await response.text();
}
function applySampleSource(sample, source) {
currentSampleId = sample.id;
sampleSelect.value = sample.id;
editor.value = source;
editor.focus();
editor.setSelectionRange(0, 0);
editor.scrollTop = 0;
clearErrorLineHighlight();
syncLineNumbers();
}
function clearScheduledRun() {
if (!autoRunTimer) return;
window.clearTimeout(autoRunTimer);
autoRunTimer = 0;
}
function scheduleRunCode({ immediate = false, jumpToError = false } = {}) {
clearScheduledRun();
if (immediate) {
void runCode({ jumpToError });
return;
}
autoRunTimer = window.setTimeout(() => {
autoRunTimer = 0;
void runCode({ jumpToError });
}, AUTO_RUN_DELAY_MS);
}
async function runCode({ jumpToError = false } = {}) {
const currentRun = ++runSequence;
host.stop("compiling");
clearErrorLineHighlight();
renderOutput("");
try {
const result = compileCToWasm(editor.value);
if (currentRun !== runSequence) return;
compiledWasmBytes = result.wasmBytes;
await startProgram(currentRun);
if (currentRun !== runSequence) return;
renderOutput([
"コンパイル成功",
`wasm size: ${result.wasmBytes.length} bytes`,
`globals: ${result.globalsSize} bytes`,
`stack base: ${result.stackBase}`,
].join("\n"));
} catch (error) {
if (currentRun !== runSequence) return;
compiledWasmBytes = null;
renderError(error instanceof Error ? error.message : String(error), { jumpToError });
}
}
async function startProgram(currentRun = runSequence) {
const { instance } = await WebAssembly.instantiate(compiledWasmBytes, host.imports);
if (currentRun !== runSequence) return;
host.load(instance);
if (currentRun !== runSequence) return;
host.run(instance);
}
function syncLineNumbers() {
const count = editor.value.split("\n").length;
lineNumbers.textContent = Array.from({ length: count }, (_, i) => String(i + 1)).join("\n");
syncLineNumbersScroll();
syncEditorHighlights();
}
function syncLineNumbersScroll() {
lineNumbers.scrollTop = editor.scrollTop;
}
function handleEditorKeydown(event) {
if (event.key !== "Tab") return;
event.preventDefault();
if (event.shiftKey) {
outdentSelection();
} else {
indentSelection();
}
syncLineNumbers();
}
function indentSelection() {
const start = editor.selectionStart;
const end = editor.selectionEnd;
if (start === end) {
replaceEditorRange(start, end, " ");
return;
}
const value = editor.value;
const lineStart = value.lastIndexOf("\n", Math.max(0, start - 1)) + 1;
const lineEnd = getSelectionLineEnd(value, end);
const block = value.slice(lineStart, lineEnd);
const lines = block.split("\n");
const updated = lines.map((line) => ` ${line}`).join("\n");
replaceEditorRange(lineStart, lineEnd, updated);
editor.setSelectionRange(start + 2, end + lines.length * 2);
}
function outdentSelection() {
const value = editor.value;
const start = editor.selectionStart;
const end = editor.selectionEnd;
const lineStart = value.lastIndexOf("\n", Math.max(0, start - 1)) + 1;
const lineEnd = getSelectionLineEnd(value, end);
const selectionText = value.slice(lineStart, lineEnd);
const lines = selectionText.split("\n");
let removedBeforeStart = 0;
let removedTotal = 0;
const updated = lines.map((line, index) => {
if (line.startsWith(" ")) {
removedTotal += 2;
if (index === 0) {
removedBeforeStart = Math.min(2, start - lineStart);
}
return line.slice(2);
}
return line;
}).join("\n");
replaceEditorRange(lineStart, lineEnd, updated);
const nextStart = Math.max(lineStart, start - removedBeforeStart);
const nextEnd = Math.max(nextStart, end - removedTotal);
editor.setSelectionRange(nextStart, nextEnd);
}
function replaceEditorRange(start, end, text) {
editor.focus();
editor.setSelectionRange(start, end);
const inserted = document.execCommand?.("insertText", false, text);
if (!inserted) {
editor.setRangeText(text, start, end, "end");
}
}
function syncCurrentLineHighlight() {
const line = getCursorLine();
currentLineHighlight.style.top = `${getHighlightTop(line)}px`;
}
function syncEditorHighlights() {
syncCurrentLineHighlight();
if (errorLine !== null) {
showErrorLineHighlight(errorLine);
}
}
function renderOutput(text) {
errorLocation = null;
outputText.textContent = text;
outputJump.hidden = true;
}
function renderError(message, { jumpToError = true } = {}) {
const location = parseErrorLocation(message);
errorLocation = location;
if (location) {
showErrorLineHighlight(location.line);
} else {
clearErrorLineHighlight();
}
if (!location) {
outputText.textContent = message;
outputJump.hidden = true;
return;
}
outputText.textContent = message.replace(/\s*\(line \d+, col \d+\)\s*$/, "");
outputJump.hidden = false;
outputJump.textContent = `Go to line ${location.line}`;
if (!jumpToError) {
return;
}
focusEditorPosition(location.line, location.col);
}
function parseErrorLocation(message) {
const match = message.match(/\(line (\d+), col (\d+)\)$/);
if (!match) return null;
return { line: Number(match[1]), col: Number(match[2]) };
}
function focusEditorPosition(line, col) {
const lines = editor.value.split("\n");
const safeLine = Math.max(1, Math.min(line, lines.length));
const lineStart = lines.slice(0, safeLine - 1).reduce((sum, value) => sum + value.length + 1, 0);
const safeCol = Math.max(1, Math.min(col, lines[safeLine - 1].length + 1));
const index = lineStart + safeCol - 1;
editor.focus();
editor.setSelectionRange(index, index);
editor.scrollTop = Math.max(0, (safeLine - 3) * getLineHeight());
syncLineNumbersScroll();
syncCurrentLineHighlight();
showErrorLineHighlight(safeLine);
}
function showErrorLineHighlight(line) {
if (!errorLineHighlight) return;
errorLine = line;
errorLineHighlight.hidden = false;
errorLineHighlight.style.top = `${getHighlightTop(line)}px`;
}
function clearErrorLineHighlight() {
if (!errorLineHighlight) return;
errorLine = null;
errorLineHighlight.hidden = true;
}
function getLineHeight() {
return 15 * 1.55;
}
function getHighlightTop(line) {
return 16 + (line - 1) * getLineHeight() - editor.scrollTop;
}
function getCursorLine() {
let line = 1;
for (let i = 0; i < editor.selectionStart; i += 1) {
if (editor.value[i] === "\n") line += 1;
}
return line;
}
function getSelectionLineEnd(value, end) {
if (end > 0 && value[end - 1] === "\n") {
return end - 1;
}
const nextBreak = value.indexOf("\n", end);
return nextBreak === -1 ? value.length : nextBreak;
}