Skip to content

Commit

Permalink
Add State.map which returns an IWritable.
Browse files Browse the repository at this point in the history
  • Loading branch information
JaggerJo committed Nov 4, 2023
1 parent a625eaa commit a3b4b41
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
27 changes: 19 additions & 8 deletions src/Avalonia.FuncUI/Components/State/State.Adapters.fs
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,27 @@ type internal ReadValueMapped<'a, 'b>
member this.Dispose () =
()

type internal ValueMapped<'a, 'b>
( src: IWritable<'a>,
mapFunc: 'a -> 'b,
mapBackFunc: 'b -> 'a ) =

inherit ReadValueMapped<'a, 'b>(src, mapFunc)
type internal ValueMapped<'a, 'b>(src: IWritable<'a>, read: 'a -> 'b, write: 'a * 'b -> 'a) =
let mutable current: 'b = read src.Current

interface IWritable<'b> with
member this.Set (value: 'b) : unit =
src.Set (mapBackFunc value)
member this.InstanceId with get () = src.InstanceId
member this.InstanceType with get () = InstanceType.Create src
member this.ValueType with get () = typeof<'b>
member this.Current with get () = current
member this.Subscribe (handler: 'b -> unit) =
src.Subscribe (fun value ->
current <- read value
handler current
)
member this.SubscribeAny (handler: obj -> unit) =
(this :> IReadable<'b>).Subscribe handler

member this.Set (value: 'b) =
src.Set(write(src.Current, value))

member this.Dispose () =
()

type internal ReadValueMap<'value, 'key when 'key : comparison>
( src: IReadable<'value list>,
Expand Down
3 changes: 3 additions & 0 deletions src/Avalonia.FuncUI/Components/State/State.Functions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ module State =
let readMap (mapFunc: 'a -> 'b) (value: IReadable<'a>) : IReadable<'b> =
new ReadValueMapped<'a, 'b>(value, mapFunc) :> _

let map (read: 'a -> 'b) (write: 'a * 'b -> 'a) (state: IWritable<'a>) : IWritable<'b> =
new ValueMapped<'a, 'b>(state, read, write)

let readTryFindByKey (keyPath: 'value -> 'key) (key: IReadable<'key>) (wire: IReadable<list<'value>>) : IReadable<'value option> =
let keyedWire: IReadable<Map<'key, 'value>> = new ReadValueMap<'value, 'key>(wire, keyPath) :> _
let keyFocusedWire: IReadable<'value option> = new ReadKeyFocusedValue<'value, 'key>(keyedWire, key) :> _
Expand Down

0 comments on commit a3b4b41

Please sign in to comment.