forked from bmalnad/btcjamhelper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
featherlight.js
516 lines (464 loc) · 18.6 KB
/
featherlight.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
/**
* Featherlight - ultra slim jQuery lightbox
* Version 1.2.0 - http://noelboss.github.io/featherlight/
*
* Copyright 2015, Noël Raoul Bossart (http://www.noelboss.com)
* MIT Licensed.
**/
(function($) {
"use strict";
if('undefined' === typeof $) {
if('console' in window){ window.console.info('Too much lightness, Featherlight needs jQuery.'); }
return;
}
/* Featherlight is exported as $.featherlight.
It is a function used to open a featherlight lightbox.
[tech]
Featherlight uses prototype inheritance.
Each opened lightbox will have a corresponding object.
That object may have some attributes that override the
prototype's.
Extensions created with Featherlight.extend will have their
own prototype that inherits from Featherlight's prototype,
thus attributes can be overriden either at the object level,
or at the extension level.
To create callbacks that chain themselves instead of overriding,
use chainCallbacks.
For those familiar with CoffeeScript, this correspond to
Featherlight being a class and the Gallery being a class
extending Featherlight.
The chainCallbacks is used since we don't have access to
CoffeeScript's `super`.
*/
function Featherlight($content, config) {
if(this instanceof Featherlight) { /* called with new */
this.id = Featherlight.id++;
this.setup($content, config);
this.chainCallbacks(Featherlight._callbackChain);
} else {
var fl = new Featherlight($content, config);
fl.open();
return fl;
}
}
var opened = [],
pruneOpened = function(remove) {
opened = $.grep(opened, function(fl) {
return fl !== remove && fl.$instance.closest('body').length > 0;
} );
return opened;
};
// structure({iframeMinHeight: 44, foo: 0}, 'iframe')
// #=> {min-height: 44}
var structure = function(obj, prefix) {
var result = {},
regex = new RegExp('^' + prefix + '([A-Z])(.*)');
for (var key in obj) {
var match = key.match(regex);
if (match) {
var dasherized = (match[1] + match[2].replace(/([A-Z])/g, '-$1')).toLowerCase();
result[dasherized] = obj[key];
}
}
return result;
};
/* document wide key handler */
var eventMap = { keyup: 'onKeyUp', resize: 'onResize' };
var globalEventHandler = function(event) {
$.each(Featherlight.opened().reverse(), function() {
if (!event.isDefaultPrevented()) {
if (false === this[eventMap[event.type]](event)) {
event.preventDefault(); event.stopPropagation(); return false;
}
}
});
};
var toggleGlobalEvents = function(set) {
if(set !== Featherlight._globalHandlerInstalled) {
Featherlight._globalHandlerInstalled = set;
var events = $.map(eventMap, function(_, name) { return name+'.'+Featherlight.prototype.namespace; } ).join(' ');
$(window)[set ? 'on' : 'off'](events, globalEventHandler);
}
};
Featherlight.prototype = {
constructor: Featherlight,
/*** defaults ***/
/* extend featherlight with defaults and methods */
namespace: 'featherlight', /* Name of the events and css class prefix */
targetAttr: 'data-featherlight', /* Attribute of the triggered element that contains the selector to the lightbox content */
variant: null, /* Class that will be added to change look of the lightbox */
resetCss: false, /* Reset all css */
background: null, /* Custom DOM for the background, wrapper and the closebutton */
openTrigger: 'click', /* Event that triggers the lightbox */
closeTrigger: 'click', /* Event that triggers the closing of the lightbox */
filter: null, /* Selector to filter events. Think $(...).on('click', filter, eventHandler) */
root: 'body', /* Where to append featherlights */
openSpeed: 250, /* Duration of opening animation */
closeSpeed: 250, /* Duration of closing animation */
closeOnClick: 'background', /* Close lightbox on click ('background', 'anywhere' or false) */
closeOnEsc: true, /* Close lightbox when pressing esc */
closeIcon: '✕', /* Close icon */
loading: '', /* Content to show while initial content is loading */
otherClose: null, /* Selector for alternate close buttons (e.g. "a.close") */
beforeOpen: $.noop, /* Called before open. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
beforeContent: $.noop, /* Called when content is loaded. Gets event as parameter, this contains all data */
beforeClose: $.noop, /* Called before close. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
afterOpen: $.noop, /* Called after open. Gets event as parameter, this contains all data */
afterContent: $.noop, /* Called after content is ready and has been set. Gets event as parameter, this contains all data */
afterClose: $.noop, /* Called after close. Gets event as parameter, this contains all data */
onKeyUp: $.noop, /* Called on key down for the frontmost featherlight */
onResize: $.noop, /* Called after new content and when a window is resized */
type: null, /* Specify type of lightbox. If unset, it will check for the targetAttrs value. */
contentFilters: ['jquery', 'image', 'html', 'ajax', 'iframe', 'text'], /* List of content filters to use to determine the content */
/*** methods ***/
/* setup iterates over a single instance of featherlight and prepares the background and binds the events */
setup: function(target, config){
/* all arguments are optional */
if (typeof target === 'object' && target instanceof $ === false && !config) {
config = target;
target = undefined;
}
var self = $.extend(this, config, {target: target}),
css = !self.resetCss ? self.namespace : self.namespace+'-reset', /* by adding -reset to the classname, we reset all the default css */
$background = $(self.background || [
'<div class="'+css+'-loading '+css+'">',
'<div class="'+css+'-content">',
'<span class="'+css+'-close-icon '+ self.namespace + '-close">',
self.closeIcon,
'</span>',
'<div class="'+self.namespace+'-inner">' + self.loading + '</div>',
'</div>',
'</div>'].join('')),
closeButtonSelector = '.'+self.namespace+'-close' + (self.otherClose ? ',' + self.otherClose : '');
self.$instance = $background.clone().addClass(self.variant); /* clone DOM for the background, wrapper and the close button */
/* close when click on background/anywhere/null or closebox */
self.$instance.on(self.closeTrigger+'.'+self.namespace, function(event) {
var $target = $(event.target);
if( ('background' === self.closeOnClick && $target.is('.'+self.namespace))
|| 'anywhere' === self.closeOnClick
|| $target.closest(closeButtonSelector).length ){
event.preventDefault();
self.close();
}
});
return this;
},
/* this method prepares the content and converts it into a jQuery object or a promise */
getContent: function(){
var self = this,
filters = this.constructor.contentFilters,
readTargetAttr = function(name){ return self.$currentTarget && self.$currentTarget.attr(name); },
targetValue = readTargetAttr(self.targetAttr),
data = self.target || targetValue || '';
/* Find which filter applies */
var filter = filters[self.type]; /* check explicit type like {type: 'image'} */
/* check explicit type like data-featherlight="image" */
if(!filter && data in filters) {
filter = filters[data];
data = self.target && targetValue;
}
data = data || readTargetAttr('href') || '';
/* check explicity type & content like {image: 'photo.jpg'} */
if(!filter) {
for(var filterName in filters) {
if(self[filterName]) {
filter = filters[filterName];
data = self[filterName];
}
}
}
/* otherwise it's implicit, run checks */
if(!filter) {
var target = data;
data = null;
$.each(self.contentFilters, function() {
filter = filters[this];
if(filter.test) {
data = filter.test(target);
}
if(!data && filter.regex && target.match && target.match(filter.regex)) {
data = target;
}
return !data;
});
if(!data) {
if('console' in window){ window.console.error('Featherlight: no content filter found ' + (target ? ' for "' + target + '"' : ' (no target specified)')); }
return false;
}
}
/* Process it */
return filter.process.call(self, data);
},
/* sets the content of $instance to $content */
setContent: function($content){
var self = this;
/* we need a special class for the iframe */
if($content.is('iframe') || $('iframe', $content).length > 0){
self.$instance.addClass(self.namespace+'-iframe');
}
self.$instance.removeClass(self.namespace+'-loading');
/* replace content by appending to existing one before it is removed
this insures that featherlight-inner remain at the same relative
position to any other items added to featherlight-content */
self.$instance.find('.'+self.namespace+'-inner')
.slice(1).remove().end() /* In the unexpected event where there are many inner elements, remove all but the first one */
.replaceWith($.contains(self.$instance[0], $content[0]) ? '' : $content);
self.$content = $content.addClass(self.namespace+'-inner');
return self;
},
/* opens the lightbox. "this" contains $instance with the lightbox, and with the config */
open: function(event){
var self = this;
if((!event || !event.isDefaultPrevented())
&& self.beforeOpen(event) !== false) {
if(event){
event.preventDefault();
}
var $content = self.getContent();
if($content){
opened.push(self);
toggleGlobalEvents(true);
self.$instance.appendTo(self.root).fadeIn(self.openSpeed);
self.beforeContent(event);
/* Set content and show */
$.when($content).always(function($content){
self.setContent($content);
self.afterContent(event);
/* Call afterOpen after fadeIn is done */
$.when(self.$instance.promise()).done(function(){
self.afterOpen(event);
});
});
return self;
}
}
return false;
},
/* closes the lightbox. "this" contains $instance with the lightbox, and with the config */
close: function(event){
var self = this;
if(self.beforeClose(event) === false) {
return false;
}
if (0 === pruneOpened(self).length) {
toggleGlobalEvents(false);
}
self.$instance.fadeOut(self.closeSpeed,function(){
self.$instance.detach();
self.afterClose(event);
});
},
/* Utility function to chain callbacks
[Warning: guru-level]
Used be extensions that want to let users specify callbacks but
also need themselves to use the callbacks.
The argument 'chain' has callback names as keys and function(super, event)
as values. That function is meant to call `super` at some point.
*/
chainCallbacks: function(chain) {
for (var name in chain) {
this[name] = $.proxy(chain[name], this, $.proxy(this[name], this));
}
}
};
$.extend(Featherlight, {
id: 0, /* Used to id single featherlight instances */
autoBind: '[data-featherlight]', /* Will automatically bind elements matching this selector. Clear or set before onReady */
defaults: Featherlight.prototype, /* You can access and override all defaults using $.featherlight.defaults, which is just a synonym for $.featherlight.prototype */
/* Contains the logic to determine content */
contentFilters: {
jquery: {
regex: /^[#.]\w/, /* Anything that starts with a class name or identifiers */
test: function(elem) { return elem instanceof $ && elem; },
process: function(elem) { return $(elem).clone(true); }
},
image: {
regex: /\.(png|jpg|jpeg|gif|tiff|bmp)(\?\S*)?$/i,
process: function(url) {
var self = this,
deferred = $.Deferred(),
img = new Image(),
$img = $('<img src="'+url+'" alt="" class="'+self.namespace+'-image" />');
img.onload = function() {
/* Store naturalWidth & height for IE8 */
$img.naturalWidth = img.width; $img.naturalHeight = img.height;
deferred.resolve( $img );
};
img.onerror = function() { deferred.reject($img); };
img.src = url;
return deferred.promise();
}
},
html: {
regex: /^\s*<[\w!][^<]*>/, /* Anything that starts with some kind of valid tag */
process: function(html) { return $(html); }
},
ajax: {
regex: /./, /* At this point, any content is assumed to be an URL */
process: function(url) {
var self = this,
deferred = $.Deferred();
/* we are using load so one can specify a target with: url.html #targetelement */
var $container = $('<div></div>').load(url, function(response, status){
if ( status !== "error" ) {
deferred.resolve($container.contents());
}
deferred.fail();
});
return deferred.promise();
}
},
iframe: {
process: function(url) {
var deferred = new $.Deferred();
var $content = $('<iframe/>')
.hide()
.attr('src', url)
.css(structure(this, 'iframe'))
.on('load', function() { deferred.resolve($content.show()); })
// We can't move an <iframe> and avoid reloading it,
// so let's put it in place ourselves right now:
.appendTo(this.$instance.find('.' + this.namespace + '-content'));
return deferred.promise();
}
},
text: {
process: function(text) { return $('<div>', {text: text}); }
}
},
functionAttributes: ['beforeOpen', 'afterOpen', 'beforeContent', 'afterContent', 'beforeClose', 'afterClose'],
/*** class methods ***/
/* read element's attributes starting with data-featherlight- */
readElementConfig: function(element) {
var Klass = this,
config = {};
if (element && element.attributes) {
$.each(element.attributes, function(){
var match = this.name.match(/^data-featherlight-(.*)/);
if (match) {
var val = this.value,
name = $.camelCase(match[1]);
if ($.inArray(name, Klass.functionAttributes) >= 0) { /* jshint -W054 */
val = new Function(val); /* jshint +W054 */
} else {
try { val = $.parseJSON(val); }
catch(e) {}
}
config[name] = val;
}
});
}
return config;
},
/* Used to create a Featherlight extension
[Warning: guru-level]
Creates the extension's prototype that in turn
inherits Featherlight's prototype.
Could be used to extend an extension too...
This is pretty high level wizardy, it comes pretty much straight
from CoffeeScript and won't teach you anything about Featherlight
as it's not really specific to this library.
My suggestion: move along and keep your sanity.
*/
extend: function(child, defaults) {
/* Setup class hierarchy, adapted from CoffeeScript */
var Ctor = function(){ this.constructor = child; };
Ctor.prototype = this.prototype;
child.prototype = new Ctor();
child.__super__ = this.prototype;
/* Copy class methods & attributes */
$.extend(child, this, defaults);
child.defaults = child.prototype;
return child;
},
attach: function($source, $content, config) {
var Klass = this;
if (typeof $content === 'object' && $content instanceof $ === false && !config) {
config = $content;
$content = undefined;
}
/* make a copy */
config = $.extend({}, config);
/* Only for openTrigger and namespace... */
var tempConfig = $.extend({}, Klass.defaults, Klass.readElementConfig($source[0]), config);
$source.on(tempConfig.openTrigger+'.'+tempConfig.namespace, tempConfig.filter, function(event) {
/* ... since we might as well compute the config on the actual target */
var elemConfig = $.extend({$source: $source, $currentTarget: $(this)}, Klass.readElementConfig($source[0]), Klass.readElementConfig(this), config);
new Klass($content, elemConfig).open(event);
});
return $source;
},
current: function() {
var all = this.opened();
return all[all.length - 1] || null;
},
opened: function() {
var klass = this;
pruneOpened();
return $.grep(opened, function(fl) { return fl instanceof klass; } );
},
close: function() {
var cur = this.current();
if(cur) { cur.close(); }
},
/* Does the auto binding on startup.
Meant only to be used by Featherlight and its extensions
*/
_onReady: function() {
var Klass = this;
if(Klass.autoBind){
/* First, bind click on document, so it will work for items added dynamically */
Klass.attach($(document), {filter: Klass.autoBind});
/* Auto bound elements with attr-featherlight-filter won't work
(since we already used it to bind on document), so bind these
directly. We can't easily support dynamically added element with filters */
$(Klass.autoBind).filter('[data-featherlight-filter]').each(function(){
Klass.attach($(this));
});
}
},
/* Featherlight uses the onKeyUp callback to intercept the escape key.
Private to Featherlight.
*/
_callbackChain: {
onKeyUp: function(_super, event){
if(27 === event.keyCode) {
if (this.closeOnEsc) {
this.$instance.find('.'+this.namespace+'-close:first').click();
}
return false;
} else {
return _super(event);
}
},
onResize: function(_super, event){
if (this.$content.naturalWidth) {
var w = this.$content.naturalWidth, h = this.$content.naturalHeight;
/* Reset apparent image size first so container grows */
this.$content.css('width', '').css('height', '');
/* Calculate the worst ratio so that dimensions fit */
var ratio = Math.max(
w / parseInt(this.$content.parent().css('width'),10),
h / parseInt(this.$content.parent().css('height'),10));
/* Resize content */
if (ratio > 1) {
this.$content.css('width', '' + w / ratio + 'px').css('height', '' + h / ratio + 'px');
}
}
return _super(event);
},
afterContent: function(_super, event){
var r = _super(event);
this.onResize(event);
return r;
}
}
});
$.featherlight = Featherlight;
/* bind jQuery elements to trigger featherlight */
$.fn.featherlight = function($content, config) {
return Featherlight.attach(this, $content, config);
};
/* bind featherlight on ready if config autoBind is set */
$(document).ready(function(){ Featherlight._onReady(); });
}(jQuery));