Skip to content

Commit

Permalink
Add an example to the README
Browse files Browse the repository at this point in the history
  • Loading branch information
WorldMaker committed Sep 8, 2024
1 parent 515c2e2 commit fb666a1
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,67 @@ and operators.
[Getting Started][started] can lead you through a gentle tour of
Butterfloat features.

## A Usage Example

A complex component with embedded state may look something like this:

```tsx
import { ComponentContext, ObservableEvent, butterfly, jsx } from 'butterfloat'
import { map } from 'rxjs'

interface GardenProps {}

interface GardenEvents {
rake: ObservableEvent<MouseEvent>
}

function Garden(
props: GardenProps,
{ bindEffect, events }: ComponentContext<GardenEvents>,
) {
const [money, setMoney] = butterfly(1)
const [labor, setLabor] = butterfly(0)

const moneyPercent = money.pipe(
map((money) => money.toLocaleString(undefined, { style: 'percent ' })),
)

const laborPercent = labor.pipe(
map((labor) => labor.toLocaleString(undefined, { style: 'percent' })),
)

bindEffect(events.rake, () => {
setMoney((money) => money - 0.15)
setLabor((labor) => labor + 0.3)
})

return (
<div class="garden">
<div class="stat-label">Money</div>
<progress
title="Money"
bind={{ value: money, innerText: moneyPercent }}
/>
<div class="stat-label">Labor</div>
<progress
title="Labor"
bind={{ value: labor, innerText: laborPercent }}
/>
<div class="section-label">Activities</div>
<button type="button" events={{ click: events.rake }}>
Rake
</button>
</div>
)
}
```

This may look like React at first glance, especially the intentional
surface level resemblance of `butterfly` to `useState` and `bindEffect`
to `useEffect`. This exact example is refactored in ways that a React
component can't be (moving the `butterfly` state to its own "view model")
in the [State Management][state] documentation, but it is suggested you
take the scenic route and start with [Getting Started][started].

[started]: ./docs/getting-started.md
[state]: ./docs/state.md

0 comments on commit fb666a1

Please sign in to comment.