package miaou-core

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

Source file switch_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
(******************************************************************************)
(*                                                                            *)
(* 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; on : bool; cancelled : bool; disabled : bool}

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

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

let render (t : t) ~focus =
  let core = if t.on then "[ ON ]" else "[ OFF ]" in
  let sw = if t.on then green core else dim core in
  match t.label with
  | None -> sw
  | Some l ->
      let lbl = if focus then bold l else l in
      lbl ^ ": " ^ sw

(** 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 on = not t.on}, Miaou_interfaces.Key_event.Handled)
    | "Esc" | "Escape" ->
        ({t with cancelled = true}, Miaou_interfaces.Key_event.Handled)
    | key ->
        (* Mouse click toggles switch *)
        if Miaou_helpers.Mouse.is_click key then
          ({t with on = not t.on}, 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_on t = t.on

let set_on t v = {t with on = v}

let is_cancelled t = t.cancelled

let reset_cancelled t = {t with cancelled = false}

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