-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.html
350 lines (311 loc) · 10.8 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🤖</text></svg>">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Starter</title>
<meta property="og:title" content="Starter" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="A starter pack of JS exercises" />
<meta property="og:description" content="A starter pack of JS exercises" />
<link rel="canonical" href="https://nan-academy.github.io/starter/" />
<meta property="og:url" content="https://nan-academy.github.io/starter/" />
<meta property="og:site_name" content="starter" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="Init" />
<script type="application/ld+json">
{ "@type": "WebPage", "url": "https://nan-academy.github.io/starter/", "headline": "Starter", "description": "A starter pack of JS exercises", "@context": "https://schema.org" }
</script>
<link rel="stylesheet" href="lib/codemirror.css" />
<link rel="stylesheet" href="lib/style.css" />
<style id="root-style">
body { padding-bottom: 40em }
#container h2 { margin-top: 96px }
#container .cm-s-neo.CodeMirror { background-color: #f6f8fa }
button:disabled { color: #6c7278 }
button {
margin: 12px 12px 12px 0;
display: inline-block;
background: #f6f8fa;
border: 2px solid #ddd;
border-radius: 4px;
font-weight: bold;
color: #535e6a;
}
h1 em, h2::before {
color: #aaa;
margin-left: -2.5ch;
font-style: normal;
}
@media (max-width: 1080px) {
h2::before { margin-left: 0 }
}
</style>
</head>
<body>
<div id="container" class="container-lg px-3 my-5 markdown-body">
</div>
<script src="lib/codemirror.js"></script>
<script type="module">
const cache = {
get: (k, v) => localStorage[`starter@${k}`] || cache.set(k, v),
set: (k, v) => v == null
? localStorage.removeItem(`starter@${k}`)
: (localStorage[`starter@${k}`] = v)
}
const urlSession = new URL(location).searchParams.get('session')
const genId = () => Math.random().toString(36).slice(2).padStart('0', 11)
const session = cache.get('session', urlSession || genId())
const notGithub = !location.hostname.includes('.github.io')
const log = notGithub ? console.log : data => {
fetch(`https://7.oct.ovh:8443/starter-progress?session=${session}`, {
method: 'POST',
mode: 'no-cors',
credentials: 'omit',
body: JSON.stringify(data),
}).catch(console.debug)
}
function notEqualError(a, b) {
console.warn('Not Equal:', [a, b])
throw Error('Not Equal')
}
function scrollToElement(element) {
const y = element.getBoundingClientRect().top + window.scrollY - 70
window.scrollTo({ top: y, behavior: 'smooth' })
}
function equal(a, b) {
if (a === b) return true
if (typeof a !== typeof b) notEqualError(a, b)
if (typeof a === 'number' && Number.isNaN(a) && Number.isNaN(b)) return true
if (typeof a === 'object') {
if (!a || !b) notEqualError(a, b)
if (a.constructor !== b.constructor) notEqualError(a, b)
const entries = Object.entries(a)
if (entries.length !== Object.values(b).length) notEqualError(a, b)
for (const [k, v] of entries) {
if (!equal(b[k], v)) notEqualError(a, b)
}
return true
}
notEqualError(a, b)
}
const restore = new Set()
function saveArguments(src, key) {
const savedArgs = []
const fn = src[key]
src[key] = (...args) => {
savedArgs.push(args)
return fn(...args)
}
restore.add(() => (src[key] = fn))
return savedArgs
}
function tryRun(code) {
try { eval(code) }
catch (err) { return err }
finally {
for (const cleanup of restore) cleanup()
restore.clear()
}
}
function runTests({ solution, tests }) {
for (const test of tests) {
console.clear()
const code = test.code.includes('// Your code')
? test.code.replace('// Your code', solution.trim())
: `${solution.trim()}\n\n${test.code}`
const err = tryRun(code)
if (err) {
console.error(err.message)
test.element.style.display = 'block'
return false
} else {
test.element.style.display = 'none'
}
}
return true
}
const isTitle = (node, name) => node.tagName === 'H3' &&
node.textContent.trim().toLowerCase() === name
const shortcut = navigator.platform.startsWith('Mac')
? `Command+Option+${navigator.userAgent.includes("Firefox") ? 'K' : 'J'}`
: `Control+Shift+${navigator.userAgent.includes("Firefox") ? 'K' : 'J'}`
const defaultCode = `
// Write your solution here
// ${shortcut} to open the console
`
const root = document.getElementById('container')
const rootStyle = document.getElementById('root-style')
// generate style
rootStyle.innerHTML += [...Array(30).keys()].map(n => `
.exercise:nth-of-type(${n}) h2::before {
content: '${String(n).padStart(2, '0')} ';
}`).join('')
function prepareEditor(exercise, exercises) {
const { container, tests, name, quest, key } = exercise
const editorElement = document.createElement('textarea')
const editorTitle = document.createElement('h3')
const submit = document.createElement('button')
const copy = document.createElement('button')
const skip = document.createElement('button')
editorElement.value = cache.get(key, localStorage[name]) || defaultCode
editorTitle.textContent = 'Editor'
submit.textContent = '⚙️ Submit Solution'
skip.textContent = '⏭️ Skip to next Quest'
copy.textContent = '💾 Export Progress (url)'
skip.onclick = () => loadQuest(quest + 1)
copy.onclick = () => {
const url = `${location.origin}${location.pathname}?session=${cache.get('session')}`
navigator.clipboard.writeText(url)
console.log('Your progression url is copied !')
}
skip.classList.add('tests')
editorTitle.classList.add('tests')
editorElement.classList.add('tests')
container.append(editorTitle, editorElement, submit, copy)
exercise.bonus && container.append(skip)
const completed = () => {
for (const n of [
...container.getElementsByClassName('tests'),
...container.getElementsByClassName('instructions'),
...container.getElementsByClassName('CodeMirror'),
]) {
n.style.display = 'none'
}
const { editor } = exercise
submit.parentNode.insertBefore(submit, editor.getWrapperElement())
const hideSolution = () => {
submit.onclick = showSolution
editor.getWrapperElement().style.display = 'none'
submit.textContent = '▶️ Show Solution'
}
const showSolution = submit.onclick = () => {
submit.onclick = hideSolution
submit.textContent = '🔽 Hide Solution'
editor.getWrapperElement().style.display = 'block'
editor.refresh()
}
hideSolution()
}
exercise.skip = () => {
exercise.init()
completed({ scroll: false })
}
exercise.init = () => {
root.append(container)
const run = () => {
if (submit.onclick !== run) return submit.onclick()
const solution = exercise.editor.getValue()
const pass = runTests({ solution, tests })
const next = exercises[exercise.index + 1]
const code = solution.replace(defaultCode.trim(), '\n').trim()
if (code.length > 10 && cache.get(key) !== code) {
cache.set(key, code)
log({ key, pass, code })
localStorage.removeItem(name) // TODO: remove
}
if (!pass) return
if (!next) return loadQuest(quest + 1)
submit.textContent = '🎉 Bim !'
submit.disabled = true
submit.onclick = () => {}
setTimeout(() => {
submit.disabled = false
submit.textContent = '🎉 Bim ! Jump to the next exercise'
submit.onclick = () => {
completed()
next.init()
next.editor.focus()
setTimeout(scrollToElement, 50, next.container)
}
}, 250)
}
submit.onclick = run
exercise.editor = CodeMirror.fromTextArea(editorElement, {
mode: 'javascript',
theme: 'neo',
keyMap: 'sublime',
tabSize: 2,
lineNumbers: true,
indentWithTabs: false,
autoCloseBrackets: true,
scrollbarStyle: 'null',
extraKeys: { 'Ctrl-S': run, 'Cmd-S': run, 'Ctrl-Enter': run }
})
}
}
async function loadQuest(quest) {
quest === 6 && (quest++) // skip dom quest
const res = await fetch(`quests/${String(quest).padStart(2, '0')}`)
const txt = await res.text()
const dom = new DOMParser().parseFromString(txt, 'text/html')
cache.set('at', Math.max(Number(cache.get('at')), quest))
while (root.firstChild) root.removeChild(root.firstChild)
let exercise, state
const exercises = []
for (const node of dom.body.firstElementChild.childNodes) {
if (node.tagName === 'H1') {
node.innerHTML = `<em>${String(quest).padStart(2, '0')}</em> ${node.textContent}`
node.id && root.append(node)
if (quest > 1) {
const prevBtn = document.createElement('button')
prevBtn.textContent = '⏮️ Load previous exercises'
prevBtn.onclick = () => loadQuest(quest - (1 + (quest === 7)))
node.insertAdjacentElement('afterend', prevBtn)
}
} else if (node.tagName === 'H2') {
state = 'subject'
const name = node.id.replace(/-+/g, ' ').trim().replace(/\s+/g, '-')
exercise = {
key: `${quest}/${name}`,
name,
quest,
bonus: node.textContent.startsWith('🌟'),
index: exercises.length,
tests: [],
container: document.createElement('div'),
}
exercise.container.classList.add('exercise')
exercise.container.append(node)
exercises.push(exercise)
} else if (exercise) {
if (node.tagName === 'H3') {
state = node.textContent.trim().toLowerCase()
state === 'tests' && prepareEditor(exercise, exercises)
} else if (state === 'tests' && node.classList.contains('language-js')) {
node.id = `${exercise.name}-test-${exercise.testCount}`
node.style.display = 'none'
exercise.tests.push({ element: node, code: node.textContent })
}
if (state === 'tests' || state === 'instructions') {
node.classList.add(state)
}
exercise.container.append(node)
}
}
let currentExercise = exercises[0]
for (const e of exercises) {
const next = exercises[e.index + 1]
if (!next) break
if (!cache.get(next.key)) break
e.skip()
currentExercise = next
}
if (!currentExercise) return document.body.append('~~ The End ~~')
currentExercise.init()
scrollToElement(currentExercise.container)
}
loadQuest(Number(cache.get('at', '1')))
/*
TODO:
- go back to previous quest
- export / load progress
-
- move info text to hideable banner and use html syntax
<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd>
*/
</script>
</body>
</html>