Skip to content

tinyweb for JavaScript

tinyweb’s JavaScript implementation is a library of its own: a JavaScript program can use it to draw on a web page, add buttons, labels and sliders to it, play sounds and answer the reader, with no Pyking anywhere. It is the file Pyking copies beside a program compiled for node24, renamed tinyweb.js.

Download tinyweb-javascript.zip: tinyweb.js, the example below, and the samples in tinyweb_assets/.

Running a program

The program serves its own page: web_init starts the server and prints its address, and once the program’s own code has finished it goes on serving the page and calling the functions it handed over until it is stopped (Ctrl-C). Open the address in a browser.

Terminal window
node example.js

The page asks for a sample beside where the program runs first, then in tinyweb_assets/ there.

An example

// A canvas, two circles, two samples and buttons that play them, written
// in JavaScript against tinyweb.js, for node. Run it with
// `node example.js` and open the address it prints.
import * as tw from "./tinyweb.js";
tw.web_init(0);
const kick = tw.load_sample("kick1.wav");
const snare = tw.load_sample("snare1.wav");
const canvas = tw.canvas(400, 200);
tw.draw_circle(canvas, 100, 50, 30, "#ff0000");
tw.draw_circle(canvas, 100, 50, 20, "#000000");
let presses = 0;
tw.make_button("Play kick", () => tw.play_sample(kick, 0.0, 1.0, 1.0));
tw.make_button("Play snare", () => {
presses += 1;
console.log(`snare, press ${presses}`);
tw.play_sample(snare, 0.0, 0.5, 1.0);
});
tw.make_button("Does nothing", () => {});
console.log("built the page");

Functions

Every function but web_init needs web_init to have been called first, or PYKING_TINYWEB_LOG to be set (below); otherwise it says so and the program ends with status 1.

web_init

/** @param {number} port @returns {undefined} */
export function web_init(port)

Serves the program’s page on port and prints its address, tinyweb: http://127.0.0.1:N/; port 0 picks any free port. Call it before anything else. With PYKING_TINYWEB_LOG set it does nothing.

canvas

/** @param {number} width @param {number} height @returns {number} */
export function canvas(width, height)

A new canvas, width by height pixels, placed below what the page already shows. Answers the number that names it.

fill_canvas

/** @param {number} c @param {string} color @returns {undefined} */
export function fill_canvas(c, color)

Fills the whole canvas c with color, a CSS color such as "#ff0000" or "red".

draw_circle

/** @param {number} c @param {number} x @param {number} y @param {number} radius @param {string} color @returns {undefined} */
export function draw_circle(c, x, y, radius, color)

A filled circle on the canvas c, centred at (x, y).

draw_rect

/** @param {number} c @param {number} x @param {number} y @param {number} width @param {number} height @param {string} color @returns {undefined} */
export function draw_rect(c, x, y, width, height, color)

A filled rectangle on the canvas c, with its top left corner at (x, y).

draw_line

/** @param {number} c @param {number} x1 @param {number} y1 @param {number} x2 @param {number} y2 @param {string} color @param {number} width @returns {undefined} */
export function draw_line(c, x1, y1, x2, y2, color, width)

A straight line on the canvas c, from (x1, y1) to (x2, y2), width pixels wide.

draw_text

/** @param {number} c @param {number} x @param {number} y @param {string} words @param {string} color @param {number} size @returns {undefined} */
export function draw_text(c, x, y, words, color, size)

words written on the canvas c, with the top left corner of the text at (x, y), size pixels high.

make_button

/** @param {string} title @param {() => void} on_click @returns {number} */
export function make_button(title, on_click)

A button showing title, placed below what the page already shows, which calls on_click each time it is pressed. Answers the number that names it.

label

/** @param {string} text @returns {number} */
export function label(text)

A line of text, placed below what the page already shows. Answers the number that names it to set_label.

set_label

/** @param {number} id @param {string} text @returns {undefined} */
export function set_label(id, text)

Replaces the text of the label id with text.

make_slider

/** @param {number} low @param {number} high @param {number} value @param {(number) => void} on_change @returns {number} */
export function make_slider(low, high, value, on_change)

A slider from low to high, starting at value, placed below what the page already shows, which calls on_change with each new value it is moved to. Answers the number that names it.

apply_style

/** @param {number} id @param {string} kind @param {string} property @param {string} value @returns {undefined} */
export function apply_style(id, kind, property, value)

