~alcinnz/haskell-stylist

ref: 38022972af85067203abd9b8855ad0f9e56a0399 haskell-stylist/src/Stylish/Style/Selector/Specificity.hs -rw-r--r-- 1.6 KiB
38022972 — Adrian Cochrane Implement dispatching parser of CSS properties. 5 years ago
                                                                                
524ca9cc Adrian Cochrane
d47030fd Adrian Cochrane
524ca9cc Adrian Cochrane
9e7ce5e0 Adrian Cochrane
524ca9cc Adrian Cochrane
9e7ce5e0 Adrian Cochrane
ee89bcfd Adrian Cochrane
9e7ce5e0 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
module Stylish.Style.Selector.Specificity(
        OrderedRuleStore(..)
    ) where

import Stylish.Parse.Selector
import Stylish.Style.Selector.Common
import Data.List

computeSpecificity :: Selector -> (Int, Int, Int)
computeSpecificity (Element selector) = computeSpecificity' selector
computeSpecificity (Child upSel sel) = computeSpecificity upSel `add` computeSpecificity' sel
computeSpecificity (Descendant upSel sel) = computeSpecificity upSel `add` computeSpecificity' sel
computeSpecificity (Adjacent upSel sel) = computeSpecificity upSel `add` computeSpecificity' sel
computeSpecificity (Sibling upSel sel) = computeSpecificity upSel `add` computeSpecificity' sel

computeSpecificity' (Tag _:sel) = computeSpecificity' sel `add` (0, 0, 1)
computeSpecificity' (Class _:sel) = computeSpecificity' sel `add` (0, 1, 0)
computeSpecificity' (Property _ _:sel) = computeSpecificity' sel `add` (0, 1, 0)
computeSpecificity' (Id _:sel) = computeSpecificity' sel `add` (1, 0, 0)
computeSpecificity' [] = (0, 0, 0)

add :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)
add (a, b, c) (x, y, z) = (a + x, b + y, c + z)

---

data OrderedRuleStore inner = OrderedRuleStore inner Int

instance RuleStore inner => RuleStore (OrderedRuleStore inner) where
    new = OrderedRuleStore new 0
    addStyleRule (OrderedRuleStore self count) priority rule = OrderedRuleStore (
            addStyleRule self priority $ rule {
                rank = (priority, computeSpecificity $ selector rule, count)
            }
        ) (count + 1)
    lookupRules (OrderedRuleStore self _) el = sort $ lookupRules self el