/
HtmlNormalizer.scala
316 lines (282 loc) · 9.98 KB
/
HtmlNormalizer.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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package net.liftweb
package http
import scala.xml._
import scala.collection.immutable.Vector
import js.JsCmd
import js.JsCmds.Noop
import js.JE.{AnonFunc, Call, JsRaw}
import util.Helpers._
/**
* Represents an HTML attribute for an event handler. Carries the event name and
* the JS that should run when that event is triggered as a String.
*/
private case class EventAttribute(eventName: String, jsString: String)
private object EventAttribute {
/**
* Some elements allow a URL attribute to take a `javascript:(//)`-style
* URL instead of setting an `on*` event in order to invoke JS. For example,
* you can (and Lift does) set a form's `action` attribute to
* `javascript://(some JS)` instead of setting `onsubmit` to `(someJS);
* return false`.
*
* This is a map from those attribute names to the corresponding JS event
* that would be used to execute that JS when it isn't run in line.
*/
val eventsByAttributeName =
Map(
"action" -> "submit",
"href" -> "click"
)
object EventForAttribute {
def unapply(attributeName: String): Option[String] = {
eventsByAttributeName.get(attributeName)
}
}
}
case class NodesAndEventJs(nodes: NodeSeq, js: JsCmd) {
def append(newNodesAndEventJs: NodesAndEventJs): NodesAndEventJs = {
this.copy(
nodes = nodes ++ newNodesAndEventJs.nodes,
js = js & newNodesAndEventJs.js
)
}
def append(newNodeAndEventJs: NodeAndEventJs): NodesAndEventJs = {
append(newNodeAndEventJs.node, newNodeAndEventJs.js)
}
def append(newNode: Node): NodesAndEventJs = {
this.copy(nodes = nodes :+ newNode)
}
def append(newJs: JsCmd): NodesAndEventJs = {
this.copy(js = js & newJs)
}
def append(newNode: Node, newJs: JsCmd): NodesAndEventJs = {
this.copy(nodes = nodes :+ newNode, js = js & newJs)
}
}
private[http] case class NodeAndEventJs(node: Node, js: JsCmd) {
def append(newJs: JsCmd): NodeAndEventJs = {
this.copy(js = js & newJs)
}
}
/**
* Helper class that performs certain Lift-specific normalizations of HTML
* represented as `NodeSeq`s:
* - Fixes URLs for `link`, `a`, `form`, and `script` elements to properly
* prepend the container's context path in case these are absolute URLs.
* - Extracts event attributes (replacing them with
* `[[LiftRules.attributeForRemovedEventAttributes]]` if needed), returning
* instead JavaScript that will attach the corresponding event handler to
* that element.
* - Provides for caller-specific additional processing for each node.
*/
private[http] final object HtmlNormalizer {
// Fix URLs using Req.normalizeHref and extract JS event attributes for
// putting into page JS. Returns a triple of:
// - The optional id that was found in this set of attributes.
// - The normalized metadata.
// - A list of extracted `EventAttribute`s.
private[this] def normalizeUrlAndExtractEvents(
attributeToNormalize: String,
attributes: MetaData,
contextPath: String,
shouldRewriteUrl: Boolean, // whether to apply URLRewrite.rewriteFunc
extractInlineJavaScript: Boolean,
eventAttributes: List[EventAttribute] = Nil
): (Option[String], MetaData, List[EventAttribute]) = {
if (attributes == Null) {
(None, Null, eventAttributes)
} else {
// Note: we don't do this tail-recursively because we have to preserve
// attribute order!
val (id, normalizedRemainingAttributes, remainingEventAttributes) =
normalizeUrlAndExtractEvents(
attributeToNormalize,
attributes.next,
contextPath,
shouldRewriteUrl,
extractInlineJavaScript,
eventAttributes
)
attributes match {
case attribute @ UnprefixedAttribute(
EventAttribute.EventForAttribute(eventName),
attributeValue,
remainingAttributes
) if attributeValue.text.startsWith("javascript:") && extractInlineJavaScript =>
val attributeJavaScript = {
// Could be javascript: or javascript://.
val base = attributeValue.text.substring(11)
val strippedJs =
if (base.startsWith("//"))
base.substring(2)
else
base
if (strippedJs.trim.isEmpty) {
Nil
} else {
// When using javascript:-style URIs, event.preventDefault is implied.
List(strippedJs + "; event.preventDefault()")
}
}
val updatedEventAttributes =
attributeJavaScript.map(EventAttribute(eventName, _)) :::
remainingEventAttributes
(id, normalizedRemainingAttributes, updatedEventAttributes)
case UnprefixedAttribute(name, _, _) if name == attributeToNormalize =>
val normalizedUrl =
Req.normalizeHref(
contextPath,
attributes.value,
shouldRewriteUrl,
URLRewriter.rewriteFunc
)
val newMetaData =
new UnprefixedAttribute(
attributeToNormalize,
normalizedUrl,
normalizedRemainingAttributes
)
(id, newMetaData, remainingEventAttributes)
case UnprefixedAttribute(name, attributeValue, _) if name.startsWith("on") && extractInlineJavaScript =>
val updatedEventAttributes =
EventAttribute(name.substring(2), attributeValue.text) ::
remainingEventAttributes
(id, normalizedRemainingAttributes, updatedEventAttributes)
case UnprefixedAttribute("id", attributeValue, _) =>
val idValue = Option(attributeValue.text).filter(_.nonEmpty)
(idValue, attributes.copy(normalizedRemainingAttributes), remainingEventAttributes)
case _ =>
(id, attributes.copy(normalizedRemainingAttributes), remainingEventAttributes)
}
}
}
// Given an element id and the `EventAttribute`s to apply to elements with
// that id, return a JsCmd that binds all those event handlers to that id.
private[this] def jsForEventAttributes(elementId: String, eventAttributes: List[EventAttribute]): JsCmd = {
eventAttributes.map {
case EventAttribute(name, handlerJs) =>
Call(
"lift.onEvent",
elementId,
name,
AnonFunc("event", JsRaw(handlerJs).cmd)
).cmd
}.foldLeft(Noop)(_ & _)
}
private[http] def normalizeElementAndAttributes(
element: Elem,
attributeToNormalize: String,
contextPath: String,
shouldRewriteUrl: Boolean,
extractEventJavaScript: Boolean
): NodeAndEventJs = {
val (id, normalizedAttributes, eventAttributes) =
normalizeUrlAndExtractEvents(
attributeToNormalize,
element.attributes,
contextPath,
shouldRewriteUrl,
extractEventJavaScript
)
val attributesIncludingEventsAsData =
LiftRules.attributeForRemovedEventAttributes match {
case Some(attribute) if eventAttributes.nonEmpty =>
val removedAttributes = eventAttributes.map {
case EventAttribute(event, _) =>
s"on$event"
}
new UnprefixedAttribute(attribute, removedAttributes.mkString(" "), normalizedAttributes)
case _ =>
normalizedAttributes
}
id.map { foundId =>
NodeAndEventJs(
element.copy(attributes = attributesIncludingEventsAsData),
jsForEventAttributes(foundId, eventAttributes)
)
} getOrElse {
if (eventAttributes.nonEmpty) {
val generatedId = s"lift-event-js-${nextFuncName}"
NodeAndEventJs(
element.copy(attributes = new UnprefixedAttribute("id", generatedId, attributesIncludingEventsAsData)),
jsForEventAttributes(generatedId, eventAttributes)
)
} else {
NodeAndEventJs(
element.copy(attributes = attributesIncludingEventsAsData),
Noop
)
}
}
}
private[http] def normalizeNode(
node: Node,
contextPath: String,
stripComments: Boolean,
extractEventJavaScript: Boolean
): Option[NodeAndEventJs] = {
node match {
case element: Elem =>
val (attributeToFix, shouldRewriteUrl) =
element.label match {
case "form" =>
("action", true)
case "a" =>
("href", true)
case "link" =>
("href", false)
case "script" =>
("src", false)
case _ =>
("src", true)
}
Some(
normalizeElementAndAttributes(
element,
attributeToFix,
contextPath,
shouldRewriteUrl,
extractEventJavaScript
)
)
case _: Comment if stripComments =>
None
case otherNode =>
Some(NodeAndEventJs(otherNode, Noop))
}
}
/**
* Normalizes `nodes` to adjust URLs with the given `contextPath`, stripping
* comments if `stripComments` is `true`, and extracting event JavaScript
* into the `js` part of the returned `NodesAndEventJs` if
* `extractEventJavaScript` is `true`.
*
* See `[[LiftMerge.merge]]` for sample usage.
*/
def normalizeHtmlAndEventHandlers(
nodes: NodeSeq,
contextPath: String,
stripComments: Boolean,
extractEventJavaScript: Boolean
): NodesAndEventJs = {
nodes.foldLeft(NodesAndEventJs(Vector[Node](), Noop)) { (soFar, nodeToNormalize) =>
normalizeNode(nodeToNormalize, contextPath, stripComments, extractEventJavaScript).map {
case NodeAndEventJs(normalizedElement: Elem, js: JsCmd) =>
val NodesAndEventJs(normalizedChildren, childJs) =
normalizeHtmlAndEventHandlers(
normalizedElement.child,
contextPath,
stripComments,
extractEventJavaScript
)
soFar
.append(js)
.append(normalizedElement.copy(child = normalizedChildren), childJs)
case node =>
soFar.append(node)
} getOrElse {
soFar
}
}
}
}