Source file skyline_tree_v1.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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
open! Core
open! Bonsai_web
open! Bonsai.Let_syntax
module Layout = Layout

module Decoration = struct
  type t =
    | Primary
    | Foreground of Skyline_theme_v1.Color.t
    | Background of Skyline_theme_v1.Color.t
    | Secondary
    | Inherit
  [@@deriving sexp_of]
end

module Path = struct
  type t = string Nonempty_list.t [@@deriving sexp, compare]

  let to_string path = String.concat ~sep:"/" (Nonempty_list.to_list path)
  let of_string path = Nonempty_list.of_list_exn (String.split path ~on:'/')

  let string_length path =
    Nonempty_list.foldi path ~init:0 ~f:(fun idx accum elem ->
      if idx = 0 then String.length elem else accum + 1 + String.length elem)
  ;;

  type comparator_witness = String.comparator_witness Nonempty_list.comparator_witness

  let comparator = Nonempty_list.comparator String.comparator

  include functor Comparable.Make_using_comparator

  module Segment = struct
    include Path_segment

    let path_elements { segments; _ } = segments

    let component ?(should_handle_indentation = true) segment =
      component
        { segment with
          indent_tree_leaf = should_handle_indentation && segment.indent_tree_leaf
        }
    ;;
  end
end

(* Helper function to apply [component]'s [?to_item_text] to a path, which changes the
   search/default display text of leaf nodes *)
let apply_item_text_to_path ~to_item_text (path : Path.t) item : Path.t =
  Nonempty_list.append' (Nonempty_list.drop_last path) [ to_item_text path item ]
;;

module Branch = struct
  type 'a t =
    | Parent of Path.t
    | Empty of Path.t
    | Leaf_parent of Path.t * 'a
    | Leaf of Path.t * 'a

  let item = function
    | Parent _ | Empty _ -> None
    | Leaf_parent (_, item) | Leaf (_, item) -> Some item
  ;;
end

