Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
4
5 This tutorial demonstrates how to write a XWiki Skin Extension.
6
7 {{velocity}}
8 ## $xwiki.ssx.use("$doc.fullName") ## Load the SSX object held in this document
9 {{/velocity}}
10
11 = Introduction to XWiki Skin Extensions =
12
13 XWiki Skins eXtensions (abbreviated as **SX**) is a mechanism available in XWiki that allows to customize the layout of your wiki, or just some pages of your wiki, without the need of changing its skin templates and/or stylesheets. For this, the [[Skin Extension plugin>>extensions:Extension.Skin Extension Plugin]] (bundled in all XWiki Enterprise versions superior to 1.5) provides the ability to send to the browser extra JavaScript and CSS files that are not part of the actual skin of the wiki. The code for these //extensions// is defined in [[wiki objects>>platform:DevGuide.DataModel]].
14
15 This tutorial assumes that you already have basic knowledge of application development with XWiki. If this is not the case, we strongly advise you to start with the [[FAQ application tutorial>>FAQTutorialManual]] or the [[TODO application tutorial>>http://www.theserverside.com/news/1363830/XWiki-A-Platform-for-Collaborative-Apps]].
16 To illustrate usage of Skin Extension in XWiki, this tutorial will guide you through the creation of minimal JavaScript and StyleSheet working extensions. Then, will push it further to build a fully functional extension based on Natalie Downe's ##addSizes.js## script.
17
18 A minimal [[JavaScript>>http://en.wikipedia.org/wiki/JavaScript]] and [[CSS>>http://en.wikipedia.org/wiki/CSS]] knowledge is also needed to take full advantage of XWiki Skin Extensions, although expert knowledge in those fields is not needed to follow the tutorial.
19
20 {{info}}
21 If you are interested by the Skin eXtension mechanism itself and its internals, you should read its [[plugin page>>extensions:Extension.Skin Extension Plugin]], and its [[design page on dev.xwiki.org>>dev:Design.Skin Extensions]]. This tutorial does not address this topic. Or, since this is an Open Source project, feel free to {{scm path="xwiki-platform-core/xwiki-platform-skin/xwiki-platform-skin-skinx"}}browse the code{{/scm}}, and [[propose enhancements or improvements>>dev:Community.Contributing]].
22 {{/info}}
23
24 = My first Skin eXtension =
25
26 Skin eXtensions are defined as [[XWiki Objects>>platform:DevGuide.DataModel||anchor="HXWikiClasses2CObjects2CandProperties"]]. As a consequence, you can create them from your browser. Two types of extensions are currently supported: JavaScript eXtensions (incarnated by XWiki objects of class **XWiki.JavaScriptExtension**), and StyleSheet eXtensions (incarnated by XWiki objects of class **XWiki.StyleSheetExtension**). The very first step to create an eXtension is then... to create its object!
27
28 == Minimal JavaScript eXtension ==
29
30 === Creating an eXtension object ===
31
32 Point your wiki on the page you want to create your extension in, and edit it with the object editor. The page itself can be any XWiki page - an existing page or a new page. I use in this example the page **XWiki.SkinExt**. From the **New Object** drop-down list of the object editor choose **XWiki.JavaScriptExtension**. Then, click the "Add" button.
33
34 {{image reference="CreateJSXObject.png"/}}
35
36 {{info}}
37 The object editor is available only to [[advanced users>>platform:Features.PageEditing||anchor="HAdvancedMode"]].
38 {{/info}}
39
40 Once the page is loaded, you should see your extension object in the object list.
41
42 === Writing the eXtension ===
43
44 Now that the object is available, we can just start writing the actual eXtension. For this, we will fill in all the fields of the created object. The first one is the extension name. This is easy! We can just write here **Hello World** (this information is only descriptive, it is not actually used by the SX plugin). The next field name is **code**, and this is where we will write the javascript code we want our extension to execute. This eXtension is supposed to be minimalist, so let's write something very basic here: a traditional greeting alert
45
46 {{code}}
47 alert("Hello World!");
48 {{/code}}
49
50 Now the next field asks us if we want this extension to be used **Always** or **On Demand**. We will explore all the differences between those two modes later in the tutorial, let us for now just precise we want it **On Demand**, which will force us to call the eXtension explicitly to see it executed.
51
52 Next thing our eXtension wants to know is if we want its content being parsed or not. This option allows to write **[[velocity code>>platform:DevGuide.Scripting]]**, for example to dynamically generate the javascript code to be executed. We did not write any velocity, so we can just say **No**. We will see later on an example of an extension with parsed content.
53
54 Finally, we can precise a **caching policy**, to tune the HTTP headers that will be returned with the generated javascript file. Let's not go wild, and chose the **default** one here
55
56 That's it ! our eXtension is production-ready ! It should by now look like the following:
57
58 {{image reference="MyFirstJSX.png"/}}
59
60 //Note: the "code" area size has been intentionally reduced for this screenshot.//
61
62 === Testing the actual extension ===
63
64 Let's now test the whole thing! Remember we chose that our extension should be used //on demand// ? Well, that's what we are going to do right now. For this we will make a call to the [[Skin Extension plugin>>extensions:Extension.Skin Extension Plugin]]. We can do it for instance in the wiki content of our extension page, or any other page. For this, we edit the target page in Wiki mode, and write the following:
65
66 {{code}}
67 {{velocity}}
68 #set ($discard = $xwiki.jsx.use('XWiki.SkinExt.WebHome'))
69 {{/velocity}}
70 {{/code}}
71
72 Of course, if you did not use this page name for your extension, you should adapt it. Click "Save and View", et voila! If everything is fine, you should see the magic:
73
74 {{image reference="JSXMagic.png"/}}
75
76 You may have noticed that the javascript alert displays before the document is fully loaded in the browser. This is actually expected! If you look close at the generated sources, you will see that your extension has actually been added in the HTML header as any other **.js files** from the skin: (comments added for this tutorial)
77
78 {{code}}
79 <script type="text/javascript" src="/xwiki/skins/albatross/skin.js"></script>
80 <!-- [SNIP] here are all others javascript files from the skin -->
81 <script type="text/javascript" src="/xwiki/bin/skin/skins/albatross/scripts/shortcuts.js"></script>
82
83 <!-- And here is your JSX ! You can open its URL in a browser and see the code -->
84 <script type='text/javascript' src='/xwiki/bin/jsx/XWiki/SkinExt?lang=en'></script>
85 {{/code}}
86
87 You may also note, that the browser is delivered a minified version of the script given in the object's text. This is good practice for the memory of the browser but may make it hard to debug. Using the extra parameter ##debug=true## is a way to prevent it as explained in the [[Debugging Page>>url:http://dev.xwiki.org/xwiki/bin/view/Community/Debugging]].
88
89 == Minimal StyleSheet eXtension ==
90
91 Good, we wrote our first javascript extension. But, we see things big and we already are looking forward to modify the graphical appearance of wiki pages using those eXtensions. That's what **StyleSheet eXtensions** are meant for. And the good news is that it just works the same as javascript extensions, the only difference being that the code written is **CSS code**.
92
93 Create a new page named **XWiki.MyFirstStylesheetExtension**. From the **New Object** drop-down list of the object editor choose **XWiki.StyleSheetExtension**. Then, click the "Add" button. We will name it **Blue Background**, give it a **default** cache policy, ask it not to parse the content, and write the following **code**:
94
95 {{code}}
96 #xwikicontent {
97 background-color: lightBlue;
98 }
99 {{/code}}
100
101 {{info}}
102 If you want to use the colors of your active ColorTheme you can check how to [[call those variables>>extensions:Extension.Color Theme Application||anchor="HUsingColorThemesvariables"]].
103 {{/info}}
104
105 == Put all together ==
106
107 Now let's try something new with this eXtension. Instead of loading it "On Demand", we can ask to have it used **"Always on this wiki"**. For this to happen however, you need to save the extension document with [[programming rights>>platform:AdminGuide.Access Rights||anchor="HSpecialpermissions"]].
108
109 Your StyleSheet eXtension should now look like the following:
110
111 {{image reference="MyFirstSSX.png"/}}
112
113 //Note: the "code" area size has been intentionally reduced for this Screenshot.//
114
115 It's time to test it. No need to call the SkinExtension plugin this time, this is the power of **Use Always** extensions, just click "Save and View" and see the SSX Magic. You can browse your wiki, all pages will be affected by your extension, for example the Main.WebHome page:
116
117 {{image reference="SSXMagic.png"/}}
118
119 Note: if you want to use StyleSheet extension on demand, the principle is the same as for javascript, except that the plugin name is **ssx**, not **jsx**. Just make your call like this, and you are done:
120
121 {{code}}
122 {{velocity}}
123 #set ($discard = $xwiki.ssx.use('XWiki.MyFirstStylesheetExtension.WebHome'))
124 {{/velocity}}
125 {{/code}}
126
127 {{info}}
128 A document can have as many **ssx** or **jsx** object as it needs, but a skin extension is identified by the name of the document, so in the end an extension is a document. The content of a skin extension is the concatenation of the objects in that document, so it's impossible to write two different extensions in a single document, only different parts of the same extension.
129 {{/info}}
130
131 = Real-world eXtension with addSizes.js =
132
133 Let's now go further with this idea, and build a complete extension that will dynamically add the file type and size next to certain links that are present in a wiki document. This extension will make usage of the **addSizes.js** script published by Natalie Downe. This Javascript snippet itself relies on **json-head**, a Google App Engine application by Simon Willison which //"provides a JSON-P API for running [[HEAD requests>>http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4]] against an arbitrary URL"//. **addSizes.js** consumes this service to dynamically add the file type and size next to links in HTML documents. And this is what we will do in our new eXtension, using the aforementioned script and service.
134
135 Our new skin extension will be composed of a javascript and a stylesheet extension. We will hold the two objects in the same wiki page, namely **XWiki.AddSizesExtension**.
136
137 Once the document is loaded the javascript extension will be in charge of finding all the interesting links we want to decorate with sizes and file type icons, actually query for their size on the cloud, and finally inject this information next to each concerned link.
138
139 The stylesheet extension will just define the style we want for the extra size information that is injected next to the links.
140
141 The implementation below looks for the following file formats:
142
143 * OpenOffice.org Writer, Calc, and Impress (.odt, .ods, .odp)
144 * The most well known proprietary equivalents of the formats above
145 * Zip archives (.zip)
146 * PDFs (.pdf)
147
148 Of course, this can adapted to look for other formats that are relevant for your business
149
150 == Requesting and injecting files size with JSX ==
151
152 Our javascript extension will be composed of two code snippets. The second one will be the actual addSizes.js code, ported to work with Prototype instead of jQuery. The first one is a function needed by this portage.
153
154 AddSizes.js relies on the [[JSON with padding technique>>http://en.wikipedia.org/wiki/JSONP]] to query the **json-head** service, which is located on a different domain than the wiki, in a transparent manner. An alternative to this would be to have a similar service on the wiki itself (for example, in the [[groovy language>>platform:DevGuide.Scripting||anchor="HGroovy"]]), and query it using a traditional AJAX request. [[Prototype.js>>http://prototypejs.org/]], the javascript framework bundled with XWiki, does not yet provide support for JSON-P requests. We will use for this a code snippet by Juriy Zaytsev written for this purpose. Let's first paste his code in a new **JSX** object, in **XWiki.AddSizesExtension** :
155
156 {{code}}
157 // getJSON function by Juriy Zaytsev
158 // http://github.com/kangax/protolicious/tree/master/get_json.js
159 (function(){
160 var id = 0, head = $$('head')[0], global = this;
161 global.getJSON = function(url, callback) {
162 var script = document.createElement('script'), token = '__jsonp' + id;
163
164 // callback should be a global function
165 global[token] = callback;
166
167 // url should have "?" parameter which is to be replaced with a global callback name
168 script.src = url.replace(/\?(&|$)/, '__jsonp' + id + '$1');
169
170 // clean up on load: remove script tag, null script variable and delete global callback function
171 script.onload = function() {
172 script.remove();
173 script = null;
174 delete global[token];
175 };
176 head.appendChild(script);
177
178 // callback name should be unique
179 id++;
180 }
181 })();
182 {{/code}}
183
184 With this, we can now have a prototype version of addSizes.js. We can just paste this second snippet under the first one in the **code** are of our extension object, or add a new JavaScriptExtension object to the page (as SX combines all the objects of the same page into a single response):
185
186 {{code}}
187 // addSizes was written by Natalie Downe
188 // http://natbat.net/2008/Aug/27/addSizes/
189 // ported to prototype.js by Jerome Velociter, and adapted to XWiki for this tutorial
190
191 // Copyright (c) 2008, Natalie Downe under the BSD license
192 // http://www.opensource.org/licenses/bsd-license.php
193
194 Event.observe(window, 'load', function(event) {
195 $('xwikicontent').select(
196 'a[href$=".pdf"], a[href$=".doc"], a[href$=".zip"], a[href$=".xls"], a[href$=".odt"], a[href$=".ods"], a[href$=".odp"], a[href$=".ppt"]')
197 .each(function(link){
198 var bits = link.href.split('.');
199 var type = bits[bits.length -1];
200
201 var url = "http://json-head.appspot.com/?url="+encodeURIComponent (link.href)+"&callback=?";
202
203 getJSON(url, function(json){
204 var content_length = json.headers['Content-Length'];
205 if(!content_length) {
206 content_length = json.headers['content-length'];
207 }
208 if(json.ok && content_length) {
209 var length = parseInt(content_length, 10);
210
211 // divide the length into its largest unit
212 var units = [
213 [1024 * 1024 * 1024, 'GB'],
214 [1024 * 1024, 'MB'],
215 [1024, 'KB'],
216 [1, 'bytes']
217 ];
218
219 for(var i = 0; i < units.length; i++){
220
221 var unitSize = units[i][0];
222 var unitText = units[i][1];
223 if (length >= unitSize) {
224 length = length / unitSize;
225 // 1 decimal place
226 length = Math.ceil(length * 10) / 10;
227 var lengthUnits = unitText;
228 break;
229 }
230 }
231
232 // insert the text in a span directly after the link and add a class to the link
233 Element.insert(link, {'after':
234 ' <span class="filesize">(' + length + ' ' + lengthUnits + ')</span>'});
235 link.addClassName(type);
236 }
237 });
238 }); // each matched link
239 });
240 {{/code}}
241
242 This is it! At this point, the extension should be already functional. If you test it now, you should be able to see the size of links getting injected next to matching each link in the content of a wiki document.
243
244 We will now make this information look nicer, and add an icon to represent the file type of the link, thanks to a stylesheet extension.
245
246 == Making it look nice with SSX ==
247
248 This time, we will take advantage of the **Parse** attribute of extensions that has been evoked upper in this tutorial. This way, we can be lazy and generate the CSS code using the velocity templating language, instead of writing a rule for each file format manually. Thanks to velocity and to the XWiki api, we will also be able to reference images attached to the extension document.
249
250 The class name that is added to each matching link by the JSX is actually the matching file extension itself (doc, pdf, etc.). Thus, we can then iterate over the extensions that we target, and generate a rule for each one of them. And more, if we name our icons with the convention of using the file extension, we can also reference the image within the same iteration.
251
252 You can [[download here>>attach:addSizesIcons.zip]] an archive with the set of icons used for this tutorial. The icons for MS products and for zip and pdf files are from the **[[Silk Icons Set>>http://www.famfamfam.com/lab/icons/silk/]]** by Mark James, under the [[Creative Commons Attribution 2.5 License>>http://creativecommons.org/licenses/by/2.5/]] license. To add the icons to your extension, just unzip the archive and attach them manually to your **XWiki.AddSizesExtension** document. Of course, you can also use your own set of icons. If you change the name of the files however, keep in mind you will have to adapt the stylesheet extension below.
253
254 Once you have the icons attached, create the stylesheet extension, set its parse attribute to **Yes**, and paste this code in the "Code" section:
255
256 {{code language="velocity"}}
257 /* A little padding on the right of links for the icons to fit */
258 #foreach($ext in ['odt', 'ods', 'odp', 'doc', 'xls', 'ppt', 'pdf', 'zip'])
259 #xwikicontent a.${ext} #if($velocityCount < 8), #end
260 #end {
261 padding-right:20px;
262 }
263
264 /* Files icons as background for the links */
265 #foreach($ext in ['odt', 'ods', 'odp', 'doc', 'xls', 'ppt', 'pdf', 'zip'])
266 #xwikicontent a.${ext} {
267 background:transparent url($doc.getAttachmentURL("${ext}.png")) no-repeat scroll right center;
268 }
269 #end
270
271 /* Nice spans for file size information */
272 #xwikicontent span.filesize {
273 font-size: 0.6em;
274 background-color:lightYellow;
275 }
276 {{/code}}
277
278 When asked to serve the CSS file, XWiki will evaluate this code using its Velocity Rendering engine, and will return a file that contains pure CSS code!
279
280 == Testing the final eXtension ==
281
282 Ok, it's time for us to see the whole thing in action! The snippet below is intended to showcase the extension on its own wiki page. It request to the **jsx** and **ssx** plugins the use of the contained objects, and then give an example of all the supported links.
283
284 {{code}}
285 {{velocity}}
286 #set($discard = $xwiki.jsx.use($doc.fullName))
287 #set($discard = $xwiki.ssx.use($doc.fullName))
288 {{/velocity}}
289
290 * [[An OpenOffice.org Writer document>>http://pt.openoffice.org/coop/ooo2prodspeca4pt.odt]]
291 * [[A MS Word document>>http://www.microsoft.com/hiserver/techinfo/Insurance.doc]]
292 * [[An OOo Spreadshet>>http://documentation.openoffice.org/Samples_Templates/Samples/Business_planner.ods]]
293 * [[Link to a MS Excel document>>http://www.microsoft.com/MSFT/download/financialhistoryT4Q.xls]]
294 * [[An OOo Presentation>>http://pt.openoffice.org/coop/ooo2prodintroen.odp]]
295 * [[Link to a MS Powerpoint file>>http://research.microsoft.com/ACM97/nmNoVid.ppt]]
296 * [[A great archive>>http://maven.xwiki.org/releases/com/xpn/xwiki/products/xwiki-enterprise-jetty-hsqldb/2.0/xwiki-enterprise-jetty-hsqldb-2.0.zip]]
297 * [[A PDF file>>http://www.adobe.com/motion/pdfs/sjsu_fumi_ss.pdf]]
298 {{/code}}
299
300 Now there are two things to keep in mind :
301
302 * The browser must be able to reach the Internet, since the extension does need the help of the json-head service hosted on Google App Engine.
303 * As Natalie Downe wrote, //"this may not be 100% reliable due to App Engine being occasionally and unavoidably flakey"//. You may for example experience a long loading time (but since the extension triggers only once the whole wiki document is loaded, this will not penalize the wiki users).
304
305 In a future extension of this tutorial, we will address those two issues writing our own version of the json-head service on the wiki itself, using the [[groovy programming language>>platform:DevGuide.Scripting||anchor="HGroovy"]].
306
307 Enough talk, let us see the result !
308
309 {{image reference="AddSizesMagic.png"/}}
310
311 == Bonus: links to activate/deactivate the extension ==
312
313 [[image:bonus.gif]]
314
315 You can add this snippet in the wiki content of the extension document, and users with the programming right granted will be provided a link to activate or not the extension on all pages of the wiki:
316
317 {{code}}
318 {{velocity}}{{html}}
319 #if($xwiki.hasAccessLevel('programming', $context.user)) ## Only programmers should be able to change the loading type
320 ## otherwise, Always-used extensions will not work
321
322 #if($doc.getObject('XWiki.JavaScriptExtension').getProperty('use').value == 'always')
323 #info('This extension is configured to be loaded on all the pages of this wiki.')
324
325 <span class=buttonwrapper>
326 <a href="$doc.getURL('save','XWiki.JavaScriptExtension_0_use=onDemand&XWiki.StyleSheetExtension_0_use=onDemand')">
327 De-activate loading for all pages.
328 </a>
329 </span>
330 #else
331 #info('This extension is configured to be loaded only on pages that request it.')
332
333 <span class=buttonwrapper>
334 <a href="$doc.getURL('save','XWiki.JavaScriptExtension_0_use=always&XWiki.StyleSheetExtension_0_use=always')">
335 Activate loading for all pages.
336 </a>
337 </span>
338 #end
339
340 #end
341 {{/html}}{{/velocity}}
342 {{/code}}
343
344 = Additional Details =
345
346 == How to use Velocity in parsed content ==
347
348 Example for **XWiki.JavaScriptExtension** code:
349
350 {{code}}
351 #if (!$xcontext.userReference)
352 alert("Hello guest!");
353 #else
354 alert("Hello user!");
355 #end
356 {{/code}}
357
358 will show different alerts for different users on page refresh.
359
360 Example for **XWiki.StyleSheetExtension** code:
361
362 {{code}}
363 #if (!$xcontext.userReference)
364 #mainContentArea {
365 background-color: grey;
366 }
367 #else
368 #mainContentArea {
369 background-color: blue;
370 }
371 #end
372 {{/code}}
373
374 will show different background colors for authenticated and anonymous users.
375
376 Velocity doesn't know about CSS. Everything that looks like a Velocity macro or variable is evaluated. So, undefined macros and
377 variables are printed as is. E.g. **#xwikicontent** will be used as CSS ID field, unless **xwikicontent** Velocity macro is defined.
378
379 Velocity is a template language, so when the Velocity code is evaluated the Velocity variables are simply substituted in the template by their values. So:
380
381 {{code}}
382 alert(false);
383 {{/code}}
384
385 works because **false*** is a literal boolean value in JavaScript.
386
387 Though:
388
389 {{code}}
390 alert($xcontext.user);
391 {{/code}}
392
393 will be evaluated e.g. as **alert(XWiki.User);** which will throw an exception unless **User** is a JavaScript variable previously defined, therefor you need to wrap the value in quotes, e.g.
394
395 {{code}}
396 alert('$xcontext.user');
397 {{/code}}
398
399 Or even more, because the value coming from Velocity can contain characters that are not allowed in a JavaScript string literal. So safest is to write:
400
401 {{code}}
402 alert('$escapetool.javascript($xcontext.user)');
403 {{/code}}
404
405 {{info}}
406 You can use XWiki global velocity variables **$doc**, **$request** and **$xcontext** in parsed content.
407 {{/info}}
408
409 = LESS =
410
411 Since XWiki 6.4M2, you can use [[LESS>>http://www.lesscss.org/]] in your Skin Extensions. Get a look to [[extensions:Extension.Skin Extension Plugin||anchor="HUseLESS"]] for more informations.
412
413 = References =
414
415 * [[extensions:Extension.Skin Extension Plugin]]
416 * [[JSON with Padding>>http://en.wikipedia.org/wiki/JSONP]]
417 * [[HTTP HEAD Request>>http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4]]
418 * [[get_json.js>>https://github.com/kangax/protolicious/blob/master/get_json.js]]
419 * [[json-head>>http://json-head.appspot.com/]]

Get Connected