-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
frontend.nim
290 lines (268 loc) · 9.43 KB
/
frontend.nim
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
include karax / prelude
import karax / [vstyles, kdom, kajax]
import jsffi except `&`
import json
import sugar
import macros, strutils
macro createAliases(tag: string, body: untyped): untyped =
result = newStmtList()
for classes in body:
assert classes.kind == nnkStrLit, "Input must be a list of string literals"
let tmplName = newIdentNode(classes.strVal.multiReplace([(" ", ""), ("-", "")]))
result.add quote do:
macro `tmplName`(rest: varargs[untyped]): untyped =
var
exprs: seq[NimNode]
classes = `classes`
for argument in rest:
if $argument[0] != "class":
exprs.add argument
else:
classes = classes & " " & argument[1].strVal
var ret = nnkCall.newTree(
newIdentNode("buildHtml"),
nnkCall.newTree(
newIdentNode(`tag`)
)
)
for expr in exprs:
ret[1].add expr
ret[1].add nnkExprEqExpr.newTree(
newIdentNode("class"),
newLit(classes)
)
ret
createAliases("button"):
"main button"
"other button"
createAliases("tdiv"):
"headerbar"
"mainarea"
"base column"
"grow content"
"bar"
"big editor"
"small column"
"optionsbar"
"content2"
type
CodeMirror = distinct Element
OutputKind = enum
Debug = "debug", Output = "output"
Regex = ref object of RootObj
proc newCodeMirror(element: Element, config: js): CodeMirror {. importcpp: "CodeMirror(@)" .}
proc setValue(cm: CodeMirror, value: kstring) {.importcpp: "#.setValue(@)".}
proc getValue(cm: CodeMirror): kstring {.importcpp: "#.getValue()".}
proc setOption(cm: CodeMirror, key: kstring, value: js) {.importcpp: "#.setOption(@)".}
proc replaceSelection(cm: CodeMirror, value: kstring) {.importcpp: "#.replaceSelection(@)".}
proc refresh(cm: CodeMirror) {.importcpp: "#.refresh()".}
proc replace(str: kstring, r: Regex, cmd: proc (x: kstring): kstring): kstring {.importcpp: "#.replace(@)".}
proc setHash(str: kstring) {.importcpp: "window.location.hash = #".}
proc sanitize(str: kstring): kstring {.importcpp: "DOMPurify.sanitize(#)".}
converter toRegex(r: kstring): Regex {.importcpp: "new RegExp(#, 'g')", noSideEffect.}
var
output = Output
myCodeMirror: CodeMirror
outputText: array[Output.low..Output.high, string]
runningCode = false
awaitingShare = false
loadedPasty = ""
showingTour = false
loadedTour = ""
codeCurrentSection = -1
currentSection = 0
totalSections = 0
tourContent = buildHtml:
text "Loading tour..."
knownVersions = @["latest"]
proc switchOutput() =
output = case output:
of Debug: Output
of Output: Debug
proc runCode() =
runningCode = true
kxi.redraw()
proc cb(httpStatus: int, response: cstring) =
runningCode = false
if httpStatus == 200:
let jsonResponse = parseJson($response)
outputText[Output] = jsonResponse["log"].getStr.replace("\n", "<br/>")
outputText[Debug] = $(jsonResponse["compileLog"].getStr)
if outputText[Output] != "<br/>":
output = Output
else:
output = Debug
else:
outputText[Debug] = "No reply from server:<br/>" & $httpStatus & ": " & $response
outputText[Output] = ""
output = Debug
let
compilationTarget = if kdom.getElementById("compilationtarget").value == "C": "c" else: "cpp"
nimversion = $kdom.getElementById("nimversion").value
request = %*{"code": $myCodeMirror.getValue(), "compilationTarget": $compilationTarget, "outputFormat": "html", "version": nimversion}
ajaxPost("/compile", @[], $request, cb)
proc sharePaste() =
awaitingShare = true
proc cb(httpStatus: int, response: cstring) =
awaitingShare = false
if httpStatus == 200:
let id = ($response).rsplit("/", maxsplit = 1)[^1]
outputText[Output] = "https://play.nim-lang.org/#pasty=" & id
outputText[Debug] = ""
output = Output
if not showingTour:
loadedPasty = id
setHash("#pasty=" & loadedPasty)
else:
outputText[Debug] = "No reply from server:<br/>" & $httpStatus & ": " & $response
outputText[Output] = ""
output = Debug
let request = %*{"code": $myCodeMirror.getValue(), "compilationTarget": "c"}
ajaxPost("/pasty", @[], $request, cb)
proc loadPaste(id: string) =
proc cb(httpStatus: int, response: cstring) =
if httpStatus == 200:
outputText[Output] = ""
outputText[Debug] = ""
output = Output
myCodeMirror.setValue(response)
else:
outputText[Debug] = "No reply from server:<br/>" & $httpStatus & ": " & $response
outputText[Output] = ""
output = Debug
ajaxGet("/pasty/" & id, @[], cb)
loadedPasty = id
proc loadTour(id: string) =
proc cb(httpStatus: int, response: cstring) =
if httpStatus == 200:
outputText[Output] = ""
outputText[Debug] = ""
output = Output
var tourNodes = buildHtml:
verbatim response.sanitize
tourContent = tourNodes
else:
outputText[Debug] = "No reply from server:<br/>" & $httpStatus & ": " & $response
outputText[Output] = ""
output = Debug
ajaxGet("/tour/" & encodeUriComponent(id), @[], cb)
loadedTour = id
showingTour = true
proc postRender(data: RouterData) =
if knownVersions.len == 1:
proc cb(httpStatus: int, response: cstring) =
if httpStatus == 200:
for version in parseJson($response)["versions"].getElems:
knownVersions.add version.getStr
ajaxGet("/versions", @[], cb)
if myCodeMirror.Element == nil:
myCodeMirror = newCodeMirror(kdom.getElementById("editor"), js{
mode: "nim".kstring,
value: "".kstring,
tabSize: 2,
lineNumbers: true,
theme: "dracula".kstring
})
myCodeMirror.setOption("extraKeys", js{
Tab: proc(cm: CodeMirror) =
cm.replaceSelection(" ")
,
"Ctrl-Enter": proc(cm: CodeMirror) =
if (not runningCode): runCode()
,
"Cmd-Enter": proc(cm: CodeMirror) =
if (not runningCode): runCode()
})
if showingTour:
var tourContent = kdom.getElementById("tour")
let sections = tourContent.getElementsByTagName("section")
totalSections = sections.len
for idx, section in sections:
if idx != currentSection:
section.style.display = "none"
else:
section.style.display = "block"
let
headers = section.getElementsByTagName("h1")
codes = section.getElementsByTagName("code")
kdom.getElementById("sectionTitle").innerHtml = $(currentSection + 1) & "/" & $totalSections & ": " & (if headers.len > 0: $headers[0].innerHtml else: "No title")
if codes.len > 0 and codeCurrentSection != currentSection:
codeCurrentSection = currentSection
myCodeMirror.setValue(codes[^1].innerHtml)
codes[^1].style.display = "none"
proc changeFontSize() =
let
editor = kdom.getElementById("editor")
fontSizeInput = kdom.getElementById("fontsize")
editor.applyStyle(style(fontSize, fontSizeInput.value & "px"))
myCodeMirror.refresh()
proc createDom(data: RouterData): VNode =
let strhash = $data.hashPart
if strhash.len > "#pasty=".len:
if strhash[0..6] == "#pasty=":
if loadedPasty != strhash[7..^1]:
loadPaste(strhash[7..^1])
if strhash.len > "#tour=".len:
if strhash[0..5] == "#tour=":
if loadedTour != strhash[6..^1]:
loadTour(strhash[6..^1])
result = buildHtml(tdiv):
headerbar:
a(href = "https://play.nim-lang.org"):
img(src = "/assets/logo.svg")
span: text "Playground"
a(href = "https://github.com/PMunch/nim-playground-frontend"):
span: text "Code on GitHub"
mainarea:
if showingTour:
baseColumn:
growContent(id = "tour"):
tourContent
bar:
span(id = "sectionTitle"): text ""
otherButton(onclick = () => (currentSection = max(currentSection - 1, 0))):
text "Previous"
mainButton(onclick = () => (currentSection = min(currentSection + 1, totalSections - 1))):
text "Next"
baseColumn:
bigEditor(id = "editor", class = "monospace"):
optionsBar:
span:
text "Font size: "
input(`type` = "number", id = "fontsize", value = "13", `min` = "8", `max` = "50", step = "1", required = "required", onchange = changeFontSize)
span:
text " Compilation target: "
select(id = "compilationtarget"):
option:
text "C"
option:
text "C++"
span:
text " Nim version: "
select(id = "nimversion"):
for version in knownVersions:
option:
text version
bar:
if not awaitingShare:
otherButton(onclick = sharePaste):
text "Share with pasty.ee"
else:
otherButton(class = "is-loading"):
text "Share with pasty.ee"
otherButton(onclick = switchOutput):
text "Showing: " & $output
if not runningCode:
mainButton(onclick = runCode):
text "Run!"
span(class = "buttonhint"):
text "(ctrl-enter)"
else:
mainButton(class = "is-loading"):
text "Run!"
content2(id = "output"):
pre(class = "monospace"):
verbatim outputText[output]
setRenderer createDom, "ROOT", postRender
setForeignNodeId "tour"
setForeignNodeId "editor"