Skip to content

Commit

Permalink
Base64 (en|de)coding (#7)
Browse files Browse the repository at this point in the history
fixes #4
  • Loading branch information
jshawl authored Jun 6, 2024
1 parent 3cc606e commit 5636763
Show file tree
Hide file tree
Showing 6 changed files with 500 additions and 14 deletions.
62 changes: 54 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@
[![Package Version](https://img.shields.io/hexpm/v/lustre_hash_state)](https://hex.pm/packages/lustre_hash_state)
[![Hex Docs](https://img.shields.io/badge/hex-docs-ffaff3)](https://hexdocs.pm/lustre_hash_state/)

---

`lustre_hash_state` provides `Effect`s to store a model's state in the
hash fragment:

```
type Model {
Model(dict.from_list([#("example_key", "example_value")]))
}
```

```txt
https://example.com/#example_key=example_value
```

When the model changes, the hash changes! When the hash changes, the model changes, too!

## Usage

```sh
gleam add lustre_hash_state
```
Expand All @@ -12,32 +31,30 @@ import lustre_hash_state
pub opaque type Msg {
// ...
// Bring your own key value Msg type
HashChange(key: String, value: String)
}
pub fn main() {
let app = lustre.application(init, update, view)
let assert Ok(_) = lustre.start(app, "#app", Nil)
}
fn init(_flags) -> #(Model, effect.Effect(Msg)) {
// dispatch a HashChange Msg when the "hashchange" event is
// dispatched from the browser
#(Model(dict.new()), lustre_hash_state.init(HashChange))
}
fn update(model: Model, msg: Msg) -> #(Model, effect.Effect(msg)) {
let Model(dct) = model
case msg {
// hash change events can update the model
// update the model on hashchange events
HashChange(key, value) -> {
#(Model(dict.update(dct, key, fn(_x) { value })), effect.none())
}
UserUpdatedMessage(key, value) -> {
#(
Model(dict.update(dct, key, fn(_x) { value })),
// and user events can update the hash
// update the hash with the new key value pair
lustre_hash_state.update(key, value),
)
}
// ...
}
}
Expand All @@ -58,6 +75,35 @@ fn view(model: Model) -> Element(Msg) {
}
```

## Encoding

Need to work with data types more complex than strings? No problem!

Within lustre's init fn, decode the data:

```gleam
fn init(_flags) -> #(Model, effect.Effect(Msg)) {
#(
Model(dict.new()),
lustre_hash_state.init(fn(key: String, value: String) {
// decoded using the `from_base64` convenience method
HashChange(key, value |> lustre_hash_state.from_base64)
}),
)
}
```

Within lustre's update fn, encode the data:

```gleam
UserUpdatedMessage(key, value) -> {
#(
Model(...),
lustre_hash_state.update(key, value |> lustre_hash_state.to_base64),
)
}
```

Further documentation can be found at <https://hexdocs.pm/lustre_hash_state>.

## Development
Expand Down
Loading

0 comments on commit 5636763

Please sign in to comment.