npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

bs-preact

v0.3.0

Published

> An opinionated Preact v10 binding for (OCaml | ReasonML) + BuckleScript with > compile time enforcement of the ["Rules of Hooks"](https://reactjs.org/docs/hooks-rules.html).

Downloads

3

Readme

bs-preact

An opinionated Preact v10 binding for (OCaml | ReasonML) + BuckleScript with compile time enforcement of the "Rules of Hooks".

Live Demos | Starter

Overview

The "Hello, World!" of bs-preact looks like this:

module P = Preact

let main = P.h1 [ P.id "hello" ] [ P.string "Hello, world!" ]

let () =
  match P.find "main" with
  | Some element -> P.render main element
  | None -> Js.Console.error "<main> not found!"

The code above renders <h1 id="hello">Hello, World!</h1> into the first element on the page matching the selector main.

Note: If you want to use ReasonML syntax instead of OCaml, check out the last section for the equivalent ReasonML code.


Components are defined using a syntax extension [@preact.component "DisplayNameOfComponent"] applied to funs of one argument:

module P = Preact

module Counter = struct
  let make =
   fun [@preact.component "Counter"] initial ->
    P.div [] [P.int initial]
end

Components are initialized using simple function calls:

let main = Counter.make 0

Hooks are invoked using a [@hook] annotation on let expressions:

let make =
 fun [@preact.component "Counter"] initial ->
  let[@hook] count, setCount = P.useState initial in
  P.div [] [P.int initial]

Here's a full example of a Counter with two buttons, one to increment and one to decrement the value (full source):

module Counter = struct
  let make =
   fun [@preact.component "Counter"] initial ->
    let[@hook] count, setCount = P.useState initial in
    P.div
      []
      [ P.button [ P.onClick (fun _ -> setCount (count - 1)) ] [ P.string "-" ]
      ; P.string " "
      ; P.int count
      ; P.string " "
      ; P.button [ P.onClick (fun _ -> setCount (count + 1)) ] [ P.string "+" ]
      ]
end

Custom hooks are created using a syntax extension [@preact.hook] applied to funs of one argument. Here's a custom hook that wraps useReducer, invoking any action dispatched twice instead of once.

let useDoubleReducer =
 fun [@preact.hook] (reducer, initialValue) ->
  let[@hook] state, dispatch = P.useReducer reducer initialValue in
  let dispatchTwice action =
    let () = dispatch action in
    dispatch action
  in
  state, dispatchTwice

These custom hooks are called in the same manner as the built-in hooks -- using let[@hook]:

let make =
 fun [@preact.component "CustomHooks"] () ->
  let reducer state action = state + action in
  let[@hook] state, dispatch = useDoubleReducer (reducer, 0) in
  P.button [ P.onClick (fun _ -> dispatch 2) ] [ P.int state ]

Full example here.

Quick Start

$ git clone https://github.com/utkarshkukreti/bs-preact-starter
$ cd bs-preact-starter
$ yarn install
$ yarn build

This will build /src/Main.ml into the /dist/ directory which you can run by opening /index.html in your browser.

Feel free to copy code from examples into src/Main.ml and recompile.

How are the Rules of Hooks enforced at compile time?

bs-preact uses an OCaml syntax extension to enforce them.

This requires annotating components with fun [@preact.component], custom hooks with fun [@preact.hook], and every use of a hook with let[@hook].

For [@preact.hook], the syntax extension appends a dummy argument to the function, the value of which must be of type Preact.undefined (represented as plain undefined in JS).

For both [@preact.hook] and [@preact.component], the syntax extension traverses the top level let expressions and rewrites let[@hook] expressions, appending the undefined value to the function call on the right.

If you call a hook without let[@hook], you will get a type check error due to a missing argument.

After all this is done, the syntax extension traverses the whole program and checks whether any of these annotations were not processed and throws an error if it finds any because it means the annotation was incorrectly used.

For more examples, check out the files under /examples. A live demo of all the examples is available here.

ReasonML

Here's the Hello World example in ReasonML:

module P = Preact;

let main = P.h1([P.id("hello")], [P.string("Hello, world!")]);

switch (P.find("main")) {
| Some(element) => P.render(main, element)
| None => Js.Console.error("<main> not found!")
};

Here's an example of ReasonML code which uses all the three annotations that this library uses:

module P = Preact;

let useDoubleReducer =
  [@preact.hook]
  (
    ((reducer, initialValue)) => {
      let [@hook] (state, dispatch) = P.useReducer(reducer, initialValue);
      let dispatchTwice = action => {
        dispatch(action);
        dispatch(action);
      };
      (state, dispatchTwice);
    }
  );

let make =
  [@preact.component "CustomHooks"]
  (
    () => {
      let reducer = (state, action) => state + action;
      let [@hook] (state, dispatch) = useDoubleReducer((reducer, 0));
      P.button([P.onClick(_ => dispatch(2))], [P.int(state)]);
    }
  );

let main = make();
switch (P.find("main")) {
| Some(element) => P.render(main, element)
| None => Js.Console.error("<main> not found!")
};

For more guidance on how to translate OCaml code into ReasonML, try pasting the OCaml code in the Try ReasonML page or read this guide.

License

MIT