module FortyTwo.Prompts.Password (password) where
import System.Console.ANSI (cursorBackward, clearFromCursorToScreenEnd, setCursorColumn, clearFromCursorToLineEnd)
import Control.Monad (unless)
import FortyTwo.Renderers.Password (renderPassword, hideLetters)
import FortyTwo.Renderers.Question (renderQuestion)
import FortyTwo.Constants (emptyString, enterKey, delKey)
import FortyTwo.Utils
password :: String -> IO String
password :: String -> IO String
password String
question = do
String -> IO ()
putStrLn String
emptyString
String -> String -> String -> IO ()
renderQuestion String
question String
emptyString String
emptyString
String -> IO ()
putStr String
" "
IO ()
flush
IO ()
noBuffering
String
answer <- String -> IO String
loop String
emptyString
IO ()
restoreBuffering
Int -> IO ()
setCursorColumn Int
0
IO ()
clearFromCursorToLineEnd
String -> String -> String -> IO ()
renderQuestion String
question String
emptyString forall a b. (a -> b) -> a -> b
$ String -> String
hideLetters String
answer
forall (m :: * -> *) a. Monad m => a -> m a
return String
answer
loop :: String -> IO String
loop :: String -> IO String
loop String
pass = do
IO ()
noEcho
String -> IO ()
renderPassword String
pass
String
key <- IO String
getKey
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
pass) forall a b. (a -> b) -> a -> b
$ do
Int -> IO ()
cursorBackward forall a b. (a -> b) -> a -> b
$ forall (t :: * -> *) a. Foldable t => t a -> Int
length String
pass
IO ()
clearFromCursorToScreenEnd
String
res <- String -> String -> IO String
handleEvent String
pass (if forall (t :: * -> *) a. Foldable t => t a -> Int
length String
key forall a. Ord a => a -> a -> Bool
> Int
1 then String
emptyString else String
key)
IO ()
restoreEcho
forall (m :: * -> *) a. Monad m => a -> m a
return String
res
handleEvent :: String -> String -> IO String
handleEvent :: String -> String -> IO String
handleEvent String
pass String
key
| String
key forall a. Eq a => a -> a -> Bool
== String
enterKey = forall (m :: * -> *) a. Monad m => a -> m a
return String
pass
| String
key forall a. Eq a => a -> a -> Bool
== String
delKey =
if forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
pass then forall (m :: * -> *) a. Monad m => a -> m a
return String -> IO String
loop String
emptyString String
pass
else forall (m :: * -> *) a. Monad m => a -> m a
return String -> IO String
loop String
emptyString (forall a. [a] -> [a]
init String
pass)
| Bool
otherwise = String -> IO String
loop forall a b. (a -> b) -> a -> b
$ String
pass forall a. [a] -> [a] -> [a]
++ String
key