Skip to content

Examples

The best example of usage of these bindings are the tests.
These typically contain tweaks made to the generated bindings to make them more ergonomic.

AddEventListener__test.res

open WebAPI
open WebAPI.Global
let button = document->Document.querySelector("button")->Null.toOption
let h2 = document->Document.querySelector("h2")->Null.toOption
switch (button, h2) {
| (Some(button), Some(h2)) =>
button->Element.addEventListener(EventAPI.Click, (e: UIEventsAPI.mouseEvent) => {
Console.log(`Button clicked, ${Int.toString(e.button)}`)
switch h2.textContent {
| Null => h2.textContent = Value("1")
| Value(text) =>
switch Int.fromString(text) {
| None => h2.textContent = Value("1")
| Some(number) => h2.textContent = Value(Int.toString(number + 1))
}
}
})
| _ => Console.log("Stuff not found")
}

Global__test.res

open WebAPI.Global
let response = await fetch("https://rescript-lang.org/")
let response2 = await fetch(
"https://rescript-lang.org/",
~init={
headers: HeadersInit.fromDict(
dict{
"Content-Type": "application/json",
"Authorization": "Bearer token",
},
),
body: BodyInit.fromString(`secret=foo&response=bar`),
},
)

HTMLCanvasElement__test.res

open WebAPI.Global
let myCanvas: DOMAPI.htmlCanvasElement =
document->Document.getElementById("myCanvas")->Prelude.unsafeConversation
let ctx = myCanvas->HTMLCanvasElement.getContext_2D
ctx.fillStyle = FillStyle.fromString("red")
ctx->CanvasRenderingContext2D.fillRect(~x=50., ~y=50., ~w=200., ~h=200.)
ctx.fillStyle = FillStyle.fromString("black")
ctx.font = "2px Tahoma"
ctx.textBaseline = CanvasAPI.Top
ctx->CanvasRenderingContext2D.fillText(~text="MY TEXT", ~x=60., ~y=60.)
switch ctx.fillStyle->FillStyle.decode {
| FillStyle.String(color) => Console.log(`Color: ${color}`)
| FillStyle.CanvasGradient(_) => Console.log("CanvasGradient")
| FillStyle.CanvasPattern(_) => Console.log("CanvasPattern")
}

HTMLElement__test.res

open WebAPI
open WebAPI.Global
document
->Document.querySelector("form")
->Null.toOption
->Option.forEach(form => {
form->Element.scrollIntoView_withOptions({behavior: DOMAPI.Smooth})
})

HTMLInputElement__test.res

open Global
let input: DOMAPI.htmlInputElement =
document->Document.createElement(~localName="input")->Prelude.unsafeConversation
let value = input.value

Location__test.res

open Global
// Note that this only works when you added the `-open Global` bsc flag.
let location = window.location
// Access properties using `.`
let href = location.href
// Invoke methods using the `->TypeModule`
location->Location.reload
let a = 0