Changes the page’s look. With kind “theme”, value names a theme: “light” (the default), “dark”, “plain”, “paper” or “retro”. With kind “page”, “button”, “label”, “slider” or “canvas”, property of every element of that kind becomes value; with kind “element”, only the element id’s. property is one of background, color, border, radius, font, size, padding, gap, accent and width, and value is CSS, such as “#336699” or “12px”. id is 0 except for an element.

load_sample

/** @param {string} name @returns {number} */
export function load_sample(name)

Starts loading the sound file name and answers a number naming it to play_sample. The name is looked up beside where the program runs first, and then among the samples tinyweb ships in tinyweb_assets/: kick1.wav, snare1.wav, hihat1.wav and piano_c1.wav.

play_sample

/** @param {number} sample @param {number} at @param {number} volume @param {number} rate @returns {undefined} */
export function play_sample(sample, at, volume, rate)

Plays the sample sample: at the time at on the page’s clock, or now if that has passed; volume times as loud, and rate times as fast, which raises its pitch as much.

time

/** @returns {number} */
export function time()

The page’s clock, in seconds, as the page last reported it: inside an on_frame callback, the time the frame is for. It is the audio clock once sound has started, so a time read here is a time play_sample can be given.

on_frame

/** @param {(number) => void} draw @returns {undefined} */
export function on_frame(draw)

Calls draw before each frame the page shows, with the time the frame is for.

on_mouse

/** @param {number} c @param {(number, number) => void} click @returns {undefined} */
export function on_mouse(c, click)

Calls click with the position, in pixels from the top left corner, of every click on the canvas c.

on_key

/** @param {(string) => void} pressed @returns {undefined} */
export function on_key(pressed)

Calls pressed with the name of every key pressed while the page has the focus: a letter or digit as itself, and otherwise the browser’s name for it, such as “ArrowLeft”, “Enter” or ” ”.

Without a page

Two environment variables, each a file path, run a program with no page at all, which is how it is tested: with PYKING_TINYWEB_LOG set, every command the program would send its page is appended to that file as one line, and once the program’s own code has finished the events PYKING_TINYWEB_EVENTS lists — click ID, slide ID VALUE, frame T, mouse ID X Y, key NAME, one per line — are delivered as if a reader had caused them.

Terminal window
PYKING_TINYWEB_LOG=page.log PYKING_TINYWEB_EVENTS=clicks.txt node example.js

What Pyking generates

Pyking’s own tinyweb tests, compiled for node24. Each comes with the libraries it needs as Pyking writes them — tinyweb’s implementation under its own name, and the module Pyking compiles from tinyweb’s Pyking half — and is built and run with:

Terminal window
node program.js

lib_tinyweb_frames

# Animation kept in time with sound: each frame is drawn for the time
# the page gives it, and each beat is scheduled half a second ahead on
# the same clock, so it sounds where the picture says it is. The
# .events file delivers four frames.
import tinyweb as tw
tw.web_init(0)
c = tw.canvas(200, 100)
kick = tw.load_sample("kick1.wav")
beat = 0.5
var next_beat = 0.0
def draw(t: Float):
tw.clear(c, "#111111")
tw.circle(c, int(t * 100.0), 50, 10, "#ffcc00")
if t >= next_beat:
print("beat scheduled at " ++ string(next_beat + beat) ++ ", drawn at " ++ string(t))
tw.play(kick, at = next_beat + beat)
next_beat := next_beat + beat
tw.on_frame(draw)
print(tw.time())

lib_tinyweb_frames.zip

program.js, as Pyking generates it
// Generated from lib_tinyweb_frames.pyk by the Pyking compiler. Do not edit.
// Target: node24. Run with: node <this file>
import { print, pykFloatStr, pykTrunc } from './pyk-runtime.js';
// A Pyking list is a JavaScript array with a marker on it: a tuple
// is an array too, and the two print differently. A property rather
// than a class, so that a formatter in another module can read it.
function pykList(items) {
items.pykList = true;
return items;
}
// Pyking's `++` joins two strings or two lists. A list is an array
// here and JavaScript's `+` would stringify one, so which is meant
// is decided by looking -- this backend infers no types.
function pykConcat(a, b) {
return Array.isArray(a) ? pykList([...a, ...b]) : a + b;
}
import * as tw from './tinyweb.js';
import * as tw_external from './tinyweb_external.js';
tw_external.web_init(0);
const c = tw_external.canvas(200, 100);
const kick = tw_external.load_sample('kick1.wav');
const beat = 0.5;
let next_beat = 0.0;
function draw(t) {
tw.clear(c, '#111111');
tw.circle(c, pykTrunc(t * 100.0), 50, 10, '#ffcc00');
if (t >= next_beat) {
print(pykConcat(pykConcat(pykConcat('beat scheduled at ', pykFloatStr(next_beat + beat)), ', drawn at '), pykFloatStr(t)));
tw.play(kick, next_beat + beat, tw.play__default__volume(), tw.play__default__rate());
next_beat = next_beat + beat;
}
}
tw_external.on_frame(draw);
print(pykFloatStr(tw_external.time()));

