-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
7999 lines (7743 loc) · 303 KB
/
main.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
/*!
Sqimitive.js - a JavaScript primitive
https://squizzle.me/js/sqimitive | Public domain/Unlicense
*/
;(function (factory) {
var deps = 'nodash?main:_'
var me = 'Sqimitive'
// --- Universal Module (squizzle.me) - CommonJS - AMD - window --- IE9+ ---
if (typeof exports != 'undefined' && !exports.nodeType) {
// CommonJS/Node.js.
deps = (deps.replace(/\?[^:]*/g, '').match(/\S+(?=:)/g) || []).map(require)
if (typeof module != 'undefined' && module.exports) {
module.exports = factory.apply(this, deps)
} else {
exports = factory.apply(this, deps)
}
} else if (typeof define == 'function' && define.amd) {
// AMD/Require.js.
define(deps.replace(/\?/g, '/').match(/\S+(?=:)/g) || [], factory)
} else {
// In-browser. self = window or web worker scope.
var root = typeof self == 'object' ? self
: typeof global == 'object' ? global
: (this || {})
var by = function (obj, path) {
path = path.split('.')
while (obj && path.length) { obj = obj[path.shift()] }
return obj
}
// No lookbehind in IE.
deps = (deps.match(/:\S+/g) || []).map(function (dep) {
var res = by(root, dep = dep.substr(1))
if (!res) { throw me + ': missing dependency: ' + dep }
return res
})
me = me.split(/\.([^.]+)$/)
if (me.length > 1) { root = by(root, me.shift()) }
root[me[0]] = factory.apply(this, deps)
}
}).call(this, function (_) {
"use strict";
var ap = Array.prototype
// Subclass extension method, taken from Backbone.
//
// protoProps - only 'constructor' (if present) is used. Assign
// instance/static fields manually later (note that static fields are not
// inherited with prototype, so you need to copy them from parent explicitly).
function extend(name, parent, protoProps) {
var child
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor
} else {
// It seems at least Chrome always shows the original function's value
// even with defineProperty() on `'name. It'd be possible to create a
// function without eval() or Function() but only in ES6:
// child = {[name]: function ...}[name]
// But passing name is still useful in other cases (like util.inspect()).
child = function Sqimitive() { return parent.apply(this, arguments) }
}
var Surrogate = function () { this.constructor = child }
Surrogate.prototype = parent.prototype
child.prototype = new Surrogate
child.__super__ = parent.prototype
return child
}
//! +cl=Sqimitive
// Root object for framework's classes (`#Base, `#jQuery, etc.) with several
// constants.
var Sqimitive = {
// Version of the core Sqimitive library in use.
version: '1.3',
// Reference to the utility library in use.
//
// Particularly useful with modular frameworks like npm and Require.js so
// that it's possible to access `'_ by requiring Sqimitive alone).
//
//= NoDash `@no@`@`, Underscore `@un:`@`, LoDash
_: _,
}
/***
Sqimitive.Core - Basic Event/Inheritance
***/
//! +cl=Sqimitive.Core
//
// Implements inheritance and event system without any other Sqimitive
// (`#Base) functionality.
//
// In a typical scenario you don't need to use `#Core directly - use
// `[Sqimitive.Base`] instead.
//
// In special cases, since `'Core lacks any specialized functionality it can
// be used as a base class for your classes that need better inheritance
// and/or events (like a more elaborate alternative to
// `@https://github.com/primus/eventemitter3`@)...
//[
// var MyEventAwareClass = Sqimitive.Core.extend({
// doFoo: function () {
// this.fire('beforeFoo', ['arg', 'arg'])
// // ...
// this.fire('afterFoo', ['...'])
// }
// })
//
// // Now clients can subscribe to its events:
// myEventAwareObject.on('beforeFoo', function () {
// alert('Boo!')
// })
//
// // ...
//
// myEventAwareObject.doFoo() //=> Boo!
//]
//
// ...Or as an instance object held in an internal property if you want to
// avoid exposing any Sqimitive functionality at all:
//[
// var MyEventAwareClass = function () {
// var _events = new Sqimitive.Core
//
// this.on = function() { _events.on.apply(_events, arguments) }
// this.off = function() { _events.off.apply(_events, arguments) }
// this.fire = function() { _events.fire.apply(_events, arguments) }
//
// // Just like in the above example:
// this.doFoo = function () { ... }
// }
//
// myEventAwareObject.on('beforeFoo', ...)
// myEventAwareObject.doFoo()
//]
//! +fn=constructor
// Assigns new unique `#_cid (a string: `'p + unique positive number) and
// clones all instance properties of self that are not listed in
// `#_shareProps. Cloning puts a stop to accidental static sharing of
// properties among all instances of a class where those properties are
// defined.
var Core = Sqimitive.Core = function Sqimitive_Core() {
// Stores the stack trace at the time this instance was `#constructor'ed, if
// `#::trace was on.
//
//#-trc
Core.trace && (this.trace = (new Error).stack)
// To clone newly created instance's properties we need their list.
// Obtaining it is slow (see the comment in _copyProps) and we can't
// pre-generate it in extend() because the declaration is still being
// modified after it returns, e.g. by mixIn() or changing _shareProps:
// var MySqim = Sqimitive.extend({...})
// MySqim._shareProps.push(...)
// // Later: new MySqim(...)
// Thus we'd either have to explicitly call some kind of
// "refreshCopyProps()" after complete declaration or do that in the
// constructor (assuming the declaration no longer changes after it's
// called). The latter is more convenient and not much slower (it's done
// only once per class).
this.constructor._copyProps.call(this, this)
this._cid = 'p' + Core.unique('p')
this._eventsByCx = new Map
}
//! +ig
// Default value for Core._copyProps.
function initCopyProps() {
var o = this.constructor.deepCloner()
o.func = []
for (var prop in this) {
if (this._mustClone(prop)) {
o.func.push('\nthis[' + JSON.stringify(prop) + ']=')
this.constructor.deepCloner(this[prop], o)
}
}
;(this.constructor._copyProps = o.compile())
.call(this, this)
}
// Can be used as Core._copyProps to benchmark object construction.
//
// According to my tests using console.time/End(), deepCloner() is 3.5 times
// faster than run-time deepClone() and close to no cloning at all:
//* no property copying is 100% (200ms over 100k iterations)
//* initCopyProps() - copying with deepCloner() is 135% (270ms)
//* deepCopyProps() - allKeys() plus deepClone() is 1175% (2350ms)
//* deepCopyProps() with cached allKeys()/filter() is 480% (960ms)
function deepCopyProps() {
var copy = _.allKeys(this).filter(this._mustClone, this)
for (var i = 0; i < copy.length; i++) {
this[copy[i]] = Core.deepClone(this[copy[i]])
}
}
//! +clst
// Static fields of Sqimitive.Core.
_.assign(Core, {
// Enables tracing of certain events to aid in debugging. Can be changed on
// run-time.
//
//#trc
// Sometimes you find yourself wondering why a hook was called or who caused
// a property to be updated. Given that hooks often point to generic
// functions or that `'_opt changes are `#batch()'ed, finding initiators can
// be a tricky business.
//
// Effects of `#::trace:
//* Every sqimitive stores `#constructor()-time stack trace in `#.trace
//* Last bunch of `#fire()'d event hooks is recorded under `#lastFired (in
// form of their `'eobj, cloned, with `'self set to call context)
//* Objects of `'_events (`'eobj) hold stack trace of their registration
// (`#fuse()) under `'trace
//* `#batch()'ed events receive new `'trace field in `'options, along with
// `'batchID and others
//* Various wrapper functions (`#picker(), `#firer(), `#once(), etc.) store
// their arguments under `'trace
//
// All added properties are meant for inspection in debugger.
//
//?`[
// var sq1 = new Sqimitive.Core
// alert(sq1.trace) //=> undefined
// Sqimitive.Core.trace = true
// var sq2 = new Sqimitive.Core
// alert(sq2.trace) //=> 'Error\n at ...'
// `]
//
// Note: setting `'trace on subclasses of `'Core will have no effect.
//
// By default, Chrome limits trace depth to 10 which usually prevents you
// from seeing actually important frames. One way to increase it is:
//[
// Error.stackTraceLimit = 100
//]
// Other ways: `@https://stackoverflow.com/questions/9931444`@.
trace: false,
// Holds recently `#fire()'d event hooks (cloned `'eobj-s with `'self set to
// call context) if `#::trace is on.
//
//#-trc
lastFired: [],
//! +ig
// For `#unique().
//= object {str prefix: int last taken}
_unique: {},
//#+tag_Extension
//* `@Core::_mergeProps`@
//
//#-setOnDeclViaPush
//
// Specifies which instance properties are to be merged rather than
// overwritten when redefined in a subclass.
//
//= array of string `- property names
//
// Properties must be of these types:
//> array `- Merged using `[Array.concat(baseClass[prop],
// childClass[prop])`]. Subclass' values are added after parents' values:
// `[['a', 'b'] + ['c'] = ['a', 'b', 'c']`].
//> object `- Merged using `[_.extend(baseClass[prop], childClass[prop])`].
// Keys defined in parents are kept unless also defined in a subclass:
// `[{a: 1, b: 2} + {a: 3, c: 4} = {a: 3, b: 2, c: 4}`].
//
//? `[
// var MyParent = Sqimitive.Base.extend({
// _objectProperty: {key1: 'value1', key2: 'value2'},
// _arrayProperty: ['item1', 'item2'],
// })
//
// MyParent._mergeProps.push('_objectProperty', '_arrayProperty')
//
// var MyChild = MyParent.extend({
// _objectProperty: {key2: 'CHILD1', key3: 'CHILD2'},
// _arrayProperty: ['item3', 'item4'],
// })
//
// // MyChild._objectProperty is now
// // {key1: 'value1', key2: 'CHILD1', key3: 'CHILD2'}
//
// // MyChild._arrayProperty is now ['item1', 'item2', 'item3', 'item4']
//]
//
//#mergePropsExtend
// ` `*Warning:`* when passing `#_mergeProps or `#_shareProps inside
// `'staticProps (second argument of `#extend()) all inherited items will be
// removed. The correct way to add your properties while keeping those in
// the base classes is this:
//[
// var MySqimitive = Sqimitive.Base.extend({
// // Define instance fields...
// }, {
// // Define static fields if you need, else don't pass this parameter.
// })
//
// // extend() has copied the inherited _mergeProps list which we can now
// // append to or modify using regular Array functions.
// MySqimitive._mergeProps.push('prop1', 'prop2', ...)
// // Same with _shareProps.
// MySqimitive._shareProps.push('prop1', 'prop2', ...)
//]
//
// These are `*wrong`* ways to append to these properties:
//[
// var MySqimitive = Sqimitive.Base.extend({
// // WRONG: _mergeProps is static so it won't be read from here.
// _mergeProps: ['prop'],
// }, {
// // WRONG: technically fine but will entirely replace base class'
// // merge list.
// _mergeProps: ['prop'],
// })
//
// // WRONG: works but once again will replace all the inherited items.
// MySqimitive._mergeProps = ['prop']
//
// // CORRECT:
// MySqimitive._mergeProps.push('prop')
//]
//
//#
//
// Other notes:
//* `#extend() always clones `#_mergeProps and `#_shareProps.
//* By default, `#Base class adds `@Base._opt`@, `@Base.elEvents`@ and
// `#_respToOpt to this list.
//* See instance `#.mixIn() for the implementation.
//* Removing a parent-of-parent's property from `'_mergeProps doesn't
// "un-merge" it since merging happens in `#extend() (`#mixIn()) so after
// `#extend() the new class already has merged properties of all of its
// ancestors. However, removal does affect new subclasses: `[
// var ClassA = Sqimitive.Base.extend({array: ['in A']})
// ClassA._mergeProps.push('array')
// // (new ClassA).array is ['in A']
//
// var ClassB = ClassA.extend({array: ['in B']})
// // (new ClassB).array is ['in A', 'in B']
//
// var ClassC = ClassB.extend({array: ['in C']})
// ClassC._mergeProps = []
// // (new ClassC).array is ['in A', 'in B', 'in C']
//
// var ClassD = ClassC.extend({array: ['in D']})
// // (new ClassD).array is ['in D'] - not merged!
// `]
//
//# Complex inherited value modification
// `'_mergeProps doesn't allow deleting members or otherwise changing the
// value. However, in some contexts `'null or `'undefined does the job for
// objects (in contrast with `'delete such properties still appear when
// using `[for..in`], etc.):
//[
// var MyParent = Sqimitive.Base.extend({
// _objectProperty: {key1: 'value1', key2: 'value2'},
// })
//
// MyParent._mergeProps.push('_objectProperty')
//
// var MyChild = MyParent.extend({
// _objectProperty: {key1: null},
// })
//
// // MyChild._objectProperty is now {key1: null, key2: 'value2'}
//
// for (var key in new MyChild) { alert(key) }
// //=> key1
// //=> key2
//]
//
// Use `@Base.init()`@ or `#postInit() to modify inherited values in other
// ways:
//[
// var MyParent = Sqimitive.Base.extend({
// _objectProperty: {key1: 'value1', key2: 'value2'},
// })
//
// var MyChild = MyParent.extend({
// events: {
// init: function () {
// // MyParent's _objectProperty is unaffected, see _shareProps.
// delete this._objectProperty.key1
// this._objectProperty.key2 += 'foo'
// },
// },
// })
//
// // MyChild._objectProperty is now {key2: 'value2foo'}
//
// for (var key in new MyChild) { alert(key) }
// //=> key2
//]
//
//#-inBB
// In Backbone, when you extend a parent class with a property that it
// already has you end up with a completely new property. This doesn't
// always make sense - for example, if a class has its own
// `@bb:View-events`@ then what you really need is merge its own (base)
// events with the events of new subclass. Same thing with
// `@bb:Model-attributes`@ and `@bb:Model-defaults`@, `@bb:Router-routes`@
// and others. Example (`@http://jsfiddle.net/Proger/u2n3e6ex/`@):
//[
// var MyView = Backbone.View.extend({
// events: {
// 'click .me': function () { alert('You clicked it!') },
// },
// })
//
// var MyOtherView = MyView.extend({
// // This object entirely replaces MyView's event map.
// events: {
// 'keypress .me': function () {
// alert('Oh noes, we broke the button :(')
// },
// },
// })
//]
_mergeProps: [],
//#+tag_Extension
//* `@Core::_shareProps`@
//
//#-setOnDeclViaPush
//
// Specifies which instance properties are not to be cloned upon
// construction. They will be shared by all instances of a class (where the
// property was defined, i.e. where given to `#extend()).
//
//= array of string `- property names
//
// Unlisted instance properties are cloned (using `#deepClone()) upon new
// object instantiation (in `#constructor). If using a complex object
// (`'Date, `'Node, etc. - not just `[{}`]) then assign it in
// `@Base.init()`@ or `#postInit(). If using an instance property as if it
// were static, either list it in `#_shareProps or move to `'staticProps
// (`#extend()) and access as `[this.constructor.foo`] (yes, JavaScript
// makes it pretty inconvenient).
//
//? One particular case when the default cloning causes problem is when you
// are assigning "classes" to properties - recursive copying of such a
// value not just breaks it (`[MyClass === myObj._model`] no longer works)
// but is also very heavy.
//
// Either use `#_shareProps...
// `[
// var MyView = Sqimitive.Base.extend({
// _model: MyApp.MyModel,
// })
//
// // _shareProps is a static property.
// MyView._shareProps.push('_model')
// `]
//
// ...Or assign the value after instantiation, which is less declarative:
// `[
// var MyView = Sqimitive.Base.extend({
// _model: null, // MyApp.MyModel¹
//
// events: {
// init: function () {
// this._model = MyApp.MyModel
// },
// },
// })
// `]
// `¹ It's customary in Sqimitive to leave a comment with the type's
// name next to such property.
//
//#-mergePropsExtend
//
// Other notes:
//* By default, `#Base class adds `#_childClass to this list.
//* See instance `#.mixIn() for the implementation.
//
//#-inBB
// In Backbone, values of all properties inherited by a subclass are shared
// among all instances of the base class where they are defined. Just like
// in Python, if you have `[...extend( {array: []} )`] then doing
// `[this.array.push(123)`] will affect all instances where `'array wasn't
// overwritten with a new object. This poses a typical problem in day-to-day
// development.
//
// Example (`@http://jsfiddle.net/Proger/vwqk67h8/`@):
//[
// var MyView = Backbone.View.extend({foo: {}})
// var x = new MyView
// var y = new MyView
// x.foo.bar = 123
// alert(y.foo.bar)
//]
//
// Can you guess the alert message? It's `'123!
_shareProps: [],
//! +ig
// An internal field - list of prototype (instance) properties being cloned
// in the constructor. Running `[for..in`] each time is extremely expensives
// (10X). This is maintained automatically by `#extend()/`#mixIn(). Change
// this to use custom cloning logic, for example (slow!):
//[
// _copyProps: function () {
// var copy = _.allKeys(this).filter(this._mustClone, this)
// for (var i = 0; i < copy.length; i++) {
// this[copy[i]] = Sqimitive.Core.deepClone(this[copy[i]])
// }
// },
//]
// ...Or use `#_shareProps or override `'_mustClone() to return `'false and
// do your cloning in `#init() or elsewhere.
_copyProps: null,
//! `, +fna=function ( [name,] [protoProps [, staticProps]] )
//
//#+tag_Extension
//* `@Core::extend()`@
//#
//
// Creates a subclass of the class on which `#extend() is called.
//
//> name string `- Optional convenience string displayed in the debugger (as
// the function/constructor - "class" name). Defaults to name of base
// class.
// `[
// var MyClass = Sqimitive.Base.extend('My.Class')
// MyClass.name //=> 'My.Class'
// ;(new MyClass).constructor.name //=> 'My.Class'
// `]
//> protoProps object `- New instance fields (properties or methods). May
// contain special non-field keys (see `#mixIn()).
//> staticProps object `- New static fields.
//
// `'protoProps fields become accessible as `[(new MyClass).instanceSomething()`]
// while `'staticProps - as `[MyClass.staticSomething()`].
//
// Any argument may be `'null or omitted. If all are such then you get a
// copy of the base class (and yet `[BaseClass !== SubClass`]).
//
// Other notes:
//* In Sqimitive, subclassing is a special case of mix-ins (multi-parent
// inheritance in OOP). `#extend() simply creates a new "blank" class and
// mixes the base class into it. Therefore most of the job is performed by
// `#mixIn() (which also allows changing particular object's prototype
// after class construction on run-time).
//* `#extend() creates a new prototype, sets its parent, assigns `'__super__
// (a static property pointing to the base class), calls `#::mixIn() and
// resolves `#_childClass if it's a string (since it can't be done before
// the prototype is created).
//#-mixInDoes
//* If `'staticProps argument is given, it replaces
// `[protoProps.staticProps`]. As expected, this key (or argument) is
// applied by `#mixIn() after applying `'staticProps of `'mixIns.
// `[
// var MixIn = {
// staticProps: {sp: 'm'}
// }
// var Class = Sqimitive.Base.extend({
// mixIns: [MixIn]
// }, {
// sp: 'c'
// })
// // Equivalent:
// var Class = Sqimitive.Base.extend({
// staticProps: {sp: 'c'},
// mixIns: [MixIn]
// })
// // Above, Class.sp is 'c'. However, if mixing-in later, it'd be 'm':
// Class.mixIn(MixIn)
// `]
//
//? In case of duplicated field names, subclass' fields take precedence and
// overwrite fields in the parent class except for fields listed in
// `#_mergeProps: `[
// // First we extend a base Sqimitive class with our own properties.
// var MyBase = Sqimitive.jQuery.extend({
// _somethingBase: 123,
// _somethingNew: 'foo',
//
// el: {tag: 'nav', id: 'nav'},
//
// _opt: {
// baseOption: 'boo',
// baseMore: 'moo',
// },
// })
//
// // Now if we extend MyBase...
// var MySubclass = MyBase.extend({
// _somethingSub: 'bar',
// _somethingBase: 987,
//
// el: {tag: 'footer'},
//
// _opt: {
// subOption: 'sub',
// baseMore: 'bus',
// },
// })
//
// /*
// ...we get the following class, after merging with its parent:
//
// MySubclass = {
// // Got new value - overridden in MySubclass.
// _somethingBase: 987,
// // Retained old value from MyBase.
// _somethingNew: 'foo',
// // New property - introduced in MySubclass.
// _somethingSub: 'bar',
//
// // Got new value in MySubclass.
// el: {tag: 'footer'},
//
// // Unlike el, _opt is listed in _mergeProps by default so its
// // keys are merged and not entirely replaced.
// _opt: {
// // Retained.
// baseOption: 'boo',
// // Introduced.
// subOption: 'sub',
// // Overridden.
// baseMore: 'bus',
// },
// }
// */
// `]
extend: function (name, protoProps, staticProps) {
// this = base class.
// Only works in strict mode which disconnects parameter vars from members
// of arguments.
name = typeof arguments[0] == 'string' ? ap.shift.call(arguments) : this.name
var child = extend(name, this, arguments[0])
//! +ig
// Since base class has its own __super__, make sure child's (set up by
// extend() above) isn't overwritten.
_.assign(child, this, {__super__: child.__super__})
// Ensure changing these in a subclass doesn't affect the parent:
// var Sub = Sqimitive.Base.extend()
// Sqimitive.Base._mergeProps.length //=> 3
// Sub._mergeProps.push('new')
// Sqimitive.Base._mergeProps.length //=> 4
child._mergeProps = (child._mergeProps || this._mergeProps).concat()
child._shareProps = (child._shareProps || this._shareProps).concat()
//! +ig
// Function.prototype.length confuses "isArrayLike" functions.
// Just `[delete Core.length`] doesn't work.
Object.defineProperty(child, 'length', {value: 'NotAnArray'})
name && Object.defineProperty(child, 'name', {value: name})
if (arguments[1]) {
(arguments[0] = arguments[0] || {}).staticProps = arguments[1]
}
arguments[0] && child.mixIn(arguments[0])
// _childClass is technically part of Base, not Core but doing it here for
// simplicity.
//
// String class path is relative to the base class; instead of searching
// all prototypes to find where this property was introduced (without this
// all children will reference to them as the base class), we "fixate" it
// when declaring the class. Done here, not in mixIn(), to avoid questions
// like "is the string, if given by a mix-in, relative to the mix-in or
// the target class?".
if (typeof child.prototype._childClass == 'string') {
child.prototype._childClass = [child, child.prototype._childClass]
}
return child
},
//#+tag_Extension
//* `@Core::mixIn()`@
//#
//
// Extends this class with a behaviour of another "class" (a "mix-in").
//
// The instance `#.mixIn() works the same way but allows extending a
// particular object instance on run-time. Its description follows.
//
//#-mixInDesc
mixIn: function (newClass, options) {
return this.prototype.mixIn(newClass, options)
},
// Simply an empty function that returns `'undefined.
//
// ` `#stub() is similar to `@un:noop`@() in Underscore and LoDash.
//
//? Use `#stub() or `'undefined in places where you don't want to supply any
// implementation - this lets Sqimitive optimize things when it knows that
// a function (acting as a method or an event handler) can be simply
// discarded or overridden.
// `[
// var MySqim = Sqimitive.Base.extend({
// success: Sqimitive.Base.stub,
// error: Sqimitive.Base.stub,
// // Equivalent:
// success: undefined,
// error: undefined,
// })
//
// var my = new MySqim
// // Replaces the empty handler entirely.
// my.on('success', function () { alert('Good!') })
// //=> my._events.success.length is 1
// `]
//
// Otherwise, if you are not a performance purist you can just use
// `[function () {}`] or `[new Function`]:
//[
// var MySqim = Sqimitive.Base.extend({
// success: function () { },
// })
//
// var my = new MySqim
// my.on('success', function () { alert('Good!') })
// //=> my._events.success.length is 2
//]
//
// Special values `#stub() and `'undefined are only recognized in
// properties, not `#events:
//[
// var MySqim = Sqimitive.Base.extend({
// events: {
// // Registers new hook that is called but has no effect on anything.
// success: Sqimitive.Base.stub,
// // Itself does nothing but previously registered hooks are removed.
// '=success': Sqimitive.Base.stub,
// // Simply wrong, undefined is not callable.
// success: undefined,
// },
// })
//
// var my = new MySqim
// my.on('success', function () { alert('Good!') })
// //=> my._events.success.length is 2 (existing stub handler kept)
// my.on('success', Sqimitive.Base.stub)
// //=> my._events.success.length is 3 (new stub handler added)
// my.on('success', undefined)
// // simply wrong, undefined is not callable
//]
stub: function Sqimitive_stub() { },
//! `, +fna=function ( [prefix] )
//
//#+tag_Utilities
//* `@Core::unique()`@
//#
//
// Returns a sequential number starting from `[1`] that is guaranteed to be
// unique among all calls to `#unique() with the same `'prefix during this
// session (page load, etc.).
//
// ` `#_cid receives one such value in `#constructor.
//
// ` `#unique() is similar to `@un:uniqueId`@() in Underscore and LoDash.
//
//?`[
// unique('my') //=> 3
// unique() //=> 87
// unique('my') //=> 4
// unique('some') //=> 21
// unique('my') //=> 5
// `]
//
// Well-known `'prefix'es:
//> p `- used in `#_cid (sqimitive's ID)
//> e `- used in `#on() (event handler's ID)
//> o `- used in `#set() (operation's ID)
//> b `- used in `#batch() (batch's ID - group of operations)
//> bg `- used in `#batchGuard() (guard's instance)
unique: function (prefix) {
return this._unique[prefix] = 1 + (this._unique[prefix] || 0)
},
//! `, +fna=function ( prop [, args] )
//
//#+tag_Utilities
//* `@Core::picker()`@
//#
//
// Returns a function accepting an object and returning value of the
// property at `'prop, accessible via that object.
//
//> prop string dotted property path`, array already split path, empty array
// to return the `'a'rgument itself (or result of calling it)`, other
// stringified and split
//> args array`, mixed = `[[[args]]`]`, omitted = `'[] `- list of argument
// lists for `'function-type properties
//
// The returned function (`'f) expects one argument (`'a). When called, `'f
// walks `'prop, treating each item as a key ("own" or not) in the "current"
// object (which starts as `'a) and returns the last "current" object.
//
// If there is a `'function at that key (or `'a itself is one) and its
// `'name is not a string starting with a capital letter (i.e. not a class
// constructor), `'f calls it in previous "current" object's context
// (`'undefined if calling `'a) with the next unused member of `'args (`'[]
// if none) and stores the result as the new "current" object.
//
// `'f returns `'undefined when trying to descend into `'undefined/`'null
// "current" value.
//
// ` `#picker() is similar to `@un:result`@() in Underscore and LoDash.
//
//? `[
// var obj = {
// one: 1,
// two: function () { return 2 },
// some: function (a, b) { return a + '--' + b },
// }
//
// var picker = Sqimitive.Base.picker
// picker('one')(obj) //=> 1
// picker('two')(obj) //=> 2
// picker('some', [['A', 'B']])(obj) //=> 'A--B'
//
// var collection = ['foo', null, ['bar'], obj]
// _.map(collection, picker('one'))
// //=> [undefined, undefined, undefined, 1]
//
// 'toString' in obj //=> true
// _.has(obj, 'toString') //=> false
// picker('toString')(obj) //=> '[object Object]'
//
// picker([])(obj) //=> obj
// picker([])('foo') //=> 'foo'
// picker([])(() => 123) //=> 123
// // typeof Date is 'function' but Date.name[0] is upper-case.
// picker([])(Date) //=> Date
// picker(0)('foo') //=> 'f'
// picker('0.0.0')('foo') //=> 'f'
// picker([])(null) //=> null
// picker(0)(null) //=> undefined
// `]
//
//? Usually `#picker()'s result is given to some filtering function
// (`#util). Example from `#chld: `[
// getIncomplete: function () {
// return this.reject(MyToDoList.picker('get', 'isCompleted'))
// },
// `]
//
//? `'args is a list of multiple argument lists, not a single argument list.
// This enables `#picker() to call methods of objects returned by other
// methods. However, `'prop often references just one property which is
// either not a method or a method taking nothing (so you can omit `'args),
// or a method taking one scalar argument (so you can pass that value
// directly):
// `[
// picker('remove')(sqim) //= sqim.remove()
// picker('get')(sqim) //= sqim.get()
// picker('get', 'opt')(sqim) //= sqim.get('opt')
//
// picker('nested.get', [['ch1'], ['opt']])(sqim)
// // Same as:
// sqim.nested('ch1').get('opt')
//
// picker('nested.get', [['ch1']])(sqim)
// // Same as:
// picker('nested.get', 'ch1')(sqim)
// // Same as:
// sqim.nested('ch1').get()
//
// // WRONG, will fail:
// picker('nested.get', ['ch1', 'opt'])(sqim)
// picker('nested.get', ['ch1'])(sqim)
// `]
picker: function (prop, args) {
_.isArray(prop) || (prop = (prop + '').split('.'))
if (arguments.length > 1 && !_.isArray(args)) {
args = [[args]]
}
function picker_(obj) {
var cx
var ai = 0
function picker_call() {
if (typeof obj == 'function' && !/^[A-Z]/.test(obj.name)) {
obj = obj.apply(cx, args && args[ai++])
}
}
picker_call()
for (var i = 0; i < prop.length; i++) {
if (obj == null) { return }
cx = obj
obj = obj[prop[i]]
picker_call()
}
return obj
}
Core.trace && (picker_.trace = arguments)
return picker_
},
//! `, +fna=function ( func [, obj] )
//
// Expands a function reference `'func of object `'obj (`'this if not given)
// into a real `'Function.
//
// ` `#expandFunc() is used in `#on(), `#events and others to
// short-reference the instance's own methods.
//
// If `'func is a string and contains a dot or a dash (`[.-`]) - returns
// masked (`#masker()) version of this method (`'mask starts with the first
// such character). If it's a string without them - returns a function that
// calls the method named `'func on `'obj (or `'this if omitted). In other
// cases returns `'func as is (if `'obj is omitted) or `[_.bind(func, obj)`]
// (if `'obj is given).
//
//?`[
// var func = Sqimitive.Base.expandFunc('meth')
// // returned function will call this.meth(arguments, ...)
//
// var obj = {meth: function (s) { alert(s) }}
// func.call(obj, 123)
// // alerts 123
//
// var func = Sqimitive.Base.expandFunc('meth-.', obj)
// // this function works in obj context, calling meth with just one
// // argument (2nd it was given) - see masker()
//
// _.each({k1: 1, k2: 2}, func)
// // each() calls func(1, 'k1') and func(2, 'k2')
// // func calls obj.meth('k1') and obj.meth('k2')
// // alerts twice: 'k1' and 'k2'
//
// _.each({k1: 1, k2: 2}, _.bind(func, obj))
// // if we didn't give obj to expandFunc() previous example would
// // fail - func() would be called on window which has no 'meth'
// // method
// `]
expandFunc: function (func, obj) {
if (typeof func == 'string') {
var parts = func.split(/([.-][\d.-]*)$/)
if (parts.length > 1) {
return Core.masker(parts[0], parts[1], obj)
} else {
function expandFunc_() {
var callCx = obj || this
return callCx[func].apply(callCx, arguments)
}
Core.trace && (expandFunc_.trace = arguments)
return expandFunc_
}
} else {
return obj ? _.bind(func, obj) : func
}
},
//! `, +fna=function ( func[, mask[, cx[, args]]] )
//
//#+tag_Utilities
//* `@Core::masker()`@
//#
//
// Returns a version of `'func with arguments reordered according to `'mask.
//
//> mask number to skip that many leading arguments alike to `@no@rest`@()`,
// null/omitted to assume the number `'1 (skip first argument)`, string
// pattern `#maskerPattern
//> func string method name`, function `- called on `'cx
//> cx object`, null/omitted use `'this `- the context for `'func
//> args array `- extra left-side arguments to `'func
//
// ` `#masker() is similar to LoDash's `'rearg().
//
// Masking is a way to work around `#argDanger and avoid writing callback
// function wrappers that only ignore or reorder arguments. It's implicitly
// used in string `#events values since they are passed to `#expandFunc().
//
//#es6this
//? ES6 arrow functions could be useful for this but they are ill-suited for
// use as handlers when `#extend()'ing because of their permanent `'this.
//
// `[
// var MyClass = Sqimitive.Base.extend({
// events: {
// // WRONG: will pass res as s, value as chars and break clean():