Wiki source code of Suggest Widget

Version 75.1 by Marius Dumitru Florea on 2019/06/21

Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc start="2"/}}
3 {{/box}}
4
5 The suggest widget is implemented using [[Selectize.js>>http://selectize.github.io/selectize.js/]] with its Bootstrap skin and is bundled by default in XWiki platform.
6
7 == Predefined Suggesters ==
8
9 A couple of suggesters are available by default in XWiki. Each suggester provides:
10
11 * dedicated helper Velocity macros (to import required resources and to output the required HTML)
12 * a jQuery plugin to activate the suggest behavior on any input or select element
13 * a CSS class that activates the suggest behavior automatically
14
15 The dedicated Velocity macros are in fact loading a JavaScript code that calls the dedicated jQuery plugin on all the elements (input or select) that are marked with the dedicated CSS class. Here's the list of available suggesters:
16
17 |=Data|=Velocity Macros|=jQuery Plugin|=CSS Class
18 |Pages|pagePicker, pagePicker_import|suggestPages|suggest-pages
19 |Attachments|attachmentPicker, attachmentPicker_import|suggestAttachments|suggest-attachments
20 |Users|userPicker, userPicker_input, userPicker_import|suggestUsers|suggest-users
21 |Groups|groupPicker|suggestGroups|suggest-groups
22 |Property Values|xpropertySuggestInputDisplayer|suggestPropertyValues|suggest-propertyValues
23
24 === Usage ===
25
26 There are 3 ways in which you can activate a predefined suggester:
27
28 * from Velocity (by calling the dedicated Velocity macro)
29 * from JavaScript (by calling the dedicated jQyery plugin)
30 * from HTML (by marking form fields with the dedicated CSS class)
31
32 Use the one that suits you the best.
33
34 ==== From Velocity ====
35
36 You can do this by putting the following code in the content of a wiki page. Here we're calling the dedicated ##pagePicker## Velocity macro. Note that you can pass configuration options. Most of these settings are translated into HTML attributes (of the generated suggest input element) read by the dedicated jQuery plugin. You can use the ##data-xwiki-selectize## parameter to pass configuration options to the [[Selectize.js>>https://github.com/selectize/selectize.js/blob/master/docs/usage.md#configuration]] widget. Each predefined suggester might also have custom parameters you can set, check their documentation below.
37
38 {{code language="none"}}
39 {{velocity}}
40 {{html}}
41 #set ($pagePickerParams = {
42 'name': 'targetPages',
43 'value': ['Path.To.Alice', 'Path.To.Bob'],
44 'multiple': 'multiple'
45 })
46 #pagePicker($pagePickerParams)
47 {{/html}}
48 {{/velocity}}
49 {{/code}}
50
51 ==== From JavaScript ====
52
53 You can do this from a JavaScript Skin extension. First you need to configure the path to the suggester you want to use and then you need to call the dedicated jQuery plugin (##suggestAttachments##) from a require block. Note that you can pass configuration options when activating the suggester. These configuration options are either generic (for the [[Selectize>>https://github.com/selectize/selectize.js/blob/master/docs/usage.md#configuration]] widget) or specific to each suggester (see below).
54
55 {{code language="js"}}
56 require.config({
57 paths: {
58 'xwiki-suggestAttachments': "$xwiki.getSkinFile('uicomponents/suggest/suggestAttachments.js', true)" +
59 "?v=$escapetool.url($xwiki.version)"
60 }
61 });
62
63 require(['jquery', 'xwiki-suggestAttachments'], function($) {
64 $('input[name="logo"]').suggestAttachments({
65 accept: 'image/,.mp4,.pdf',
66 uploadAllowed: true
67 });
68 });
69 {{/code}}
70
71 Of course, you still need to load your skin extension code (from the content of a wiki page):
72
73 {{code language="none"}}
74 {{velocity}}
75 {{html}}
76 #set ($discard = $xwiki.jsx.use('Path.To.Your.JSX'))
77 <input type="text" name="logo" value="[email protected]"/>
78 {{/html}}
79 {{/velocity}}
80 {{/code}}
81
82 ==== From HTML ====
83
84 Put the following code in the content of a wiki page. First you need to import the resources required by the suggester and then you need to mark the form fields you wish to enhance (using the dedicated CSS class, ##suggest-users## here). Note that you can use the ##data-xwiki-selectize## attribute to pass configuration options in JSON format to the [[Selectize.js>>https://github.com/selectize/selectize.js/blob/master/docs/usage.md#configuration]] widget. Each predefined suggester might also have custom attributes you can set, check their documentation below.
85
86 {{code language="none"}}
87 {{velocity output="false"}}
88 #userPicker_import
89 {{/velocity}}
90
91 {{html}}
92 <input type="text" name="manager" value="XWiki.mflorea" class="suggest-users"/>
93 {{/html}}
94 {{/code}}
95
96 === Suggest Pages ===
97
98 This suggester displays the page rendered title and the page location. The value that is saved in the end is the page reference. The hidden page user preference is taken into account.
99
100 {{code language="none"}}
101 {{velocity}}
102 {{html}}
103 #set ($pagePickerParams = {
104 ...
105 })
106 #pagePicker($pagePickerParams)
107 {{/html}}
108 {{/velocity}}
109 {{/code}}
110
111 {{image reference="page-picker.jpg"/}}
112
113 Custom configuration parameters:
114
115 |=Name|=Description|=Default Value
116 |data-suggest-space|Restrict the suggestions to a specific location|None
117
118 === Suggest Attachments ===
119
120 This suggester displays the attachment (file) name and the attachment location. The suggestion icon is either a preview, if the attachment is an image or an icon that depends on the attachment media type. The value that is saved in the end is the attachment reference. The hidden page user preference is taken into account (e.g. attachments from hidden pages are not displayed by default).
121
122 {{code language="none"}}
123 {{velocity}}
124 {{html}}
125 #set ($attachmentPickerParams = {
126 ...
127 })
128 #attachmentPicker($attachmentPickerParams)
129 {{/html}}
130 {{/velocity}}
131 {{/code}}
132
133 {{image reference="attachmentPicker.png"/}}
134
135 It supports local file upload, either by selecting the files from the file browser or by dropping them on the suggest input. It also supports drag and drop of attachment links from the Attachment tab at the bottom of the wiki page.
136
137 Custom configuration parameters:
138
139 |=Name|=Description|=Default Value
140 |data-document-reference|The document where the selected values are saved and where new files are being uploaded. Stored attachment references will be relative this document.|Current page
141 |data-search-scope|(((Where to look for attachments. The following is supported:
142 * "wiki:wikiName" look for attachments in the specified wiki
143 * "space:spaceReference": look for attachments in the specified space
144 * "document:documentReference" look for attachments in the specified document)))|Current wiki
145 |data-upload-allowed|Whether to allow the user to upload files|false
146 |data-accept|(((Indicates the type of files that can be selected or uploaded. The value is a comma separated list of:
147 * file name extensions (e.g. .png,.pdf)
148 * complete or partial media types (e.g. image/,video/mpeg)
149
150 If nothing is specified then no restriction is applied.)))|None
151
152 === Suggest Users ===
153
154 This suggester displays the user avatar and their name. The value that is saved in the end is the user reference (the reference of the user profile page).
155
156 {{code language="none"}}
157 {{velocity}}
158 {{html}}
159 #set ($userPickerParams = {
160 ...
161 })
162 #userPicker($userPickerParams)
163 {{/html}}
164 {{/velocity}}
165 {{/code}}
166
167 {{image reference="userPicker.png"/}}
168
169 Custom configuration parameters:
170
171 |=Name|=Description|=Default Value
172 |data-userScope|Where to retrieve the user suggestions from. Supported values are: LOCAL_ONLY, GLOBAL_ONLY, LOCAL_AND_GLOBAL|User scope of the current wiki
173
174 === Suggest Groups ===
175
176 The suggester displays the group logo and its name. The group logo is the first image attachment found on the group page. The value that is saved in the end is the group reference (the reference of the group page).
177
178 {{code language="none"}}
179 {{velocity}}
180 {{html}}
181 #set ($groupPickerParams = {
182 ...
183 })
184 #groupPicker($groupPickerParams)
185 {{/html}}
186 {{/velocity}}
187 {{/code}}
188
189 {{image reference="groupPicker.png"/}}
190
191 Custom configuration parameters:
192
193 |=Name|=Description|=Default Value
194 |data-userScope|Where to retrieve the group suggestions from. Supported values are: LOCAL_ONLY, GLOBAL_ONLY, LOCAL_AND_GLOBAL. Note that GLOBAL_ONLY has the same effect as LOCAL_AND_GLOBAL because a wiki with only global users can have local groups|User scope of the current wiki
195
196 === Suggest Property Values ===
197
198 This suggester displays the label assocaited with a property value and saves the raw property value. The following property types are supported by this suggester: Static List and Database List. Note that these property types have default custom displayers associated that load the suggest widget when the "Use suggest" meta property is on. So normally the only thing you need to do is to display the property.
199
200 {{code language="none"}}
201 {{velocity}}
202 $doc.display('myDatabaseListProperty')
203 {{/velocity}}
204 {{/code}}
205
206 {{image reference="propertyValuePicker.png"/}}
207
208 Custom configuration parameters:
209
210 |=Name|=Description|=Default Value
211 |data-className|The class where the property is defined|None
212 |data-propertyName|The property whose values are to be retrieved as suggestions|None
213 |data-freeText|Whether free text is allowed or forbidden. Possible values are: allowed, forbidden|None
214
215 == Custom Suggesters ==
216
217 === Suggest from Static Data ===
218
219 Let's see how you can use the suggest widget with static data (i.e. data that is available when the web page is loaded).
220
221 {{html wiki="true"}}
222 <div>
223 <ul class="nav nav-tabs" role="tablist">
224 <li role="presentation" class="active">
225 <a href="#staticDataV1" aria-controls="staticDataV1" role="tab" data-toggle="tab">V1: The Basics</a>
226 </li>
227 <li role="presentation">
228 <a href="#staticDataV2" aria-controls="staticDataV2" role="tab" data-toggle="tab">V2: Separate Data</a>
229 </li>
230 <li role="presentation">
231 <a href="#staticDataV3" aria-controls="staticDataV3" role="tab" data-toggle="tab">V3: Helper Macros</a>
232 </li>
233 <li role="presentation">
234 <a href="#staticDataV4" aria-controls="staticDataV4" role="tab" data-toggle="tab">V4: Reusable Code</a>
235 </li>
236 </ul>
237
238 <div class="tab-content">
239 <div role="tabpanel" class="tab-pane active" id="staticDataV1">
240 <p>The following code:</p>
241
242 * loads the resources (JavaScript and CSS) needed by the suggest widget
243 * outputs the HTML (select element) needed by the suggest widget
244
245 <p>Note that the select element is marked with the ##xwiki-selectize## CSS class which activates the suggest widget.</p>
246
247 {{code language="none"}}
248 {{velocity}}
249 #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.bootstrap3.css'),
250 {'type': 'text/css', 'rel': 'stylesheet'}))
251 #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true))
252 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true))
253 {{/velocity}}
254
255 {{html}}
256 <select class="xwiki-selectize">
257 <option value="">Select the country</option>
258 <option value="fr">France</option>
259 <option value="de">Germany</option>
260 <option value="ro">Romania</option>
261 </select>
262 {{/html}}
263 {{/code}}
264
265 </div>
266
267 <div role="tabpanel" class="tab-pane" id="staticDataV2">
268 <p>In this version we separate the code that generates the data used to provide suggestions. The data is usually retrieved from the database.</p>
269
270 {{code language="none"}}
271 {{velocity}}
272 {{html}}
273 #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.bootstrap3.css'),
274 {'type': 'text/css', 'rel': 'stylesheet'}))
275 #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true))
276 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true))
277 #set ($countries = [
278 {'name': 'France', 'code': 'fr'},
279 {'name': 'Germany', 'code': 'de'},
280 {'name': 'Romania', 'code': 'ro'}
281 ])
282 ## See https://github.com/selectize/selectize.js/blob/master/docs/usage.md#configuration
283 #set ($selectizeSettings = {})
284 <select class="xwiki-selectize" data-xwiki-selectize="$escapetool.xml($jsontool.serialize($selectizeSettings))">
285 <option value="">Select the country</option>
286 #foreach ($country in $countries)
287 <option value="$!escapetool.xml($country.code)">$!escapetool.xml($country.name)</option>
288 #end
289 </select>
290 {{/html}}
291 {{/velocity}}
292 {{/code}}
293
294 </div>
295
296 <div role="tabpanel" class="tab-pane" id="staticDataV3">
297 <p>In this version we use some helper Velocity macros: ##picker_import## and ##suggestInput##. Notice the way we specify the selected value and the placeholder by passing parameters to the ##suggestInput## macro.</p>
298
299 {{code language="none"}}
300 {{velocity output="false"}}
301 #set ($countries = [
302 {'name': 'France', 'code': 'fr'},
303 {'name': 'Germany', 'code': 'de'},
304 {'name': 'Romania', 'code': 'ro'}
305 ])
306
307 #macro (countryPicker_displayOptions $selectedValues)
308 #foreach ($country in $countries)
309 <option value="$!escapetool.xml($country.code)"#if ($selectedValues.contains($country.code)) selected="selected"#end
310 >$!escapetool.xml($country.name)</option>
311 #end
312 #end
313 {{/velocity}}
314
315 {{velocity}}
316 {{html}}
317 #picker_import
318 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true))
319 ## See https://github.com/selectize/selectize.js/blob/master/docs/usage.md#configuration
320 #set ($selectizeSettings = {})
321 #set ($suggestInputAttributes = {
322 'name': 'country',
323 'class': 'xwiki-selectize',
324 'data-xwiki-selectize': $selectizeSettings,
325 'value': 'ro',
326 'placeholder': 'Select the country'
327 })
328 #suggestInput($suggestInputAttributes 'countryPicker_displayOptions')
329 {{/html}}
330 {{/velocity}}
331 {{/code}}
332
333 </div>
334
335 <div role="tabpanel" class="tab-pane" id="staticDataV4">
336 <p>In this last version we make the code reusable by creating the ##countryPicker## and ##countryPicker_import## Velocity macros.</p>
337
338 {{code language="none"}}
339 {{velocity output="false"}}
340 #set ($countries = [
341 {'name': 'France', 'code': 'fr'},
342 {'name': 'Germany', 'code': 'de'},
343 {'name': 'Romania', 'code': 'ro'}
344 ])
345
346 #macro (countryPicker_displayOptions $selectedValues)
347 #foreach ($country in $countries)
348 <option value="$!escapetool.xml($country.code)"#if ($selectedValues.contains($country.code)) selected="selected"#end
349 >$!escapetool.xml($country.name)</option>
350 #end
351 #end
352
353 #macro (countryPicker_import)
354 #picker_import
355 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true))
356 #end
357
358 #macro (countryPicker $parameters)
359 #countryPicker_import
360 #if ("$!parameters" == "")
361 #set ($parameters = {})
362 #end
363 #set ($discard = $parameters.put('class', "$!parameters.get('class') xwiki-selectize suggest-countries"))
364 #if (!$parameters.containsKey('placeholder'))
365 #set ($parameters.placeholder = 'Select the country')
366 #end
367 #suggestInput($parameters 'countryPicker_displayOptions')
368 #end
369 {{/velocity}}
370
371 {{velocity}}
372 {{html}}
373 #set ($countryPickerParams = {
374 'name': 'country',
375 'value': 'ro'
376 })
377 #countryPicker($countryPickerParams)
378 {{/html}}
379 {{/velocity}}
380 {{/code}}
381
382 </div>
383 </div>
384 </div>
385 {{/html}}
386
387 === Suggest from Remote Data ===
388
389 Most of the time you will want to retrive suggestions when the user types rather than loading all the suggestions on page load. Let's see how you can do this.
390
391 {{html wiki="true"}}
392 <div>
393 <ul class="nav nav-tabs" role="tablist">
394 <li role="presentation" class="active">
395 <a href="#remoteDataV1" aria-controls="remoteDataV1" role="tab" data-toggle="tab">V1: The Basics</a>
396 </li>
397 <li role="presentation">
398 <a href="#remoteDataV2" aria-controls="remoteDataV2" role="tab" data-toggle="tab">V2: Reusable Code</a>
399 </li>
400 </ul>
401
402 <div class="tab-content">
403 <div role="tabpanel" class="tab-pane active" id="remoteDataV1">
404 <p>In order to retrieve suggestions as you type you need to write some JavaScript code that makes an asynchronous HTTP request to retrive the data. You can put this code in a JavaScript Skin extension object. Then you need to load this JavaScript code on the page where you want to activate the suggest widget.</p>
405
406 {{code language="js"}}
407 require.config({
408 paths: {
409 'xwiki-selectize': "$xwiki.getSkinFile('uicomponents/suggest/xwiki.selectize.js', true)" +
410 "?v=$escapetool.url($xwiki.version)"
411 }
412 });
413
414 require(['jquery', 'xwiki-selectize'], function($) {
415 var settings = {
416 load: function(typedText, callback) {
417 $.getJSON('your/service/url', {
418 text: typedText
419 }).done(callback).fail(callback);
420 },
421 loadSelected: function(selectedValue, callback) {
422 $.getJSON('your/service/url', {
423 text: typedText,
424 exactMatch: true
425 }).done(callback).fail(callback);
426 }
427 };
428
429 $('.suggest-countries').xwikiSelectize(settings);
430 });
431 {{/code}}
432
433 {{code language="none"}}
434 {{velocity}}
435 #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.bootstrap3.css'),
436 {'type': 'text/css', 'rel': 'stylesheet'}))
437 #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true))
438 #set ($discard = $xwiki.jsx.use('Path.To.Your.JSX'))
439 {{/velocity}}
440
441 {{html}}
442 <select class="suggest-countries">
443 <option value="">Select the country</option>
444 </select>
445 {{/html}}
446 {{/code}}
447
448 </div>
449
450 <div role="tabpanel" class="tab-pane" id="remoteDataV2">
451 <p>In this last version we make the code reusable by creating a jQuery plugin and some helper Velocity macros.</p>
452
453 {{code language="js"}}
454 require.config({
455 paths: {
456 'xwiki-selectize': "$xwiki.getSkinFile('uicomponents/suggest/xwiki.selectize.js', true)" +
457 "?v=$escapetool.url($xwiki.version)"
458 }
459 });
460
461 define('xwiki-suggestCountries', ['jquery', 'xwiki-selectize'], function($) {
462 var getSettings = function(select) {
463 return {
464 load: function(typedText, callback) {
465 $.getJSON('your/service/url', {
466 text: typedText
467 }).done(callback).fail(callback);
468 },
469 loadSelected: function(selectedValue, callback) {
470 $.getJSON('your/service/url', {
471 text: typedText,
472 exactMatch: true
473 }).done(callback).fail(callback);
474 }
475 };
476 };
477
478 $.fn.suggestCountries = function(settings) {
479 return this.each(function() {
480 $(this).xwikiSelectize($.extend(getSettings($(this)), settings));
481 });
482 };
483 });
484
485 require(['jquery', 'xwiki-suggestCountries', 'xwiki-events-bridge'], function($) {
486 var init = function(event, data) {
487 var container = $((data && data.elements) || document);
488 container.find('.suggest-countries').suggestCountries();
489 };
490
491 $(document).on('xwiki:dom:loaded xwiki:dom:updated', init);
492 XWiki.domIsLoaded && init();
493 });
494 {{/code}}
495
496 {{code language="none"}}
497 {{velocity output="false"}}
498 #macro (countryPicker_import)
499 #picker_import
500 #set ($discard = $xwiki.jsx.use('Path.To.Your.JSX'))
501 #end
502
503 #macro (countryPicker $parameters)
504 #countryPicker_import
505 #if ("$!parameters" == "")
506 #set ($parameters = {})
507 #end
508 #set ($discard = $parameters.put('class', "$!parameters.get('class') suggest-countries"))
509 #if (!$parameters.containsKey('placeholder'))
510 #set ($parameters.placeholder = 'Select the country')
511 #end
512 #suggestInput($parameters)
513 #end
514 {{/velocity}}
515
516 {{velocity}}
517 {{html}}
518 #set ($countryPickerParams = {
519 'name': 'country',
520 'value': 'ro'
521 })
522 #countryPicker($countryPickerParams)
523 {{/html}}
524 {{/velocity}}
525 {{/code}}
526
527 </div>
528 </div>
529 </div>
530 {{/html}}
531
532 The remote data should have the following JSON format:
533
534 {{code language="js"}}
535 [
536 {
537 'label': '...',
538 'value': '...',
539 'url': '...',
540 'icon': {
541 'iconSetName': '...',
542 'iconSetType': 'IMAGE or FONT',
543 'cssClass': 'for font icons',
544 'url': 'for image icons'
545 },
546 'hint': '...'
547 },
548 ...
549 ]
550 {{/code}}

Get Connected