module Style = struct
  include
    [%css
    stylesheet
      ~dont_hash_prefixes:[ "--skyline" ]
      {|
        .container {
          box-sizing: border-box;
          width: 100%;
        }

        .row {
          width: 100%;
          box-sizing: border-box;
          min-height: 24px;
          display: flex;
          flex-direction: row;
          flex-wrap: wrap;
          align-items: center;
          justify-content: start;
          column-gap: 8px;
          row-gap: 2px;
          margin: 0;
          padding: 0 4px;

          font-family: var(--skyline-font-sans, sans-serif);
          line-height: 1.2;
          text-align: left;

          border-width: 0;
          border-style: solid;
          border-radius: 4px;
          background-color: inherit;

          -webkit-appearance: button;
          appearance: button;
          outline: none;
        }

        .row:nth-child(odd) {
          background-color: var(--alternate-background-color);
        }

        .row:hover:not([aria-disabled="true"]),
        .row.highlighted {
          background-color: var(--skyline-color-border);
        }

        /* Disabled rows have no [tabindex], so they can never match [:focus]. */
        .row:focus {
          outline-color: var(--skyline-color-accent);
          outline-width: 1px;
          outline-style: solid;
          outline-offset: -1px;
        }

        .chevron {
          box-sizing: border-box;
          width: 16px;
          height: 16px;
          display: flex;
          margin: 0;
          padding: 0;

          border: none;
          border-radius: 2px;
          color: var(--skyline-color-primary, inherit);
          background-color: inherit;
        }
        .row:not([aria-disabled="true"]) .chevron:hover {
          background-color: var(--skyline-color-border);
        }

        .path-indent {
          box-sizing: border-box;
          min-height: 24px;
          width: var(--width);
          padding: 0;
          margin: 0;
          flex-shrink: 0;
          background-image: repeating-linear-gradient(
            90deg,
            transparent 0px,
            transparent 11px,
            #9993 11px,
            #9993 12px,
            transparent 12px
          );
          background-size: 12px;
        }

        .row-flex-grow {
          flex-grow: 1;
        }
      |}]

  let row ~alternating_row_background ~disabled =
    let alternate_background_color =
      if alternating_row_background
      then Skyline_theme_v1.surface |> Css_gen.Color.to_string_css
      else "inherit"
    in
    let enabled_or_disabled =
      (* Only enabled rows get a [tabindex], as disabled rows shouldn't t take focus (not
         even on click). [Keyboard_navigation] relies on the presence of [tabindex] to
         move focus with arrow keys.

         [aria-disabled] rather than the native [disabled] attribute so that pointer
         events (e.g. tooltips explaining why a row is disabled) still work. Assistive
         tools and e.g. vimium look for [aria-disabled]. *)
      if disabled
      then [ Vdom.Attr.create "aria-disabled" "true"; Vdom.Attr.role "button" ]
      else [ Vdom.Attr.tabindex 0 ]
    in
    Vdom.Attr.many
      (enabled_or_disabled @ [ Variables.set ~alternate_background_color (); row ])
  ;;

  let path_indent parents =
    let width = Css_gen.Length.to_string_css (`Px (1 + (12 * parents))) in
    Vdom.Attr.many [ Variables.set ~width (); path_indent ]
  ;;
end

let tree_row_path_segment ~matching_indices ~display_path row : Path.Segment.t =
  let _, intent, branch = Bonsai_web_contrib_tree_table.Row.data row in
  let segments =
    List.fold_until
      (Bonsai_web_contrib_tree_table.Row.ancestors row)
      ~init:[ Nonempty_list.last display_path ]
      ~f:(fun acc (_, (_, _, branch)) ->
        match (branch : _ Branch.t) with
        | Empty path -> Continue (Nonempty_list.last path :: acc)
        | Parent _ | Leaf_parent _ | Leaf _ -> Stop acc)
      ~finish:Fn.id
    |> Nonempty_list.of_list_exn
  in
  let parent_path_length =
    Bonsai_web_contrib_tree_table.Row.ancestors row
    |> List.hd
    |> Option.value_map ~f:(fun (key, _) -> Path.string_length key + 1) ~default:0
  in
  let indent_tree_leaf =
    match branch with
    | Leaf _ -> true
    | Empty _ | Parent _ | Leaf_parent _ -> false
  in
  { layout = Tree
  ; parent_path_length
  ; matching_indices
  ; intent
  ; segments
  ; indent_tree_leaf
  }
;;

let list_row_path_segment ~decoration ~matching_indices key : Path.Segment.t =
  let intent =
    match (decoration : Decoration.t) with
    | Primary | Secondary | Inherit -> `Primary `None
    | Foreground intent -> `Primary (`Foreground intent)
    | Background intent -> `Primary (`Background intent)
  in
  { layout = List
  ; parent_path_length = 0
  ; matching_indices
  ; intent
  ; segments = key
  ; indent_tree_leaf = false
  }
;;

let is_child_of_collapsed ~collapsed_paths row =
  Bonsai_web_contrib_tree_table.Row.ancestors row
  |> List.exists ~f:(fun (key, (_, _, branch)) ->
    match branch with
    | Branch.Empty _ ->
      (* If the parent is empty, we don't care that it's been collapsed since it's never
         rendered. *)
      false
    | Parent _ | Leaf_parent _ | Leaf _ -> Set.mem collapsed_paths key)
;;

let tree_row_contents ~collapsed ~disabled ~toggle_collapsed ~content key row =
  let indent =
    let non_empty_parents =
      List.count
        (Bonsai_web_contrib_tree_table.Row.ancestors row)
        ~f:(fun (_, (_, _, branch)) ->
          match (branch : _ Branch.t) with
          | Parent _ | Leaf_parent _ | Leaf _ -> true
          | Empty _ -> false)
    in
    Vdom.Node.div ~attrs:[ Style.path_indent non_empty_parents ] []
  in
  let toggle =
    match collapsed with
    | Some collapsed ->
      let attrs =
        if disabled
        then [ Style.chevron ]
        else
          [ Style.chevron
          ; Vdom.Attr.on_click (fun event ->
              Js_of_ocaml.Dom_html.stopPropagation event;
              Js_of_ocaml.Dom.preventDefault event;
              toggle_collapsed key)
          ]
      in
      (if disabled then Vdom.Node.div else Vdom.Node.button)
        ~attrs
        [ Codicons.svg (if collapsed then Chevron_right else Chevron_down) ]
    | None -> None
  in
  Skyline_flex_v1.row
    ~gap:(`Px 4)
    ~align:Stretch
    ~justify:Flex_start
    ~attrs:[ Style.row_flex_grow ]
    [ indent
    ; Skyline_flex_v1.row
        ~gap:(`Px 4)
        ~align:Center
        ~justify:Flex_start
        ~attrs:[ Style.row_flex_grow ]
        [ toggle; content ]
    ]
;;

let tree_row
  ~collapsed_paths
  ~toggle_collapsed
  ~search
  ~to_item_text
  ~on_click
  ~disabled
  ~on_contextmenu
  ~highlight
  ~render_segment
  ~render_item
  ~alternating_row_background
  ~disable_keyboard_navigation
  key
  row
  graph
  =
  let branch : _ Branch.t Bonsai.t =
    let%arr collapsed_paths and key and row in
    match Bonsai_web_contrib_tree_table.Row.data row with
    | _, _, (Branch.Empty _ as empty) -> empty
    | _, _, branch ->
      if is_child_of_collapsed ~collapsed_paths row then Empty key else branch
  in
  let display_path =
    let%arr key and branch in
    match to_item_text, (branch : _ Branch.t) with
    | None, _ | Some _, (Parent _ | Empty _) -> key
    | Some to_item_text, (Leaf_parent (_, item) | Leaf (_, item)) ->
      apply_item_text_to_path ~to_item_text key item
  in
  let matching_indices =
    let%arr search and display_path in
    let%bind.Option search in
    Fuzzy_search.matching_indices search ~item:(Path.to_string display_path)
  in
  let highlight =
    let%arr key
    and highlight = Bonsai.transpose_opt highlight in
    Option.value_map highlight ~f:(Path.equal key) ~default:false
  in
  let container ~disabled ~on_click ~on_contextmenu ~highlight contents =
    let attrs =
      [ Style.row ~alternating_row_background ~disabled
      ; (if highlight then Style.highlighted else Vdom.Attr.empty)
      ; (if disabled || disable_keyboard_navigation
         then Vdom.Attr.empty
         else Keyboard_navigation.row_attr ~on_enter:on_click)
      ; (if disabled then Vdom.Attr.empty else Vdom.Attr.on_contextmenu on_contextmenu)
      ]
    in
    match disabled, on_click with
    | true, _ -> Vdom.Node.div ~attrs contents
    | false, Effect.Open { url; target } ->
      Vdom.Node.a
        ~attrs:
          (Vdom.Attr.href url
           :: Vdom.Attr.target (Effect.Open_url_target.to_target target)
           :: attrs)
        contents
    | false, _ ->
      Vdom.Node.button ~attrs:(Vdom.Attr.on_click (const on_click) :: attrs) contents
  in
  match%sub branch with
  | Empty _ -> Bonsai.return None
  | Parent key ->
    let%arr content =
      render_segment
        key
        (let%arr matching_indices and display_path and row in
         tree_row_path_segment ~matching_indices ~display_path row)
        graph
    and collapsed_paths
    and toggle_collapsed
    and on_click
    and disabled
    and on_contextmenu
    and highlight
    and key
    and row in
    let disabled = disabled key None in
    container
      ~disabled
      ~on_click:(on_click key None)
      ~on_contextmenu:(fun event -> on_contextmenu event key None)
      ~highlight
      [ tree_row_contents
          ~collapsed:(Some (Set.mem collapsed_paths key))
          ~disabled
          ~toggle_collapsed
          ~content
          key
          row
      ]
    |> Option.return
  | Leaf_parent (key, item) ->
    let%arr content =
      render_item
        key
        (let%arr matching_indices and display_path and row in
         tree_row_path_segment ~matching_indices ~display_path row)
        item
        graph
    and collapsed_paths
    and toggle_collapsed
    and on_click
    and disabled
    and on_contextmenu
    and highlight
    and key
    and item
    and row in
    let disabled = disabled key (Some item) in
    container
      ~disabled
      ~on_click:(on_click key (Some item))
      ~on_contextmenu:(fun event -> on_contextmenu event key (Some item))
      ~highlight
      [ tree_row_contents
          ~collapsed:(Some (Set.mem collapsed_paths key))
          ~disabled
          ~toggle_collapsed
          ~content
          key
          row
      ]
    |> Option.return
  | Leaf (key, item) ->
    let%arr content =
      render_item
        key
        (let%arr matching_indices and display_path and row in
         tree_row_path_segment ~matching_indices ~display_path row)
        item
        graph
    and toggle_collapsed
    and on_click
    and disabled
    and on_contextmenu
    and highlight
    and key
    and item
    and row in
    let disabled = disabled key (Some item) in
    container
      ~disabled
      ~on_click:(on_click key (Some item))
      ~on_contextmenu:(fun event -> on_contextmenu event key (Some item))
      ~highlight
      [ tree_row_contents ~collapsed:None ~disabled ~toggle_collapsed ~content key row ]
    |> Option.return
;;

let list_row
  ~search
  ~to_item_text
  ~highlight
  ~decoration
  ~render_item
  ~on_click
  ~disabled
  ~on_contextmenu
  ~alternating_row_background
  ~disable_keyboard_navigation
  key
  item
  graph
  =
  let display_path =
    let%arr key and item in
    Option.value_map to_item_text ~default:key ~f:(fun to_item_text ->
      apply_item_text_to_path ~to_item_text key item)
  in
  let matching_indices =
    let%arr search and display_path in
    let%bind.Option search in
    Fuzzy_search.matching_indices search ~item:(Path.to_string display_path)
  in
  let%arr on_click
  and disabled
  and on_contextmenu
  and highlight = Bonsai.transpose_opt highlight
  and content =
    render_item
      key
      (let%arr matching_indices and display_path and key and item in
       let decoration = decoration key (Some item) in
       list_row_path_segment ~decoration ~matching_indices display_path)
      item
      graph
  and key
  and item in
  let highlight =
    match highlight with
    | Some key' when Path.equal key' key -> Style.highlighted
    | _ -> Vdom.Attr.empty
  in
  let disabled = disabled key (Some item) in
  let on_click = on_click key (Some item) |> Option.value ~default:Effect.Ignore in
  let attrs =
    [ Style.row ~alternating_row_background ~disabled
    ; highlight
    ; (if disabled then Vdom.Attr.empty else Vdom.Attr.on_click (const on_click))
    ; (if disabled
       then Vdom.Attr.empty
       else Vdom.Attr.on_contextmenu (fun event -> on_contextmenu event key (Some item)))
    ; (if disabled || disable_keyboard_navigation
       then Vdom.Attr.empty
       else Keyboard_navigation.row_attr ~on_enter:on_click)
    ]
  in
  (if disabled then Vdom.Node.div else Vdom.Node.button) ~attrs [ content ]
;;

let tree_of_items' ~to_item_text filter_and_items_by_path =
  let filter = Incr.map filter_and_items_by_path ~f:fst in
  let items_by_path = Incr.map filter_and_items_by_path ~f:snd in
  let add_item_to_tree ~filter ~key ~item tree =
    match filter with
    | Some query ->
      let search_path =
        match to_item_text with
        | None -> key
        | Some to_item_text -> apply_item_text_to_path ~to_item_text key item
      in
      let search_string = Path.to_string search_path in
      let score = Fuzzy_search.score query ~item:search_string in
      if score > 0
      then Bonsai_web_contrib_tree_table.Tree.set tree ~key ~data:(score, item)
      else tree
    | None -> Bonsai_web_contrib_tree_table.Tree.set tree ~key ~data:(0, item)
  in
  let build_non_incr ~filter items_by_path =
    Map.fold
      items_by_path
      ~init:(Bonsai_web_contrib_tree_table.Tree.empty (module String))
      ~f:(fun ~key ~data tree -> add_item_to_tree ~filter ~key ~item:data tree)
  in
  Incr.Map.unordered_fold_with_extra
    ~init:(Bonsai_web_contrib_tree_table.Tree.empty (module String))
    ~add:(fun ~key ~data tree filter -> add_item_to_tree ~filter ~key ~item:data tree)
    ~remove:(fun ~key ~data:_ tree _filter ->
      Bonsai_web_contrib_tree_table.Tree.remove tree key)
    ~extra_changed:(fun ~old_extra:_ ~new_extra:filter ~input _ ->
      build_non_incr ~filter input)
    items_by_path
    filter
;;

type child_intent =
  { error : int
  ; warning : int
  ; success : int
  ; accent : int
  }

let tree_of_items
  ~merge_empty_paths
  ~decoration
  ~has_external_children
  ~search
  ~to_item_text
  items_by_path
  graph
  =
  let how_to_map =
    let score_of_branch branch =
      let score, _, _ = Bonsai_web_contrib_tree_table.Tree.data branch in
      score
    in
    let intent_of_color color =
      if phys_equal color Skyline_theme_v1.error
      then Some `Error
      else if phys_equal color Skyline_theme_v1.warning
      then Some `Warning
      else if phys_equal color Skyline_theme_v1.success
      then Some `Success
      else if phys_equal color Skyline_theme_v1.accent
      then Some `Accent
      else None
    in
    let intent_of_branch branch : _ option =
      let _, intent, _ = Bonsai_web_contrib_tree_table.Tree.data branch in
      match intent with
      | `Primary `None | `Secondary None -> None
      | `Primary (`Foreground intent) | `Primary (`Background intent) ->
        intent_of_color intent
      | `Secondary (Some intent) -> intent_of_color intent
    in
    let counts_to_intent { error; warning; success; accent } : _ option =
      if error > 0
      then Some Skyline_theme_v1.error
      else if warning > 0
      then Some Skyline_theme_v1.warning
      else if success > 0
      then Some Skyline_theme_v1.success
      else if accent > 0
      then Some Skyline_theme_v1.accent
      else None
    in
    let common ~children_total_score ~children_intent ~has_leaf_child ~key ~data =
      let intent =
        match decoration key (Option.map data ~f:snd) with
        | Decoration.Primary -> `Primary `None
        | Secondary -> `Secondary None
        | Foreground intent -> `Primary (`Foreground intent)
        | Background intent -> `Primary (`Background intent)
        | Inherit -> `Secondary children_intent
      in
      match data, has_leaf_child with
      | Some (score, item), `No_children ->
        if has_external_children key item
        then
          (* If the children are external we can't score them. *)
          score, intent, Branch.Leaf_parent (key, item)
        else score, intent, Branch.Leaf (key, item)
      | Some (score, item), _ ->
        score + children_total_score, intent, Leaf_parent (key, item)
      | None, `Single_non_leaf_child ->
        (* Mark paths with a single non leaf child as empty if we want them to be elided
           (i.e. collapsed into a single branch) in the rendered tree. *)
        children_total_score, intent, if merge_empty_paths then Empty key else Parent key
      | None, _ -> children_total_score, intent, Parent key
    in
    let has_leaf_child children =
      if Map.length children <= 1
      then (
        match Map.data children with
        | [ branch ] ->
          let _, _, branch = Bonsai_web_contrib_tree_table.Tree.data branch in
          (match branch with
           | Branch.Leaf _ | Leaf_parent _ -> `Single_leaf_child
           | Parent _ | Empty _ -> `Single_non_leaf_child)
        | _ -> `No_children)
      else `Many_children
    in
    let incremental ~key ~data ~children =
      let%map.Incr children_total_score =
        Incr_map.sum children (module Int) ~f:score_of_branch
      and has_leaf_child = Incr.map children ~f:has_leaf_child
      and children_intent =
        Incr_map.unordered_fold
          children
          ~init:{ error = 0; warning = 0; success = 0; accent = 0 }
          ~add:(fun ~key:_ ~data:branch count ->
            match intent_of_branch branch with
            | Some `Error -> { count with error = count.error + 1 }
            | Some `Warning -> { count with warning = count.warning + 1 }
            | Some `Success -> { count with success = count.success + 1 }
            | Some `Accent -> { count with accent = count.accent + 1 }
            | None -> count)
          ~remove:(fun ~key:_ ~data:branch count ->
            match intent_of_branch branch with
            | Some `Error -> { count with error = count.error - 1 }
            | Some `Warning -> { count with warning = count.warning - 1 }
            | Some `Success -> { count with success = count.success - 1 }
            | Some `Accent -> { count with accent = count.accent - 1 }
            | None -> count)
      and data in
      common
        ~children_total_score
        ~has_leaf_child
        ~children_intent:(counts_to_intent children_intent)
        ~key
        ~data
    in
    let nonincremental ~key ~data ~children =
      let children_total_score = Map.sum (module Int) children ~f:score_of_branch in
      let children_intent =
        Map.fold
          children
          ~init:{ error = 0; warning = 0; success = 0; accent = 0 }
          ~f:(fun ~key:_ ~data:branch count ->
            match intent_of_branch branch with
            | Some `Error -> { count with error = count.error + 1 }
            | Some `Warning -> { count with warning = count.warning + 1 }
            | Some `Success -> { count with success = count.success + 1 }
            | Some `Accent -> { count with accent = count.accent + 1 }
            | None -> count)
      in
      common
        ~children_total_score
        ~has_leaf_child:(has_leaf_child children)
        ~children_intent:(counts_to_intent children_intent)
        ~key
        ~data
    in
    Bonsai_web_contrib_tree_table.How_to_map.incrementally_with_nonincremental_fallback
      ~incremental
      ~nonincremental
      ()
  in
  Bonsai.Incr.compute
    (Bonsai.both search items_by_path)
    ~f:(fun filter_and_items_by_path ->
      tree_of_items' ~to_item_text filter_and_items_by_path
      |> Bonsai_web_contrib_tree_table.map ~how_to_map
      |> Bonsai_web_contrib_tree_table.tree_to_map ~how_to_deal_with_nones:Preserve)
    graph
;;

let compare_tree_rows ~compare =
  let key = Bonsai_web_contrib_tree_table.Row.key in
  let compare_row = Bonsai_web_contrib_tree_table.Row.lift_comparison compare in
  let compare =
    Bonsai_web_contrib_tree_table.Row.sort_override Path.compare compare_row
  in
  fun lhs rhs -> compare (key lhs, lhs) (key rhs, rhs)
;;

let compare_tree_rows_by_score ~compare_key =
  let compare (_, (score, _, _)) (_, (score', _, _)) =
    (* Ascending here translates to best total score first in the list. *)
    Int.ascending score score'
  in
  let compare =
    Comparable.lexicographic [ compare; Comparable.lift compare_key ~f:(fun (k, _) -> k) ]
  in
  compare_tree_rows ~compare
;;

let compare_tree_rows_by_item ~compare_item ~compare_key =
  let compare (key, (_, _, branch)) (key', (_, _, branch')) =
    match Branch.item branch, Branch.item branch' with
    | Some item, Some item' ->
      let cmp = compare_item item item' in
      if cmp = 0 then compare_key key key' else cmp
    | _ -> compare_key key key'
  in
  compare_tree_rows ~compare
;;

let collapsed_state graph =
  let collapsed, set_collapsed = Bonsai.state' Path.Set.empty graph in
  let toggle =
    let%arr set_collapsed in
    fun path ->
      set_collapsed (fun collapsed ->
        if Set.mem collapsed path
        then Set.remove collapsed path
        else Set.add collapsed path)
  in
  collapsed, toggle
;;

let component
  (type a)
  ?collapsed:external_collapsed_state
  ?(layout = Bonsai.return Layout.Tree)
  ?(merge_empty_paths = true)
  ?compare_path
  ?compare
  ?(filter = Bonsai.return "")
  ?to_item_text
  ?on_click
  ?(disabled = Bonsai.return (fun _ _ -> false))
  ?on_contextmenu
  ?highlight
  ?(decoration =
    fun _ data : Decoration.t -> if Option.is_some data then Primary else Secondary)
  ?(alternating_row_background = false)
  ?(disable_keyboard_navigation = false)
  ?(has_external_children = fun _ _ -> false)
  ?segment:(render_segment =
      fun _ segment (local_ _graph) ->
        let%arr segment in
        Path.Segment.component segment)
  ?item:(render_item = fun path segment _ graph -> render_segment path segment graph)
  (items_by_path : a Path.Map.t Bonsai.t)
  (local_ graph)
  =
  let collapsed_paths, toggle_collapsed =
    match external_collapsed_state with
    | None -> collapsed_state graph
    | Some state -> state
  in
  let on_contextmenu =
    match on_contextmenu with
    | None -> return (fun _ _ _ -> Effect.Ignore)
    | Some on_contextmenu ->
      let menu, set_menu = Bonsai.state [] graph in
      let%arr on_contextmenu
      and set_menu
      and show_menu = Skyline_context_menu_v1.manual_position menu graph in
      fun event path item ->
        (match%bind.Effect on_contextmenu path item with
         | [] -> Effect.Ignore
         | _ :: _ as menu ->
           Js_of_ocaml.Dom.preventDefault event;
           Js_of_ocaml.Dom_html.stopPropagation event;
           let get num_opt ~default =
             Js_of_ocaml.Js.Optdef.to_option num_opt
             |> Option.value ~default
             |> Js_of_ocaml.Js.to_float
           in
           let top = get event##.pageY ~default:event##.clientY in
           let left = get event##.pageX ~default:event##.clientX in
           let%bind.Effect () = set_menu menu in
           show_menu ~top ~left)
  in
  let search =
    let%arr filter in
    if String.is_empty (String.strip filter)
    then None
    else Some (Fuzzy_search.Query.create filter)
  in
  match%sub layout with
  | Tree ->
    let tree =
      let on_click =
        (* If there is [Some on_click] and [on_click path item] resolves to [Some effect],
           then attach the effect to the row, which means you have to click exactly the
           little chevron to [toggle_collapsed]. Else [toggle_collapsed path] when
           clicking any part of the row. *)
        match on_click with
        | Some on_click ->
          let%arr on_click and toggle_collapsed in
          fun path elt ->
            (match on_click path elt with
             | None -> toggle_collapsed path
             | Some on_click -> on_click)
        | None ->
          let%arr toggle_collapsed in
          fun path _ -> toggle_collapsed path
      in
      Bonsai.assoc
        (module Path)
        (tree_of_items
           ~merge_empty_paths
           ~search
           ~to_item_text
           ~decoration
           ~has_external_children
           items_by_path
           graph)
        ~f:(fun key row (local_ graph) ->
          let%arr row
          and view =
            tree_row
              ~collapsed_paths
              ~toggle_collapsed
              ~search
              ~to_item_text
              ~on_click
              ~disabled
              ~on_contextmenu
              ~highlight
              ~render_segment
              ~render_item
              ~alternating_row_background
              ~disable_keyboard_navigation
              key
              row
              graph
          in
          row, view)
        graph
    in
    (match%sub search with
     | Some _ ->
       let%arr tree in
       let sorted_rows =
         let compare_key = Option.value compare_path ~default:Path.compare in
         let compare = compare_tree_rows_by_score ~compare_key in
         List.filter_map (Map.data tree) ~f:(function
           | row, Some view -> Some (row, view)
           | _, None -> None)
         |> List.sort ~compare:(fun (row, _) (row', _) -> compare row row')
         |> List.map ~f:snd
       in
       if List.is_empty sorted_rows
       then Skyline_placeholder_v1.component ~icon:Search_stop "No matching items"
       else View.vbox ~attrs:[ Style.container ] sorted_rows
     | None ->
       let%arr tree in
       let rows =
         let custom_compare =
           match compare with
           | None ->
             let%map.Option compare_path in
             compare_tree_rows_by_item
               ~compare_item:(fun _ _ -> 0)
               ~compare_key:compare_path
           | Some compare_item ->
             let compare_key = Option.value compare_path ~default:Path.compare in
             Some (compare_tree_rows_by_item ~compare_item ~compare_key)
         in
         match custom_compare with
         | None -> List.filter_map (Map.data tree) ~f:snd
         | Some compare ->
           List.filter_map (Map.data tree) ~f:(function
             | row, Some view -> Some (row, view)
             | _, None -> None)
           |> List.sort ~compare:(fun (row, _) (row', _) -> compare row row')
           |> List.map ~f:snd
       in
       View.vbox ~attrs:[ Style.container ] rows)
  | List ->
    let list =
      let on_click =
        match on_click with
        | Some on_click -> on_click
        | None -> Bonsai.return (fun _ _ -> None)
      in
      Bonsai.assoc
        (module Path)
        items_by_path
        ~f:(fun key item graph ->
          Bonsai.both
            (list_row
               ~search
               ~to_item_text
               ~highlight
               ~decoration
               ~render_item
               ~on_click
               ~disabled
               ~on_contextmenu
               ~alternating_row_background
               ~disable_keyboard_navigation
               key
               item
               graph)
            item)
        graph
    in
    (match%sub search with
     | Some query ->
       let%arr query and list in
       let compare =
         match compare with
         | Some compare ->
           (* If we are searching, the custom compare function should be a tiebreaker. *)
           fun (score1, (_, x)) (score2, (_, y)) ->
           (match [%compare: int] score1 score2 with
            | 0 -> compare x y
            | r -> r)
         | None -> [%compare: int * _]
       in
       let sorted_rows =
         List.filter_map (Map.to_alist list) ~f:(fun (key, (view, item)) ->
           let search_path =
             match to_item_text with
             | None -> key
             | Some to_item_text -> apply_item_text_to_path ~to_item_text key item
           in
           let%map.Option score =
             Fuzzy_search.score_opt query ~item:(Path.to_string search_path)
           in
           score, (view, item))
         |> List.sort ~compare
         |> List.map ~f:snd
         |> List.map ~f:fst
       in
       View.vbox
         ~attrs:[ Style.container ]
         (if List.is_empty sorted_rows
          then [ Skyline_placeholder_v1.component ~icon:Search_stop "No matching items" ]
          else sorted_rows)
     | None ->
       let%arr list in
       let sorted_rows =
         match compare with
         | None -> Map.data list
         | Some compare ->
           let compare (_, x) (_, y) = compare x y in
           List.sort ~compare (Map.data list)
       in
       View.vbox
         ~attrs:[ Style.container ]
         ~cross_axis_alignment:Stretch
         (List.map ~f:fst sorted_rows))
;;