reasonml-community / bs-webapi-incubator Goto Github PK
View Code? Open in Web Editor NEWBuckleScript bindings to the DOM and other Web APIs
License: MIT License
BuckleScript bindings to the DOM and other Web APIs
License: MIT License
I've created the bindings for URL and URLSearchParams at https://github.com/bryanthomaschen/bs-webapi-incubator/blob/feature/implement-url/src/file/UrlRe.re
Would this be an appropriate addition to bs-webapi
?
^ current behaviour results in undefined is not an Object
๐
How to set width and height to canvas ?
I must write declaration like follow code ?
[@bs.set] external setWidth : (Dom.element, int) => unit = "width";
[@bs.set] external setHeight : (Dom.element, int) => unit = "height";
and then
setWidth(canvas, ElementRe.clientWidth(DocumentRe.documentElement(document)));
setHeight(canvas, ElementRe.clientHeight(DocumentRe.documentElement(document)));
or has any solution ?
Per MDN, requestAnimationFrame
should return a long
, which can then be passed to its sister function cancelAnimationFrame
to abandon the animation request before it is rendered. However, the Webapi module currently only exports requestAnimationFrame : ((float) => unit) => unit
.
When using the fetchWithInit example, I get an error from the browser: TypeError: Failed to execute 'fetch' on 'Window': Invalid referrer policy
According to the spec, referrerPolicy should never be undefined.
Adding None as the referrerPolicy works:
Fetch.RequestInit.make method_::Post referrerPolicy::None ();
Hi! Why does it have docType
name and not a doctype
? To me it looks it should be doctype
https://www.w3schools.com/jsref/prop_document_doctype.asp
https://developer.mozilla.org/en-US/docs/Web/API/Document/doctype
I'm trying out Reason and BuckleScript and trying to convert a simple canvas demo as a learning vehicle. There are a couple of other bs canvas demos that have been published, and it involves little interaction with the DOM. So far so good.
But getting the mouse coordinates and satisfying the type system was surprisingly confusing with these bindings. This is what I tried:
let display = Document.getElementById "display" document;
let canvas = switch display {
| Some display => display
| None => raise (Failure "Could not find #display DOM Node")
};
let ctx = ReasonJs.CanvasElement.getContext canvas "2d";
let onMouseMove e => {
state.mouse.x = MouseEvent.clientX e;
state.mouse.y = MouseEvent.clientY e;
};
Element.addEventListener "mousemove" onMouseMove canvas;
but this results in a type error:
Error: This expression has type ReasonJs.Dom.MouseEvent.t => unit
but an expression was expected of type Dom.event => unit
Type
ReasonJs.Dom.MouseEvent.t =
Dom.event_like (Dom._uiEvent (Dom._mouseEvent Dom._baseClass))
is not compatible with type Dom.event = Dom.event_like Dom._baseClass
Type Dom._uiEvent (Dom._mouseEvent Dom._baseClass)
is not compatible with type Dom._baseClass
@glennsl helped on Discord and suggested adding a type conversion function:
external eventToMouseEvent : Dom.event => MouseEvent.t = "%identity";
which works great! But:
Reason beginner here, so apologies in advance if this is not a bug.
If I open Webapi.Dom
, it shadows the None
constructor, and I cannot have optional variables in the same file.
It currently shadows None with Webapi.Dom.eventPhase
.
in the event of the user increasing / decreasing the level of zoom in their browser, Dom.Window.scrollY
, Dom.Element.offsetTop
, etc. will return return floats rather than integers. Current type signatures make it difficult to account for this in a sane manner.
Chrome 67.0.3396.99 / Firefox 60.0.1 - OS X 10.13.3
Due to OCaml's rules for which identifiers can be lower case and upper case, the current convention is PascalCase/camelCase, e.g. "Html", "Json", "dom" etc.
Should it be "DOM"/"dom", "JSON"/"json" instead? How would that work with module fiilenames? Should it be e.g. "jsonRe.re", it would then have to be used internally as "JsonRe" and be exported as "module JSON = JsonRe".
FocusEvent relatedTarget is defined to always return something but there are times when it may be null.
offsetParent
can return null (a common situation is recursively walking up the DOM until offsetParent
returns null
- i.e. the body
element has been reached).
However, the binding of offsetParent
does not return an option - so this case is not detectable and can cause an exception.
The following fixed it for me:
[@bs.get] [@bs.return nullable] external offsetParent : HtmlElementRe.t => option(Dom.element) = "";
Thanks!
Given that fast piping is becoming the standard in Reason are there plans to make a t
-first version of the library that doesn't use piping?
As per https://developer.mozilla.org/en-US/docs/Web/API/Body, .arrayBuffer()
, .blob()
, .formData()
, .json()
, and .text()
all return Promise
s, as the body has not been consumed before the invocation of one of those methods.
Hi, similarly to #49, several FFI functions returning a 'a option
miss a [@@bs.return (undifined|null)_to_opt]
, which breaks any match
afterwards (getting undefined
through Some
).
I found this when trying to use:
But it seems that a bunch of other functions are suffering from the same issue, like
orbs-webapi-incubator/src/dom/traversal/NodeIteratorRe.re
Lines 9 to 10 in f0db37b
_MyConstant
, _MY_CONSTANT
or something else entirely?
I need to use websocket for the project I am working on, and it is missing from here.
Here is what I am using so far:
module MessageEvent = {
type t;
external data : t => ArrayBuffer.t = "" [@@bs.get];
};
module WebSocket = {
type t;
external create_ws : string => t = "WebSocket" [@@bs.new];
external setBinaryType : t => string => unit = "binaryType" [@@bs.set];
external onMsg : t => (MessageEvent.t => unit) => unit = "onmessage" [@@bs.set];
external onOpen : t => (unit => unit) => unit = "onopen" [@@bs.set];
external send : Uint8Array.t => unit = "" [@@bs.send.pipe : t];
external onError : t => (unit => unit) => unit = "onerror" [@@bs.set];
external onClose : t => (unit => unit) => unit = "onclose" [@@bs.set];
let make url => {
let ws = create_ws url;
setBinaryType ws "arraybuffer";
ws
};
let onMsg ws cb => onMsg ws (fun ev => MessageEvent.data ev |> Uint8Array.fromBuffer |> cb);
};
This is only designed for a binary use case / mine, its also incredibly incomplete.
I will overtime improve it as necessary for my use case, but otherwise, I am asking what the plan is for this api. I can definitely help write the types for it.
Although I know it isn't in the browser, making a Sink / Stream api from this would make it more pleasant to use. Perhaps taking something from most.js (which I know someone in the discord is making type definitions for).
Currently I'm using this:
[@bs.get] external getEventDetail: Dom.event => Js.t({..}) = "detail";
Perhaps this should be in bs-webapi?
https://github.com/BuckleTypes/bs-webapi-incubator/blob/master/src/dom/nodes/documentRe.re#L6
I hit this when my test HTML file didn't have a doctype defined. It might be reasonable to require a doctype declaration, but the error message was not helpful until you looked at the code. Something about "name"
of undefined
.
createText
is still in the latest when installed from npm, meaning I can't create text nodes :(.
The commit that handled it was 1d8a298
The version just needs to be bumped and published to npm. Thanks :)
This doesn't typecheck:
Webapi.Dom.EventTarget.dispatchEvent(
Webapi.Dom.CustomEvent.makeWithOptions(
"my-event",
{
"detail": {
"test": "test",
},
},
),
element
)
Errors:
Webapi.Dom.CustomEvent.makeWithOptions(...
This has type:
Webapi.Dom.CustomEvent.t (defined as Dom.event_like(Dom._customEvent))
But somewhere wanted:
Dom.event (defined as Dom.event_like(Dom._baseClass))
The incompatible parts:
Dom._customEvent
vs
Dom._baseClass
If I switch from CustomEvent
to Event
it works and dispatches but the details
are not included in the result.
Currently the type of get
in URLSearchParamsRe.re is:
[@bs.send.pipe : t] external get: string => option(string) = "";
As you can see in the documentation here
The type I think should be:
[@bs.send.pipe : t] external get: string => Js.Nullable.t(string) = "";
Quite happy to make a PR if I am correct about this :)
I noticed that all files in such package ends with Re
,
maybe we can add a style field in bsconfig, like
{ namespace : "re", format: "suffix"}
So that the build system will generate a map file for only exported units
re.ml
module CssDeclaration = CssDeclarationRe
So that ender users could call Re.CssDeclaration
with auto-completion.
Two issues:
:; node_modules/.bin/bsb -make-world
Regenerating build spec : File not found
Fatal error: exception Sys_error("tests/fetch: No such file or directory")
Error happened when running command .../reason-js/node_modules/bs-platform/bin/bsb.exe with args [ '-make-world' ]
It seems like it's looking for the directory structure in src/
to be mirrored in tests/
.
:; cp -a src/fetch/ tests/fetch/
:; node_modules/.bin/bsb -make-world
Regenerating build spec : File not found
Fatal error: exception Sys_error("tests/gl: No such file or directory")
Error happened when running command /Users/solidsnack/Downloads/reason-js/node_modules/bs-platform/bin/bsb.exe with args [ '-make-world' ]
How does the .re
code get translated to .ml
?
Wouldn't it make senes to activate namespaces in this project? I see that the Bs_webapi module was deprecated in favour of Webapi but I still think it makes sense to activate namespaces here.
We're using this for some shimmed APIs in React Native but we needed to vendor this package to activate namespaces because both projects have a file called ImageRe.re
Instead of doubling the effort in re-creating the DOM bindings it might be simpler to transform the AST of TypeScript definitions into Reason bindings. The added benefit would be that such a transformer would be universal - given the huge number of good quality typings available for TypeScript, Reason could quickly become a hugely popular alternative to it, especially given the BuckleScript 1.0 release and the fantastic benefits it offers over TS.
Thoughts?
E.g.
external navigator: navigator = "" [@@bs.val]
external userAgent: string = "" [@@bs.val] [@@bs.scope "navigator"]
I'm curious about the choice of functions to get event properties instead of passing recordings to event handlers. I come from a JS background and find calling functions to access fields on events quite awkward.
Hi,
I'm writing a simple 2d canvas game, and have been building up a bunch of bindings for the CanvasRenderingContext2D API. Would it be helpful to add them in a pull request here? If so, a couple of questions:
There's an existing ReasonJs.CanvasElement.getContext
function that takes a string, and returns a context. However the existing context API here is for WebGL, not the 2d API. So I'd propose changing this to getWebGLContext
, and creating a new get2dContext
function. It looks like [@bs.as]
will work to pass the appropriate string parameter in to js's getContext
ints or floats for canvas methods? I've been using floats myself but I'm wondering if there's a case for integer arguments
The version was bumped but it wasn't published
Pipe form would enable usage like:
let el = document
|> Document.createElement "div"
|> Element.setInnerText "</>"
|> Element.setClassName "reason_tools_button"
|> setOnClick swap
|> Body.appendChild;
And it would be more consistent with "regular" functions. But without BS support, it would be a bit of work. See also rescript-lang/rescript-compiler#1188
So their presence can actually be checked for before they're used.
Hi,
I've stumbled upon this error when trying to integrate bucklescript into our JS for a project. We don't currently have the possibility to change the build system so I'm stuck with brunch.
Building with bsb
isn't really an issue, but on page load when trying to use bs-webapi
I get the following error:
Cannot find module 'bs-platform/lib/js/curry.js' from 'bs-webapi/src/dom/nodes/ElementRe.js'
This, to me, seemed strictly like a brunch issue until I tried using another library to see if it actually was a general issue. bs-fetch
is usable even though it also depends on bs-platform
. I'm not sure if this is just because of dead code elimination and it ends up not using any modules from bs-platform
, though.
bs-platform
is at v2.2.3
bs-webapi
is at v0.8.3
Shouldn't History.state
be parameterized?
Currently, to fetch and log out an API response requires something like the following:
let p = ReasonJs.fetch "https://jsonplaceholder.typicode.com/posts/1";
ReasonJs.Promise.thenDo (ReasonJs.Promise.thenDo p ReasonJs.Response.text) Js.log;
This is rather unwieldy, but can be made somewhat cleaner by aliasing some of the functions:
let fetch = ReasonJs.fetch;
let then_ = ReasonJs.Promise.thenDo;
let p = ReasonJs.fetch "https://jsonplaceholder.typicode.com/posts/1";
then_ (then_ p ReasonJs.Response.text) Js.log;
By flipping the arguments, I am able to get an even nicer syntax:
let fetch = ReasonJs.fetch;
let then_ a b => ReasonJs.Promise.thenDo b a;
let p = fetch "https://jsonplaceholder.typicode.com/posts/1";
p |> then_ ReasonJs.Response.text |> then_ Js.log;
Perhaps the API can be reshaped to make usage more idiomatic.
https://bucklescript.github.io/bucklescript/api/Dom.html#TYPEnodeFilter
It is typed as record.
So it compiles to [() => 0]
instead of { acceptNode: () => 0 }
;
BS issue rescript-lang/rescript-compiler#2764
Repository has no LICENSE. We should add one. MIT? BSD? LGPL? WTF?
I've seen quite a few user land canvas bindings now, and upon perusing webapi's, I feel they're ready to be upstreamed? Tell me if I'm mistaken. Otherwise, great stuff once again, @glennsl @bloodyowl =D
Also, anyone dogfooding webGLRe.re?
As it is now you create an element by doing document |> Document.createElement "img"
which gives you an element
that you'll then have to cast down to an htmlImageElement
to be able to use it with functions specific to that type of element. Even though you know damn well that you've just created an htmlImageElement
the type system does not. So how do we force-feed it?
Add element-specific create methods, e.g. HtmlImageElement.create
. Can we then hard-code this to document.createElement
or are elements bound to a specific document instance?
Could we use GADTs somehow? e.g.
type elementType =
| ...
| HtmlImageElement : <put magic here> -> htmlImageElement
let imageElement = document |> Document.createElement HtmlImageElement
The issue is similar with getElementsByTagName
and perhaps other functions.
Might have to write bindings for a test framework first. Or use/extend bs-mocha.
When doing:
let url = Webapi.Url.make("http://www.example.com");
Js.log(url->Webapi.Url.hostname);
The generated javascript is:
console.log(url.hostname());
This causes an error as the property is not a function.
Should change [@bs.send.pipe : t]
to [@bs.get]
E.g.
external availHeight: int = "" [@@bs.val] [@@bs.scope "window", "screen"]
external availWidth: int = "" [@@bs.val] [@@bs.scope "window", "screen"]
Or should enums have an Unknown variant that encodes to some nonsense that will break something later (current approach, mostly)?
Currently cloneNode
has the type signature:
'a Dom.node_like -> Dom._baseClass Dom.node_like
But with this signature, if I clone an element, it becomes a node, so I can't appendChild etc.
As I understand it we could either use a different return type for each module cloneNode appears in, or make use of the generic inheritance thing and change it to:
'a Dom.node_like -> 'a Dom.node_like
Given that the spec calls this DocumentElement
and that HTMLElement
is something else, this is very confusing. Don't you think renaming the module DocumentElement
would help make it easier?
cc @chenglou
Other than potentially forgetting to check in the rendered artifacts and not having it be caught by CI, do we really lose anything by not having a test script and the explicit "expected" snapshots, compared to just using checked in artifacts as snapshots and the review process to verify them? It might even be a win, since there would be more eyes on it.
I'm trying to do POST requests with the fetch API, but I think currently it's not supported (according to the signature, it only takes a string, nothing more).
external fetch : string => CoreRe.promise response = "" [@@bs.val];
Are there plans to do a fetchPost version?
Running npm install bs-webapi-incubator
as in the README will fail.
The package is not present in the npm repository.
Shouldnt it return an Element ?
The HTMLElement.offsetParent read-only property returns a reference to the object which is the closest (nearest in the containment hierarchy) positioned containing element.
from: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.