Stdlib: Ropes implementation, supports Mutable and Immutable versions
[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
31 # Define head content
32 fun head do end
33 # Define body content
34 fun body do end
35
36 private var root = new HTMLTag("html")
37 private var current: HTMLTag = root
38 private var stack = new List[HTMLTag]
39
40 # Render the page as a html string
41 fun render: String do
42 root.children.clear
43 open("head")
44 head
45 close("head")
46 open("body")
47 body
48 close("body")
49 return "<!DOCTYPE html>{root.html}"
50 end
51
52 # Add a html tag to the current element
53 # add("div").attr("id", "mydiv").text("My Div")
54 fun add(tag: String): HTMLTag do
55 var node = new HTMLTag(tag)
56 current.add(node)
57 return node
58 end
59
60 # Add a raw html string
61 # add_html("<a href='#top'>top</a>")
62 fun add_html(html: String) do current.add(new HTMLRaw(html))
63
64 # Open a html tag
65 # open("ul")
66 # add("li").text("item1")
67 # add("li").text("item2")
68 # close("ul")
69 fun open(tag: String): HTMLTag do
70 stack.push(current)
71 current = add(tag)
72 return current
73 end
74
75 # Close previously opened tag
76 # Ensure: tag = previous.tag
77 fun close(tag: String) do
78 if not tag == current.tag then
79 print "Error: Trying to close '{tag}', last opened tag was '{current.tag}'."
80 abort
81 end
82 current = stack.pop
83 end
84
85 # Save html page in the specified file
86 fun save(file: String) do
87 var out = new OFStream.open(file)
88 out.write(self.render)
89 out.close
90 end
91 end
92
93 class HTMLTag
94 # HTML tagname: 'div' for <div></div>
95 var tag: String
96 init(tag: String) do self.tag = tag
97
98 init with_attrs(tag: String, attrs: Map[String, String]) do
99 self.tag = tag
100 self.attrs = attrs
101 end
102
103 # Tag attributes map
104 var attrs: Map[String, String] = new HashMap[String, String]
105
106 # Get the attributed value of 'prop' or null if 'prop' is undifened
107 fun get_attr(key: String): nullable String do
108 if not attrs.has_key(key) then return null
109 return attrs[key]
110 end
111
112 # Set a 'value' for 'key'
113 # var img = new HTMLTag("img")
114 # img.attr("src", "./image.png").attr("alt", "image")
115 fun attr(key: String, value: String): HTMLTag do
116 attrs[key] = value
117 return self
118 end
119
120 # Add a CSS class to the HTML tag
121 # var img = new HTMLTag("img")
122 # img.add_class("logo").add_class("fullpage")
123 fun add_class(klass: String): HTMLTag do
124 classes.add(klass)
125 return self
126 end
127 private var classes: Set[String] = new HashSet[String]
128
129 # Add multiple CSS classes
130 fun add_classes(classes: Collection[String]): HTMLTag do
131 self.classes.add_all(classes)
132 return self
133 end
134
135 # Set a CSS 'value' for 'prop'
136 # var img = new HTMLTag("img")
137 # img.css("border", "2px solid black").css("position", "absolute")
138 fun css(prop: String, value: String): HTMLTag do
139 css_props[prop] = value
140 return self
141 end
142 private var css_props: Map[String, String] = new HashMap[String, String]
143
144 # Get CSS value for 'prop'
145 fun get_css(prop: String): nullable String do
146 if not css_props.has_key(prop) then return null
147 return css_props[prop]
148 end
149
150 # Add a HTML 'child' to self
151 # var ul = new HTMLTag("ul")
152 # ul.add(new HTMLTag("li"))
153 fun add(child: HTMLTag) do children.add(child)
154
155 # List of children HTML elements
156 var children: Set[HTMLTag] = new HashSet[HTMLTag]
157
158 # Clear all child and set the text of element
159 # var p = new HTMLTag("p")
160 # p.text("Hello World!")
161 # assert p.html == "<p>Hello World!</p>"
162 # Text is escaped see: `standard::String::html_escape`
163 fun text(txt: String): HTMLTag do
164
165 children.clear
166 append(txt)
167 return self
168 end
169
170 # Append text to element
171 # var p = new HTMLTag("p")
172 # p.append("Hello")
173 # p.add(new HTMLTag("br"))
174 # p.append("World!")
175 # assert p.html == "<p>Hello<br/>World!</p>"
176 # Text is escaped see: standard::String::html_escape
177 fun append(txt: String): HTMLTag do
178 add(new HTMLRaw(txt.html_escape))
179 return self
180 end
181
182 # Append raw HTML to element
183 # var p = new HTMLTag("p")
184 # p.append("Hello")
185 # p.add_raw_html("<bla/>")
186 # p.html #- "<p>Hello<bla/></p>"
187 # Note: the HTML in insered as it, no verification is done
188 fun add_raw_html(txt: String): HTMLTag do
189 add(new HTMLRaw(txt))
190 return self
191 end
192
193 # Render the element as HTML string
194 fun html: String do
195 var res = new Array[String]
196 render_in(res)
197 return res.to_s
198 end
199
200 # Save html page in the specified file
201 fun save(file: String) do
202 var out = new OFStream.open(file)
203 var res = new Array[String]
204 render_in(res)
205 for r in res do
206 out.write(r)
207 end
208 out.close
209 end
210
211 # In order to avoid recursive concatenation,
212 # this function collects in `res` all the small fragments of `String`
213 private fun render_in(res: Sequence[String])
214 do
215 res.add "<"
216 res.add tag
217 render_attrs_in(res)
218 if tag != "script" and children.is_empty then
219 res.add "/>"
220 else
221 res.add ">"
222 for child in children do child.render_in(res)
223 res.add "</"
224 res.add tag
225 res.add ">"
226 end
227 end
228
229 private fun render_attrs_in(res: Sequence[String]) do
230 if attrs.has_key("class") or not classes.is_empty then
231 res.add " class=\""
232 for cls in classes do
233 res.add cls.html_escape
234 res.add " "
235 end
236 if attrs.has_key("class") then
237 res.add attrs["class"].html_escape
238 res.add " "
239 end
240 if res.last == " " then res.pop
241 res.add "\""
242 end
243
244 if attrs.has_key("style") or not css_props.is_empty then
245 res.add " style=\""
246 for k, v in attrs do
247 res.add k.html_escape
248 res.add ": "
249 res.add v.html_escape
250 res.add "; "
251 end
252 if attrs.has_key("style") then
253 res.add(attrs["style"].html_escape)
254 end
255 if res.last == "; " then res.pop
256 res.add "\""
257 end
258
259 if attrs.is_empty then return
260
261 for key, value in attrs do
262 if key == "class" or key == "style" then continue
263 res.add " "
264 res.add key.html_escape
265 res.add "=\""
266 res.add value.html_escape
267 res.add "\""
268 end
269 end
270 end
271
272 private class HTMLRaw
273 super HTMLTag
274
275 private var content: String
276 init(content: String) do self.content = content
277 redef fun html do return content
278 redef fun render_in(res) do res.add content
279 end