lib_tinyweb_input

# The mouse, the keyboard and a slider, each reported on a label, and
# the other drawing functions. The .events file clicks the canvas,
# presses two keys -- the second Enter -- and moves the slider.
import tinyweb as tw
tw.web_init(0)
c = tw.canvas(300, 200)
tw.rect(c, 0, 0, 300, 200, "#eeeeee")
tw.line(c, 0, 0, 300, 200)
tw.line(c, 0, 200, 300, 0, "red", width = 3)
tw.text(c, 10, 10, "click \"me\"", size = 20)
status = tw.label("nothing yet")
def clicked(x: Int, y: Int):
tw.set_label(status, "clicked at " ++ string(x) ++ ", " ++ string(y))
tw.circle(c, x, y, 5, "blue")
def pressed(key: String):
print("key [" ++ key ++ "]")
if key == "Enter":
tw.play_file("snare1.wav")
def moved(value: Int):
tw.set_label(status, "slider at " ++ string(value))
tw.on_mouse(c, clicked)
tw.on_key(pressed)
tw.slider(0, 10, 5, on_change = moved)
tw.slider(1, 3, 2)

lib_tinyweb_input.zip

program.js, as Pyking generates it
// Generated from lib_tinyweb_input.pyk by the Pyking compiler. Do not edit.
// Target: node24. Run with: node <this file>
import { print, pykFormat } from './pyk-runtime.js';
// A Pyking list is a JavaScript array with a marker on it: a tuple
// is an array too, and the two print differently. A property rather
// than a class, so that a formatter in another module can read it.
function pykList(items) {
items.pykList = true;
return items;
}
// Pyking's `++` joins two strings or two lists. A list is an array
// here and JavaScript's `+` would stringify one, so which is meant
// is decided by looking -- this backend infers no types.
function pykConcat(a, b) {
return Array.isArray(a) ? pykList([...a, ...b]) : a + b;
}
import * as tw from './tinyweb.js';
import * as tw_external from './tinyweb_external.js';
tw_external.web_init(0);
const c = tw_external.canvas(300, 200);
tw.rect(c, 0, 0, 300, 200, '#eeeeee');
tw.line(c, 0, 0, 300, 200, tw.line__default__color(), tw.line__default__width());
tw.line(c, 0, 200, 300, 0, 'red', 3);
tw.text(c, 10, 10, 'click "me"', tw.text__default__color(), 20);
const status = tw_external.label('nothing yet');
function clicked(x, y) {
tw_external.set_label(status, pykConcat(pykConcat(pykConcat('clicked at ', pykFormat(x)), ', '), pykFormat(y)));
return tw.circle(c, x, y, 5, 'blue');
}
function pressed(key) {
print(pykConcat(pykConcat('key [', key), ']'));
if (key === 'Enter') {
tw.play_file('snare1.wav');
}
}
function moved(value) {
return tw_external.set_label(status, pykConcat('slider at ', pykFormat(value)));
}
tw_external.on_mouse(c, clicked);
tw_external.on_key(pressed);
tw.slider(0, 10, 5, moved);
tw.slider(1, 3, 2, tw.slider__default__on_change());

lib_tinyweb_sound_graphics1

# A canvas, two circles, two samples and buttons that play them: the
# first tinyweb program.
import tinyweb as tw
tw.web_init(0)
kick = tw.load_sample("kick1.wav")
snare = tw.load_sample("snare1.wav")
canvas = tw.canvas(400, 200)
tw.circle(canvas, 100, 50, 30, "#ff0000") # canvas, x, y, radius, color
tw.circle(canvas, 100, 50, 20) # the color defaults to "#000000"
var presses = 0
def play_kick():
tw.play(kick)
def play_sound():
presses := presses + 1
print("snare, press " ++ string(presses))
tw.play(snare, volume = 0.5)
tw.button("Play kick", on_click = play_kick)
tw.button("Play snare", on_click = play_sound)
tw.button("Does nothing") # on_click is optional
print("built the page")

lib_tinyweb_sound_graphics1.zip

