/
JavascriptTagLib.groovy
473 lines (426 loc) · 18.3 KB
/
JavascriptTagLib.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.plugins.web.taglib
import grails.artefact.Artefact
import javax.annotation.PostConstruct
import org.codehaus.groovy.grails.plugins.GrailsPluginManager
import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.util.ClassUtils
/**
* Tags for developing javascript and ajax applications.
*
* @author Graeme Rocher
*/
@Artefact("TagLibrary")
class JavascriptTagLib implements ApplicationContextAware {
ApplicationContext applicationContext
/**
* Mappings to the relevant files to be included for each library.
*/
public static final String INCLUDED_LIBRARIES = "org.codehaus.grails.INCLUDED_JS_LIBRARIES"
static final String INCLUDED_JS = "org.codehaus.grails.INCLUDED_JS"
static final String CONTROLLER = "org.codehaus.groovy.grails.CONTROLLER"
static final LIBRARY_MAPPINGS = [:]
static final PROVIDER_MAPPINGS = [:]
GrailsPluginManager pluginManager
Class<JavascriptProvider> defaultProvider
boolean hasResourceProcessor = false
static encodeAsForTags = [escapeJavascript: 'JavaScript', javascript: [expressionCodec:"JavaScript", scriptletCodec:"JavaScript", replaceOnly:true]]
JavascriptTagLib() {
def cl = Thread.currentThread().contextClassLoader
def hasJquery = ClassUtils.isPresent("org.codehaus.groovy.grails.plugins.jquery.JQueryProvider", cl)
if (hasJquery) {
try {
defaultProvider = cl.loadClass("org.codehaus.groovy.grails.plugins.jquery.JQueryProvider")
} catch (e) {
// ignore
}
}
}
@PostConstruct
private void initHasResourceProcessor() {
hasResourceProcessor = applicationContext.containsBean('grailsResourceProcessor')
}
/**
* Includes a javascript src file, library or inline script
* if the tag has no 'src' or 'library' attributes its assumed to be an inline script:<br/>
*
* <g:javascript>alert('hello')</g:javascript><br/>
*
* The 'library' attribute will attempt to use the library mappings defined above to import the
* right js files and not duplicate imports eg.<br/>
*
* <g:javascript library="scriptaculous" /> // imports all the necessary js for the scriptaculous library<br/>
*
* The 'src' attribute will merely import the js file but within the right context (ie inside the /js/ directory of
* the Grails application:<br/>
*
* <g:javascript src="myscript.js" /> // actually imports '/app/js/myscript.js'
*
* @attr src The name of the javascript file to import. Will look in web-app/js dir
* @attr library The name of the library to include. e.g. "jquery", "prototype", "scriptaculous", "yahoo" or "dojo"
* @attr plugin The plugin to look for the javascript in
* @attr contextPath the context path to use (relative to the application context path). Defaults to "" or path to the plugin for a plugin view or template.
* @attr base specifies the full base url to prepend to the library name
*/
Closure javascript = { attrs, body ->
setUpRequestAttributes()
if (attrs.src) {
javascriptInclude(attrs)
}
else if (attrs.library) {
if (hasResourceProcessor) {
out << r.require(module:attrs.library)
includedLibrary(attrs.library)
} else {
if (LIBRARY_MAPPINGS.containsKey(attrs.library)) {
LIBRARY_MAPPINGS[attrs.library].each {
if (!request[INCLUDED_JS].contains(it)) {
request[INCLUDED_JS] << it
def newattrs = [:] + attrs
newattrs.src = String.valueOf(it) + '.js'
javascriptInclude(newattrs)
}
}
includedLibrary(attrs.library)
}
else {
if (!request[INCLUDED_LIBRARIES].contains(attrs.library)) {
def newattrs = [:] + attrs
newattrs.src = String.valueOf(newattrs.remove('library')) + '.js'
javascriptInclude(newattrs)
includedLibrary(attrs.library)
request[INCLUDED_JS] << attrs.library
}
}
}
}
else {
if (hasResourceProcessor) {
out << r.script(Collections.EMPTY_MAP, body)
} else {
out.println '<script type="text/javascript">'
out << body()
out.println()
out.println '</script>'
}
}
}
private includedLibrary(library) {
if (!request[INCLUDED_LIBRARIES].contains(library)) {
request[INCLUDED_LIBRARIES] << library
}
}
private javascriptInclude(attrs) {
def requestPluginContext
if (attrs.plugin) {
requestPluginContext = pluginManager.getPluginPath(attrs.remove('plugin')) ?: ''
}
else {
if (attrs.contextPath != null) {
requestPluginContext = attrs.remove('contextPath').toString()
}
else {
requestPluginContext = pageScope.pluginContextPath ?: ''
}
}
if (attrs.base) {
attrs.uri = attrs.remove('base') + attrs.remove('src')
} else {
def appBase = grailsAttributes.getApplicationUri(request)
if (!appBase.endsWith('/')) {
appBase += '/'
}
def reqResCtx = ''
if (requestPluginContext) {
reqResCtx = (requestPluginContext.startsWith("/") ? requestPluginContext.substring(1) : requestPluginContext) + '/'
}
attrs.uri = appBase + reqResCtx + 'js/'+attrs.remove('src')
}
out << g.external(attrs)
}
/**
* Creates a remote function call.
*
* @emptyTag
*
* @attr before The javascript function to call before the remote function call
* @attr after The javascript function to call after the remote function call
* @attr update Either a map containing the elements to update for 'success' or 'failure' states, or a string with the element to update in which cause failure events would be ignored
* @attr action the name of the action to use in the link, if not specified the default action will be linked
* @attr controller the name of the controller to use in the link, if not specified the current controller will be linked
* @attr id The id to use in the link
* @attr asynchronous Whether to do the call asynchronously or not (defaults to true, specified in 'options' array)
* @attr method The method to use the execute the call (defaults to "post")
*/
Closure remoteFunction = { attrs ->
// before remote function
def after = ''
if (attrs.before) {
out << "${attrs.remove('before')};"
}
if (attrs.after) {
after = "${attrs.remove('after')};"
}
getProvider().doRemoteFunction(owner, attrs, out)
attrs.remove('update')
// after remote function
if (after) {
out << after
}
}
private setUpRequestAttributes() {
if (!request[INCLUDED_JS]) request[INCLUDED_JS] = []
if (!request[INCLUDED_LIBRARIES]) request[INCLUDED_LIBRARIES] = []
}
/**
* Normal map implementation does a shallow clone. This implements a deep clone for maps
* using recursion.
*/
private deepClone(Map map) {
def cloned = [:]
map.each { k,v ->
if (v instanceof Map) {
cloned[k] = deepClone(v)
}
else {
cloned[k] = v
}
}
return cloned
}
/**
* Creates a link to a remote uri that can be invoked via ajax.
*
* @attr update Either a map containing the elements to update for 'success' or 'failure' states, or a string with the element to update in which cause failure events would be ignored
* @attr before The javascript function to call before the remote function call
* @attr after The javascript function to call after the remote function call
* @attr asynchronous Whether to do the call asynchronously or not (defaults to true)
* @attr method The method to use the execute the call (defaults to "post")
* @attr controller The name of the controller to use in the link, if not specified the current controller will be linked
* @attr action The name of the action to use in the link, if not specified the default action will be linked
* @attr uri relative URI
* @attr url A map containing the action,controller,id etc.
* @attr base Sets the prefix to be added to the link target address, typically an absolute server URL. This overrides the behaviour of the absolute property, if both are specified.
* @attr absolute If set to "true" will prefix the link target address with the value of the grails.serverURL property from Config, or http://localhost:<port> if no value in Config and not running in production.
* @attr id The id to use in the link
* @attr fragment The link fragment (often called anchor tag) to use
* @attr params A map containing URL query parameters
* @attr mapping The named URL mapping to use to rewrite the link
* @attr elementId the DOM element id
*/
Closure remoteLink = { attrs, body ->
out << '<a href="'
def cloned = deepClone(attrs)
out << createLink(cloned)
out << '" onclick="'
// create remote function
out << remoteFunction(attrs)
out << 'return false;"'
// These options should not be included as attributes of the anchor element.
attrs.remove('method')
attrs.remove('url')
attrs.remove('action')
attrs.remove('controller')
// handle elementId like link
def elementId = attrs.remove('elementId')
if (elementId) {
out << " id=\"${elementId}\""
}
// process remaining attributes
attrs.each { k,v ->
out << ' ' << k << "=\"" << v << "\""
}
out << ">"
// output the body
out << body()
// close tag
out << "</a>"
}
/**
* A field that sends its value to a remote link.
*
* @emptyTag
*
* @attr name REQUIRED the name of the field
* @attr value The initial value of the field
* @attr paramName The name of the parameter send to the server
* @attr action the name of the action to use in the link, if not specified the default action will be linked
* @attr controller the name of the controller to use in the link, if not specified the current controller will be linked
* @attr id The id to use in the link
* @attr update Either a map containing the elements to update for 'success' or 'failure' states, or a string with the element to update in which cause failure events would be ignored
* @attr before The javascript function to call before the remote function call
* @attr after The javascript function to call after the remote function call
* @attr asynchronous Whether to do the call asynchronously or not (defaults to true)
* @attr method The method to use the execute the call (defaults to "post")
*/
Closure remoteField = { attrs, body ->
def paramName = attrs.paramName ? attrs.remove('paramName') : 'value'
def value = attrs.remove('value')
if (!value) value = ''
out << "<input type=\"text\" name=\"${attrs.remove('name')}\" value=\"${value}\" onkeyup=\""
if (attrs.params) {
if (attrs.params instanceof Map) {
attrs.params[paramName] = new JavascriptValue('this.value')
}
else {
attrs.params += "+'${paramName}='+this.value"
}
}
else {
attrs.params = "'${paramName}='+this.value"
}
out << remoteFunction(attrs)
attrs.remove('params')
out << "\""
attrs.remove('url')
attrs.each { k,v->
out << " $k=\"$v\""
}
out <<" />"
}
/**
* A form which uses the javascript provider to serialize its parameters and submit via an asynchronous ajax call.
*
* @attr name REQUIRED The form name
* @attr url REQUIRED The url to submit to as either a map (containing values for the controller, action, id, and params) or a URL string
* @attr action The action to execute as a fallback, defaults to the url if non specified
* @attr update Either a map containing the elements to update for 'success' or 'failure' states, or a string with the element to update in which cause failure events would be ignored
* @attr before The javascript function to call before the remote function call
* @attr after The javascript function to call after the remote function call
* @attr asynchronous Whether to do the call asynchronously or not (defaults to true)
* @attr method The method to use the execute the call (defaults to "post")
*/
Closure formRemote = { attrs, body ->
if (!attrs.name) {
throwTagError("Tag [formRemote] is missing required attribute [name]")
}
if (!attrs.url) {
throwTagError("Tag [formRemote] is missing required attribute [url]")
}
// 'formRemote' does not support the 'params' attribute.
if (attrs.params != null) {
throwTagError("""\
Tag [formRemote] does not support the [params] attribute - add\
a 'params' key to the [url] attribute instead.""")
}
// get javascript provider
def p = getProvider()
def url = attrs.url
if (!(url instanceof CharSequence)) {
url = deepClone(attrs.url)
}
// prepare form settings
p.prepareAjaxForm(attrs)
def params = [onsubmit:remoteFunction(attrs) + 'return false',
method: (attrs.method? attrs.method : 'post'),
action: (attrs.action? attrs.action : url instanceof CharSequence ? url.toString() : createLink(url))]
attrs.remove('url')
params.putAll(attrs)
if (params.name && !params.id) {
params.id = params.name
}
// The <form> element shouldn't have a 'name' attribute.
// See http://jira.codehaus.org/browse/GRAILS-2839
params.remove 'name'
out << withTag(name:'form',attrs:params) {
out << body()
}
}
/**
* Creates a form submit button that submits the current form to a remote ajax call.
*
* @attr url The url to submit to, either a map contraining keys for the action,controller and id or string value
* @attr update Either a map containing the elements to update for 'success' or 'failure' states, or a string with the element to update in which cause failure events would be ignored
* @attr before The javascript function to call before the remote function call
* @attr after The javascript function to call after the remote function call
* @attr asynchronous Whether to do the call asynchronously or not (defaults to true)
* @attr method The method to use the execute the call (defaults to "post")
*/
Closure submitToRemote = { attrs, body ->
// get javascript provider
def p = getProvider()
// prepare form settings
attrs.forSubmitTag = ".form"
p.prepareAjaxForm(attrs)
def params = [onclick: remoteFunction(attrs) + 'return false',
type: 'button',
name: attrs.remove('name'),
value: attrs.remove('value'),
id: attrs.remove('id'),
'class': attrs.remove('class')]
out << withTag(name: 'input', attrs: params) {
out << body()
}
}
/**
* Escapes a javascript string replacing single/double quotes and new lines.<br/>
*
* <g:escapeJavascript>This is some "text" to be escaped</g:escapeJavascript>
*/
Closure escapeJavascript = { attrs, body ->
if (body) {
out << body()
}
else if (attrs.value) {
out << attrs.value
}
}
Closure setProvider = { attrs, body ->
if (request[JavascriptTagLib.INCLUDED_LIBRARIES] == null) {
request[JavascriptTagLib.INCLUDED_LIBRARIES] = []
}
request[JavascriptTagLib.INCLUDED_LIBRARIES] << attrs.library
}
/**
* Returns the provider of the necessary function calls to perform Javascript functions
*/
private JavascriptProvider getProvider() {
setUpRequestAttributes()
def providerClass = PROVIDER_MAPPINGS.find { request[JavascriptTagLib.INCLUDED_LIBRARIES]?.contains(it.key) }?.value
if (providerClass == null) {
if (defaultProvider == null) {
throw new GrailsTagException("No javascript provider is configured")
}
return defaultProvider.newInstance()
}
return providerClass.newInstance()
}
}
/**
* Defines methods that a JavaScript provider must implement.
*
* @author Graeme Rocher
*/
interface JavascriptProvider {
/**
* Creates a remote function call
*
* @param The attributes to use
* @param The output to write to
*/
def doRemoteFunction(taglib,attrs, out)
def prepareAjaxForm(attrs)
}
class JavascriptValue {
def value
JavascriptValue(value) {
this.value = value
}
String toString() { "'+$value+'" }
}