-
Notifications
You must be signed in to change notification settings - Fork 2
/
code_blocks.js
2241 lines (2003 loc) · 79.5 KB
/
code_blocks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import _ from 'lodash';
import classNames from 'classnames';
import memoizeOne from 'memoize-one';
import * as React from 'react';
import {BigNumber} from 'bignumber.js';
import low from 'lowlight/lib/core';
import unified from 'unified';
import rehypestringify from 'rehype-stringify';
import pythonHl from 'highlight.js/lib/languages/python';
low.registerLanguage('python', pythonHl);
import HighLightJStyle from 'highlight.js/styles/default.css';
import Slider from 'rc-slider/lib/Slider';
import 'rc-slider/assets/index.css';
import SmoothScrollbar from 'react-smooth-scrollbar';
import {MyErrorBoundary, getUxSettings, DebounceWhenOutOfView, RED, BLUE, isDefinedSmallBoxScreen} from './util';
import {isNone, isDummy, repr, displayStr} from './hash_impl_common';
import {globalSettings} from './store';
import {observer} from 'mobx-react';
import {library} from '@fortawesome/fontawesome-svg-core';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faPlay} from '@fortawesome/free-solid-svg-icons/faPlay';
import {faStepForward} from '@fortawesome/free-solid-svg-icons/faStepForward';
import {faStepBackward} from '@fortawesome/free-solid-svg-icons/faStepBackward';
import {faFastForward} from '@fortawesome/free-solid-svg-icons/faFastForward';
import {faFastBackward} from '@fortawesome/free-solid-svg-icons/faFastBackward';
import {faPause} from '@fortawesome/free-solid-svg-icons/faPause';
import {faRedoAlt} from '@fortawesome/free-solid-svg-icons/faRedoAlt';
import {
List as ImmutableList,
Map as ImmutableMap,
fromJS as immutableFromJS,
Record as ImmutableRecord,
} from 'immutable';
library.add(faPlay);
library.add(faStepForward);
library.add(faStepBackward);
library.add(faFastForward);
library.add(faFastBackward);
library.add(faPause);
library.add(faRedoAlt);
function reflow(node) {
if (!node) {
console.error('Not reflowing non-existant node!');
return;
}
node && node.scrollTop;
}
function renderPythonCode(codeString) {
let lowAst = low.highlight('python', codeString).value;
const processor = unified().use(rehypestringify);
return processor.stringify({
type: 'root',
children: lowAst,
});
}
export function dummyFormat(bp) {
/* return JSON.stringify(bp); */
return '';
}
export function SimpleCodeBlock(props) {
return (
<pre className="simple-code-block hl-left pl-2">
<code dangerouslySetInnerHTML={{__html: renderPythonCode(props.children)}} />
</pre>
);
}
export function SimpleCodeInline(props) {
return <code dangerouslySetInnerHTML={{__html: renderPythonCode(props.children)}} />;
}
export const DEFAULT_BOX_GEOMETRY = {
boxGeometry: {boxSize: 40, boxPadding: 2, spacingX: 1, spacingY: 5, fontSize: 12, borderRadius: 10},
labelFontSize: 16,
};
export const SMALLER_BOX_GEOMETRY = {
boxGeometry: {boxSize: 30, boxPadding: 1, spacingX: 1, spacingY: 4, fontSize: 9, borderRadius: 7.5},
labelFontSize: 12,
};
export const LARGER_BOX_GEOMETRY = {
boxGeometry: {boxSize: 50, boxPadding: 1, spacingX: 1, spacingY: 4, fontSize: 15, borderRadius: 12},
labelFontSize: 16,
};
function computeBoxTransformProperty(idx, y, boxSize, spacingX, z = 0) {
let x = (spacingX + boxSize) * idx;
return `translate3d(${x}px, ${y}px, ${z}px)`;
}
function pyObjToReactKey(obj) {
return repr(obj, false);
}
class ActiveBoxSelectionUnthrottled extends React.PureComponent {
render() {
let {extraClassName, idx, status, transitionDuration, color, boxSize, spacingX, borderRadius} = this.props;
let yOffset = this.props.yOffset || 0;
const animatedClass = 'active-box-selection-animated';
let classes = ['active-box-selection', extraClassName, animatedClass];
let opacity;
switch (status) {
case 'removing':
opacity = 0;
break;
case 'created':
opacity = 0.15;
break;
case 'adding':
opacity = 1;
break;
}
const style = {
opacity: opacity,
transitionDuration: `${transitionDuration}ms`,
borderColor: color,
width: boxSize,
height: boxSize,
borderRadius,
// TODO: the part after : is weird/wrong
transform: idx != null ? computeBoxTransformProperty(idx, yOffset, boxSize, spacingX) : undefined,
};
return <div ref={this.props.setInnerRef} className={classNames(classes)} style={style} />;
}
}
class ActiveBoxSelectionThrottledHelper extends React.Component {
handleRef = node => {
this.node = node;
};
render() {
let {idx, status, extraClassName, yOffset, color, boxSize, spacingX, borderRadius} = this.props;
return (
<ActiveBoxSelectionUnthrottled
setInnerRef={this.handleRef}
extraClassName={extraClassName}
idx={idx}
status={status}
yOffset={yOffset}
color={color}
boxSize={boxSize}
spacingX={spacingX}
borderRadius={borderRadius}
transitionDuration={this.props.transitionDuration}
/>
);
}
handleTransitionEnd = transitionId => {
this.props.onTransitionEnd(this.props.propsId);
};
componentDidUpdate() {
if (this.props.onTransitionEnd) {
this.node.addEventListener('transitionend', () => this.handleTransitionEnd(this.props.propsId), {
once: true,
capture: false,
});
}
}
}
function SingleBoxSelection({idx, status, boxSize, spacingX, spacingY, borderRadius, ...restProps}) {
return (
<SelectionGroup
idx={idx}
status={status}
individualSelectionsProps={[{key: 0, ...restProps}]}
boxSize={boxSize}
borderRadius={borderRadius}
spacingX={spacingX}
spacingY={spacingY}
/>
);
}
class SelectionGroup extends React.Component {
TRANSITION_DURATION = 500;
constructor() {
super();
this.state = {
transitionRunning: false,
transitionStarting: false,
epoch: 0,
};
}
render() {
const isSelectionThrottled = getUxSettings().THROTTLE_SELECTION_TRANSITIONS;
const {idx, status} = this.state;
const {individualSelectionsProps, ...restProps} = this.props;
return individualSelectionsProps.map(extraProps => (
<ActiveBoxSelectionThrottledHelper
{...extraProps}
{...restProps}
idx={idx}
status={status}
transitionDuration={this.TRANSITION_DURATION}
propsId={isSelectionThrottled && this.state.epoch}
onTransitionEnd={isSelectionThrottled && this.handleTransitionEnd}
/>
));
}
handleTransitionEnd = epoch => {
if (epoch === this.state.epoch) {
this.setState(state => {
if (state.transitionRunning) {
return {transitionRunning: false};
} else {
return null;
}
});
}
};
componentDidUpdate() {
if (this.state.transitionRunning && this.state.transitionStarting) {
this.setState(state => {
return {
transitionStarting: false,
};
});
this.handleStartingTransition();
}
}
handleStartingTransition() {
let selectionTimeout = getUxSettings().THROTTLE_SELECTION_TIMEOUT;
if (typeof selectionTimeout !== 'number') {
selectionTimeout = this.TRANSITION_DURATION + 20;
} else {
selectionTimeout = Math.min(this.TRANSITION_DURATION + 20, selectionTimeout);
}
const currentEpoch = this.state.epoch;
setTimeout(() => {
if (currentEpoch === this.state.epoch) {
this.handleTransitionEnd(currentEpoch);
}
}, selectionTimeout);
}
static getDerivedStateFromProps(props, state) {
const isSelectionThrottled = getUxSettings().THROTTLE_SELECTION_TRANSITIONS;
if (isSelectionThrottled) {
if (!state.transitionRunning && (state.idx !== props.idx || state.status !== props.status)) {
const statusAllowsTransition = state.status === 'adding' && props.status === 'adding';
let newState = {
idx: props.idx,
status: props.status,
transitionRunning: statusAllowsTransition,
transitionStarting: statusAllowsTransition,
epoch: state.epoch + 1,
};
return newState;
} else {
return null;
}
} else {
return {idx: props.idx, status: props.status};
}
}
}
class Box extends React.PureComponent {
shortDisplayedString(value) {
const extraType =
value === 'DUMMY' ||
value === 'EMPTY' ||
value === '' ||
(typeof value === 'string' && /^[-+]?[0-9]+$/.test(value));
let isEmpty = false;
const maxLen = extraType ? 8 : 12;
// TODO: add hover?
let s = displayStr(value, false);
let shortenedValue;
if (s.length <= maxLen) {
shortenedValue = [s];
} else {
const cutCharsCount = extraType ? 3 : 4;
if (cutCharsCount === 4) {
shortenedValue = [
s.substring(0, cutCharsCount),
<br key="br1" />,
'\u22EF',
<br key="br2" />,
s.substring(s.length - cutCharsCount, s.length),
];
} else {
shortenedValue = [
s.substring(0, cutCharsCount),
'\u2026',
s.substring(s.length - cutCharsCount, s.length),
];
}
}
return {
shortenedValue,
extraType,
isEmpty,
};
}
render() {
const {
value,
idx,
status,
extraStyleWhenAdding,
removedOffset,
createdOffset,
boxSize,
spacingX,
fontSize,
spacingY,
borderRadius,
boxPadding,
} = this.props;
const yOffset = (this.props.yRel || 0) * (boxSize + spacingY);
let classes = ['box', {'box-animated': status !== 'removed' && status !== 'created'}];
let classesContent = [...classes];
let content;
if (value != null) {
const {shortenedValue, extraType} = this.shortDisplayedString(value);
let extraTypeSpan;
let style = {fontSize: this.props.fontSize * 0.75};
if (
shortenedValue.length === 1 &&
shortenedValue[0] === '' /* TODO FIXME: this check is kidna ugly & is a leaky abstraction */
) {
extraTypeSpan = (
<span className="box-content-extra-type" style={style}>
(empty str)
</span>
);
} else {
extraTypeSpan = extraType ? (
<span className="box-content-extra-type" style={style}>
(str)
</span>
) : null;
}
classes.push('box-full');
content = (
<span className="box-content">
{shortenedValue} {extraTypeSpan}
</span>
);
} else {
classes.push('box-empty');
}
let y;
let extraStyle;
let boxStatus;
switch (status) {
case 'removed':
boxStatus = 'box-removed';
break;
case 'removing':
boxStatus = 'box-removing';
y = value != null ? yOffset - (removedOffset != null ? removedOffset : boxSize) : yOffset;
break;
case 'created':
boxStatus = 'box-created';
y = value != null ? yOffset - (createdOffset != null ? createdOffset : boxSize) : yOffset;
break;
case 'adding':
y = yOffset;
extraStyle = this.props.extraStyleWhenAdding;
break;
}
classes.push(boxStatus);
classesContent.push(boxStatus);
return (
<>
<div
style={{
transform:
status !== 'removed'
? computeBoxTransformProperty(idx, y, boxSize, spacingX, 0)
: 'translate(0px, 0px)',
width: boxSize,
height: boxSize,
fontSize: fontSize,
lineHeight: `${fontSize}px`,
borderRadius,
padding: boxPadding,
...extraStyle,
}}
className={classNames(classes)}
/>
{content && (
<div
style={{
transform:
status !== 'removed'
? computeBoxTransformProperty(idx, y, boxSize, spacingX, 5)
: 'translate(0px, 0px)',
width: boxSize,
height: boxSize,
fontSize: fontSize,
lineHeight: `${fontSize}px`,
borderRadius,
padding: boxPadding,
...extraStyle,
}}
className={classNames(classesContent, 'box-content-wrapper')}
>
{content}
</div>
)}
</>
);
}
}
class SlotSelection extends React.PureComponent {
render() {
const {extraClassName, idx, status, color, boxSize, spacingX, spacingY, borderRadius} = this.props;
const individualSelectionsProps = [
{
key: `${extraClassName}-hashCode`,
extraClassName,
color,
yOffset: 0,
},
{key: `${extraClassName}-key`, extraClassName, color, yOffset: boxSize + spacingY},
{
key: `${extraClassName}-value`,
extraClassName,
color,
yOffset: 2 * (boxSize + spacingY),
},
];
return (
<SelectionGroup
individualSelectionsProps={individualSelectionsProps}
idx={idx}
status={status}
boxSize={boxSize}
spacingX={spacingX}
spacingY={spacingY}
borderRadius={borderRadius}
/>
);
}
}
class LineOfBoxesSelection extends React.PureComponent {
render() {
const {extraClassName, idx, status, count, color, boxSize, spacingX, spacingY, borderRadius} = this.props;
let individualSelectionsProps = [];
for (let i = 0; i < this.props.count; ++i) {
individualSelectionsProps.push({
key: `${extraClassName}-${i}`,
extraClassName,
color,
yOffset: i * (boxSize + spacingY),
});
}
return (
<SelectionGroup
individualSelectionsProps={individualSelectionsProps}
idx={idx}
status={status}
boxSize={boxSize}
spacingX={spacingX}
spacingY={spacingY}
spacingY={spacingY}
borderRadius={borderRadius}
/>
);
}
}
const BBRecord = ImmutableRecord({
status: null,
modId: null,
box: null,
value: null,
group: null,
id: null,
idx: null,
someProps: null,
});
class BaseBoxesComponent extends React.PureComponent {
static ANIMATION_DURATION_TIMEOUT = 500;
constructor() {
super();
this.state = {
keyData: null,
activeBoxSelection1: null,
activeBoxSelection1status: null,
activeBoxSelection2: null,
activeBoxSelection2status: null,
lastIdx: null,
lastIdx2: null,
needProcessCreatedAfterRender: false,
needReflow: false,
firstRender: true,
modificationId: 0,
lastBoxId: 0,
removingValueToGroupToKeyToId: null,
};
this.ref = React.createRef();
this.gcTimeout = null;
}
static markRemoved(state, targetModId) {
let updatedCount = 0;
let toMerge = {};
let gcModId = state.gcModId;
if (targetModId) {
gcModId = Math.max(gcModId, targetModId);
}
console.log('BaseBoxesComponent markRemoved', gcModId);
for (const [key, data] of state.keyData.entries()) {
if (data.status === 'removing' && data.modId <= gcModId) {
updatedCount++;
toMerge[key] = {
box: React.cloneElement(data.box, {status: 'removed'}),
status: 'removed',
};
}
}
if (updatedCount > 0) {
console.log('BaseBoxesComponent.markRemoved() removed', updatedCount);
return {
keyData: state.keyData.mergeDeep(toMerge),
needReflow: true,
gcModId,
};
} else {
return null;
}
}
// FIXME: this function
// FIXME: you may not like it, but this is what peak engineering looks like
static getDerivedStateFromProps(nextProps, state) {
const t1 = performance.now();
// BaseBoxesComponent.staticDebugLogState(state);
// Some boxes are already timed out, so mark them as such
if (!state.firstRender) {
const mrState = BaseBoxesComponent.markRemoved(state);
if (mrState) {
state = {...state, ...mrState};
}
}
const modificationId = state.modificationId + 1;
const gcModId = state.gcModId;
const Selection = nextProps.selectionClass;
const boxFactory = nextProps.boxFactory;
const boxGeometry = nextProps.boxGeometry;
const boxFontSizeOverride = nextProps.boxFontSizeOverride;
const actualGeometry = {...boxGeometry};
if (boxFontSizeOverride) {
actualGeometry.fontSize = boxFontSizeOverride;
}
const geometryChanged = !state.firstRender && boxGeometry !== state.boxGeometry;
if (geometryChanged) {
const toMerge = {};
for (const [key, data] of state.keyData.entries()) {
toMerge[key] = {box: React.cloneElement(data.box, {...actualGeometry})};
}
state = {...state, keyData: state.keyData.mergeDeep(toMerge), boxGeometry};
}
let nextArray = nextProps.array;
let nextArrayPreConversion = nextArray;
const convertNextArray = () => {
if (isImmutableListOrMap(nextArray)) {
// TODO: use Immutable.js api?
// console.log('immutable.js next provided');
const _tna = performance.now();
nextArray = nextArray.toJS();
// console.log('toJS() timing', performance.now() - _tna);
} else {
// console.warn('nextArray non-immutable');
}
};
let lastBoxId = state.lastBoxId;
let newState;
const t2 = performance.now();
console.log('BaseBoxesComponent::gdsp before update state timing', t2 - t1);
if (!state.firstRender) {
// This should help when setState is called after needProcessCreatedAfterRender = true
// (And also can possible help sometimes when a slider is dragged)
if (nextArrayPreConversion !== state.lastNextArrayPreConversion) {
convertNextArray();
nextArray = nextArray || [];
const nextArrayKeys = nextProps.getKeys(nextArray);
let newRemovingValueToGroupToKeyToId = state.removingValueToGroupToKeyToId.asMutable();
let toMerge = {};
let nextKeysSet = new Set(_.flatten(nextArrayKeys));
let needGarbageCollection = false;
// First check boxes that will be removed
// FIXME: some are already removed, it might be a good idea to maintain a list of "present" boxes
for (let [key, oldData] of state.keyData.entries()) {
if (!nextKeysSet.has(key)) {
const status = oldData.status;
if (status !== 'removing' && status !== 'removed') {
const group = oldData.group;
const value = oldData.value;
const box = React.cloneElement(oldData.box, {status: 'removing'});
toMerge[key] = {status: 'removing', modId: modificationId, box};
newRemovingValueToGroupToKeyToId.setIn([repr(value, true), group, key], {
id: oldData.id,
idx: oldData.idx,
});
needGarbageCollection = true;
}
}
}
const newBox = (key, idx, someProps, group, value) => {
needProcessCreatedAfterRender = true;
needReflow = true;
const id = (++lastBoxId).toString();
const box = <Box idx={idx} status="created" key={id} {...actualGeometry} {...someProps} />;
toMerge[key] = new BBRecord({
status: 'created',
id,
box,
modId: modificationId,
group,
value,
idx,
someProps,
});
};
let needProcessCreatedAfterRender = false;
let needReflow = false;
// const t3 = performance.now();
// console.log('BaseBoxesComponent::gdsp before processing adding stage1', t3 - t2);
let notExistingKeyToData = {};
for (let idx = 0; idx < nextArray.length; ++idx) {
const keys = nextArrayKeys[idx];
const idxBoxesProps = boxFactory(keys, nextArray[idx]);
for (const [group, [key, someProps]] of idxBoxesProps.entries()) {
const value = someProps.value;
const oldData = state.keyData.get(key);
if (!oldData) {
// if box does not exist at all
// Then there are two options
if (value != null) {
// There may be an opportunity to recycle non-empty boxes
notExistingKeyToData[key] = {value, group, idx, someProps};
} else {
// But empty boxes should be recreated. It may make sense to recycle
// non-empty boxes as well, but in the current explanation there are no patterns
// where it'd help (empty box keys are very regular and have index in it)
newBox(key, idx, someProps, group, value);
}
} else {
// if box already exists
const status = oldData.status;
// potential FIXME: does not properly compare someProps, may not update boxes if someProps become more important
if (
status !== 'adding' ||
oldData.idx !== idx ||
oldData.someProps.yOffset !== someProps.yOffset ||
oldData.someProps.yRel !== someProps.yRel
) {
// Box is changed, time to update it
const box = oldData.box;
const newStatus = status === 'removed' ? 'created' : 'adding';
if (newStatus === 'created') {
needProcessCreatedAfterRender = true;
needReflow = true;
}
const newBox = React.cloneElement(box, {
idx,
status: newStatus,
...someProps,
});
toMerge[key] = {
box: newBox,
status: newStatus,
modId: modificationId,
idx,
someProps,
};
BaseBoxesComponent.notSoDeepDel(newRemovingValueToGroupToKeyToId, [
repr(value, true),
group,
key,
]);
}
}
}
}
let keyToRecycledBox = {};
let instaRemovedKeys = [];
const recycleId = (key, idx, value, groupOfKeyToId, keyToId) => {
let keyWithRecycledId;
if (keyToId.size > 1) {
for (let [key, {idx: otherIdx}] of keyToId.entries()) {
// TODO: the best value could probably be selected based as argmin(abs(otherIdx - idx))
// TODO: but for now this feels good enough, since it does not swap two boxes with the same value
if (otherIdx === idx) {
keyWithRecycledId = key;
break;
}
}
}
if (keyWithRecycledId == null) {
keyWithRecycledId = keyToId.keySeq().first();
}
keyToRecycledBox[key] = state.keyData.get(keyWithRecycledId).box;
BaseBoxesComponent.notSoDeepDel(newRemovingValueToGroupToKeyToId, [
repr(value, true),
groupOfKeyToId,
keyWithRecycledId,
]);
instaRemovedKeys.push(keyWithRecycledId);
};
// const t4 = performance.now();
// console.log('BaseBoxesComponent::gdsp before processing recycling 1', t4 - t3);
// Do a first pass and attempt to recycle boxes in the same row
for (let key in notExistingKeyToData) {
const data = notExistingKeyToData[key];
const potentialKeyToId = newRemovingValueToGroupToKeyToId.getIn([
repr(data.value, true),
data.group,
]);
if (potentialKeyToId) {
recycleId(key, data.idx, data.value, data.group, potentialKeyToId);
}
}
// const t5 = performance.now();
// console.log('BaseBoxesComponent::gdsp before processing recycling 2', t5 - t4);
// Do a second pass and attempt to recycle boxes in other rows
for (let key in notExistingKeyToData) {
if (key in keyToRecycledBox) {
continue;
}
const data = notExistingKeyToData[key];
const potentialGroupToKeyToId = newRemovingValueToGroupToKeyToId.get(repr(data.value, true));
if (potentialGroupToKeyToId) {
// TODO: might be better to prefer keys and values for each others rather than select randoml
// (this might lead to box from hash codes being transferred to keys/values)
const firstGroup = potentialGroupToKeyToId.keySeq().first();
const keyToId = potentialGroupToKeyToId.get(firstGroup);
recycleId(key, data.idx, data.value, firstGroup, keyToId);
}
}
// const t6 = performance.now();
// console.log('BaseBoxesComponent::gdsp before processing recycling 3', t6 - t5);
for (let key in notExistingKeyToData) {
const data = notExistingKeyToData[key];
if (key in keyToRecycledBox) {
// if found a recycled box
const value = data.someProps.value;
const box = keyToRecycledBox[key];
const status = box.props.status;
const id = box.key;
const idx = data.idx;
const newStatus = status === 'removed' ? 'created' : 'adding';
if (newStatus === 'created') {
needProcessCreatedAfterRender = true;
needReflow = true;
}
const newBox = React.cloneElement(box, {
idx: idx,
status: newStatus,
...data.someProps,
});
toMerge[key] = new BBRecord({
box: newBox,
idx,
id,
status: newStatus,
modId: modificationId,
group: data.group,
value: data.value,
someProps: data.someProps,
});
} else {
// if no recycled box found, then just create a new box
newBox(key, data.idx, data.someProps, data.group, data.value);
}
}
//const t7 = performance.now();
//console.log('BaseBoxesComponent::gdsp before merging', t7 - t6);
let newKeyData = state.keyData.mergeDeep(toMerge);
newKeyData = newKeyData.deleteAll(instaRemovedKeys);
// const t8 = performance.now();
// console.log('BaseBoxesComponent::gdsp after merging', t8 - t7);
newState = {
keyData: newKeyData,
removingValueToGroupToKeyToId: newRemovingValueToGroupToKeyToId.asImmutable(),
firstRender: false,
needProcessCreatedAfterRender: needProcessCreatedAfterRender,
needReflow: needReflow,
needGarbageCollection: needGarbageCollection,
modificationId: modificationId,
gcModId: gcModId,
lastBoxId: lastBoxId,
lastNextArrayPreConversion: nextArrayPreConversion,
epoch: nextProps.epoch,
boxGeometry: boxGeometry,
};
}
} else {
convertNextArray();
let keyData = {};
let arrayBoxKeys = nextProps.getKeys(nextArray);
for (let idx = 0; idx < nextArray.length; ++idx) {
const keys = arrayBoxKeys[idx];
const idxBoxesProps = boxFactory(keys, nextArray[idx]);
for (const [group, [key, someProps]] of idxBoxesProps.entries()) {
const value = someProps.value;
const id = (++lastBoxId).toString();
const box = <Box idx={idx} key={id} status="adding" {...boxGeometry} {...someProps} />;
keyData[key] = new BBRecord({
status: 'adding',
modId: modificationId,
box,
id,
group,
value,
someProps,
});
}
}
newState = {
keyData: new ImmutableMap(keyData),
removingValueToGroupToKeyToId: new ImmutableMap(),
firstRender: false,
needProcessCreatedAfterRender: false,
needGarbageCollection: false,
gcModId: -1,
modificationId: modificationId,
lastBoxId: lastBoxId,
lastNextArray: nextArray,
epoch: nextProps.epoch,
boxGeometry: boxGeometry,
};
}
// This can be located in the beginning of the function, but I think it is better to move it here, b/c this might lead
// to better recycling of boxes
//
// Epoch changes when the main "toolbar input changes". It is a hack to make dragging sliders work better
// Re-using old boxes rather than creating new ones seems to work better in most browsers (and much better in firefox)
if (!state.firstRender && state.epoch != nextProps.epoch) {
const currentState = newState != null ? newState : state;
const gcState = BaseBoxesComponent.garbageCollect(currentState, gcModId);
if (gcState) {
newState = {...currentState, ...gcState};
}
}
// Can happen when there is no change between arrays
if (newState == null) {
newState = {...state};
}
let activeBoxSelection1 = state.activeBoxSelection1;
let activeBoxSelection2 = state.activeBoxSelection2;
let activeBoxSelection1status = state.activeBoxSelection1status;
let activeBoxSelection2status = state.activeBoxSelection2status;
// FIXME: handling active selection is extremely ugly, should be rewritten in a much cleaner fashion
// FIXME: probably better to get rid of created/removing/adding statuses here
//
// TODO: it may be a good idea to combine it with Selection component
const getOrModSelection = (selection, extraClassName, oldIdx, _idx, status, color) => {
if (_idx == null) {
status = 'removing';
} else if (status === 'created' || _idx != null) {
status = 'adding';
}
const idx = _idx != null ? _idx : oldIdx;
if (!selection) {
return [
<Selection
{...nextProps.selectionProps}
key={extraClassName}
keyTemplate={extraClassName}
extraClassName={extraClassName}
idx={idx}
status={status}
color={color}
{...boxGeometry}
/>,
status,
];
} else {
return [React.cloneElement(selection, {idx, status, ...boxGeometry}), status];
}
};
if (activeBoxSelection1 || nextProps.idx != null) {
[activeBoxSelection1, activeBoxSelection1status] = getOrModSelection(
activeBoxSelection1,
'active-box-selection-1',
state.lastIdx,
nextProps.idx,
activeBoxSelection1status,
nextProps.selection1color || RED
);
}
if (activeBoxSelection2 || nextProps.idx2 != null) {
[activeBoxSelection2, activeBoxSelection2status] = getOrModSelection(
activeBoxSelection2,
'active-box-selection-2',
state.lastIdx2,
nextProps.idx2,
activeBoxSelection2status,
nextProps.selection2color || BLUE
);
}
if (nextProps.idx != null) {
newState.lastIdx = nextProps.idx;
} else {
newState.lastIdx = state.lastIdx;
}
if (nextProps.idx2 != null) {
newState.lastIdx2 = nextProps.idx2;
} else {
newState.lastIdx2 = state.lastIdx2;
}
newState.activeBoxSelection1status = activeBoxSelection1status;
newState.activeBoxSelection2status = activeBoxSelection2status;
newState.activeBoxSelection1 = activeBoxSelection1;
newState.activeBoxSelection2 = activeBoxSelection2;
const totalTiming = performance.now() - t1;
if (typeof window !== 'undefined') {
if (!('bbTiming' in window)) {
window.bbTiming = 0;
}
window.bbTiming += totalTiming;
}
console.log('BaseBoxesComponent.getDerivedStateFromProps timing', totalTiming);