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`),
},
)
let response3 = await fetch_withRequest(
Request.make2(~input="https://rescript-lang.org/"),
~init={
method: "POST",
headers: HeadersInit.fromDict(
dict{
"Content-Type": "application/x-www-form-urlencoded",
},
),
body: BodyInit.fromString(`secret=foo&response=bar`),
},
)
removeEventListener(Mousedown, MouseEvent.preventDefault, ~options={capture: false})
let registrationResult = await navigator.serviceWorker->ServiceWorkerContainer.register("/sw.js")
let subscription = await registrationResult.pushManager->PushManager.subscribe(
~options={
userVisibleOnly: true,
applicationServerKey: ApplicationServerKey.fromString("MyPublicKey"),
},
)
let pushSubscriptionJSON = subscription->PushSubscription.toJSON
let (auth, p256dh) = switch pushSubscriptionJSON.keys {
| None => ("?", "?")
| Some(keys) => (keys.auth, keys.p256dh)
}
Console.log(`For subscription ${subscription.endpoint}, auth is ${auth} and p256dh is ${p256dh}`)

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

IntersectionObserver__test.res

let observer = IntersectionObserver.make(~callback=(entry, observer) => {
Console.log2(entry, observer)
})
let root = Global.document->Document.querySelector("#root")->Null.getUnsafe
let observer2 = IntersectionObserver.make(
~callback=(entry, observer) => {
Console.log2(entry, observer)
},
~options={
root: root->IntersectionObserverRoot.fromElement,
rootMargin: "10px",
threshold: [0.1],
},
)
switch observer2.root->IntersectionObserverRoot.decode {
| Element(_) => Console.log("Element")
| Document(_) => Console.log("Document")
| Null => Console.log("Null")
}
let rootMargin2 = observer2.rootMargin
let targetElement = Global.document->Document.querySelector("#targetElement")->Null.toOption
switch targetElement {
| Some(e) => {
observer2->IntersectionObserver.observe(e)
observer2->IntersectionObserver.unobserve(e)
}
| _ => Console.log("Target element not found.")
}
let entries2 = observer2->IntersectionObserver.takeRecords
Console.log(entries2->Array.length)
observer2->IntersectionObserver.disconnect

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

Notification__test.res

open WebAPI.NotificationAPI
Notification.requestPermission()
->Promise.thenResolve(notificationPermission => {
switch notificationPermission {
| Granted => Console.log("Permission granted")
| Denied => Console.log("Permission denied")
| Default => Console.log("Permission default")
}
})
->Promise.done

ServiceWorker__test.res

open WebAPI.ServiceWorkerAPI
external self: serviceWorkerGlobalScope = "self"
self->ServiceWorkerGlobalScope.addEventListener(EventAPI.Push, (event: PushAPI.pushEvent) => {
Console.log("received push event")
// Extract data
let (title, body) = switch event.data {
| Some(data) =>
switch data->PushMessageData.json {
| JSON.Object(dict{"title": JSON.String(title), "body": JSON.String(body)}) => (title, body)
| _ => ("???", "???")
}
| None => ("???", "???")
}
// Handle some data sync
event->PushEvent.waitUntil(self->ServiceWorkerGlobalScope.fetch("https://rescript-lang.org"))
// Show notification
self.registration
->ServiceWorkerRegistration.showNotification(
~title,
~options={
body,
icon: "/icon.png",
actions: [{action: "open", title: "Open"}, {action: "close", title: "Close"}],
// For example the id of a new data entry
data: JSON.Number(17.),
},
)
->Promise.done
})
self->ServiceWorkerGlobalScope.addEventListener(EventAPI.NotificationClick, (
event: NotificationAPI.notificationEvent,
) => {
Console.log(`notification clicked: ${event.action}`)
// Close the notification
event.notification->Notification.close
// Open a new window if that is relevant
event.notification.data
->Option.flatMap(data => {
switch data {
| JSON.Number(id) => Some(Float.toString(id))
| _ => None
}
})
->Option.forEach(id => {
self.clients
->Clients.openWindow(`https://mywebsite.com/mydata/${id}`)
->Promise.done
})
})

Storage__test.res

open WebAPI.Global
open WebAPI.Storage
for i in 0 to localStorage.length - 1 {
localStorage->key(i)->Null.getOr("nothing")->Console.log
}
let item1 = localStorage->getItem("foo")->Null.getOr("nothing")
localStorage->setItem(~key="bar", ~value="...")
localStorage->removeItem("bar")
localStorage->clear