forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
370 lines (347 loc) · 16 KB
/
Copy pathindex.html
File metadata and controls
370 lines (347 loc) · 16 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nulang Playground</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #1a1a2e; color: #e0e0e0; display: flex; flex-direction: column; height: 100vh; }
header { background: #16213e; padding: 12px 20px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid #0f3460; flex-wrap: wrap; }
header h1 { font-size: 20px; color: #e94560; margin-right: auto; }
header select, header button { padding: 6px 12px; border-radius: 4px; border: 1px solid #0f3460; background: #0f3460; color: #e0e0e0; cursor: pointer; font-size: 13px; }
header button:hover { background: #1a4a8a; }
header button.run { background: #e94560; border-color: #e94560; font-weight: bold; }
header button.run:hover { background: #ff6b81; }
header button.compile { background: #0f3460; border-color: #0f3460; }
header button.compile:hover { background: #1a4a8a; }
header button.check { background: #0f3460; border-color: #0f3460; }
header button.check:hover { background: #1a4a8a; }
header button.secondary { background: #233554; border-color: #233554; }
header button.secondary:hover { background: #2d4570; }
main { display: flex; flex: 1; overflow: hidden; }
#editor { flex: 1; height: 100%; min-width: 0; }
#output { width: 380px; background: #0d1117; border-left: 1px solid #0f3460; padding: 16px; overflow-y: auto; font-family: 'Fira Code', 'Cascadia Code', monospace; font-size: 13px; white-space: pre-wrap; word-break: break-all; display: flex; flex-direction: column; }
#output .out { color: #c9d1d9; }
#output .err { color: #f85149; }
#output .info { color: #58a6ff; }
#output .empty { color: #484f58; font-style: italic; }
#output-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid #0f3460; }
#output-header h3 { font-size: 14px; font-weight: 600; color: #e0e0e0; }
#output-toolbar { display: flex; gap: 6px; }
#output-toolbar button { padding: 4px 8px; font-size: 11px; border-radius: 3px; border: 1px solid #0f3460; background: #16213e; color: #8b949e; cursor: pointer; }
#output-toolbar button:hover { background: #233554; color: #e0e0e0; }
#status { font-size: 12px; color: #58a6ff; padding: 0 8px; }
.cm-editor { height: 100%; font-size: 14px; }
.cm-focused { outline: none; }
.cm-lineNumbers { min-width: 3rem; padding: 0 12px 0 8px; color: #484f58; }
.cm-gutters { background: #16213e; border-right: 1px solid #0f3460; }
@media (max-width: 768px) {
main { flex-direction: column; }
#output { width: 100%; height: 300px; border-left: none; border-top: 1px solid #0f3460; }
header { flex-wrap: wrap; }
header h1 { margin-right: 0; margin-bottom: 8px; width: 100%; }
}
.toast { position: fixed; bottom: 24px; right: 24px; background: #16213e; color: #e0e0e0; padding: 12px 20px; border-radius: 6px; border: 1px solid #0f3460; box-shadow: 0 4px 12px rgba(0,0,0,0.3); z-index: 1000; animation: slideIn 0.3s ease; }
@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
.toast.success { border-color: #3fb950; }
.toast.error { border-color: #f85149; }
</style>
<!-- CodeMirror 6 with Lezer -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@codemirror/theme-one-dark@6/themes/one-dark.css">
<script type="module">
import { EditorView, basicSetup, lineNumbers, highlightActiveLineGutter, updateListener } from "https://cdn.jsdelivr.net/npm/codemirror@6/view/+esm";
import { keymap } from "https://cdn.jsdelivr.net/npm/@codemirror/view@6/+esm";
import { indentWithTab } from "https://cdn.jsdelivr.net/npm/@codemirror/commands@6/+esm";
import { defaultKeymap, history, historyKeymap } from "https://cdn.jsdelivr.net/npm/@codemirror/commands@6/+esm";
import { bracketMatching } from "https://cdn.jsdelivr.net/npm/@codemirror/matchbrackets@6/+esm";
import { closeBrackets, closeBracketsKeymap } from "https://cdn.jsdelivr.net/npm/@codemirror/autocomplete@6/+esm";
import { syntaxHighlighting, defaultHighlightStyle, tags as t } from "https://cdn.jsdelivr.net/npm/@codemirror/language@6/+esm";
import { LRLanguage, LanguageSupport } from "https://cdn.jsdelivr.net/npm/@codemirror/language@6/+esm";
import { LezerHighlightStyle } from "https://cdn.jsdelivr.net/npm/@lezer/highlight@1/+esm";
import { parser } from "./nulang-grammar.js";
// Syntax highlighting style for Nulang
const nulangHighlightStyle = LezerHighlightStyle.define([
{ tag: t.comment, color: "#546e7a" },
{ tag: t.string, color: "#c3e88d" },
{ tag: t.keyword, color: "#c792ea" },
{ tag: t.builtin, color: "#82aaff" },
{ tag: t.number, color: "#f78c6c" },
{ tag: t.operator, color: "#89ddff" },
{ tag: t.variableName, color: "#e0e0e0" },
{ tag: t.function(t.variableName), color: "#82aaff" },
{ tag: t.typeName, color: "#ffcb6b" },
{ tag: t.modifier, color: "#c792ea" },
{ tag: t.propertyName, color: "#80cbc4" },
{ tag: t.definition(t.variableName), color: "#82aaff" },
{ tag: t.labelName, color: "#89ddff" },
]);
// Create the language support
const nulangLanguage = LRLanguage.define({
name: "nulang",
parser: parser.configure({
props: [
nulangLanguage.data.of({
closeBrackets: { brackets: ["(", "[", "{", "'", '"'] },
indentOnInput: /^\s*(?:case|default|else|catch|finally)\b/
})
]
})
});
const nulangSupport = new LanguageSupport(nulangLanguage, [
syntaxHighlighting(nulangHighlightStyle)
]);
// Configure editor with line numbers and active line highlighting
const editor = new EditorView({
state: EditorState.create({
doc: 'perform IO.print("Hello, Nulang!")',
extensions: [
basicSetup,
lineNumbers(),
highlightActiveLineGutter(),
keymap.of([...defaultKeymap, ...historyKeymap, ...closeBracketsKeymap, indentWithTab]),
nulangSupport,
EditorView.lineWrapping,
EditorState.tabSize.of(4),
updateListener.of(v => { if (v.docChanged) localStorage.setItem('nulang-playground-code', v.state.doc.toString()); })
]
}),
parent: document.getElementById('editor')
});
// Keyboard shortcut: Ctrl+Enter to run
editor.dispatch({
effects: EditorView.addKeyMap.of([
{ key: "Ctrl-Enter", run: () => { run(); return true; } },
{ key: "Mod-Enter", run: () => { run(); return true; } } // macOS
])
});
// Example code samples
const examples = {
"": "— Examples —",
"hello": 'perform IO.print("Hello, Nulang!")',
"fib": "let fib = fn(n) { if n <= 1 then n else fib(n - 1) + fib(n - 2) } in fib(10)",
"option": "type Option[T] = Some(T) | None\nlet x = Some(42) in match x with { | Some(n) => n | None => 0 }",
"pipe": "let add = fn(x, y) { x + y } in 5 |> add(3)",
"strlen": 'perform String.length("hello")',
"strcat": 'perform String.concat("Hello", " World")',
"debug": 'perform Debug.inspect("x", 42 * 2)',
"match": "match 42 { case 1 => 10 case 42 => 100 case _ => 0 }",
"closure": "let inc = fn(n) { n + 1 } in inc(41)",
"log": 'perform IO.log("info", "server started")',
"actor": "actor Counter { state count = 0 behavior Inc { perform IO.print(count); count := count + 1 } }\nspawn Counter() as \"counter\"\nsend \"counter\" Inc()",
"effect": "effect Log { fn info(msg: String) }\nlet logHandler = handler { | Log.info(msg) => perform IO.print(msg) }\nhandle { perform Log.info(\"Hello from effect!\") } with logHandler",
"async": "perform LLM.ask({ model: \"llama3\", messages: [{ role: \"user\", content: \"Hello!\" }] })",
"crdt": "let counter = CRDT.GCounter()\ncounter.increment()\ncounter.increment()\nperform IO.print(counter.value())"
};
// Populate dropdown
const select = document.getElementById('examples');
for (const [key, value] of Object.entries(examples)) {
const option = document.createElement('option');
option.value = key;
option.textContent = key === "" ? "— Examples —" : key.charAt(0).toUpperCase() + key.slice(1);
select.appendChild(option);
}
// Example dropdown change handler
select.addEventListener('change', function() {
if (this.value && examples[this.value]) {
editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: examples[this.value] } });
}
});
// Load from localStorage or URL hash
function loadInitialCode() {
if (location.hash) {
try {
const code = decodeURIComponent(location.hash.slice(1));
if (code) return code;
} catch(e) {}
}
const saved = localStorage.getItem('nulang-playground-code');
if (saved) return saved;
return null;
}
const initialCode = loadInitialCode();
if (initialCode) {
editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: initialCode } });
}
// Save to localStorage on change
editor.state.doc.onChange = () => {
localStorage.setItem('nulang-playground-code', editor.state.doc.toString());
};
// Run function
async function run() {
const code = editor.state.doc.toString();
const out = document.getElementById('output-content');
const status = document.getElementById('status');
out.innerHTML = '<span class="info">Running...</span>';
status.textContent = 'running...';
status.style.color = '#58a6ff';
try {
const resp = await fetch('/run', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
const data = await resp.json();
let html = '';
if (data.stdout) html += '<span class="out">' + escapeHtml(data.stdout) + '</span>';
if (data.stderr) html += '<span class="err">' + escapeHtml(data.stderr) + '</span>';
if (!data.stdout && !data.stderr) html = '<span class="empty">(no output)</span>';
out.innerHTML = html;
status.textContent = data.ok ? 'ok' : 'error';
status.style.color = data.ok ? '#3fb950' : '#f85149';
showToast(data.ok ? 'Execution completed' : 'Execution failed', data.ok);
} catch(e) {
out.innerHTML = '<span class="err">Connection error: ' + escapeHtml(e.message) + '</span>';
status.textContent = 'offline';
status.style.color = '#f85149';
showToast('Connection error: ' + e.message, false);
}
}
// Compile function
async function compile() {
const code = editor.state.doc.toString();
const out = document.getElementById('output-content');
const status = document.getElementById('status');
out.innerHTML = '<span class="info">Compiling...</span>';
status.textContent = 'compiling...';
status.style.color = '#58a6ff';
try {
const target = document.getElementById('compile-target').value;
const resp = await fetch('/compile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, target }),
});
const data = await resp.json();
let html = '';
if (data.stdout) html += '<span class="out">' + escapeHtml(data.stdout) + '</span>';
if (data.stderr) html += '<span class="err">' + escapeHtml(data.stderr) + '</span>';
if (!data.stdout && !data.stderr) html = '<span class="empty">(no output)</span>';
out.innerHTML = html;
status.textContent = data.ok ? 'ok' : 'error';
status.style.color = data.ok ? '#3fb950' : '#f85149';
showToast(data.ok ? 'Compilation completed' : 'Compilation failed', data.ok);
} catch(e) {
out.innerHTML = '<span class="err">Connection error: ' + escapeHtml(e.message) + '</span>';
status.textContent = 'offline';
status.style.color = '#f85149';
showToast('Connection error: ' + e.message, false);
}
}
// Check function
async function check() {
const code = editor.state.doc.toString();
const out = document.getElementById('output-content');
const status = document.getElementById('status');
out.innerHTML = '<span class="info">Type checking...</span>';
status.textContent = 'checking...';
status.style.color = '#58a6ff';
try {
const resp = await fetch('/check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
const data = await resp.json();
let html = '';
if (data.stdout) html += '<span class="out">' + escapeHtml(data.stdout) + '</span>';
if (data.stderr) html += '<span class="err">' + escapeHtml(data.stderr) + '</span>';
if (!data.stdout && !data.stderr) html = '<span class="empty">(no output)</span>';
out.innerHTML = html;
status.textContent = data.ok ? 'ok' : 'error';
status.style.color = data.ok ? '#3fb950' : '#f85149';
showToast(data.ok ? 'Type check passed' : 'Type check failed', data.ok);
} catch(e) {
out.innerHTML = '<span class="err">Connection error: ' + escapeHtml(e.message) + '</span>';
status.textContent = 'offline';
status.style.color = '#f85149';
showToast('Connection error: ' + e.message, false);
}
}
// Share function
function share() {
const code = editor.state.doc.toString();
const url = location.origin + location.pathname + '#' + encodeURIComponent(code);
navigator.clipboard.writeText(url).then(() => {
showToast('Share URL copied to clipboard!', true);
}).catch(() => {
showToast('Failed to copy URL', false);
});
}
// Clear output
function clearOutput() {
const out = document.getElementById('output-content');
out.innerHTML = '<span class="empty">Output appears here — click ▶ Run</span>';
document.getElementById('status').textContent = '';
}
// Copy output
function copyOutput() {
const out = document.getElementById('output-content');
const text = out.innerText || out.textContent;
if (text && text !== 'Output appears here — click ▶ Run') {
navigator.clipboard.writeText(text).then(() => {
showToast('Output copied!', true);
});
} else {
showToast('Nothing to copy', false);
}
}
// Toast notifications
function showToast(message, success) {
const existing = document.querySelector('.toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.className = 'toast ' + (success ? 'success' : 'error');
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.animation = 'slideIn 0.3s ease reverse';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
function escapeHtml(s) { return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
// Wire up button clicks and select changes
document.getElementById('btn-run').addEventListener('click', run);
document.getElementById('btn-compile').addEventListener('click', compile);
document.getElementById('btn-check').addEventListener('click', check);
document.getElementById('btn-share').addEventListener('click', share);
document.getElementById('btn-clear').addEventListener('click', clearOutput);
document.getElementById('btn-copy').addEventListener('click', copyOutput);
document.getElementById('btn-clear-out').addEventListener('click', clearOutput);
document.getElementById('examples').addEventListener('change', function() {
if (this.value && examples[this.value]) {
editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: examples[this.value] } });
}
});
</script>
</head>
<body>
<header>
<h1>Nulang Playground</h1>
<select id="examples"></select>
<button class="run" id="btn-run">▶ Run (Ctrl+Enter)</button>
<select id="compile-target" style="min-width: 120px;">
<option value="native">native</option>
<option value="riscv64">riscv64</option>
<option value="ptx">ptx</option>
</select>
<button class="compile" id="btn-compile">⚙ Compile</button>
<button class="check" id="btn-check">✓ Check</button>
<button class="secondary" id="btn-share">🔗 Share</button>
<button class="secondary" id="btn-clear">🗑 Clear</button>
<span id="status"></span>
</header>
<main>
<div id="editor"></div>
<div id="output">
<div id="output-header">
<h3>Output</h3>
<div id="output-toolbar">
<button id="btn-copy">📋 Copy</button>
<button id="btn-clear-out">🗑 Clear</button>
</div>
</div>
<div id="output-content"><span class="empty">Output appears here — click ▶ Run</span></div>
</div>
</main>
</body>