Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
c280d86
Fix a typo
BillHally Apr 11, 2022
82c3286
add styles in the Lit functions
AngelMunoz May 17, 2022
4560f60
Remove mention to --runFast in docs
alfonsogarciacaro May 27, 2022
6317d3a
Solutions for #31 and #39
alfonsogarciacaro May 27, 2022
8ae1d78
add extra types to LitElement
AngelMunoz May 29, 2022
33f1d2e
add computation expressions for Class LitElements
AngelMunoz May 29, 2022
def3e96
add class based examples
AngelMunoz May 29, 2022
a143bc0
update to .NET6
AngelMunoz May 30, 2022
cfa578d
update local tools
AngelMunoz May 30, 2022
6835f81
re-order things a bit
AngelMunoz May 30, 2022
30b287e
fix format and simplify CEs
AngelMunoz May 30, 2022
c973f2c
fix sample usage
AngelMunoz May 30, 2022
f218ffe
inline CE, address pr comments
AngelMunoz May 30, 2022
0ff2c7a
fix reactive controller call
AngelMunoz May 30, 2022
a2cecec
update definitions
AngelMunoz May 30, 2022
e999185
update lit version
AngelMunoz May 31, 2022
b4e4872
fix pr comments
AngelMunoz May 31, 2022
f33299f
add full bindings to directives
AngelMunoz May 31, 2022
6c1629c
add experimental module
AngelMunoz May 31, 2022
4d989f0
remove decorator experiment
AngelMunoz Jun 2, 2022
eea6e79
add elmish controller test
AngelMunoz Jun 2, 2022
a09642a
enable controllers + hook.GetController
AngelMunoz Jun 2, 2022
6de1489
Fixing self closing web component tags
leolorenzoluis Jul 7, 2022
2277f3a
Added Lit.mapiUnique
leolorenzoluis Jul 7, 2022
b08eb88
Publish 1.4.2
alfonsogarciacaro Jul 14, 2022
3e29301
Update templates.md
alfonsogarciacaro Jul 25, 2022
52275d9
Merge branch 'master' into experimental-class-bindings
AngelMunoz Jul 30, 2022
e27e10c
Merge branch 'master' into experimental-class-bindings
AngelMunoz Jul 30, 2022
d3da340
Update hook-components.md
JordanMarr Aug 1, 2022
2d99bad
Update hook-components.md
alfonsogarciacaro Aug 22, 2022
4cb291d
Fix #67
alfonsogarciacaro Aug 23, 2022
70937c2
Fix Github actions
alfonsogarciacaro Sep 5, 2022
7c04731
Merge branch 'master' into experimental-class-bindings
AngelMunoz Sep 14, 2022
3cccb17
change the name for consistency
AngelMunoz Sep 14, 2022
9a66338
add class docs
AngelMunoz Sep 14, 2022
c9bd281
add controllers docs
AngelMunoz Sep 14, 2022
0168858
add new pages to the menu
AngelMunoz Sep 14, 2022
e18f8b8
remove the effect controller
AngelMunoz Sep 14, 2022
379fdc1
fix the compilation issue
AngelMunoz Sep 14, 2022
028629d
add doc strings
AngelMunoz Sep 14, 2022
c241b13
add a couple more comments
AngelMunoz Sep 14, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,22 @@
"isRoot": true,
"tools": {
"fable": {
"version": "3.6.1",
"version": "3.7.12",
"commands": [
"fable"
]
},
"femto": {
"version": "0.9.0",
"version": "0.13.0",
"commands": [
"femto"
]
},
"fantomas": {
"version": "5.0.0-alpha-008",
"commands": [
"fantomas"
]
}
}
}
4 changes: 1 addition & 3 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Setup .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: 5.0.x
uses: actions/setup-dotnet@v2.1.0
- name: Setup Node.js environment
uses: actions/setup-node@v2.4.0
with:
Expand Down
4 changes: 1 addition & 3 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-dotnet@v1
with:
dotnet-version: '5.0.x'
- uses: actions/setup-dotnet@v2.1.0
- uses: actions/setup-node@v2
with:
node-version: 14.17.*
Expand Down
95 changes: 95 additions & 0 deletions docsrc/docs/class-components.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Class Lit Components

Lit's own API is based on class components, not functions while Fable.Lit tries to provide the best experience for F# with idiomatic style you are very likely to know and love, we also understand that there's also things that are hard to do with the current API specially those that expect Lit Elements as classes.

The simplest component example would be the following:

