forked from yui/yui3-gallery
/
gallery-dispatcher.js
486 lines (440 loc) · 14.8 KB
/
gallery-dispatcher.js
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
474
475
476
477
478
479
480
481
482
483
484
485
486
/**
* <p>The Dispatcher satisfies a very common need of developers using the
* YUI library: dynamic execution of HTML Fragments or remote content. Typical strategies to
* fulfill this need, like executing the innerHTML property or referencing remote
* scripts, are unreliable due to browser incompatibilities. The Dispatcher normalize
* this behavior across all a-grade browsers.
*
* <p>To use the Dispatcher Module, simply create a new object based on Y.Dispatcher
* and pass a reference to a node that should be handled.</p>
*
* <p>
* <code>
* <script type="text/javascript"> <br>
* <br>
* // Call the "use" method, passing in "gallery-dispatcher". This will <br>
* // load the script for the Dispatcher Module and all of <br>
* // the required dependencies. <br>
* <br>
* YUI().use("gallery-dispatcher", function(Y) { <br>
* <br>
* (new Y.Dispatcher ({<br>
* node: '#demoajax',<br>
* content: 'Please wait... (Injecting fragment.html)'<br>
* })).set('uri', 'fragment.html');<br>
* <br>
* <br>
* </script> <br>
* </code>
* </p>
*
* <p>The Dispatcher has several configuration properties that can be
* set via an object literal that is passed as a first argument during the
* initialization, or using "set" method.
* </p>
*
* @module gallery-dispatcher
*/
// Util shortcuts
var getClassName = Y.ClassNameManager.getClassName,
// Frequently used strings
DISPATCHER = "dispatcher",
SC = "script",
DISPATCHER_FETCH = 'fetch',
DISPATCHER_PURGE = 'purge',
DISPATCHER_BEFOREEXECUTE = 'beforeExecute',
DISPATCHER_LOAD = 'load',
DISPATCHER_READY = 'ready',
DISPATCHER_ERROR = 'error',
// Attribute keys
ATTR_URI = 'uri',
ATTR_CONTENT = 'content',
ATTR_AUTOPURGE = 'autopurge',
ATTR_LOADING = 'loading',
ATTR_NODE = 'node',
ATTR_NORMALIZE = 'normalize',
// Regular Expressions
reBODY = /<\s*body.*?>(.*?)<\/\s*?body[^>\w]*?>/i,
reHEAD = /<\s*head.*?>(.*?)<\/\s*?head[^>\w]*?>/i,
// CSS class names
CLASS_DISPATCHER_LOADING = getClassName(DISPATCHER, 'loading'),
// shorthands
L = Y.Lang,
isBoolean = L.isBoolean,
isString = L.isString;
// Utility functions
function _parseContent(content, normalize) {
var fragment = Y.Node.create('<div></div>'),
head = fragment.cloneNode(),
o = {}, match = null, inject = '';
// if normalize is set, let's parse the head
if (normalize && (match = reHEAD.exec(content))) {
Y.log('normalizing scripts, links and styles from the head tag', 'info', DISPATCHER);
fragment.setContent(match[1]).all(SC+',style,link').each(function(n) {
head.append(n);
});
inject = head.get('innerHTML');
Y.log('trying to inject this content: '+inject, 'info', DISPATCHER);
}
// if the content has a body tag, we should take the content of the body, if not, assume full content
// we should also include any injection from the head if exists
fragment.setContent(inject+((match=reBODY.exec(content))?match[1]:content));
o.js = fragment.all(SC).each(function(n) {
n.get('parentNode').removeChild(n);
});
o.content = fragment.get('innerHTML');
return o;
}
function _propagateIOEvent (ev, cfg, args) {
if (cfg && cfg.on && cfg.on[ev]) {
cfg.on[ev].apply(cfg.context || Y, args);
}
}
/**
* The Dispatcher class represents an object that can manage Node Elements to
* inject HTML content as the content of the Node..
* @namespace Y
* @class Dispatcher
*/
Y.Dispatcher = Y.Base.create(DISPATCHER, Y.Base, [], {
// Prototype Properties for Dispatcher
/**
* @property _queue
* @description Execution queue.
* @default null
* @protected
* @type Object
*/
_queue: null,
/**
* @property _io
* @description Connection Handler for AJAX requests.
* @default null
* @protected
* @type Object
*/
_io: null,
initializer: function(config) {
var instance = this;
config = config || {};
Y.log('Initializer', 'info', DISPATCHER);
instance._queue = new Y.AsyncQueue();
instance.after(ATTR_CONTENT + "Change", function(e) {
instance._dispatch(e.newVal);
});
instance.after(ATTR_URI + "Change", function(e) {
instance._fetch(e.newVal);
});
// making the trick for content and uri in case the user want to set up thru config
if (config[ATTR_CONTENT]) {
instance._dispatch(instance.get(ATTR_CONTENT));
}
if (config[ATTR_URI]) {
instance._fetch(instance.get(ATTR_URI));
}
},
destructor: function() {
var instance = this;
instance.stop();
instance._queue = null;
instance._io = null;
},
// Protected methods
/**
* @method _executeScript
* @description Inject an inline script into the page as part of the dispatcher process.
* @protected
* @param {string} text Script code that should be executed
* @param {Node} n A reference to the original SCRIPT tag Node, in case you want to get more specific attributes
*/
_executeScript: function (text, jsNode) {
var d = ( jsNode ? jsNode.get('ownerDocument') : null ) || Y.one('doc'),
h = d.one('head') || d.get('documentElement'),
// creating a new script node to execute the inline javascrip code
newScript = Y.Node.create('<' + SC + '></' + SC + '>');
Y.log('inline script tag: ' + text, 'info', DISPATCHER);
if (text) {
newScript._node.text = text;
}
h.appendChild(newScript);
// removing script nodes as part of the clean up process
newScript.remove();
if (jsNode) {
jsNode.remove();
}
},
/**
* @method _getScript
* @description Inject an external script into the page as part of the dispatcher process. Due
* the async nature of this routine, we need to run the queue after the execution.
* @protected
* @param {string} src URI of the script that need to be injected
* @param {Node} n A reference to the original SCRIPT tag Node, in case you want to get more specific attributes
*/
_getScript: function (src, jsNode) {
var instance = this,
q = instance._queue;
Y.log('external script tag: ' + src, 'info', DISPATCHER);
Y.Get.script(src, {
autopurge: true, //removes the script node immediately after executing it
onFailure: function(o) {
Y.log('external script tag fails to load: ' + src, 'error', DISPATCHER);
// notifying that an error has occurred
instance.fire(DISPATCHER_ERROR, o);
},
onEnd: function(o) {
// continuing the async execution
if (q) {
q.run();
}
}
});
},
/**
* @method _setContent
* @description Set a new content into the dispatcher host node.
* @protected
* @param {string} content HTML code that will replace the current content
*/
_setContent: function (content) {
var n = this.get(ATTR_NODE);
Y.log('setting new content: ' + content, 'info', DISPATCHER);
n.setContent(content);
},
/**
* @method _purgeContent
* @description Purge all the child node in preparation for a new content to be injected.
* @protected
*/
_purgeContent: function() {
var n = this.get(ATTR_NODE);
Y.log('purging children collection', 'info', DISPATCHER);
n.get('children').each(function(c) {
c.purge(true);
});
},
/**
* @method _dispatch
* @description Dispatch a content into the code, parsing out the scripts,
* injecting the code into the DOM, then executing the scripts.
* @protected
* @param {string} content html content that should be injected in the page
* @return null
*/
_dispatch: function(content) {
var instance = this,
o = _parseContent(content, instance.get(ATTR_NORMALIZE)),
q = instance._queue,
n = instance.get(ATTR_NODE);
// stopping any previous process, just in case...
instance.stop();
if (!n) {
Y.log('Dispatcher requires a NODE to dispatch the content', 'error', DISPATCHER);
return;
}
Y.log('dispatching a new content', 'info', DISPATCHER);
// autopurging children collection
if (instance.get(ATTR_AUTOPURGE)) {
q.add({
fn: function() {
instance._purgeContent();
instance.fire(DISPATCHER_PURGE, n);
}
});
}
// injecting new content
q.add({
fn: function() {
instance._setContent(o.content);
instance.fire(DISPATCHER_BEFOREEXECUTE, n);
}
});
// executing JS blocks before the injection
o.js.each(function(jsNode) {
if (jsNode && jsNode.get('src')) {
q.add({
fn: Y.bind(instance._getScript, instance, jsNode.get('src'), jsNode),
autoContinue: false
});
} else {
q.add({
fn: Y.bind(instance._executeScript, instance, jsNode._node.text, jsNode)
});
}
});
q.add({
fn: function() {
instance.fire(DISPATCHER_READY);
}
});
// executing the queue
instance._queue.run();
},
/**
* @description Fetching a remote file using Y.io. The response will be dispatched thru _dispatch method...
* @method _fetch
* @protected
* @param {string} uri uri that should be loaded using Y.io
* @return object Reference to the connection handler
*/
_fetch: function(uri) {
var instance = this,
defIOConfig = instance.get("ioConfig") || {},
cfg;
// stopping any previous process, just in case...
instance.stop();
if (!uri) {
return false;
}
Y.log('dispatching a new url ' + uri, 'info', DISPATCHER);
// minimal config + def attr ioConfig + arg cfg ; in that order or priority (single level merge)
cfg = Y.merge({
method: 'GET'
}, defIOConfig);
cfg.on = {
start: function() {
instance._set(ATTR_LOADING, true);
Y.log('Start Loading', 'info', DISPATCHER);
_propagateIOEvent ('start', defIOConfig, arguments);
},
success: function(tid, o) {
Y.log('Success: ' + o.responseText, 'info', DISPATCHER);
instance.set(ATTR_CONTENT, o.responseText);
_propagateIOEvent ('success', defIOConfig, arguments);
},
failure: function(tid, o) {
Y.log('Failure: ' + uri, 'warn', DISPATCHER);
_propagateIOEvent ('failure', defIOConfig, arguments);
instance.fire(DISPATCHER_ERROR, o);
},
end: function() {
instance._set(ATTR_LOADING, false);
Y.log('End Loading', 'info', DISPATCHER);
_propagateIOEvent ('end', defIOConfig, arguments);
}
};
cfg.context = instance;
return (instance._io = Y.io(uri, cfg));
},
// Public methods
/**
* @method stop
* @description Cancel the current loading and execution process immediately
* @public
* @return {object} reference for chaining
*/
stop: function() {
var instance = this;
instance._queue.stop();
if (instance._io) {
instance._io.abort();
}
return instance;
}
}, {
// Static Properties for Dispatcher
EVENT_PREFIX: DISPATCHER,
/**
* Static property used to define the default attribute configuration of
* the component.
*
* @property Y.Dispatcher.ATTRS
* @Type Object
* @static
*/
ATTRS: {
/**
* YUI Node Object that represent a dynamic area in the page.
* @attribute node
* @default null
* @type object
*/
node: {
value: null,
setter: function(n) {
// stopping the current process if needed to define a new node
this.stop();
return Y.one(n);
}
},
/**
* If dispatcher should purge the DOM elements before replacing the content
* @attribute autopurge
* @default true
* @type boolean
*/
autopurge: {
value: true,
validator: isBoolean
},
/**
* If dispatcher should analyze the content before injecting it. This will help
* to support full html document injection, to collect scripts and styles from head if exists, etc.
* @attribute normalize
* @default false
* @type boolean
*/
normalize: {
value: false,
validator: isBoolean
},
/**
* URL that should be injected within the host
* @attribute uri
* @default null
* @type string
*/
uri: {
value: null,
validator: function(v) {
return (v && isString(v) && (v !== ''));
}
},
/**
* default content for the dynamic area
* @attribute content
* @default empty
* @type string
*/
content: {
value: '',
validator: isString
},
/**
* Boolean indicating that a process is undergoing.
*
* @attribute loading
* @default false
* @readonly
* @type {boolean}
*/
loading: {
value: false,
validator: isBoolean,
readOnly: true,
setter: function(v) {
var instance = this;
Y.log('setting status to ' + v, 'info', DISPATCHER);
if (v) {
instance.fire(DISPATCHER_FETCH);
instance.get(ATTR_NODE).addClass(CLASS_DISPATCHER_LOADING);
} else {
instance.fire(DISPATCHER_LOAD);
instance.get(ATTR_NODE).removeClass(CLASS_DISPATCHER_LOADING);
}
return v;
}
},
/**
* Default IO Config object that will be used as base configuration for Y.io calls.
* http://developer.yahoo.com/yui/3/io/#configuration
*
* @attribute ioConfig
* @type Object
* @default null
*/
ioConfig: {
value: null
}
}
});