Repository navigation
Expand file tree
/
Copy pathplayground.js
More file actions
351 lines (328 loc) · 14.6 KB
/
Copy pathplayground.js
File metadata and controls
351 lines (328 loc) · 14.6 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
(function () {
var STORE_KEY = 'luaslice-wiki-playground';
var INBOX_KEY = 'luaslice-wiki-playground-in';
var SAMPLES = {
luaslice: [
"function onCreate()",
" debug.info('Hello from ' .. songName)",
" makeSolidSprite('panel', 40, 40, 320, 120, '#14243A', 'hud', 100)",
"",
" song.atBeat(8, function()",
" camera.flash('game', '#FFFFFF', 0.5)",
" end)",
"end",
"",
"function onBeatHit(beat)",
" if beat % 4 == 0 then",
" camera.setZoom('game', 1.03)",
" end",
"end",
"",
"function onNoteHit(event)",
" if event.note ~= nil and event.note.kind == 'Heal Note' then",
" addHealth(0.08)",
" end",
"end",
""
].join('\n'),
psych: [
"function onCreate()",
" debugPrint('Hello from', songName)",
" makeLuaSprite('panel', nil, 24, 24)",
" makeGraphic('panel', 380, 80, '14243A')",
" setObjectCamera('panel', 'hud')",
" addLuaSprite('panel', true)",
"end",
"",
"function onBeatHit()",
" if curBeat % 4 == 0 then",
" setProperty('camGame.zoom', getProperty('camGame.zoom') + 0.015)",
" end",
"end",
"",
"function goodNoteHit(id, direction, noteType, isSustainNote)",
" if noteType == 'Bonus' then",
" addScore(50)",
" end",
"end",
""
].join('\n')
};
function b64e(str) {
var bytes = new TextEncoder().encode(str), bin = '';
for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function b64d(s) {
s = s.replace(/-/g, '+').replace(/_/g, '/');
while (s.length % 4) s += '=';
var bin = atob(s), bytes = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return new TextDecoder().decode(bytes);
}
function el(tag, attrs, kids) {
var e = document.createElement(tag);
if (attrs) Object.keys(attrs).forEach(function (k) {
if (k === 'text') e.textContent = attrs[k];
else if (k === 'cls') e.className = attrs[k];
else if (attrs[k] === true) e.setAttribute(k, '');
else if (attrs[k] !== false && attrs[k] != null) e.setAttribute(k, attrs[k]);
});
(kids || []).forEach(function (c) { if (c) e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); });
return e;
}
function load() {
var st = { api: 'luaslice', code: SAMPLES.luaslice, beats: 16, noteKind: 'Heal Note', noteBeat: 2, eventName: '', eventBeat: 4, value1: '', value2: '', calls: true };
try {
var saved = JSON.parse(localStorage.getItem(STORE_KEY) || 'null');
if (saved) Object.keys(st).forEach(function (k) { if (saved[k] != null) st[k] = saved[k]; });
} catch (e) {}
try {
var inbox = JSON.parse(localStorage.getItem(INBOX_KEY) || 'null');
localStorage.removeItem(INBOX_KEY);
if (inbox && typeof inbox.code === 'string') {
st.code = inbox.code;
if (inbox.api === 'psych' || inbox.api === 'luaslice') st.api = inbox.api;
}
} catch (e) {}
var m = /^#playground\/s=([A-Za-z0-9_-]+)/.exec(location.hash);
if (m) {
try {
var shared = JSON.parse(b64d(m[1]));
if (typeof shared.c === 'string') st.code = shared.c;
if (shared.a === 'psych' || shared.a === 'luaslice') st.api = shared.a;
} catch (e) {}
}
if (st.api !== 'psych') st.api = 'luaslice';
return st;
}
function mount(root, helpers) {
var st = load();
var runtime = null;
var saveTimer = 0, checkTimer = 0;
function persist() {
clearTimeout(saveTimer);
saveTimer = setTimeout(function () { try { localStorage.setItem(STORE_KEY, JSON.stringify(st)); } catch (e) {} }, 300);
}
root.innerHTML = '';
root.appendChild(el('h1', { text: 'Lua playground' }));
root.appendChild(el('p', { cls: 'pg-lead', text: 'Write a script and run it against a mock of the API. Every API call is logged, and the hooks fire as if a song were playing: onCreate, onSongStart, then onStepHit and onBeatHit for each beat. It runs Lua 5.3 in your browser, so it checks your logic and syntax, not how things look in game.' }));
var tabs = el('div', { cls: 'gen-tabs', role: 'tablist', 'aria-label': 'API' });
var runBtn = el('button', { type: 'button', cls: 'text-btn solid', text: 'Run ▶' });
var shareBtn = el('button', { type: 'button', cls: 'text-btn', text: 'Share link' });
var copyBtn = el('button', { type: 'button', cls: 'text-btn', text: 'Copy' });
var dlBtn = el('button', { type: 'button', cls: 'text-btn', text: 'Download' });
var sampleBtn = el('button', { type: 'button', cls: 'text-btn', text: 'Sample' });
var bar = el('div', { cls: 'pg-bar' }, [tabs, el('div', { cls: 'gen-actions' }, [runBtn, copyBtn, shareBtn, dlBtn, sampleBtn])]);
var gutter = el('div', { cls: 'pg-gutter', 'aria-hidden': 'true' });
var hl = el('code', { cls: 'language-lua' });
var pre = el('pre', { cls: 'pg-hl', 'aria-hidden': 'true' }, [hl]);
var ta = el('textarea', { cls: 'pg-input', spellcheck: 'false', autocomplete: 'off', autocapitalize: 'off', wrap: 'off', 'aria-label': 'Lua code' });
ta.value = st.code;
var area = el('div', { cls: 'pg-area' }, [pre, ta]);
var editor = el('div', { cls: 'pg-editor' }, [gutter, area]);
var status = el('p', { cls: 'pg-status', role: 'status' });
function num(label, key, min, max) {
var i = el('input', { type: 'number', value: st[key], min: min, max: max });
i.addEventListener('input', function () { st[key] = +i.value || 0; persist(); });
return el('label', { cls: 'gen-field' }, [el('span', { text: label }), i]);
}
function txt(label, key, ph) {
var i = el('input', { type: 'text', value: st[key], placeholder: ph || '', spellcheck: 'false' });
i.addEventListener('input', function () { st[key] = i.value; persist(); });
return el('label', { cls: 'gen-field' }, [el('span', { text: label }), i]);
}
var sim = el('details', { cls: 'pg-sim' }, [
el('summary', { text: 'Simulation settings' }),
el('div', { cls: 'gen-grid' }, [
num('Beats to play', 'beats', 0, 1024),
txt('Note kind to hit', 'noteKind', 'empty = none'),
num('Note hit on beat', 'noteBeat', 0, 1024),
txt('Chart event name', 'eventName', 'empty = none'),
num('Event on beat', 'eventBeat', 0, 1024),
txt('Event value 1', 'value1'),
txt('Event value 2', 'value2')
])
]);
var showCalls = el('input', { type: 'checkbox', checked: st.calls });
var clearBtn = el('button', { type: 'button', cls: 'link-btn', text: 'Clear' });
var stats = el('span', { cls: 'pg-stats' });
var consoleEl = el('div', { cls: 'pg-console' + (st.calls ? '' : ' hide-calls'), role: 'log', 'aria-live': 'polite' });
consoleEl.appendChild(el('p', { cls: 'pg-line pg-muted', text: 'Press Run or Ctrl+Enter.' }));
var consoleBox = el('div', { cls: 'pg-out' }, [
el('div', { cls: 'pg-out-head' }, [el('b', { text: 'Console' }), stats, el('label', { cls: 'gen-check' }, [showCalls, el('span', { text: 'API calls' })]), clearBtn]),
consoleEl
]);
root.appendChild(bar);
root.appendChild(el('div', { cls: 'pg-wrap' }, [el('div', { cls: 'pg-left' }, [editor, status, sim]), consoleBox]));
function drawTabs() {
tabs.innerHTML = '';
[['luaslice', 'LuaSlice (.lua)'], ['psych', 'Psych (.luap)']].forEach(function (p) {
var b = el('button', { type: 'button', role: 'tab', cls: 'gen-tab' + (st.api === p[0] ? ' on' : ''), 'aria-selected': st.api === p[0] ? 'true' : 'false', text: p[1] });
b.addEventListener('click', function () {
st.api = p[0];
if (st.api === 'psych' && st.noteKind === 'Heal Note') st.noteKind = 'Bonus';
if (st.api === 'luaslice' && st.noteKind === 'Bonus') st.noteKind = 'Heal Note';
persist();
drawTabs();
});
tabs.appendChild(b);
});
}
var errorLine = 0;
function paint() {
var code = ta.value;
var html;
if (window.hljs) {
try { html = hljs.highlight(code, { language: 'lua', ignoreIllegals: true }).value; } catch (e) { html = null; }
}
if (html == null) html = code.replace(/[&<>]/g, function (c) { return { '&': '&', '<': '<', '>': '>' }[c]; });
hl.innerHTML = html + '\n';
var n = code.split('\n').length, g = '';
for (var i = 1; i <= n; i++) g += '<span' + (i === errorLine ? ' class="err"' : '') + '>' + i + '</span>';
gutter.innerHTML = g;
sync();
}
function sync() {
pre.style.transform = 'translate(' + (-ta.scrollLeft) + 'px,' + (-ta.scrollTop) + 'px)';
gutter.style.transform = 'translateY(' + (-ta.scrollTop) + 'px)';
}
function setStatus(kind, text) {
status.className = 'pg-status ' + kind;
status.textContent = text;
}
function check() {
if (!runtime) return;
var err = runtime.check(ta.value);
errorLine = err ? err.line : 0;
if (err) setStatus('bad', 'Line ' + err.line + ': ' + err.message);
else setStatus('good', 'Syntax OK');
paint();
}
function insert(text) {
ta.focus();
var done = false;
try { done = text ? document.execCommand('insertText', false, text) : document.execCommand('delete'); } catch (e) {}
if (!done) {
ta.setRangeText(text, ta.selectionStart, ta.selectionEnd, 'end');
onInput();
}
}
function onInput() {
st.code = ta.value;
persist();
paint();
clearTimeout(checkTimer);
checkTimer = setTimeout(check, 350);
}
ta.addEventListener('input', onInput);
ta.addEventListener('scroll', sync);
ta.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); run(); return; }
if (e.key === 'Tab' && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
var s = ta.selectionStart, v = ta.value;
if (e.shiftKey) {
var ls = v.lastIndexOf('\n', s - 1) + 1;
var lead = /^ {1,4}/.exec(v.slice(ls));
if (lead) {
ta.setSelectionRange(ls, ls + lead[0].length);
insert('');
ta.setSelectionRange(Math.max(ls, s - lead[0].length), Math.max(ls, s - lead[0].length));
}
} else insert(' ');
return;
}
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.isComposing) {
var pos = ta.selectionStart, val = ta.value;
var lineStart = val.lastIndexOf('\n', pos - 1) + 1;
var line = val.slice(lineStart, pos);
var indent = /^\s*/.exec(line)[0];
var opens = /(\bthen|\bdo|\belse|\brepeat|\bfunction\s*[\w.:]*\s*\([^)]*\)|\{|\()\s*$/.test(line);
e.preventDefault();
insert('\n' + indent + (opens ? ' ' : ''));
}
});
function line(kind, text) {
var p = document.createElement('p');
p.className = 'pg-line pg-' + kind;
p.textContent = text;
return p;
}
var running = false;
function run() {
if (running) return;
if (!runtime) { setStatus('', 'Loading Lua…'); return ready.then(run); }
running = true;
runBtn.disabled = true;
setTimeout(function () {
var frag = document.createDocumentFragment();
var counts = { call: 0, hook: 0, error: 0, warn: 0 };
var res = runtime.run(ta.value, {
api: st.api, beats: st.beats, noteKind: st.noteKind.trim(), noteBeat: st.noteBeat,
eventName: st.eventName.trim(), eventBeat: st.eventBeat, value1: st.value1, value2: st.value2
}, function (kind, text) {
if (counts[kind] != null) counts[kind]++;
frag.appendChild(line(kind, text));
});
consoleEl.innerHTML = '';
consoleEl.appendChild(frag);
if (!consoleEl.children.length) consoleEl.appendChild(line('muted', 'No output. Define hooks like onCreate to see them run.'));
consoleEl.scrollTop = 0;
stats.textContent = counts.hook + ' hooks · ' + counts.call + ' calls · ' + res.ms + ' ms';
errorLine = res.error ? res.error.line : 0;
if (res.error) setStatus('bad', (res.error.line ? 'Line ' + res.error.line + ': ' : '') + res.error.message);
else setStatus('good', 'Ran without errors' + (counts.warn ? ' (' + counts.warn + ' warning' + (counts.warn > 1 ? 's' : '') + ')' : ''));
paint();
running = false;
runBtn.disabled = false;
if (window.innerWidth < 1240) consoleBox.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 10);
}
runBtn.addEventListener('click', run);
copyBtn.addEventListener('click', function () {
helpers.copy(ta.value).then(function () { helpers.toast('Code copied'); }, function () { helpers.toast('Copy failed'); });
});
shareBtn.addEventListener('click', function () {
var url = location.href.split('#')[0] + '#playground/s=' + b64e(JSON.stringify({ a: st.api, c: ta.value }));
helpers.copy(url).then(function () { helpers.toast('Share link copied'); }, function () { helpers.toast('Copy failed'); });
});
dlBtn.addEventListener('click', function () {
var name = st.api === 'psych' ? 'script.luap' : 'script.lua';
var url = URL.createObjectURL(new Blob([ta.value], { type: 'text/x-lua;charset=utf-8' }));
var a = el('a', { href: url, download: name });
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
});
sampleBtn.addEventListener('click', function () {
ta.select();
insert(SAMPLES[st.api]);
ta.setSelectionRange(0, 0);
ta.scrollTop = 0;
onInput();
});
showCalls.addEventListener('change', function () {
st.calls = showCalls.checked;
consoleEl.classList.toggle('hide-calls', !st.calls);
persist();
});
clearBtn.addEventListener('click', function () {
consoleEl.innerHTML = '';
stats.textContent = '';
});
drawTabs();
paint();
setStatus('', 'Loading Lua…');
var ready = helpers.loadScript('vendor/fengari-web.js').then(function () {
return helpers.loadScript('lua-runtime.js');
}).then(function () {
runtime = window.LuaSliceRuntime.create(window.fengari);
check();
}, function () {
setStatus('bad', 'Could not load the Lua runtime. Check your connection and reload.');
});
}
window.LuaSlicePlayground = { mount: mount, encode: b64e, decode: b64d, INBOX_KEY: INBOX_KEY };
})();