source: trunk/grails-app/taglib/dbnp/studycapturing/WizardTagLib.groovy @ 216

Last change on this file since 216 was 216, checked in by duh, 14 years ago
  • event grouping data is now handled properly
  • added image support to ajaxButton which now renders to an "input type='image'" instead of the default "input type='button'"
  • changed some in grouping to famfamfam icons
  • evenGroup deletions
  • eventGroup names are now uniquely generated
  • improved CSS
  • improved javascript
  • Property svn:keywords set to
    Date
    Author
    Rev
File size: 13.8 KB
Line 
1package dbnp.studycapturing
2
3import org.codehaus.groovy.grails.plugins.web.taglib.JavascriptTagLib
4import dbnp.studycapturing.*
5import dbnp.data.*
6
7/**
8 * Wizard tag library
9 *
10 * @author Jeroen Wesbeek
11 * @since 20100113
12 * @package wizard
13 *
14 * Revision information:
15 * $Rev: 216 $
16 * $Author: duh $
17 * $Date: 2010-02-26 14:23:03 +0000 (vr, 26 feb 2010) $
18 */
19class WizardTagLib extends JavascriptTagLib {
20        // define the tag namespace (e.g.: <wizard:action ... />
21        static namespace = "wizard"
22
23        // define the AJAX provider to use
24        static ajaxProvider = "jquery"
25
26        // define default text field width
27        static defaultTextFieldSize = 25;
28
29        /**
30         * ajaxButton tag, this is a modified version of the default
31         * grails submitToRemote tag to work with grails webflows.
32         * Usage is identical to submitToRemote with the only exception
33         * that a 'name' form element attribute is required. E.g.
34         * <wizard:ajaxButton name="myAction" value="myButton ... />
35         *
36         * you can also provide a javascript function to execute after
37         * success. This behaviour differs from the default 'after'
38         * action which always fires after a button press...
39         *
40         * @see http://blog.osx.eu/2010/01/18/ajaxifying-a-grails-webflow/
41         * @see http://www.grails.org/WebFlow
42         * @see http://www.grails.org/Tag+-+submitToRemote
43         * @todo perhaps some methods should be moved to a more generic
44         *        'webflow' taglib or plugin
45         * @param Map attributes
46         * @param Closure body
47         */
48        def ajaxButton = { attrs, body ->
49                // get the jQuery version
50                def jQueryVersion = grailsApplication.getMetadata()['plugins.jquery']
51
52                // fetch the element name from the attributes
53                def elementName = attrs['name'].replaceAll(/ /, "_")
54
55                // javascript function to call after success
56                def afterSuccess = attrs['afterSuccess']
57
58                // src parameter?
59                def src = attrs['src']
60                def alt = attrs['alt']
61
62                // generate a normal submitToRemote button
63                def button = submitToRemote(attrs, body)
64
65                /**
66                 * as of now (grails 1.2.0 and jQuery 1.3.2.4) the grails webflow does
67                 * not properly work with AJAX as the submitToRemote button does not
68                 * handle and submit the form properly. In order to support webflows
69                 * this method modifies two parts of a 'normal' submitToRemote button:
70                 *
71                 * 1) replace 'this' with 'this.form' as the 'this' selector in a button
72                 *    action refers to the button and / or the action upon that button.
73                 *    However, it should point to the form the button is part of as the
74                 *    the button should submit the form data.
75                 * 2) prepend the button name to the serialized data. The default behaviour
76                 *    of submitToRemote is to remove the element name altogether, while
77                 *    the grails webflow expects a parameter _eventId_BUTTONNAME to execute
78                 *    the appropriate webflow action. Hence, we are going to prepend the
79                 *    serialized formdata with an _eventId_BUTTONNAME parameter.
80                 */
81                if (jQueryVersion =~ /^1.([1|2|3]).(.*)/) {
82                        // fix for older jQuery plugin versions
83                        button = button.replaceFirst(/data\:jQuery\(this\)\.serialize\(\)/, "data:\'_eventId_${elementName}=1&\'+jQuery(this.form).serialize()")
84                } else {
85                        // as of jQuery plugin version 1.4.0.1 submitToRemote has been modified and the
86                        // this.form part has been fixed. Consequently, our wrapper has changed as well...
87                        button = button.replaceFirst(/data\:jQuery/, "data:\'_eventId_${elementName}=1&\'+jQuery")
88                }
89 
90                // add an after success function call?
91                // usefull for performing actions on success data (hence on refreshed
92                // wizard pages, such as attaching tooltips)
93                if (afterSuccess) {
94                        button = button.replaceFirst(/\.html\(data\)\;/, '.html(data);' + afterSuccess + ';')
95                }
96
97                // got an src parameter?
98                if (src) {
99                        def replace = 'type="image" src="' + src + '"'
100
101                        if (alt) replace = replace + ' alt="' + alt + '"'
102
103                        button = button.replaceFirst(/type="button"/, replace)
104                }
105
106                // replace double semi colons
107                button = button.replaceAll(/;{2,}/, ';')
108               
109                // render button
110                out << button
111        }
112
113        /**
114         * generate ajax webflow redirect javascript
115         *
116         * As we have an Ajaxified webflow, the initial wizard page
117         * cannot contain a wizard form, as upon a failing submit
118         * (e.g. the form data does not validate) the form should be
119         * shown again. However, the Grails webflow then renders the
120         * complete initial wizard page into the success div. As this
121         * ruins the page layout (a page within a page) we want the
122         * initial page to redirect to the first wizard form to enter
123         * the webflow correctly. We do this by emulating an ajax post
124         * call which updates the wizard content with the first wizard
125         * form.
126         *
127         * Usage: <wizard:ajaxFlowRedirect form="form#wizardForm" name="next" url="[controller:'wizard',action:'pages']" update="[success:'wizardPage',failure:'wizardError']" />
128         * form = the form identifier
129         * name = the action to execute in the webflow
130         * update = the divs to update upon success or error
131         *
132         * Example initial webflow action to work with this javascript:
133         * ...
134         * mainPage {
135         *      render(view: "/wizard/index")
136         *      onRender {
137         *              flow.page = 1
138         *      }
139         *      on("next").to "pageOne"
140         * }
141         * ...
142         *
143         * @param Map attributes
144         * @param Closure body
145         */
146        def ajaxFlowRedirect = { attrs, body ->
147                // define AJAX provider
148                setProvider([library: ajaxProvider])
149
150                // generate an ajax button
151                def button = this.ajaxButton(attrs, body)
152
153                // strip the button part to only leave the Ajax call
154                button = button.replaceFirst(/<[^\"]*\"jQuery.ajax/,'jQuery.ajax')
155                button = button.replaceFirst(/return false.*/,'')
156
157                // change form if a form attribute is present
158                if (attrs.get('form')) {
159                        button = button.replaceFirst(/this\.form/,
160                                "\\\$('" + attrs.get('form') + "')"
161                        )
162                }
163
164                // generate javascript
165                out << '<script language="JavaScript">'
166                out << '$(document).ready(function() {'
167                out << button
168                out << '});'
169                out << '</script>'
170        }
171
172        /**
173         * render the content of a particular wizard page
174         * @param Map attrs
175         * @param Closure body  (help text)
176         */
177        def pageContent = {attrs, body ->
178                // define AJAX provider
179                setProvider([library: ajaxProvider])
180
181                // render new body content
182                out << render(template: "/wizard/common/tabs")
183                out << '<div class="content">'
184                out << body()
185                out << '</div>'
186                out << render(template: "/wizard/common/navigation")
187                out << render(template: "/wizard/common/error")
188        }
189
190        /**
191         * generate a base form element
192         * @param String        inputElement name
193         * @param Map           attributes
194         * @param Closure       help content
195         */
196        def baseElement = { inputElement, attrs, help ->
197                // work variables
198                def description = attrs.remove('description')
199                def addExampleElement = attrs.remove('addExampleElement')
200                def addExample2Element  = attrs.remove('addExample2Element')
201
202                // render a form element
203                out << '<div class="element">'
204                out << ' <div class="description">'
205                out << description
206                out << ' </div>'
207                out << ' <div class="input">'
208                out << "$inputElement"(attrs)
209                if(help()) {
210                        out << '        <div class="helpIcon"></div>'
211                }
212
213                // add an disabled input box for feedback purposes
214                // @see dateElement(...)
215                if (addExampleElement) {
216                        def exampleAttrs = new LinkedHashMap()
217                        exampleAttrs.name = attrs.get('name')+'Example'
218                        exampleAttrs.class  = 'isExample'
219                        exampleAttrs.disabled = 'disabled'
220                        exampleAttrs.size = 30
221                        out << textField(exampleAttrs)
222                }
223
224                // add an disabled input box for feedback purposes
225                // @see dateElement(...)
226                if (addExample2Element) {
227                        def exampleAttrs = new LinkedHashMap()
228                        exampleAttrs.name = attrs.get('name')+'Example2'
229                        exampleAttrs.class  = 'isExample'
230                        exampleAttrs.disabled = 'disabled'
231                        exampleAttrs.size = 30
232                        out << textField(exampleAttrs)
233                }
234
235                out << ' </div>'
236
237                // add help content if it is available
238                if (help()) {
239                        out << '  <div class="helpContent">'
240                        out << '    ' + help()
241                        out << '  </div>'
242                }
243
244                out << '</div>'
245        }
246
247        /**
248         * render a textFieldElement
249         * @param Map attrs
250         * @param Closure body  (help text)
251         */
252        def textFieldElement = { attrs, body ->
253                // set default size, or scale to max length if it is less than the default size
254                if (!attrs.get("size")) {
255                        if (attrs.get("maxlength")) {
256                                attrs.size = ((attrs.get("maxlength") as int) > defaultTextFieldSize) ? defaultTextFieldSize : attrs.get("maxlength")
257                        } else {
258                                attrs.size = defaultTextFieldSize
259                        }
260                }
261
262                // render template element
263                baseElement.call(
264                        'textField',
265                        attrs,
266                        body
267                )
268        }
269
270
271        /**
272         * render a select form element
273         * @param Map attrs
274         * @param Closure body  (help text)
275         */
276        def selectElement = { attrs, body ->
277                baseElement.call(
278                        'select',
279                        attrs,
280                        body
281                )
282        }
283
284        /**
285         * render a checkBox form element
286         * @param Map attrs
287         * @param Closure body  (help text)
288         */
289        def checkBoxElement = { attrs, body ->
290                baseElement.call(
291                        'checkBox',
292                        attrs,
293                        body
294                )
295        }
296
297        /**
298         * render a dateElement
299         * NOTE: datepicker is attached through wizard.js!
300         * @param Map attrs
301         * @param Closure body  (help text)
302         */
303        def dateElement = { attrs, body ->
304                // transform value?
305                if (attrs.value instanceof Date) {
306                        // transform date instance to formatted string (dd/mm/yyyy)
307                        attrs.value = String.format('%td/%<tm/%<tY', attrs.value)
308                }
309               
310                // set some textfield values
311                attrs.maxlength = (attrs.maxlength) ? attrs.maxlength : 10
312                attrs.addExampleElement = true
313               
314                // render a normal text field
315                //out << textFieldElement(attrs,body)
316                textFieldElement.call(
317                        attrs,
318                        body
319                )
320        }
321
322        /**
323         * render a dateElement
324         * NOTE: datepicker is attached through wizard.js!
325         * @param Map attrs
326         * @param Closure body  (help text)
327         */
328        def timeElement = { attrs, body ->
329                // transform value?
330                if (attrs.value instanceof Date) {
331                        // transform date instance to formatted string (dd/mm/yyyy)
332                        attrs.value = String.format('%td/%<tm/%<tY %<tH:%<tM', attrs.value)
333                }
334
335                attrs.addExampleElement = true
336                attrs.addExample2Element = true
337                attrs.maxlength = 16
338
339                // render a normal text field
340                //out << textFieldElement(attrs,body)
341                textFieldElement.call(
342                        attrs,
343                        body
344                )
345        }
346       
347        /**
348         * Template form element
349         * @param Map           attributes
350         * @param Closure       help content
351         */
352        def speciesElement = { attrs, body ->
353                // render template element
354                baseElement.call(
355                        'speciesSelect',
356                        attrs,
357                        body
358                )
359        }
360
361        /**
362         * Button form element
363         * @param Map           attributes
364         * @param Closure       help content
365         */
366        def buttonElement = { attrs, body ->
367                // render template element
368                baseElement.call(
369                        'ajaxButton',
370                        attrs,
371                        body
372                )
373        }
374
375        /**
376         * render a species select element
377         * @param Map attrs
378         */
379        def speciesSelect = { attrs ->
380                // fetch the speciesOntology
381                // note that this is a bit nasty, probably the ontologyName should
382                // be configured in a configuration file... --> TODO: centralize species configuration
383                def speciesOntology = Ontology.findByName('NCBI Taxonomy')
384
385                // fetch all species
386                attrs.from = Term.findAllByOntology(speciesOntology)
387
388                // got a name?
389                if (!attrs.name) {
390                        // nope, use a default name
391                        attrs.name = 'species'
392                }
393
394                out << select(attrs)
395        }
396
397        /**
398         * Template form element
399         * @param Map           attributes
400         * @param Closure       help content
401         */
402        def templateElement = { attrs, body ->
403                // render template element
404                baseElement.call(
405                        'templateSelect',
406                        attrs,
407                        body
408                )
409        }
410       
411        /**
412         * render a template select element
413         * @param Map attrs
414         */
415        def templateSelect = { attrs ->
416                // fetch all templates
417                attrs.from = Template.findAll() // for now, all templates
418
419                // got a name?
420                if (!attrs.name) {
421                        attrs.name = 'template'
422                }
423               
424                out << select(attrs)
425        }
426
427        /**
428         * Term form element
429         * @param Map           attributes
430         * @param Closure       help content
431         */
432        def termElement = { attrs, body ->
433                // render term element
434                baseElement.call(
435                        'termSelect',
436                        attrs,
437                        body
438                )
439        }
440
441        /**
442         * render a term select element
443         * @param Map attrs
444         */
445        def termSelect = { attrs ->
446                // fetch all terms
447                attrs.from = Term.findAll()     // for now, all terms as we cannot identify terms as being treatment terms...
448
449                // got a name?
450                if (!attrs.name) {
451                        attrs.name = 'term'
452                }
453
454                out << select(attrs)
455        }
456
457        def show = { attrs ->
458                // is object parameter set?
459                def o = attrs.object
460
461                println o.getProperties();
462                o.getProperties().each {
463                        println it
464                }
465
466                out << "!! test version of 'show' tag !!"
467        }
468
469        /**
470         * render table headers for all subjectFields in a template
471         * @param Map attributes
472         */
473        def templateColumnHeaders = { attrs ->
474                def template = attrs.remove('template')
475
476                // output table headers for template fields
477                template.subjectFields.each() {
478                        out << '<div class="' + attrs.get('class') + '">' + it + '</div>'
479                }
480        }
481
482        /**
483         * render table input elements for all subjectFields in a template
484         * @param Map attributes
485         */
486        def templateColumns = { attrs, body ->
487                def subject                     = attrs.remove('subject')
488                def subjectId           = attrs.remove('id')
489                def template            = attrs.remove('template')
490                def intFields           = subject.templateIntegerFields
491                def stringFields        = subject.templateStringFields
492                def floatFields         = subject.templateFloatFields
493                def termFields          = subject.templateTermFields
494
495                // output columns for these subjectFields
496                template.subjectFields.each() {
497                        // output div
498                        out << '<div class="' + attrs.get('class') + '">'
499
500                        switch (it.type) {
501                                case 'STRINGLIST':
502                                        // render stringlist subjectfield
503                                        if (!it.listEntries.isEmpty()) {
504                                                out << select(
505                                                        name: attrs.name + '_' + it.name,
506                                                        from: it.listEntries,
507                                                        value: (stringFields) ? stringFields.get(it.name) : ''
508                                                )
509                                        } else {
510                                                out << '<span class="warning">no values!!</span>'
511                                        }
512                                        break;
513                                case 'INTEGER':
514                                        // render integer subjectfield
515                                        out << textField(
516                                                name: attrs.name + '_' + it.name,
517                                                value: (intFields) ? intFields.get(it.name) : ''
518                                        )
519                                        break;
520                                case 'FLOAT':
521                                        // render float subjectfield
522                                        out << textField(
523                                                name: attrs.name + '_' + it.name,
524                                                value: (floatFields) ? floatFields.get(it.name) : ''
525                                        )
526                                        break;
527                                default:
528                                        // unsupported field type
529                                        out << '<span class="warning">!'+it.type+'</span>'
530                                        break;
531                        }
532                        out << '</div>'
533                }
534        }
535}
Note: See TracBrowser for help on using the repository browser.