Skip to content

Instantly share code, notes, and snippets.

@matthiaskern
Forked from girvo/utils.re
Created January 17, 2018 13:51
Show Gist options
  • Save matthiaskern/9964a30cc1459e3d12c5a511e056effe to your computer and use it in GitHub Desktop.
Save matthiaskern/9964a30cc1459e3d12c5a511e056effe to your computer and use it in GitHub Desktop.
A small utility module I use with my ReasonML projects
module Result = {
type result('a, 'b) =
| Ok('a)
| Error('b);
let isOk = (result_) =>
switch result_ {
| Ok(_) => true
| Error(_) => false
};
let isError = (result_) =>
switch result_ {
| Ok(_) => false
| Error(_) => true
};
};
module Dom = {
open ReasonReact;
open ReactDOMRe;
open ReactEventRe;
/**
* Unsafe value access for a FormEvent
*/
let internal_getValue = (event) => domElementToObj(Form.target(event))##value;
/**
* Safe access for a FormEvent value
*/
let getValue = (event) =>
internal_getValue(event)
|> Js.Null.to_opt;
/**
* Tiny wrapper so one can do:
*
* <div> (se(someStr)) </div>
*/
let se = stringToElement;
/**
* Takes an optional and a react element to wrap it in
*/
let renderOptional = (opt: option(string), wrapper: reactElement) =>
switch opt {
| Some(opt_) => cloneElement(wrapper, [|se(opt_)|])
| None => nullElement
};
/**
* Internal bindings to DOM `getAttribute` function
*/
[@bs.send] external internal_getAttribute : (Js.t('a), string) => Js.null(string) =
"getAttribute";
/**
* Accessing an attribute on a DOM element, wrapped in an Optional.
* The example below uses the "open" statements in this module for clarity.
*
* let onclick = (ev) => {
* Mouse.preventDefault(ev);
* let maybeHref =
* Mouse.target(ev)
* |> domElementToObj
* |> getAttribute("href");
*
* switch (maybeHref) {
* | Some(href) => DirectorRe.setRoute(router, href)
* | None => ()
* }
* };
*/
let getAttribute = (name, node) => Js.Null.to_opt(internal_getAttribute(node, name));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment