-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
562 lines (502 loc) · 19.1 KB
/
app.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
import _ from 'lodash';
import {createBrowserHistory} from 'history';
import Bootstrap from 'bootstrap/dist/css/bootstrap.min.css';
import './mainpage.css';
import './styles.css';
import classnames from 'classnames';
import * as React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Switch, Route, Link, Redirect, withRouter} from 'react-router-dom';
import {MyErrorBoundary, initUxSettings, getUxSettings, BootstrapAlert, doubleRAF} from './util';
import {win, globalSettings} from './store';
import {ForeverAnimation, dummyFormat, TetrisFactory, HashBoxesComponent, LineOfBoxesComponent} from './code_blocks';
import {
BubbleSort,
BUBBLE_SORT_CODE,
InsertionSort,
INSERTION_SORT_CODE,
QUICK_SORT_CODE,
QuickSort,
formatQuickSort,
formatBubbleSort,
} from './new_demos';
import {Player} from './player';
import {
Chapter1_SimplifiedHash,
SIMPLE_LIST_SEARCH,
SIMPLIFIED_INSERT_ALL_BROKEN_CODE,
SIMPLIFIED_INSERT_ALL_CODE,
SIMPLIFIED_SEARCH_CODE,
formatSimpleListSearchBreakpointDescription,
formatSimplifiedInsertAllDescription,
formatSimplifiedSearchDescription,
SimpleListSearchStateVisualization,
SimplifiedInsertStateVisualization,
SimplifiedSearchStateVisualization,
SimplifiedInsertBrokenStateVisualization,
} from './chapter1_simplified_hash';
import {
Chapter2_HashTableFunctions,
HASH_CREATE_NEW_CODE,
HASH_SEARCH_CODE,
HASH_REMOVE_CODE,
HASH_RESIZE_CODE,
formatHashCreateNewAndInsert,
formatHashRemoveSearch,
formatHashResize,
HashCreateNewStateVisualization,
HashNormalStateVisualization,
HashResizeStateVisualization,
} from './chapter2_hash_table_functions';
import {CollisionsTheory, SimplifiedHashTheory, HashTheory, BubbleSortTheory, QuickSortTheory} from './theory';
function getWindowDimensions() {
const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;
return {width, height};
}
function logViewportStats() {
console.log(`DIMENSIONS: window inner: ${window.innerWidth}x${window.innerHeight}`);
console.log(
`DIMENSIONS: document.documentElement: ${document.documentElement.clientWidth}x${
document.documentElement.clientHeight
}`
);
const vv = window.visualViewport;
console.log(`DIMENSIONS: visualViewport: ${vv != null ? vv.width + 'x' + vv.height : vv}`);
const {width, height} = getWindowDimensions();
console.log(`DIMENSIONS: used: ${width}x${height}`);
// TODO FIXME: this is for debugging only
/*const url = `/viewports?wi=${window.innerWidth}x${window.innerHeight}&de=${document.documentElement.clientWidth}x${document.documentElement.clientHeight}&vv=${vv.width}x${vv.height}`;
const Http = new XMLHttpRequest();
Http.open("GET", url);
Http.send();*/
}
function Footer() {
return (
<footer>
<a className="link" href="https://bureau.ru/school/designers/12/">
Сделано в 2021 году в Школе Бюро Горбунова ›
</a>
</footer>
);
}
function sendGA(location) {
console.log('Calling sendGA');
const gtag = window.gtag;
if (typeof gtag === 'function') {
gtag('event', 'page_view');
}
}
// mainly to prevent addressbar stuff on mobile changing things excessively
const SIGNIFICANT_HEIGHT_CHANGE = 0;
export class App extends React.Component {
constructor() {
super();
this.state = {
mounted: false,
windowWidth: null,
windowHeight: null,
};
}
handleWindowSizeChange = () => {
logViewportStats();
const dimensions = getWindowDimensions();
const windowWidth = dimensions.width;
const windowHeight = dimensions.height;
if (this.state.windowWidth !== windowWidth || this.state.windowHeight !== windowHeight) {
console.log('Processing window size change', windowWidth, windowHeight);
if (
this.state.windowWidth != windowWidth ||
this.state.windowHeight > windowHeight ||
windowHeight - this.state.windowHeight > SIGNIFICANT_HEIGHT_CHANGE
) {
console.log('App size changed from', this.state);
this.setState({
windowWidth,
windowHeight,
});
if (win.width !== windowWidth || win.height !== windowHeight) {
win.setWH(windowWidth, windowHeight);
}
}
}
};
componentDidMount() {
const dimensions = getWindowDimensions();
const windowWidth = dimensions.width;
const windowHeight = dimensions.height;
console.log('componentDidMount() window geometry', windowWidth, windowHeight);
window.addEventListener('resize', _.throttle(this.handleWindowSizeChange, 500));
globalSettings.maxCodePlaySpeed = getUxSettings().MAX_CODE_PLAY_SPEED;
this.setState({
windowWidth,
windowHeight,
mounted: true,
});
win.setAll(windowWidth, windowHeight, window.scrollY, true);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleWindowSizeChange);
}
render() {
console.log('App.render()');
const {windowWidth, windowHeight} = this.state.mounted ? this.state : {};
console.log('Window sizes', windowWidth, windowHeight);
if (!this.state.mounted) {
return <div>Loading...</div>;
}
return (
<Router>
<Route path="/" render={sendGA} />
<Switch>
<Route path="/lesson/:id">
<Lesson windowWidth={windowWidth} windowHeight={windowHeight} />
</Route>
<Route path="/">
<MainPage windowWidth={windowWidth} windowHeight={windowHeight} />
</Route>
</Switch>
</Router>
);
}
}
function runBubbleSort(a, granular = false) {
const bs = new BubbleSort();
bs.run(a, granular);
const bp = bs.getBreakpoints();
return {bp};
}
function runInsertionSort(a, granular = false) {
const is = new InsertionSort();
is.run(a, granular);
const bp = is.getBreakpoints();
return {bp};
}
function runQuickSort(a) {
const qs = new QuickSort();
qs.run(a);
const bp = qs.getBreakpoints();
console.log('quicksort bp', bp);
return {bp};
}
const InsertionSortVisualisation = TetrisFactory([[LineOfBoxesComponent, [{labels: [null]}, 'a', 'i', undefined]]]);
export const MinimalSortVisualisation = TetrisFactory([[HashBoxesComponent, [{labels: [null]}, 'a']]]);
export const QuickSortVisualisation = TetrisFactory([
[HashBoxesComponent, [{labels: [null]}, 'array', 'left', 'right']],
]);
export const BubbleSortVisualisation = TetrisFactory([[HashBoxesComponent, [{labels: [null]}, 'a', 'j', 'jplus1']]]);
const chapter1 = new Chapter1_SimplifiedHash();
const chapter2 = new Chapter2_HashTableFunctions();
// const GLOBAL_STATE = {
// simplifiedHash: /*...*/,
// simplifiedKeyToSearch: /* ... */,
// };
// const inputsToPass = {
// inputs:
// }
const SIMPLIFIED_HASH_ORIGINAL_LIST_INPUT = {
label: 'original_list',
type: 'array_int',
id: 'simplified-hash-original-list',
default: '1 56 50 2 44 25 17 4',
};
const SORTS_LIST_INPUT = {
label: '',
type: 'array_int',
id: 'sorts-list',
default: '42 13 11 92 27 87 14 67 1 12 44 9 20 7',
};
const HASH_FROM_KEYS_INPUT = {
label: 'from_keys',
type: 'array',
id: 'hash-from-keys',
default: "'uname' 'mv' 1 'time' -6 'ps' 'mkdir' 'less'",
};
const LESSONS = {
bubble_sort: {
mainPagePaneHeaderTitle: 'Пузырьком',
mainPagePaneClassName: 'bubble-sort',
playerHeaderTitle: 'сортировку пузырьком',
mobilePlayerHeaderTitle: 'Сортировка пузырьком',
getBreakpoints: numbers => {
return runBubbleSort(numbers.map(n => n.toNumber()), true).bp;
},
inputs: [SORTS_LIST_INPUT],
formatBpDesc: formatBubbleSort,
stateVisualization: BubbleSortVisualisation,
code: BUBBLE_SORT_CODE,
resetToZero: true,
theory: <BubbleSortTheory />,
},
quick_sort: {
mainPagePaneHeaderTitle: 'Быстрая',
mainPagePaneClassName: 'quick-sort',
playerHeaderTitle: 'быструю сортировку',
mobilePlayerHeaderTitle: 'Быстрая сортировка',
getBreakpoints: numbers => {
return runQuickSort(numbers.map(n => n.toNumber())).bp;
},
inputs: [SORTS_LIST_INPUT],
formatBpDesc: formatQuickSort,
stateVisualization: QuickSortVisualisation,
code: QUICK_SORT_CODE,
resetToZero: true,
theory: <QuickSortTheory />,
},
// linear_search: {
// mainPagePaneHeaderTitle: 'Линейный поиск',
// mainPagePaneClassName: 'linear-search',
// playerHeaderTitle: 'линейный поиск',
// mobilePlayerHeaderTitle: 'Линейный поиск',
// code: SIMPLE_LIST_SEARCH,
// breakpoints: slsRes.bp,
// formatBpDesc: formatSimpleListSearchBreakpointDescription,
// stateVisualization: SimpleListSearchStateVisualization,
// },
simplified_hash_collisions: {
mainPagePaneHeaderTitle: 'Коллизии',
mainPagePaneClassName: 'simplified-hash-collisions',
playerHeaderTitle: 'коллизии в хеш-таблицах',
code: SIMPLIFIED_INSERT_ALL_BROKEN_CODE,
getBreakpoints: original_list => {
return chapter1.runSimplifiedInsertAllBroken(original_list).bp;
},
inputs: [SIMPLIFIED_HASH_ORIGINAL_LIST_INPUT],
formatBpDesc: formatSimplifiedInsertAllDescription,
stateVisualization: SimplifiedInsertBrokenStateVisualization,
theory: <CollisionsTheory />,
},
simplified_hash_create: {
mainPagePaneHeaderTitle: 'Создание',
mainPagePaneClassName: 'simplified-hash-create',
playerHeaderTitle: 'создание простейшей хеш-таблицы',
code: SIMPLIFIED_INSERT_ALL_CODE,
getBreakpoints: original_list => chapter1.runSimplifiedInsertAll(original_list).bp,
inputs: [SIMPLIFIED_HASH_ORIGINAL_LIST_INPUT],
formatBpDesc: formatSimplifiedInsertAllDescription,
stateVisualization: SimplifiedInsertStateVisualization,
theory: <SimplifiedHashTheory active="simplified_hash_create" />,
},
simplified_hash_search: {
mainPagePaneHeaderTitle: 'Поиск',
mainPagePaneClassName: 'simplified-hash-search',
playerHeaderTitle: 'поиск в простейшей хеш-таблице',
code: SIMPLIFIED_SEARCH_CODE,
getBreakpoints: (original_list, number) => {
const keys = chapter1.runSimplifiedInsertAll(original_list).keys;
return chapter1.runSimplifiedSearch(keys, number).bp;
},
inputs: [
SIMPLIFIED_HASH_ORIGINAL_LIST_INPUT,
{
label: 'number',
type: 'int',
id: 'simplified-hash-search-number',
default: '25',
},
],
formatBpDesc: formatSimplifiedSearchDescription,
stateVisualization: SimplifiedSearchStateVisualization,
theory: <SimplifiedHashTheory active="simplified_hash_search" />,
},
hash_create: {
mainPagePaneHeaderTitle: 'Создание',
mainPagePaneClassName: 'hash-create',
playerHeaderTitle: 'создание хеш-таблицы',
code: HASH_CREATE_NEW_CODE,
getBreakpoints: from_keys => {
return chapter2.runCreateNew(from_keys).bp;
},
inputs: [HASH_FROM_KEYS_INPUT],
formatBpDesc: formatHashCreateNewAndInsert,
stateVisualization: HashCreateNewStateVisualization,
theory: <HashTheory />,
},
hash_search: {
mainPagePaneHeaderTitle: 'Поиск',
mainPagePaneClassName: 'hash-search',
playerHeaderTitle: 'поиск в хеш-таблице',
code: HASH_SEARCH_CODE,
getBreakpoints: (from_keys, key) => {
const {hashCodes, keys} = chapter2.runCreateNew(from_keys);
return chapter2.runSearch(hashCodes, keys, key).bp;
},
inputs: [
HASH_FROM_KEYS_INPUT,
{
label: 'key',
type: 'int_str_none',
id: 'hash-search-key',
default: "'less'",
},
],
formatBpDesc: formatHashRemoveSearch,
stateVisualization: HashNormalStateVisualization,
theory: <HashTheory />,
},
hash_remove: {
mainPagePaneHeaderTitle: 'Удаление',
mainPagePaneClassName: 'hash-remove',
playerHeaderTitle: 'удаление из хеш-таблицы',
code: HASH_REMOVE_CODE,
getBreakpoints: (from_keys, key) => {
const {hashCodes, keys} = chapter2.runCreateNew(from_keys);
return chapter2.runRemove(hashCodes, keys, key).bp;
},
inputs: [
HASH_FROM_KEYS_INPUT,
{
label: 'key',
type: 'int_str_none',
id: 'hash-remove-key',
default: "'ps'",
},
],
formatBpDesc: formatHashRemoveSearch,
stateVisualization: HashNormalStateVisualization,
theory: <HashTheory />,
},
hash_resize: {
mainPagePaneHeaderTitle: 'Расширение',
mainPagePaneClassName: 'hash-resize',
playerHeaderTitle: 'расширение хеш-таблицы',
code: HASH_RESIZE_CODE,
getBreakpoints: from_keys => {
const {hashCodes, keys} = chapter2.runCreateNew(from_keys);
return chapter2.runResize(hashCodes, keys).bp;
},
inputs: [HASH_FROM_KEYS_INPUT],
formatBpDesc: formatHashResize,
stateVisualization: HashResizeStateVisualization,
theory: <HashTheory />,
},
};
class LessonPane extends React.Component {
constructor() {
super();
this.state = {
navigatingPlayer: false,
};
}
render() {
const id = this.props.id;
const lesson = LESSONS[id];
console.log('Lesson pane', id, LESSONS[id]);
if (this.state.navigatingPlayer) {
return <Redirect to={`lesson/${id}`} />;
}
return (
<a
href={`/lesson/${id}`}
className={classnames('pane', lesson.mainPagePaneClassName)}
onClick={this.navigatePlayer}
>
<h2>{lesson.mainPagePaneHeaderTitle}</h2>
</a>
);
}
}
const Lesson = withRouter(
class extends React.Component {
render() {
console.log('withRouter', this.props);
const id = this.props.match.params.id;
const {windowWidth, windowHeight} = this.props;
console.log('Lesson', id, LESSONS[id]);
return <Player {...LESSONS[id]} windowWidth={windowWidth} windowHeight={windowHeight} lessonId={id} />;
}
}
);
export class MainPage extends React.Component {
constructor() {
super();
// this.timerId = setInterval(() => {
// const newTime = this.state.time + 1;
// if (newTime <= MAX_PAGE_TIME) {
// this.setState({time: newTime});
// } else {
// this.setState({time: 0});
// }
// }, 2000);
}
render() {
return (
<div className="frontpage">
<div className="header">
<div className="title">Объясняем код</div>
<div className="definition">
<div className="definition-1">Интерактивные визуализации</div>
<div className="definition-2">с комментариями к коду</div>
</div>
</div>
{/* <div className="sorts">
<h1>Сортировки</h1>
<div className="panes-container">
<LessonPane lessonId="bubble_sort" />
<div className="pane insertion-sort">
<h2>Вставками</h2>
</div>
</div>
</div> */}
<div className="section">
<h1>Простейшие хеш-таблицы</h1>
<div className="pane-collection simplified-hash-collection">
<div className="simplified-hash-collection-left">
<LessonPane id="simplified_hash_collisions" />
</div>
<div className="simplified-hash-collection-right">
<LessonPane id="simplified_hash_create" />
<LessonPane id="simplified_hash_search" />
</div>
</div>
</div>
<div className="section">
<h1>Хеш-таблицы с открытой адресацией</h1>
<div className="pane-collection hash-collection">
<div className="hash-collection-top">
<LessonPane id="hash_create" />
<LessonPane id="hash_search" />
</div>
<div className="hash-collection-bottom">
<LessonPane id="hash_remove" />
<LessonPane id="hash_resize" />
</div>
</div>
</div>
<div className="section">
<h1>Сортировки</h1>
<div className="pane-collection sorts-collection">
<div className="sort-1">
<LessonPane id="bubble_sort" />
</div>
<div className="sort-2">
<LessonPane id="quick_sort" />
</div>
</div>
</div>
<Footer />
</div>
);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
}
export function initAndRender() {
if (typeof window !== 'undefined') {
initUxSettings();
window.addEventListener('load', () => {
logViewportStats();
const root = document.getElementById('root');
const isSSR = root.hasChildNodes();
ReactDOM.render(<App />, root);
/*if (isSSR) {
console.log('Rehydrating');
ReactDOM.hydrate(<App {...props} />, root);
} else {
console.log('Rendering from scratch');
ReactDOM.render(<App {...props} />, root);
}*/
});
}
}