package miaou-core

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file checkbox_widget.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
(******************************************************************************)
(*                                                                            *)
(* SPDX-License-Identifier: MIT                                               *)
(* Copyright (c) 2025 Nomadic Labs <contact@nomadic-labs.com>                 *)
(* Copyright (c) 2026 Mathias Bourgoin <mathias.bourgoin@atacama.tech>        *)
(*                                                                            *)
(******************************************************************************)

open Miaou_widgets_display.Widgets

type t = {
  label : string option;
  checked_ : bool;
  cancelled : bool;
  disabled : bool;
}

let create ?label ?(checked_ = false) ?(disabled = false) () =
  {label; checked_; cancelled = false; disabled}

let open_centered ?label ?(checked_ = false) ?disabled () =
  create ?label ~checked_ ?disabled ()

let render (t : t) ~focus =
  let box = if t.checked_ then "[X]" else "[ ]" in
  match t.label with
  | None -> box
  | Some l ->
      let lbl = if focus then bold l else l in
      box ^ " " ^ lbl

(** New unified key handler returning Key_event.result *)
let on_key (t : t) ~key =
  if t.disabled then (t, Miaou_interfaces.Key_event.Bubble)
  else
    match key with
    | " " | "Space" | "Enter" ->
        ({t with checked_ = not t.checked_}, Miaou_interfaces.Key_event.Handled)
    | "Esc" | "Escape" ->
        ({t with cancelled = true}, Miaou_interfaces.Key_event.Handled)
    | key ->
        (* Mouse click toggles checkbox *)
        if Miaou_helpers.Mouse.is_click key then
          ( {t with checked_ = not t.checked_},
            Miaou_interfaces.Key_event.Handled )
        else (t, Miaou_interfaces.Key_event.Bubble)

(** @deprecated Use [on_key] instead. Returns just state for backward compat. *)
let handle_key (t : t) ~key =
  let t', _ = on_key t ~key in
  t'

let is_checked t = t.checked_

let set_checked t v = {t with checked_ = v}

let is_cancelled t = t.cancelled

let reset_cancelled t = {t with cancelled = false}

let () =
  Miaou_registry.register ~name:"checkbox" ~mli:[%blob "checkbox_widget.mli"] ()