~technomancy/fennel-lang.org

ref: c9a7db72fe3fd06b5eec936984713f034acd9511 fennel-lang.org/init.lua -rw-r--r-- 8.6 KiB
c9a7db72Phil Hagelberg Remove broken contributors link until we can get it fixed. 3 months ago
                                                                                
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
-- mostly based on repl.lua from Fengari itself:
-- https://github.com/fengari-lua/fengari.io/blob/master/static/lua/web-cli.lua
package.path = "./?.lua"
local js = require "js"

local welcome = nil

-- the hacks below are needed specifically to get the Fennel test suite to pass

-- just make a few things not blow up
_G.os.exit = function() end
_G.os.getenv = function() return nil end

-- require-macros depends on io.open; we splice in a hacky replacement
io={open=function(filename)
       return {
          read = function(_, all)
             assert(all=="*all", "Can only read *all.")
             local xhr = js.new(js.global.XMLHttpRequest)
             xhr:open("GET", filename, false)
             xhr:send()
             assert(xhr.status == 200, xhr.status .. ": " .. xhr.statusText)
             return tostring(xhr.response)
          end,
          close = function() end,
       }
end}

package.preload.fennelview = assert(loadfile("fennelview.lua"))

-- Save references to lua baselib functions used
local _G = _G
local pack = table.pack
local tostring = tostring

local document = js.global.document
local output = document:getElementById("fengari-console")
local prompt = document:getElementById("fengari-prompt")
local input = document:getElementById("fengari-input")
local luacode = document:getElementById("compiled-lua")
local luapane = document:getElementById("lua-pane")
local togglebtn = document:getElementById("toggle-compiled-code")
assert(output and prompt and input and luacode and luapane and togglebtn)

local function triggerEvent(el, type)
    local e = document:createEvent("HTMLEvents")
    e:initEvent(type, false, true)
    el:dispatchEvent(e)
end

local history = {}
local historyIndex = nil
local historyLimit = 100

local function highlightLines(target, elements)
   for i = 0, #elements-1 do
      if tonumber(elements[i]:getAttribute("history")) == target then
	 elements[i].style.backgroundColor = (elements[i].style.backgroundColor == "") and "pink" or ""
      else
	 elements[i].style.backgroundColor = ""
      end
   end
end

