diff options
author | Eileen Noonan <enoonan@arcstone.com> | 2024-03-22 15:26:14 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-03-22 19:26:14 +0000 |
commit | 1d8d13d766b6467188cbded28d103ffb13421c77 (patch) | |
tree | ebfb5ed7e62463b6392a6f133ae675b65e97ac0c | |
parent | e85bc4729a15d9af5af5345151178afe849036ba (diff) | |
download | lustre-1d8d13d766b6467188cbded28d103ffb13421c77.tar.gz lustre-1d8d13d766b6467188cbded28d103ffb13421c77.zip |
🔀 Write a readme for example 04-custom-event-handlers. (#72)
* readme for example 04
* Update README.md
tweaks
-rw-r--r-- | examples/03-controlled-inputs/README.md | 2 | ||||
-rw-r--r-- | examples/04-custom-event-handlers/README.md | 72 | ||||
-rw-r--r-- | examples/04-custom-event-handlers/gleam.toml | 2 | ||||
-rw-r--r-- | examples/04-custom-event-handlers/header.png | bin | 0 -> 99692 bytes | |||
-rw-r--r-- | examples/04-custom-event-handlers/manifest.toml | 10 | ||||
-rw-r--r-- | examples/04-custom-event-handlers/src/app.gleam | 13 |
6 files changed, 80 insertions, 19 deletions
diff --git a/examples/03-controlled-inputs/README.md b/examples/03-controlled-inputs/README.md index 4696c6d..fcbbb1f 100644 --- a/examples/03-controlled-inputs/README.md +++ b/examples/03-controlled-inputs/README.md @@ -31,7 +31,7 @@ ui.input([ Central to Lustre's architecture is the idea that your model is the single source of truth for your application's UI. This opens up the door to things like serialising -progam state to load in the future, time-travel debugging, and rehydrating your +program state to load in the future, time-travel debugging, and rehydrating your app's state from a server. It also gives you tighter control of when and how to update your UI in response diff --git a/examples/04-custom-event-handlers/README.md b/examples/04-custom-event-handlers/README.md index 2c7553d..10c6296 100644 --- a/examples/04-custom-event-handlers/README.md +++ b/examples/04-custom-event-handlers/README.md @@ -1,13 +1,77 @@ + + # 04 Custom Event Handlers > **Note**: this guide is written for Lustre v4. The latest stable release of > Lustre is v3. To follow along with this guide, you need to _manually_ edit your > `gleam.toml` and change the required version of lustre to `"4.0.0-rc.2"`. -We haven't quite got round to documenting this example yet. If you know a little -bit about Lustre or Elm and want to help out, we'd love to have your help! Please -[open an issue](https://github.com/lustre-labs/lustre/issues/new) if you have any -ideas or reach out to @hayleigh.dev on the [Gleam discord](https://discord.gg/Fm8Pwmy). +While Lustre's built-in event handlers can cover most of your basic needs, in practice you will often need to provide more advanced functionality. For this, we can reach for the `event.on("eventname", handler)` function to generate attributes that can provide custom event handling. + +But first, let's take a look under the hood to see what event handlers actually _do_. + +## Decoding Dynamic Data + +Lustre is a type-safe framework, but the DOM allows HTML elements to generate events containing values of any arbitrary type and structure. In Gleam, such data is referred to as _dynamic_, and is handled by the `gleam/dynamic` library. `gleam/dynamic` is used for decoding everything from unpredictable JSON input to Lustre's DOM events. + +If you peek at [the gleam\dynamic documentation](https://hexdocs.pm/gleam_stdlib/0.17.1/gleam/dynamic/#module-types), you'll quickly see it exports four types: + +```gleam + pub external type Dynamic + // data for which we don't know the type + + pub type DecodeError { ... } + // the error returned when unexpected data is encountered + + pub type DecodeErrors = List(DecodeError) + + pub type Decoder(t) = fn(Dynamic) -> Result(t, DecodeErrors) + // any function that accepts dynamic data and returns a Result(t, DecodeErrors) +``` + +In Lustre, all DOM event values are converted to `Dynamic` values before being passed to their respective handlers. Event handlers accept those `Dynamic` values and return a `Result` of either `Ok(Msg)`, or `DecodeErrors` - the `DecodeError` list. + +Therefore, Lustre event handlers are simply an implementation of the `Decoder` function type. + +## Writing A Custom Input Handler + +In javascript, input event handlers often look something like this: + +```js + function onInput(event) { + const input = event.target.value + // do your stuff! + } +``` + +This is very convenient! But it's not type-safe. From the function's perspective, there is no guarantee that _`event`_ is an object with a property named _`target`_ which itself has a property named _`value`_. In a more complex app, we might even pass it a numeric or boolean value on accident. The failure to handle such error conditions leads to many `Uncaught TypeError` crashes. + +Here's how we can extract the event's dynamic value in a type-safe way in Lustre: + +```gleam + let on_input = fn(event: dynamic.Dynamic) -> Result(Msg, dynamic.DecodeErrors) { + use target <- result.try(dynamic.field("target", dynamic.dynamic)(event)) + use value <- result.try(dynamic.field("value", dynamic.string)(target)) + // do your stuff! + Ok(GotInput(value)) + } +``` + +First we extract the `target` field from our `event`, which is expected to be of the type `dynamic.dynamic`. Because the target is itself dynamic, we can again use the dynamic library to extract its `value` field, which is expected to be of type `dynamic.string`. If either of those expectations are not met, the function will return an error, and nothing more will happen. + +This is such a common use case that Lustre's `event` module has a helper function for it. Here is a far less verbose version that provides the exact same type-safe guarantees: + +```gleam + let on_input = fn(event) { + use value <- result.try(event.value(event)) + // do your stuff! + Ok(GotInput(value)) + } +``` + +## Make it Loud + +In this [example code](./src/app.gleam#L63), we define a custom input handler called `make_it_loud`, which calls `string.uppercase` to make sure all our input is LOUD. Then in our [view function](./src/app.gleam#L79), instead of calling `event.on_input(GotInput)` like we did in the last example, we can just call `event.on("input", make_it_loud)`. ## Getting help diff --git a/examples/04-custom-event-handlers/gleam.toml b/examples/04-custom-event-handlers/gleam.toml index a9666db..421e8e8 100644 --- a/examples/04-custom-event-handlers/gleam.toml +++ b/examples/04-custom-event-handlers/gleam.toml @@ -4,7 +4,7 @@ target = "javascript" [dependencies] gleam_stdlib = "~> 0.34 or ~> 1.0" -lustre = { path = "../../" } +lustre = "4.0.0-rc.1" lustre_ui = "~> 0.4" [dev-dependencies] diff --git a/examples/04-custom-event-handlers/header.png b/examples/04-custom-event-handlers/header.png Binary files differnew file mode 100644 index 0000000..e75e2b5 --- /dev/null +++ b/examples/04-custom-event-handlers/header.png diff --git a/examples/04-custom-event-handlers/manifest.toml b/examples/04-custom-event-handlers/manifest.toml index 9352c3c..f3ed2be 100644 --- a/examples/04-custom-event-handlers/manifest.toml +++ b/examples/04-custom-event-handlers/manifest.toml @@ -6,18 +6,18 @@ packages = [ { name = "filepath", version = "0.2.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "filepath", source = "hex", outer_checksum = "FC1B1B29438A5BA6C990F8047A011430BEC0C5BA638BFAA62718C4EAEFE00435" }, { name = "gleam_community_ansi", version = "1.4.0", build_tools = ["gleam"], requirements = ["gleam_community_colour", "gleam_stdlib"], otp_app = "gleam_community_ansi", source = "hex", outer_checksum = "FE79E08BF97009729259B6357EC058315B6FBB916FAD1C2FF9355115FEB0D3A4" }, { name = "gleam_community_colour", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_community_colour", source = "hex", outer_checksum = "A49A5E3AE8B637A5ACBA80ECB9B1AFE89FD3D5351FF6410A42B84F666D40D7D5" }, - { name = "gleam_erlang", version = "0.24.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_erlang", source = "hex", outer_checksum = "26BDB52E61889F56A291CB34167315780EE4AA20961917314446542C90D1C1A0" }, - { name = "gleam_json", version = "1.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib", "thoas"], otp_app = "gleam_json", source = "hex", outer_checksum = "8B197DD5D578EA6AC2C0D4BDC634C71A5BCA8E7DB5F47091C263ECB411A60DF3" }, + { name = "gleam_erlang", version = "0.25.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_erlang", source = "hex", outer_checksum = "054D571A7092D2A9727B3E5D183B7507DAB0DA41556EC9133606F09C15497373" }, + { name = "gleam_json", version = "0.7.0", build_tools = ["gleam"], requirements = ["gleam_stdlib", "thoas"], otp_app = "gleam_json", source = "hex", outer_checksum = "CB405BD93A8828BCD870463DE29375E7B2D252D9D124C109E5B618AAC00B86FC" }, { name = "gleam_otp", version = "0.10.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "0B04FE915ACECE539B317F9652CAADBBC0F000184D586AAAF2D94C100945D72B" }, - { name = "gleam_package_interface", version = "1.0.0", build_tools = ["gleam"], requirements = ["gleam_json", "gleam_stdlib"], otp_app = "gleam_package_interface", source = "hex", outer_checksum = "52A721BCA972C8099BB881195D821AAA64B9F2655BECC102165D5A1097731F01" }, { name = "gleam_stdlib", version = "0.36.0", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "C0D14D807FEC6F8A08A7C9EF8DFDE6AE5C10E40E21325B2B29365965D82EB3D4" }, { name = "glearray", version = "0.2.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "glearray", source = "hex", outer_checksum = "908154F695D330E06A37FAB2C04119E8F315D643206F8F32B6A6C14A8709FFF4" }, { name = "gleeunit", version = "1.0.2", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "D364C87AFEB26BDB4FB8A5ABDE67D635DC9FA52D6AB68416044C35B096C6882D" }, { name = "glint", version = "0.16.0", build_tools = ["gleam"], requirements = ["gleam_community_ansi", "gleam_community_colour", "gleam_stdlib", "snag"], otp_app = "glint", source = "hex", outer_checksum = "61B7E85CBB0CCD2FD8A9C7AE06CA97A80BF6537716F34362A39DF9C74967BBBC" }, { name = "justin", version = "1.0.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "justin", source = "hex", outer_checksum = "7FA0C6DB78640C6DC5FBFD59BF3456009F3F8B485BF6825E97E1EB44E9A1E2CD" }, - { name = "lustre", version = "4.0.0-rc.2", build_tools = ["gleam"], requirements = ["argv", "filepath", "gleam_community_ansi", "gleam_erlang", "gleam_json", "gleam_otp", "gleam_package_interface", "gleam_stdlib", "glint", "justin", "simplifile", "spinner", "tom"], source = "local", path = "../.." }, + { name = "lustre", version = "4.0.0-rc1", build_tools = ["gleam"], requirements = ["argv", "filepath", "gleam_community_ansi", "gleam_erlang", "gleam_json", "gleam_otp", "gleam_stdlib", "glint", "justin", "shellout", "simplifile", "spinner", "tom"], otp_app = "lustre", source = "hex", outer_checksum = "E49E96AB45A43B0AFDF82B58D727AFB45FF457BEAD2BA158381A8E979F51F604" }, { name = "lustre_ui", version = "0.4.0", build_tools = ["gleam"], requirements = ["gleam_community_colour", "gleam_stdlib", "lustre"], otp_app = "lustre_ui", source = "hex", outer_checksum = "9FE07E26EABDB13F7CB29F90AD8763618040729BF16E5F451A6ED584C52AA093" }, { name = "repeatedly", version = "2.1.1", build_tools = ["gleam"], requirements = [], otp_app = "repeatedly", source = "hex", outer_checksum = "38808C3EC382B0CD981336D5879C24ECB37FCB9C1D1BD128F7A80B0F74404D79" }, + { name = "shellout", version = "1.6.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "shellout", source = "hex", outer_checksum = "E2FCD18957F0E9F67E1F497FC9FF57393392F8A9BAEAEA4779541DE7A68DD7E0" }, { name = "simplifile", version = "1.5.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "simplifile", source = "hex", outer_checksum = "EB9AA8E65E5C1E3E0FDCFC81BC363FD433CB122D7D062750FFDF24DE4AC40116" }, { name = "snag", version = "0.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "snag", source = "hex", outer_checksum = "54D32E16E33655346AA3E66CBA7E191DE0A8793D2C05284E3EFB90AD2CE92BCC" }, { name = "spinner", version = "1.1.0", build_tools = ["gleam"], requirements = ["gleam_community_ansi", "gleam_erlang", "gleam_stdlib", "glearray", "repeatedly"], otp_app = "spinner", source = "hex", outer_checksum = "200BA3D4A04D468898E63C0D316E23F526E02514BC46454091975CB5BAE41E8F" }, @@ -28,5 +28,5 @@ packages = [ [requirements] gleam_stdlib = { version = "~> 0.34 or ~> 1.0" } gleeunit = { version = "~> 1.0" } -lustre = { path = "../../" } +lustre = { version = "4.0.0-rc.1" } lustre_ui = { version = "~> 0.4" } diff --git a/examples/04-custom-event-handlers/src/app.gleam b/examples/04-custom-event-handlers/src/app.gleam index 35a6831..aa9638c 100644 --- a/examples/04-custom-event-handlers/src/app.gleam +++ b/examples/04-custom-event-handlers/src/app.gleam @@ -60,16 +60,13 @@ fn view(model: Model) -> Element(Msg) { let styles = [#("width", "100vw"), #("height", "100vh"), #("padding", "1rem")] let length = int.to_string(model.length) let max = int.to_string(model.max) - let on_input = fn(event) { + let make_it_loud = fn(event) -> Result(Msg, List(dynamic.DecodeError)) { use target <- result.try(dynamic.field("target", dynamic.dynamic)(event)) use value <- result.try(dynamic.field("value", dynamic.string)(target)) - // Decoding the `value` from anevent target is so common we provider a decoder - // for it already: - // - // use value <- result.try(event.value(event)) + let loud = string.uppercase(value) - Ok(GotInput(value)) + Ok(GotInput(loud)) } ui.centre( @@ -78,8 +75,8 @@ fn view(model: Model) -> Element(Msg) { [aside.content_first(), aside.align_centre()], ui.field( [], - [element.text("Write a message:")], - ui.input([attribute.value(model.value), event.on("input", on_input)]), + [element.text("Write a LOUD message:")], + ui.input([attribute.value(model.value), event.on("input", make_it_loud)]), [element.text(length <> "/" <> max)], ), ui.button([event.on_click(Reset)], [element.text("Reset")]), |