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