Getting Started
By the end of this page you will have created a counter, changed it while it runs in a browser, tested it without a browser, and built it for deployment.
Set up
First open the current Roc Signals release notes.
Under Compilers, find the Roc nightly that release was built and tested
with. Install that nightly from
roc-lang/nightlies and put
its roc executable on your PATH.
Check the installed version before downloading the tool:
roc version
The version should match the nightly named in the Signals release notes. Those notes also describe any compiler or dependency limitations affecting the release; a newer nightly may behave differently.
signals.roc is a small Roc program that creates, serves, builds and tests
an app. Use the tool matching these docs: it generates an entry point for
its matching platform. A documentation preview may link an unreleased
candidate; keep its tool, platform and samples together rather than mixing
versions. Download the tool and create an app:
curl -fLO "https://github.com/lukewilliamboswell/roc-signals/releases/latest/download/signals.roc"
roc signals.roc init counter
cd counter
roc downloads what signals.roc needs the first time it runs: the
roc-signals package it names, and the basic-cli platform it runs on.
roc signals.roc help lists the commands and says which release and
nightly you have.
The files of an app
init writes a counter, the same one this page explains:
| File | Purpose |
|---|---|
signals.roc | The tool, which runs init, serve, build and test |
Counter.roc | The app: its state, view and program |
main.roc | The entry point, which names the platform: it builds for the browser and as the native spec runner |
index.html | The page that mounts the app |
specs/counter.scm | A spec, run by test |
.gitignore | Keeps build output (.signals/ and dist/) out of version control |
Write the app
import pf.Engine exposing [Elem, In, Root, State]
import pf.Html
## A counter: one piece of state and two buttons that change it.
Counter := [].{
## Inside the counter's state: one local state holding an `I64`.
Ctx : In(Root, I64)
## The program both platforms run.
program : Engine.Program
program = Engine.program_startup({}, Engine.entries({ fallback: Some("/") }, [{ path: "/", route: 0.U8 }]), |_route| Engine.state(0, Counter.view))
view : State(Ctx, I64) -> Elem(Ctx)
view = |count|
Html.div(
"counter",
[
Html.button("-", [Html.aria_label("Decrement")], count.update(|n| n - 1)),
Html.span_s("${count.signal()}", [Engine.test_id("count")]),
Html.button("+", [Html.aria_label("Increment")], count.update(|n| n + 1)),
],
)
}
Engine.state(0, Counter.view) creates a piece of local state with the
initial value 0 and passes its State to view. Inside view:
count.signal()is a signal of the state’s current value..mapturns it into the text thespanshows. The engine re-evaluates that text only whencountchanges.count.update(|n| n + 1)is a handler: a reducer the engine applies when the button is clicked.Ctxnames the context the view runs in: inside one state of typeI64at the root. Every signal,Stateand element is typed by the context it belongs to, so a value can never be read where it does not exist.Html.aria_labelgives each button an accessible name, which is also how specs find it.
view runs once, when the app starts. It does not run again on a click: the
engine applies the reducer and rewrites the one text that reads count.
The count is local state because only the counter cares about it. State that several parts of an app share lives in a store instead, and Thinking in Signals says how to choose.
program is the value the entry point binds.
The entry point
main.roc names the platform and binds the app’s program as main:
The example uses <package release URL here> as a placeholder. Keep the
actual platform URL that init wrote in your file. If writing an entry
point by hand, use the platform bundle URL from the
Roc Signals release notes.
app [main] { pf: platform "<package release URL here>" }
import pf.Engine
import Counter
## `roc build --target=wasm32` gives the browser module and
## `roc build --target=x64musl` its native spec runner.
main : Engine.Program
main = Counter.program
## Check that the default first page mounts while this app compiles.
mounted : U64
mounted = Engine.mounts(main)
The platform builds this one file for two kinds of target:
--target=wasm32 gives the module the browser runs, and your system’s
native target gives the app’s native spec runner: x64musl on Linux,
arm64mac or x64mac on macOS, x64win on Windows. signals.roc makes
both builds for you, choosing the native target for the machine it runs
on.
Run it in a browser
roc signals.roc serve
Building the app...
Serving the app at http://127.0.0.1:8000/ (press Ctrl-C to stop). Pages reload when you save a change, and show build errors over the app.
Between the two lines it says how long the build took. Open the address.
The page is your index.html, which loads the app with the platform’s
runtime:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Counter</title>
<style>
#app[data-roc-failed] { border: 1px solid #a00; padding: 1rem; }
#app[data-roc-failed]::before { content: "The app could not start. Reload to try again."; display: block; }
</style>
</head>
<body>
<div id="app" data-roc-picture></div>
<noscript><p>JavaScript is needed to interact with this app.</p></noscript>
<script type="module">
import { mountRocEngineApp } from "./runtime.mjs";
await mountRocEngineApp({
wasmUrl: "app.wasm",
root: document.getElementById("app"),
onFault: (fault) => console.error(`${fault.class}: ${fault.message}`),
});
</script>
</body>
</html>
The server supplies runtime.mjs and its environment.mjs readers (with
worker.mjs, which the runtime
starts workers from) and app.wasm, the app’s
development build; your other files are served as they are. When port 8000
is taken it uses the next free one and says so; --port N chooses another.
Now change the initial value in Counter.roc from 0 to 10, and save.
The server rebuilds the app and the page reloads, showing 10. Reloading
starts the app afresh: nothing of the running app is carried across a
change. If the build fails, the compiler’s report appears over the page,
which keeps the last build that worked, and the terminal shows it too; fix
the error and save, and the page reloads. An error that stops the page from
mounting the app, and a fault the engine contains while it runs, appear the
same way. A change to any other file, such as index.html, reloads the page
without a build. The script that does this is added to the page as the
server sends it; your index.html is never changed.
If the app breaks a contract, onFault receives the classified diagnostic;
Under the Hood
explains what each class means.
Test it
Use another terminal in the counter directory while the development server
runs, or stop it with Ctrl+C before running the commands below.
Before continuing, restore the initial value to 0 in Counter.roc and
save. The spec below describes that original counter: it starts at 0,
counts up twice to 2, then down to 1. Keeping a different starting
value is valid, but its spec must expect those different counts too.
A spec describes what a user does and sees, located the way a screen reader would find things:
(test "the counter counts both ways"
(steps
(expect-text (test-id "count") "0")
(click (role button :name "Increment"))
(click (role button :name "Increment"))
(expect-text (test-id "count") "2")
(click (role button :name "Decrement"))
(expect-text (test-id "count") "1")))
roc signals.roc test
Building the app's spec runner...
Running 1 spec:
passed the counter counts both ways
The spec passed.
test builds the app’s native spec runner and runs every spec in specs/.
Compiler warnings are printed even when the build succeeds; they do not make a
passing test command fail.
The runner drives the real engine and checks the DOM it would build, so a
spec takes milliseconds. A failing spec names its file, line and the step
that did not hold, and test exits with 1. The native spec runner is built
for Linux on x86-64, macOS on Apple silicon and on Intel, and Windows on
x86-64, and a spec means the same on each; on any other system (Linux on
ARM64, for now) test says which systems run them.
Testing covers the spec language and the Chrome replay.
Build it for deployment
roc signals.roc build
The tool shows the compiler’s warnings even when the build succeeds. Optimized
builds keep dbg, so read its warning before deploying the output. A warning
alone does not make the command fail.
Built the app into dist/:
dist/index.html
dist/assets/5e711d3a91d0f155/app.wasm
dist/assets/5e711d3a91d0f155/runtime.mjs
dist/assets/5e711d3a91d0f155/environment.mjs
dist/assets/5e711d3a91d0f155/worker.mjs
build makes the app’s module with --opt=size, lays out dist/, and
lists each file it wrote with its size. The layout is:
dist/index.html, your page, with each quoted relative URL that names one of the files below pointed into the hashed directory. Nothing else in it changes.dist/assets/<hash>/: the module, the platform’s runtime, its environment helper and worker script, and the app’s other files (its scripts, styles and images, in their own folders). The directory’s name is a hash of everything in it, so a browser may cache it for ever. The files keep their places relative to each other, so the runtime still importsenvironment.mjsand findsworker.mjsbeside it.- Everything under
public/, copied to the top ofdist/under its own name: put there a file something names by a fixed URL, such as data the app’s Roc code downloads,robots.txtor a favicon.
build replaces dist/ each time. Serve it from any static file server:
.mjs files as text/javascript and app.wasm as application/wasm, with
index.html not cached. No other headers are needed.
Build a first page
roc signals.roc build prerenders every concrete entry declared by the app’s
Engine.entries catalogue. The scaffold uses Engine.program_startup with one
entry, /. An app declaring / and /tasks/ gets dist/index.html and
dist/tasks/index.html, sharing the same immutable assets:
roc signals.roc build
The catalogue supplies each path’s fixed initial route to the app. The build uses that same entry, view and engine to produce its HTML. It does not crawl links or enumerate every possible database id. Declare a finite set of concrete entries, or build an explicit shell and configure the static host’s fallback. Query and fragment values are later browser facts, rather than additional pages.
The browser binds the complete first frame using private engine annotations. Ordinary content keeps its DOM objects through startup. Managed controls, forms and editable surfaces wait behind producer-added gates; declared native content can remain useful while the module loads. Once the frame is bound, initial follow-ups settle through the ordinary engine. A declared update or scope replacement may then change content. Explicit placeholders can defer a live body and replace their static content in later turns.
Startup callbacks receive the fixed route, without live Boot data. Apps needing current browser facts request an environment snapshot after bootstrap. Existing Boot-reading entries remain supported through the explicit plain-page opt-out:
roc signals.roc build --no-prerender
A default build refuses an ineligible app instead of silently omitting its
first pages. --no-prerender creates the page through ordinary runtime mounting.
Legacy apps can still request replacement-only pictures with --picture URL...;
those old pictures retain their inert-then-replace behavior.
A build template marks exactly one authored mount root with data-roc-picture.
The generated annotated page uses private data-roc-frame, data-roc-node and
data-roc-children attributes; leave those names to the engine. An HTML root gets
no automatic blanket gate. For an SVG, MathML or other non-HTML root, author an
immediate HTML parent marked data-roc-picture-inert-parent=""; its only ordinary
element child is the mount root. This explicit owner stays inert through
startup. The builder adds no wrapper or enclosing namespace and refuses a
host template the browser would repair. Authored inert text is preserved.
Keep the scaffold’s loader shape: its wasmUrl names the quoted relative file
app.wasm or ./app.wasm. Build stamps that reference with an explicit
?roc-build=… receipt matching the generated frame and immutable assets, including
on nested pages. The CLI refuses a template without this supported reference;
use --no-prerender for that template. A separate build integration may supply
the matching receipt through the runtime’s startupBuildToken option.
Asset references are projected in the original template before app markup is
inserted, so app text and attributes resembling asset names stay unchanged.
Deploy the generated HTML and its matching assets together. Missing or modified
annotations and mismatched build receipts are startup faults; there is no
automatic local repair. The scaffold styles data-roc-failed on the root. A
faulted first page remains inert until explicit fresh recovery or reload.
Keep the project and external compiler inputs unchanged during a build. The
tool checks the project’s file inventory and modification times before
publication and refuses detected edits, preserving the previous dist/.
The complete output is staged before publication. A refused entry, output-path
collision or invalid frame leaves the published dist/ intact. Replacing an
existing directory uses a backup and rename with rollback. Prerendering requires
one of the native-runner systems listed above.
Working in a checkout
To work on roc-signals itself, or to run this page’s counter from
www/samples/counter/ in a checkout of
the repository,
see Contributing: Blueprint provides the tools,
and the platform builds from source.
Next
Read Thinking in Signals for the model, then build the Tutorial app, which keeps its state in a store.