/
BindHelpers.scala
2473 lines (2131 loc) · 83 KB
/
BindHelpers.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2007-2011 WorldWide Conferencing, LLC
*
* 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 net.liftweb
package util
import scala.xml._
import common._
import scala.collection.mutable.ListBuffer
import java.util.{List => JavaList}
/**
* This trait is used to identify an object that is representable as a {@link NodeSeq}.
*/
trait Bindable {
def asHtml: NodeSeq
}
trait AttrHelper[+Holder[X]] {
type Info
def apply(key: String): Holder[Info] = convert(findAttr(key))
def apply(prefix: String, key: String): Holder[Info] =
convert(findAttr(prefix, key))
def apply(key: String, default: => Info): Info =
findAttr(key) getOrElse default
def apply(prefix: String, key: String, default: => Info): Info =
findAttr(prefix, key) getOrElse default
def apply[T](key: String, f: Info => T): Holder[T] =
convert(findAttr(key).map(f))
def apply[T](prefix: String, key: String, f: Info => T): Holder[T] =
convert(findAttr(prefix, key).map(f))
def apply[T](key: String, f: Info => T, default: => T): T =
findAttr(key).map(f) getOrElse default
def apply[T](prefix: String, key: String, f: Info => T, default: => T): T =
findAttr(prefix, key).map(f) getOrElse default
protected def findAttr(key: String): Option[Info]
protected def findAttr(prefix: String, key: String): Option[Info]
protected def convert[T](in: Option[T]): Holder[T]
}
/**
* BindHelpers can be used to obtain additional information while a {@link bind} call is executing.
* This informaiton includes node attributes of the current bound node or the entire NodeSeq that is
* to be bound. Since the context is created during bind execution and destroyed when bind terminates,
* you can benefit of these helpers in the context of FuncBindParam or FuncAttrBindParam. You can
* also provide your own implementation of BindParam and your BindParam#calcValue function will be called
* in the appropriate context.
*
* Example:
* <pre name="code" class="scala">
* bind("hello", xml,
* "someNode" -> {node: NodeSeq => <function-body>})
* </pre>
*
* In <code>function-body</code> you can safely use BindHelpers methods to obtain correctly-scoped information.
*/
object BindHelpers extends BindHelpers {
private val _bindNodes = new ThreadGlobal[List[NodeSeq]]
private val _currentNode = new ThreadGlobal[Elem]
/**
* A list of NodeSeq that preceeds the NodeSeq passed to bind. The head of the list
* is the most recent NodeSeq. This returns Empty if it is called outside its context,
* or Full(Nil) if there are no child nodes but the function is called within the
* appropriate context.
*/
def bindNodes: Box[List[NodeSeq]] = _bindNodes.box
/**
* A Box containing the current Elem, the children of which are passed to the bindParam
*/
def currentNode: Box[Elem] = _currentNode.box
/**
* Helpers for obtaining attributes of the current Elem
*/
object attr extends AttrHelper[Option] {
type Info = NodeSeq
protected def findAttr(key: String): Option[Info] =
for { n <- _currentNode.box.toOption
at <- n.attributes.find(at => at.key == key && !at.isPrefixed) }
yield at.value
protected def findAttr(prefix: String, key: String): Option[Info] =
for { n <- _currentNode.box.toOption
at <- n.attributes.find {
case at: PrefixedAttribute => at.key == key && at.pre == prefix
case _ => false
}}
yield at.value
protected def convert[T](in: Option[T]): Option[T] = in
}
}
/**
* Helpers assocated with bindings
*/
trait BindHelpers {
private lazy val logger = Logger(classOf[BindHelpers])
def errorDiv(body: NodeSeq): Box[NodeSeq] =
Props.mode match {
case Props.RunModes.Development | Props.RunModes.Test =>
Full(<div class="snippeterror" style="display: block; padding: 4px; margin: 8px; border: 2px solid red">
{body}
<i>note: this error is displayed in the browser because
your application is running in "development" or "test" mode.If you
set the system property run.mode=production, this error will not
be displayed, but there will be errors in the output logs.
</i>
</div>)
case _ => Empty
}
/**
* Adds a css class to the existing class tag of an Elem or create
* the class attribute
*/
def addCssClass(cssClass: Box[String], elem: Elem): Elem =
cssClass match {
case Full(css) => addCssClass(css, elem)
case _ => elem
}
/**
* Adds a css class to the existing class tag of an Elem or create
* the class attribute
*/
def addCssClass(cssClass: String, elem: Elem): Elem = {
elem.attribute("class") match {
case Some(clz) => {
def fix(in: MetaData) =
new UnprefixedAttribute("class", clz.text.trim + " " + cssClass.trim,
in.filter{
case p: UnprefixedAttribute =>
p.key != "class"
case _ => true
})
new Elem(elem.prefix,
elem.label,
fix(elem.attributes),
elem.scope,
elem.child :_*)
}
case _ => elem % new UnprefixedAttribute("class", cssClass, Null)
}
}
/**
* Takes attributes from the first node of 'in' (if any) and mixes
* them into 'out'. Curried form can be used to produce a
* NodeSeq => NodeSeq for bind.
*
* @param in where to take the attributes from
* @param out where to put the attributes
*
* @return 'out' element with attributes from 'in'
*/
def mixinAttributes(out: Elem)(in: NodeSeq): NodeSeq = {
val attributes = in.headOption.map(_.attributes).getOrElse(Null)
out % attributes
}
/**
* Finds and returns one of many templates from the children based
* upon the namespace and tag name: for example, for prefix "choose"
* and tag name "stuff" this would return the contents of the
* first tag <code><choose:stuff> ... </choose:stuff></code>
* in the specified NodeSeq.
*
* @param prefix the prefix (e.g., "choose")
* @param tag the tag to choose (e.g., "stuff")
* @param xhtml the node sequence to search for the specified element
*
* @return the first matching node sequence
*/
def chooseTemplate(prefix: String, tag: String, xhtml: NodeSeq): NodeSeq =
Helpers.findElems(xhtml)(e => e.label == tag && e.prefix == prefix).toList match {
case Nil => NodeSeq.Empty
case x :: xs => x.child
}
/**
* Similar to chooseTemplate, this returns the contents of the element in a Full Box if
* found or an Empty Box otherwise.
*/
def template(xhtml: NodeSeq, prefix: String, tag: String): Box[NodeSeq] =
Helpers.findElems(xhtml)(e => e.label == tag && e.prefix == prefix).toList match {
case Nil => Empty
case x :: xs => Full(x.child)
}
/**
* Find two of many templates from the children
*/
def template(xhtml: NodeSeq, prefix: String, tag1: String,
tag2: String): Box[(NodeSeq, NodeSeq)] =
for (x1 <- template(xhtml, prefix, tag1);
x2 <- template(xhtml, prefix, tag2)) yield (x1, x2)
/**
* Find three of many templates from the children
*/
def template(xhtml: NodeSeq, prefix: String, tag1: String,
tag2: String, tag3: String): Box[(NodeSeq, NodeSeq, NodeSeq)] =
for (x1 <- template(xhtml, prefix, tag1);
x2 <- template(xhtml, prefix, tag2);
x3 <- template(xhtml, prefix, tag3)) yield (x1, x2, x3)
/**
* Base class for Bind parameters. A bind parameter has a name and is able to extract its value from a NodeSeq.
*/
sealed trait BindParam {
def name: String
def calcValue(in: NodeSeq): Option[NodeSeq]
}
/**
* A trait that indicates what the newly bound attribute name should be.
*/
trait BindWithAttr {
def newAttr: String
}
/**
* A case class that wraps attribute-oriented BindParams to allow prefixing the resulting attribute
*/
sealed case class PrefixedBindWithAttr(prefix : String, binding: BindParam with BindWithAttr) extends BindParam with BindWithAttr {
val name = binding.name
def calcValue(in : NodeSeq) = binding.calcValue(in)
val newAttr = binding.newAttr
}
/**
* Constant BindParam always returning the same value
*/
final class TheBindParam(val name: String, value: NodeSeq)
extends Tuple2(name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(value)
}
object TheBindParam {
def apply(name: String, value: NodeSeq) = new TheBindParam(name, value)
}
/**
* Constant BindParam always returning the same value
*/
final class TheStrBindParam(val name: String, value: String)
extends Tuple2(name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = value match {
case null => Some(NodeSeq.Empty)
case str => Some(Text(str))
}
}
object TheStrBindParam {
def apply(name: String, value: String) = new TheStrBindParam(name, value)
}
/**
* BindParam that binds a given value into a new attribute.
* For example, given the following markup:
*
* <pre name="code" class="xml">
* <lift:AttrBinds >
* <div test:w="foo" />
* <div test:x="foo" />
* <div test:y="foo" />
* <div test:z="foo" />
* </lift:AttrBinds >
* </pre>
*
* The following snippet:
*
* <pre name="code" class="scala">
* import scala.xml._
* class AttrBinds {
* def render(xhtml : NodeSeq) : NodeSeq =
* BindHelpers.bind("test", xhtml,
* AttrBindParam("w", Text("fooW"), "id"),
* AttrBindParam("x", "fooX", "id"),
* AttrBindParam("y", Text("fooW"), ("lift","calcId")),
* AttrBindParam("z", "fooZ", ("lift", "calcId")))
* </pre>
*
* produces this markup:
*
* <pre name="code" class="xml">
* <div id="fooW" />
* <div id="fooX" />
* <div lift:calcId="fooY" />
* <div lift:calcId="fooZ" />
* </pre>
*
* @param name the name of the binding to replace
* @param myValue the value of the new attribute
* @param newAttr The new attribute label
*/
final class AttrBindParam(val name: String, myValue: => NodeSeq, val newAttr: String)
extends BindParam with BindWithAttr {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(myValue)
}
/**
* BindParam that binds a given value into a new attribute.
*
* This object provides factory methods for convenience.
*/
object AttrBindParam {
/**
* Returns an unprefixed attribute binding containing the specified NodeSeq
*
* @param name The name to bind against
* @param myValue The value to place in the new attribute
* @param newAttr The new attribute label
*/
def apply(name: String, myValue: => NodeSeq, newAttr: String) =
new AttrBindParam(name, myValue, newAttr)
/**
* Returns an unprefixed attribute binding containing the specified String
* wrapped in a Text() element
*
* @param name The name to bind against
* @param myValue The value to place in the new attribute
* @param newAttr The new attribute label
*/
def apply(name: String, myValue: String, newAttr: String) =
new AttrBindParam(name, if (null eq myValue) NodeSeq.Empty else Text(myValue), newAttr)
/**
* Returns a prefixed attribute binding containing the specified NodeSeq
*
* @param name The name to bind against
* @param myValue The value to place in the new attribute
* @param newAttr The new attribute in the form (prefix,label)
*/
def apply(name: String, myValue: => NodeSeq, newAttr: Pair[String,String]) =
PrefixedBindWithAttr(newAttr._1, new AttrBindParam(name, myValue, newAttr._2))
/**
* Returns a prefixed attribute binding containing the specified String
* wrapped in a Text() element
*
* @param name The name to bind against
* @param myValue The value to place in the new attribute
* @param newAttr The new attribute in the form (prefix,label)
*/
def apply(name: String, myValue: String, newAttr: Pair[String,String]) =
PrefixedBindWithAttr(newAttr._1, new AttrBindParam(name,
if (null eq myValue) NodeSeq.Empty else Text(myValue), newAttr._2))
}
/**
* BindParam using a function to calculate its value
*/
final class FuncBindParam(val name: String, value: NodeSeq => NodeSeq)
extends Tuple2(name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(value(in))
}
object FuncBindParam {
def apply(name: String, value: NodeSeq => NodeSeq) = new FuncBindParam(name, value)
}
/**
* BindParam that computes a new attribute value based on the current
* attribute value. For example, given the following markup:
*
* <pre name="code" class="xml">
* <lift:AttrBinds >
* <div test:x="foo" />
* <div test:y="foo" />
* </lift:AttrBinds >
* </pre>
*
* The following snippet:
*
* <pre name="code" class="scala">
* import scala.xml._
* class AttrBinds {
* def render(xhtml : NodeSeq) : NodeSeq =
* BindHelpers.bind("test", xhtml,
* FuncAttrBindParam("x", { ns : NodeSeq => Text(ns.text.toUpperCase + "X")}, "id"),
* FuncAttrBindParam("y", { ns : NodeSeq => Text(ns.text.length + "Y")}, ("lift","calcId")))
* </pre>
*
* produces this markup:
*
* <pre name="code" class="xml">
* <div id="FOOX" />
* <div lift:calcId="3Y" />
* </pre>
*
* @param name The name to bind against
* @param value A function that takes the current attribute's value and computes
* the new attribute value
* @param newAttr The new attribute label
*/
final class FuncAttrBindParam(val name: String, value: => NodeSeq => NodeSeq, val newAttr: String)
extends BindParam with BindWithAttr {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(value(in))
}
/**
* BindParam using a function to calculate its value.
*
* This object provides factory methods for convenience.
*
*/
object FuncAttrBindParam {
/**
* Returns an unprefixed attribute binding computed by the provided function
*
* @param name The name to bind against
* @param value The function that will transform the original attribute value
* into the new attribute value
* @param newAttr The new attribute label
*/
def apply(name: String, value: => NodeSeq => NodeSeq, newAttr: String) = new FuncAttrBindParam(name, value, newAttr)
/**
* Returns a prefixed attribute binding computed by the provided function
*
* @param name The name to bind against
* @param value The function that will transform the original attribute value
* into the new attribute value
* @param newAttr The new attribute name in the form (prefix,label)
*/
def apply(name: String, value: => NodeSeq => NodeSeq, newAttr: Pair[String,String]) =
PrefixedBindWithAttr(newAttr._1, new FuncAttrBindParam(name, value, newAttr._2))
}
final class OptionBindParam(val name: String, value: Option[NodeSeq])
extends Tuple2(name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = value
}
object OptionBindParam {
def apply(name: String, value: Option[NodeSeq]) = new OptionBindParam(name, value)
}
final class BoxBindParam(val name: String, value: Box[NodeSeq])
extends Tuple2(name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = value
}
object BoxBindParam {
def apply(name: String, value: Box[NodeSeq]) = new BoxBindParam(name, value)
}
/**
* BindParam that computes an optional new attribute value based on
* the current attribute value. Returning None in the transform function
* will result in the Attribute being omitted. For example, given the
* following markup:
*
* <pre name="code" class="xml">
* <lift:AttrBinds>
* <div test:x="foo">
* <div test:y="foo">
* </lift:AttrBinds>
* </pre>
*
* The following snippet:
*
<pre name="code" class="scala">
import scala.xml._
class AttrBinds {
def render(xhtml : NodeSeq) : NodeSeq =
BindHelpers.bind("test", xhtml,
FuncAttrOptionBindParam("x", { ns : NodeSeq =>
Some(Text(ns.text.toUpperCase + "X"))
}, ("lift","calcId")),
FuncAttrOptionBindParam("y", { ns : NodeSeq =>
if (ns.text.length > 10) {
Some(Text(ns.text.length + "Y"))
} else {
None
}, ("lift","calcId")))
</pre>
*
* produces this markup:
*
* <pre name="code" class="xml">
* <div lift:calcId="FOOX" />
* <div />
* </pre>
*
* @param name The name to bind against
* @param value The function that will transform the original attribute value
* into the new attribute value. Returning None will cause this attribute to
* be omitted.
* @param newAttr The new attribute label
*
*/
final class FuncAttrOptionBindParam(val name: String, func: => NodeSeq => Option[NodeSeq], val newAttr: String)
extends BindParam with BindWithAttr {
def calcValue(in: NodeSeq): Option[NodeSeq] = func(in)
}
/**
* BindParam that computes an optional new attribute value based on
* the current attribute value. Returning None in the transform function
* will result in the Attribute not being bound.
*
* This object provides factory methods for convenience.
*/
object FuncAttrOptionBindParam {
/**
* Returns an unprefixed attribute binding computed by the provided function
*
* @param name The name to bind against
* @param value The function that will transform the original attribute value
* into the new attribute value. Returning None will cause this attribute to
* be omitted.
* @param newAttr The new attribute label
*/
def apply(name: String, func: => NodeSeq => Option[NodeSeq], newAttr: String) =
new FuncAttrOptionBindParam(name, func, newAttr)
/**
* Returns a prefixed attribute binding computed by the provided function
*
* @param name The name to bind against
* @param value The function that will transform the original attribute value
* into the new attribute value. Returning None will cause this attribute to
* be omitted.
* @param newAttr The new attribute name in the form (prefix,label)
*/
def apply(name: String, func: => NodeSeq => Option[NodeSeq], newAttr: Pair[String,String]) =
PrefixedBindWithAttr(newAttr._1, new FuncAttrOptionBindParam(name, func, newAttr._2))
}
/**
* BindParam that computes an optional new attribute value based on
* the current attribute value. Returning Empty in the transform function
* will result in the Attribute being omitted. For example, given the
* following markup:
*
* <pre name="code" class="xml">
* <lift:AttrBinds>
* <div test:x="foo">
* <div test:y="foo">
* </lift:AttrBinds>
* </pre>
*
* The following snippet:
*
<pre name="code" class="scala">
import scala.xml._
class AttrBinds {
def render(xhtml : NodeSeq) : NodeSeq =
BindHelpers.bind("test", xhtml,
FuncAttrBoxBindParam("x", { ns : NodeSeq => Full(Text(ns.text.toUpperCase + "X"))}, ("lift","calcId")),
FuncAttrBoxBindParam("y", { ns : NodeSeq =>
if (ns.text.length > 10) {
Full(Text(ns.text.length + "Y"))
} else {
Empty
}, ("lift","calcId")))
</pre>
*
* produces this markup:
*
* <pre name="code" class="xml">
* <div lift:calcId="FOOX" />
* <div />
* </pre>
*
* @param name The name to bind against
* @param value The function that will transform the original attribute value
* into the new attribute value. Returning Empty will cause this attribute to
* be omitted.
* @param newAttr The new attribute label
*
*/
final class FuncAttrBoxBindParam(val name: String, func: => NodeSeq => Box[NodeSeq], val newAttr: String)
extends BindParam with BindWithAttr {
def calcValue(in: NodeSeq): Option[NodeSeq] = func(in)
}
/**
* BindParam that computes an optional new attribute value based on
* the current attribute value. Returning Empty in the transform function
* will result in the Attribute being omitted.
*
* This object provides factory methods for convenience.
*/
object FuncAttrBoxBindParam {
/**
* Returns an unprefixed attribute binding computed by the provided function
*
* @param name The name to bind against
* @param value The function that will transform the original attribute value
* into the new attribute value. Returning Empty will cause this attribute to
* be omitted.
* @param newAttr The new attribute label
*/
def apply(name: String, func: => NodeSeq => Box[NodeSeq], newAttr: String) =
new FuncAttrBoxBindParam(name, func, newAttr)
/**
* Returns a prefixed attribute binding computed by the provided function
*
* @param name The name to bind against
* @param value The function that will transform the original attribute value
* into the new attribute value. Returning Empty will cause this attribute to
* be omitted.
* @param newAttr The new attribute name in the form (prefix,label)
*/
def apply(name: String, func: => NodeSeq => Box[NodeSeq], newAttr: Pair[String,String]) =
PrefixedBindWithAttr(newAttr._1, new FuncAttrBoxBindParam(name, func, newAttr._2))
}
final class SymbolBindParam(val name: String, value: Symbol)
extends Tuple2(name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(if (null eq value.name) NodeSeq.Empty else Text(value.name))
}
object SymbolBindParam {
def apply(name: String, value: Symbol) = new SymbolBindParam(name, value)
}
final class IntBindParam(val name: String, value: Int)
extends Tuple2[String, Int](name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(value.toString match {
case null => NodeSeq.Empty
case str => Text(str)})
}
object IntBindParam {
def apply(name: String, value: Int) = new IntBindParam(name, value)
}
final class LongBindParam(val name: String, value: Long)
extends Tuple2[String, Long](name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(Text(value.toString))
}
object LongBindParam {
def apply(name: String, value: Long) = new LongBindParam(name, value)
}
final class BooleanBindParam(val name: String, value: Boolean)
extends Tuple2[String, Boolean](name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(Text(value.toString))
}
object BooleanBindParam {
def apply(name: String, value: Boolean) = new BooleanBindParam(name, value)
}
final class TheBindableBindParam[T <: Bindable](val name: String, value: T)
extends Tuple2[String, T](name, value) with BindParam {
def calcValue(in: NodeSeq): Option[NodeSeq] = Some(value.asHtml)
}
object TheBindableBindParam {
def apply[T <: Bindable](name: String, value: T) = new TheBindableBindParam(name, value)
}
/**
* Remove all the <head> tags, just leaving the child tags
*/
def stripHead(in: NodeSeq): NodeSeq = {
("head" #> ((ns: NodeSeq) => ns.asInstanceOf[Elem].child))(in)
}
/**
* Replace the element with the id that matches with the replacement
* nodeseq.
*/
def replaceIdNode(in: NodeSeq, id: String, replacement: NodeSeq): NodeSeq = {
(("#"+id) #> replacement)(in)
}
/**
* transforms a Box into a Text node
*/
@deprecated("use -> instead", "2.4")
object BindParamAssoc {
implicit def canStrBoxNodeSeq(in: Box[Any]): Box[NodeSeq] = in.map(_ match {
case null => Text("null")
case v => v.toString match {
case null => NodeSeq.Empty
case str => Text(str)
}
})
}
/**
* takes a NodeSeq and applies all the attributes to all the Elems at the top level of the
* NodeSeq. The id attribute is applied to the first-found Elem only
*/
def addAttributes(in: NodeSeq, attributes: MetaData): NodeSeq = {
if (attributes == Null) in
else {
val noId = attributes.filter(_.key != "id")
var doneId = false
in map {
case e: Elem =>
if (doneId) e % noId else {
doneId = true
e % attributes
}
case x => x
}
}
}
private def snToNs(in: Seq[Node]): NodeSeq = in
class SuperArrowAssoc(name: String) {
// Because JsObj is a subclass of Node, we don't want it
// getting caught because it's not a bind param
def ->[T <: SpecialNode](in: T with SpecialNode) = Tuple2[String, T](name, in)
def ->(in: String) = TheStrBindParam(name, in)
def ->(in: NodeSeq) = TheBindParam(name, in)
def ->(in: Text) = TheBindParam(name, in)
def ->(in: Node) = TheBindParam(name, in)
def ->(in: Seq[Node]) = TheBindParam(name, in)
def ->(in: NodeSeq => NodeSeq) = FuncBindParam(name, in)
def ->(in: Box[NodeSeq]) = BoxBindParam(name, in)
def ->(in: Option[NodeSeq]) = OptionBindParam(name, in)
def ->(in: Symbol) = SymbolBindParam(name, in)
def ->(in: Int) = IntBindParam(name, in)
def ->(in: Long) = LongBindParam(name, in)
def ->(in: Boolean) = BooleanBindParam(name, in)
def ->[T <: Bindable](in: T with Bindable) = TheBindableBindParam[T](name, in)
def ->[T](in: T) = Tuple2[String, T](name, in)
def -%>(in: NodeSeq) = FuncBindParam(name, old => addAttributes(in , (BindHelpers.currentNode.map(_.attributes) openOr Null)))
def -%>(in: Box[NodeSeq]) = FuncBindParam(name,
old => in.map(a => addAttributes(a,
(BindHelpers.currentNode.map(_.attributes) openOr Null))) openOr
NodeSeq.Empty)
def -%>(in: Option[NodeSeq]) = FuncBindParam(name, old => in.map(a => addAttributes(a,
(BindHelpers.currentNode.map(_.attributes) openOr
Null))) getOrElse NodeSeq.Empty)
def -%>(in: NodeSeq => NodeSeq) = FuncBindParam(name, old => addAttributes(in(old),
(BindHelpers.currentNode.map(_.attributes) openOr Null)))
def _id_>(in: Elem) = FuncBindParam(name, _ => in % new UnprefixedAttribute("id", name, Null))
def _id_>(in: Box[Elem]) = FuncBindParam(name, _ => in.map(_ % new UnprefixedAttribute("id", name, Null)) openOr NodeSeq.Empty)
def _id_>(in: Option[Elem]) = FuncBindParam(name, _ => in.map(_ % new UnprefixedAttribute("id", name, Null)) getOrElse NodeSeq.Empty)
def _id_>(in: NodeSeq => Elem) = FuncBindParam(name, kids => in(kids) % new UnprefixedAttribute("id", name, Null))
}
implicit def strToSuperArrowAssoc(in: String): SuperArrowAssoc = new SuperArrowAssoc(in)
/**
* This class creates a BindParam from an input value
*
* @deprecated use -> instead
*/
@deprecated("use -> instead", "2.4")
class BindParamAssoc(val name: String) {
def -->(value: String): BindParam = TheBindParam(name, if (null eq value) NodeSeq.Empty else Text(value))
def -->(value: NodeSeq): BindParam = TheBindParam(name, value)
def -->(value: Symbol): BindParam = TheBindParam(name, Text(value.name))
def -->(value: Any): BindParam = TheBindParam(name, Text(value match {
case null => "null"
case v => v.toString match {
case null => ""
case str => str
}
}))
def -->(func: NodeSeq => NodeSeq): BindParam = FuncBindParam(name, func)
def -->(value: Box[NodeSeq]): BindParam = TheBindParam(name, value.openOr(Text("Empty")))
}
/**
* transforms a String to a BindParamAssoc object which can be associated to a BindParam object
* using the --> operator.<p/>
* Usage: <code>"David" --> "name"</code>
*
* @deprecated use -> instead
*/
@deprecated("use -> instead", "2.4")
implicit def strToBPAssoc(in: String): BindParamAssoc = new BindParamAssoc(in)
/**
* transforms a Symbol to a SuperArrowAssoc object which can be associated to a BindParam object
* using the -> operator.<p/>
* Usage: <code>'David -> "name"</code>
*
* @deprecated use -> instead
*/
@deprecated("use -> instead", "2.4")
implicit def symToSAAssoc(in: Symbol): SuperArrowAssoc = new SuperArrowAssoc(in.name)
/**
* Experimental extension to bind which passes in an additional "parameter" from the XHTML to the transform
* function, which can be used to format the returned NodeSeq.
*
* @deprecated use bind instead
*/
@deprecated("use bind instead", "2.4")
def xbind(namespace: String, xml: NodeSeq)(transform: PartialFunction[String, NodeSeq => NodeSeq]): NodeSeq = {
def rec_xbind(xml: NodeSeq): NodeSeq = {
xml.flatMap {
node => node match {
case s: Elem if (node.prefix == namespace) =>
if (transform.isDefinedAt(node.label))
transform(node.label)(node)
else
Text("FIX"+"ME failed to bind <"+namespace+":"+node.label+" />")
case Group(nodes) => Group(rec_xbind(nodes))
case s: Elem => Elem(node.prefix, node.label, node.attributes, node.scope, rec_xbind(node.child): _*)
case n => node
}
}
}
rec_xbind(xml)
}
/**
* Bind a set of values to parameters and attributes in a block of XML.<p/>
*
* For example: <pre name="code" class="scala">
* bind("user", <user:hello>replace this</user:hello>, "hello" -> <h1/>)
* </pre>
* will return <pre><h1></h1></pre>
* @param namespace the namespace of tags to bind
* @param xml the NodeSeq in which to find elements to be bound.
* @param params the list of BindParam bindings to be applied
*
* @return the NodeSeq that results from the specified transforms
*/
def bind(namespace: String, xml: NodeSeq, params: BindParam*): NodeSeq =
bind(namespace, Empty, Empty, xml, params: _*)
/**
* Bind a set of values to parameters and attributes in a block of XML
* with defined transforms for unbound elements within the specified
* namespace.<p/>
*
* For example:<pre name="code" class="scala">
* bind("user",
* Full(xhtml: NodeSeq => Text("Default Value")),
* Empty,
* <user:hello>replace this</user:hello><user:dflt>replace with default</user:dflt>,
* "hello" -> <h1/>)
* </pre>
* will return <pre><h1></h1>Default Value</pre>
*
* @param namespace the namespace of tags to bind
* @param nodeFailureXform a box containing the function to use as the default transform
* for tags in the specified namespace that do not have bindings specified.
* @param paramFailureXform a box containing the function to use as the default transform
* for unrecognized attributes in bound elements.
* @param xml the NodeSeq in which to find elements to be bound.
* @param params the list of BindParam bindings to be applied
*
* @return the NodeSeq that results from the specified transforms
*/
def bind(namespace: String, nodeFailureXform: Box[NodeSeq => NodeSeq],
paramFailureXform: Box[PrefixedAttribute => MetaData],
xml: NodeSeq, params: BindParam*): NodeSeq =
bind(namespace, nodeFailureXform, paramFailureXform, false, xml, params: _*)
/**
* Bind a set of values to parameters and attributes in a block of XML
* with defined transforms for unbound elements within the specified
* namespace.<p/>
*
* For example:<pre name="code" class="scala">
* bind("user",
* Full(xhtml: NodeSeq => Text("Default Value")),
* Empty,
* <user:hello>replace this</user:hello><user:dflt>replace with default</user:dflt>,
* "hello" -> <h1/>)
* </pre>
* will return <pre><h1></h1>Default Value</pre>
*
* @param namespace the namespace of tags to bind
* @param nodeFailureXform a box containing the function to use as the default transform
* for tags in the specified namespace that do not have bindings specified.
* @param paramFailureXform a box containing the function to use as the default transform
* for unrecognized attributes in bound elements.
* @param preserveScope: true if the scope should be preserved, false is the normal setting
* @param xml the NodeSeq in which to find elements to be bound.
* @param params the list of BindParam bindings to be applied
*
* @return the NodeSeq that results from the specified transforms
*/
def bind(namespace: String, nodeFailureXform: Box[NodeSeq => NodeSeq],
paramFailureXform: Box[PrefixedAttribute => MetaData],
preserveScope: Boolean,
xml: NodeSeq, params: BindParam*): NodeSeq = {
val nsColon = namespace + ":"
BindHelpers._bindNodes.doWith(xml :: (BindHelpers._bindNodes.box.openOr(Nil))) {
val map: scala.collection.immutable.Map[String, BindParam] = scala.collection.immutable.HashMap.empty ++ params.map(p => (p.name, p))
def attrBind(attr: MetaData): MetaData = attr match {
case Null => Null
case upa: UnprefixedAttribute => new UnprefixedAttribute(upa.key, upa.value, attrBind(upa.next))
case pa: PrefixedAttribute if pa.pre == namespace => map.get(pa.key) match {
case None => paramFailureXform.map(_(pa)) openOr new PrefixedAttribute(pa.pre, pa.key, Text("FIX"+"ME find to bind attribute"), attrBind(pa.next))
case Some(PrefixedBindWithAttr(prefix,binding)) => binding.calcValue(pa.value).map(v => new PrefixedAttribute(prefix, binding.newAttr, v, attrBind(pa.next))) getOrElse attrBind(pa.next)
case Some(abp: BindWithAttr) => abp.calcValue(pa.value).map(v => new UnprefixedAttribute(abp.newAttr, v, attrBind(pa.next))) getOrElse attrBind(pa.next)
case Some(bp: BindParam) => bp.calcValue(pa.value).map(v => new PrefixedAttribute(pa.pre, pa.key, v, attrBind(pa.next))) getOrElse attrBind(pa.next)
}
case pa: PrefixedAttribute => new PrefixedAttribute(pa.pre, pa.key, pa.value, attrBind(pa.next))
}
def in_bind(xml: NodeSeq): NodeSeq = {
xml.flatMap {
case BoundAttr(e, av) if av.startsWith(nsColon) => {
val fixedAttrs = e.attributes.filter {
case up: UnprefixedAttribute => true
case pa: PrefixedAttribute => {
val res = !(pa.pre == "lift" && pa.key == "bind")
res
}
case _ => true
}
val fixedLabel = av.substring(nsColon.length)
val fake = new Elem(namespace, fixedLabel, fixedAttrs,
e.scope, new Elem(e.namespace,
e.label,
fixedAttrs,
e.scope,
e.child :_*))
BindHelpers._currentNode.doWith(fake) {
map.get(fake.label) match {
case None =>
nodeFailureXform.map(_(fake)) openOr fake
case Some(ns) =>
ns.calcValue(fake.child) getOrElse NodeSeq.Empty
}
}
}
case s: Elem if s.prefix == namespace => BindHelpers._currentNode.doWith(s) {
map.get(s.label) match {
case None =>
nodeFailureXform.map(_(s)) openOr s
case Some(ns) =>
//val toRet = ns.calcValue(s.child)
//mergeBindAttrs(toRet, namespace, s.attributes)
ns.calcValue(s.child) getOrElse NodeSeq.Empty
}
}
case s: Elem if bindByNameType(s.label) && (attrStr(s, "name").startsWith(namespace+":")) &&
bindByNameTag(namespace, s) != "" => BindHelpers._currentNode.doWith(s) {
val tag = bindByNameTag(namespace, s)
map.get(tag) match {
case None => nodeFailureXform.map(_(s)) openOr s
case Some(bindParam) => bindByNameMixIn(bindParam, s)
}
}
case Group(nodes) => Group(in_bind(nodes))
case s: Elem => Elem(s.prefix, s.label, attrBind(s.attributes), if (preserveScope) s.scope else TopScope,