d3a92eb628d7c0a4e7ff7c9272005c33ec26ccd6
[nit.git] / lib / html / html.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # HTML output facilities
16 module html
17
18 # A html page
19 #
20 # You can define subclass and override methods head and body
21 #
22 # ~~~nitish
23 # class MyPage
24 # super HTMLPage
25 # redef body do add("p").text("Hello World!")
26 # end
27 # ~~~
28 #
29 # HTMLPage use fluent interface so you can chain calls as:
30 #
31 # ~~~nitish
32 # add("div").attr("id", "mydiv").text("My Div")
33 # ~~~
34 class HTMLPage
35 super Writable
36
37 # Define head content
38 fun head do end
39 # Define body content
40 fun body do end
41
42 private var root = new HTMLTag("html")
43 private var current: HTMLTag = root
44 private var stack = new List[HTMLTag]
45
46 redef fun write_to(stream) do
47 root.children.clear
48 open("head")
49 head
50 close("head")
51 open("body")
52 body
53 close("body")
54 stream.write "<!DOCTYPE html>"
55 root.write_to(stream)
56 end
57
58 # Add a html tag to the current element
59 #
60 # ~~~nitish
61 # add("div").attr("id", "mydiv").text("My Div")
62 # ~~~
63 fun add(tag: String): HTMLTag do
64 var node = new HTMLTag(tag)
65 current.add(node)
66 return node
67 end
68
69 # Add a raw html string
70 #
71 # ~~~nitish
72 # add_html("<a href='#top'>top</a>")
73 # ~~~
74 fun add_html(html: String) do current.add(new HTMLRaw("", html))
75
76 # Open a html tag
77 #
78 # ~~~nitish
79 # open("ul")
80 # add("li").text("item1")
81 # add("li").text("item2")
82 # close("ul")
83 # ~~~
84 fun open(tag: String): HTMLTag do
85 stack.push(current)
86 current = add(tag)
87 return current
88 end
89
90 # Close previously opened tag
91 # Ensure: tag = previous.tag
92 fun close(tag: String) do
93 if not tag == current.tag then
94 print "Error: Trying to close '{tag}', last opened tag was '{current.tag}'."
95 abort
96 end
97 current = stack.pop
98 end
99 end
100
101 # An HTML element.
102 class HTMLTag
103 super Writable
104
105 # HTML element type.
106 #
107 # `"div"` for `<div></div>`.
108 var tag: String
109 init do
110 self.is_void = (once ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]).has(tag)
111 end
112
113 # Is the HTML element a void element?
114 #
115 # assert (new HTMLTag("img")).is_void == true
116 # assert (new HTMLTag("p")).is_void == false
117 var is_void: Bool is noinit
118
119 # Create a HTML elements with the specifed type and attributes.
120 init with_attrs(tag: String, attrs: Map[String, String]) do
121 self.tag = tag
122 self.attrs = attrs
123 end
124
125 # Tag attributes map
126 var attrs: Map[String, String] = new HashMap[String, String]
127
128 # Get the attributed value of 'prop' or null if 'prop' is undifened
129 #
130 # var img = new HTMLTag("img")
131 # img.attr("src", "./image.png").attr("alt", "image")
132 # assert img.get_attr("src") == "./image.png"
133 fun get_attr(key: String): nullable String do
134 if not attrs.has_key(key) then return null
135 return attrs[key]
136 end
137
138 # Set a 'value' for 'key'
139 #
140 # var img = new HTMLTag("img")
141 # img.attr("src", "./image.png").attr("alt", "image")
142 # assert img.write_to_string == """<img src=".&#47;image.png" alt="image"/>"""
143 fun attr(key: String, value: String): HTMLTag do
144 attrs[key] = value
145 return self
146 end
147
148 # Add a CSS class to the HTML tag
149 #
150 # var img = new HTMLTag("img")
151 # img.add_class("logo").add_class("fullpage")
152 # assert img.write_to_string == """<img class="logo fullpage"/>"""
153 fun add_class(klass: String): HTMLTag do
154 classes.add(klass)
155 return self
156 end
157
158 # CSS classes
159 var classes: Set[String] = new HashSet[String]
160
161 # Add multiple CSS classes
162 #
163 # var img = new HTMLTag("img")
164 # img.add_classes(["logo", "fullpage"])
165 # assert img.write_to_string == """<img class="logo fullpage"/>"""
166 fun add_classes(classes: Collection[String]): HTMLTag do
167 self.classes.add_all(classes)
168 return self
169 end
170
171 # Set a CSS 'value' for 'prop'
172 #
173 # var img = new HTMLTag("img")
174 # img.css("border", "2px solid black").css("position", "absolute")
175 # assert img.write_to_string == """<img style="border: 2px solid black; position: absolute"/>"""
176 fun css(prop: String, value: String): HTMLTag do
177 css_props[prop] = value
178 return self
179 end
180 private var css_props: Map[String, String] = new HashMap[String, String]
181
182 # Get CSS value for 'prop'
183 #
184 # var img = new HTMLTag("img")
185 # img.css("border", "2px solid black").css("position", "absolute")
186 # assert img.get_css("border") == "2px solid black"
187 # assert img.get_css("color") == null
188 fun get_css(prop: String): nullable String do
189 if not css_props.has_key(prop) then return null
190 return css_props[prop]
191 end
192
193 # Replace `self` by `parent`.
194 #
195 # var elem = new HTMLTag("li")
196 # elem.add_outer(new HTMLTag("ul"))
197 # assert elem.write_to_string == "<ul><li></li></ul>"
198 fun add_outer(parent: HTMLTag) do
199 # copy self in new object
200 var child = new HTMLTag(self.tag)
201 child.attrs = self.attrs
202 child.classes = self.classes
203 child.css_props = self.css_props
204 child.children = self.children
205 # add copy in parent children elements
206 parent.children.add(child)
207 # replace self by parent
208 self.tag = parent.tag
209 self.attrs = parent.attrs
210 self.classes = parent.classes
211 self.css_props = parent.css_props
212 self.is_void = parent.is_void
213 self.children = parent.children
214 end
215
216 # Add a HTML 'child' to self
217 #
218 # var ul = new HTMLTag("ul")
219 # ul.add(new HTMLTag("li"))
220 # assert ul.write_to_string == "<ul><li></li></ul>"
221 # returns `self` for fluent programming
222 fun add(child: HTMLTag): HTMLTag
223 do
224 children.add(child)
225 return self
226 end
227
228 # Create a new HTMLTag child and return it
229 #
230 # var ul = new HTMLTag("ul")
231 # ul.open("li").append("1").append("2")
232 # ul.open("li").append("3").append("4")
233 # assert ul.write_to_string == "<ul><li>12</li><li>34</li></ul>"
234 fun open(tag: String): HTMLTag
235 do
236 var res = new HTMLTag(tag)
237 add(res)
238 return res
239 end
240
241 # List of children HTML elements
242 var children: Set[HTMLTag] = new HashSet[HTMLTag]
243
244 # Clear all child and set the text of element
245 #
246 # var p = new HTMLTag("p")
247 # p.text("Hello World!")
248 # assert p.write_to_string == "<p>Hello World!</p>"
249 # Text is escaped see: `core::String::html_escape`
250 fun text(txt: String): HTMLTag do
251
252 children.clear
253 append(txt)
254 return self
255 end
256
257 # Append text to element
258 #
259 # var p = new HTMLTag("p")
260 # p.append("Hello")
261 # p.add(new HTMLTag("br"))
262 # p.append("World!")
263 # assert p.write_to_string == "<p>Hello<br/>World!</p>"
264 # Text is escaped see: core::String::html_escape
265 fun append(txt: String): HTMLTag do
266 add(new HTMLRaw("", txt.html_escape))
267 return self
268 end
269
270 # Append raw HTML to element
271 #
272 # var p = new HTMLTag("p")
273 # p.append("Hello")
274 # p.add_raw_html("<bla/>foo")
275 # assert p.write_to_string == "<p>Hello<bla/>foo</p>"
276 #
277 # Note: the HTML in insered as it, no verification is done.
278 fun add_raw_html(txt: String): HTMLTag do
279 add(new HTMLRaw("", txt))
280 return self
281 end
282
283 redef fun write_to(stream) do
284 var res = new Array[String]
285 render_in(res)
286 for r in res do
287 stream.write(r)
288 end
289 end
290
291 # In order to avoid recursive concatenation,
292 # this function collects in `res` all the small fragments of `String`
293 private fun render_in(res: Sequence[String])
294 do
295 res.add "<"
296 res.add tag
297 render_attrs_in(res)
298 if is_void and children.is_empty then
299 res.add "/>"
300 else
301 res.add ">"
302 for child in children do child.render_in(res)
303 res.add "</"
304 res.add tag
305 res.add ">"
306 end
307 end
308
309 private fun render_attrs_in(res: Sequence[String]) do
310 if attrs.has_key("class") or not classes.is_empty then
311 res.add " class=\""
312 for cls in classes do
313 res.add cls.html_escape
314 res.add " "
315 end
316 if attrs.has_key("class") then
317 res.add attrs["class"].html_escape
318 res.add " "
319 end
320 if res.last == " " then res.pop
321 res.add "\""
322 end
323
324 if attrs.has_key("style") or not css_props.is_empty then
325 res.add " style=\""
326 for k, v in css_props do
327 res.add k.html_escape
328 res.add ": "
329 res.add v.html_escape
330 res.add "; "
331 end
332 if attrs.has_key("style") then
333 res.add(attrs["style"].html_escape)
334 end
335 if res.last == "; " then res.pop
336 res.add "\""
337 end
338
339 if attrs.is_empty then return
340
341 for key, value in attrs do
342 if key == "class" or key == "style" then continue
343 res.add " "
344 res.add key.html_escape
345 res.add "=\""
346 res.add value.html_escape
347 res.add "\""
348 end
349 end
350 end
351
352 private class HTMLRaw
353 super HTMLTag
354
355 var content: String
356 redef fun render_in(res) do res.add content
357 end