|
| 1 | +namespace Saturn |
| 2 | + |
| 3 | +open Channels |
| 4 | +open Microsoft.AspNetCore.Http |
| 5 | +open Microsoft.Extensions.DependencyInjection |
| 6 | +open System.Threading.Tasks |
| 7 | +open Giraffe.GiraffeViewEngine |
| 8 | +open Elmish |
| 9 | +open FSharp.Control.Tasks.V2 |
| 10 | + |
| 11 | +module LiveComponenet = |
| 12 | + type ILiveComponenet = |
| 13 | + abstract member InternalChannel : IChannel with get |
| 14 | + |
| 15 | + type LiveComponentMsg = {Event: string; ElementId: string; Data: string} |
| 16 | + type internal ViewUpdateMsg = {ComponentId: string; Data: string} |
| 17 | + |
| 18 | +[<AutoOpen>] |
| 19 | +module LiveComponentBuilder = |
| 20 | + open LiveComponenet |
| 21 | + |
| 22 | + type LiveComponenetBuilderState<'State, 'Msg> = { |
| 23 | + Join: (HttpContext -> ClientInfo -> Task<JoinResult>) option |
| 24 | + Init: (HttpContext -> ClientInfo -> (Cmd<'Msg> -> unit) -> Task<'State * Cmd<'Msg>>) option |
| 25 | + Update: (HttpContext -> ClientInfo -> 'Msg -> 'State -> Task<'State * Cmd<'Msg>>) option |
| 26 | + View: (HttpContext -> ClientInfo -> 'State -> XmlNode) option |
| 27 | + MessageMap: (HttpContext -> ClientInfo -> LiveComponentMsg -> 'Msg) option |
| 28 | + } |
| 29 | + |
| 30 | + type internal StateMsg<'State, 'Msg> = |
| 31 | + | Init of HttpContext * ClientInfo |
| 32 | + | SetState of 'State |
| 33 | + | Dispatch of Cmd<'Msg> |
| 34 | + | Update of 'Msg |
| 35 | + |
| 36 | + |
| 37 | + type LiveComponenetBuilder<'State, 'Msg> internal (componentId: string) = |
| 38 | + |
| 39 | + member __.Yield (_) : LiveComponenetBuilderState<'State, 'Msg> = |
| 40 | + {Join = None; Init = None; Update = None; View = None; MessageMap = None} |
| 41 | + |
| 42 | + [<CustomOperation("join")>] |
| 43 | + ///Action executed when client tries to join the channel. |
| 44 | + ///You can either return `Ok` if channel allows join, or reject it with `Rejected` |
| 45 | + ///Typical cases for rejection may include authorization/authentication, |
| 46 | + ///not being able to handle more connections or other business logic reasons. |
| 47 | + /// |
| 48 | + /// As arguments, `join` action gets: |
| 49 | + /// * current `HttpContext` for the request |
| 50 | + /// * `ClientInfo` instance representing additional information about client sending request |
| 51 | + member __.Join (state, handler) : LiveComponenetBuilderState<'State, 'Msg> = |
| 52 | + {state with Join = handler} |
| 53 | + |
| 54 | + [<CustomOperation("init")>] |
| 55 | + ///Action executed after client succesfully join the channel. Used to set initial state of the compnent. |
| 56 | + /// |
| 57 | + /// As arguments, `init` action gets: |
| 58 | + /// * current `HttpContext` for the request |
| 59 | + /// * `ClientInfo` instance representing additional information about client sending request |
| 60 | + /// * `(Cmd<'Msg> -> unit)` function that can be used to dispatch additional messages (for example used when in `init` you can subscribe to external events) |
| 61 | + /// |
| 62 | + /// Returns: `Task<'State * Cmd<'Msg>>` |
| 63 | + member __.Init (state, handler) : LiveComponenetBuilderState<'State, 'Msg> = |
| 64 | + {state with Init = handler} |
| 65 | + |
| 66 | + [<CustomOperation("update")>] |
| 67 | + ///Action executed after client performs some event in the component |
| 68 | + /// |
| 69 | + /// As arguments, `update` action gets: |
| 70 | + /// * current `HttpContext` for the request |
| 71 | + /// * `ClientInfo` instance representing additional information about client sending request |
| 72 | + /// * message `'Msg` that represetns event that happened |
| 73 | + /// |
| 74 | + /// Returns: `Task<'State * Cmd<'Msg>>` |
| 75 | + member __.Update (state, handler) : LiveComponenetBuilderState<'State, 'Msg> = |
| 76 | + {state with Update = handler} |
| 77 | + |
| 78 | + [<CustomOperation("view")>] |
| 79 | + ///Function responsible for mapping current state to the view |
| 80 | + /// |
| 81 | + /// As arguments, `view` action gets: |
| 82 | + /// * current `HttpContext` for the request |
| 83 | + /// * `ClientInfo` instance representing additional information about client sending request |
| 84 | + /// * current state `'State` |
| 85 | + /// |
| 86 | + /// Returns: `XmlNode` (Giraffe.ViewEngine) |
| 87 | + member __.View (state, handler) : LiveComponenetBuilderState<'State, 'Msg> = |
| 88 | + {state with View = handler} |
| 89 | + |
| 90 | + [<CustomOperation("message_map")>] |
| 91 | + ///Function responsible for mapping raw messages into component domain messages |
| 92 | + /// |
| 93 | + /// As arguments, `message_map` action gets: |
| 94 | + /// * current `HttpContext` for the request |
| 95 | + /// * `ClientInfo` instance representing additional information about client sending request |
| 96 | + /// * instance of `LiveComponentMsg` representing raw message |
| 97 | + /// |
| 98 | + /// Returns: `'Msg` representing domain message |
| 99 | + member __.MessageMap (state, handler) : LiveComponenetBuilderState<'State, 'Msg> = |
| 100 | + {state with MessageMap = handler} |
| 101 | + |
| 102 | + member __.Run (state : LiveComponenetBuilderState<'State, 'Msg>) : ILiveComponenet = |
| 103 | + if state.Join.IsNone then failwith "Join is required operation for any Live Component. Please use `join` operation in your `liveComponent` CE to define it." |
| 104 | + if state.Init.IsNone then failwith "Init is required operation for any Live Component. Please use `init` operation in your `liveComponent` CE to define it." |
| 105 | + if state.View.IsNone then failwith "View is required operation for any Live Component. Please use `view` operation in your `liveComponent` CE to define it." |
| 106 | + if state.Update.IsNone then failwith "Update is required operation for any Live Component. Please use `update` operation in your `liveComponent` CE to define it." |
| 107 | + if state.MessageMap.IsNone then failwith "MessageMap is required operation for any Live Component. Please use `message_map` operation in your `liveComponent` CE to define it." |
| 108 | + |
| 109 | + |
| 110 | + let joinH = state.Join.Value |
| 111 | + let initH = state.Init.Value |
| 112 | + let viewH = state.View.Value |
| 113 | + let updateH = state.Update.Value |
| 114 | + let mmH = state.MessageMap.Value |
| 115 | + |
| 116 | + let c = |
| 117 | + let rec stateMP = MailboxProcessor.Start(fun inbox -> |
| 118 | + |
| 119 | + let rec messageLoop(state: 'State, (ctx: HttpContext), ci) = async { |
| 120 | + let! msg = inbox.Receive() |
| 121 | + let! newState, ctx, ci = |
| 122 | + match msg with |
| 123 | + | Init (ctx, ci) -> |
| 124 | + async { return state, ctx, ci} |
| 125 | + | SetState (state) -> |
| 126 | + async { |
| 127 | + let clientHub = ctx.RequestServices.GetService<ISocketHub> () |
| 128 | + let viewTemplate = viewH ctx ci state |
| 129 | + let viewStr = Giraffe.GiraffeViewEngine.renderHtmlDocument viewTemplate |
| 130 | + let viewMsg = {ComponentId = componentId; Data = viewStr} |
| 131 | + do! clientHub.SendMessageToClient ci "liveComponent" viewMsg |> Async.AwaitTask |
| 132 | + |
| 133 | + return state, ctx, ci |
| 134 | + } |
| 135 | + | Update msg -> |
| 136 | + async { |
| 137 | + let! (state, cmd) = (updateH ctx ci msg state |> Async.AwaitTask) |
| 138 | + |
| 139 | + let clientHub = ctx.RequestServices.GetService<ISocketHub> () |
| 140 | + let viewTemplate = viewH ctx ci state |
| 141 | + let viewStr = Giraffe.GiraffeViewEngine.renderHtmlDocument viewTemplate |
| 142 | + let viewMsg = {ComponentId = componentId; Data = viewStr} |
| 143 | + do! clientHub.SendMessageToClient ci "liveComponent" viewMsg |> Async.AwaitTask |
| 144 | + |
| 145 | + inbox.Post (Dispatch cmd) |
| 146 | + return state, ctx, ci |
| 147 | + } |
| 148 | + | Dispatch (cmd: Cmd<'Msg>) -> |
| 149 | + async { |
| 150 | + cmd |> List.iter (fun n -> n (Update >> inbox.Post) ) |
| 151 | + return state, ctx, ci |
| 152 | + } |
| 153 | + return! messageLoop (newState, ctx, ci) } |
| 154 | + |
| 155 | + let inState = Unchecked.defaultof<'State> |
| 156 | + let inCtx = Unchecked.defaultof<HttpContext> |
| 157 | + let inCi = Unchecked.defaultof<ClientInfo> |
| 158 | + messageLoop (inState, inCtx, inCi) |
| 159 | + ) |
| 160 | + |
| 161 | + channel { |
| 162 | + join (fun ctx si -> task { |
| 163 | + let! res = joinH ctx si |
| 164 | + match res with |
| 165 | + | JoinResult.Ok -> |
| 166 | + stateMP.Post (Init (ctx, si)) |
| 167 | + let! (s,cmd) = initH ctx si (Dispatch >> stateMP.Post) |
| 168 | + stateMP.Post (SetState s) |
| 169 | + stateMP.Post (Dispatch cmd) |
| 170 | + | _ -> |
| 171 | + () |
| 172 | + return res |
| 173 | + }) |
| 174 | + |
| 175 | + handle "liveComponent" (fun ctx si (msg: Message<LiveComponentMsg>) -> task { |
| 176 | + let m = mmH ctx si msg.Payload |
| 177 | + stateMP.Post (Update m) |
| 178 | + return () |
| 179 | + }) |
| 180 | + |
| 181 | + terminate (fun ctx si -> task { |
| 182 | + (stateMP :> System.IDisposable).Dispose() |
| 183 | + return () |
| 184 | + }) |
| 185 | + } |
| 186 | + |
| 187 | + { new ILiveComponenet with |
| 188 | + member __.InternalChannel with get () = c |
| 189 | + } |
| 190 | + |
| 191 | + let liveComponent<'State, 'Msg> id = LiveComponenetBuilder<'State, 'Msg>(id) |
| 192 | + |
0 commit comments