~alcinnz/CatTrap

ref: c4626b0b1ba761355ad57c1657d92e0d25f96cb9 CatTrap/Graphics/Layout/CSS.hs -rw-r--r-- 14.9 KiB
c4626b0b — Adrian Cochrane Incorporate inline-blocks/etc into the layout model. 8 months ago
                                                                                
17c324d5 Adrian Cochrane
fdea2a59 Adrian Cochrane
49365312 Adrian Cochrane
3d40a0a8 Adrian Cochrane
09970dfc Adrian Cochrane
17c324d5 Adrian Cochrane
9db95983 Adrian Cochrane
d379817e Adrian Cochrane
9d1b071d Adrian Cochrane
c4626b0b Adrian Cochrane
17c324d5 Adrian Cochrane
09970dfc Adrian Cochrane
a226a881 Adrian Cochrane
5bd4424d Adrian Cochrane
ed7d0445 Adrian Cochrane
8b24d68f Adrian Cochrane
0eabb595 Adrian Cochrane
9b5c291c Adrian Cochrane
7301a489 Adrian Cochrane
09970dfc Adrian Cochrane
b07f5dcb Adrian Cochrane
9db95983 Adrian Cochrane
590ef319 Adrian Cochrane
3e2dcdd3 Adrian Cochrane
fdea2a59 Adrian Cochrane
c4626b0b Adrian Cochrane
fdea2a59 Adrian Cochrane
66067a7c Adrian Cochrane
590ef319 Adrian Cochrane
72d01922 Adrian Cochrane
d379817e Adrian Cochrane
5c0e2aa9 Adrian Cochrane
590ef319 Adrian Cochrane
d379817e Adrian Cochrane
590ef319 Adrian Cochrane
d379817e Adrian Cochrane
b07f5dcb Adrian Cochrane
d379817e Adrian Cochrane
878e6868 Adrian Cochrane
d379817e Adrian Cochrane
8fb3f54a Adrian Cochrane
d379817e Adrian Cochrane
878e6868 Adrian Cochrane
d379817e Adrian Cochrane
7301a489 Adrian Cochrane
8fb3f54a Adrian Cochrane
7301a489 Adrian Cochrane
590ef319 Adrian Cochrane
d379817e Adrian Cochrane
66067a7c Adrian Cochrane
d379817e Adrian Cochrane
72d01922 Adrian Cochrane
b07f5dcb Adrian Cochrane
406578a2 Adrian Cochrane
5c3e14af Adrian Cochrane
b07f5dcb Adrian Cochrane
590ef319 Adrian Cochrane
e0d43db4 Adrian Cochrane
b07f5dcb Adrian Cochrane
590ef319 Adrian Cochrane
406578a2 Adrian Cochrane
e0d43db4 Adrian Cochrane
406578a2 Adrian Cochrane
9b5c291c Adrian Cochrane
85d144a0 Adrian Cochrane
7abbe00f Adrian Cochrane
9b5c291c Adrian Cochrane
c4626b0b Adrian Cochrane
9b5c291c Adrian Cochrane
c4626b0b Adrian Cochrane
2fe0db0f Adrian Cochrane
c4626b0b Adrian Cochrane
878e6868 Adrian Cochrane
fdea2a59 Adrian Cochrane
79c5cd46 Adrian Cochrane
590ef319 Adrian Cochrane
c4626b0b Adrian Cochrane
fdea2a59 Adrian Cochrane
c4626b0b Adrian Cochrane
fdea2a59 Adrian Cochrane
878e6868 Adrian Cochrane
fdea2a59 Adrian Cochrane
b07f5dcb Adrian Cochrane
9d1b071d Adrian Cochrane
e8a4642a Adrian Cochrane
878e6868 Adrian Cochrane
5c3e14af Adrian Cochrane
9b5c291c Adrian Cochrane
72d01922 Adrian Cochrane
d379817e Adrian Cochrane
878e6868 Adrian Cochrane
8b24d68f Adrian Cochrane
878e6868 Adrian Cochrane
8b24d68f Adrian Cochrane
878e6868 Adrian Cochrane
8b24d68f Adrian Cochrane
a7083fe3 Adrian Cochrane
878e6868 Adrian Cochrane
5c3e14af Adrian Cochrane
0eabb595 Adrian Cochrane
a7083fe3 Adrian Cochrane
0eabb595 Adrian Cochrane
8b24d68f Adrian Cochrane
d379817e Adrian Cochrane
0eabb595 Adrian Cochrane
5c3e14af Adrian Cochrane
0eabb595 Adrian Cochrane
5c3e14af Adrian Cochrane
0eabb595 Adrian Cochrane
5c3e14af Adrian Cochrane
878e6868 Adrian Cochrane
0eabb595 Adrian Cochrane
5c3e14af Adrian Cochrane
0eabb595 Adrian Cochrane
878e6868 Adrian Cochrane
0eabb595 Adrian Cochrane
5c3e14af Adrian Cochrane
0eabb595 Adrian Cochrane
8b24d68f Adrian Cochrane
0eabb595 Adrian Cochrane
878e6868 Adrian Cochrane
0eabb595 Adrian Cochrane
a7083fe3 Adrian Cochrane
d47a72b2 Adrian Cochrane
a7083fe3 Adrian Cochrane
d47a72b2 Adrian Cochrane
a7083fe3 Adrian Cochrane
878e6868 Adrian Cochrane
a7083fe3 Adrian Cochrane
878e6868 Adrian Cochrane
66067a7c Adrian Cochrane
878e6868 Adrian Cochrane
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
{-# LANGUAGE OverloadedStrings #-}
-- These following language extensions are to aid a dependency injection into
-- inline styling.
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, FlexibleContexts #-}
-- | Parses & desugars CSS properties to general CatTrap datastructures.
module Graphics.Layout.CSS(CSSBox(..), BoxSizing(..), Display(..),
        finalizeCSS, finalizeCSS') where

import qualified Data.Text as Txt
import Stylist (PropertyParser(..))
import Stylist.Tree (StyleTree(..))
import Data.Text.ParagraphLayout.Rich (constructParagraph, defaultBoxOptions,
        LineHeight(..), InnerNode(..), Box(..), RootNode(..), strut)

import Graphics.Layout.Box as B
import Graphics.Layout
import Graphics.Layout.CSS.Length
import Graphics.Layout.CSS.Font
import Graphics.Layout.Grid.CSS
import Graphics.Layout.Grid
import Graphics.Layout.Grid.Table
import Graphics.Layout.Inline.CSS
import Graphics.Layout.Flex.CSS

import Data.Char (isSpace)
import Graphics.Layout.CSS.Parse
import Data.Maybe (fromMaybe)

instance (PropertyParser x, Zero m, Zero n) => Default (UserData m n x) where
    def = ((placeholderFont, 0), Left zero, temp)

-- | Resolves length units in properties handled by downstream components.
inner' :: PropertyParser x => Font' -> CSSBox x -> x
inner' f self = foldr apply (inner self) $ innerProperties self
  where apply (k, v) ret = fromMaybe ret $
            longhand (innerParent self) ret k $ finalizeLengths f v

-- | Desugar parsed CSS into more generic layout parameters.
finalizeCSS :: PropertyParser x => Font' -> Font' -> StyleTree (CSSBox x) ->
        LayoutItem Length Length x
finalizeCSS root parent StyleTree { style = self'@CSSBox { display = None } } =
    LayoutFlow (inner' parent self') lengthBox []
finalizeCSS root parent self@StyleTree {
    style = self'@CSSBox { display = Grid }, children = childs
  } = LayoutFlow (inner' font_ self') (finalizeBox self' font_) [
        finalizeGrid (gridStyles self') font_ (map cellStyles $ map style childs)
            (finalizeChilds root font_ self' childs)]
  where
    font_ = pattern2font (font self') (font' self') parent root
finalizeCSS root parent self@StyleTree {
        style = self'@CSSBox {
            display = Table, tableOptions = opts@TableOptions {captionBelow=False}
        },
        children = childs
    } = LayoutFlow (inner' font_ self')
        (finalizeBox (collapseTBorders' self') font_)
        ([finalizeCSS root font_ child { style = child' { display = Block } }
            | child@StyleTree { style = child'@CSSBox { display = TableCaption } } <- childs] ++
        [finalizeTable root font_ temp opts childs])
  where
    font_ = pattern2font (font self') (font' self') parent root
finalizeCSS root parent self@StyleTree {
        style = self'@CSSBox {
            display = Table, tableOptions = opts@TableOptions {captionBelow=True}
        }, children = childs
    } = LayoutFlow (inner' font_ self')
        (finalizeBox (collapseTBorders' self') font_)
        (finalizeTable root font_ temp opts childs:
        [finalizeCSS root font_ child { style = child' { display = Block } }
            | child@StyleTree { style = child'@CSSBox { display = TableCaption } } <- childs])
  where
    font_ = pattern2font (font self') (font' self') parent root
finalizeCSS root parent self@StyleTree {
        style = self'@CSSBox { display = Flex, flexOptions = flex },
        children = childs
    } = LayoutFlow (inner' font_ self' ) (finalizeBox self' font_) [
        LayoutFlex temp $ lowerFlex flex font_ (map flexOptions childs')
            (flip map childs $ finalizeCSS root font_) (map style2font childs')]
  where
    font_ = style2font self'
    style2font style = pattern2font (font style) (font' style) parent root
    childs' = map style childs
finalizeCSS root parent self@StyleTree {
    style = self', children = childs
  } = LayoutFlow (inner' font_ self') (finalizeBox self' font_)
        (finalizeChilds root font_ self' childs)
  where
    font_ = pattern2font (font self') (font' self') parent root
-- | Desugars parsed CSS with a provided system font into more generic layout parameters.
finalizeCSS' sysfont self@StyleTree { style = self' } =
    finalizeCSS (pattern2font (font self') (font' self') sysfont sysfont) sysfont self

-- | Desugar a sequence of child nodes, taking care to capture runs of inlines.
finalizeChilds :: PropertyParser x => Font' -> Font' -> CSSBox x ->
        [StyleTree (CSSBox x)] -> [LayoutItem Length Length x]
finalizeChilds root parent style' (StyleTree { style = CSSBox { display = None } }:childs) =
    finalizeChilds root parent style' childs
finalizeChilds root parent style' childs@(child:_)
    | isInlineTree childs, Just self <- finalizeParagraph (flattenTree0 childs) =
        [LayoutInline (inherit $ inner' parent style') self paging]
    | (inlines@(_:_), blocks) <- spanInlines childs,
        Just self <- finalizeParagraph (flattenTree0 inlines) =
            LayoutInline (inherit $ inner' parent style') self paging :
                finalizeChilds root parent style' blocks
    | (StyleTree { style = CSSBox { display = Inline } }:childs') <- childs =
        finalizeChilds root parent style' childs' -- Inline's all whitespace...
  where
    paging = pageOptions $ style child
    isInlineTree = all isInlineTree0
    isInlineTree0 StyleTree { style = CSSBox { display = Inline }, children = childs } =
        isInlineTree childs
    isInlineTree0 StyleTree { style = CSSBox { display = Inline' _ } } = True
    isInlineTree0 _ = False
    spanInlines childs = case span isInlineTree0 childs of
        (inlines, (StyleTree {
            style = CSSBox { display = Inline }, children = tail
          }:blocks)) -> let (inlines', blocks') = spanInlines tail
            in (inlines ++ inlines', blocks' ++ blocks)
        ret -> ret
    flattenTree0 = strut def . flattenTree0'
    flattenTree0' childs
        | iStyle@(CSSInline _ _ bidi) <- inlineStyles style',
            bidi `elem` [BdOverride, BdIsolateOverride] = RootBox $ Box
                (applyBidi iStyle $ map (flattenTree parent) $ enumerate childs)
                $ flip applyFontInline parent $ txtOpts style'
        | otherwise = RootBox $ Box (map (flattenTree parent) $ enumerate childs)
            $ flip applyFontInline parent $ txtOpts style'
    flattenTree p (i, StyleTree self@CSSBox { display = Inline' disp' } kids) =
        buildInline' (pattern2font (font self) (font' self) p root) i
            (Right $ finalizeCSS root p $ StyleTree self { display = disp' } kids)
            self []
    flattenTree p (i, StyleTree self child@(_:_)) =
        buildInline f i self $ map (flattenTree f) $ enumerate child
      where f = pattern2font (font self) (font' self) p root
    flattenTree f (i,StyleTree {style=self@CSSBox {inlineStyles=CSSInline txt _ _}})
        = buildInline f i self [
            TextSequence ((f, 0), Left zero, inherit $ inner' parent self) txt]
    buildInline f i self childs =
        buildInline' f i (Left $ finalizeBox self f) self childs
    buildInline' f i val self childs =
        InlineBox ((f, i), val, inner' parent self)
                (Box childs' $ flip applyFontInline f $ txtOpts self)
                $ resolveBoxOpts f (tableOptions self)
      where childs' = applyBidi (inlineStyles self) childs
    finalizeParagraph (RootBox (Box [TextSequence _ txt] _))
        | Txt.all isSpace txt = Nothing -- Discard isolated whitespace.
    finalizeParagraph tree =
        Just $ constructParagraph "" tree "" $ paragraphOptions style'
    enumerate = zip $ enumFrom 0
finalizeChilds root parent style'@CSSBox { tableOptions = tOpts } childs
    | (_:_) <- table = finalizeTable root parent temp tOpts table:
        finalizeChilds root parent style' rest
    | (child:childs') <- childs = finalizeCSS root parent child:
        finalizeChilds root parent style' childs'
    | otherwise = []
  where
    (table, rest) = span isTable childs
    isTable (StyleTree CSSBox { display = TableRow } _) = True
    isTable (StyleTree CSSBox { display = TableHeaderGroup } _) = True
    isTable (StyleTree CSSBox { display = TableRowGroup } _) = True
    isTable (StyleTree CSSBox { display = TableFooterGroup } _) = True
    isTable (StyleTree CSSBox { display = TableCell } _) = True
    isTable (StyleTree CSSBox { display = TableColumn } _) = True
    isTable (StyleTree CSSBox { display = TableColumnGroup } _) = True
    -- Treat TableCaption as a block element!
    isTable _ = False

-- | Desugar most units, possibly in reference to given font.
finalizeBox self@CSSBox { cssBox = box } font_ =
    mapY' (flip finalizeLength font_) $ mapX' (flip finalizeLength font_) box

-- | Desugar a styletree of table elements to a grid layout.
finalizeTable root parent val opts childs = LayoutGrid val grid cells' childs'
  where
    grid = Track {
        cells = replicate width $ Left Auto,
        gap = hGap,
        trackMins = [], trackNats = []
      } `Size` Track {
        cells = replicate height $  Left Auto,
        gap = yGap,
        trackMins = [], trackNats = []
      }
    (cells', childs') = unzip (decor ++ cells)
    (hGap, yGap) = finalizeGap opts parent

    (cells, width, height) = lowerCells childs 0 emptyRow
    decor = decorateRow childs width 0 ++ decorateCol childs height 0
    lowerCells (StyleTree self@CSSBox { display = TableRow } cells:rest) h x =
        (row ++ rows, Prelude.max rowwidth width', height')
      where
        (row, rowwidth, x') = lowerRow cells 0 h x
        (rows, width', height') = lowerCells rest (succ h) $ commitRow x'
    lowerCells (StyleTree CSSBox { display = TableHeaderGroup } childs:rest) h x =
        -- Ignore table-header-group styles for now...
        -- Though it'd be nice for this to impact pagination...
        lowerCells (childs ++ rest) h x
    lowerCells (StyleTree CSSBox { display = TableFooterGroup } childs:rest) h x =
        lowerCells (childs ++ rest) h x -- As per TableHeaderGroup
    lowerCells (StyleTree CSSBox { display = TableRowGroup } childs:rest) h x =
        lowerCells (childs ++ rest) h x -- As per TableHeaderGroup
    lowerCells (StyleTree CSSBox { display = TableColumnGroup } _:rest) h x =
        lowerCells rest h x -- It'd be nice to allow styling based on this...
    lowerCells (StyleTree CSSBox { display = TableColumn } _:rest) h x =
        lowerCells rest h x -- As per TableColumnGroup, should be contained within.
    lowerCells (StyleTree CSSBox { display = TableCaption } _:rest) h x =
        lowerCells rest h x -- Handled by callers!
    lowerCells [] h _ = ([], 0, h)
    lowerCells items h x = (row ++ rows, Prelude.max rowwidth width', height')
      where
        (cells, rest) = break isRowGroup items
        (row, rowwidth, x') = lowerRow cells 0 h x
        (rows, width', height') = lowerCells rest (succ h) $ commitRow x'

    lowerRow (StyleTree self@CSSBox {
            display = TableCell, tableOptions = self' } childs:rest) ix row x =
        (cell:cells, width, x')
      where
        (cells, width, x') = lowerRow rest end row $
            insertCell start (colspan self') (rowspan self') x
        start = allocCol ix x
        end = start + colspan self'
        cell = (GridItem start end Start 0 0
                `Size` GridItem row (row + rowspan self') valign 0 0,
            finalizeCSS root parent $ StyleTree self { display = Block } childs)
        valign = finalizeVAlign self'
        halign = finalizeHAlign (paragraphOptions self) (direction self)
    lowerRow (self:rest) ix row x = (cell:cells, width, x')
      where
        ix' = allocCol ix x
        (cells, width, x') = lowerRow rest (succ ix') row $ insertCell ix' 1 1 x
        cell = (GridItem ix' (succ ix') Start 0 0
                `Size` GridItem row (succ row) Start 0 0,
            finalizeCSS root parent self {
                style = (style self) {
                    cssBox = collapseBorders opts $ cssBox $ style self
                }
            })
    lowerRow [] ix _ x = ([], ix, x)

    decorateRow (StyleTree self@CSSBox { display = TableRow } _:rest) w row =
        buildDecor self 0 w row 1:decorateRow rest w (succ row)
    decorateRow (StyleTree self@CSSBox { display = d } childs:rest) w row
        | d `elem` [TableHeaderGroup, TableFooterGroup, TableRowGroup] =
            buildDecor self 0 w row (countRows childs):
                decorateRow (childs ++ rest) w (row + countRows childs)
        | d `elem` [TableCaption, TableColumn, TableColumnGroup] =
            decorateRow rest w row
        | otherwise = decorateRow (dropWhile (not . isRowGroup) rest) w$succ row
    decorateRow [] _ _ = []
    decorateCol (StyleTree self@CSSBox { display = TableColumn } _:rest) h col =
        buildDecor self col 1 0 h:decorateCol rest h (succ col)
    decorateCol (StyleTree self@CSSBox { display = TableColumnGroup } childs:rest)
        h col = buildDecor self col (countCols' childs self) 0 h:
            decorateCol (childs ++ rest) h (col + countCols' childs self)
    decorateCol (_:rest) h col = decorateCol rest h col
    decorateCol [] _ _ = []

    countRows (StyleTree CSSBox { display = TableRow } _:rest) =
        succ $ countRows rest
    countRows (StyleTree CSSBox { display = d } childs:rest)
        | d `elem` [TableHeaderGroup, TableFooterGroup, TableRowGroup] =
            countRows childs + countRows rest
        | d `elem` [TableCaption, TableColumn, TableColumnGroup] = countRows rest
        | otherwise = succ $ countRows $ dropWhile (not . isRowGroup) rest
    countRows [] = 0
    countCols' cols@(_:_) _ = countCols cols
    countCols' _ CSSBox { tableOptions = TableOptions { colspan = x } } = x
    countCols (StyleTree CSSBox {
            display = TableColumn,
            tableOptions = TableOptions { colspan = x }
        } _:rest) = x + countCols rest
    countCols (StyleTree CSSBox {
            display = TableColumnGroup,
            tableOptions = TableOptions { colspan = x }
        } []:rest) = x + countCols rest
    countCols (StyleTree CSSBox { display = TableColumnGroup } childs:rest) =
        countCols childs + countCols rest
    countCols (_:rest) = countCols rest
    countCols [] = 0

    buildDecor self col colspan row rowspan =
        (GridItem col (col + colspan) Start 0 0 `Size`
            GridItem row (row + rowspan) Start 0 0,
            finalizeCSS root parent $ StyleTree self {
                display = Block, cssBox = collapseBorders opts $ cssBox self
            } [])

    isRowGroup (StyleTree CSSBox { display = TableRow } _) = True
    isRowGroup (StyleTree CSSBox { display = TableHeaderGroup } _) = True
    isRowGroup (StyleTree CSSBox { display = TableFooterGroup } _) = True
    isRowGroup (StyleTree CSSBox { display = TableRowGroup } _) = True
    isRowGroup (StyleTree CSSBox { display = TableCaption } _) = True
    isRowGroup (StyleTree CSSBox { display = TableColumn } _) = True
    isRowGroup (StyleTree CSSBox { display = TableColumnGroup } _) = True
    isRowGroup _ = False

-- | Applies border-collapse to a table element.
collapseTBorders' :: CSSBox x -> CSSBox x
collapseTBorders' self = self {
    cssBox = collapseTBorders (tableOptions self) (cssBox self)
  }