Source file browser.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
(* This module handles all calls to javascript

*)

open Fmlib_js
open Fmlib_js.Dom




(* Basic definitions
   ============================================================
*)



type element             = Element.t * Handler.EventHs.t

type node                = Node.t * element option

type 'msg dom            = ('msg, node) Vdom.t1

type 'msg dom_operations = ('msg, node) Vdom.operations


let document (): Document.t = Window.(get () |> document)

type ('state, 'msg) view1 = 'state -> 'msg Vdom.t
type ('state, 'msg) view2 = 'state -> 'msg Vdom.t * string

type ('state, 'msg) update1 = 'state -> 'msg -> 'state
type ('state, 'msg) update2 = 'state -> 'msg -> 'state * 'msg Command.t



type ('s, 'm) operations =
    | Sandbox of
          ('s, 'm) view1
          * ('s -> 'm Subscription.t)
          * ('s, 'm) update1
    | Element of
          ('s, 'm) view1
          * ('s -> 'm Subscription.t)
          * ('s, 'm) update2
          * (Base.Value.t -> unit)
    | App     of
          ('s, 'm) view2
          * ('s -> 'm Subscription.t)
          * ('s, 'm) update2
          * (Base.Value.t -> unit)



type ('state, 'msg) data =
    {
        mutable state: 'state;
        mutable dirty: bool;
        mutable dom:   'msg dom option;
        mutable subs:  'msg Subscriptions.t option;
        root:          Element.t;
        operations:    ('state, 'msg) operations;
    }





(* Dom operations
   ============================================================

   Accessing the real dom.

   Operations are needed for the module [Vdom].
*)