local function makeLine(...)
    local toprint = pack(...)

    local line = document:createElement("pre")
    line.style["white-space"] = "pre-wrap"

    line:setAttribute("history", #history)

    line.onclick = function()
       local n = tonumber(line:getAttribute("history"))

       highlightLines(n, output.children)
       highlightLines(n, luacode.children)
    end

    for i = 1, toprint.n do
        if i ~= 1 then
            line:appendChild(document:createTextNode("\t"))
        end
        line:appendChild(document:createTextNode(tostring(toprint[i])))
    end

    return line
end

_G.printLuacode = function(...)
   local line = makeLine(...)

   luacode:appendChild(line)
   luacode.scrollTop = luacode.scrollHeight
   triggerEvent(luacode, "change")
end

_G.print = function(...)
   local line = makeLine(...)

   output:appendChild(line)
   output.scrollTop = output.scrollHeight
   triggerEvent(output, "change")
end

_G.narrate = function(...)
    local line = makeLine(...)
    line.style.color = "blue"

    output:appendChild(line)

    output.scrollTop = output.scrollHeight
    triggerEvent(output, "change")
end

_G.printError = function(...)
   local line = makeLine(...)
   line.style.color = "red"

   output:appendChild(line)

   output.scrollTop = output.scrollHeight
   triggerEvent(output, "change")
end

local repl = { alreadyStarted = false, loaded = false, instance = nil, stack = {} }

function initReplForWebThroughWorker()
    input:setAttribute("disabled", "disabled")
    input:setAttribute("placeholder", "0%")
    input.value = ''

    _G.print("Loading...")

    local percentage = 0
    local dots = ''

    local loader = js.global:setInterval(function()
      if not repl.loaded and percentage < 99 then
        percentage = percentage + 1
        input:setAttribute("placeholder", percentage .. "%")
      elseif not repl.loaded then
        dots = dots .. "."
        if #dots > 40 then
          dots = '.'
        end
        input:setAttribute("placeholder", percentage .. "%" .. dots)
      else
        js.global:clearInterval(loader);
      end
    end, (10 * (1000)) / 100) -- Maximum expected time on a slow computer: 10s

    repl.instance = js.new(js.global.Worker, '/repl-worker.js')

    repl.instance.onmessage = function(_, message)
        local content = message.data

        local pipePosition = content:find('|')
        local functionName = content:sub(1, pipePosition-1)

        content = content:sub(pipePosition+1, #content)

        pipePosition = content:find('|')

        local command = content:sub(1, pipePosition-1)

        content = content:sub(pipePosition+1, #content)

        if command == 'append' then
            if repl.stack[functionName] == nil then
                repl.stack[functionName] = {}
            end

          table.insert(repl.stack[functionName], content)
        elseif command == 'dispatch' then
            _G[functionName](table.unpack(repl.stack[functionName]))

            repl.stack[functionName] = {}
        elseif command == 'loaded' then
            welcome = content

            js.global:clearInterval(loader);
            repl.loaded = true
            input:removeAttribute("disabled")
            input:setAttribute("placeholder", "Type code here...")

            js.global:setTimeout(function()
            input = document:getElementById("fengari-input")
            input.value = '100%'
            input.value = ''
            end)
        end
    end
end

function initReplForWeb()
    _G.print("Loading Fennel...")
    js.global:setTimeout(function()
        local fennel = require("fennel/fennel")
        package.loaded.fennel = fennel
        _G.print("Loading REPL...")
        js.global:setTimeout(function()
            repl.instance = coroutine.create(fennel.dofile("repl.fnl"))
            assert(coroutine.resume(repl.instance))
            welcome = "Welcome to Fennel " .. fennel.version ..
                ", running on Fengari (" .. _VERSION .. ")"
            _G.print(welcome)
            _G.printLuacode("Compiled Lua code")
        end)
    end)
end

function initReplForTerminal()
    local fennel = require("fennel/fennel")
    package.loaded.fennel = fennel
    repl.instance = coroutine.create(fennel.dofile("repl.fnl"))
end

function initRepl()
    if repl.alreadyStarted then
        return
    end

    repl.alreadyStarted = true

    if js.global.Worker then
        initReplForWebThroughWorker()
    elseif js.global.setTimeout then
        initReplForWeb()
    else
        initReplForTerminal()
    end
end

function input.onfocus()
    initRepl()
end

function evaluateFennelInput(value)
    if js.global.Worker then
        repl.instance:postMessage(value)
    else
        coroutine.resume(repl.instance, value)
    end
end

togglebtn.onclick = function()
    if luapane.style.display == 'flex' then
        luapane.style.display = 'none'
    else
        luapane.style.display = 'flex'
    end
end

function input.onkeydown(_, e)
    if not e then
        e = js.global.event
    end

    local key = e.key or e.which
    if key == "Enter" and not e.shiftKey then
        historyIndex = nil
        if #input.value > 0 then
           if history[#history] ~= input.value then
              table.insert(history, input.value)
              if #history > historyLimit then
                 table.remove(history, 1)
              end
           end
           evaluateFennelInput(input.value)
           input.value = ""
        end
        return false
    elseif key == "ArrowUp" or key == "Up" then
        if historyIndex then
            if historyIndex > 1 then
                historyIndex = historyIndex - 1
            end
        else -- start with more recent history item
            local hist_len = #history
            if hist_len > 0 then
                historyIndex = hist_len
            end
        end
        input.value = history[historyIndex]
        return false
    elseif key == "ArrowDown" or key == "Down" then
        local newvalue = ""
        if historyIndex then
            if historyIndex < #history then
                historyIndex = historyIndex + 1
                newvalue = history[historyIndex]
            else -- no longer in history
                historyIndex = nil
            end
        end
        input.value = newvalue
        return false
    elseif key == "l"
        and e.ctrlKey
        and not e.shiftKey
        and not e.altKey
        and not e.metaKey
        and not e.isComposing then
        -- Ctrl+L clears screen like you would expect in a terminal
        output.innerHTML = ""
        _G.print(welcome)
        return false
    end
end

if js.global.Worker or not js.global.setTimeout then
    initRepl()
end

return repl.instance