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 WebAPIopen WebAPI.Global
let button = document->Document.querySelector("button")->Null.toOptionlet 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")}
import * as Int from "rescript/lib/es6/Int.js";import * as Primitive_option from "rescript/lib/es6/Primitive_option.js";
let button = document.querySelector("button");
let h2 = document.querySelector("h2");
if (button !== null && h2 !== null) { button.addEventListener("click", e => { console.log("Button clicked, " + e.button.toString()); let text = h2.textContent; if (text === null) { h2.textContent = "1"; return; } let number = Int.fromString(text, undefined); if (number !== undefined) { h2.textContent = (number + 1 | 0).toString(); } else { h2.textContent = "1"; } });} else { console.log("Stuff not found");}
let button$1 = button === null ? undefined : Primitive_option.some(button);
let h2$1 = h2 === null ? undefined : Primitive_option.some(h2);
export { button$1 as button, h2$1 as h2,}/* button Not a pure module */
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.toJSONlet (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}`)
let response = await fetch("https://rescript-lang.org/");
let response2 = await fetch("https://rescript-lang.org/", { headers: { "Content-Type": "application/json", Authorization: "Bearer token" }, body: "secret=foo&response=bar"});
let response3 = await fetch(new Request("https://rescript-lang.org/"), { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "secret=foo&response=bar"});
removeEventListener("mousedown", prim => { prim.preventDefault();}, { capture: false});
let registrationResult = await navigator.serviceWorker.register("/sw.js");
let subscription = await registrationResult.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: "MyPublicKey"});
let pushSubscriptionJSON = subscription.toJSON();
let keys = pushSubscriptionJSON.keys;
let match = keys !== undefined ? [ keys.auth, keys.p256dh ] : [ "?", "?" ];
let p256dh = match[1];
let auth = match[0];
console.log("For subscription " + subscription.endpoint + ", auth is " + auth + " and p256dh is " + p256dh);
export { response, response2, response3, registrationResult, subscription, pushSubscriptionJSON, auth, p256dh,}
HTMLCanvasElement__test.res
open WebAPI.Global
let myCanvas: DOMAPI.htmlCanvasElement = document->Document.getElementById("myCanvas")->Prelude.unsafeConversationlet 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.Topctx->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")}
import * as FillStyle$WebAPI from "../../src/DOMAPI/FillStyle.js";
let myCanvas = document.getElementById("myCanvas");
let ctx = myCanvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 200, 200);
ctx.fillStyle = "black";
ctx.font = "2px Tahoma";
ctx.textBaseline = "top";
ctx.fillText("MY TEXT", 60, 60);
let color = FillStyle$WebAPI.decode(ctx.fillStyle);
switch (color.TAG) { case "String" : console.log("Color: " + color._0); break; case "CanvasGradient" : console.log("CanvasGradient"); break; case "CanvasPattern" : console.log("CanvasPattern"); break;}
export { myCanvas, ctx,}/* myCanvas Not a pure module */
HTMLElement__test.res
open WebAPIopen WebAPI.Global
document->Document.querySelector("form")->Null.toOption->Option.forEach(form => { form->Element.scrollIntoView_withOptions({behavior: DOMAPI.Smooth})})
import * as Option from "rescript/lib/es6/Option.js";import * as Primitive_option from "rescript/lib/es6/Primitive_option.js";
Option.forEach(Primitive_option.fromNull(document.querySelector("form")), form => { form.scrollIntoView({ behavior: "smooth" });});
/* Not a pure module */
HTMLInputElement__test.res
open Global
let input: DOMAPI.htmlInputElement = document->Document.createElement(~localName="input")->Prelude.unsafeConversationlet value = input.value
let input = document.createElement("input");
let value = input.value;
export { input, value,}/* input Not a pure module */
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.toOptionswitch targetElement {| Some(e) => { observer2->IntersectionObserver.observe(e) observer2->IntersectionObserver.unobserve(e) }| _ => Console.log("Target element not found.")}
let entries2 = observer2->IntersectionObserver.takeRecordsConsole.log(entries2->Array.length)
observer2->IntersectionObserver.disconnect
import * as Primitive_option from "rescript/lib/es6/Primitive_option.js";import * as IntersectionObserverRoot$WebAPI from "../../src/IntersectionObserverAPI/IntersectionObserverRoot.js";
let observer = new IntersectionObserver((entry, observer) => { console.log(entry, observer);});
let root = document.querySelector("#root");
let observer2 = new IntersectionObserver((entry, observer) => { console.log(entry, observer);}, { root: Primitive_option.some(root), rootMargin: "10px", threshold: [0.1]});
let match = IntersectionObserverRoot$WebAPI.decode(observer2.root);
if (typeof match !== "object") { console.log("Null");} else if (match.TAG === "Element") { console.log("Element");} else { console.log("Document");}
let rootMargin2 = observer2.rootMargin;
let targetElement = document.querySelector("#targetElement");
if (targetElement !== null) { observer2.observe(targetElement); observer2.unobserve(targetElement);} else { console.log("Target element not found.");}
let entries2 = observer2.takeRecords();
console.log(entries2.length);
observer2.disconnect();
let targetElement$1 = targetElement === null ? undefined : Primitive_option.some(targetElement);
export { observer, root, observer2, rootMargin2, targetElement$1 as targetElement, entries2,}/* observer Not a pure module */
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
let location = window.location;
let href = location.href;
location.reload();
let a = 0;
export { location, href, a,}/* location Not a pure module */
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
Notification.requestPermission().then(notificationPermission => { switch (notificationPermission) { case "default" : console.log("Permission default"); return; case "denied" : console.log("Permission denied"); return; case "granted" : console.log("Permission granted"); return; }});
/* Not a pure module */
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 })})
import * as Option from "rescript/lib/es6/Option.js";import * as Primitive_option from "rescript/lib/es6/Primitive_option.js";
self.addEventListener("push", event => { console.log("received push event"); let data = event.data; let match; if (data !== undefined) { let match$1 = Primitive_option.valFromOption(data).json(); if (typeof match$1 === "object" && !Array.isArray(match$1)) { let title = match$1.title; if (typeof title === "string") { let body = match$1.body; match = typeof body === "string" ? [ title, body ] : [ "???", "???" ]; } else { match = [ "???", "???" ]; } } else { match = [ "???", "???" ]; } } else { match = [ "???", "???" ]; } event.waitUntil(self.fetch("https://rescript-lang.org")); self.registration.showNotification(match[0], { body: match[1], icon: "/icon.png", data: 17, actions: [ { action: "open", title: "Open" }, { action: "close", title: "Close" } ] });});
self.addEventListener("notificationclick", event => { console.log("notification clicked: " + event.action); event.notification.close(); Option.forEach(Option.flatMap(event.notification.data, data => { if (typeof data === "number") { return data.toString(); }
}), id => { self.clients.open("https://mywebsite.com/mydata/" + id); });});
/* Not a pure module */
Storage__test.res
open WebAPI.Globalopen 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
import * as Null from "rescript/lib/es6/Null.js";
for (let i = 0, i_finish = localStorage.length; i < i_finish; ++i) { console.log(Null.getOr(localStorage.key(i), "nothing"));}
let item1 = Null.getOr(localStorage.getItem("foo"), "nothing");
localStorage.setItem("bar", "...");
localStorage.removeItem("bar");
localStorage.clear();
export { item1,}/* Not a pure module */