Working with a web page in the browser: elements, events, timers and JavaScript objects.
import dom
This package lets a Salam program drive a web page: find and create elements, change their text, classes and styles, react to clicks and keys, run timers and keep small values in localStorage. A program that uses it runs in the browser. Translate it to JavaScript with salam build app.salam --platform=js --output=app.js and load it with a <script src="app.js"> tag; main runs once the page is ready, and println writes to the browser console. That is why the examples on this page are only checked, not run. For drawing use web.canvas, for games that read the keyboard every frame web.keys, and for a desktop window around a page webview.
Elements and other JavaScript objects are held in an i64 variable, and events and timers take an anonymous function such as (): ... end. Each function maps to one browser call (SetText is textContent, SetStyle is style.setProperty and so on), so the MDN documentation for that call applies.
Things that catch people out:
•
A missing element is JavaScript null, not 0.el == 0 is never true for it, and using it throws. Check with Exists(id) before ById, or with CountOf(QueryAll(sel)) == 0 for a selector.
•
SetHtml runs whatever HTML it gets. Put text from users in with SetText, never with SetHtml.
•
SetStyle takes CSS names such as background-color, not the JavaScript form backgroundColor.
•
OnReady does nothing when called from main, because main already runs after the page is ready and the browser does not repeat the ready event. Put start-up code straight in main.
•
OffEvent needs the very function value you registered, so keep it in a variable; a second lambda with the same body is a different function.
Running the examples
Each program below is a whole page's script. Save it as app.salam, translate it, and open an HTML file that loads the result:
Then visit http://127.0.0.1:8000. Output from println appears in the browser console. With --output=app.html instead, salam build --platform=js writes one self contained page.
A to-do list
Most pages follow the same shape: build the elements once in main, keep the ones you need later in global variables, and react to events. A click handler that is created inside a function, like the one on each new list item, remembers the element it was made for. StoreSetInt and StoreGetInt keep a number in the browser's localStorage, so it survives a reload.
dom-todo.salam
import dom
mut list := 0asi64mut entry := 0asi64mut added := 0funcadd_item(text: str):
item := dom.Create("li")
dom.SetText(item, text)
dom.OnEvent(item, "click", (): dom.ToggleClass(item, "done") end)
dom.Append(list, item)
added++
dom.StoreSetInt("todo-added", added asi64)
endfuncmain:
dom.SetTitle("To do")
entry = dom.Create("input")
dom.SetAttr(entry, "placeholder", "What needs doing?")
button := dom.Create("button")
dom.SetText(button, "Add")
list = dom.Create("ul")
dom.Append(dom.Body(), entry)
dom.Append(dom.Body(), button)
dom.Append(dom.Body(), list)
dom.OnEvent(button, "click", (): text := dom.GetValue(entry) if text.Len() > 0: add_item(text) dom.SetValue(entry, "") endend)
dom.OnEventE(entry, "keydown", (e: i64): if dom.EventKey(e) == "Enter": dom.PreventDefault(e) text := dom.GetValue(entry) if text.Len() > 0: add_item(text) dom.SetValue(entry, "") endendend)
println"items added on this device so far:", dom.StoreGetInt("todo-added")
end
OnEvent takes a handler without arguments; use OnEventE when you need the event itself, for example to read the key with EventKey or to stop the browser's default action with PreventDefault.
Working with elements already on the page
When the HTML comes from a server or a template, the script finds the elements instead of creating them. This one filters a product table as the user types. It first checks with Exists that the page has what it needs, then takes every row with QueryAll and walks them with CountOf and ItemAt. Hiding a row is SetStyle(row, "display", "none"), and an empty value removes the style again.
dom-filter.salam
import dom
importstrfuncfilter(rows: i64, word: str, counter: i64):
mut shown := 0repeat dom.CountOf(rows) in i:
row := dom.ItemAt(rows, i)
name := str.Lower(dom.GetText(row))
if word.Len() == 0orstr.Contains(name, word):
dom.SetStyle(row, "display", "")
shown++
else:
dom.SetStyle(row, "display", "none")
endend
dom.SetText(counter, shown + " of " + dom.CountOf(rows) + " products")
endfuncmain:
ifnot (dom.Exists("search") and dom.Exists("count")):
println"this script needs #search and #count on the page"retend
search := dom.ById("search")
counter := dom.ById("count")
rows := dom.QueryAll("#products tr")
if dom.CountOf(rows) == 0:
dom.SetText(counter, "no products")
retend
dom.SetStyle(dom.Query("#products"), "background-color", "#fafafa")
dom.OnEvent(search, "input", (): filter(rows, str.Lower(str.Trim(dom.GetValue(search))), counter) end)
filter(rows, "", counter)
end
It expects markup such as <input id="search"> <p id="count"></p> <table id="products"><tr><td>Green tea</td></tr>...</table>. QueryAll returns the rows that exist at that moment; rows added later are not in the list, so query again after you change the table.
Checking a form as the user types
The input event fires on every change to a text box, which makes it the place for live checks. One function looks at all fields, writes the first problem into a message element and switches the button with SetBool(el, "disabled", ...). Calling it once at the end of main puts the form in the right state before the user touches it.
dom-form-check.salam
import dom
importstrmut email := 0asi64mut password := 0asi64mut submit := 0asi64mut note := 0asi64funccheck():
e := dom.GetValue(email)
p := dom.GetValue(password)
mut problem := ""ifnotstr.Contains(e, "@"):
problem = "Enter an email address."else p.Len() < 8:
problem = "The password needs at least 8 characters."end
dom.SetText(note, problem)
dom.SetBool(submit, "disabled", problem.Len() > 0)
if problem.Len() > 0:
dom.AddClass(note, "error")
else:
dom.RemoveClass(note, "error")
endendfuncmain:
email = dom.Create("input")
dom.SetAttr(email, "type", "email")
password = dom.Create("input")
dom.SetAttr(password, "type", "password")
submit = dom.Create("button")
dom.SetText(submit, "Sign up")
note = dom.Create("p")
each el in [email, password, submit, note]:
dom.Append(dom.Body(), el)
end
dom.OnEvent(email, "input", (): check() end)
dom.OnEvent(password, "input", (): check() end)
dom.OnEvent(submit, "click", (): dom.Alert("Welcome, " + dom.GetValue(email)) end)
check()
end
An event wants a function value, so wrap a named function in a short lambda: (): check() end. Checks in the browser are for the user's comfort only; the server must check the same things again, for example with net.http.validate.
A countdown with a timer
SetInterval calls a function every so many milliseconds and returns an id; keep it in a global so the function can stop itself with ClearInterval. For a single delayed call use SetTimeout, and for anything that moves on screen use EveryFrame instead, which follows the display's refresh rate.
dom-countdown.salam
import dom
mut left := 10mut timer := 0asi64mut label := 0asi64funcmain:
label = dom.Create("h1")
dom.Append(dom.Body(), label)
dom.SetText(label, "" + left)
timer = dom.SetInterval((): left-- dom.SetText(label, "" + left) if left == 0: dom.ClearInterval(timer) dom.SetText(label, "Time is up") dom.SetStyle(label, "color", "crimson") dom.Tone(660, 300) endend, 1000)
end
Tone plays a short beep through the Web Audio API. Browsers only allow sound after the user has clicked or typed something on the page, so a beep from a timer that started on load may stay silent.