-
Notifications
You must be signed in to change notification settings - Fork 44
/
styles.scala
260 lines (225 loc) · 9.85 KB
/
styles.scala
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
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package laika.ast.styles
import laika.api.bundle.Precedence
import laika.ast.{ Element, Path }
/** Represents a single predicate which is
* part of the selector for a style declaration.
*/
sealed trait StylePredicate {
/** The specificity of this predicate.
* Used to calculate the precedence if
* multiple selectors apply to the same
* target element.
*/
def specificity: Specificity
/** Indicates whether this predicate holds
* for the specified element.
*/
def evaluate(element: Element): Boolean
}
/** Contains the available predicate types.
*
* The available selector types represent a subset of the full
* CSS standard, picking those features which are reasonably suited
* in the context of the Laika document model. It includes type,
* class and id selectors, but no attribute selectors as most
* Laika tree elements primarily contain a sequence of children
* and not many other properties to match against.
*
* It also supports the CSS syntax to declare selectors for
* child elements (e.g. `Paragraph .intro`) or immediate
* children (e.g. `Paragraph > .intro`).
*/
object StylePredicate {
/** A predicate that holds if the given type name matches the type
* of the target element. In contrast to web CSS, in Laika
* this is not a tag name, but the (unqualified) name
* of the class of the target element instance (e.g. `Paragraph`).
*/
case class ElementType(name: String) extends StylePredicate {
val specificity = Specificity(0, 0, 1, 0)
def evaluate(element: Element): Boolean = element.getClass.getSimpleName == name
}
/** A predicate that holds if the given id matches
* the id of the target element.
*/
case class Id(id: String) extends StylePredicate {
val specificity = Specificity(1, 0, 0, 0)
def evaluate(element: Element): Boolean = element.options.id.contains(id)
}
/** A predicate that holds if the given style name matches
* one of the styles of the target element.
*/
case class StyleName(name: String) extends StylePredicate {
val specificity = Specificity(0, 1, 0, 0)
def evaluate(element: Element): Boolean = element.hasStyle(name)
}
}
/** Represents a parent selector and indicates whether it is
* an immediate parent or an ancestor anywhere in the hierarchy.
*/
case class ParentSelector(selector: StyleSelector, immediate: Boolean)
/** Represents the specificity of a style selector or predicate.
* This is modeled after the precedence rules of the CSS standard.
*/
case class Specificity(ids: Int, classes: Int, types: Int, order: Int)
extends Ordered[Specificity] {
/** Adds this and the given specificity by summing
* all its individual parameters.
*/
def + (other: Specificity): Specificity =
Specificity(ids + other.ids, classes + other.classes, types + other.types, order)
/** Compares this instance with the given specificity.
* Applies the CSS standard weighting of first comparing the number of specified ids, followed by classes,
* then types and finally the order.
*/
def compare(other: Specificity): Int =
if (ids != other.ids) ids compare other.ids
else if (classes != other.classes) classes compare other.classes
else if (types != other.types) types compare other.types
else order compare other.order
}
/** Responsible for determining whether a style declaration should be applied to a target element,
* basing its decision on a set of predicates.
*
* @param predicates the set of predicates that need to hold
* for this selector to be applicable to a target element
* @param parent the optional parent selector
* @param order the index of the style declaration this selector
* belongs to
*/
case class StyleSelector(
predicates: Set[StylePredicate] = Set(),
parent: Option[ParentSelector] = None,
order: Int = 0
) {
/** The specificity of this selector, calculated from the specificity of its predicates and the order.
*
* Used to calculate the precedence if multiple selectors apply to the same target element.
*/
def specificity: Specificity = {
val thisSpec = predicates.map(_.specificity).reduceLeftOption(_ + _).getOrElse(
Specificity(0, 0, 0, 0)
).copy(order = order)
parent.fold(thisSpec)(thisSpec + _.selector.specificity)
}
/** Indicates whether this selector applies to the specified target element.
*
* @param target the target element to apply this selector to
* @param parents the parents of the specified target element, which
* also need to match in case this selector has parent selectors.
* @return true if this selector matches the target element
*/
def matches(target: Element, parents: Seq[Element]): Boolean = {
def matchesParent(parents: Seq[Element], selector: StyleSelector): Boolean = parents match {
case Seq() => false
case seq => selector.matches(seq.head, seq.tail) || matchesParent(seq.tail, selector)
}
predicates.forall(_.evaluate(target)) &&
parent.fold(true) { parent =>
if (parent.immediate) parents.headOption.fold(false)(parent.selector.matches(_, parents.tail))
else matchesParent(parents, parent.selector)
}
}
}
/** Represents a single style declaration.
*
* @param selector the selector to determine which elements this declaration applies to
* @param styles the styles themselves in a map representing the names and values of each style
*/
case class StyleDeclaration(selector: StyleSelector, styles: Map[String, String]) {
/** Indicates whether this style declaration applies to the specified target
* element.
*
* @param element the target element to apply the selector of this style declaration to
* @param parents the parents of the specified target element, which
* also need to match in case the selector of this declaration has parent selectors.
* @return true if this style declaration applies to the target element
*/
def appliesTo(element: Element, parents: Seq[Element]): Boolean =
selector.matches(element, parents)
/** Returns a new style declaration with the order parameter
* in its Specificity property increased by the specified amount.
*/
def increaseOrderBy(amount: Int): StyleDeclaration =
if (amount == 0) this
else StyleDeclaration(selector.copy(order = selector.order + amount), styles)
}
/** Companion providing factory methods for the StyleDeclaration class.
*/
object StyleDeclaration extends ((StyleSelector, Map[String, String]) => StyleDeclaration) {
/** Creates a new StyleDeclaration with only one predicate.
*/
def apply(predicate: StylePredicate, styles: (String, String)*): StyleDeclaration =
apply(StyleSelector(Set(predicate)), styles.toMap)
}
/** Represents a set of one or more style declarations.
*
* @param paths the paths the style declarations have been obtained from
* @param styles the style declarations that belong to this set
* @param precedence the precedence of this set compared to other provided sets
*/
case class StyleDeclarationSet(
paths: Set[Path],
styles: Set[StyleDeclaration],
precedence: Precedence = Precedence.High
) {
/** Collects all the styles that apply to the specified target element.
*
* @param target the target element to collect the matching styles for
* @param parents the parents of the specified target element
* @return a map representing the keys and values of all styles that apply to the target element
*/
def collectStyles(target: Element, parents: Seq[Element]): Map[String, String] = {
val decls = styles.filter(_.appliesTo(target, parents)).toSeq.sortBy(_.selector.specificity)
decls.foldLeft(Map[String, String]()) { case (acc, decl) => acc ++ decl.styles }
}
/** Merges the style declaration of this instance with the specified set and returns the merged set in a new instance.
*/
def ++ (set: StyleDeclarationSet): StyleDeclarationSet = {
val (lo, hi) =
if (Ordering[Precedence].gt(this.precedence, set.precedence))
(set.styles, this.styles)
else (this.styles, set.styles)
val maxOrder = if (lo.isEmpty) 0 else lo.maxBy(_.selector.order).selector.order + 1
val mergedPrecedence =
if (this.precedence == Precedence.Low && set.precedence == Precedence.Low) Precedence.Low
else Precedence.High
new StyleDeclarationSet(
paths ++ set.paths,
lo ++ hi.map(_.increaseOrderBy(maxOrder)),
mergedPrecedence
)
}
}
/** Companion providing factory methods for the StyleDeclaration class.
*/
object StyleDeclarationSet
extends ((Set[Path], Set[StyleDeclaration], Precedence) => StyleDeclarationSet) {
/** Creates an empty StyleDeclarationSet with `Root` as its only path element.
*/
val empty: StyleDeclarationSet = new StyleDeclarationSet(Set(Path.Root), Set.empty)
/** Creates a new StyleDeclarationSet with a single path element and
* the specified declarations.
*/
def apply(path: Path, styles: StyleDeclaration*): StyleDeclarationSet =
apply(Set(path), styles.toSet)
/** Creates a new StyleDeclarationSet with a single path element and
* the specified declarations.
*/
def forPath(path: Path, styles: Set[StyleDeclaration]) = apply(Set(path), styles)
}