forked from folio-org/stripes-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaneset.js
602 lines (545 loc) · 19 KB
/
Paneset.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import React from 'react';
import PropTypes from 'prop-types';
import { pickBy, uniqueId, cloneDeep, debounce, isEqual } from 'lodash';
import parseCSSUnit from '../../util/parseCSSUnit';
import insertByClientRect from './insertByClientRect';
import css from './Paneset.css';
import PaneResizeContainer from './PaneResizeContainer';
import { withPaneset, PanesetContext } from './PanesetContext';
const defaultProps = {
defaultWidth: 'fill',
onLayout: () => null,
initialLayouts: [],
};
function getNewPanewidthObject(key, CSSvalue, proportionalChange) {
const unit = parseCSSUnit(CSSvalue);
let newWidth = CSSvalue;
switch (unit) {
case 'percent':
newWidth = parseFloat(CSSvalue, 10) * proportionalChange;
newWidth = `${newWidth}%`;
break;
case 'vw': break;
case 'px':
newWidth = Math.ceil(parseInt(CSSvalue, 10) * proportionalChange);
newWidth = `${newWidth}px`;
break;
case 'em':
newWidth = Math.ceil(parseInt(CSSvalue, 10) * 14 * proportionalChange);
newWidth = `${newWidth / 14}em`;
break;
case 'rem':
newWidth = Math.ceil(parseInt(CSSvalue, 10) * 14 * proportionalChange);
newWidth = `${newWidth / 14}rem`;
break;
default: break;
}
return {
id: key,
defaultWidth: newWidth,
};
}
class Paneset extends React.Component {
static propTypes = {
// panes and other things that render panes..
children: PropTypes.node,
// if necessary, Paneset can be assigned a percentage width.
defaultWidth: PropTypes.string,
// id attribute applied to outer <div>.
id: PropTypes.string,
// used to initialize Layout Cache of paneset widths
initialLayouts: PropTypes.arrayOf(PropTypes.object),
// this paneset will not report itself to an ascendent paneset
isRoot: PropTypes.bool,
// applies styling to properly nest the paneset
nested: PropTypes.bool,
// callback for overriding layout from the application level
onLayout: PropTypes.func,
// callback when panes are resized by the user.
onResize: PropTypes.func,
// the parent paneset of the current paneset
paneset: PropTypes.shape({
getTopmostContainer: PropTypes.func,
handleClose: PropTypes.func,
registerPane: PropTypes.func,
removePane: PropTypes.func,
}),
// set if the height of the paneset needs to be controlled.
static: PropTypes.bool,
}
constructor(props) {
super(props);
let initStyle = {};
// Set fixed width only for panes with the counted value
if (this.props.defaultWidth !== 'fill') {
initStyle = { flex: `0 0 ${this.props.defaultWidth}` };
}
this.state = {
paneManager: {
handleClose: this.handleClose,
registerPane: this.registerPane,
removePane: this.removePane,
getContainer: this.getContainer,
getTopmostContainer: this.getTopmostContainer,
},
panes: [],
layoutCache: props.initialLayouts,
style: initStyle,
changeType: 'init',
};
this.container = React.createRef();
this.resizeContainer = React.createRef();
this.id = props.id || uniqueId('paneset-');
this.widths = [];
this.interval = null;
this._isMounted = false;
}
componentDidMount() {
if (!this.props.isRoot) {
if (this.props.paneset) { // register with parent paneset if it exists
this.props.paneset.registerPane({
id: this.id,
setStyle: this.setStyle,
getChildInfo: this.getChildInfo,
isThisMounted: this.isThisMounted,
isPaneset: true,
transition: 'none',
doTransition: false,
getRef: this.getRef,
getInstance: this.getInstance,
handlePaneResize: this.handlePaneResize
});
}
}
this._isMounted = true;
this.resizeHandler = window.addEventListener('resize', debounce(this.handleWindowResize, 50));
this.previousContainerWidth = this.container.current.getBoundingClientRect().width;
}
componentWillUnmount() {
this._isMounted = false;
window.removeEventListener('resize', this.resizeHandler);
if (this.widthsRAF) {
cancelAnimationFrame(this.widthsRAF);
this.widthsRAF = null;
}
if (this.resizeNestedTO) {
clearTimeout(this.resizeNestedTO);
this.resizeNestedTO = null;
}
if (this.transitionCallbackTO) {
clearTimeout(this.transitionCallbackTO);
this.transitionCallbackTO = null;
}
if (this.interval) {
clearTimeout(this.interval);
this.interval = null;
}
if (!this.props.isRoot && this.props.paneset) {
this.props.paneset.removePane(false);
}
}
resizeToContainer = () => {
// pick the active layout cache entry - will contain matching id's and number of id's...
const paneIds = [];
this.state.panes.forEach((p) => paneIds.push(p.id));
const matchingCacheIndex = this.state.layoutCache.findIndex((c) => isEqual(Object.keys(c), paneIds));
if (matchingCacheIndex !== -1) {
const matchingLCache = this.state.layoutCache[matchingCacheIndex];
// set array up with defaultWidth and id...pass to calc widths.
const tempPanesList = [];
let currentWidth;
if (!this.props.paneset) {
currentWidth = window.innerWidth;
} else {
currentWidth = this.container.current?.getBoundingClientRect().width;
}
if (currentWidth) {
let totalWidth = 0;
// get an actual width of the paneset...
this.state.panes.forEach((p) => {
const elem = p.getRef();
if (elem.current) { totalWidth += elem.current.getBoundingClientRect().width; }
});
// check actual width against width of containing element... this prevents continued proportional resizes.
if (Math.floor(totalWidth) !== currentWidth) {
const proportionalChange = currentWidth / totalWidth;
for (const p in matchingLCache) {
if (Object.prototype.hasOwnProperty.call(matchingLCache, p)) {
const newPO = getNewPanewidthObject(p, matchingLCache[p], proportionalChange);
tempPanesList.push(newPO);
}
}
// be sure and update the so that we can use this on the next resize...
this.previousContainerWidth = currentWidth;
this.setState((curr) => {
const tempCache = cloneDeep(curr.layoutCache);
tempCache.splice(matchingCacheIndex, 1);
return {
layoutCache: tempCache,
};
}, () => {
// // adjust the layout cache relative to the new client rect size
// // size panes accordingly.
const newWidths = this.calcWidths(tempPanesList);
const changeType = 'windowResize';
this.updateLayoutCache(newWidths, changeType);
this.resizePanes(this.state.panes, newWidths);
this.resizeNestedTO = setTimeout(() => {
this.state.panes.forEach((p) => {
if (p.isPaneset) {
p.getInstance().resizeToContainer();
}
});
});
});
}
}
}
}
handleWindowResize = () => {
const {
isRoot,
paneset
} = this.props;
if (isRoot || !paneset) {
this.resizeToContainer();
}
}
isThisMounted = () => this._isMounted;
getContainer = () => this.container.current;
getTopmostContainer = () => {
const { paneset, isRoot } = this.props;
if (!isRoot && paneset) {
return paneset.getTopmostContainer();
}
return this.getContainer();
}
getClassName = () => {
const nested = this.props.nested ? css.nested : '';
const staticClass = this.props.static === true ? css.static : '';
const base = css.paneset;
return `${base} ${nested} ${staticClass}`;
}
setStyle = (style) => {
if (this.isThisMounted()) {
this.setState((oldState) => {
const newState = oldState;
// clone because you can't mutate style....
const newStyle = Object.assign({}, newState.style, style);
newState.style = newStyle;
newState.changeType = 'paneset-resized';
return newState;
});
}
}
resizePanes = (panes, widths) => {
panes.forEach((pane) => {
const styleObject = { flex: `0 0 ${widths[pane.id]}` };
if (!pane.transitioning) {
styleObject.left = '0px';
}
pane.setStyle(styleObject);
});
}
removePane = (shouldResize = true) => {
this.setState((oldState) => {
// accounts for odd situations where multiple Panes are dismissed/dismounted at once...
// simply filters out any that have dismounted.
const newPanes = oldState.panes.filter(p => p.isThisMounted());
const newState = Object.assign({}, oldState);
newState.panes = newPanes;
newState.changeType = 'removed';
return newState;
}, () => {
if (shouldResize) this.calcWidthsAndResize('removed');
});
}
// transitions
// set up initial state for transitions...(register)
// measurements still in state where new pane isn't there...
// apply 'in' state for transitions...
// measurements with added pane
// Closing...
// apply 'out' state with callback to remove pane...
registerPane = (paneObject) => {
this.setState((oldState) => {
let newState = Object.assign({}, oldState);
// if the new pane has a transition just set its starting appearance...
// otherwise resize all the panes...
if (paneObject.transition !== 'none') {
this.transitionStart(paneObject);
this.resizePanes(newState.panes, this.widths); // pass cached widths
newState.panes.push(paneObject);
this.interval = setTimeout(() => {
this.transitionEnd(paneObject);
this.interval = null;
});
} else {
// insert sorted by left coordinate of clientrect...
const newPanes = insertByClientRect(newState.panes, paneObject);
newState = Object.assign(newState, { panes: newPanes, changeType: 'added' });
// newState = this.insertPaneObject(newState, paneObject);
}
return newState;
}, () => {
this.calcWidthsAndResize('added');
});
}
// sometimes the cached sizes might not match up to the actual container due to different sized window.
// If that's true, scale the cached sizes accordingly.
resizeCachedSizesToFit = (layoutIndex) => {
const { layoutCache } = this.state;
const { paneset } = this.props;
const layoutObject = layoutCache[layoutIndex];
if (!paneset) {
// sum the pixels...
let totalWidth = 0;
let value;
for (const p in layoutObject) {
if (layoutObject[p]) {
const unit = parseCSSUnit(layoutObject[p]);
if (unit === 'px') {
value = Math.ceil(parseInt(layoutObject[p], 10));
totalWidth += value;
} else if (unit === 'percent') {
value = (parseFloat(layoutObject[p], 10) / 100) * (this.containerWidth || window.innerWidth);
totalWidth += value;
} else {
return null;
}
}
}
// if the window size has not changed, the cached pane widths may still need to be validated...
if (Math.abs(this.previousContainerWidth - window.innerWidth) < 1) {
if (Math.abs(this.previousContainerWidth - totalWidth) > 1) {
let newCacheObject = {};
const proportion = this.previousContainerWidth / totalWidth;
for (const p in layoutObject) {
if (layoutObject[p]) {
const newWidth = getNewPanewidthObject(p, layoutObject[p], proportion);
newCacheObject = { ...newCacheObject, [newWidth.id]: newWidth.defaultWidth };
}
}
this.previousContainerWidth = window.innerWidth;
return newCacheObject;
} else {
return layoutCache[layoutIndex];
}
} else {
this.resizeToContainer();
}
}
return null;
}
calcWidthsAndResize = (changeType) => {
this.widthsRAF = requestAnimationFrame(() => {
let widths;
const nextLayout = {};
this.state.panes.forEach(p => { nextLayout[p.id] = 0; });
const sizesCached = this.hasCachedLayout(nextLayout);
const toApply = this.props.onLayout({
changeType,
nextLayout,
layoutCached: (sizesCached === -1),
layoutCache: this.state.layoutCache,
widths: sizesCached !== -1 ? null : this.state.layoutCache[sizesCached],
});
if (toApply && sizesCached === -1) {
widths = toApply;
} else if (sizesCached !== -1) {
widths = this.resizeCachedSizesToFit(sizesCached) || this.state.layoutCache[sizesCached];
} else {
widths = this.calcWidths(this.state.panes);
}
this.resizePanes(this.state.panes, widths);
// check if the panes all have stable id's before caching their sizes.
if (this.state.panes.every((p) => p.hasGeneratedId === false)) {
this.updateLayoutCache(widths, changeType);
}
});
}
transitionStart = (pane) => {
if (pane.transition === 'slide') {
const styleObject = {};
if (!Number.isNaN(parseInt(pane.defaultWidth, 10))) {
styleObject.flex = `0 0 ${pane.defaultWidth}`;
}
styleObject.left = '100vw';
styleObject.transition = 'left .25s ease';
pane.transitioning = true;
pane.setStyle(styleObject);
}
}
transitionEnd = (pane) => {
pane.transitioning = false;
this.calcWidthsAndResize('endedTransition');
}
isRegistered = (id) => {
const pane = this.state.panes.filter(p => p.id === id)[0];
return !!pane;
}
handleClose = (id, callback) => {
const pane = this.state.panes.filter(p => p.id === id)[0];
if (pane.transition !== 'none') {
this.transitionStart(pane);
this.removePane();
this.transitionEnd(pane);
if (callback) {
this.transitionCallbackTO = setTimeout(() => {
callback();
}, 300);
}
} else {
this.removePane();
if (callback) { callback(); }
}
}
calcWidths = (panes) => { // find all static widths.
let staticSpace = 0;
const dynamics = [];
const widths = {};
const container = this.getContainer();
if (!container) {
this.widths = widths;
return widths;
}
const containerWidth = container.offsetWidth;
panes.forEach((pane) => {
if (pane.staticWidth) {
staticSpace += pane.staticWidth;
} else {
const currentPaneWidth = parseInt(pane.defaultWidth, 10);
// if we can't get an int from default width, it's something dynamic like 'fill'
if (Number.isNaN(currentPaneWidth)) {
dynamics.push(pane.id);
} else {
// parse unit
const unit = parseCSSUnit(pane.defaultWidth);
// convert to pixels
let parsedWidth;
switch (unit) {
case 'percent':
case 'vw':
parsedWidth = currentPaneWidth * 0.01 * containerWidth;
break;
case 'px':
parsedWidth = currentPaneWidth;
break;
case 'em':
case 'rem':
// system rem of 14
parsedWidth = currentPaneWidth * 14;
break;
default:
parsedWidth = currentPaneWidth;
}
staticSpace += parsedWidth;
pane.staticWidth = parsedWidth;
}
}
});
const staticPercent = ((containerWidth - staticSpace) / containerWidth) * 100;
const basePercentage = staticPercent / Math.max(Object.keys(dynamics).length, 1);
panes.forEach((pane, i) => {
if (dynamics.indexOf(pane.id) !== -1) {
widths[pane.id] = `${basePercentage}%`;
} else {
widths[pane.id] = panes[i].defaultWidth;
}
});
this.widths = widths;
return widths;
}
getRef = () => this.container;
getInstance = () => this;
hasCachedLayout = (candidate) => {
const layoutIndex = this.state.layoutCache.findIndex((cache) => {
const cacheKeys = Object.keys(cache);
const candidateKeys = Object.keys(candidate);
if (cacheKeys.length === candidateKeys.length) {
return cacheKeys.every(ck => candidateKeys.indexOf(ck) !== -1);
}
return false;
});
return layoutIndex;
};
updateLayoutCache = (layoutMap) => {
if (this.isThisMounted()) {
this.setState(({ layoutCache }) => {
// find duplicates with like lengths, id's...
const layoutIndex = this.hasCachedLayout(layoutMap);
if (layoutIndex !== -1) {
const tempCache = cloneDeep(layoutCache);
tempCache[layoutIndex] = layoutMap;
return {
layoutCache: tempCache
};
}
return { layoutCache: [...layoutCache, layoutMap], changeType: 'resize' };
}, () => {
if (this.props.onResize) {
this.props.onResize({
currentLayout: layoutMap,
layoutCache: this.state.layoutCache
});
}
});
}
}
// Accepts the positions of handles, the client rect of the container.
handlePaneResize = ({ positions, containerRect, ...rest }) => {
const { panes } = this.state;
const newWidths = {};
const otherWidths = [];
positions.forEach((pos, i) => {
const nextPos = positions[i + 1];
const positionBounds = nextPos ? nextPos.x : containerRect.width;
if (panes.findIndex(p => p.id === pos.elementId) !== -1) {
const newWidth = `${positionBounds - pos.x}px`;
newWidths[pos.elementId] = newWidth;
} else {
// other widths remain as numbers for future math (no css unit yet)
otherWidths.push(positionBounds - pos.x);
}
});
const panesetIndex = panes.findIndex(p => p.isPaneset);
if (panesetIndex !== -1) {
// sum the other widths as a paneset width...
const paneSetWidth = otherWidths.reduce((sum, w) => sum + w, 0);
const panesetId = panes[panesetIndex].id;
newWidths[panesetId] = paneSetWidth;
panes[panesetIndex].handlePaneResize({ positions, containerRect, ...rest });
}
this.resizePanes(panes, newWidths);
// check if the panes all have stable id's before caching their sizes.
if (this.state.panes.every((p) => p.generatedId === false)) {
this.updateLayoutCache(newWidths, 'resize');
}
}
render() {
const {
id,
children,
paneset,
isRoot
} = this.props;
// pull any data-test-* props into a spreadable object
const dataProps = pickBy(this.props, (val, key) => /^data-test/.test(key));
return (
<PanesetContext.Provider value={this.state.paneManager}>
<PaneResizeContainer
isRoot={isRoot || !paneset}
parentElement={this.container?.current}
onElementResize={this.handlePaneResize}
resizeContainerRef={this.resizeContainer}
>
<div className={this.getClassName()} id={id} style={this.state.style} ref={this.container} {...dataProps}>
{children}
</div>
</PaneResizeContainer>
</PanesetContext.Provider>
);
}
}
Paneset.defaultProps = defaultProps;
export default withPaneset(Paneset);