module Brick.Widgets.List.Utils where

import           Brick.Widgets.List
import           Data.Maybe
import qualified Data.Vector as V
import           Lens.Micro

-- | Replace the contents of a list with a new set of elements but preserve the
-- currently selected index.
--
-- This is a version of listReplace that doesn't try to be smart, but assumes
-- that all the elements in one list are distinct.
--
-- listReplace itself is broken as of brick-0.2 due to a bogus implementation of
-- the `merge` function.
listSimpleReplace :: Eq e => V.Vector e -> List n e -> List n e
listSimpleReplace :: forall e n. Eq e => Vector e -> List n e -> List n e
listSimpleReplace Vector e
elems List n e
oldList =
  let selected :: Maybe Int
selected = forall a b c. (a -> b -> c) -> b -> a -> c
flip forall a. Eq a => a -> Vector a -> Maybe Int
V.elemIndex Vector e
elems forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (a, b) -> b
snd forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< forall (t :: * -> *) e n.
(Splittable t, Traversable t, Semigroup (t e)) =>
GenericList n t e -> Maybe (Int, e)
listSelectedElement List n e
oldList
      newSelected :: Maybe Int
newSelected = if forall a. Vector a -> Bool
V.null Vector e
elems
                       then forall a. Maybe a
Nothing
                       else forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a -> a
fromMaybe Int
0 Maybe Int
selected
  in List n e
oldList forall a b. a -> (a -> b) -> b
& forall n (t1 :: * -> *) e1 (t2 :: * -> *) e2.
Lens (GenericList n t1 e1) (GenericList n t2 e2) (t1 e1) (t2 e2)
listElementsL forall s t a b. ASetter s t a b -> b -> s -> t
.~ Vector e
elems forall a b. a -> (a -> b) -> b
& forall n (t :: * -> *) e. Lens' (GenericList n t e) (Maybe Int)
listSelectedL forall s t a b. ASetter s t a b -> b -> s -> t
.~ Maybe Int
newSelected