```fsharp
type MyElement() =
inherit LitElement()

let mutable counter = 0

let increment _ =
counter <- counter + 1

let decrement _ =
counter <- counter + 1

override _.render() =
html
$"""
<p>{counter}</p>
<button @click={increment}>Increment</button>
<button @click={decrement}>Decrement</button>
"""
// runs the auto-registration process for this custom element
// similar to the @customElement("name") decorator from Lit
registerElement<MyElement> "element-with-controller" {
// registers a property to be tracked by lit
reactiveProperty "counter" {
use_state
}

css $"p {{ color: red; }}"
}
```

As you can see this is pretty much how you would write a custom element with typescript

```ts
@cutomElement("my-element")
class MyElement extends LitElement {
static styles = [
css`
p {
color: red;
}
`,
];

@state
private counter = 0;

private increment = () => {
this.counter += 1;
};

private decrement = () => {
this.counter -= 1;
};

render() {
return html`
<p>${this.counter}</p>
<button @click=${increment}>Increment</button>
<button @click=${decrement}>Decrement</button>
`;
}
}
```

### Main Differences

One difference you can see with the function based API is that the configuration is not done via the init function, which has advantages and disadvantages.

- Function components with the `ComponentFunction` and `LitElement` attributes are compatible with HMR
- Classes are as close as lit's API as you will get
- Functions use hook style composition
- Classes use controller style composition

### When to use class components

Class components lend themselves to be used more with more mutable state management and also the usage of reactive controllers which may come from third party packages or even lit's official packages. Consider using class components when:

- You are already familiar with Lit and come from typescript.
- Your component uses several controllers or has complex mutable state.
- You want to stay as close to Lit as possible.

### When not to use class components

Consider function components when:

- You are familiar with the Feliz/Fable Ecosystem
- You are getting started with Lit and F#
- You are familiar with React
187 changes: 187 additions & 0 deletions docsrc/docs/controllers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# Controllers

