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