6 Input🔗ℹ

read-event returns an event. The common types are:

Event

 

Contents

key-event

 

a key: @racket[key] is a character or a symbol such as @racket['up], and @racket[mods] holds modifiers

paste-event

 

paste: raw bytes and text

mouse-event

 

mouse: action, button, and coordinates

resize-event

 

window size: rows and columns

Read modifiers with mods-ctrl?, mods-alt?, and mods-shift?.

Applications rarely need to write match by hand; build-input is simpler:

(define handler
  (build-input
   #:text (λ (s) (insert-text s))
   #:enter (λ () (submit!))
   #:backspace (λ () (delete-back!))
   #:up (λ () (move-up!))
   #:escape (λ () (set! running? #f))))

#:text receives printable characters and pasted text; #:enter, #:up, and similar keywords are shortcuts for unmodified keys; everything else goes to #:key. Use loop-input/stop for the event loop:

(loop-input/stop (not running?) handler)

Here is a small input box:

#lang racket
 
(require tui
         racket/list
         racket/string)
 
(define text "")
(define submitted '())
(define running? #t)
 
(define (draw)
  (define parts
    (append
     (list
      format-screen-clear
      (format-cursor-move 2 3)
      (format-styled 'title "Input")
      (format-cursor-move 4 3)
      (format-styled 'heading "Current:")
      (format-cursor-move 5 3)
      (format-styled 'input-focus (string-append "> " text " ▌"))
      (format-cursor-move 7 3)
      (format-styled 'heading "Submitted:"))
     (for/list ([line (in-list submitted)] [i (in-naturals)])
       (bytes-append
        (format-cursor-move (+ 8 i) 3)
        (format-styled 'list-item (format "~a. ~a" (add1 i) line))))
     (list
      (format-cursor-move 16 3)
      (format-styled 'info "Enter submit · Backspace delete · Esc quit"))))
  (put-bytes (apply bytes-append parts)))
 
(define handler
  (build-input
   #:text (λ (s) (set! text (string-append text s)))
   #:backspace (λ ()
                 (when (positive? (string-length text))
                   (set! text (substring text 0 (sub1 (string-length text))))))
   #:enter (λ ()
             (unless (string=? text "")
               (set! submitted (cons text submitted))
               (set! text "")))
   #:escape (λ () (set! running? #f))))
 
(define (handle ev)
  (handler ev)
  (draw))
 
(with-tui
 (λ ()
   (cursor-hide)
   (draw)
   (loop-input/stop (not running?) handle)))

Why doesn’t Esc end up in the text? Esc is the named key 'escape and is handled by #:escape; only printable characters go to #:text. This is why interactive input consistently uses Esc to quit.