program.js, as Pyking generates it
// Generated from lib_tinyweb_sound_graphics1.pyk by the Pyking compiler. Do not edit.
// Target: node24. Run with: node <this file>
import { print, pykFormat } from './pyk-runtime.js';
// A Pyking list is a JavaScript array with a marker on it: a tuple
// is an array too, and the two print differently. A property rather
// than a class, so that a formatter in another module can read it.
function pykList(items) {
items.pykList = true;
return items;
}
// Pyking's `++` joins two strings or two lists. A list is an array
// here and JavaScript's `+` would stringify one, so which is meant
// is decided by looking -- this backend infers no types.
function pykConcat(a, b) {
return Array.isArray(a) ? pykList([...a, ...b]) : a + b;
}
import * as tw from './tinyweb.js';
import * as tw_external from './tinyweb_external.js';
tw_external.web_init(0);
const kick = tw_external.load_sample('kick1.wav');
const snare = tw_external.load_sample('snare1.wav');
const canvas = tw_external.canvas(400, 200);
tw.circle(canvas, 100, 50, 30, '#ff0000');
tw.circle(canvas, 100, 50, 20, tw.circle__default__color());
let presses = 0;
function play_kick() {
return tw.play(kick, tw.play__default__at(), tw.play__default__volume(), tw.play__default__rate());
}
function play_sound() {
presses = presses + 1;
print(pykConcat('snare, press ', pykFormat(presses)));
return tw.play(snare, tw.play__default__at(), 0.5, tw.play__default__rate());
}
tw.button('Play kick', play_kick);
tw.button('Play snare', play_sound);
tw.button('Does nothing', tw.button__default__on_click());
print('built the page');

lib_tinyweb_style

# The page's look: a theme, the style of every element of a kind, and
# the style of one element. The .events file presses the button, which
# changes the theme and one label while the page is showing.
import tinyweb as tw
tw.web_init(0)
tw.theme("paper")
tw.theme("no such theme")
tw.page_style(background = "#fdf6e3", color = "#586e75", font = "serif", size = 18, padding = 12, gap = 16)
tw.button_style(background = "#268bd2", color = "white", border = "none", radius = 14, font = "monospace", size = 16, padding = 8)
tw.label_style(background = "lightyellow", color = "#333333", border = "1px solid gold", radius = 4, font = "sans-serif", size = 14, padding = 6)
tw.slider_style(accent = "crimson", width = 240, color = "crimson", font = "monospace", size = 20)
tw.canvas_style(border = "3px solid teal", radius = 10)
title = tw.label("Styled")
tw.set_style(title, background = "navy", color = "white", border = "2px dashed orange", radius = 0, font = "Georgia", size = 28, padding = 10, width = 300)
level = tw.slider(0, 10, 4)
tw.set_colors(level, color = "seagreen")
c = tw.canvas(120, 60)
tw.set_style(c, border = "1px solid black")
def pressed():
tw.theme("retro")
tw.set_colors(title, background = "black")
print("now retro")
ok = tw.button("Retro", on_click = pressed)
tw.set_colors(ok, color = "black", background = "gold")

lib_tinyweb_style.zip

program.js, as Pyking generates it
// Generated from lib_tinyweb_style.pyk by the Pyking compiler. Do not edit.
// Target: node24. Run with: node <this file>
import { print } from './pyk-runtime.js';
import * as tw from './tinyweb.js';
import * as tw_external from './tinyweb_external.js';
tw_external.web_init(0);
tw.theme('paper');
tw.theme('no such theme');
tw.page_style('#fdf6e3', '#586e75', 'serif', 18, 12, 16);
tw.button_style('#268bd2', 'white', 'none', 14, 'monospace', 16, 8);
tw.label_style('lightyellow', '#333333', '1px solid gold', 4, 'sans-serif', 14, 6);
tw.slider_style('crimson', 240, 'crimson', 'monospace', 20);
tw.canvas_style('3px solid teal', 10);
const title = tw_external.label('Styled');
tw.set_style(title, 'navy', 'white', '2px dashed orange', 0, 'Georgia', 28, 10, tw.set_style__default__accent(), 300);
const level = tw.slider(0, 10, 4, tw.slider__default__on_change());
tw.set_colors(level, 'seagreen', tw.set_colors__default__background());
const c = tw_external.canvas(120, 60);
tw.set_style(c, tw.set_style__default__background(), tw.set_style__default__color(), '1px solid black', tw.set_style__default__radius(), tw.set_style__default__font(), tw.set_style__default__size(), tw.set_style__default__padding(), tw.set_style__default__accent(), tw.set_style__default__width());
function pressed() {
tw.theme('retro');
tw.set_colors(title, tw.set_colors__default__color(), 'black');
print('now retro');
}
const ok = tw.button('Retro', pressed);
tw.set_colors(ok, 'black', 'gold');