-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
317 lines (216 loc) · 7.98 KB
/
script.js
File metadata and controls
317 lines (216 loc) · 7.98 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
// ================== Utilities ==================
const $ = s => document.querySelector(s);
const $$ = s => Array.from(document.querySelectorAll(s));
const out = $('#output');
const preview = $('#preview');
const STORAGE_KEY = 'academy-codelab-web';
const escapeHtml = s =>
String(s).replace(/[&<>"]/g, c => ({
'&':'&',
'<':'<',
'>':'>',
'"':'"'
}[c]
));
function log(msg, type='info'){
const color = type==='error' ? 'var(--err)' : type==='warn' ? 'var(--warn)' : 'var(--brand)';
const time = new Date().toLocaleTimeString();
const line = document.createElement('div');
line.innerHTML = `<span style="color:${color}">[${time}]</span> ${escapeHtml(msg)}`;
out.appendChild(line); out.scrollTop = out.scrollHeight;
}
function clearOut(){ out.innerHTML=''; }
$('#clearOut')?.addEventListener('click', clearOut);
// ================== ACE Editors (HTML/CSS/JS) ==================
function makeEditor(id, mode){
const ed = ace.edit(id, {
theme:'ace/theme/dracula',
mode, tabSize:2, useSoftTabs:true, showPrintMargin:false, wrap:true
});
ed.session.setUseWrapMode(true);
ed.commands.addCommand({
name:'run', bindKey:{win:'Ctrl-Enter',mac:'Command-Enter'},
exec(){ runWeb(false); }
});
ed.commands.addCommand({
name:'save', bindKey:{win:'Ctrl-S',mac:'Command-S'},
exec(){ saveProject(); }
});
return ed;
}
const ed_html = makeEditor('ed_html','ace/mode/html');
const ed_css = makeEditor('ed_css','ace/mode/css');
const ed_js = makeEditor('ed_js','ace/mode/javascript');
// ================== Tabs (robust + a11y) ==================
const TAB_ORDER = ['html','css','js'];
const wraps = Object.fromEntries($$('#webEditors .editor-wrap').map(w => [w.dataset.pane, w]));
const editors = { html: ed_html, css: ed_css, js: ed_js };
function activePane(){
const t = $('#webTabs .tab.active');
return t ? t.dataset.pane : 'html';
}
function showPane(name){
TAB_ORDER.forEach(k => { if(wraps[k]) wraps[k].hidden = (k !== name); });
$$('#webTabs .tab').forEach(t => {
const on = t.dataset.pane === name;
t.classList.toggle('active', on);
t.setAttribute('aria-selected', on);
t.tabIndex = on ? 0 : -1;
});
requestAnimationFrame(() => {
const ed = editors[name];
if(ed && ed.resize){ ed.resize(true); ed.focus(); }
});
}
$('#webTabs')?.addEventListener('click', (e)=>{
const btn = e.target.closest('.tab'); if(!btn) return;
showPane(btn.dataset.pane);
});
$('#webTabs')?.addEventListener('keydown', (e)=>{
const idx = TAB_ORDER.indexOf(activePane());
if(e.key==='ArrowLeft' || e.key==='ArrowRight'){
const delta = e.key==='ArrowLeft' ? -1 : 1;
showPane(TAB_ORDER[(idx+delta+TAB_ORDER.length)%TAB_ORDER.length]);
e.preventDefault();
}
});
showPane('html');
// ================== Preview ==================
function buildWebSrcdoc(withTests=false){
const html = ed_html.getValue();
const css = ed_css.getValue();
const js = ed_js.getValue();
const tests = ($('#testArea')?.value || '').trim();
return `<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>${css}\n</style></head>
<body>${html}
<script>
try{
${js}
${withTests && tests ? `\n/* tests */\n${tests}` : ''}
}catch(e){console.error(e)}<\/script>
</body>
</html>`;
}
function runWeb(withTests=false){
preview.srcdoc = buildWebSrcdoc(withTests);
log(withTests ? 'Run with tests.' : 'Web preview updated.');
}
$('#runWeb')?.addEventListener('click', ()=>runWeb(false));
$('#runTests')?.addEventListener('click', ()=>runWeb(true));
$('#openPreview')?.addEventListener('click', ()=>{
const src = buildWebSrcdoc(false);
const w = window.open('about:blank');
w.document.open(); w.document.write(src); w.document.close();
});
// ================== Save / Load (Web-only) ==================
function projectJSON(){
return {
version: 1,
kind: 'web-only',
assignment: $('#assignment')?.value || '',
test: $('#testArea')?.value || '',
html: ed_html.getValue(),
css: ed_css.getValue(),
js: ed_js.getValue()
};
}
function loadProject(obj){
try{
if($('#assignment')) $('#assignment').value = obj.assignment || '';
if($('#testArea')) $('#testArea').value = obj.test || '';
ed_html.setValue(obj.html || '', -1);
ed_css.setValue(obj.css || '', -1);
ed_js.setValue(obj.js || '', -1);
log('Web project loaded.');
}catch(e){ log('Unable to load project: '+e, 'error'); }
}
function setDefaultContent(){
ed_html.setValue(`<!-- Welcome card -->
<section class="card" style="max-width:520px;margin:24px auto;padding:18px;text-align:center">
<h1>Welcome to the Academy</h1>
<p>This example runs locally in the browser.</p>
<button id="btn">Try me</button>
</section>`, -1);
ed_css.setValue(`body{font-family:system-ui;background:#f7fafc;margin:0}
h1{color:#0f172a}
#btn{padding:.75rem 1rem;border:0;border-radius:10px;background:#60a5fa;color:#08111f;font-weight:700}`, -1);
ed_js.setValue(`document.getElementById('btn').addEventListener('click',()=>alert('Well done!'));
console.log('Hello from JavaScript!');`, -1);
}
function saveProject(){
try{
const data = JSON.stringify(projectJSON(), null, 2);
localStorage.setItem(STORAGE_KEY, data);
const blob = new Blob([data], {type:'application/json'});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'academy-web.json';
a.click();
log('Saved locally and downloaded JSON file.');
}catch(e){ log('Unable to save: '+e, 'error'); }
}
$('#saveBtn')?.addEventListener('click', saveProject);
$('#loadBtn')?.addEventListener('click', ()=> $('#openFile').click());
$('#openFile')?.addEventListener('change', async (e)=>{
const f = e.target.files?.[0]; if(!f) return;
try{ const obj = JSON.parse(await f.text()); loadProject(obj); }
catch(err){ log('Invalid project file', 'error'); }
});
// ================== Initial load ==================
try{
const cache = localStorage.getItem(STORAGE_KEY);
if(cache){ loadProject(JSON.parse(cache)); }
else { setDefaultContent(); }
}catch{ setDefaultContent(); }
log('Ready — Web-only Editor (HTML/CSS/JS) ✨');
function normalizeProject(raw){
if (!raw || typeof raw !== 'object') throw new Error('Not an object');
// accept old/new shapes; fall back to empty strings
const html = typeof raw.html === 'string' ? raw.html : (raw.web && raw.web.html) || '';
const css = typeof raw.css === 'string' ? raw.css : (raw.web && raw.web.css ) || '';
const js = typeof raw.js === 'string' ? raw.js : (raw.web && raw.web.js ) || '';
return {
version: 1,
kind: 'web-only',
assignment: typeof raw.assignment === 'string' ? raw.assignment : (raw.task || ''),
test: typeof raw.test === 'string' ? raw.test : (raw.tests || ''),
html, css, js
};
}
function safeSetValue(id, val){
const el = document.getElementById(id);
if (el) { el.value = val; }
else { log(`Warning: #${id} not found; skipped setting value`, 'warn'); }
}
function loadProject(raw){
const proj = normalizeProject(raw);
safeSetValue('assignment', proj.assignment);
safeSetValue('testArea', proj.test);
if (typeof ed_html?.setValue === 'function') ed_html.setValue(proj.html, -1);
if (typeof ed_css?.setValue === 'function') ed_css.setValue(proj.css, -1);
if (typeof ed_js?.setValue === 'function') ed_js.setValue(proj.js, -1);
log('Project loaded.');
}
// Buttons
// ===== Initial restore (after DOM is parsed) =====
window.addEventListener('DOMContentLoaded', () => {
try{
const cached = localStorage.getItem(STORAGE_KEY);
if (cached) {
const obj = JSON.parse(cached);
loadProject(obj);
} else {
// seed defaults if nothing cached
if (!document.getElementById('assignment')) return;
// your default seeding function if you have one:
// setDefaultContent();
}
}catch(e){
log('Skipping auto-restore: ' + e, 'warn');
}
});