-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.stateWidget.js
675 lines (673 loc) · 22 KB
/
jquery.stateWidget.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
$(function() {
$.udel = $.udel || {};
/** Start of API **/
$.udel.api = $.udel.api || {};
//
// This is a stateWidget: a widget that exists by transitioning between
// states.
//
// It also supports synchronous and synchronous data get/saving.
//
// Usually, implementations will also throw an event when a state starts
// to transition and completes a transition in addition to the
// changingState flag. This is not required, but recommended to give
// outside applications hooks.
//
$.udel.api.stateWidget = {
//
// This function saves the state of the widget to
// a non-local store. When implemented, this widget
// should be able to restore to this state.
//
// Keep this synchronous (you can use synchronous ajax requests)
//
saveState: function() {},
// You don't have to pass in data, but if you do it overrides and mixes
// in with the current data.
// Returns a copy and does not modify existing data.
getData: function(dataIn) {
var data = {};
$.extend(true, data, this.data, dataIn);
return data;
},
saveData: function(data) {
this.data = data;
},
//see store for callback info
callStore: function(callback, data, storeName) {
if (this.stores && this.stores[storeName]) {
return this.stores[storeName].fetch(callback, data);
}
},
doAction: function(action, dataIn, queueAfterIfChangingState) {
// If currently changing state, ignore other requests to change
// state unless queueAfterIfChangingState
if (!this.changingState) {
this.changingState = true;
var that = this;
var callback = function() {
that.changingState = false;
//TODO: fire stateChanged event here!
if (that.nextAction) {
var nextAction = that.nextAction.action;
var data = that.nextAction.data;
that.nextAction = null;
that.doAction(nextAction, data);
}
};
var gotoNextState = function(nextState) {
if (nextState) {
that.currentState = nextState;
nextState.loadState(callback, that, dataIn);
}
else {
callback();
}
};
if (this.currentState) {
this.currentState.getNextState(gotoNextState, this, action);
} else if (this.initialState) {
gotoNextState(this.initialState);
}
} else if (queueAfterIfChangingState) {
this.nextAction = {action: action, data:dataIn};
}
}
};
//
// A state a widget can be in.
//
// Define the stack to be executed when changing state by
// setting the function stack array. this.funcionStack should
// be a list of functionNames to be executed in order via callbacks.
//
//
$.udel.api.state = {
//
// This is not usually overloaded.
//
// Instead make a list of the functions in an array called functionStack.
// The elements of the list can either be functions (executed on the state's scope)
// or strings that map to methods on the state.
//
loadState: function(callback, widget, data) {
var lastFunc = callback;
if (this.functionStack && this.functionStack.length > 0) {
var stack = this.functionStack.slice(0).reverse();
var that = this;
$.each(stack, function(i) {
var f = lastFunc;
lastFunc = function() {
if ($.isFunction(stack[i])) {
stack[i].call(that, f, widget, data);
} else {
that[stack[i]](f, widget, data);
}
};
});
}
if (lastFunc) {
lastFunc();
}
},
//
// This is usually overloaded (unless a widget can transition
// to ANY state.
//
// Returns null to NOT validate the action. The current state will remain.
//
//
getNextState: function(callback, widget, action) {
callback(this._getNextState(widget, action));
},
//
// Synchronous method for getting the next state, wrapped by
// getNextState
//
_getNextState: function(widget, action) {
return widget.states[action];
}
};
//
// This represents a store-- an asynchronous source and destination
// for data.
//
$.udel.api.store = {
//
// Usually overloaded (default implementation is a successful mirror).
//
// This fetches data from the store (done differently by
// different implementations)
// after sending some data to it (a query or an update).
//
// After the store responds, the callback is called like so:
// callback(success/boolean, response/{});
//
//
fetch: function(callback, data) {
var toRet = data;
if (callback) {
callback(true, toRet);
}
}
};
/** End of API **/
/** Start UD implementations **/
//
// This is a udel store implementation.
// Pretty straightforward url based implementation with some additional hooks.
//
// args can include/override anything, but esp:
// - url
// - preformatter (formats data before request)
// - postformatter (formats data after response)
// - method (default is POST)
//
$.udel.store = function(args) {
$.extend(true, this, $.udel.api.store);
this.method = "POST";
this.fetch = function(callback, data) {
var that = this;
var dataReceiver = function(success, data) {
if (callback) {
if (that.postformatter) {
data = that.postformatter(data);
}
callback(success, data);
}
};
if (this.preformatter) {
data = this.preformatter(data);
}
if (this.url) {
$.ajax({
'data': $.flattenObject(data, null, null, {
nullsAsEmptyString: true
}),
url: that.url,
type: that.method,
success: function(responseData) {
dataReceiver(true, responseData);
},
error: function(responseData) {
dataReceiver(false, responseData);
}
});
} else {
dataReceiver(true, data);
}
};
$.extend(true, this, args);
};
//
// This is the udel state implementation.
// Anything in args overrides anything here.
//
// templateName/String and actions/{} should probably be defined in args.
//
// widget.states and widget.templates should be defined as follows:
//
// It has a couple of conventions that are nice:
// 1) It assumes the widget has a map of names->states called states.
// 2) If widget.states maps an action to a string,
// it assumes its the action that matches that string in the widget.
// 3) If widget.states maps an action to a function,
// it assumes its a synchronous function that takes a widget and returns a state name.
// 4) It assumes the widget has a map of names->templates called templates.
// These templates are '$.udel.template's.
//
$.udel.state = function(args) {
$.extend(true, this, $.udel.api.state);
//
// Define the function stack for $.udel.api.state
//
this.functionStack = ['delayActionSupport', 'init', 'loadTemplate',
'decorateTemplate', 'onTemplateLoad'];
//
// This is a utility function to delay an action, but only if another
// action hasn't been executed.
//
// Very useful for timeout actions or delays.
//
this.delayAction = function(delay, widget, action, data) {
var a = widget.delayedAction = {};
setTimeout(function() {
if (a === widget.delayedAction) {
widget.doAction(action, data, true);
}
}, delay);
};
//
//
//
this.delayActionSupport = function(callback, widget) {
widget.delayedAction = null;
callback();
};
//
// Initialize the widget before the template loads.
// If transitioning to another state, this rarely is the place--
// only transition here if you're not waiting for a fetch.
//
this.init = function(callback, widget, initialData) {
if (this._init) {
this._init(widget, initialData);
}
callback();
};
//
// This decorates a te
this.decorateTemplate = function(callback, widget, initialData) {
if (this._decorateTemplate) {
this._decorateTemplate(widget, initialData);
}
$(".stateWidgetAction",widget.element).each(function(i, o) {
var l = $(o);
l.bind(l.attr("eventType") ? l.attr("eventType") : 'click',
function() {
widget.doAction($(this).attr("action"));
return false;
});
});
callback();
};
//
// Get the template determined by this.templateName
// stored on the widget. Then, apply the template
// to the widgetElement with the widget data.
//
this.keepPreviousTemplate = false;
this.loadTemplate = function(callback, widget, data, templateName) {
var template = widget.templates[templateName ? templateName : this.templateName];
console.log("template to render:");
console.log(template);
template.applyTemplate(widget.getData(), widget.element, callback, this.keepPreviousTemplate);
};
//
// Do something after the widget after the template loads and is decorated.
// If transitioning to another state, this is typically the place
// (esp. if that transition is based on fetched data).
//
this.onTemplateLoad = function(callback, widget) {
if (this._onTemplateLoad) {
this._onTemplateLoad(widget);
}
callback();
};
//
// This sychronous getNextState uses this.actionsg
// to discover the name of the state mapping to
// the name of a state in this widget.
//
// The action can be either a string or a synchronous
// function that returns a string (takes a widget and this state.)
//
// You may choose not to validate an action in its action function
// by returning null
//
this._getNextState = function(widget, action) {
var nextState = this.actions[action];
if (nextState && $.isFunction(nextState)) {
nextState = nextState(widget, this);
}
return nextState === null ? null : widget.states[nextState];
};
if (args) {
$.extend(true, this, args);
}
};
//
// Now this is the wonderful $.udel.stateWidget complete with a ton of conventions.
//
//
var stateWidget = $.extend(true, {}, $.udel.api.stateWidget, {
_create: function() {
// This registers with $.udel.factory
if (this._registerInstance) {
this._registerInstance();
}
// This actually creates the widget
this._stateWidgetCreate.apply(this, arguments);
},
_stateWidgetCreate: function() {
this._initStores();
this._initTemplates();
this._initStates();
var that = this;
$(window).unload(function() {
that.saveState();
});
this.doAction(null, this.options.initialData);
},
//
// Set up this.stores and this.defaultStore via _getStore()
//
_initStores: function() {
var stores = {};
var defaultStore = null;
if (this.options.stores) {
var that = this;
$.each(this.options.stores, function(i) {
stores[i] = that._getStore(that.options.stores[i]);
if (!defaultStore || that.options.stores[i].defaultStore) {
defaultStore = stores[i];
}
});
}
this.stores = stores;
if (defaultStore) {
this.defaultStore = defaultStore;
}
},
//
// Set up this.templates via _getTemplate()
//
_initTemplates: function() {
var templates = {};
if (this.options.templates) {
var that = this;
$.each(this.options.templates, function(i) {
templates[i] = that._getTemplate(that.options.templates[i]);
});
}
this.templates = templates;
},
//
// Set up this.states and this.initialState via _getState()
//
_initStates: function() {
var states = {};
var initialState;
if (this.options.states) {
var that = this;
$.each(this.options.states, function(i) {
states[i] = that._getState(that.options.states[i]);
if (!initialState || states[i].initialState) {
initialState = states[i];
}
});
}
this.states = states;
if (initialState) {
this.initialState = initialState;
}
},
//
// Widget store
// Convention: if args is a string, that string is the url.
// Also, if a storeBaseUrl is provided and the url does not
// have http at the front, the url is appended to the storeBaseUrl.
//
_getStore: function(argsIn) {
var args = argsIn;
if (typeof argsIn === "string") {
args = {
url: argsIn
};
}
if (this.options.storeBaseUrl && args.url && (args.url.substring(0, 4) !== "http")) {
args.url = this.options.storeBaseUrl + args.url;
}
return new $.udel.store(args);
},
//
// Widget template
// Convention: if args is a string, that string is the url.
// Also, if a templateBaseUrl is provided and the url does not
// have http at the front, the url is appended to the templateBaseUrl.
//
_getTemplate: function(argsIn) {
var args = argsIn;
if (typeof argsIn === "string") {
args = {
url: argsIn
};
}
if (this.options.templateBaseUrl && args.url && (args.url.substring(0, 4) !== "http")) {
args.url = this.options.templateBaseUrl + args.url;
}
return new $.udel.template(args);
},
//
// Widget state
// Convention: if args is a string, that string is the template name.
//
_getState: function(argsIn) {
var args = argsIn;
if (typeof argsIn === "string") {
args = {
templateName: argsIn
};
}
return new $.udel.state(args);
}
});
$.widget("udel.stateWidget", stateWidget);
/* End UD Implementation */
/** Utility functions and classes **/
//
// A wait queue that allows you to add waiters by some key then calling
// them later (probably when some condition is satisfied).
//
$.udel.waitQueue = function(args) {
this.waits=[];
this.addWait = function(callback, maxWait, maxWaitExceeded) {
var i = this.waits.push({success: callback, failure:maxWaitExceeded});
if (maxWait) {
var that = this;
var waits = this.waits;
var remove = function() {
if (this.waits === that.waits) {
var waits = this.waits;
if (waits[i] !== null) {
var f = waits[i].failure;
waits[i] = null;
f();
}
}
};
remove.waits = waits;
setTimeout(remove, maxWait);
}
};
this.resume = function(args) {
var waits = this.waits;
this.waits = [];
$.each(waits, function(i) {
if (waits[i] !== null) {
var s = waits[i].success;
waits[i] = null;
s();
}
});
};
if (args) {
$.extend(true, this, args);
}
};
//
// This is a cache implemenation
// You can synchronously put(), contains() and markAsLoading().
// You can asynchronously get() and getput() and putget().
//
// get() is asynchronous because it might wait until a put() is called if
// the key is marked as loading.
// key is whatever you want it to be, required.
// callback is an optional function that takes 2 arguments:
// success/boolean and the value/?
// maxWait is optional, max wait time in ms
//
// putget() and getput() act both a get and a put. If the key is ready or
// markedAsLoading, it acts just like get(). Otherwise, it marks the key
// as loading, loads a value and gets it. If loader is not a function,
// it calls put(key,loader) and then get(key,callback). If loader is a
// function, it passes loader() a callback function that takes a value,
// calls put(key,value) then get(key,callback).
//
$.udel.cache = function(args) {
this.cache={};
this.ready={};
this.allowWaiting = true;
this.waiters = {};
this.contains = function(key) {
return this.ready[key] !== undefined;
};
this.markAsLoading = function(key) {
this.ready[key] = false;
};
// key is whatever you want it to be
// callback takes 2 arguments: success and the object
// maxWait in ms, optional
this.get = function(key, callback, maxWait) {
if (!callback) {
return;
}
if (this.ready[key] === undefined) {
callback(false);
} else if (this.ready[key]) {
callback(true, this.cache[key]);
} else if (this.allowWaiting) {
this._addWait(key, callback, maxWait);
} else {
callback(false);
}
};
this.put = function(key, value) {
this.cache[key] = value;
this.ready[key] = true;
if (this.allowWaiting) {
this._resume(key);
}
};
this.putget = this.getput = function(key, loader, callback, maxWait) {
if (this.ready[key] === undefined) {
this.markAsLoading(key);
if ($.isFunction(loader)) {
if (maxWait) {
this.get(key, callback, maxWait);
}
var that = this;
loader(function(value) {
that.put(key, value);
if (!maxWait) {
that.get(key, callback);
}
});
} else {
this.put(key, loader);
this.get(key, callback);
}
} else {
this.get(key, callback);
}
};
this._addWait = function(key, callback, maxWait) {
var waitQueue = this.waiters[key] = this.waiters[key] || new $.udel.waitQueue();
var that = this;
waitQueue.addWait(
function() {that.get(key, callback);},
function() {callback(false);},
maxWait);
};
this._resume = function(key) {
var waitQueue = this.waiters[key];
if (waitQueue) {
waitQueue.resume();
}
};
if (args) {
$.extend(true, this, args);
}
};
//
// This is a wrapper around the jquery template library.
//
// The function to notice is:
// applyTemplate(data/{}, target/DOMNode,
// callback/function, keepPreviousTemplate/boolean)
// Once a template is instanced, calling this function will apply
// the template with the given data, then call the callback with
// no arguments.
//
// args should include any (1) of the following: url, templateString, template.
// If these aren't good enough for you, override _init (and remember to set ready).
//
// You can also override cacheIt to avoid caching (jsps/dynamic).
//
$.udel.template = function(args) {
this.isCachingEnabled = true;
this.applyTemplate = function(data, target, callback, keepPreviousTemplate) {
var that = this;
this.getTemplate(function(template) {
if (template !== null) {
that._applyTemplate(template, data, target, keepPreviousTemplate);
}
if (callback) {
callback();
}
});
};
this._applyTemplate = function(template, data, target, keepPreviousTemplate) {
if (!keepPreviousTemplate) {
target.html("");
}
$.tmpl(template, data).appendTo(target);
};
this.getTemplate = function(callback) {
if (this.template) {
if (callback) {
callback(this.template);
}
} else if (this.templateString) {
console.log("compiling template:");
console.log(this.templateString);
this.template = $.template(this.templateString);
if (callback) {
callback(this.template);
}
} else if (this.url) {
if (this.isCachingEnabled) {
var cache = $.udel.template.urlCache = $.udel.template.urlCache || new $.udel.cache();
var that = this;
cache.getput(this.url,
function(callback) {
that.loadTemplate(that.url, that.isCachingEnabled, callback);
},
function(success, template) {
if (success) {
that.template = template;
}
if (callback) {
callback(template);
}
});
}
else {
this.loadTemplate(callback);
}
}
};
this.loadTemplate = function(url, isCachingEnabled, callback) {
$.ajax({
dataType: "text",
url: url,
type: "GET",
ifModified: isCachingEnabled,
success: function(tmplString) {
callback($.template(tmplString));
},
error: function() {
callback("error loading template");
}
});
};
this._init = function() {
this.getTemplate();
};
if (args) {
$.extend(true, this, args);
}
this._init();
};
/** End utility functions and classes */
});