nitiwiki: add a dhref helper function
[nit.git] / contrib / nitiwiki / src / wiki_links.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 # Wiki internal links handling.
16 module wiki_links
17
18 import wiki_base
19 import markdown::wikilinks
20 import ordered_tree
21
22 redef class Nitiwiki
23 # Looks up a WikiEntry by its `name`.
24 #
25 # Rules are:
26 # 1. Looks in the current section
27 # 2. Looks in the current section children
28 # 3. Looks in the current section parent
29 # 4. Looks up to wiki root
30 #
31 # Returns `null` if no article can be found.
32 fun lookup_entry_by_name(context: WikiEntry, name: String): nullable WikiEntry do
33 var section: nullable WikiEntry = context.parent or else context
34 var res = section.lookup_entry_by_name(name)
35 if res != null then return res
36 while section != null do
37 if section.name == name then return section
38 if section.children.has_key(name) then return section.children[name]
39 section = section.parent
40 end
41 return null
42 end
43
44 # Looks up a WikiEntry by its `title`.
45 #
46 # Rules are:
47 # 1. Looks in the current section
48 # 2. Looks in the current section children
49 # 3. Looks in the current section parent
50 # 4. Looks up to wiki root
51 #
52 # Returns `null` if no article can be found.
53 fun lookup_entry_by_title(context: WikiEntry, title: String): nullable WikiEntry do
54 var section: nullable WikiEntry = context.parent or else context
55 var res = section.lookup_entry_by_title(title)
56 if res != null then return res
57 while section != null do
58 if section.title.to_lower == title.to_lower then return section
59 for child in section.children.values do
60 if child.title.to_lower == title.to_lower then return child
61 end
62 section = section.parent
63 end
64 return null
65 end
66
67 # Looks up a WikiEntry by its `path`.
68 #
69 # Path can be relative from `context` like `context/entry`.
70 # Or absolute like `/entry1/entry2`.
71 #
72 # Returns `null` if no article can be found.
73 fun lookup_entry_by_path(context: WikiEntry, path: String): nullable WikiEntry do
74 var entry = context.parent or else context
75 var parts = path.split_with("/")
76 if path.has_prefix("/") then
77 entry = root_section
78 if parts.is_empty then return root_section.index
79 parts.shift
80 end
81 while not parts.is_empty do
82 var name = parts.shift
83 if name.is_empty then continue
84 if entry.name == name then continue
85 if not entry.children.has_key(name) then return null
86 entry = entry.children[name]
87 end
88 return entry
89 end
90
91 # Trails between pages
92 #
93 # Trails are represented as a forest of entries.
94 # This way it is possible to represent a flat-trail as a visit of a tree.
95 var trails = new OrderedTree[WikiEntry]
96 end
97
98 redef class WikiEntry
99
100 # Relative path to `self` from the target root_url
101 fun href: String do return breadcrumbs.join("/")
102
103 # Relative path to the directory `self` from the target root_url
104 fun dir_href: String do return href.dirname
105
106 # A relative `href` to `self` from the page `context`.
107 #
108 # Should be used to navigate between documents.
109 fun href_from(context: WikiEntry): String
110 do
111 var res = context.dir_href.relpath(href)
112 return res
113 end
114
115 # A relative hyperlink <a> to `self` from the page `context`.
116 #
117 # If `text` is not given, `title` will be used instead.
118 fun a_from(context: WikiEntry, text: nullable Text): Writable
119 do
120 var title = title.html_escape
121 if text == null then text = title else text = text.html_escape
122 var href = href_from(context)
123 return """<a href="{{{href}}}" title="{{{title}}}">{{{text}}}</a>"""
124 end
125
126 redef fun render do
127 super
128 if not is_dirty and not wiki.force_render then return
129 render_sidebar_wikilinks
130 end
131
132 # Search in `self` then `self.children` if an entry has the name `name`.
133 fun lookup_entry_by_name(name: String): nullable WikiEntry do
134 if children.has_key(name) then return children[name]
135 for child in children.values do
136 var res = child.lookup_entry_by_name(name)
137 if res != null then return res
138 end
139 return null
140 end
141
142 # Search in `self` then `self.children` if an entry has the title `title`.
143 fun lookup_entry_by_title(title: String): nullable WikiEntry do
144 for child in children.values do
145 if child.title.to_lower == title.to_lower then return child
146 end
147 for child in children.values do
148 var res = child.lookup_entry_by_title(title)
149 if res != null then return res
150 end
151 return null
152 end
153
154 private var md_proc: NitiwikiMdProcessor is lazy do
155 return new NitiwikiMdProcessor(wiki, self)
156 end
157
158 # Process wikilinks from sidebar.
159 private fun render_sidebar_wikilinks do
160 var blocks = sidebar.blocks
161 for i in [0..blocks.length[ do
162 blocks[i] = md_proc.process(blocks[i].to_s).write_to_string
163 md_proc.emitter.decorator.headlines.clear
164 end
165 end
166 end
167
168 redef class WikiSection
169
170 # The index page for this section.
171 #
172 # If no file `index.md` exists for this section,
173 # a summary is generated using contained articles.
174 var index: WikiArticle is lazy do
175 for child in children.values do
176 if child isa WikiArticle and child.is_index then return child
177 end
178 return new WikiSectionIndex(wiki, "index", self)
179 end
180
181 redef fun dir_href do return href
182 end
183
184 redef class WikiArticle
185
186 # Headlines ids and titles.
187 var headlines = new ArrayMap[String, HeadLine]
188
189 # Is `self` an index page?
190 #
191 # Checks if `self.name == "index"`.
192 fun is_index: Bool do return name == "index"
193
194 redef fun href do
195 if parent == null then
196 return "{name}.html"
197 else
198 return parent.href.join_path("{name}.html")
199 end
200 end
201
202 redef fun render do
203 super
204 if not is_dirty and not wiki.force_render or not has_source then return
205 content = md_proc.process(md.as(not null))
206 headlines.recover_with(md_proc.emitter.decorator.headlines)
207 end
208 end
209
210 # A `WikiArticle` that contains the section index tree.
211 class WikiSectionIndex
212 super WikiArticle
213
214 # The section described by `self`.
215 var section: WikiSection
216
217 redef fun title do return section.title
218
219 redef fun href do return section.href
220
221 redef fun dir_href do return section.dir_href
222 end
223
224 # A MarkdownProcessor able to parse wiki links.
225 class NitiwikiMdProcessor
226 super MarkdownProcessor
227
228 # Wiki used to resolve links.
229 var wiki: Nitiwiki
230
231 # Article parsed by `self`.
232 #
233 # Used to contextualize links.
234 var context: WikiEntry
235
236 init do
237 emitter = new MarkdownEmitter(self)
238 emitter.decorator = new NitiwikiDecorator(wiki, context)
239 end
240 end
241
242 # The decorator associated to `MarkdownProcessor`.
243 class NitiwikiDecorator
244 super HTMLDecorator
245
246 # Wiki used to resolve links.
247 var wiki: Nitiwiki
248
249 # Article used to contextualize links.
250 var context: WikiEntry
251
252 redef fun add_wikilink(v, token) do
253 var wiki = v.processor.as(NitiwikiMdProcessor).wiki
254 var target: nullable WikiEntry = null
255 var anchor: nullable String = null
256 var link = token.link
257 if link == null then return
258 var name = token.name
259 v.add "<a "
260 if not link.has_prefix("http://") and not link.has_prefix("https://") then
261 # Extract commands from the link.
262 var command = null
263 var command_split = link.split_once_on(":")
264 if command_split.length > 1 then
265 command = command_split[0].trim
266 link = command_split[1].trim
267 end
268
269 if link.has("#") then
270 var parts = link.split_with("#")
271 link = parts.first
272 anchor = parts.subarray(1, parts.length - 1).join("#")
273 end
274 if link.has("/") then
275 target = wiki.lookup_entry_by_path(context, link.to_s)
276 else
277 target = wiki.lookup_entry_by_name(context, link.to_s)
278 if target == null then
279 target = wiki.lookup_entry_by_title(context, link.to_s)
280 end
281 end
282 if target != null then
283 if name == null then name = target.title
284 link = target.href_from(context)
285
286 if command == "trail" then
287 if target isa WikiSection then target = target.index
288 wiki.trails.add(context, target)
289 end
290 else
291 wiki.message("Warning: unknown wikilink `{link}` (in {context.src_path.as(not null)})", 0)
292 v.add "class=\"broken\" "
293 end
294 end
295 v.add "href=\""
296 append_value(v, link)
297 if anchor != null then append_value(v, "#{anchor}")
298 v.add "\""
299 var comment = token.comment
300 if comment != null and not comment.is_empty then
301 v.add " title=\""
302 append_value(v, comment)
303 v.add "\""
304 end
305 v.add ">"
306 if name == null then name = link
307 v.emit_text(name)
308 v.add "</a>"
309 end
310 end