forked from dowjones/intentionjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
intention.js
487 lines (377 loc) · 12.2 KB
/
intention.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
/*!
* intention.js Library v0.9.6.3
* http://intentionjs.com/
*
* Copyright 2011, 2013 Dowjones and other contributors
* Released under the MIT license
*
*/
(function(root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define('intention', ['jquery', 'underscore'], factory);
} else {
root.Intention = factory(root.jQuery, root._);
}
}(this, function($, _) {
'use strict';
var Intention = function(params){
var intent = _.extend(this, params,
{_listeners:{}, contexts:[], elms:$(), axes:{}, priority:[]});
return intent;
};
Intention.prototype = {
// public methods
responsive:function responsive(contexts, options){
// for generating random ids for axis when not specified
var idChars = 'abcdefghijklmnopqrstuvwxyz0123456789',
id='', i;
// create a random id for the axis
for(i=0; i<5; i++){
id += idChars[Math.floor(Math.random() * idChars.length)];
}
var defaults = {
// if no matcher function is specified expect to compare a
// string to the ctx.name property
matcher: function(measure, ctx){
return measure === ctx.name;
},
// function takes one arg and returns it
measure: _.identity,
ID: id
};
if(_.isObject(options) === false) {
options = {};
}
if((_.isArray(contexts)) && (_.isArray(contexts[0].contexts))){
_.each(contexts, function(axis){
responsive.apply(this, axis);
}, this);
return;
}
if((_.isArray(contexts) === false) && _.isObject(contexts)){
options = contexts;
} else {
options.contexts = contexts;
}
// fill in the options
options = _.extend({}, defaults, options);
// bind an the respond function to the axis ID
this.on(options.ID, _.bind(
function(e){
this.axes = this._contextualize(
options.ID, e.context, this.axes);
this._respond(this.axes, this.elms);
}, this));
var axis = {
ID:[options.ID],
current:null,
contexts:options.contexts,
respond:_.bind(this._responder(options.ID,
options.contexts, options.matcher, options.measure), this)
};
this.axes[options.ID] = axis;
this.axes.__keys__ = this.priority;
this.priority.unshift(options.ID);
return axis;
},
elements: function(scope){
// find all responsive elms in a specific dom scope
if(!scope){
scope = document;
}
$('[data-intent],[intent],[data-in],[in]',
scope).each(_.bind(function(i, elm){
this.add($(elm));
}, this));
return this;
},
add: function(elms, options){
var spec;
if(!options) {
options = {};
}
// is expecting a jquery object
elms.each(_.bind(function(i, elm){
var exists = false;
this.elms.each(function(i, respElm){
if(elm === respElm) {
exists=true;
return false;
}
});
if(exists === false){
// create the elements responsive data
spec = this._fillSpec(
_.extend(options, this._attrsToSpec(elm.attributes)));
// make any appropriate changes based on the current contexts
this._makeChanges($(elm), spec, this.axes);
this.elms.push({
elm: elm,
spec: spec
});
}
}, this));
return this;
},
remove: function(elms){
// is expecting a jquery object
var respElms = this.elms;
// elms to remove
elms.each(function(i, elm){
// elms to check against
respElms.each(function(i, candidate){
if(elm === candidate.elm){
respElms.splice(i, 1);
// found the match, break the loop
return false;
}
});
});
return this;
},
is: function(ctxName){
var axes = this.axes;
return _.some(axes.__keys__, function(key){
return ctxName === axes[key].current;
});
},
// code and concept taken from simple implementation of
// observer pattern outlined here:
// http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/
on: function(type, listener){
if(this._listeners[type] === undefined) {
this._listeners[type]=[];
}
this._listeners[type].push(listener);
return this;
},
off: function(type, listener){
if(_.isArray(this._listeners[type])){
var listeners = this._listeners[type],
i;
for(i=0;listeners.length; i++){
if(listeners[i] === listener){
listeners.splice(i,1);
break;
}
}
}
return this;
},
// privates
_responder: function(axisID, contexts, matcher, measure){
var currentContext;
// called to perform a check
return function(){
var measurement = measure.apply(this, arguments);
_.every(contexts, function(ctx){
if( matcher(measurement, ctx)) {
// first time, or different than last context
if( (currentContext===undefined) ||
(ctx.name !== currentContext.name)){
currentContext = ctx;
// emit the axis event
this._emitter({_type:axisID, context:currentContext.name},
currentContext, this)
// then emit the context event (second ensures the context
// changes happen after all dom manipulations)
._emitter(_.extend({}, {_type:currentContext.name},
currentContext), currentContext, this);
// done, break the loop
return false;
}
// same context, break the loop
return false;
}
return true;
}, this);
// return the intention object for chaining
return this;
};
},
_emitter: function(event){
if(typeof event === 'string') {
event={_type:event};
}
if(!event.target){
event.target=this;
}
if(!event._type){
throw new Error(event._type + ' is not a supported event.');
}
if(_.isArray(this._listeners[event._type])){
var listeners = this._listeners[event._type],
i;
for(i=0; i<listeners.length; i++){
listeners[i].apply(this, arguments);
}
}
return this;
},
_fillSpec: function(spec){
var applySpec = function(fn){
_.each(spec, fn);
}, filler={};
applySpec(function(options){
// check to see if the ctx val is an object, could be a string
if(_.isObject(options)){
_.each(options, function(val, func){
filler[func] = '';
});
}
});
applySpec(function(options, ctx){
if(_.isObject(options)){
spec[ctx] = _.extend({}, filler, options);
}
});
return spec;
},
_attrsToSpec: function(attrs){
var spec={},
fullPattern = new RegExp(
'^(data-)?(in|intent)-([a-zA-Z0-9][_a-zA-Z0-9]*)-([A-Za-z:-]+)'),
axisPattern = new RegExp(
'^(data-)?(in|intent)-([a-zA-Z0-9][_a-zA-Z0-9]*)$'),
addProp=function(obj, name, value){
obj[name] = value;
return obj;
};
_.each(attrs, function(attr){
var specMatch = attr.name.match(fullPattern);
if(specMatch !== null) {
specMatch = specMatch.slice(-2);
var ctx = specMatch[0],
ctxSpec = spec[ctx] || {};
spec = addProp(spec, ctx,
addProp(ctxSpec, specMatch[1], attr.value));
} else if(axisPattern.test(attr.name)){
spec['_' + attr.name.match(axisPattern)[3]] = attr.value;
}
});
return spec;
},
_resolveSpecs: function(currentContexts, specs){
var changes={},
moveFuncs=['append', 'prepend', 'before', 'after'];
_.each(currentContexts, function(ctxName){
_.each(specs[ctxName], function(val, func){
if(func==='class'){
if(!changes[func]){
changes[func] = [];
}
changes[func] = _.union(changes[func], val.split(' '));
} else if(((changes.move === undefined) ||
(changes.move.value === '')) &&
($.inArray(func, moveFuncs) !== -1)){
changes.move = {value:val, placement:func};
} else {
if((changes[func] === undefined) || (changes[func] === '')){
changes[func]=val;
}
}
}, this);
}, this);
return changes;
},
_currentContexts: function(axes) {
var contexts = [];
_.each(axes.__keys__, function(ID){
if(axes[ID].current !== null) {
contexts.push(axes[ID].current);
return;
}
});
return contexts;
},
_removeClasses: function(specs, axes) {
var toRemove = [];
_.each(axes.__keys__, function(key){
var axis = axes[key],
axisSpec = false;
if(specs['_' + axis.ID] !== undefined){
axisSpec = true;
}
_.each(axis.contexts, function(ctx){
// ignore the current context, those classes SHOULD be applied
if(ctx.name === axis.current) {
return;
}
if(axisSpec) {
toRemove.push(ctx.name);
}
var contextSpec = specs[ctx.name],
classes;
if(contextSpec !== undefined) {
if(contextSpec['class'] !== undefined) {
classes = contextSpec['class'].split(' ');
if(classes !== undefined){
toRemove = _.union(toRemove, classes);
}
}
}
}, this);
}, this);
return toRemove;
},
_contextConfig: function(specs, axes){
var config = this._resolveSpecs(this._currentContexts(axes), specs, axes);
// add the axis specs:
_.each(specs, function(spec, specName){
var match;
if(this._axis_test_pattern.test(specName)) {
match = specName.match(this._axis_match_pattern)[1];
if(axes[match]){
config['class'] = _.union(config['class'],
[axes[match].current, spec]);
}
}
}, this);
return config;
},
_makeChanges: function(elm, specs, axes){
if(_.isEmpty(axes)===false){
var ctxConfig = this._contextConfig(specs, axes);
_.each(ctxConfig, function(change, func){
if(func==='move'){
if( (specs.__placement__ !== change.placement) ||
(specs.__move__ !== change.value)){
$(change.value)[change.placement](elm);
// save the last placement of the element so
// we're not moving it around for no good reason
specs.__placement__ = change.placement;
specs.__move__ = change.value;
}
} else if(func === 'class') {
var classes = elm.attr('class') || '';
// the class add/remove formula
classes = _.union(change,
_.difference(classes.split(' '), this._removeClasses(specs, axes)));
elm.attr('class', classes.join(' '));
} else {
elm.attr(func, change);
}
}, this);
}
return elm;
},
_respond: function(axes, elms){
// go through all of the responsive elms
elms.each(_.bind(function(i, elm){
var $elm = $(elm.elm);
this._makeChanges($elm, elm.spec, axes);
$elm.trigger('intent', this);
}, this));
},
_contextualize: function(axisID, context, axes){
axes[axisID].current = context;
return axes;
},
// private props
_axis_test_pattern: /^_[^_]/, // does it begin with an underscore
// match a group after the underscore:
_axis_match_pattern: /^_([a-zA-Z0-9][_a-zA-Z0-9]*)/
};
return Intention;
}));