|
1 /* |
|
2 * Copyright 2011 Tomas Zeman <tzeman@volny.cz> |
|
3 * |
|
4 * Licensed under the Apache License, Version 2.0 (the "License"); |
|
5 * you may not use this file except in compliance with the License. |
|
6 * You may obtain a copy of the License at |
|
7 * |
|
8 * http://www.apache.org/licenses/LICENSE-2.0 |
|
9 * |
|
10 * Unless required by applicable law or agreed to in writing, software |
|
11 * distributed under the License is distributed on an "AS IS" BASIS, |
|
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
13 * See the License for the specific language governing permissions and |
|
14 * limitations under the License. |
|
15 */ |
|
16 package net.tz.lift.snippet |
|
17 |
|
18 import net.liftweb.common._ |
|
19 import net.liftweb.util.Helpers._ |
|
20 import scala.xml.{Elem, NodeSeq, Text} |
|
21 |
|
22 object Column { |
|
23 def apply[T](name: String, f: T => NodeSeq): Column[T] = |
|
24 new Column[T](Text(name), f, { _ => Empty}) |
|
25 def apply[T](name: String, f: T => NodeSeq, tdCss: String): Column[T] = |
|
26 new Column[T](Text(name), f, { _ => Full(tdCss)}) |
|
27 } |
|
28 |
|
29 class Column[T](name: => NodeSeq, f: T => NodeSeq, tdCss: T => Box[String]) |
|
30 extends Function1[T, NodeSeq] { |
|
31 |
|
32 def th: Elem = <th>{name}</th> |
|
33 def td(in: T): Elem = { |
|
34 val r = <td>{apply(in)}</td> |
|
35 tdCss(in) map { css => r % ("class" -> css) } openOr r |
|
36 } |
|
37 def apply(in: T): NodeSeq = f(in) |
|
38 } |
|
39 |
|
40 object Table { |
|
41 def apply[T](cols: Iterable[Column[T]], rows: Iterable[T]) = new Table(Empty, |
|
42 cols, rows, Empty) |
|
43 def apply[T](css: String, cols: Iterable[Column[T]], rows: Iterable[T], |
|
44 foot: NodeSeq) = new Table(Full(css), cols, rows, Full(foot)) |
|
45 } |
|
46 |
|
47 class Table[T](css: Box[String], cols: Iterable[Column[T]], |
|
48 rows: => Iterable[T], foot: Box[NodeSeq]) extends |
|
49 Function1[NodeSeq, NodeSeq] { |
|
50 |
|
51 def oddEven(i: Int) = (i % 2) match { |
|
52 case 1 => "even" |
|
53 case 0 => "odd" |
|
54 } |
|
55 |
|
56 def thead: Elem = <thead><tr>{ cols.map(c => c.th) }</tr></thead> |
|
57 def tbody: Elem = <tbody>{ |
|
58 rows.zipWithIndex.map( r => tr(r._1, r._2)) |
|
59 }</tbody> |
|
60 def tr(in: T, idx: Int): Elem = <tr class={oddEven(idx)}>{ |
|
61 cols.map(_.td(in)) |
|
62 }</tr> |
|
63 |
|
64 def tfoot: Elem = <tfoot>{ |
|
65 foot map { f => <tr><td colspan={cols.size.toString}>{f}</td></tr> |
|
66 } openOr NodeSeq.Empty |
|
67 }</tfoot> |
|
68 |
|
69 def apply(ns: NodeSeq): NodeSeq = { |
|
70 val t = <table>{ |
|
71 List(thead, tfoot, tbody) |
|
72 }</table> |
|
73 css map { cl => t % ("class" -> cl) } openOr t |
|
74 } |
|
75 |
|
76 } |
|
77 |
|
78 // vim: set ts=2 sw=2 et: |