module Text.Tabl.Ascii
( ascii
) where
import Safe
import qualified Data.Text as T
import Text.Tabl.Alignment
import Text.Tabl.Util
columnWidths :: [[T.Text]]
-> [Int]
columnWidths cells = foldr combine zeros cells
where
zeros = replicate (length $ head cells) 0
combine = zipWith (\txt len -> max len (T.length txt))
verticalDecorators :: [Bool]
-> [T.Text]
verticalDecorators pres = [left $ head pres]
++ map mid (drop 1 $ init pres)
++ [right $ last pres]
where
left = bool "| " ""
mid = bool " | " " "
right = bool " |" ""
horizontalLine :: [T.Text]
-> [T.Text]
-> T.Text
horizontalLine frow vdecor = zipcat isects dashes
where
dashes = map (\cell -> T.replicate (T.length cell) "-") frow
isects = map (T.map conv) vdecor
conv c = lookupJustDef '?' c [(' ', '-'), ('|', '+')]
applyDecoration :: [Bool]
-> [Bool]
-> [[T.Text]]
-> [T.Text]
applyDecoration hpres vpres cells = intersperseOn rows hpres hline
where
vdecor = verticalDecorators vpres
hline = horizontalLine (head cells) vdecor
rows = map (zipcat vdecor) cells
alignCell :: Alignment
-> Int
-> T.Text
-> T.Text
alignCell AlignLeft = flip T.justifyLeft ' '
alignCell AlignRight = flip T.justifyRight ' '
alignCell AlignCentre = flip T.center ' '
alignCells :: [[T.Text]]
-> [Int]
-> [Alignment]
-> [[T.Text]]
alignCells cells widths aligns = map (zipWith3 alignCell aligns widths) cells
ascii :: [Bool]
-> [Bool]
-> [Alignment]
-> [[T.Text]]
-> T.Text
ascii hpres vpres aligns cells = T.intercalate "\n" decorated
where
decorated = applyDecoration hpres vpres aligned
aligned = alignCells escaped (columnWidths escaped) aligns
escaped = map (map (T.replace "\n" "\\n" . T.replace "\t" "\\t")) cells