/
base.sjs
1483 lines (1317 loc) · 44.2 KB
/
base.sjs
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
/*
* Oni Apollo 'surface/base' module
* Lightweight cross-browser UI toolkit - Core functionality
*
* Part of the Oni Apollo Standard Module Library
* Version: 'unstable'
* http://onilabs.com/apollo
*
* (c) 2012 Oni Labs, http://onilabs.com
*
* This file is licensed under the terms of the MIT License:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
@module surface/base
@summary Lightweight cross-browser UI toolkit - Core functionality (unstable work-in-progress)
@home apollo:surface/base
@hostenv xbrowser
@desc Work-in-progress
*/
var tt = new Date();
waitfor {
var common = require('../common');
}
and {
var coll = require('../collection');
}
and {
var dom = require('../xbrowser/dom');
}
and {
var debug = require('../debug');
}
and {
var func = require('../function');
}
console.log("surface.sjs loading deps: #{(new Date())-tt}");
tt = new Date();
//----------------------------------------------------------------------
// StyleElement: stylesheet conditioned on unique css classes
/*
A coarse CSS parser, parsing into an array BLOCK, which takes elements:
- "decl_str"
- [ "kw_or_selector", BLOCK ]
*/
var blockRE = /\s*((?:[^\"\'\{\}\;\/]|\/[^\*])*)(\"|\'|\/\*|\{|\}|\;)/g;
var dstrRE = /(\"(?:[^\"]|\\\")*\")/g;
var sstrRE = /(\'(?:[^\']|\\\')*\')/g;
var commentRE = /\*\//g;
var wsRE = /\s*$/g;
__js function parseCSSBlocks(src) {
var index = 0;
function block() {
var matches, chunk = '', content = [];
// parse chunk up to next 'operator': " OR ' OR /* OR { OR } OR ;
blockRE.lastIndex = index;
while ((matches = blockRE.exec(src))) {
//console.log(matches);
index = blockRE.lastIndex;
if (matches[1]) chunk += matches[1];
switch (matches[2]) {
case '"':
dstrRE.lastIndex = index-1;
matches = dstrRE.exec(src);
if (!matches) throw new Error('Invalid CSS: Unterminated string');
chunk += matches[1];
index = dstrRE.lastIndex;
break;
case "'":
sstrRE.lastIndex = index-1;
matches = sstrRE.exec(src);
if (!matches) throw new Error('Invalid CSS: Unterminated string');
chunk += matches[1];
index = sstrRE.lastIndex;
break;
case '/*':
commentRE.lastIndex = index;
matches = commentRE.exec(src);
if (!matches) throw new Error('Invalid CSS: Unterminated comment');
// ignore comment
index = commentRE.lastIndex;
break;
case '{':
content.push([chunk, block()]);
if (src.charAt(index-1) != '}') throw new Error('Invalid CSS: Unterminated block');
chunk = '';
break;
case '}':
if (chunk.length) content.push(chunk);
return content;
break;
case ';':
content.push(chunk + ';');
chunk = '';
break;
}
blockRE.lastIndex = index;
}
if (chunk.length) throw new Error('Invalid CSS: Trailing content in block');
return content;
}
var rv = block();
if (index != src.length) {
// allow trailing whitespace:
wsRE.lastIndex = index;
if (wsRE.exec(src) == null)
throw new Error(
"Invalid CSS: Unparsable around '#{src.substr(Math.max(0,index-20), 40).replace(/\n/g,'\\n')}'"
);
}
return rv;
}
/**
@class StyleElement
@summary Object with style information to be applied to a [::UIElement]
*/
var StyleElement = {};
var styleClassCounter = 0;
__js StyleElement.init = function(content, global) {
if (!global) {
var cssClass = this.cssClass = "__oni"+(++styleClassCounter);
// fold cssClass into selectors:
var tt = new Date();
var blocks = parseCSSBlocks(content);
console.log("parse style=#{(new Date())-tt}ms");
function processBlock(b,lvl,cssClass) {
return coll.map(b, function(b) {
if (!Array.isArray(b))
return b; // a decl
else {
if (lvl) {
throw new Error("Invalid CSS: invalid nesting of '#{b[0]}{#{b[1].join(' ')}}'");
}
if (b[0].charAt(0) != '@') {
// fold cssClass into selector
b[0] = coll.map(b[0].split(','), function(s){ return "#{cssClass} #{s}" }).join(',');
return "#{b[0]} { #{processBlock(b[1],lvl+1,cssClass)} }";
}
else if (b[0].indexOf('@global') == 0) {
// apply style globally (i.e. don't fold cssClass into selector)
return processBlock(b[1],lvl,'');
}
else {
// generic '@'-rule (maybe a media query)
return "#{b[0]} { #{processBlock(b[1],lvl,cssClass)} }";
}
}
}).join('\n');
}
tt = new Date();
content = processBlock(blocks, 0, '.'+cssClass);
console.log("process style=#{(new Date())-tt}ms");
}
var elem = this.dompeer = document.createElement('style');
elem.setAttribute('type', 'text/css');
elem.innerHTML = content;
this.refCount = 0;
};
__js StyleElement.use = function() {
if (this.refCount++ == 0)
document.head.appendChild(this.dompeer);
};
__js StyleElement.unuse = function() {
if (--this.refCount == 0)
this.dompeer.parentNode.removeChild(this.dompeer);
};
/**
@function CSS
@summary Create a local [::StyleElement] from CSS style rules
@param [String] CSS style rules
@return {::StyleElement}
@desc
Creates a [::StyleElement] that, when applied to a [::UIElement] `ui`, will be
have its rules only applied to `ui` and descendents of `ui`.
*/
__js var CSS = exports.CSS = function(content) {
var obj = Object.create(StyleElement);
obj.init(content);
return obj;
};
/**
@function GlobalCSS
@summary Create a global [::StyleElement] from CSS style rules
@param [String] CSS style rules
@return {::StyleElement}
@desc
Create a [::StyleElement] that, when applied to an [::UIElement], will have its rules
applied globally to all elements in the webapp.
*/
__js var GlobalCSS = exports.GlobalCSS = function(content) {
var obj = Object.create(StyleElement);
obj.init(content, true);
return obj;
};
//----------------------------------------------------------------------
// DOM Measuring helpers
__js {
// see http://erik.eae.net/archives/2007/07/27/18.54.15/
function getStyle(el, prop) {
if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el, null)[prop];
} else if (el.currentStyle) {
return getPixelValue(el, el.currentStyle[prop]);
} else {
return getPixelValue(el, el.style[prop]);
}
}
var PIXEL = /^\d+(.\d*)+(px)?$/i;
function getPixelValue(element, value) {
if (!value) return 0;
if (PIXEL.test(value)) {
return parseInt(value);
}
var style = element.style.left;
var runtimeStyle = element.runtimeStyle.left;
element.runtimeStyle.left = element.currentStyle.left;
element.style.left = value || 0;
value = element.style.pixelLeft;
element.style.left = style;
element.runtimeStyle.left = runtimeStyle;
return value;
}
}
//----------------------------------------------------------------------
/*
Constrained quantity used for box layouts
{
explicit : explicit value || undefined
flex : flex value || 0
min : minimum constraint || 0
max : maximum constraint || UNCONSTRAINED
val : value calculated by box layout
}
*/
var UNCONSTRAINED = 1e10;
exports.UNCONSTRAINED = UNCONSTRAINED;
// parse the quantity into a [unit, value] array
__js function parseQuantity(q) {
if (q===undefined) return undefined;
var rv;
if (typeof q == "number")
rv = ["px", q];
else {
var val = parseFloat(q);
if (isNaN(val)) val = 1;
if (/\*$/.exec(q)) {
// starred (flex) size
rv = ["*", val];
}
else {
// map everything else to px:
rv = ["px", val];
}
}
// console.log("val="+rv);
return rv;
}
// For entity 'X', parse X, minX, maxX into a 'constrained
// quantity struct'
__js function makeConstrainedQuantity(entity, attribs) {
var cq = {};
var v;
cq.flex=0;
if ((v=parseQuantity(attribs[entity])) !== undefined) {
if (v[0] == "*") {
cq.flex = v[1];
}
else {
// we'll treat everything else as 'px' for now
cq.explicit = v[1];
}
}
cq.min = 0;
if ((v=parseQuantity(attribs['min'+entity])) !== undefined) {
if (v[0] != "*") {
cq.min = v[1];
}
}
cq.max = UNCONSTRAINED;
if ((v=parseQuantity(attribs['max'+entity])) !== undefined) {
if (v[0] != "*") {
cq.max = v[1];
}
}
return cq;
}
//----------------------------------------------------------------------
// UIElement base class
/*
abstract base class for ui elements
{
dompeer: root DOM element
style: ...
}
*/
/**
@class UIElement
@summary Base class for UI elements
@variable UIElement
*/
var UIElement = exports.UIElement = {};
/**
@function UIElement.init
@summary Called by constructor functions to initialize UIElement objects
@param {Object} [attribs] Hash with attributes
@attrib {optional Object} [mechanisms] Hash of functions that will
be spawned when the element has been activated and aborted when
the element is deactivated
(see [::UIElement::activated] & [::UIElement::deactivated]).
See description below for more information.
@attrib {optional ::StyleElement|Array} [style] [::StyleElement]
(or array of elements) to apply to this UIElement.
@attrib {optional String} [content] HTML content for this UIElement.
@desc
### Mechanisms
A mechanism is a function that will be spawned automatically by
[::UIElement::activated] and aborted (if it is still running) by
[::UIElement::deactivated].
A mechanism function has the signature `f(ui, api)`, where `ui` is
the [::UIElement] for which it has been activated, and `api` is an
empty object into which the mechanism can install functions that will
be reflected in [::UIElement::api] under the name of the mechanism. When
the mechanism exits (either on its own or by being aborted), the reflected
api will be removed.
**Example:**
var surface = require('apollo:surface/base');
var dom = require('apollo:xbrowser/dom');
var elem =
surface.Html({
...,
mechanisms : {
commands: function(ui, api) {
api.get = { ||
dom.waitforEvent(ui.dompeer, 'click',
{ |e| e.getAttribute('data-type') == 'command' })
};
hold();
}
}
});
surface.withUI(surface.surface, elem) { ||
while (1) {
// process next click on element with data-type=='command':
var ev = elem.api.commands.get();
// ...
}
}
*/
__js UIElement.init = function(attribs) {
if (attribs.debug) {
this.debugtags = attribs.debug.tags || "";
this.debugid = attribs.debug.id || "DEBUG";
}
else {
this.debugtags = "";
this.debugid = "";
}
this.dompeer = document.createElement('surface-ui');
this.dompeer.setAttribute('style', 'display:block;visibility:hidden');
this.dompeer.ui = this;
this.mechanisms = attribs.mechanisms;
this.style = attribs.style || [];
if (StyleElement.isPrototypeOf(this.style)) this.style = [this.style];
coll.each(this.style, function(s) {
if (s.cssClass) this.dompeer.setAttribute('class', s.cssClass+" "+this.dompeer.getAttribute('class')); }, this);
if (typeof attribs.content !== 'undefined')
this.dompeer.innerHTML = attribs.content;
this.api = {};
};
/**
@variable UIElement.api
@summary API reflected by mechanisms. See [::UIElement::init] for more information.
*/
/**
@function UIElement.debug
@summary Check if debugging is enabled for the given tag
@param {String} [tag] Debugging tag
@return {Boolean}
*/
UIElement.debug = function(tag) { return this.debugtags.indexOf(tag)!=-1; };
/**
@function UIElement.select1
@summary Selects first matching DOM child
@param {String} CSS selector
@return {DOMElement|null}
*/
UIElement.select1 = function(selector) { return this.dompeer.querySelector(selector); };
/**
@function UIElement.select
@summary Select all matching DOM children
@param {String} CSS selector
@return {NodeList}
*/
UIElement.select = function(selector) { return this.dompeer.querySelectorAll(selector); };
/**
@function UIElement.activate
@summary Called when this UIElement is about to be attached (directly or indirectly)
to the global surface. When attaching to a container that is active, this method will
(by design) be called before [::UIElement:attached]
*/
UIElement.activate = function() {
if (this.isActivated) throw new Error("UIElement already activated");
coll.each(this.style, {|s| s.use() });
};
/**
@function UIElement.activated
@summary Called when this UIElement has been attached (directly or indirectly) to the global surface
*/
UIElement.activated = function() {
if (this.isActivated) throw new Error("UIElement already activated");
this.isActivated = true;
this.dompeer.style.visibility = 'visible';
if (this.mechanisms) {
this.stratum = spawn coll.par.each(this.mechanisms) {
|f, name|
try { f(this, this.api[name] = {}); }
finally { delete this.api[name]; }
}
}
/* if (Array.isArray(this.mechanisms))
this.stratum = spawn coll.par.waitforAll(this.mechanisms, undefined, this);
else
this.stratum = spawn this.mechanisms.apply(this);
} */
};
/**
@function UIElement.deactivated
@summary Called when this UIElement has become detached from the global surface
*/
UIElement.deactivated = function() {
if (!this.isActivated) throw new Error("UIElement already deactivated");
if (this.stratum) {
this.stratum.abort();
this.stratum = undefined;
}
this.isActivated = false;
this.dompeer.style.visibility = 'hidden';
coll.each(this.style, {|s| s.unuse() });
};
/**
@function UIElement.attached
@summary Called when this UIElement has been attached to a container
@param {::UIContainerElement} [parent]
@desc Sets [::UIElement::parent]
*/
UIElement.attached = function(parent) {
this.parent = parent;
};
/**
@function UIElement.detached
@summary Called when this UIElement has been detached from a container
@desc Clears [::UIElement::parent]
*/
UIElement.detached = function() {
this.parent = undefined;
};
/**
@variable UIElement.parent
@summary [::UIContainerElement] to which this UIElement is currently attached
@desc See [::UIElement::attached] and [::UIElement::detached]
*/
UIElement.parent = undefined;
/**
@variable UIElement.parentSlot
@summary Slot for use by element's parent
*/
UIElement.parentSlot = undefined;
/**
UIElement::layout(layoutSpec) -> layoutSpec
@function UIElement.layout
@purevirtual
@summary Lay out this UIElement
@param {Object} [layout_spec] Object with layout specification; see below for description
@return {Object} layout_spec (potentially modified; see below)
@desc
`layout_spec` is an object which can take the following forms:
* **{ type: 'abs', w: integer|undefined, h: integer|undefined }**
The element is to be layed out absolutely. Fields `w` and `h`
specify the explicit width and/or height that the element should have.
If either or both are undefined, the undefined value(s) should be determined
implicitly and set in the layout_spec object before this is returned.
The position of the object will be set in (a) future call(s) to [::UIElement::place].
* **{ type: 'w', w: integer }**:
The element is to be layed out relatively. The width is given; the height should
be determined implicitly. If the element is a passive element
(see [::UIElement::active]), it should set its width to '100%', rather than
an absolute width: When the available width of the container changes later on,
passive elements will not receive layout calls.
* **{ type: 'h', h: integer }**:
The element is to be layed out relatively. The height is given; the width should
be determined implicitly. If the element is a passive element
(see [::UIElement::active]), it should set its height to '100%', rather than
an absolute height: When the available height of the container changes later on,
passive elements will not receive layout calls.
* **{ type: 'wh', w: integer, h: integer }**
The element is to be layed out absolutely. Width and height are given.
If the element is a passive element (see [::UIElement::active]), it
should set its width and height to '100%', rather than an absolute value: When the
available width/height of the container changes later on,
passive elements will not receive layout calls.
*/
/**
@variable UIElement.active
@summary Flag that determines if element needs relayout when dimensions of container change
@desc
`false` by default.
If this flag is `true` when a UIElement is added to a container, the container
will relayout the element on size changes, even if the current layout mode is
one of the relative positioning modes.
*/
UIElement.active = false;
/**
@function UIElement.place
@summary Place this UIElement
@param {Integer} [x]
@param {Integer} [y]
@desc
Called by containers to set the position of this element. Only called when the
the layout mode is 'abs' (see [::UIElement::layout]).
*/
__js UIElement.place = function(x,y) {
this.dompeer.style.left = x+"px";
this.dompeer.style.top = y+"px";
};
/**
@function UIElement.getMargins
@summary Retrieve total margin width and height in pixels
@return {Array} [ ] [mw,mh]
*/
__js UIElement.getMargins = function() {
var elem = this.dompeer;
return [parseInt(getStyle(elem, "marginLeft"))+parseInt(getStyle(elem, "marginRight")),
parseInt(getStyle(elem, "marginTop"))+parseInt(getStyle(elem, "marginBottom"))];
};
/**
@function UIElement.getPadding
@summary Retrieve padding (left, right, top and bottom) in pixels
@return {Array} [ ] [pl,pr,pt,pb]
*/
__js UIElement.getPadding = function() {
var elem = this.dompeer;
return [parseInt(getStyle(elem, "paddingLeft")),
parseInt(getStyle(elem, "paddingRight")),
parseInt(getStyle(elem, "paddingTop")),
parseInt(getStyle(elem, "paddingBottom"))];
};
/**
@function UIElement.getBorders
@summary Retrieve border width and height (including scrollbars if applicable) in pixels
@return {Array} [ ] [bw,bh]
*/
__js UIElement.getBorders = function() {
var elem = this.dompeer;
// border sizes (including scrollbars):
return [elem.offsetWidth-elem.clientWidth, elem.offsetHeight-elem.clientHeight];
};
//----------------------------------------------------------------------
// UIContainerElement
/**
@class UIContainerElement
@summary Base class for UI containers
@inherit ::UIElement
@variable UIContainerElement
*/
__js var UIContainerElement = exports.UIContainerElement = Object.create(UIElement);
/**
@function UIContainerElement.init
@summary Called by constructor functions to initialize UIContainerElement objects
@param {Object} [attribs] Hash with attributes. Will also be passed to [::UIElement::init]
*/
// nothing special for UIContainerElement... just inherit for now
/**
@variable UIContainerElement.active
@summary see [::UIElement.active]
@desc
Set to `true` for UIContainerElements
*/
UIContainerElement.active = true;
/**
@function UIContainerElement.remove
@purevirtual
@summary Remove a UIElement from this container
@param {::UIElement} [child] The child to be removed
*/
/**
@function UIContainerElement.append
@purevirtual
@summary Append a UIElement to this container
@param {::UIElement} [child] The child to be appended
@param {optional Object} [attribs] Optional layout attributes (see UIContainer subclasses)
*/
//----------------------------------------------------------------------
// ChildManagement mixin
var ChildManagement = {
init: function(attribs) {
this.children = [];
coll.each(attribs.children,
{ |c|
if (UIElement.isPrototypeOf(c))
this.append(c);
else // [child, attribs]
this.append(c[0],c[1]);
});
},
remove: function(ui) {
coll.remove(this.children, ui);
ui.dompeer.parentNode.removeChild(ui.dompeer);
if (ui.isActivated)
ui.deactivated();
ui.detached();
},
activate: function() {
coll.each(this.children, { |c| c.activate() });
},
activated: function() {
coll.each(this.children, { |c| c.activated() });
},
deactivated: function() {
coll.each(this.children, { |c| c.deactivated() });
},
mixinto: function(target) {
target.init = func.seq(target.init, this.init);
target.remove = this.remove;
target.activate = func.seq(target.activate, this.activate);
target.activated = func.seq(target.activated, this.activated);
target.deactivated = func.seq(target.deactivated, this.deactivated);
}
};
//----------------------------------------------------------------------
// BoxElement
/**
@class BoxElement
@summary Box layout container
@inherit ::UIContainerElement
@variable BoxElement
*/
__js var BoxElement = exports.BoxElement = Object.create(UIContainerElement);
__js var Box = exports.Box = function(attribs) {
var obj = Object.create(BoxElement);
obj.init(attribs);
return obj;
};
/**
@function HBox
@summary Construct a horizontally-stacking [::BoxElement]
@param [attribs] ...
*/
__js var HBox = exports.HBox = function(attribs) {
return Box(common.mergeSettings(attribs, {direction:'w'}));
};
/**
@function VBox
@summary Construct a vertically-stacking [::BoxElement]
@param [attribs] ...
*/
__js var VBox = exports.VBox = function(attribs) {
return Box(common.mergeSettings(attribs, {direction:'h'}));
}
/**
@function BoxElement.init
@summary Called by constructor functions to initialize BoxElement objects
@param {Object} [attribs] Hash with attributes. Will also be passed to [::UIContainerElement::init]
@attrib {String} [direction='h'] 'w' for horizontal-stacking box, 'h' for vertically-stacking box
*/
BoxElement.init = function(attribs) {
UIContainerElement.init.apply(this, [attribs]);
this.direction = attribs.direction || 'h';
}
ChildManagement.mixinto(BoxElement);
BoxElement.append = function(ui, attribs) {
attribs || (attribs = {});
// attribs.w || (attribs.w = "*");
// attribs.h || (attribs.h = "*");
ui.parentSlot = {
w: makeConstrainedQuantity("w", attribs),
h: makeConstrainedQuantity("h", attribs),
align: attribs.align || "<"
};
this.children.push(ui);
if (this.isActivated)
ui.activate();
this.dompeer.appendChild(ui.dompeer);
ui.attached(this);
if (this.isActivated)
ui.activated();
this.invalidate(ui);
};
__js BoxElement.invalidate = function(child) {
// XXX be more specific
surface.scheduleLayout();
};
BoxElement.layoutBox = function(entity, avail, oentity, ostart,
centity, cavail, coentity, costart) {
// console.log('layout '+entity+': '+avail+' '+centity+': '+cavail);
// relaxation algorithm inspired by
// http://users.encs.concordia.ca/~haarslev/publications/jvlc92/node5.html
// amended with flex weighting
/*
PRIMARY DIMENSION:
'avail' undefined:
(0) flex: set to min
(1) fix : layout( entity=undefined, . )
'avail' given:
(2) flex: set to min; LATER share from S (<max)
(3) fix: layout( entity=undefined, . )
COMPLEMENTARY DIMENSION:
'cavail' undefined:
(~0) cflex: set to min; LATER sized to Sc (< max)
(~1) cfix : layout( centity=undefined, . )
'cavail' given:
(~2) cflex: set to min(cavail,max)
(~3) cfix: layout( centity=undefined, . )
i: needs initial layout
s: needs second layout
.: either will do
2 0 1 3
~0 s s is is
~2 s . i i
~1 is i i i
~3 is i i i
*/
var Sp = 0; // space taken in primary direction
var Sc = cavail ? cavail : 0; // max space taken in complementary direction
var F = 0; // total flex
var A = []; // remaining quantities flexible in primary direction
var B = []; // remaining quantities to be resized in complementary direction
var M = 1e10; // lowest individual distributed space
// 1. satisfy minimum space requirements, construct A&B, determine Sp,
// Sc (for non-primary flexibles), note M, and sum up F:
for (var i=0; i<this.children.length; ++i) {
var child = this.children[i];
var p = child.parentSlot[entity], c = child.parentSlot[centity];
// set up initial dimensions:
// primary dimension:
if (p.flex > 0) { // flexible in primary direction
p.val = p.min;
if (avail) {
var min = p.val/p.flex;
if (min < M) M = min;
F += p.flex;
A.push(child);
}
}
else { // inflexible in primary direction
p.val = undefined; // we'll measure
}
// complementary dimension:
if (c.flex > 0) { // flexible in complementary direction
if (cavail) {
c.val = Math.min(Sc, c.max);
}
else {
c.val = c.min;
B.push(child);
}
}
else { // inflexible in complementary direction
c.val = undefined; // we'll measure
}
// measure shrink-wrap if we need to:
if (p.val == undefined || ((c.val == undefined )&& !cavail)) {
var child_spec = child.layout({type:'abs', w:child.parentSlot.w.val, h:child.parentSlot.h.val});
child.parentSlot.w.val = child_spec.w;
child.parentSlot.h.val = child_spec.h;
child.parentSlot.layed_out = true;
}
else
child.parentSlot.layed_out = false;
// sum up Sc, Sp
Sp += p.val;
if (!cavail)
Sc = Math.max(Sc, c.val);
}
// S = space to be distributed to primary direction:
var S = avail ? avail - Sp : 0;
// 2. distribute remaining space until none left, or until we run
// out of flexible children:
while (S >= 1 && A.length > 0) {
if (this.debug('bld')) {
console.log(this.debugid+" bld: S:"+S+" A.l:"+A.length);
}
// portion/flex to distribute:
var P = S/F;
var m = M; // m: level from which to distribute
var distributed = 0; // total distributed space in this round
M = 1e10;
for (var i=0; i<A.length; ++i) {
var child = A[i];
var l = child.parentSlot[entity];
// level for this layout:
var level = Math.floor((P + m)*l.flex);
if (this.debug('bld')) {
console.log(this.debugid+" bld: "+i+" level:"+level+" P:"+P );
}
level = Math.min(l.max, level);
if (level > l.val) {
distributed += (level - l.val);
l.val = level;
child.parentSlot.layed_out = false; // need to re-layout
}
if (l.val >= l.max) {
// max flex reached
A.splice(i, 1);
--i;
F -= l.flex;
}
else {
if (this.debug('bld')) {
console.log(this.debugid+" bld: min:"+min );
}
var min = l.val/l.flex;
if (min < M) M = min;
}
}
if (distributed < 0.1) break;
S -= distributed;
}
if (this.debug('bld')) {
console.log(this.debugid+" bld: S left at end of first round:"+S );
}
// add any leftover space to the last flexible element:
while (S >= 1 && A.length > 0) {
if (this.debug('bld')) {
console.log(this.debugid+" bld: distribute to last:"+S );
}
var last = A.length-1, child = A[last];
var l = child.parentSlot[entity];
l.val += S;
if (l.val > l.max) {
S = l.max - l.val;
l.val = l.max;
A.splice(last,1);
}
else
break;
}
// 3. adjust complementary dimensions:
for (i=0; i<B.length; ++i) {
var child = B[i];
var c = child.parentSlot[centity];
if (c.val < Sc) {
c.val = Math.min(Sc, c.max);
child.parentSlot.layed_out = false; // need to re-layout
}
}
// 4. re-layout & adjust offsets:
var offset = ostart;
for (var i=0; i<this.children.length; ++i) {
var child = this.children[i];
if (!child.parentSlot.layed_out) {
child.parentSlot[entity].val = Math.round(child.parentSlot[entity].val);
child.layout({type:'abs', w:child.parentSlot.w.val, h:child.parentSlot.h.val});
child.parentSlot.layed_out = true;
}
// stack up in primary direction:
child.parentSlot[oentity] = offset;
if (child.parentSlot.align == "<")
child.parentSlot[coentity] = costart;
else if (child.parentSlot.align == ">")
child.parentSlot[coentity] = costart+Sc-child.parentSlot[centity].val;
else // align == "|"
child.parentSlot[coentity] = costart+(Sc-child.parentSlot[centity].val)/2;
child.place(child.parentSlot.x, child.parentSlot.y);
offset += child.parentSlot[entity].val;
}
// 5. ALL DONE :-)
if (!avail) avail = Sp;
return entity == 'w' ? [avail,Sc] : [Sc,avail];
};
BoxElement.layout = function(layout_spec) {
var margins = this.getMargins();
var padding = this.getPadding();
var borders = this.getBorders(); // including scrollbars
var elem = this.dompeer;
var style = elem.style;