This repository has been archived by the owner on Aug 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjuicy-tile-table.html
829 lines (744 loc) · 38 KB
/
juicy-tile-table.html
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
<!--
`juicy-tile-table` is a Custom Element with <table> renderer that mimics CSS Grid Layout of [`juicy-tile-grid`](Juicy/juicy-tile-grid).
@element juicy-tile-table
@demo https://Juicy.github.io/juicy-tile-table/
version: 0.0.7
-->
<!-- Import juicy-tile-list -->
<link rel="import" href="../juicy-tile-list/src/juicy-tile-list.html">
<!-- Workaround for IE that does not support <td>s in template (outside of tr),
we will create td manually later -->
<template id="juicy-tile">
<div class="juicy-tile"><content></content></div>
</template>
<!-- <template id="juicy-tile">
<td><div class="juicy-tile"><content></content></div></td>
</template> -->
<template id="juicy-tile-table">
<style>
:host {
display: block;
}
/*table , for Shimmed, better use class:*/
.juicy-tile-table {
table-layout: fixed;
border-spacing: 0;
width: 100%;
border-collapse: collapse;
}
/*
Done inline
.juicy-tile-table.vertical{
width: auto;
}*/
/** We are overspeficying selectors, to be less problematic with
bleeding ShadowCSS in shimmed browsers */
/*td{*/
.juicy-shadow-row > td {
/* do not grow with content*/
/*overflow: hidden;*/
margin: 0;
padding: 0;
/* position within grid area*/
vertical-align: top;
}
.juicy-tile,
.containerBackground,
.juicy-tight-group > .containerBackground,
.juicy-tight-group > .juicy-tile {
/*display: inline-block;*/
position: static;
/*height: 100%;
width: 100%;*/
float: left; /* block margin collapsing */
}
.juicy-tile {
height: 100%;
width: 100%;
}
/*.juicy-tight-group {
display: table;
}*/
/** for precalculate */
:host(.disabled) {
position: relative;
z-index: 0;
}
:host(.disabled) .juicy-tile {
position: absolute;
display: inline-block;
}
.containerBackground {
z-index: -1;
}
.containerBackground.juicy-tight-group {
z-index: initial;
}
</style>
<content select="script,style,template" class="not-a-tile"></content>
<!-- <content select=":not([juicytile])" class="not-a-tile"></content> -->
</template>
<script>
(function (scriptDocument) {
var template = scriptDocument.querySelector("#juicy-tile-table");
if (window.ShadowDOMPolyfill) {
WebComponents.ShadowCSS.shimStyling(template.content, 'juicy-tile-table');
}
var tileDecorator = scriptDocument.getElementById("juicy-tile").content;
var JuicyTileGridPrototype = Object.create(JuicyTileList.prototype);
var proto = JuicyTileGridPrototype;
/** Safari check needed to parse HTML from content property to document fragment */
var isSafari = navigator.vendor && navigator.vendor.indexOf("Apple") > -1 && navigator.userAgent && !navigator.userAgent.match("CriOS");
/**
* Flage used to force updating ShadowDOM wrappers on regular .setup change
* @private
* @type {Boolean}
*/
proto._isShadomDOMOutdated = true;
/**
* attachedCallback wrapper to workaround Chromium Bugs
* https://code.google.com/p/chromium/issues/detail?id=581176
* @see #_attachedCallback
*/
proto.attachedCallback = function gridAttached() {
this.attributeChangedCallback("refreshonattached", this.refreshOnAttached);
// tomalec: Ugly workaround for https://code.google.com/p/chromium/issues/detail?id=581176
// to wait for element to get attached, and Chromium HTML imports release metrics
// to measure elements inner dimention if not provided in setup
// XXX: causes FOUC
if (this.refreshOnAttached &&
navigator.userAgent.toLowerCase().indexOf('chrome') > -1 && // is chrome
(!this.setup ||
(!this.setup.width || this.setup.direction == "vertical" && !this.setup.height)
)
) {
var list = this;
setTimeout(function() {
list._attachedCallback();
});
} else {
this._attachedCallback();
}
// ---
};
/**
* The real meat of attachedCallback
*/
proto._attachedCallback = function deferredGridAttached() {
// move those two to created also for -grid and -list
var root = this.createShadowRoot();
var clone = document.importNode(template.content, true);
// IE/polyfill support
//
root.appendChild(clone);
this.shadowContainer = root;
// this.shadowContainer = root;
// this.shadowContainer.style = root.host.style;
// IDEA: consider merging with createItemsList, and re-flow setup, to fix Starcounter merged partials glitches (tomalec)
Package.call(this, this.setup && this.setup.items !== undefined ? this.setup : undefined);
if (this.gutter != undefined) {
this.setup.gutter = parseInt(this.gutter, 10);
}
this.createItemsList();
// Setup initials
// attributeChangedCallback for refresh* checks the value itselfes
this.attributeChangedCallback("refreshonresize", this.refreshonresize);
this.attributeChangedCallback("refreshonmutation", this.refreshonmutation);
this.attributeChangedCallback("refreshonattached", this.refreshOnAttached);
this.attributeChangedCallback("defaulttilesetup", this.defaulttilesetup, this.getAttribute("defaulttilesetup"));
if (this.refreshOnAttached) {
this.refresh();
}
this.isReady = true;
};
proto.orig_updateWrappers = proto.updateWrappers;
/**
* Updates ShadowDOM wrappers for tiles.
* Workaround lack of imperative content distribution API.
* Builds `#tiles` map, and nested grids tree.
* @param {Array of child elements to cover} elementsArray [description]
* @return {Array<HTMLElement>} array and map of tiles in ShadowDOM
*/
proto.updateWrappers = function(elementsArray, element) {
// debugger
//TODO: improve performance
//TODO: decide how to handle setup when something was removed/added in the middle
// to shift or not to shift indexes?
//when something added/ removed clear all first
// if (element.shadowContainer.children.length) {
// element.shadowContainer.innerHTML = "";
// }
//TODO(tomalec): Clean it after refactoring to slots (latest W3C spec)
var table = element.shadowRoot.querySelector('table');
table && table.parentNode.removeChild(table);
var tiles = [],
tile, child, id,
//scoping magic
scopePrefix = "",
scopedIndex = 0;
/**
* Builds tree of nested CSS Grid containers
* @param {DocumentFragment} parentFragment where to append
* @param {Array<SetupItem>} items array of setup items
*/
function buildGridsTree(items) {
var item;
for (var itemNo = 0, len = items.length; itemNo < len; itemNo++) {
item = items[itemNo];
if (!item.items) {
createTileWrapper(item.id, tiles);
// add also key based
} else if (item.tightGroup) {
stampShadowContainer(item.id, 'containerBackground juicy-tight-group')
buildGridsTree(item.items);
} else {
// -table does not support DOM nodes for loose groups
// stampShadowContainer(item.id, 'containerBackground juicy-group');
buildGridsTree(item.items);
}
}
}
/**
* Creates an instance of `tileDecorator` with given _id_,
* adds tile into `tiles` map.
* @param {String} id tile id
* @param {Object} tiles map of tiles to update
*/
function createTileWrapper(id, tiles) {
var frag = document.importNode(tileDecorator, true);
// Workaround for IE that does not support <td>s in template (outside of tr)
var tile = document.createElement('td');
tile.appendChild(frag.children[0]);
tile.id = id;
tile.firstChild.firstChild.setAttribute('select', '[juicytile="' + id + '"]');
// add to key based map
tiles[id] = tile;
}
/**
* Creates an instance of juicy-tile-table container with given _id_,
* adds tile into `tiles` map.
* @param {String} id container/tile id
* @param {String} [className] is container tight group/nested css grid?classname for the container
*/
function stampShadowContainer(id, className) {
var tightTile = document.createElement('td');
tightTile.className = className;
// add to key based map
tiles[id] = tightTile;
tightTile.id = id;
return tightTile;
}
// build tree from setup
buildGridsTree(this.setup.items);
// set distribution attributes, and wrapp child elements w/o setup
var regularTileIndex = -1;
for (var i = 0, len = elementsArray.length; i < len; i++) {
child = elementsArray[i];
//scoping magic
//
if (child.tagName === "JUICY-TILE-GROUP") {
scopePrefix = child.getAttribute("name") || "";
scopePrefix += "/";
scopedIndex = 0;
continue;
}
id = scopePrefix + scopedIndex;
scopedIndex++;
regularTileIndex++;
//id = i;
tile = tiles[id];
// if tile was not yet distributed to a tight group
if (!tile) {
createTileWrapper(id, tiles);
tile = tiles[id];
}
// Add reference to Light DOM element to make it easier for setup checking
tile.element = child;
// make it work with good old indexes as well
tiles[regularTileIndex] = tile;
//if (elem.setAttribute) {
// attach a selectable key to each light-dom node
child.setAttribute('juicytile', id);
//}
}
tiles["root"] = element; // real HTML element, not DocumentFragment at // .shadowContainer;
this._isShadomDOMOutdated = undefined;
return tiles;
};
proto.renderer = (function() { // scope for helper functions, to return grid renderer
/**
* Check whether all/any/none items have given property set
* @param {Array<Object>} items list of items to check
* @return {Number} 1 all, 0 any, -1 none
*/
function countProperty(items, propertyName) {
var len = items.length,
itemNo = 0,
counter = 0;
for (; itemNo < len; itemNo++) {
items[itemNo][propertyName] && counter++;
}
return counter;
}
/**
* Subtracts given _size_ from all elements in _gutters_ array,
* removes negative ones
* @param {Array<Number>} gutters array of gutters
* @param {Number} size size to subtract
*/
function reduceOpenedGutters(gutters, size) {
var gutterNo = gutters.length;
while (gutterNo--) {
gutters[gutterNo] -= size;
if (gutters[gutterNo] < 0) {
gutters.splice(gutterNo, 1);
}
}
}
/**
* Mark set given _propertyName_ to given _lineNo_ for all items from _items_
* @param {String} propertyName name of property to set
* @param {Array<Object>} starts list of items to set
* @param {Number} lineNo value to set
*/
function markGridItems(starts, propertyName, lineNo) {
var itemNo = starts.length;
while (itemNo--) {
starts[itemNo][propertyName] = lineNo;
}
}
/**
* Subtracts one array from another, mark subtracted elements as .{propertyName} = {lineNo}
* @param {Array<Object>} from the array from which given elements should be subtracted
* @param {Array<Object>} what array of objects to be subtracted. IMPORTANT: we assume that the exist in `from`
* @param {String} propertyName property name to set to _lineNo_
* @param {Number} lineNo line number to set to the property
* @return {Array<Object>} changed array
*/
function arraySubtractAndMark(from, what, propertyName, lineNo) {
var whatLeft = what.length,
endingItem;
while (whatLeft--) {
endingItem = what[whatLeft];
endingItem[propertyName] = lineNo;
from.splice(from.indexOf(endingItem), 1);
}
return from;
}
/**
* Add new line at given position if there is none,
* otherwise just update starts, ends, gutters arrays.
* @param {Array} array of lines
* @param {Number} position line position
* @param {Object} [starts] item that starts at this line
* @param {Object} [ends] item that ends at this line
* @param {Boolean} [gutter] do we have a gutter after this line?
* @returns line number for line at given position
*/
function drawGridLine(array, position, starts, ends, gutter) {
var len = array.length,
line;
// while(len-- && array[len] > position){
while (len-- && array[len].position > position) {}
// if(len>-1 && array[len] == position){
if (len > -1 && array[len].position == position) {
line = array[len];
} else {
// array.splice( len+1, 0, position );
line = {
position: position,
starts: [],
ends: [],
gutter: []
};
len++;
array.splice(len, 0, line);
}
starts && line.starts.push(starts);
ends && line.ends.push(ends);
// for <table> we need to start gutter cells as well ?
gutter && line.gutter.push(gutter);
return len;
}
/**
* Apply styles given by _packedItems_ to _tiles_.
* @param {Object<HTMLElement>} tiles map (by id) of tiles
* @param {Object} packedGroup configuration
* @param {Boolean} [hideAll] should all items be hidden (parent element has .hidden = true)
* @param {HTLMElement} container
*/
function applyStyles(tiles, packedGroup, hideAll) {
var itemNo = packedGroup.items.length;
var packedItem, element, elementStyle;
var table = document.createElement('table');
table.classList.add('juicy-tile-table');
if (packedGroup.direction === "vertical") {
table.style.width = 'auto';
table.style.minHeight = packedGroup.height + 'px';
} else {
table.style.minWidth = packedGroup.width + 'px';
}
if (packedGroup.tightGroup && !hideAll) {
/// probs for root
// IDEA tomalec: Consider merging those 3 lines into single funciton for better performance
setGridTracks("row", packedGroup.rowAxes, "heightFlexible", "heightDynamic", packedGroup.height);
setGridTracks("column", packedGroup.columnAxes, "widthFlexible", "widthDynamic", packedGroup.width);
var tableGrid = getFullTableGrid(packedGroup.rowAxes, packedGroup.columnAxes);
var shadowRow, row, column, shadowTile, tileItem;
// last columnAxes is the end line of the last row
for (var columnNo = 1; columnNo < packedGroup.columnAxes.length; columnNo++) {
col = document.createElement('col');
column = packedGroup.columnAxes[columnNo];
// force inline style
// .style does not work with ShadowDOM distribution for some reason
// IDEA tomalec: create Chromium issue about isolated problem
col.setAttribute('style',
(column.size ? 'width:' + column.size + ';' : '') +
(column.minSize ? 'min-width:' + column.minSize + ';' : '') +
// 'max-width:'+ column.maxSize +';');
(column.maxSize ? 'max-width:' + column.maxSize + ';' : '')
);
table.appendChild(col);
}
// last rowAxes is the end line of the last row
for (var rowNo = 0; rowNo < tableGrid.length; rowNo++) {
row = tableGrid[rowNo];
shadowRow = document.createElement('tr');
shadowRow.style.height = packedGroup.rowAxes[rowNo + 1].size;
shadowRow.style.minHeight = packedGroup.rowAxes[rowNo + 1].minSize;
shadowRow.style.maxHeight = packedGroup.rowAxes[rowNo + 1].maxSize;
shadowRow.classList.add('juicy-shadow-row'); // just for debugging
for (var colNo = 0; colNo < packedGroup.columnAxes.length; colNo++) {
tileItem = row[colNo];
if (tileItem === null) { // gutter
shadowRow.appendChild(document.createElement('td'));
} else if (tileItem !== undefined) { // not a span but tile
// TODO create SD?
shadowTile = tiles[tileItem.id];
// loose groups does not have tiles, and we do not render a thing for them
if (shadowTile) {
shadowTile.setAttribute('colspan', tileItem.columnEnd - tileItem.columnStart);
shadowTile.setAttribute('rowspan', tileItem.rowEnd - tileItem.rowStart);
var hidden = hideAll || tileItem.hidden;
if (tileItem.items) { // virtual container
shadowTile.appendChild(
applyStyles(tiles, tileItem, hidden)
);
}
var elementStyle = shadowTile.firstChild.style;
elementStyle.width = tileItem.widthFlexible || tileItem.widthDynamic ? "100%" : tileItem.width + "px";
// elementStyle.height = ( tileItem.height /*+ 2 * oversize*/ ) + "px";
elementStyle.height = tileItem.heightFlexible ? '100%' : tileItem.heightDynamic ? 'min-content' : tileItem.height + "px";
if (hidden) {
elementStyle.display = "none";
} else {
var oversize = tileItem.oversize || 0;
if (tileItem.background !== undefined) {
elementStyle.backgroundColor = tileItem.background || "transparent";
}
elementStyle.outline = tileItem.outline || "";
if (oversize) {
elementStyle.padding = oversize + "px";
elementStyle.margin = "-" + oversize + "px";
}
}
if(tileItem.content){
// fragmentFromString(strHTML) from http://stackoverflow.com/a/25214113/868184
var range = document.createRange();
// Safari does not support `createContextualFragment` without selecting a node.
if (isSafari) {
range.selectNode(this);
}
shadowTile.appendChild(range.createContextualFragment(tileItem.content));
}
shadowRow.appendChild(shadowTile);
}
}
}
table.appendChild(shadowRow);
}
}
return table;
}
/**
* Prepare grid track setup, update grid position, for items at given _gridLines_
* @param {String} trackType type of track (`"column"||"row"`)
* @param {Array<Object>} gridLines array of gridlines, see `drawGridLine`
* @param {String} flexPropertyName property name that indicates flexible size of axis in question
* @param {String} dynamicPropertyName property name that indicates dynamic size of axis in question
*/
function setGridTracks(trackType, gridLines, flexPropertyName, dynamicPropertyName, containerSize) {
var linesAmount = gridLines.length,
currentLine = gridLines[0],
previousLine = currentLine,
trackSize,
str = "",
openedTiles,
openedGutters = [];
// lineNo == 1, currentLine = gridLines[0]
markGridItems(currentLine.starts, trackType + "Start", 1);
openedTiles = currentLine.starts.slice();
// In CSS Grid lines, and tracks are counted from 1
if (linesAmount == 1) {
markGridItems(currentLine.ends, trackType + "End", 1);
}
var col;
for (var lineNo = 2; lineNo <= linesAmount; lineNo++) {
currentLine = gridLines[lineNo - 1];
trackSize = currentLine.position - previousLine.position;
// Workaround for dynamic col.style changes in ShadowDOM
reduceOpenedGutters(openedGutters, trackSize);
if (lineNo == linesAmount && openedTiles.length == 0) {
// Last line, if empty, should be flexible
// str += trackSize + "fr ";
currentLine.size = (100 * trackSize / containerSize) + "%";
break;
} else if (openedGutters.length) {
// Gutters should be fixed size
currentLine.size = trackSize + "px";
} else {
//does not contain any gutter
switch (countProperty(openedTiles, flexPropertyName)) {
case 0: // all are non-flex
// there is dynamic
if (countProperty(openedTiles, dynamicPropertyName)) {
// str += "minmax( min-content, max-content ) "
// TODO: check just width auto
currentLine.minSize = 'min-content';
currentLine.maxSize = 'max-content';
} else {
// all are non-dynamic (fixed)
currentLine.size = trackSize + "px ";
}
break;
case openedTiles.length: // all intersected are flexible
// and it contains them
if (currentLine.ends.length === openedTiles.length && previousLine.starts.length === openedTiles.length) {
// str += "minmax( min-content, " + trackSize + "fr ) ";
// str = "minmax( min-content, " + (100 * trackSize/containerSize) + "%)";
currentLine.minSize = 'min-content';
currentLine.size = (100 * trackSize / containerSize) + '%';
} else {
// XXX(tomalec): min-content does not make an effect for spanning items! so we will force min size to fixed size
// str += "minmax( " + trackSize + "px, " + trackSize + "fr ) ";
// min-size in px is somehow secured by containers min-size
currentLine.size = (100 * trackSize / containerSize) + '%';
}
break;
default: //mix
// str += "minmax( " + trackSize + "px, " + trackSize + "fr ) ";
// min-size in px is somehow secured by containers min-size
currentLine.size = (100 * trackSize / containerSize) + '%';
break;
}
}
// currentLine.ends.length && arraySubtractAndMark(openedTiles, currentLine.ends, trackType + "End", lineNo);
currentLine.ends.length && arraySubtractAndMark(openedTiles, currentLine.ends, trackType + 'End', lineNo);
if (currentLine.starts.length) {
markGridItems(currentLine.starts, trackType + "Start", lineNo);
openedTiles = openedTiles.concat(currentLine.starts);
}
if (currentLine.gutter.length) {
openedGutters = openedGutters.concat(currentLine.gutter);
}
previousLine = currentLine;
}
// now we need to resolve fr
// https://www.w3.org/TR/css-grid-1/#algo-find-fr-size
// or mimic https://www.w3.org/TR/css-grid-1/#algo-overview otherwise
// calc will not help, as it is not supported for table
// https://github.com/Juicy/juicy-tile-table/issues/1
return;
}
return function grid(packedTree, tiles, offsetX, offsetY) {
// root group is always a tight group
// (have independent grid lines from its parent)
packedTree.tightGroup = true;
function drawGridLinesFromTree(node, offsetX, offsetY, columnAxes, rowAxes) {
if (node.tightGroup) {
// just position, as Object Number, with dynamic property
//{position: px, dynamic: boolean}
columnAxes = node.columnAxes = [];
rowAxes = node.rowAxes = [];
//reposition cildnodes to 0,0
offsetX = offsetY = 0;
}
var ilen = node.items.length,
item, x, y;
while (ilen--) {
var item = node.items[ilen];
if (item.hidden) {
continue;
}
x = node.rightToLeft ? node.width - item.width - item.x : item.x
x += offsetX;
y = node.bottomUp ? node.height - item.height - item.y : item.y
y += offsetY;
drawGridLine(columnAxes, x, item);
drawGridLine(columnAxes, x + item.width, undefined, item, node.gutter);
drawGridLine(rowAxes, y, item);
drawGridLine(rowAxes, y + item.height, undefined, item, node.gutter);
if (item.items) {
drawGridLinesFromTree(item, x, y, columnAxes, rowAxes);
}
}
// IDEA (tomalec): consider making it on-demand, so grid may auto-center/auto grow if last track is empty
// draw lines for end (right bottom) of our container
drawGridLine(columnAxes, offsetX + node.width);
drawGridLine(rowAxes, offsetY + node.height);
}
drawGridLinesFromTree(packedTree, 0, 0, packedTree.columnAxes, packedTree.rowAxes);
packedTree.id = "root";
if (packedTree.direction === "vertical") {
this.style.width = 'auto';
this.style.minHeight = packedTree.height + 'px';
} else {
this.style.minWidth = packedTree.width + 'px';
}
this.shadowRoot.insertBefore(
applyStyles(tiles, packedTree, undefined, this.shadowContainer),
this.shadowRoot.firstChild
);
// if (packedTree.direction === "vertical") {
// this.shadowContainer.style.height = "100%";
// }
};
/**
* Create a nxm array with table cells
* undefined - spanned cell
* null - gutter
* Object - tile that starts here
* XXX: we heavily rely on assumption that tiles do not overlap each other at any grid node
* @param {Array} rowAxes grid axes as in #drawGridLines
* @param {Array} columnAxes column axes as in #drawGridLines
* @return {Array} rows x cols table
*/
function getFullTableGrid(rowAxes, columnAxes) {
function notALooseGroup(e) {
return !e.items || e.tightGroup;
}
function byX(a, b) {
return b.x - a.x;
}
var grid = [];
var rowNo, rowsLen = rowAxes.length,
howManyTilesLeft, firstToStart,
tilesWoLooseGroups,
columnNo, columnsLen = columnAxes.length;
var gridRow, spans = Array(columnsLen - 1),
spanning = 0,
horizontalSpan, verticalSpan;
for (rowNo = 0; rowNo < rowsLen - 1; rowNo++) {
gridRow = [];
grid.push(gridRow);
// filter out loos groups, as we cannot represent them as HTML nodes in a <table>
tilesWoLooseGroups = rowAxes[rowNo].starts
.sort(byX)
.filter(notALooseGroup);
howManyTilesLeft = tilesWoLooseGroups.length;
// XXX: we assume descending order of gridlines in starts
firstToStart = tilesWoLooseGroups[--howManyTilesLeft];
for (columnNo = 1; columnNo < columnsLen; columnNo++) {
if (spans[columnNo] > 0) {
spans[columnNo]--;
gridRow.push(undefined);
} else if (firstToStart && firstToStart.columnStart === columnNo && firstToStart.rowStart === rowNo + 1) {
gridRow.push(firstToStart);
// 0-based span as a distance between axes
horizontalSpan = firstToStart.columnEnd - firstToStart.columnStart - 1;
verticalSpan = firstToStart.rowEnd - firstToStart.rowStart - 1;
spans[columnNo] = verticalSpan;
for (spanning = 0; spanning < horizontalSpan; spanning++) {
columnNo++;
spans[columnNo] = verticalSpan;
gridRow.push(undefined);
}
firstToStart = tilesWoLooseGroups[--howManyTilesLeft];
} else {
// gutter
gridRow.push(null);
}
}
}
return grid;
}
}());
/** Use package packItems method to ommit/disable pre-calculate magic */
proto.packItems = Package.prototype.packItems;
var juicyTileListRefresh = proto.refresh;
/**
* Overwrite -list.refresh to always do hard refresh when attached
* @return whatever -list.refresh returns
*/
proto.refresh = function tableRefresh() {
return juicyTileListRefresh.call(this, this.isReady);
};
/*
Parses given string containing css directives
and returns a map ruleName: ruleValue,
Parse `(width|height):NNpx` as `(width|height):NN`
and `(width|height):NN%` as `(width|height):NN%;(width|height)Flexible: true;`
@param {String} rules, css directive-like string example
\n\width:40%;\n priority:0.5;\n
@param {Object} map set of JSON properties to be extended
@retruns {Object} modified map
*/
proto.parseRules = function(rules, map) {
rules = rules.split(';');
//proccess rules
for (var i = 0; i < rules.length; i++) {
var declaration = rules[i];
//determine if declaration is a valid css declaration, ie `property S* ':' S* value;``
declaration = declaration.trim();
if (declaration.indexOf(':') !== -1) {
//declaration contains :
declaration = declaration.split(':');
var cssProperty = declaration[0].trim();
var cssValue = declaration.slice(1).join(':').trim();
// TODO (tomalec): parse some values according to
// https://drafts.csswg.org/css2/syndata.html#tokenization
// but optimze to avoid regexps as much as possible
if (cssProperty === 'width' || cssProperty === 'height') {
if (cssValue.indexOf('px') > -1) {
cssValue = parseFloat(cssValue);
map[cssProperty + 'Flexible'] = false;
} else if (cssValue.indexOf('%') > -1) {
map[cssProperty + 'Flexible'] = true;
} else {
cssValue = parseFloat(cssValue);
}
} else if(cssValue === 'true'){
cssValue = true;
} else if(cssValue === 'false'){
cssValue = false;
}
// silently ignore unknown values https://drafts.csswg.org/css2/syndata.html#unsupported-values
// if (cssProperty.length < 1 || cssValue.length < 1) {
// continue; //there is no css directive or value
// }
//save rule
map[cssProperty] = cssValue;
} else if (declaration !== '') {
console.warn("juicy-style for ", this, " contains defective declaration: ", declaration);
}
}
return map;
};
/**
* Overwrite juicy-tile-list method as `-table` does not necesarily make shadow Element for loose groups
* @param {Item} what Reference to the container to delete.
* @param {Boolean} [noRepacking=false] `true` to prevent re-packing after setup change.
* @return {Object} deleted item
*/
proto.deleteContainer = function(what, noRepacking) {
var deletedItem = Package.prototype.deleteContainer.call(this, what, noRepacking);
var deletedElement = this.tiles[deletedItem.id];
// var deletedElement = this.getTile(deletedItem.id);
deletedElement && deletedElement.parentNode.removeChild(deletedElement);
return deletedItem;
};
window.JuicyTileGrid = document.registerElement("juicy-tile-table", {
prototype: JuicyTileGridPrototype
});
}((document._currentScript || document.currentScript).ownerDocument));
</script>