> **Note**: To learn more about Reactive Controllers please visit the [lit's documentation](https://lit.dev/docs/composition/controllers/)

Lit Controllers are one way to apply composition to components, these are like React's Hooks but designed for lit.

Controllers allow you to tap into the component's life cycle that is using them which makes it easier to control when to render when a side effect has been produced and the component has to re-render.

Controllers are a class based API and while classes are not the favored construct in F#, F# knows quite well how to work with them while also providing means to ensure correctness.

A simple controller can be as follows

```fsharp
type Post =
{| usedId: int
id: int
title: string
body: string |}

type PostsController(host: LitElement) =
inherit ReactiveController(host)

// declare public properties
// that can be accessed from other components
// or used as view values
member val Posts: Post array = Array.empty with get, set
member val Page: int = 1 with get, set
member val Limit: int = 10 with get, set

// We can handle logig within the function or outsource it
// to another function if required, in this case we'll just show it here
// but it could have been something like
// `member this.Fetch(?page: int, ?limit: int) = Server.fetchPosts page limit
member this.Fetch(?page: int, ?limit: int) =
let page = defaultArg page this.Page
let limit = defaultArg limit this.Limit

promise {
let! posts =
promise {
let! result = tryFetch $"https://jsonplaceholder.typicode.com/posts?_page={page}&_limit={limit}" []

match result with
| Ok res ->
let! result = res.json () :?> JS.Promise<Post array>
return result
| Error err -> return Array.empty<Post>
}
// do the assignments as usual
this.Posts <- posts
// tap into the host's update mechanism
// and request an re-render
host.requestUpdate ()
}

member this.NextPage() =
this.Page <- this.Page + 1
this.Fetch() |> Promise.start

// tap into the hosts's lifecycle when the component is connected
// to the DOM, in vue or other frameworks
// this could be called something like `mounted`
override this.hostConnected() : unit = this.Fetch() |> Promise.start
```

Once this controller is declared we can use it in other places like

For Functions:

```fsharp
let postTemplate (post: Post) =
html $"<li>{post.title}</li>"

[<LitElement("my-element")>]
let MyElement() =
let host =
LitElement.init(fun init ->
init.controllers <- {| api = Controller.of(fun host -> PostsController host) |}
)
let api = host.controlelrs.api.Value

html
$"""
<p>Page: {api.Page}</p>
<button @click={fun _ -> api.NextPage()}>Next Page</button>
<ul>{posts}</li>
"""
// Alternatively
[<LitElement("my-element")>]
let MyElement() =
LitElement.init()

let api = Hook.useController<PostsController>()

html
$"""
<p>Page: {api.Page}</p>
<button @click={fun _ -> api.NextPage()}>Next Page</button>
<ul>{posts}</li>
"""

```

For Classes:

```fsharp

type MyElement() =
inherit LitElement()

// the controller is initialized right away
let api = PostsController jsThis

let posts =
api.Posts
|> Lit.mapUnique (fun (p: Post) -> $"{p.id}") postTemplate

override _.render() =
html
$"""
<p>Page: {api.Page}</p>
<button @click={fun _ -> api.NextPage()}>Next Page</button>
<ul>{posts}</li>
"""
```

> **Note**: When using `Hook.useController<Type>()` since it is just a convenience function, you have to know the types of the parameters your controller needs
> since we pass the parameters straight to the contructor
> For example a controller with the following constructor `type MyController (host: LitElement, apiKey: string, userId: number)`, you will have to call it this way: `Hook.useController<MyController>("this is the api key", 123435)` but we don't have a way to ensure type safety in those cases, that's why the controllers option is available in the `LitElement.init` function which uses the controller directly so you know exactly which types you need to provide

### When to use controllers

Controllers lend themselves to be used when state is mutable or full of side effects, the controllers are just means to contain mutability while the rest of the code performs as usual

- Fetching data from a server.
- Updating the view when web socket information arrives.
- Updating the view when observable values change.
- Importing existing controllers from the ecosystem

### When not to use controllers

If you are using the function based API, if you need to process or transform data, the views are stateless or there are no complex side effects that can be handled within the `Hook.useEffect` hook you are likely better using hooks rather than controllers.

Controllers help you self-contain mutability and complexity while seamlessly blend within the Lit's native rendering mechanisms in some cases you endup with easier and simpler to maintain and read components.

That being said it is an optional feature that you may never require if it doesn't fit your style

## Elmish Controller

If you have used elmish with the function based API you will be happy to know that an Elmish controller has been provided out of the box, here's an example usage:

```fsharp
open Elmish
open Lit
open Lit.Elmish

type SampleState = { counter: int }
type SampleMsg =
| Increment
| Decrement

let sampleInit () = { counter = 0 }, Cmd.none

let sampleUpdate msg state =
match msg with
| Increment -> { state with counter = state.counter + 1 }, Cmd.none
| Decrement -> { state with counter = state.counter - 1 }, Cmd.none

type ElementWithController() =
inherit LitElement()

let elmish = ElmishController(jsThis, sampleInit, sampleUpdate)

override _.render() =
html
$"""
<p>Elmish Controller Counter: {elmish.state.counter} </p>
<button @click={fun _ -> elmish.dispatch Increment}>Increment</button>
<button @click={fun _ -> elmish.dispatch Decrement}>Decrement</button>
"""


registerElement<ClassComponents.ElementWithController> "element-with-controller" {
css $"p {{ color: red; }}"
css $"li {{ color: rebeccapurple; }}"
}
```
16 changes: 0 additions & 16 deletions docsrc/docs/hmr.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,6 @@ npx vite build # Build your site for production

That's it, now you have an extremely fast development server and an optimized build with zero config (built files will be put in `dist` folder by default). If you need to edit some settings, you can still use a [config file](https://vitejs.dev/config/) or the CLI options (check them with `npx vite --help`).

## Fable --runFast

If you use `--runFast` option with Fable instead of `--run`, Vite will be started right away instead of waiting until first Fable compilation. When developing you usually already have the compiled files from the previous day, so this way you can get a development server up and running in under 200 milliseconds!

```
dotnet fable watch src -o build/client --runFast vite --open
```

> When Fable compilation finishes Vite will just reload with the updated code.

For production make sure to use `--run` so vite doesn't start bundling until Fable has finished compilation.

```
dotnet fable src -o build/client --run vite build
```

## Elmish and Local HMR

Lit.Elmish is compatible with [Elmish HMR](https://elmish.github.io/hmr/) (use Fable.Elmish.HMR >= 4.3 for Vite support).
Expand Down
6 changes: 3 additions & 3 deletions docsrc/docs/hook-components.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ let NameInput() =
html $"""
<div class="content">
<p>Hello {value}!</p>
<input {Ref inputRef}
<input {Lit.refValue inputRef}
value={value}
@keyup={EvVal setValue}
@focus={Ev(fun _ -> inputRef.Value |> Option.iter (fun el -> el.select()))}>
Expand Down Expand Up @@ -139,7 +139,7 @@ module MyHooks =

// Updating a ref doesn't cause a re-render,
// so let's use a ref with the same signature as useState
type HookContext =
type HookContext with
member ctx.useSilentState(v: 'Value) =
let r = ctx.useRef(v)
r.Value, fun v -> r := v
Expand All @@ -148,4 +148,4 @@ module MyHooks =
// IMPORTANT! This function must be inlined to access the context from the render function
static member inline useSilentState(v: 'Value): 'Value * ('Value -> unit) =
Hook.getContext().useSilentState(v)
```
```
4 changes: 3 additions & 1 deletion docsrc/docs/menu.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@
"docs/hook-components",
"docs/web-components",
"docs/hmr",
"docs/testing"
"docs/testing",
"docs/controllers",
"docs/class-components"
]
Loading