let dom_operations (dispatch: 'msg -> unit): 'msg dom_operations =
    let get_both:
        node -> element
        =
        function
        | (_, Some el) ->
          el
        | _ ->
            assert false (* Illegal call *)
    in
    let get_element:
        Node.t * element option -> Element.t
        =
        function
        | (_, Some (el, _)) ->
          el
        | _ ->
            assert false (* Illegal call *)
    in
    {
        make_text =
            (fun s -> Document.create_text_node s (document ()), None);

        make_element =
            (fun tag (lst: node list) ->
                 let open Document in
                 let open Element in
                 let open Node in
                 let doc = document () in
                 let el  = create_element tag doc in
                 List.iter
                     (fun (child, _) ->
                          append child (node el))
                     lst;
                 node el, Some (el, Handler.EventHs.empty ()));

        make_element_ns =
            (fun namespace tag (lst: node list) ->
                 let open Document in
                 let open Element in
                 let open Node in
                 let doc = document () in
                 let el  = create_element_ns namespace tag doc in
                 List.iter
                     (fun (child, _) ->
                          append child (node el))
                     lst;
                 node el, Some (el, Handler.EventHs.empty ()));

        add_child =
            (fun (child, _) (par, _) ->
                 Node.append child par);

        remove_child =
            (fun (child, _) (par, _) ->
                 Node.remove child par);

        remove_children =
            (fun (par, _) ->
                 Node.remove_children par);

        replace_child =
            (fun (old_child, _) (new_child, _) (par, _) ->
                 Node.replace new_child old_child par);

        set_style =
            (fun el key value ->
                Style.set key value (Element.style (get_element el)));

        set_attribute =
            (fun el key value ->
                 Element.set_attribute key value (get_element el));

        set_property =
            (fun el key value ->
                 Element.set_property key value (get_element el));


        remove_style =
            (fun el key ->
                 Style.remove
                     key
                     (Element.style (get_element el)));


        remove_attribute =
            (fun el key ->
                 Element.remove_attribute key (get_element el));


        remove_property =
            (fun el key ->
                 Element.delete_property key (get_element el));


        set_handlers =
            (fun el dict ->
                 let el, reals = get_both el in
                 let target = Node.event_target (Element.node el) in
                 Handler.EventHs.set target dispatch dict reals
            );

        update_handlers =
            (fun el dict1 dict2 ->
                 let el, reals = get_both el in
                 let target = Node.event_target (Element.node el) in
                 Handler.EventHs.update target dispatch dict1 dict2 reals);
    }





(* Dispatching messages to the application
   ============================================================

   - call the update function

        state -> msg -> state * cmd

   - update the subscriptions

        state might have changed, therefore subscriptions might have changed.

   - execute commands

*)

let rec dispatch (data: ('state, 'msg) data) (msg: 'msg): unit =
    let update_data state =
        let state_different = not (state == data.state)
        in
        data.dirty <- data.dirty || state_different;
        if state_different then begin
            data.state <- state;
            update_subscriptions data
        end
    in
    match data.operations with
    | Sandbox (_, _, update) ->
        update_data (update data.state msg);

    | Element (_, _, update, post) ->
        let state, cmd = update data.state msg in
        update_data state;
        Command.execute post (dispatch_next data) cmd

    | App (_, _, update, post) ->
        let state, cmd = update data.state msg in
        update_data state;
        Command.execute post (dispatch_next data) cmd


and dispatch_next (data: ('state, 'msg) data) (msg: 'msg): unit =
    ignore ( Timer.set (fun () -> dispatch data msg) 0 )


and update_subscriptions (data: ('s, 'm) data): unit =
    (* create or update the subscriptions, i.e. install all necessary handlers. *)
    let update () =
        match data.operations, data.subs with
        | Sandbox (_, sub, _),    None
        | App (_, sub, _, _),     None
        | Element (_, sub, _, _), None ->
            data.subs <-
                Some (Subscriptions.make (dispatch data) (sub data.state))

        | Sandbox (_, sub, _),    Some subs
        | App (_, sub, _, _),     Some subs
        | Element (_, sub, _, _), Some subs
            when data.dirty ->
            data.subs <-
                Some (Subscriptions.update (dispatch data) (sub data.state) subs)

        | _, _ ->
            ()
    in
    Assert_failure.attempt
        "Exception in 'update_subscriptions' of Fmlib_browser"
        update
        (fun () -> ())










(* Produce the real dom i.e. render the dom
   ============================================================

   This is there the access to the real dom of the browser happens.
*)


let put_below_root (data: ('state, 'msg) data) (dom: 'msg dom): unit =
    let root_node = Element.node data.root in
    Node.remove_children root_node;
    Node.append (Vdom.element dom |> fst) root_node





let vdom (data: ('s, 'm) data): 'm Vdom.t * (unit -> unit) =
    (* Get the virtual dom from the state and the title update function. *)
    match data.operations with
    | Sandbox (view, _, _) ->
        view data.state, (fun () -> ())
    | Element (view, _, _, _) ->
        view data.state, (fun () -> ())
    | App (view, _, _, _) ->
        let vdom, title = view data.state in
        vdom, (fun () -> Document.set_title title (document ()))




let update_dom (data: ('state, 'msg) data): unit =
    (* Create or update the real dom based on the state. First create a virtual
       dom from the state and then create or update the real dom. *)
    let update () =
        let vdom data =
            let vdom, set_title = vdom data in
            set_title ();
            vdom
        in
        match data.dom with
        | None ->
            let dom =
                Vdom.make
                    (dom_operations (dispatch data))
                    (vdom data)
            in
            data.dom <- Some dom;
            put_below_root data dom;

        | Some dom ->
            if data.dirty then begin
                let dom, created =
                    Vdom.update
                        (dom_operations (dispatch data))
                        (vdom data)
                        dom
                in
                if created then
                    put_below_root data dom;
                data.dom <- Some dom;
            end
    and cleanup () =
        data.dirty <- false
    in
    Assert_failure.attempt
        "Exception in 'update_dom' of Fmlib_browser"
        update
        cleanup;
    cleanup ();
    assert (not data.dirty)


let on_next_animation (f: float -> unit): unit =
    (* Call 'f' on next animation frame. *)
    Window.(on_next_animation f (get ()))



let rec animate (data: ('state, 'msg) data): float -> unit =
    fun _ ->
    update_dom data;
    assert (not data.dirty);
    on_next_animation (animate data)





(* Helper function to wrap user supplied functions
   ============================================================
 *)

let wrap_state_fun (str: string) (f: 's -> 'a) (state: 's): 'a =
    Assert_failure.attempt
        ("Exception in '" ^ str ^ "'")
        (fun () -> f state)
        (fun () -> ())


let wrap_view (view: 's -> 'a) (state: 's): 'a =
    wrap_state_fun "view" view state


let wrap_subscription (view: 's -> 'a) (state: 's): 'a =
    wrap_state_fun "subscriptioin" view state


let wrap_update (update: 's -> 'm -> 'a) (state: 's) (message: 'm): 'a =
    Assert_failure.attempt
        "Exception in 'update'"
        (fun () -> update state message)
        (fun () -> ())







(* Helper function to receive messages from javascript
   ============================================================
 *)

let receive_message
        (data: ('s, 'm) data option ref)
    : Base.Value.t
    =
    (* Handler for incoming messages from javascript. *)
    let open Base
    in
    let post (v: Value.t): Value.t =
        match !data with
        | None ->
            Main.log_string "receive_message: application not yet initialized";
            Value.null
        | Some data ->
            match data.subs with
            | None ->
                Main.log_string
                    "receive_message: subscriptions not yet initialized";
                Value.null
            | Some subs ->
                match subs.subs.message with
                | None ->
                    Main.log_string
                        "receive_message: event not subscribed";
                    Value.null
                | Some decode ->
                    match decode v with
                    | None ->
                        Main.log_string
                            "receive_message: cannot decode message from \
                             javascript";
                        Main.log_value v;
                        Value.null
                    | Some m ->
                        dispatch data m;
                        Value.null
    in
    Value.function1 post






(* Helper function to start an application (element or single page app)
   =======================================================================
 *)



let start_application
        (data: ('s, 'm) data)
        (command: 'm Command.t)
        (post: Base.Value.t -> unit): unit =
    update_subscriptions data;
    update_dom data;
    Command.execute post (dispatch_next data) command;
    on_next_animation (animate data)








(* Sandbox application
 * ============================================================
 *)

let make_sandbox
        (state: 's)
        (view:   ('s, 'm) view1)
        (sub:    'state -> 'msg Subscription.t)
        (update: ('s, 'm) update1)
        (_: 'a)
    : unit
    =
    (* This function is processed within the onload event of the browser
       window.
     *)

    (* Make the data for the application. *)
    let data = {
        state;
        dirty      = false;
        root       = Document.body (document ());
        dom        = None;
        subs       = None;
        operations =
            Sandbox (wrap_view view, wrap_subscription sub, wrap_update update)
    }
    in
    update_subscriptions data; (* Initial subscriptions *)
    update_dom data;           (* Initial dom. *)

    (* Processing for requestAnimationFrame *)
    on_next_animation (animate data)



let sandbox
        (state: 'state)
        (view: ('state, 'msg) view1)
        (update: ('state, 'msg) update1)
    : unit
    =
    Event_target.add
        "load"
        (make_sandbox state view (fun _ -> Subscription.none) update)
        Window.(event_target (get ()))



let sandbox_plus
        (state:  'state)
        (view:   ('state, 'msg) view1)
        (sub:    'state -> 'msg Subscription.t)
        (update: ('state, 'msg) update1)
    : unit
    =
    Event_target.add
        "load"
        (make_sandbox state view sub update)
        Window.(event_target (get ()))










(* Element application
 * ============================================================
 *)



let init_element
        (dataref: ('s, 'm) data option ref)
        (decode:  ('s * 'm Command.t) Base.Decode.t)
        (view:    ('s, 'm) view1)
        (sub:     's -> 'm Subscription.t)
        (update:  ('s, 'm) update2)
    : Base.Value.t
    =
    let open Base in
    let decode =
        let open Decode in
        let* post       = field "onMessage" _function in
        let* state, cmd = field "data" decode in
        let* element_id = field "element_id" string in
        return (element_id, state, cmd, fun v -> ignore (post [|v|]))
    in
    let init (v: Value.t): Value.t =
        match !dataref with
        | None -> begin
            match decode v with
            | None ->
                Main.log_string "cannot decode initialisation data";
                Main.log_value v;
                Value.null
            | Some (element_id, state, command, post) ->
                Event_target.add
                    "load"
                    (fun _ ->
                         match Dom.Document.find element_id (document ()) with
                         | None ->
                             Main.log_string
                                 ("Cannot find element " ^ element_id)
                         | Some root ->
                             let data = {
                                 state;
                                 dirty = false;
                                 root;
                                 dom   = None;
                                 subs  = None;
                                 operations =
                                     Element (
                                         wrap_view view,
                                         wrap_subscription sub,
                                         wrap_update update,
                                         post);
                             }
                             in
                             dataref := Some data;
                             start_application data command post
                    )
                    Window.(event_target (get ()));
                Value.null
        end
        | Some _ ->
            Main.log_string "application already initialized";
            Value.null
    in
    Value.function1 init




let element
        (name: string)
        (decode: ('s * 'm Command.t) Base.Decode.t)
        (view:   ('s, 'm) view1)
        (subs:   's -> 'm Subscription.t)
        (update: ('s, 'm) update2)
    : unit
    =
    let _ = decode, view, subs, update in
    let app = ref None in
    Base.Main.make_global
        name
        Base.Value.(
            _object
                [| "init", init_element app decode view subs update
                 ; "post", receive_message app
                |]
        )







(* Single Page Application
 * ============================================================
 *)





let init_application
        (dataref: ('s, 'm) data option ref)
        (decode:  ('s * 'm Command.t) Base.Decode.t)
        (view:    ('s, 'm) view2)
        (sub:     's -> 'm Subscription.t)
        (update:  ('s, 'm) update2)
    : Base.Value.t
    =
    let open Base in
    let decode =
        let open Decode in
        let* post       = field "onMessage" _function in
        let* state, cmd = field "data" decode in
        return (state, cmd, fun v -> ignore (post [|v|]))
    in
    let init (v: Value.t): Value.t =
        match !dataref with
        | None -> begin
            match decode v with
            | None ->
                Main.log_string "cannot decode initialisation data";
                Main.log_value v;
                Value.null
            | Some (state, command, post) ->
                Event_target.add
                    "load"
                    (fun _ ->
                         let data = {
                             state;
                             dirty = false;
                             root  = Document.body (document ());
                             dom   = None;
                             subs  = None;
                             operations =
                                 App (
                                     wrap_view view,
                                     wrap_subscription sub,
                                     wrap_update update,
                                     post);
                         }
                         in
                         dataref := Some data;
                         start_application data command post
                    )
                    Window.(event_target (get ()));
                Value.null
        end
        | Some _ ->
            Main.log_string "application already initialized";
            Value.null
    in
    Value.function1 init






let application
        (name: string)
        (decode: ('s * 'm Command.t) Base.Decode.t)
        (view:   ('s, 'm) view2)
        (subs:   's -> 'm Subscription.t)
        (update: ('s, 'm) update2)
    : unit
    =
    let app = ref None in
    Base.Main.make_global
        name
        Base.Value.(
            _object
                [| "init", init_application app decode view subs update
                 ; "post", receive_message app
                |]
        )






let basic_application
        (state:   's)
        (command: 'm Command.t)
        (view:    ('s, 'm) view2)
        (sub:     's -> 'm Subscription.t)
        (update:  ('s, 'm) update2)
    : unit
    =
    let post _ = ()
    in
    Event_target.add
        "load"
        (fun _ ->
             let data = {
                 state;
                 dirty = false;
                 root  = Document.body (document ());
                 dom   = None;
                 subs  = None;
                 operations =
                     App (
                         wrap_view view,
                         wrap_subscription sub,
                         wrap_update update,
                         post);
             }
             in
             start_application data command post
        )
        Window.(event_target (get ()));