Wiki source code of Suggest Widget

Last modified by Marius Dumitru Florea on 2022/04/19

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="pagePicker.png"/}}
112
113 Custom configuration parameters:
114
115 |=Name|=Description|=Default Value
116 |data-document-reference|The document where the selected values are saved. Stored document references will be relative to this document.|Current page
117 |data-search-scope|(((Where to look for pages. The following is supported:
118 * "wiki:wikiName" look for pages in the specified wiki
119 * "space:spaceReference" look for pages in the specified space)))|Current wiki
120
121 === Suggest Attachments ===
122
123 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).
124
125 {{code language="none"}}
126 {{velocity}}
127 {{html}}
128 #set ($attachmentPickerParams = {
129 ...
130 })
131 #attachmentPicker($attachmentPickerParams)
132 {{/html}}
133 {{/velocity}}
134 {{/code}}
135
136 {{image reference="attachmentPicker.png"/}}
137
138 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.
139
140 Custom configuration parameters:
141
142 |=Name|=Description|=Default Value
143 |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
144 |data-search-scope|(((Where to look for attachments. The following is supported:
145 * "wiki:wikiName" look for attachments in the specified wiki
146 * "space:spaceReference" look for attachments in the specified space
147 * "document:documentReference" look for attachments in the specified document)))|Current wiki
148 |data-upload-allowed|Whether to allow the user to upload files|false
149 |data-accept|(((Indicates the type of files that can be selected or uploaded. The value is a comma separated list of:
150 * file name extensions (e.g. .png,.pdf)
151 * complete or partial media types (e.g. image/,video/mpeg)
152
153 If nothing is specified then no restriction is applied.)))|None
154
155 === Suggest Users ===
156
157 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).
158
159
160 {{code language="none"}}
161 {{velocity}}
162 {{html}}
163 #set ($userPickerParams = {
164 ...
165 })
166 #userPicker(true, $userPickerParams)
167 {{/html}}
168 {{/velocity}}
169 {{/code}}
170
171 {{image reference="userPicker.png"/}}
172
173 The ##userPicker## macro requires two parameters: the first one indicates whether the picker accepts multiple values or not, and the second one contains complementary configuration parameters:
174
175 |=Name|=Description|=Default Value
176 |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
177
178 === Suggest Groups ===
179
180 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).
181
182 {{code language="none"}}
183 {{velocity}}
184 {{html}}
185 #set ($groupPickerParams = {
186 ...
187 })
188 #groupPicker(true, $groupPickerParams)
189 {{/html}}
190 {{/velocity}}
191 {{/code}}
192
193 {{image reference="groupPicker.png"/}}
194
195 Like the ##userPicker## macro, ##groupPicker## requires two parameters: the first one indicates whether the picker accepts multiple values or not, and the second one contains complementary configuration parameters:
196
197 |=Name|=Description|=Default Value
198 |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
199
200 === Suggest Property Values ===
201
202 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.
203
204 {{code language="none"}}
205 {{velocity}}
206 $doc.display('myDatabaseListProperty')
207 {{/velocity}}
208 {{/code}}
209
210 {{image reference="propertyValuePicker.png"/}}
211
212 If you don't have a property to display then you can also enable this suggester by calling the generic ##suggestInput## macro like this:
213
214 {{code language="none"}}
215 {{velocity}}
216 {{html}}
217 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/suggestPropertyValues.js',
218 {'forceSkinAction': true, 'language': $xcontext.locale}))
219 #set ($suggestParams = {
220 'class': 'suggest-propertyValues',
221 'placeholder': 'Select the movie director',
222 'data-className': 'Help.Applications.Movies.Code.MoviesClass',
223 'data-propertyName': 'databaseList1'
224 })
225 #suggestInput($suggestParams)
226 {{/html}}
227 {{/velocity}}
228 {{/code}}
229
230 If you need tag suggestions then you can use this configuration:
231
232 {{code language="none"}}
233 #set ($suggestParams = {
234 'class': 'suggest-propertyValues',
235 'multiple': 'multiple',
236 'data-className': 'XWiki.TagClass',
237 'data-propertyName': 'tags'
238 })
239 {{/code}}
240
241 Custom configuration parameters:
242
243 |=Name|=Description|=Default Value
244 |data-className|The class where the property is defined|None
245 |data-propertyName|The property whose values are to be retrieved as suggestions|None
246 |data-freeText|Whether free text is allowed or forbidden. Possible values are: allowed, forbidden|None
247
248 == Custom Suggesters ==
249
250 === Suggest from Static Data ===
251
252 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).
253
254 {{html wiki="true"}}
255 <div>
256 <ul class="nav nav-tabs" role="tablist">
257 <li role="presentation" class="active">
258 <a href="#staticDataV1" aria-controls="staticDataV1" role="tab" data-toggle="tab">V1: The Basics</a>
259 </li>
260 <li role="presentation">
261 <a href="#staticDataV2" aria-controls="staticDataV2" role="tab" data-toggle="tab">V2: Separate Data</a>
262 </li>
263 <li role="presentation">
264 <a href="#staticDataV3" aria-controls="staticDataV3" role="tab" data-toggle="tab">V3: Helper Macros</a>
265 </li>
266 <li role="presentation">
267 <a href="#staticDataV4" aria-controls="staticDataV4" role="tab" data-toggle="tab">V4: Reusable Code</a>
268 </li>
269 </ul>
270
271 <div class="tab-content">
272 <div role="tabpanel" class="tab-pane active" id="staticDataV1">
273 <p>The following code:</p>
274
275 * loads the resources (JavaScript and CSS) needed by the suggest widget
276 * outputs the HTML (select element) needed by the suggest widget
277
278 <p>Note that the select element is marked with the ##xwiki-selectize## CSS class which activates the suggest widget.</p>
279
280 {{code language="none"}}
281 {{velocity}}
282 #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.bootstrap3.css'),
283 {'type': 'text/css', 'rel': 'stylesheet'}))
284 #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true))
285 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true))
286 {{/velocity}}
287
288 {{html}}
289 <select class="xwiki-selectize">
290 <option value="">Select the country</option>
291 <option value="fr">France</option>
292 <option value="de">Germany</option>
293 <option value="ro">Romania</option>
294 </select>
295 {{/html}}
296 {{/code}}
297
298 </div>
299
300 <div role="tabpanel" class="tab-pane" id="staticDataV2">
301 <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>
302
303 {{code language="none"}}
304 {{velocity}}
305 {{html}}
306 #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.bootstrap3.css'),
307 {'type': 'text/css', 'rel': 'stylesheet'}))
308 #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true))
309 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true))
310 #set ($countries = [
311 {'name': 'France', 'code': 'fr'},
312 {'name': 'Germany', 'code': 'de'},
313 {'name': 'Romania', 'code': 'ro'}
314 ])
315 ## See https://github.com/selectize/selectize.js/blob/master/docs/usage.md#configuration
316 #set ($selectizeSettings = {})
317 <select class="xwiki-selectize" data-xwiki-selectize="$escapetool.xml($jsontool.serialize($selectizeSettings))">
318 <option value="">Select the country</option>
319 #foreach ($country in $countries)
320 <option value="$!escapetool.xml($country.code)">$!escapetool.xml($country.name)</option>
321 #end
322 </select>
323 {{/html}}
324 {{/velocity}}
325 {{/code}}
326
327 </div>
328
329 <div role="tabpanel" class="tab-pane" id="staticDataV3">
330 <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>
331
332 {{code language="none"}}
333 {{velocity output="false"}}
334 #set ($countries = [
335 {'name': 'France', 'code': 'fr'},
336 {'name': 'Germany', 'code': 'de'},
337 {'name': 'Romania', 'code': 'ro'}
338 ])
339
340 #macro (countryPicker_displayOptions $selectedValues)
341 #foreach ($country in $countries)
342 <option value="$!escapetool.xml($country.code)"#if ($selectedValues.contains($country.code)) selected="selected"#end
343 >$!escapetool.xml($country.name)</option>
344 #end
345 #end
346 {{/velocity}}
347
348 {{velocity}}
349 {{html}}
350 #picker_import
351 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true))
352 ## See https://github.com/selectize/selectize.js/blob/master/docs/usage.md#configuration
353 #set ($selectizeSettings = {})
354 #set ($suggestInputAttributes = {
355 'name': 'country',
356 'class': 'xwiki-selectize',
357 'data-xwiki-selectize': $selectizeSettings,
358 'value': 'ro',
359 'placeholder': 'Select the country'
360 })
361 #suggestInput($suggestInputAttributes 'countryPicker_displayOptions')
362 {{/html}}
363 {{/velocity}}
364 {{/code}}
365
366 </div>
367
368 <div role="tabpanel" class="tab-pane" id="staticDataV4">
369 <p>In this last version we make the code reusable by creating the ##countryPicker## and ##countryPicker_import## Velocity macros.</p>
370
371 {{code language="none"}}
372 {{velocity output="false"}}
373 #set ($countries = [
374 {'name': 'France', 'code': 'fr'},
375 {'name': 'Germany', 'code': 'de'},
376 {'name': 'Romania', 'code': 'ro'}
377 ])
378
379 #macro (countryPicker_displayOptions $selectedValues)
380 #foreach ($country in $countries)
381 <option value="$!escapetool.xml($country.code)"#if ($selectedValues.contains($country.code)) selected="selected"#end
382 >$!escapetool.xml($country.name)</option>
383 #end
384 #end
385
386 #macro (countryPicker_import)
387 #picker_import
388 #set ($discard = $xwiki.jsfx.use('uicomponents/suggest/xwiki.selectize.js', true))
389 #end
390
391 #macro (countryPicker $parameters)
392 #countryPicker_import
393 #if ("$!parameters" == "")
394 #set ($parameters = {})
395 #end
396 #set ($discard = $parameters.put('class', "$!parameters.get('class') xwiki-selectize suggest-countries"))
397 #if (!$parameters.containsKey('placeholder'))
398 #set ($parameters.placeholder = 'Select the country')
399 #end
400 #suggestInput($parameters 'countryPicker_displayOptions')
401 #end
402 {{/velocity}}
403
404 {{velocity}}
405 {{html}}
406 #set ($countryPickerParams = {
407 'name': 'country',
408 'value': 'ro'
409 })
410 #countryPicker($countryPickerParams)
411 {{/html}}
412 {{/velocity}}
413 {{/code}}
414
415 </div>
416 </div>
417 </div>
418 {{/html}}
419
420 === Suggest from Remote Data ===
421
422 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.
423
424 {{html wiki="true"}}
425 <div>
426 <ul class="nav nav-tabs" role="tablist">
427 <li role="presentation" class="active">
428 <a href="#remoteDataV1" aria-controls="remoteDataV1" role="tab" data-toggle="tab">V1: The Basics</a>
429 </li>
430 <li role="presentation">
431 <a href="#remoteDataV2" aria-controls="remoteDataV2" role="tab" data-toggle="tab">V2: Reusable Code</a>
432 </li>
433 </ul>
434
435 <div class="tab-content">
436 <div role="tabpanel" class="tab-pane active" id="remoteDataV1">
437 <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>
438
439 {{code language="js"}}
440 require.config({
441 paths: {
442 'xwiki-selectize': "$xwiki.getSkinFile('uicomponents/suggest/xwiki.selectize.js', true)" +
443 "?v=$escapetool.url($xwiki.version)"
444 }
445 });
446
447 require(['jquery', 'xwiki-selectize'], function($) {
448 var settings = {
449 load: function(typedText, callback) {
450 $.getJSON('your/service/url', {
451 text: typedText
452 }).done(callback).fail(callback);
453 },
454 loadSelected: function(selectedValue, callback) {
455 $.getJSON('your/service/url', {
456 text: selectedValue,
457 exactMatch: true
458 }).done(callback).fail(callback);
459 }
460 };
461
462 $('.suggest-countries').xwikiSelectize(settings);
463 });
464 {{/code}}
465
466 {{code language="none"}}
467 {{velocity}}
468 #set ($discard = $xwiki.linkx.use($services.webjars.url('selectize.js', 'css/selectize.bootstrap3.css'),
469 {'type': 'text/css', 'rel': 'stylesheet'}))
470 #set ($discard = $xwiki.ssfx.use('uicomponents/suggest/xwiki.selectize.css', true))
471 #set ($discard = $xwiki.jsx.use('Path.To.Your.JSX'))
472 {{/velocity}}
473
474 {{html}}
475 <select class="suggest-countries">
476 <option value="">Select the country</option>
477 </select>
478 {{/html}}
479 {{/code}}
480
481 </div>
482
483 <div role="tabpanel" class="tab-pane" id="remoteDataV2">
484 <p>In this last version we make the code reusable by creating a jQuery plugin and some helper Velocity macros.</p>
485
486 {{code language="js"}}
487 require.config({
488 paths: {
489 'xwiki-selectize': "$xwiki.getSkinFile('uicomponents/suggest/xwiki.selectize.js', true)" +
490 "?v=$escapetool.url($xwiki.version)"
491 }
492 });
493
494 define('xwiki-suggestCountries', ['jquery', 'xwiki-selectize'], function($) {
495 var getSettings = function(select) {
496 return {
497 load: function(typedText, callback) {
498 $.getJSON('your/service/url', {
499 text: typedText
500 }).done(callback).fail(callback);
501 },
502 loadSelected: function(selectedValue, callback) {
503 $.getJSON('your/service/url', {
504 text: selectedValue,
505 exactMatch: true
506 }).done(callback).fail(callback);
507 }
508 };
509 };
510
511 $.fn.suggestCountries = function(settings) {
512 return this.each(function() {
513 $(this).xwikiSelectize($.extend(getSettings($(this)), settings));
514 });
515 };
516 });
517
518 require(['jquery', 'xwiki-suggestCountries', 'xwiki-events-bridge'], function($) {
519 var init = function(event, data) {
520 var container = $((data && data.elements) || document);
521 container.find('.suggest-countries').suggestCountries();
522 };
523
524 $(document).on('xwiki:dom:loaded xwiki:dom:updated', init);
525 XWiki.domIsLoaded && init();
526 });
527 {{/code}}
528
529 {{code language="none"}}
530 {{velocity output="false"}}
531 #macro (countryPicker_import)
532 #picker_import
533 #set ($discard = $xwiki.jsx.use('Path.To.Your.JSX'))
534 #end
535
536 #macro (countryPicker $parameters)
537 #countryPicker_import
538 #if ("$!parameters" == "")
539 #set ($parameters = {})
540 #end
541 #set ($discard = $parameters.put('class', "$!parameters.get('class') suggest-countries"))
542 #if (!$parameters.containsKey('placeholder'))
543 #set ($parameters.placeholder = 'Select the country')
544 #end
545 #suggestInput($parameters)
546 #end
547 {{/velocity}}
548
549 {{velocity}}
550 {{html}}
551 #set ($countryPickerParams = {
552 'name': 'country',
553 'value': 'ro'
554 })
555 #countryPicker($countryPickerParams)
556 {{/html}}
557 {{/velocity}}
558 {{/code}}
559
560 </div>
561 </div>
562 </div>
563 {{/html}}
564
565 The remote data should have the following JSON format:
566
567 {{code language="js"}}
568 [
569 {
570 'label': '...',
571 'value': '...',
572 'url': '...',
573 'icon': {
574 'iconSetName': '...',
575 'iconSetType': 'IMAGE or FONT',
576 'cssClass': 'for font icons',
577 'url': 'for image icons'
578 },
579 'hint': '...'
580 },
581 ...
582 ]
583 {{/code}}

Get Connected