Debian Codegraph @

ivette/src/dome/renderer/layout/grids.js

raw
1 /* ************************************************************************ */
2 /* */
3 /* This file is part of Frama-C. */
4 /* */
5 /* Copyright (C) 2007-2022 */
6 /* CEA (Commissariat à l'énergie atomique et aux énergies */
7 /* alternatives) */
8 /* */
9 /* you can redistribute it and/or modify it under the terms of the GNU */
10 /* Lesser General Public License as published by the Free Software */
11 /* Foundation, version 2.1. */
12 /* */
13 /* It is distributed in the hope that it will be useful, */
14 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
15 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
16 /* GNU Lesser General Public License for more details. */
17 /* */
18 /* See the GNU Lesser General Public License version 2.1 */
19 /* for more details (enclosed in the file licenses/LGPLv2.1). */
20 /* */
21 /* ************************************************************************ */
22
23 // --------------------------------------------------------------------------
24 // --- Grid Layout
25 // --------------------------------------------------------------------------
26
27 /**
28 @packageDocumentation
29 @module dome/layout/grids
30 */
31
32 import _ from 'lodash' ;
33 import React from 'react' ;
34 import * as Json from 'dome/data/json';
35 import * as Settings from 'dome/data/settings';
36 import { dispatchEvent, DnD, DragSource, DropTarget } from 'dome/dnd' ;
37 import { AutoSizer } from 'react-virtualized' ;
38 import { DraggableCore } from 'react-draggable' ;
39
40 import * as Dome from 'dome' ;
41
42 import './style.css' ;
43
44 // --------------------------------------------------------------------------
45 // --- Grid Utilities
46 // --------------------------------------------------------------------------
47
48 function flatten( dir, gs )
49 {
50 const content = [] ;
51 gs && gs.forEach((g) => {
52 let kd = g && g.kind ;
53 if (kd)
54 if ( kd === dir ) {
55 if (g.content.length > 0) content.push( ...g.content );
56 } else
57 content.push( g );
58 });
59 return content ;
60 }
61
62 function iter( grid , fn )
63 {
64 function visit(g) {
65 if (!g) return;
66 if (g.kind === 'ITEM') fn(g);
67 else g.content.forEach(visit);
68 }
69 visit(grid);
70 }
71
72 function get( g, id )
73 {
74 if (g) {
75 if (g.id === id) return g;
76 switch( g.kind ) {
77 case 'HBOX':
78 case 'VBOX':
79 const gs = g.content ;
80 var k = 0;
81 while (k < gs.length) {
82 let r = get(gs[k],id);
83 if (r) return r;
84 k++;
85 }
86 }
87 }
88 return undefined;
89 }
90
91 /**
92 @summary Pretty-print shape.
93 */
94
95 export function stringOfShape( s )
96 {
97 if (!s) return "<>" ;
98 switch(s.kind) {
99 case 'ITEM':
100 if (s.switch || s.height)
101 return s.id + "(" + s.width + "x" + s.height + ")" ;
102 else
103 return s.id ;
104 case 'HBOX': return "H<" + s.content.map(stringOfShape).join(',') + ">" ;
105 case 'VBOX': return "V<" + s.content.map(stringOfShape).join(',') + ">" ;
106 default: return "<?" + s + "?>";
107 }
108 }
109
110 // --------------------------------------------------------------------------
111 // --- Shape Utilities
112 // --------------------------------------------------------------------------
113
114 /**
115 @summary Iterates over items in a shape.
116 @parameter {Shape} shape - the shape to iter over
117 @parameter {function} job - the function to apply on each
118 @description
119 The iteree receives `job(id,width,height)` for each `ITEM` in the shape.
120 */
121 export function iterShape( shape, job )
122 {
123 iter( shape , (item) => job(item.id,item.width,item.height) );
124 }
125
126 /**
127 @summary Returns the shape element of the given item identifier.
128 @parameter {Shape} shape - the shape to look into
129 @parameter {string} id - the item identifier
130 @return {object} the associated item object, or `undefined`
131 */
132 export function getShapeItem( shape, id )
133 {
134 return get(shape,id);
135 }
136
137 /**
138 @summary Remove an item or sub-grid from the shape.
139 @parameter {Shape} shape - the shape to filter
140 @parameter {string} id - the item or grid identifier to remove
141 @return {Shape} the filtered shape
142 */
143 export function removeShapeItem( shape, id )
144 {
145 const visit = (s) => {
146 if (s && s.id !== id) {
147 switch(s.kind) {
148 case 'ITEM':
149 return s;
150 case 'HBOX':
151 case 'VBOX':
152 return makeShapeBox( s.kind , s.id, s.content.map(visit) );
153 //otherwize continue
154 }
155 }
156 return null;
157 };
158 return visit(shape);
159 }
160
161
162 // --------------------------------------------------------------------------
163 // --- Dimensions
164 // --------------------------------------------------------------------------
165
166 function shareDim( d , ds )
167 {
168 d.min = 0;
169 d.size = 0;
170 d.next = 0;
171 d.ext = 0;
172 d.fill = false;
173 d.resize = false;
174 ds.forEach( (di) => {
175 d.min += di.min ;
176 d.size += di.size ;
177 if (di.resize) d.resize = true ;
178 if (di.fill) {
179 d.fill = true ;
180 d.ext += di.min ;
181 d.next ++ ;
182 } else
183 d.ext += di.size ;
184 });
185 }
186
187 function stackDim( d , ds )
188 {
189 d.min = 0;
190 d.size = 0;
191 d.fill = 0;
192 d.resize = 0;
193 ds.forEach( (di) => {
194 d.min = Math.max( d.min, di.min );
195 d.size = Math.max( d.size, di.size );
196 if (di.fill) d.fill = true ;
197 if (di.resize) d.resize = true ;
198 });
199 }
200
201
202 // --------------------------------------------------------------------------
203 // --- Sequence Layout
204 // --------------------------------------------------------------------------
205
206 /* Distributes extra available space w.r.t respective ratio. */
207 function layoutShare( d0 , ds )
208 {
209 const d = d0.dim ;
210 const s = d0.size ;
211 const e = d0.ext ;
212 const m = d0.min ;
213
214 let flayout ;
215
216 if ( s <= d ) {
217 const K = d0.next ;
218 flayout = (di) =>
219 di.fill ? di.size + ( d - s ) / K : di.size ;
220 } else if ( e <= d ) {
221 // Have e <= d < s, Hence e < s
222 const alpha = (d - e) / (s - e) ;
223 flayout = (di) =>
224 di.fill ? di.min + alpha * (di.size - di.min) : di.size ;
225 } else if ( m <= d ) {
226 // Have m <= d < {e,s}, Hence m < e
227 const alpha = (d - m) / (e - m) ;
228 flayout = (di) =>
229 !di.fill ? di.min + alpha * (di.size - di.min) : di.min ;
230 } else if ( m > 0 ) {
231 const alpha = d / m ;
232 flayout = (di) => alpha * di.min ;
233 } else {
234 flayout = (di) => 0 ;
235 }
236
237 var p0 = d0.pos ;
238 var p1 = p0 ;
239 var ps = 0 ;
240 ds.forEach((di) => {
241 ps += di.drag ? di.drag : flayout(di) ; // Avoids cumulative rounding
242 let p2 = p0 + Math.round(ps) ;
243 di.pos = p1 ;
244 di.dim = p2-p1 ;
245 p1 = p2 ;
246 });
247 }
248
249 // --------------------------------------------------------------------------
250 // --- Parallel Layout
251 // --------------------------------------------------------------------------
252
253 /* Apply available space to all elements */
254
255 function layoutStack( d0 , ds )
256 {
257 const p = d0.pos ;
258 const d = d0.dim ;
259 ds.forEach((di) => {
260 di.pos = p ;
261 di.dim = di.drag ? di.drag : (di.fill ? d : Math.min( d , di.size )) ;
262 di.room = d - di.dim ;
263 });
264 }
265
266 // --------------------------------------------------------------------------
267 // --- Layout Grid
268 // --------------------------------------------------------------------------
269
270 function layoutGrid(grid,width,height)
271 {
272 function visit(g) {
273 if (!g) return ;
274 switch( g.kind ) {
275 case 'ITEM':
276 break;
277 case 'HBOX':
278 layoutShare( g.dx , g.dxs );
279 layoutStack( g.dy , g.dys );
280 g.content.forEach(visit);
281 break;
282 case 'VBOX':
283 layoutStack( g.dx , g.dxs );
284 layoutShare( g.dy , g.dys );
285 g.content.forEach(visit);
286 break;
287 }
288 }
289 grid.dx.pos = 0; grid.dy.pos = 0;
290 grid.dx.dim = width; grid.dy.dim = height;
291 visit(grid);
292 }
293
294 // --------------------------------------------------------------------------
295 // --- Freezing
296 // --------------------------------------------------------------------------
297
298 function freezeGrid( g )
299 {
300 if (!g) return;
301 switch(g.kind) {
302 case 'ITEM':
303 g.dx.size = g.dx.dim ;
304 g.dy.size = g.dy.dim ;
305 break;
306 case 'HBOX':
307 g.content.forEach( freezeGrid );
308 shareDim(g.dx,g.dxs);
309 stackDim(g.dy,g.dys);
310 break;
311 case 'VBOX':
312 g.content.forEach( freezeGrid );
313 stackDim(g.dx,g.dxs);
314 shareDim(g.dy,g.dys);
315 break;
316 }
317 }
318
319 function resizeGrid(g,dgx,dgy)
320 {
321 if (!g) return;
322 switch(g.kind) {
323 case 'ITEM':
324 if (dgx && !g.dx.room) g.dx.drag = dgx ;
325 if (dgy && !g.dy.room) g.dy.drag = dgy ;
326 break;
327 case 'HBOX':
328 g.content.forEach( (g) => resizeGrid(g,g.dx.drag,dgy) );
329 break;
330 case 'VBOX':
331 g.content.forEach( (g) => resizeGrid(g,dgx,g.dy.drag) );
332 break;
333 }
334 }
335
336 // --------------------------------------------------------------------------
337 // --- Grid Constructors
338 // --------------------------------------------------------------------------
339
340 const BOXID = 'DOME$' ;
341 const MINDIM = 12 ;
342 const INSETS = 6 ; // For insertion borders
343
344 function makeGridItem( content, width, height )
345 {
346 if (content.display !== undefined && !content.display) return undefined ;
347 const dimension = (d) => Math.max( d || 0 , MINDIM );
348 const w = dimension(content.width) ;
349 const h = dimension(content.height);
350 const mw = dimension(content.minWidth);
351 const mh = dimension(content.minHeight);
352 const dx = { size: Math.max( mw , w ), min: Math.min( mw , w ), resize:false, fill:false };
353 const dy = { size: Math.max( mh , h ), min: Math.min( mh , h ), resize:false, fill:false };
354 switch( content && content.fill ) {
355 case 'both': dx.fill = true ; dy.fill = true ; break;
356 case 'horizontal': dx.fill = true ; break;
357 case 'vertical': dy.fill = true ; break;
358 }
359 switch( content && content.resize ) {
360 case undefined: dx.resize = dx.fill ; dy.resize = dy.fill; break;
361 case 'both': dx.resize = true ; dy.resize = true ; break;
362 case 'horizontal': dx.resize = true ; break;
363 case 'vertical': dy.resize = true ; break;
364 }
365 if (width && dx.resize && dx.min <= width)
366 dx.size = width ;
367 if (height && dy.resize && dy.min <= height)
368 dy.size = height ;
369 const id = content.id ;
370 return { kind: 'ITEM', dx, dy, id, content };
371 }
372
373 function makeGridHbox( id, gs )
374 {
375 const content = flatten( 'HBOX' , gs );
376 switch(content.length) {
377 case 0: return null ;
378 case 1: return content[0];
379 default:
380 const dxs = content.map((g) => g.dx);
381 const dys = content.map((g) => g.dy);
382 const dx = {} ;
383 const dy = {} ;
384 shareDim(dx,dxs);
385 stackDim(dy,dys);
386 return { kind: 'HBOX', id , dx, dxs, dy, dys, content };
387 }
388 }
389
390 function makeGridVbox( id, gs )
391 {
392 const content = flatten( 'VBOX' , gs );
393 switch(content.length) {
394 case 0: return null ;
395 case 1: return content[0];
396 default:
397 const dxs = content.map((g) => g.dx);
398 const dys = content.map((g) => g.dy);
399 const dx = {} ;
400 const dy = {} ;
401 stackDim(dx,dxs);
402 shareDim(dy,dys);
403 return { kind: 'VBOX', id, dx, dxs, dy, dys, content };
404 }
405 }
406
407 function makeGridDir( dir, id, gs )
408 {
409 switch( dir || 'vertical') {
410 case 'horizontal':
411 return makeGridHbox(id,gs);
412 case 'vertical':
413 return makeGridVbox(id,gs);
414 default:
415 return null;
416 }
417 }
418
419 function makeShapeDir( dir, id, content )
420 {
421 switch( dir || 'vertical') {
422 case 'horizontal':
423 return makeShapeBox('HBOX',id,content);
424 case 'vertical':
425 return makeShapeBox('VBOX',id,content);
426 default:
427 return null;
428 }
429 }
430
431 // --------------------------------------------------------------------------
432 // --- Shapes
433 // --------------------------------------------------------------------------
434
435 function makeShapeBox( kind, id, gs )
436 {
437 const content = flatten( kind, gs );
438 switch(content.length) {
439 case 0: return null ;
440 case 1: return content[0];
441 default: return { kind, id, content };
442 }
443 }
444
445 function makeShapeOfGrid( g )
446 {
447 let kind = g && g.kind ;
448 switch( kind ) {
449 case 'HBOX':
450 case 'VBOX':
451 return { kind, id: g.id, content: g.content.map(makeShapeOfGrid) };
452 case 'ITEM':
453 return { kind:'ITEM', id: g.id, width: g.dx.dim, height: g.dy.dim };
454 default:
455 return null;
456 }
457 }
458
459 const BOXINSERT = 'DOME$INSERT' ;
460 let insertId = 0 ;
461
462 function makeShapeInsert( shape,at,dir,item )
463 {
464 const visit = (s) => {
465 if (!s || s.id === item.id) return null;
466 switch( s.kind ) {
467 case 'HBOX':
468 case 'VBOX':
469 s = makeShapeBox( s.kind , s.id, s.content.map(visit) );
470 // then falls through
471 }
472 if (s.id === at) {
473 const id = BOXINSERT + (insertId++) ;
474 switch( dir ) {
475 case 'NORTH': return makeShapeBox('VBOX', id, [ item , s ]);
476 case 'SOUTH': return makeShapeBox('VBOX', id, [ s , item ]);
477 case 'EAST': return makeShapeBox('HBOX', id, [ s , item ]);
478 case 'WEST': return makeShapeBox('HBOX', id, [ item , s ]);
479 // otherwize falls through
480 }
481 }
482 return s ;
483 };
484 return at === '*' ? item : at === item.id ? shape : visit(shape);
485 }
486
487 // --------------------------------------------------------------------------
488 // --- Insertions
489 // --------------------------------------------------------------------------
490
491 const quadrant = ( dx , dy , x , y ) => {
492 let dir, best = 10000 ;
493 const qdir = ( d , w ) => { if (0 <= w && w < best) { best = w ; dir = d; } };
494 qdir( 'NORTH', y - dy.pos );
495 qdir( 'SOUTH', dy.pos + dy.dim - y );
496 qdir( 'EAST', dx.pos + dx.dim - x );
497 qdir( 'WEST', x - dx.pos );
498 return dir;
499 };
500
501 const isHead = (d,p) => ( d.pos <= p && p <= d.pos + INSETS );
502 const isTrail = (d,p) => ( d.pos + d.dim - INSETS <= p && p <= d.pos + d.dim ) ;
503 const inside = (x,y) => (g) => {
504 const dx = g.dx ;
505 const dy = g.dy ;
506 return ( dx.pos < x && x < dx.pos + dx.dim &&
507 dy.pos < y && y < dy.pos + dy.dim );
508 } ;
509
510 const targetAt = ( grid , x , y ) => {
511 if (!grid) return undefined;
512 const dx = grid.dx ;
513 const dy = grid.dy ;
514 let dir ;
515 switch( grid.kind ) {
516 case 'ITEM':
517 dir = quadrant(dx,dy,x,y);
518 break;
519 case 'HBOX':
520 if (isHead(dy,y)) { dir = 'NORTH'; break; }
521 if (isTrail(dy,y)) { dir = 'SOUTH'; break; }
522 return targetAt( grid.content.find(inside(x,y)), x , y );
523 case 'VBOX':
524 if (isHead(dx,x)) { dir = 'WEST'; break; }
525 if (isTrail(dx,x)) { dir = 'EAST'; break; }
526 return targetAt( grid.content.find(inside(x,y)), x , y );
527 }
528 return dir && Object.assign( { at:grid.id, dir } , makePosition(grid) ) ;
529 };
530
531 const TARGET_PLAIN = { at:'*', dir:'*', left:0, top:0 };
532
533 // --------------------------------------------------------------------------
534 // --- Resizing Events
535 // --------------------------------------------------------------------------
536
537 const onResizeStart = ({ id,resizer,dp,dq }) => {
538 dp.root = dp.dim ;
539 dq.root = dq.dim ;
540 freezeGrid( resizer.grid );
541 resizer.id = id ;
542 resizer.splitters = [resizer.splitters[id]] ;
543 resizer.element.setState({ resizer });
544 };
545
546 const onResizeDrag = ({ id,resizer,dp,dq },offset) => {
547 offset = Math.max( dp.min - dp.root , offset );
548 offset = Math.min( dq.root - dq.min , offset );
549 resizer.offset = offset ;
550 dp.drag = dp.root + offset ;
551 dq.drag = dq.root - offset ;
552 resizeGrid( resizer.grid );
553 resizer.element.forceUpdate();
554 };
555
556 const onResizeStop = ({ resizer }) => {
557 let shape = makeShapeOfGrid( resizer.grid );
558 resizer.element.setShape( shape );
559 };
560
561 const onResizeReset = ({ resizer }) => {
562 resizer.element.setShape( undefined );
563 };
564
565 // --------------------------------------------------------------------------
566 // --- Splitters & Targets
567 // --------------------------------------------------------------------------
568
569 const ITEMCLASS = 'dome-xGridLayout-item dome-container' ;
570 const HDRAGZONE = 'dome-xGridLayout-splitter dome-xGridLayout-hsplit dome-color-dragzone' ;
571 const HDRAGGING = 'dome-xGridLayout-splitter dome-xGridLayout-hdrag dome-color-dragging' ;
572 const VDRAGZONE = 'dome-xGridLayout-splitter dome-xGridLayout-vsplit dome-color-dragzone' ;
573 const VDRAGGING = 'dome-xGridLayout-splitter dome-xGridLayout-vdrag dome-color-dragging' ;
574
575 class HSPLIT extends React.Component {
576 render() {
577 let {x,y,width,height,...handler} = this.props ;
578 let id = handler.id ;
579 let { id:sid , offset=0 } = handler.resizer ;
580 return (
581 <DraggableCore
582 onStart={() => {
583 onResizeStart(handler);
584 this.forceUpdate();
585 }}
586 onDrag={(_evt,data) => {
587 onResizeDrag(handler,data.x - x + 2);
588 this.forceUpdate();
589 }}
590 onStop={() => onResizeStop(handler)}
591 >
592 <div className={ id === sid ? HDRAGGING : HDRAGZONE }
593 onClick={(evt) => evt.altKey && onResizeReset(handler)}
594 style={{ top:y, height, left:x+offset-2, width:4 }} />
595 </DraggableCore>
596 );
597 }
598 }
599
600 class VSPLIT extends React.Component {
601 render() {
602 let {x,y,width,height,...handler} = this.props ;
603 let id = handler.id ;
604 let { id:sid , offset=0 } = handler.resizer ;
605 return (
606 <DraggableCore
607 onStart={() => {
608 onResizeStart(handler);
609 this.forceUpdate();
610 }}
611 onDrag={(_evt,data) => {
612 onResizeDrag(handler,data.y - y + 2);
613 this.forceUpdate();
614 }}
615 onStop={() => onResizeStop(handler)}
616 >
617 <div className={ id === sid ? VDRAGGING : VDRAGZONE }
618 onDoubleClick={(evt) => evt.altKey && onResizeReset(handler)}
619 style={{ top:y+offset-2, height:4, left:x, width }} />
620 </DraggableCore>
621 );
622 }
623 }
624
625 const TARGET = ({target:{ dir,left,top,width,height }}) => {
626 switch(dir) {
627 case 'NORTH':
628 top = top - 3 ; height = 6 ;
629 break;
630 case 'SOUTH':
631 top = top + height - 3 ; height = 6 ;
632 break;
633 case 'WEST':
634 left = left -3 ; width = 6 ;
635 break;
636 case 'EAST':
637 left = left + width -3 ; width = 6 ;
638 break;
639 }
640 let style = { left, top, width, height };
641 return <div className='dome-xGridLayout-target' style={style} />;
642 };
643
644 const HOLDER = ({position}) => (
645 <div className='dome-xGridLayout-holder' style={position} />
646 );
647
648 const ELEMENT = ({id,className,style,children}) => (
649 <div key={id} className={className} style={style}>
650 { children }
651 </div>
652 );
653
654 // --------------------------------------------------------------------------
655 // --- Grid Splitters
656 // --------------------------------------------------------------------------
657
658 function splitSequence( d,ds,fn )
659 {
660 const n = ds.length || 0 ;
661 if (n<=0) return;
662 const dt = ds[n-1] ;
663 const dn = { resize:false, dim:0, min:0 };
664 const trail = d.room ;
665 if (trail > 0) {
666 dn.resize = true; dn.dim = trail;
667 let i,p,di ;
668 for (i = 0, p = -1; i < n; i++) {
669 di = ds[i];
670 p = di.resize ? i : p ;
671 if (p>=0) {
672 fn(di.pos+di.dim,ds[p],dn);
673 }
674 }
675 } else {
676 const dr = ds.slice(1).concat(dn);
677 const ps = Array(n);
678 const qs = Array(n);
679 let i,k ;
680 for (i = 0, k = -1; i < n; i++)
681 k = ps[i] = ds[i].resize ? i : k ;
682 for (i = n-1, k = -1; 0 <= i; i--)
683 k = qs[i] = dr[i].resize ? i : k ;
684 ds.forEach((di,i) => {
685 var p = ps[i];
686 var q = qs[i];
687 if (p>=0 && q>=0)
688 fn(di.pos+di.dim,ds[p],dr[q]);
689 });
690 }
691 }
692
693 function extendItem( d , fn ) {
694 if (d.resize && d.room > 0) {
695 const df = { resize:true, dim:d.room, min:0 };
696 fn(d.pos + d.dim,d,df);
697 }
698 };
699
700 function splitGrid( resizer,grid )
701 {
702 var SID = 0 ;
703 const splitters = resizer.splitters ;
704 const makeHsplit = (dy) => (x,dp,dq) => {
705 var id = SID++;
706 var s = (
707 <HSPLIT id={id} key={id} resizer={resizer}
708 x={x} y={dy.pos} height={dy.dim}
709 dp={dp} dq={dq}
710 />) ;
711 splitters.push(s);
712 };
713 const makeVsplit = (dx) => (y,dp,dq) => {
714 var id = SID++;
715 var s = (
716 <VSPLIT id={id} key={id} resizer={resizer}
717 x={dx.pos} y={y} width={dx.dim}
718 dp={dp} dq={dq}
719 />) ;
720 splitters.push(s);
721 };
722 function visit(g) {
723 if (!g) return;
724 switch(g.kind) {
725 case 'ITEM':
726 extendItem( g.dx , makeHsplit(g.dy) );
727 extendItem( g.dy , makeVsplit(g.dx) );
728 return;
729 case 'HBOX':
730 splitSequence( g.dx , g.dxs , makeHsplit(g.dy) );
731 g.content.forEach(visit);
732 return;
733 case 'VBOX':
734 splitSequence( g.dy , g.dys , makeVsplit(g.dx) );
735 g.content.forEach(visit);
736 return;
737 }
738 }
739 visit(grid);
740 }
741
742 // --------------------------------------------------------------------------
743 // --- Grid Elements
744 // --------------------------------------------------------------------------
745
746 const makePosition = ( {dx,dy}, padding=0 ) => ({
747 left: dx.pos + padding,
748 top: dy.pos + padding,
749 width: dx.dim - padding,
750 height: dy.dim - padding
751 });
752
753 function makeElement( render = ELEMENT, item, padding )
754 {
755 if (!item) return null;
756 const { id, content:{className:itemClass,style:itemStyle,children,...itemProps} } = item;
757 const position = makePosition( item, padding );
758 const className = itemClass ? ITEMCLASS + " " + itemClass : ITEMCLASS ;
759 const style = Object.assign( {}, itemStyle , position );
760 return render({id,className,style,children,...itemProps});
761 }
762
763 function orderElements( e1 , e2 )
764 {
765 let a = e1.key ;
766 let b = e2.key ;
767 if (!a || a < b) return -1;
768 if (!b || a > b) return 1;
769 return 0;
770 }
771
772 // --------------------------------------------------------------------------
773 // --- GridItem
774 // --------------------------------------------------------------------------
775
776 /**
777 @summary Elementary GridLayout Component.
778 @property {string} id - Component identifier
779 @property {boolean} display - Whether to mount the component
780 @property {number} width - Desired component width
781 @property {number} height - Desired component height
782 @property {number} minWidth - Minimum component width
783 @property {number} minHeight - Minium component height
784 @property {directions} [fill] - Direction(s) the component fills in
785 @property {directions} [resize] - Direction(s) the component can be resized in
786 @property {directions} [shrink] - Direction(s) the component can be shrinked in
787 @property {string} [className] - Additional class of the component
788 @property {string} [handle] - class name of the handler for dragging the component
789 @property {object} [style] - Additional style of the component
790 @property {React.children} children - grid item content
791 @description
792
793 The `id` property is mandatory for the GridLayout container
794 to property manage its different components. All items in the same GridLayout shall
795 have distinct identifiers.
796
797 Direction properties (with type `directions`) can take the following values:
798 `'none'`, `'horizontal'`, `'vertical'` or `'both'`.
799 */
800 export const GridItem = (props) => null;
801
802 // --------------------------------------------------------------------------
803 // --- Grid H/V Boxes
804 // --------------------------------------------------------------------------
805
806 /**
807 @property {ident} [id] - the box identifier
808 @property {direction} dir - either `'horizontal'` or `'vertical'`
809 @property {GridContent} [children] - internal grid contents
810 @summary Layout its content in an horizontal or vertical box.
811 @description
812
813 This container is a _fake_ component thats simply groups several
814 `GridItem`s or `GridBox`es horizontally or vertically.
815
816 It can be used only as direct children of `GridLayout`
817 and other `GridBox` containers.
818
819 See also:
820 - [[GridLayout]] top-level container
821 - [[GridItem]] elementary component
822 - [[GridHbox]] horizontal box
823 - [[GridVbox]] vertical box
824 */
825 export const GridBox = (props) => null ;
826
827 /**
828 [[GridBox]] with horizontal layout
829 @property {ident} [id] - the box identifier
830 */
831 export const GridHbox = (props) => null ;
832
833 /**
834 [[GridBox]] with vertical layout
835 @property {ident} [id] - the box identifier
836 */
837 export const GridVbox = (props) => null ;
838
839 // --------------------------------------------------------------------------
840 // --- User Grid & Components Extraction
841 // --------------------------------------------------------------------------
842
843 import { register, classOf } from 'dome/misc/register' ;
844
845 register(GridBox, 'DOME_GRIDLAYOUT_BOX');
846 register(GridHbox, 'DOME_GRIDLAYOUT_HBOX');
847 register(GridVbox, 'DOME_GRIDLAYOUT_VBOX');
848 register(GridItem, 'DOME_GRIDLAYOUT_ITEM');
849
850 /**
851 @summary Extract shape from GridChildren.
852 @parameter {GridChildren} children - Grid items elements arranged in grids
853 @parameter {direction} [dir] - default direction
854 @return {Shape} the associated shape
855 @description
856 Converts a React JSX-based grid of items into a Shape object.
857 */
858 export function makeChildrenShape( children, dir )
859 {
860 const makeEltShape = (elt) => {
861 let { id, width, height } = elt.props ;
862 return { kind: 'ITEM', id, width, height };
863 };
864
865 const makeBoxShape = (dir,elt) => {
866 let { id, children } = elt.props ;
867 let gs = makeShapes(children);
868 return makeShapeDir(dir,id,gs);
869 };
870
871 const makeShapes = (children) => {
872 return React.Children.map(children,(elt) => {
873 if (!elt) return null;
874 switch( classOf(elt) ) {
875 case 'DOME_GRIDLAYOUT_ITEM':
876 return makeEltShape(elt);
877 case 'DOME_GRIDLAYOUT_HBOX':
878 return makeBoxShape('horizontal',elt);
879 case 'DOME_GRIDLAYOUT_VBOX':
880 return makeBoxShape('vertical',elt);
881 case 'DOME_GRIDLAYOUT_BOX':
882 return makeBoxShape(elt.props.dir,elt);
883 default:
884 console.warn('[Dome.GridLayout] Unknown grid box', elt);
885 return null;
886 }
887 });
888 };
889
890 return makeShapeDir( dir, undefined, makeShapes(children) );
891 }
892
893 function makeChildrenGrid( dir, items, children, shape )
894 {
895 let kid = 0 ;
896 let index = {} ;
897
898 const indexElt = (elt) => {
899 let { id } = elt.props ;
900 let props = index[id];
901 if (!props) props = index[id] = {};
902 Object.assign( props , elt.props );
903 return props;
904 };
905
906 const makeGridElt = (elt) => makeGridItem(indexElt(elt));
907
908 const makeGridBox = (dir,elt) => {
909 let { id, children } = elt.props ;
910 if (!id) id = BOXID + (++kid) ;
911 return makeGridDir(dir,id,makeGrids(children));
912 };
913
914 const makeGrids = (children) => {
915 return React.Children.map(children,(elt) => {
916 if (!elt) return null;
917 switch( classOf(elt) ) {
918 case 'DOME_GRIDLAYOUT_ITEM':
919 return makeGridElt(elt);
920 case 'DOME_GRIDLAYOUT_HBOX':
921 return makeGridBox('horizontal',elt);
922 case 'DOME_GRIDLAYOUT_VBOX':
923 return makeGridBox('vertical',elt);
924 case 'DOME_GRIDLAYOUT_BOX':
925 return makeGridBox(elt.props.dir,elt);
926 default:
927 console.warn('[Dome.GridLayout] Unknown grid box', elt);
928 return null;
929 }
930 });
931 };
932
933 const makeShape = (s) => {
934 switch( s && s.kind ) {
935 case 'ITEM':
936 let props = index[ s.id ] ;
937 if (!props) return null;
938 index[ s.id ] = undefined ;
939 return makeGridItem( props, s.width, s.height );
940 case 'HBOX':
941 return makeGridHbox( s.id, s.content.map(makeShape) );
942 case 'VBOX':
943 return makeGridVbox( s.id, s.content.map(makeShape) );
944 default:
945 return null;
946 }
947 };
948
949 items && items.forEach && items.forEach( indexElt );
950
951 if (shape)
952 return makeShape(shape);
953 else
954 return makeGridDir(dir,BOXID,makeGrids(children));
955 }
956
957 // --------------------------------------------------------------------------
958 // --- GridLayout Core
959 // --------------------------------------------------------------------------
960
961 /**
962 @class
963 @summary Grid-based Flexible Container.
964 @property {direction} [dir] - Default children layout (`'horizontal'` or `'vertical'`)
965 @property {number} [padding] - Padding between items
966 @property {Shape} [shape] - The desired shape (defaults to children grid)
967 @property {GridItem[]} [items] - A collection of items (defaults to children items)
968 @property {GridContent} [children] - Grid items arranged in box (used for default items and shape)
969 @property {ident} [dragged] - Dragged item to materialize
970 @property {object} [dragging] - Dragging event to localize with `onTarget()`
971 @property {object} [target] - Insertion target to materialze
972 @property {function} [onReshape] - Callback with the updated shape
973 @property {function} [onTarget] - Callback when dragging is a valid target
974 @property {function} [render] - Rendering function for items
975 @property {React.ref} [targetRef] - Reference for D&D drop target
976 @description
977
978 Low-level GridLayout container, with only resizing capabilities.
979 Additional rendering options are available:
980
981 - `dragged` : item being dragged, materialized with a dragging background;
982 - `dragging` : current D&D event to notify `onTarget()` with;
983 - `target` : `{at,dir,left,top,width,height}` insertion position to materialize;
984 - `shape:Shape` : desired reshaping of the children grid;
985 - `onReshape(Shape)` : notified when grid content has been resized;
986 - `onTarget(Target)` : notified when `dragging` corresponds to a new target;
987 - `render({id,className,style,handle,children,...})` : rendering function for the provided item.
988
989 The rendering function shall return a keyed React element or fragment.
990 It receives all properties of the associated item to render, with
991 class and style merged with the `dome-xGridLayout-item` base class
992 and the absolute coordinates of the item inside the container.
993
994 */
995
996 export class GridLayoutCore extends React.Component
997 {
998
999 constructor(props) {
1000 super(props);
1001 this.state = {};
1002 }
1003
1004 setShape( newshape )
1005 {
1006 const { onReshape, shape } = this.props ;
1007 onReshape && onReshape(newshape);
1008 this.setState({ resizer:undefined });
1009 }
1010
1011 render() {
1012 const { targetRef, padding=0 } = this.props ;
1013 return (
1014 <div className='dome-xGridLayout' ref={targetRef}>
1015 <AutoSizer key='grid'>{({width,height}) => this.renderSized(width-padding,height-padding)}</AutoSizer>
1016 </div>
1017 );
1018 }
1019
1020 renderSized(width, height)
1021 {
1022 const { dragged } = this.props ;
1023 const { resizer:resizing } = this.state ;
1024 let grid,markers=[] ;
1025 if (resizing) {
1026 // When Resizing
1027 grid = resizing.grid ;
1028 markers = resizing.splitters ;
1029 layoutGrid(grid,width,height);
1030 } else {
1031 const {
1032 shape, dir,
1033 dragging, onTarget,
1034 items, children
1035 } = this.props ;
1036 // Compute Layout
1037 grid = makeChildrenGrid( dir, items, children, shape );
1038 if (grid) layoutGrid(grid,width,height);
1039 // Compute Dragging & notify Target
1040 let targetted ;
1041 if (dragging) {
1042 if (grid) {
1043 const r = dragging.targetClientRect ;
1044 if (r) {
1045 const x = dragging.clientX - r.left ;
1046 const y = dragging.clientY - r.top ;
1047 targetted = targetAt( grid, x, y );
1048 }
1049 } else {
1050 targetted = Object.assign( { width, height } , TARGET_PLAIN ) ;
1051 }
1052 }
1053 if (onTarget) {
1054 const { at,dir } = targetted || {} ;
1055 const held = dragging ? dragging.held : false ;
1056 if ( this.targetAt !== at ||
1057 this.targetDir !== dir ||
1058 this.targetHeld !== held )
1059 {
1060 this.targetAt = at ;
1061 this.targetDir = dir ;
1062 this.targetHeld = held ;
1063 if (targetted) targetted.shape = makeShapeOfGrid(grid);
1064 setImmediate(() => onTarget(targetted));
1065 }
1066 }
1067 const { target } = this.props ;
1068 if (target && target.at !== dragged) {
1069 markers.push( <TARGET key='target' target={target}/> );
1070 }
1071 if (grid && !dragging && !target) {
1072 // Splitters
1073 splitGrid( { grid,element:this,splitters:markers } ,grid );
1074 }
1075 }
1076 const elements = [];
1077 const { render, padding } = this.props ;
1078 iter(grid,(item) => {
1079 let e = makeElement(render,item,padding);
1080 if (e) elements.push(e);
1081 if (dragged && dragged === item.id)
1082 markers.push(<HOLDER key='holder' position={makePosition(item)}/>);
1083 });
1084 return [
1085 (<React.Fragment key='items'>{elements.sort(orderElements)}</React.Fragment>),
1086 (<React.Fragment key='markers'>{markers}</React.Fragment>)
1087 ];
1088 };
1089 }
1090
1091 // --------------------------------------------------------------------------
1092 // --- GridLayout Full
1093 // --------------------------------------------------------------------------
1094
1095 const positionOfStyle = ({left,top,width,height}) => ({left,top,width,height});
1096
1097 const DRAGGABLEITEM =
1098 (dnd,anchor,onSelfDrag,insert) =>
1099 ({id,className,style,handle,children}) =>
1100 ( id === insert
1101 ? ( <HOLDER key='DOME$holder' position={positionOfStyle(style)}/> )
1102 : (
1103 <DragSource
1104 key={id}
1105 dnd={dnd}
1106 handle={handle}
1107 onStart={() => onSelfDrag(id,{x:style.left,y:style.top})}
1108 >
1109 {(dragging) => {
1110 let theStyle = style ;
1111 if (dragging && anchor) {
1112 theStyle = Object.assign( {} , style );
1113 theStyle.left = anchor.x + dragging.deltaX ;
1114 theStyle.top = anchor.y + dragging.deltaY ;
1115 className += ' dome-dragging' ;
1116 }
1117 return (<div className={className} style={theStyle}>{children}</div>);
1118 }}
1119 </DragSource>
1120 )
1121 );
1122
1123 /**
1124 @class
1125 @summary Grid Container.
1126 @property {direction} [dir] - Default children layout (`'horizontal'` or `'vertical'`)
1127 @property {number} [padding] - Padding between items
1128 @property {Shape} [shape] - The desired shape (defaults to children grid)
1129 @property {GridItem[]} [items] - A collection of items (defaults to children items)
1130 @property {Grid} [children] - Grid items arranged in box (used for default items and shape)
1131 @property {string} [settings] - User-settings key for making the shape persistent
1132 @property {DnD} [dnd] - Optional D&D controller to be used
1133 @property {GridItem} [holding] - Dragged external element
1134 @property {function} [onTarget] - Callback for dragged target proposal
1135 @property {function} [onReshape] - Callback on reshaping self content
1136 @property {function} [onInsert] - Callback on dropping the holding element
1137 @property {function} [onDnd] - Callback on D&D events
1138 @property {function} [onXxx] - Other D&D callback events
1139 @description
1140
1141 Layout several components with nested vertical and horizontal boxes.
1142
1143 Direct children of the container must be either:
1144 - [[GridBox]] and its derivated
1145 - [[GridItem]] for elementary component
1146
1147 Top-level children are laidout vertically (default) or horizontally according
1148 to the `dir` property. Nested boxes of same directions are flattened,
1149 and singleton boxes simply lift-up their content into their parent box.
1150
1151 You may dynamically change the box hierarchy, without causing unmounting
1152 and re-monting the different items. Actually, the container renders all
1153 the collected `GridItem` elements as a flat array ordered by keys.
1154
1155 All item specifications are taken from the provided items. However, the grid
1156 layout of the items is taken from the provided shape, the settings of the
1157 children grix boxes, in this order of priority. Extra items or missing items are
1158 simply ignored from the shape taken into account.
1159
1160 GridLayout containers can be used as drop targets, both for re-arranging
1161 internal grid items, or to insert external drag sources inside.
1162 If you supply an external [[DnD]] controller,
1163 the GridLayout will register itself as a drop target. Otherwize, it will
1164 use its own controller.
1165
1166 The callbacks `onReshape` and `onTarget` are invoked on drag and drop operations:
1167 - `onReshape(Shape)` is invoked when the grid elements are resized or rearranged;
1168 - `onTarget(Target)` in invoked when a drag source targets an element of the grid;
1169 - `onInsert(Shape,Target)` when a drag source is dropped inside the grid, at some
1170 target position, possibly resulting in the given new shape.
1171
1172 When dragging a source over the grid, the grid element specified by the `holding`
1173 property of the grid is used to materialize the insertion of the dragged source
1174 inside the grid. To decline a dragging operation, the `onTarget()` must return a
1175 falsy value other than `undefined` (eg: `false`).
1176
1177 A `Target` is a plain serialisable object with the following properties:
1178 - `at:ident` the box or item identifier where to insert the target,
1179 or `'*'` when targetting an empty shape;
1180 - `dir:'NORTH'|'EAST'|'SOUTH'|'WEST'` the direction to insert the target item along,
1181 or `'*'` when targetting an empty shape;
1182 - `id:ident` the inserted item identifier.
1183
1184 A `Shape` is a plain serializable object with the following properties:
1185 - `{ kind:'HBOX', id, content: [Shape,…] }` for horizontal boxes,
1186 - `{ kind:'VBOX', id, content: [Shape,…] }` for vertical boxes,
1187 - `{ kind:'ITEM', id, height, width }` for leaf items.
1188
1189 */
1190 export class GridLayout extends React.Component
1191 {
1192
1193 constructor(props) {
1194 super(props);
1195 this.state = {};
1196 this.dnd = this.props.dnd || new DnD();
1197 this.onReloadSettings = this.onReloadSettings.bind(this);
1198 this.onReshape = this.onReshape.bind(this);
1199 this.onTarget = this.onTarget.bind(this);
1200 this.onSelfDrag = this.onSelfDrag.bind(this);
1201 this.onDnd = this.onDnd.bind(this);
1202 this.container = React.createRef();
1203 }
1204
1205 componentDidMount() {
1206 // DEPRECATED
1207 Settings.onWindowSettings(this.onReloadSettings);
1208 }
1209
1210 componentWillUnmont() {
1211 // DEPRECATED
1212 Settings.offWindowSettings(this.onReloadSettings);
1213 }
1214
1215 computeTargetProposal(target) {
1216 if (!target) return undefined;
1217 const { at,dir } = target ;
1218 const { dragged } = this.state ;
1219 if (dragged)
1220 return at === dragged ? undefined : { id:dragged,at,dir };
1221 else {
1222 const { holding } = this.props ;
1223 const id = holding && holding.props && holding.props.id ;
1224 return at === id ? undefined : { id,at,dir };
1225 }
1226 }
1227
1228 computeNewShapeForTarget(target) {
1229 if (!target) return [];
1230 const { shape,at,dir } = target ;
1231 const { holding } = this.props ;
1232 const { dragged,inserted:oldInsert } = this.state ;
1233 let item,inserted,newShape ;
1234 if (dragged) {
1235 item = get(shape,dragged);
1236 newShape = makeShapeInsert( shape, at, dir, item );
1237 }
1238 else if (holding && holding.props) {
1239 const { id,width,height } = holding.props ;
1240 if (at === id) {
1241 inserted = oldInsert ;
1242 newShape = shape ;
1243 } else {
1244 inserted = { at,dir,id } ;
1245 item = { kind:'ITEM',id,width,height };
1246 newShape = makeShapeInsert( shape,at,dir,item );
1247 }
1248 }
1249 return [inserted,newShape];
1250 }
1251
1252 onReloadSettings() {
1253 const { settings, onReshape } = this.props ;
1254 if (!settings) return;
1255 const newShape = Settings.getWindowSettings( settings, Json.jAny, undefined );
1256 this.setState({ shape: newShape });
1257 if (onReshape) onReshape( newShape );
1258 }
1259
1260 onReshape(newShape) {
1261 const { settings, shape:setShape, onReshape } = this.props ;
1262 if (!setShape) this.setState({ shape: newShape });
1263 if (settings) Settings.setWindowSettings( settings, newShape );
1264 if (onReshape) onReshape( newShape );
1265 }
1266
1267 onTarget(newTarget) {
1268 const proposal = this.computeTargetProposal(newTarget);
1269 if (!proposal) this.setState({target:undefined});
1270 else {
1271 const { onTarget } = this.props ;
1272 const { held } = this.state ;
1273 const approval = onTarget && onTarget(proposal) ;
1274 const valid = approval === undefined || approval ;
1275 if (valid) {
1276 if ( held ) {
1277 const [inserted,holdedShape] = this.computeNewShapeForTarget(newTarget);
1278 this.setState({held:false,target:undefined,inserted,holdedShape});
1279 } else
1280 this.setState({target: newTarget});
1281 } else
1282 this.setState({target: undefined});
1283 };
1284 }
1285
1286 // Self dragged callback, see DRAGGABLEITEM
1287 onSelfDrag(dragged,anchor) {
1288 this.setState({ dragged, anchor });
1289 }
1290
1291 // Generic D&D event
1292 onDnd(dragging) {
1293 dispatchEvent(dragging,this.props);
1294 switch( dragging && dragging.move ) {
1295 case 'HOLD': this.setState({held: true}); break;
1296 case 'MOVE': this.setState({held: false}); break;
1297 case 'DROP':
1298 let { target, inserted, holdedShape:shape } = this.state ;
1299 if (target)
1300 [inserted,shape] = this.computeNewShapeForTarget(target);
1301 if (inserted) {
1302 const { onInsert } = this.props ;
1303 const callback = onInsert || this.onReshape ;
1304 callback && callback(shape,inserted);
1305 } else {
1306 shape && this.onReshape(shape);
1307 }
1308 // Continue on 'STOP'
1309 case 'STOP':
1310 this.setState({
1311 dragged: undefined,
1312 anchor: undefined,
1313 target: undefined,
1314 held: undefined,
1315 inserted: undefined,
1316 holdedShape: undefined
1317 });
1318 break;
1319 }
1320 }
1321
1322 render() {
1323 const { shape:propShape, dir, items, children, holding, padding, settings } = this.props ;
1324 const { shape:newShape, target, dragged, anchor, holdedShape, inserted } = this.state ;
1325 const setShape = propShape === null ? {} : propShape ;
1326 const insert = inserted ? inserted.id : undefined ;
1327 const render = DRAGGABLEITEM(this.dnd,anchor,this.onSelfDrag,insert);
1328 const shape = holdedShape || setShape || newShape ||
1329 Settings.getWindowSettings(settings,Json.jAny,undefined) ;
1330 return (
1331 <DropTarget
1332 dnd={this.dnd}
1333 targetRef={this.container}
1334 onDnd={this.onDnd}
1335 >
1336 {(dragging) => (
1337 <GridLayoutCore
1338 targetRef={this.container}
1339 dir={dir}
1340 padding={padding}
1341 shape={shape}
1342 items={items}
1343 dragging={dragging}
1344 onReshape={this.onReshape}
1345 onTarget={this.onTarget}
1346 dragged={dragged}
1347 target={target}
1348 render={render}
1349 >
1350 {children}
1351 {inserted ? holding : null}
1352 </GridLayoutCore>
1353 )}
1354 </DropTarget>
1355 );
1356 }
1357 }
1358
1359 // --------------------------------------------------------------------------