module KB.Text.Layout.Html ( -- * Rendering laid-out lines render , Options (..) , height -- * Page scaffolding , page , escape ) where import Data.Text (Text) import Data.Text qualified as Text import Text.Printf (printf) import KB.Text.Layout.Break (LineEnd (..), LineRange (..), LineSlice (..), materializeSlices) import KB.Text.Layout.Measure (PreparedText) render :: Options -> PreparedText -> [LineRange] -> Text render opts prepared ranges = Text.concat $ concat [ [ "
px opts.width , ";height:" <> pxAbs (height opts (length ranges)) , "\">" ] , zipWith renderLine [0 :: Int ..] ranges , ["
"] ] where px v = pxAbs (v * opts.unit) renderLine i range = Text.concat $ concat [ [ "
px (fromIntegral i * opts.lineHeight) , ";text-box-trim:trim-both;text-box-edge:cap alphabetic" , ";white-space:pre" <> spacing <> ";" <> escape opts.baseCss <> "\">" ] , map renderSlice slices , ["
"] ] where slices = materializeSlices prepared range separators = sum [Text.count " " s.text + Text.count "\xA0" s.text | s <- slices, not s.atom] slack = opts.width - range.width spacing | opts.justify , range.ended /= HardBroken , range.ended /= Finished , abs slack > 1e-4 , separators > 0 = ";word-spacing:" <> pxAbs (slack * opts.unit / fromIntegral separators) | otherwise = "" renderSlice slice = Text.concat [ " px slice.width <> ";word-spacing:normal;" else "" , escape (opts.styleCss slice.style) , "\">" , escape slice.text , "" ] data Options = Options { width :: Float , lineHeight :: Float , unit :: Float , baseCap :: Float , justify :: Bool , baseCss :: Text , styleCss :: Int -> Text } height :: Options -> Int -> Float height opts lineCount | lineCount <= 0 = 0 | otherwise = (fromIntegral (lineCount - 1) * opts.lineHeight + opts.baseCap) * opts.unit pxAbs :: Float -> Text pxAbs v = Text.pack (printf "%.2fpx" v) page :: Text -> Text -> Text page title body = Text.concat [ "" , escape title , "" , body , "" ] escape :: Text -> Text escape = Text.concatMap \case '&' -> "&" '<' -> "<" '>' -> ">" '"' -> """ c -> Text.singleton c