-
Notifications
You must be signed in to change notification settings - Fork 7
/
oj.js
3168 lines (2657 loc) · 93.4 KB
/
oj.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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// oj.js v0.9.1
// ojjs.org
//
// Copyright 2013-2019, Evan Moran
// Released under the MIT License
//
// ===================================================================
// Unified templating for the people. Thirsty people.
;(function(root, factory){
var initDom = "<!DOCTYPE html><html><head></head><body></body></html>";
// CommonJS export for Node
if (typeof module === 'object' && module.exports) {
try {$ = root.$ || require('jquery')} catch (e){}
var thedoc = root.document;
try {
if (!thedoc) {
jsdom = require('jsdom');
dom = new jsdom.JSDOM(initDom);
thedoc = dom.window.document;
}
} catch (e){}
module.exports = factory(root, $, thedoc)
}
// else if (typeof define === 'function' && define.amd)
// // AMD export for RequireJS
// define(['jquery'], ['jsdom'], function($, jsdom){
// return factory(root, $, new jsdom.JSDOM(initDom).window.document)
// })
// Global export for client side
else
root.oj = factory(root, (root.$ || root.jQuery || root.Zepto || root.ender), root.document)
}(this, function(root, $, doc){
var ArrP = Array.prototype,
FunP = Function.prototype,
ObjP = Object.prototype,
slice = ArrP.slice,
unshift = ArrP.unshift,
concat = ArrP.concat,
pass = function(v){return v},
_udf = 'undefined'
// oj function: highest level of capture for tag functions
function oj(){
return oj.tag.apply(this, ['oj'].concat(slice.call(arguments)).concat([{__quiet__:1}]))
}
// Version
oj.version = '0.9.1'
// Configuration settings
oj.settings = {
defaultThemes: null
}
oj.isClient = !(typeof process !== _udf && process !== null ? process.versions != null ? process.versions.node : 0 : 0)
// Detect jQuery globally or in required module
if (typeof $ != _udf)
oj.$ = $
// Reference ourselves for template files to see
oj.oj = oj
// oj.load: load the page specified generating necessary html, css, and client side events
oj.load = function(page, data){
// Defer dom manipulation until the page is ready
return oj.$(function(){
// Load through require and passing through template data
var ojml = function(){require(page).call(data, data)}
oj.$.ojBody(ojml)
// Trigger events bound through onload
return oj.onload()
})
}
// oj.onload: Enlist in onload action or run them.
var _onLoadQueue = {queue: [], loaded: false}
oj.onload = function(f){
// Call everything if no arguments
if (oj.isUndefined(f)){
_onLoadQueue.loaded = true
while ((f = _onLoadQueue.queue.shift()))
f()
}
// Call load if already loaded
else if (_onLoadQueue.loaded)
f()
// Queue function for later
else
_onLoadQueue.queue.push(f)
}
// oj.emit: Used by plugins to group multiple elements as if it is a single tag.
oj.emit = function(){return oj.tag.apply(oj, ['oj'].concat(slice.call(arguments)))}
// Type Helpers
oj.isDefined = function(a){return typeof a !== _udf}
oj.isOJ = function(obj){return !!(obj != null ? obj.isOJ : void 0)}
oj.isOJType = function(a){return oj.isOJ(a) && a.type === a}
oj.isOJInstance = function(a){return oj.isOJ(a) && !oj.isOJType(a)}
oj.isEvented = function(a){return !!(a && a.on && a.off && a.trigger)}
oj.isDOM = function(a){return !!(a && (a.nodeType != null))}
oj.isDOMElement = function(a){return !!(a && a.nodeType === 1)}
oj.isDOMAttribute = function(a){return !!(a && a.nodeType === 2)}
oj.isDOMText = function(a){return !!(a && a.nodeType === 3)}
oj.isjQuery = function(a){return !!(a && a.jquery)}
oj.isUndefined = function(a){return a === void 0}
oj.isBoolean = function(a){return a === true || a === false || ObjP.toString.call(a) === '[object Boolean]'}
oj.isNumber = function(a){return !!(a === 0 || (a && a.toExponential && a.toFixed))}
oj.isString = function(a){return !!(a === '' || (a && a.charCodeAt && a.substr))}
oj.isDate = function(a){return !!(a && a.getTimezoneOffset && a.setUTCFullYear)}
oj.isPlainObject = function(a){return oj.$.isPlainObject(a) && !oj.isOJ(a)}
oj.isFunction = oj.$.isFunction
oj.isArray = oj.$.isArray
oj.isRegEx = function(a){return ObjP.toString.call(a) === '[object RegExp]'}
oj.isArguments = function(a){return ObjP.toString.call(a) === '[object Arguments]'}
oj.parse = function(str){
var n, o = str
if (str === _udf)
o = void 0
else if (str === 'null')
o = null
else if (str === 'true')
o = true
else if (str === 'false')
o = false
else if (!isNaN(n = parseFloat(str)))
o = n
return o
}
// unionArguments: Union arguments into options and args
oj.unionArguments = function(argList){
var options = {}, args = [], v, ix = 0
for (; ix < argList.length; ix++){
v = argList[ix]
if (oj.isPlainObject(v))
options = _extend(options, v)
else
args.push(v)
}
return {options: options, args: args}
}
// argumentShift: Shift argument out of options with key
oj.argumentShift = function(options, key){
var value
if ((oj.isPlainObject(options)) && (key != null) && (options[key] != null)){
value = options[key]
delete options[key]
}
return value
}
// Utility Helpers
var _keys = Object.keys,
_extend = oj.$.extend
function _isCapitalLetter(c){return !!(c.match(/[A-Z]/))}
function _has(obj, key){return ObjP.hasOwnProperty.call(obj, key)}
function _values(obj){
var keys = _keys(obj),
len = keys.length,
values = new Array(len),
i = 0
for (; i < len; i++)
values[i] = obj[keys[i]]
return values
}
function _toArray(obj){
if (!obj)
return []
if (oj.isArray(obj))
return slice.call(obj)
if (oj.isArguments(obj))
return slice.call(obj)
if (obj.toArray && oj.isFunction(obj.toArray))
return obj.toArray()
return _values(obj)
}
function _isEmpty(o){
if (oj.isArray(o))
return o.length === 0
for (var k in o)
if (_has(o, k))
return false
return true
}
function _clone(o){
if (!(oj.isArray(o) || oj.isPlainObject(o)))
return o
if (oj.isArray(o))
return o.slice()
else
return _extend({}, o)
}
// _setObject(obj, k1, k2, ..., value):
// Set object deeply key by key ensure each part is an object
function _setObject(obj){
var args = arguments,
o = obj,
len = args.length,
// keys are args ix: 1 to n-2
keys = 3 <= len ? slice.call(args, 1, len = len - 1) : (len = 1, []),
// value is last arg
value = args[len++],
ix, k
for (ix = 0; ix < keys.length; ix++){
k = keys[ix]
// Initialize key to empty object if necessary
if (typeof o[k] !== 'object')
o[k] = {}
// Set final value if this is the last key
if (ix === keys.length - 1)
o[k] = value
else
// Continue deeper
o = o[k]
}
return obj
}
// uniqueSort:
function uniqueSort(arr, isSorted){
if (isSorted == null)
isSorted = false
if (!isSorted)
arr.sort()
var out = [], ix, item
for (ix = 0; ix < arr.length; ix++){
item = arr[ix]
if (ix > 0 && arr[ix - 1] === arr[ix])
continue
out.push(item)
}
return out
}
// _d(args...): initialization helper that returns first arg that isn't null
function _d(){
for (var ix = 0;ix < arguments.length; ix++)
if (arguments[ix] != null)
return arguments[ix]
return null
}
// _e: error by throwing msg with optional fn name
function _e(fn, msg){
msg = _d(msg, fn, '')
fn = _d(fn, 0)
var pfx = "oj: "
if (fn)
pfx = "oj." + fn + ": "
throw new Error(pfx + msg)
}
// _a: assert when cond is false with msg and with optional fn name
function _a(cond, fn, msg){if (!cond) _e(fn,msg)}
// _v: validate argument n with fn name and message
function _v(fn, n, v, type){
n = {1:'first',2:'second',3: 'third', 4: 'fourth'}[n]
_a(!type || (typeof v === type), fn, "" + type + " expected for " + n + " argument")
}
// _splitAndTrim: Split string by seperator and trim result
function _splitAndTrim(str, seperator, limit){
return str.split(seperator, limit).map(function(v){
return v.trim()
})
}
// _decamelize: Convert from camal case to underscore case
function _decamelize(str){return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase()}
// _dasherize: Convert from camal case or space seperated to dashes
function _dasherize(str){return _decamelize(str).replace(/[ _]/g, '-')}
// oj.addMethod: add multiple methods to an object
oj.addMethods = function(obj, mapNameToMethod){
for (var methodName in mapNameToMethod)
oj.addMethod(obj, methodName, mapNameToMethod[methodName])
}
// oj.addMethod: Add method to object with name and fn
oj.addMethod = function(obj, name, fn){
_v('addMethod', 2, name, 'string')
_v('addMethod', 3, fn, 'function')
// Methods are non-enumerable, non-writable properties
Object.defineProperty(obj, name, {
value: fn,
enumerable: false,
writable: false,
configurable: true
})
}
// oj.removeMethod: Remove a method with name from an object
oj.removeMethod = function(obj, name){
_v('removeMethod', 2, name, 'string')
delete obj[name]
}
// oj.addProperties: add multiple properties to an object
// Properties can be specified by get/set methods or by a value
// Optionally you can include writable or enumerable settings
oj.addProperties = function(obj, mapNameToInfo){
// Iterate over properties
var propInfo, propName
for (propName in mapNameToInfo){
propInfo = mapNameToInfo[propName]
// Wrap the value if propInfo is not already a prop definition
if (((propInfo != null ? propInfo.get : void 0) == null) &&
((propInfo != null ? propInfo.value : void 0) == null))
propInfo = {value: propInfo, writable: true}
oj.addProperty(obj, propName, propInfo)
}
}
// oj.addProperty: Add property to object with name and info
oj.addProperty = function(obj, name, info){
_v('addProperty', 2, name, 'string')
_v('addProperty', 3, info, 'object')
// Default properties to enumerable and configurable
info = _extend({enumerable: true, configurable: true}, info)
// Remove property if it already exists
if (Object.getOwnPropertyDescriptor(obj, name) != null)
oj.removeProperty(obj, name)
// Add the property
Object.defineProperty(obj, name, info)
}
// oj.removeProperty: remove property from object with name
oj.removeProperty = function(obj, name){
_v('removeProperty', 2, name, 'string')
delete obj[name]
}
// oj.isProperty: Determine property in object is a get/set property
oj.isProperty = function(obj, name){
_v('isProperty', 2, name, 'string')
return Object.getOwnPropertyDescriptor(obj, name).get != null
}
// oj.copyProperty: Copy source.propName to dest.propName
oj.copyProperty = function(dest, source, propName){
var info = Object.getOwnPropertyDescriptor(source, propName)
info = _d(info, {value: [], enumerable: false, writable: true, configurable: true })
if (info.value != null)
info.value = _clone(info.value)
return Object.defineProperty(dest, propName, info)
}
// _argsStack: Abstraction to wrap global arguments stack.
// This makes me sad but it is necessary for div -> syntax
var _argsStack = []
// Access the top of the stack
oj._argsTop = function(){
if (_argsStack.length)
return _argsStack[_argsStack.length - 1]
else
return null
}
// Push scope onto arguments
oj._argsPush = function(args){
_argsStack.push(_d(args,[]))
}
// Pop scope from arguments
oj._argsPop = function(){
if (_argsStack.length)
return _argsStack.pop()
return null
}
// Append argument
oj._argsAppend = function(arg){
var top = oj._argsTop()
if (top != null)
top.push(arg)
}
// oj.tag (name, attributes, rest...)
oj.tag = function(name){
_v('tag', 1, name, 'string')
var rest = 2 <= arguments.length ? slice.call(arguments, 1) : [],
u = oj.unionArguments(rest),
args = u.args,
attributes = u.options,
isQuiet = attributes.__quiet__,
arg, len, r, ix,
// Build ojml starting with tag
ojml = [name]
if (isQuiet)
delete attributes.__quiet__
// Add attributes to ojml if they exist
if (!_isEmpty(attributes))
ojml.push(attributes)
// Store current tag context
oj._argsPush(ojml)
// Loop over attributes
for (ix = 0; ix < args.length; ix++){
arg = args[ix]
if (oj.isPlainObject(arg))
continue
else if (oj.isFunction(arg)){
len = oj._argsTop().length
// Call the fn tags will append to oj._argsTop
r = arg()
// Use return value instead if oj._argsTop didn't change
if (len === oj._argsTop().length && (r != null))
oj._argsAppend(r)
} else
oj._argsAppend(arg)
}
// Restore previous tag context
oj._argsPop()
// Append the final result to your parent's arguments
// if there exists an argument to append to.
// Do not emit when quiet is set,
if (!isQuiet)
oj._argsAppend(ojml)
return ojml
}
// Define all elements as closed or open
oj.tag.elements = {
closed: 'a abbr acronym address applet article aside audio b bdo big blockquote body button canvas caption center cite code colgroup command datalist dd del details dfn dir div dl dt em embed fieldset figcaption figure font footer form frameset h1 h2 h3 h4 h5 h6 head header hgroup html i iframe ins keygen kbd label legend li map mark menu meter nav noframes noscript object ol optgroup option output p pre progress q rp rt ruby s samp script section select small source span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr tt u ul var video wbr xmp'.split(' '),
open: 'area base br col command css !DOCTYPE embed hr img input keygen link meta param source track wbr'.split(' ')
}
// Keep track of all valid elements
oj.tag.elements.all = (oj.tag.elements.closed.concat(oj.tag.elements.open)).sort()
// tag.isClosed: Determine if an element is closed or open
oj.tag.isClosed = function(tag){return oj.tag.elements.open.indexOf(tag) === -1}
// _setTagName: Record tag name on a given tag function
function _setTagName(tag, name){if (tag != null) tag.tagName = name }
// _getTagName: Get a tag name on a given tag function
function _getTagName(tag){return tag.tagName}
// _getQuietTagName: Get quiet tag name
function _getQuietTagName(tag){return '_' + tag}
// _setInstanceOnElement: Record an oj instance on a given element
function _setInstanceOnElement(el, inst){if (el != null) el.oj = inst}
// _getInstanceOnElement: Get a oj instance on a given element
function _getInstanceOnElement(el){
if ((el != null ? el.oj : 0) != null)
return el.oj
else
return null
}
// Create tag methods for all elements
for (var ix = 0; ix < oj.tag.elements.all.length; ix++){
t = oj.tag.elements.all[ix]
;(function(t){
// Define tag function named t
oj[t] = function(){return oj.tag.apply(oj, [t].concat(slice.call(arguments)))}
// Quiet tag functions do not emit
// Define quiet tag function named qt
var qt = _getQuietTagName(t)
oj[qt] = function(){return oj.tag.apply(oj, [t, {__quiet__: 1 }].concat(slice.call(arguments)))}
// Tag functions remember their name so the OJML syntax can use the function
_setTagName(oj[t], t)
_setTagName(oj[qt], t)
})(t)
}
// oj.doctype: Method to define doctypes based on short names
var dhp = 'HTML PUBLIC "-//W3C//DTD HTML 4.01',
w3 = '"http://www.w3.org/TR/html4/',
strict5 = 'html',
strict4 = dhp + '//EN" ' + w3 + 'strict.dtd"',
_doctypes = {
'5': strict5,
'HTML 5': strict5,
'4': strict4,
'HTML 4.01 Strict': strict4,
'HTML 4.01 Frameset': dhp + ' Frameset//EN" ' + w3 + 'frameset.dtd"',
'HTML 4.01 Transitional': dhp + ' Transitional//EN" ' + w3 + 'loose.dtd"'
}
// Define the method passing through to !DOCTYPE tag function
oj.doctype = function(typeOrValue){
typeOrValue = _d(typeOrValue,'5')
return oj['!DOCTYPE'](_d(_doctypes[typeOrValue], typeOrValue))
}
// oj.extendInto (context): Extend all OJ methods into a context.
// Defaults to root, which is either `global` or `window`
// Methods that start with _ are not extended
oj.useGlobally = oj.extendInto = function(context){
context = _d(context,root)
var o = {}, k, qn, v
// For all keys and values in oj
for (k in oj){
v = oj[k]
// Extend into new object
if (k[0] !== '_' && k !== 'extendInto' && k !== 'useGlobally'){
o[k] = v
// Export _tag and _Type methods
qn = _getQuietTagName(k)
if (oj[qn])
o[qn] = oj[qn]
}
}
_extend(context, o)
}
// oj.compile(options, ojml)
// ---
// Compile ojml into meaningful parts
// options:
// * html - Compile to html
// * dom - Compile to dom
// * css - Compile to css
// * cssMap - Record css as a javascript object
// * styles -- Output css as style tags
// * minify - Minify js and css
// * ignore:{html:1} - Map of tags to ignore while compiling
oj.compile = function(options, ojml){
// Options is optional
ojml = _d(ojml, options)
var css, cssMap, dom, html,
// Default options to compile everything
options = _extend({html:1, dom:0, css:0, cssMap:0, minify:0, ignore:{}}, options),
// Init accumulator
acc = _clone(options)
acc.html = options.html ? [] : null
acc.dom = options.dom && (typeof doc !== "undefined" && doc !== null) ? doc.createElement('OJ') : null
acc.css = options.css || options.cssMap ? {} : null
acc.indent = ''
acc.data = options.data
// Accumulate insert events per element
acc.inserts = []
if (options.dom)
acc.types = []
acc.tags = {}
// Always ignore oj and css tags
_extend(options.ignore, {oj:1, css:1})
// Recursive compile to accumulator
_compileAny(ojml, acc)
// Flatten CSS
if (acc.css != null)
cssMap = _flattenCSSMap(acc.css)
// Generate css if necessary
if (options.css)
css = _cssFromPluginObject(cssMap, {minify: options.minify, tags: 0})
// Output cssMap if necessary
if (!options.cssMap)
cssMap = undefined
// Generate HTML if necessary
if (options.html)
html = acc.html.join('')
// Generate dom if necessary
if (options.dom){
// Remove the <oj> wrapping from the dom element
dom = acc.dom.childNodes
// Cleanup inconsistencies of childNodes
if (dom.length != null){
// Make dom a real array
dom = _toArray(dom)
// Filter out anything that isn't a dom element
dom = dom.filter(function(v){return oj.isDOM(v)})
}
// Ensure dom is null if empty
if (dom.length === 0)
dom = null
// Single elements are not returned as a list
else if (dom.length === 1)
// Reasoning: The common cases don't have multiple elements
// <html>,<body>, etc and this is abstracted for you anyway
// with jQuery plugins
dom = dom[0]
}
return {
html: html,
dom: dom,
css: css,
cssMap: cssMap,
types: acc.types,
tags: acc.tags,
inserts: acc.inserts
}
}
// _styleFromObject: Convert object to style string
function _styleFromObject(obj, options){
options = _extend({
inline: true,
indent: ''
}, options)
// Trailing semi should only exist on when we aren't indenting
options.semi = !options.inline
var out = "",
// Sort keys to create consistent output
keys = _keys(obj).sort(),
// Support indention and inlining
indent = options.indent != null ? options.indent : '',
newline = options.inline ? '' : '\n',
ix, k, kFancy, semi
for (ix = 0; ix < keys.length; ix++){
kFancy = keys[ix]
// Add semi if it is not inline or it is not the last key
semi = options.semi || ix !== keys.length - 1 ? ";" : ''
// Allow keys to be camal case
k = _dasherize(kFancy)
// Collect css result for this key
out += "" + indent + k + ":" + obj[kFancy] + semi + newline
}
return out
}
// _attributesFromObject: Convert object to attribute string with no special conversions
function _attributesFromObject(obj){
if (!oj.isPlainObject(obj))
return obj
// Pass through non objects
var k, v, ix,
out = '',
space = '',
// Serialize attributes in order for consistent output
attrs = _keys(obj).sort()
for (ix = 0; ix < attrs.length; ix++){
k = attrs[ix]
v = obj[k]
// Boolean attributes have no value
if (v === true)
out += "" + space + k
// Other attributes have a value
else
out += "" + space + k + "=\"" + v + "\""
space = ' '
}
return out
}
// _flattenCSSMap: Take an OJ cssMap and flatten it into the form
// `'plugin' -> '@media query' -> 'selector' ->'rulesMap'`
//
// This method vastly simplifies `_cssFromPluginObject`
// Nested, media, and comma definitions are resolved and merged
function _flattenCSSMap(cssMap){
var flatMap = {}, plugin, cssMap_
for (plugin in cssMap){
cssMap_ = cssMap[plugin]
_flattenCSSMap_(cssMap_, flatMap, [''], [''], plugin)
}
return flatMap
}
// Recursive helper with accumulators (it outputs flatMapAcc)
function _flattenCSSMap_(cssMap, flatMapAcc, selectorsAcc, mediasAcc, plugin){
// Built in media helpers
var acc, cur, inner, isMedia, mediaJoined, mediasNext, next, outer, parts, rules, selector, selectorJoined, selectorsNext, o, i,
medias = {
'widescreen': 'only screen and (min-width: 1200px)',
'monitor': '',
'tablet': 'only screen and (min-width: 768px) and (max-width: 959px)',
'phone': 'only screen and (max-width: 767px)'
}
for (selector in cssMap){
rules = cssMap[selector]
// Base Case: Record our selector when `rules` is a value
if (typeof rules !== 'object'){
// Join selectors and media accumulators with commas
selectorJoined = selectorsAcc.sort().join(',')
mediaJoined = mediasAcc.sort().join(',')
// Prepend @media as that was removed previously when spliting into parts
if (mediaJoined !== '')
mediaJoined = "@media " + mediaJoined
// Record the rule deeply in `flatMapAcc`
_setObject(flatMapAcc, plugin, mediaJoined, selectorJoined, selector, rules)
// Recursive Case: Recurse on `rules` when it is an object
} else {
// (r1) Media Query found: Generate the next media queries
if (selector.indexOf('@media') === 0){
isMedia = true
mediasNext = next = []
selectorsNext = selectorsAcc
selector = (selector.slice('@media'.length)).trim()
acc = mediasAcc
// (r2) Selector found: Generate the next selectors
} else {
isMedia = false
selectorsNext = next = []
mediasNext = mediasAcc
acc = selectorsAcc
}
// Media queries and Selectors can be comma seperated
parts = _splitAndTrim(selector, ',')
// Media queries have convience substitutions like 'phone', 'tablet'
if (isMedia){
parts = parts.map(function(v){
return _d(medias[v], v)
})
}
// Determine the next selectors or media queries
for (o = 0; o < acc.length; o++){
outer = acc[o]
for (i = 0; i < parts.length; i++){
inner = parts[i]
// When `&` is not present just insert in front with the correct join operator
cur = inner
if ((inner.indexOf('&')) === -1 && outer !== '')
cur = (isMedia ? '& and ' : '& ') + cur
next.push(cur.replace(/&/g, outer))
}
}
// Recurse through objects after calculating the next selectors
_flattenCSSMap_(
rules, flatMapAcc, selectorsNext, mediasNext, plugin
)
}
}
}
// _styleClassFromPlugin: Abstract plugin <style> naming
function _styleClassFromPlugin(plugin){return "" + plugin + "-style"}
// _styleTagFromMediaObject: Abstract creating <style> tag
oj._styleTagFromMediaObject = function(plugin, mediaMap, options){
var newline = (options != null ? options.minify : void 0) ? '' : '\n',
css = _cssFromMediaObject(mediaMap, options)
return "<style class=\"" + (_styleClassFromPlugin(plugin)) + "\">" + newline + css + "</style>"
}
// _cssFromMediaObject: Convert css from a flattened mediaMap rule object.
// The rule object is of the form:
// mediaQuery => selector => rulesObject
function _cssFromMediaObject(mediaMap, options){
options = _d(options, {})
var indent, indentRule, media, rules, selector, selectorMap, space, styles,
minify = options.minify != null ? options.minify : 0,
tags = options.tags != null ? options.tags : 0,
// Deterine what output characters are needed
newline = minify ? '' : '\n',
space = minify ? '' : ' ',
inline = minify,
css = ''
// Build css for media => selector => rules
for (media in mediaMap){
selectorMap = mediaMap[media]
// Serialize media query
if (media){
media = media.replace(/,/g, "," + space)
css += "" + media + space + "{" + newline
}
for (selector in selectorMap){
styles = selectorMap[selector]
indent = (!minify) && media ? '\t' : ''
// Serialize selector
selector = selector.replace(/,/g, "," + newline)
css += "" + indent + selector + space + "{" + newline
// Serialize style rules
indentRule = !minify ? indent + '\t' : indent
rules = _styleFromObject(styles, {
inline: inline,
indent: indentRule
})
css += rules + indent + '}' + newline
}
// End media query
if (media !== '')
css += '}' + newline
}
try {
css = oj._minifyCSS(css, options)
} catch (e){
throw new Error("css minification error: " + e.message + "\nCould not minify:\n" + css)
}
return css
}
// _cssFromPluginObject: Convert flattened css selectors and rules to a string
// pluginMaps are of the form:
// pluginName => mediaQuery => selector => rulesObject
// minify:false will output newlines
// tags:true will output the css in `<style>` tags
function _cssFromPluginObject(flatCSSMap, options){
options = _d(options, {})
var mediaMap, plugin,
minify = options.minify != null ? options.minify : 0,
tags = options.tags != null ? options.tags : 0,
// Deterine what output characters are needed
newline = minify ? '' : '\n',
space = minify ? '' : ' ',
inline = minify,
css = ''
for (plugin in flatCSSMap){
mediaMap = flatCSSMap[plugin]
if (tags)
css += "<style class=\"" + plugin + "-style\">" + newline
// Serialize CSS with potential minification
css += _cssFromMediaObject(mediaMap, options)
if (tags)
css += "" + newline + "</style>" + newline
}
return css
}
// _compileDeeper: Recursive helper for compiling that wraps indention
function _compileDeeper(method, ojml, options){
var i = options.indent
options.indent += '\t'
method(ojml, options)
options.indent = i
}
// _compileAny Recursive helper for compiling ojml or any type
function _compileAny(any, options){
// Array
if (oj.isArray(any))
_compileTag(any, options)
// String
else if (oj.isString(any)){
if (options.html != null)
options.html.push(any)
if (any.length > 0 && any[0] === '<'){
var root = doc.createElement('div')
root.innerHTML = any
if (options.dom != null)
options.dom.appendChild(root)
} else {
if (options.dom != null)
options.dom.appendChild(doc.createTextNode(any))
}
// Boolean or Number
} else if (oj.isBoolean(any) || oj.isNumber(any)){
if (options.html != null)
options.html.push("" + any)
if (options.dom != null)
options.dom.appendChild(doc.createTextNode("" + any))
// Function
} else if (oj.isFunction(any)){
// Wrap function call to allow full oj generation within any
var data = options.data || {};
_compileAny(oj(function(){any.call(data, data)}), options);
// Date
} else if (oj.isDate(any)){
if (options.html != null)
options.html.push("" + (any.toLocaleString()))
if (options.dom != null)
options.dom.appendChild(doc.createTextNode("" + (any.toLocaleString())))
// OJ Type or Instance
} else if (oj.isOJ(any)){
if (options.types != null)
options.types.push(any)
if (options.html != null)
options.html.push(any.toHTML(options))
if (options.dom != null)
options.dom.appendChild(any.toDOM(options))
if (options.css != null)
_extend(options.css, any.toCSSMap(options))
}
// Do nothing for: null, undefined, object
}
// _compileTag: Recursive helper for compiling ojml tags
function _compileTag(ojml, options){
// Empty list compiles to undefined
if (ojml.length === 0) return
// The first part of ojml is the tag
var tag = ojml[0],
tagType = typeof tag,
u = oj.unionArguments(ojml.slice(1)),