stitch

Note taking for messy minimalists

git clone git://mccd.space/stitch

input_prompt.ml (2223B)

      1 module Grep = Grep
      2 module Common = Common
      3 open Notty
      4 
      5 type state =
      6   { (* Pre = before the cursor, post = after the cursor *)
      7     user_input_pre : string
      8   ; user_input_post : string
      9   ; on_enter : string -> unit
     10   ; on_cancel : unit -> unit
     11   ; prompt : string
     12   ; screen : I.t
     13   }
     14 
     15 let rec render
     16   t
     17   ({ user_input_pre; user_input_post; on_enter; on_cancel; prompt; screen } as state)
     18   =
     19   let size_x, size_y = Common.Term.size t in
     20   Common.Term.cursor
     21     t
     22     (Some (String.length user_input_pre + String.length prompt + 3, size_y));
     23   let img =
     24     let open I in
     25     I.strf " %s " ~attr:(A.st A.reverse) prompt
     26     <|> I.strf " %s%s%s" user_input_pre user_input_post (String.make size_x ' ')
     27     |> I.pad ~l:0 ~t:(size_y - 1)
     28     </> screen
     29   in
     30   Common.Term.image t img;
     31   match Common.Term.event t with
     32   | `End | `Key (`Escape, []) | `Key (`ASCII 'G', [ `Ctrl ]) | `Key (`ASCII 'C', [ `Ctrl ])
     33     -> on_cancel ()
     34   | `Key (`Enter, []) -> on_enter (user_input_pre ^ user_input_post)
     35   | `Key (`Backspace, []) ->
     36     if String.equal "" (user_input_pre ^ user_input_post)
     37     then on_cancel ()
     38     else (
     39       let state =
     40         { state with
     41           user_input_pre =
     42             String.sub user_input_pre 0 (max (String.length user_input_pre - 1) 0)
     43         }
     44       in
     45       render t state)
     46   | `Resize _ -> render t state
     47   | `Key (`Arrow `Left, []) ->
     48     if user_input_pre = ""
     49     then render t state
     50     else (
     51       let char_to_move = Str.last_chars user_input_pre 1
     52       and new_pre = Str.string_before user_input_pre (String.length user_input_pre - 1) in
     53       let new_post = char_to_move ^ user_input_post in
     54       render t { state with user_input_pre = new_pre; user_input_post = new_post })
     55   | `Key (`Arrow `Right, []) ->
     56     if user_input_post = ""
     57     then render t state
     58     else (
     59       let char_to_move = Str.first_chars user_input_post 1
     60       and new_post = Str.string_after user_input_post 1 in
     61       let new_pre = user_input_pre ^ char_to_move in
     62       render t { state with user_input_pre = new_pre; user_input_post = new_post })
     63   | `Key (`ASCII c, []) ->
     64     let state = { state with user_input_pre = user_input_pre ^ String.make 1 c } in
     65     render t state
     66   | _ -> render t state