packages feed

kb-text-layout-0.3.0.0: demos/lib/KB/Text/Layout/Html.hs

module KB.Text.Layout.Html
  ( -- * Rendering laid-out lines
    render
  , wordSpacing
  , Options (..)
  , height

    -- * Page scaffolding
  , page
  , escape
  ) where

import Data.List (mapAccumL)
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
      [
        [ "<div style=\"position:relative;width:" <> px opts.width
        , ";height:" <> pxAbs (height opts (length ranges))
        , "\">"
        ]
      , zipWith renderLine [0 :: Int ..] ranges
      , ["</div>"]
      ]
  where
    px v = pxAbs (v * opts.unit)
    renderLine i range =
      Text.concat $
        concat
          [
            [ "<div style=\"position:absolute;left:0;top:" <> px (fromIntegral i * opts.lineHeight)
            , ";text-box-trim:trim-both;text-box-edge:cap alphabetic"
            , ";white-space:pre" <> spacing <> ";" <> escape opts.baseCss <> "\">"
            ]
          , zipWith renderSlice (runsOf slices) slices
          , ["</div>"]
          ]
      where
        slices = materializeSlices prepared range
        spacing = maybe "" (\extra -> ";word-spacing:" <> px extra) (wordSpacing opts prepared range)
        renderSlice runs slice =
          Text.concat
            [ "<span style=\""
            , if slice.atom then "display:inline-block;width:" <> px slice.width <> ";word-spacing:normal;" else ""
            , escape (opts.styleCss slice.style)
            , "\">"
            , if slice.atom then escape slice.text else Text.concat (map renderRun runs)
            , "</span>"
            ]
        renderRun run
          | run.stretches || Text.null spacing = escape run.text
          | otherwise = "<span style=\"word-spacing:normal\">" <> escape run.text <> "</span>"

wordSpacing :: Options -> PreparedText -> LineRange -> Maybe Float
wordSpacing opts prepared range
  | opts.justify
  , not range.overfull
  , slack < -1e-4 || slack > 1e-4 && not lastInParagraph
  , separators > 0 =
      Just (slack / fromIntegral separators)
  | otherwise = Nothing
  where
    runs = concat (runsOf (materializeSlices prepared range))
    separators = sum [Text.count " " run.text | run <- runs, run.stretches]
    slack = opts.width - range.width
    lastInParagraph = range.ended == HardBroken || range.ended == Finished

data Run = Run
  { text :: Text
  , stretches :: Bool
  }

runsOf :: [LineSlice] -> [[Run]]
runsOf = snd . mapAccumL spaceRuns True

spaceRuns :: Bool -> LineSlice -> (Bool, [Run])
spaceRuns indenting slice
  | slice.atom = (False, [])
  | otherwise = (indenting && Text.null rest, indentRun <> map glueAware (Text.groupBy sameGlue rest))
  where
    (indent, rest) = if indenting then Text.span (== ' ') slice.text else ("", slice.text)
    indentRun = [Run{text = indent, stretches = False} | not (Text.null indent)]
    sameGlue a b = (a == '\xA0') == (b == '\xA0')
    glueAware run = Run{text = run, stretches = not (Text.any (== '\xA0') run)}

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
    [ "<!doctype html><html><head><meta charset=\"utf-8\"><title>"
    , escape title
    , "</title></head><body>"
    , body
    , "</body></html>"
    ]

escape :: Text -> Text
escape = Text.concatMap \case
  '&' -> "&amp;"
  '<' -> "&lt;"
  '>' -> "&gt;"
  '"' -> "&quot;"
  c -> Text.singleton c