lib: fix nitish in nitunits
[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 # var img = new HTMLTag("img")
130 # img.attr("src", "./image.png").attr("alt", "image")
131 # assert img.get_attr("src") == "./image.png"
132 fun get_attr(key: String): nullable String do
133 if not attrs.has_key(key) then return null
134 return attrs[key]
135 end
136
137 # Set a 'value' for 'key'
138 # var img = new HTMLTag("img")
139 # img.attr("src", "./image.png").attr("alt", "image")
140 # assert img.write_to_string == """<img src=".&#47;image.png" alt="image"/>"""
141 fun attr(key: String, value: String): HTMLTag do
142 attrs[key] = value
143 return self
144 end
145
146 # Add a CSS class to the HTML tag
147 # var img = new HTMLTag("img")
148 # img.add_class("logo").add_class("fullpage")
149 # assert img.write_to_string == """<img class="logo fullpage"/>"""
150 fun add_class(klass: String): HTMLTag do
151 classes.add(klass)
152 return self
153 end
154
155 # CSS classes
156 var classes: Set[String] = new HashSet[String]
157
158 # Add multiple CSS classes
159 # var img = new HTMLTag("img")
160 # img.add_classes(["logo", "fullpage"])
161 # assert img.write_to_string == """<img class="logo fullpage"/>"""
162 fun add_classes(classes: Collection[String]): HTMLTag do
163 self.classes.add_all(classes)
164 return self
165 end
166
167 # Set a CSS 'value' for 'prop'
168 # var img = new HTMLTag("img")
169 # img.css("border", "2px solid black").css("position", "absolute")
170 # assert img.write_to_string == """<img style="border: 2px solid black; position: absolute"/>"""
171 fun css(prop: String, value: String): HTMLTag do
172 css_props[prop] = value
173 return self
174 end
175 private var css_props: Map[String, String] = new HashMap[String, String]
176
177 # Get CSS value for 'prop'
178 # var img = new HTMLTag("img")
179 # img.css("border", "2px solid black").css("position", "absolute")
180 # assert img.get_css("border") == "2px solid black"
181 # assert img.get_css("color") == null
182 fun get_css(prop: String): nullable String do
183 if not css_props.has_key(prop) then return null
184 return css_props[prop]
185 end
186
187 # Replace `self` by `parent`.
188 #
189 # var elem = new HTMLTag("li")
190 # elem.add_outer(new HTMLTag("ul"))
191 # assert elem.write_to_string == "<ul><li></li></ul>"
192 fun add_outer(parent: HTMLTag) do
193 # copy self in new object
194 var child = new HTMLTag(self.tag)
195 child.attrs = self.attrs
196 child.classes = self.classes
197 child.css_props = self.css_props
198 child.children = self.children
199 # add copy in parent children elements
200 parent.children.add(child)
201 # replace self by parent
202 self.tag = parent.tag
203 self.attrs = parent.attrs
204 self.classes = parent.classes
205 self.css_props = parent.css_props
206 self.is_void = parent.is_void
207 self.children = parent.children
208 end
209
210 # Add a HTML 'child' to self
211 # var ul = new HTMLTag("ul")
212 # ul.add(new HTMLTag("li"))
213 # assert ul.write_to_string == "<ul><li></li></ul>"
214 # returns `self` for fluent programming
215 fun add(child: HTMLTag): HTMLTag
216 do
217 children.add(child)
218 return self
219 end
220
221 # Create a new HTMLTag child and return it
222 #
223 # var ul = new HTMLTag("ul")
224 # ul.open("li").append("1").append("2")
225 # ul.open("li").append("3").append("4")
226 # assert ul.write_to_string == "<ul><li>12</li><li>34</li></ul>"
227 fun open(tag: String): HTMLTag
228 do
229 var res = new HTMLTag(tag)
230 add(res)
231 return res
232 end
233
234 # List of children HTML elements
235 var children: Set[HTMLTag] = new HashSet[HTMLTag]
236
237 # Clear all child and set the text of element
238 # var p = new HTMLTag("p")
239 # p.text("Hello World!")
240 # assert p.write_to_string == "<p>Hello World!</p>"
241 # Text is escaped see: `standard::String::html_escape`
242 fun text(txt: String): HTMLTag do
243
244 children.clear
245 append(txt)
246 return self
247 end
248
249 # Append text to element
250 # var p = new HTMLTag("p")
251 # p.append("Hello")
252 # p.add(new HTMLTag("br"))
253 # p.append("World!")
254 # assert p.write_to_string == "<p>Hello<br/>World!</p>"
255 # Text is escaped see: standard::String::html_escape
256 fun append(txt: String): HTMLTag do
257 add(new HTMLRaw("", txt.html_escape))
258 return self
259 end
260
261 # Append raw HTML to element
262 #
263 # var p = new HTMLTag("p")
264 # p.append("Hello")
265 # p.add_raw_html("<bla/>foo")
266 # assert p.write_to_string == "<p>Hello<bla/>foo</p>"
267 #
268 # Note: the HTML in insered as it, no verification is done.
269 fun add_raw_html(txt: String): HTMLTag do
270 add(new HTMLRaw("", txt))
271 return self
272 end
273
274 redef fun write_to(stream) do
275 var res = new Array[String]
276 render_in(res)
277 for r in res do
278 stream.write(r)
279 end
280 end
281
282 # In order to avoid recursive concatenation,
283 # this function collects in `res` all the small fragments of `String`
284 private fun render_in(res: Sequence[String])
285 do
286 res.add "<"
287 res.add tag
288 render_attrs_in(res)
289 if is_void and children.is_empty then
290 res.add "/>"
291 else
292 res.add ">"
293 for child in children do child.render_in(res)
294 res.add "</"
295 res.add tag
296 res.add ">"
297 end
298 end
299
300 private fun render_attrs_in(res: Sequence[String]) do
301 if attrs.has_key("class") or not classes.is_empty then
302 res.add " class=\""
303 for cls in classes do
304 res.add cls.html_escape
305 res.add " "
306 end
307 if attrs.has_key("class") then
308 res.add attrs["class"].html_escape
309 res.add " "
310 end
311 if res.last == " " then res.pop
312 res.add "\""
313 end
314
315 if attrs.has_key("style") or not css_props.is_empty then
316 res.add " style=\""
317 for k, v in css_props do
318 res.add k.html_escape
319 res.add ": "
320 res.add v.html_escape
321 res.add "; "
322 end
323 if attrs.has_key("style") then
324 res.add(attrs["style"].html_escape)
325 end
326 if res.last == "; " then res.pop
327 res.add "\""
328 end
329
330 if attrs.is_empty then return
331
332 for key, value in attrs do
333 if key == "class" or key == "style" then continue
334 res.add " "
335 res.add key.html_escape
336 res.add "=\""
337 res.add value.html_escape
338 res.add "\""
339 end
340 end
341 end
342
343 private class HTMLRaw
344 super HTMLTag
345
346 var content: String
347 redef fun render_in(res) do res.add content
348 end