-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.js
More file actions
401 lines (361 loc) · 11.7 KB
/
Copy pathbase.js
File metadata and controls
401 lines (361 loc) · 11.7 KB
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
const animationList = []; // 动画列表
let clearList = []; // 动画执行完成,执行清理动作
function handleChangeSpeed(ratio) {
speed = BASE_SPEED * ratio;
}
function print(arr) {
const container = document.querySelector('#console');
const items = arr.reduce((prev, next, index) => {
return `${prev}<span class="item">${next}</span>`;
}, '');
container.innerHTML = items;
}
const FONT_SIZE = 12;
const SHAPE = '30';
const LINE_WIDTH = 300;
const deep = 0;
const deepMap = {};
const RATIO = 3;
const BASE_DEG = 15;
const BASE_SPEED = 0.6;
let speed = BASE_SPEED;
// 排序二叉树
let binaryTree = [''];
function getDeep() {
let deep = 1;
const deepMap = new Map();
return function (target, value) {
if (target === undefined) {
return 0;
}
if (deepMap.has(target)) {
return deepMap.get(target);
} else {
deepMap.set(target, deep++);
return deepMap.get(target);
}
};
}
const getDeeper = getDeep();
function appendNode(parent, value = '', dir, strategy, color) {
function defaultStrategy(parent) {
return {
baseDeg: (parent.deg || BASE_DEG) * 1.5,
lineWidth: (parent.len || LINE_WIDTH) * 0.7
};
}
strategy = strategy || defaultStrategy;
const moveStance = SHAPE / 2;
// text
const textWrap = document.createElement('span');
const textNode = document.createTextNode(value);
textWrap.appendChild(textNode);
addClass(textWrap, 'text-wrap ');
textWrap.setAttribute(
'style',
`position: absolute;
top:${moveStance - FONT_SIZE / 2 + 'px'};
left: ${moveStance - FONT_SIZE / 2 + 'px'}
`
);
// info
const infoWrap = document.createElement('span');
const infoText = document.createTextNode('');
addClass(infoWrap, 'info');
infoWrap.appendChild(infoText);
if (!parent) {
const root = document.createElement('div');
root.setAttribute('data-root', true);
root.setAttribute('class', 'box');
root.style.left = window.innerWidth / 2 - SHAPE / 2 + 'px';
document.body.appendChild(root);
root.appendChild(textWrap);
root.appendChild(infoWrap);
const {baseDeg, lineWidth} = strategy({});
root.deg = baseDeg;
root.len = lineWidth;
return root;
}
// 树的深度
const deep = parent.deep || 1;
// 每层边长旋转的角度
const {baseDeg, lineWidth} = strategy(parent);
// const baseDeg = (parent.deg || BASE_DEG) * 1.5;
// const baseDeg = BASE_DEG + deep + RATIO;
// 边的长度
// const lineWidth = (parent.len || LINE_WIDTH) * 0.7;
const fragment = document.createDocumentFragment();
const x = 0;
const y = 0;
const line = document.createElement('div');
line.setAttribute('class', `line line-${value} line-${dir}`);
const transformDeg =
dir === 'right' ? `${baseDeg}deg` : `${180 - baseDeg}deg`;
line.style.width = lineWidth - 15 + 'px';
line.style.transformOrigin = 'left top';
line.style.borderColor = color;
// line.style.transform = `rotate(45deg) translateX(${moveStance}px) translateY(${moveStance}px)`;
line.style.transform = `translateX(${moveStance}px) translateY(${moveStance}px) rotate(${transformDeg})`;
const child = document.createElement('div');
child.setAttribute('class', 'box');
child.appendChild(textWrap);
child.appendChild(infoWrap);
child.deep = deep + 1;
child.len = lineWidth;
child.deg = baseDeg;
// 设置颜色,用来标识红黑树的红色节点,所以这里只是在颜色为红色的时候才设置背景色
if (!isUndefined(color) && color === 'red') {
textWrap.style.backgroundColor = 'red';
child.style.backgroundColor = color;
}
fragment.appendChild(line);
const deg = Math.PI / 180;
const letStance = x + lineWidth * Math.cos(deg * baseDeg);
const topStance = y + lineWidth * Math.sin(deg * baseDeg);
if (dir === 'right') {
child.style.left = letStance + 'px';
} else if (dir === 'left') {
child.style.left = -letStance + 'px';
}
child.style.top = topStance + 'px';
fragment.appendChild(child);
parent.appendChild(fragment);
return child;
}
function setPoistion(target, left, top) {
target.style.left = left + 'px';
target.style.top = top + 'px';
}
function isUndefined(v) {
return v === undefined;
}
function expandLine(source, target, color="black") {
let {left: sl, top: st, value: sv} = source;
let {left: tl, top: tt, value: tv} = target;
const leftDis = Math.abs(sl - tl);
const topDis = Math.abs(tt - st);
const dis = Math.sqrt(leftDis ** 2 + topDis ** 2);
let ele = document.createElement('div');
ele.setAttribute('class', 'move-line');
ele.style.borderColor = color;
document.body.appendChild(ele);
const leftDir = leftDis / dis;
const topDir = topDis / dis;
const tanValue = topDis / leftDis;
const rate = 180 / Math.PI;
let deg;
if (sl < tl) {
deg = Math.atan(tanValue) * rate;
} else {
deg = 180 - Math.atan(tanValue)* rate;
}
// const deg = theta * Math.PI / 180;
ele.style.left = sl + 15 + 'px';
ele.style.top = st + 15 + 'px';
ele.style.transform = `rotate(${deg}deg)`;
ele.style.width = '0px';
const speed = 1;
let leftPos = sl;
let topPos = st;
return new Promise((resolve) => {
const step = function () {
leftPos += speed * leftDir;
topPos += speed * topDir;
ele.style.width = parseInt(ele.style.width) + speed + 'px';
const isStop = parseInt(ele.style.width) > dis;
if (!isStop) {
window.requestAnimationFrame(step);
} else {
resolve(() => {
document.body.removeChild(ele);
});
}
};
window.requestAnimationFrame(step)
})
}
function moveByLine(source, target, targetDom, moveDir) {
let {left: sl, top: st, value: sv} = source;
let {left: tl, top: tt, value: tv} = target;
const leftDis = Math.abs(sl - tl);
const topDis = Math.abs(tt - st);
const dis = Math.sqrt(leftDis ** 2 + topDis ** 2);
let ele;
if (isUndefined(targetDom)) {
ele = document.querySelector('#circle');
ele.style.visibility = 'visible';
ele.innerHTML = sv;
} else {
ele = targetDom
}
const leftDir = leftDis / dis;
const topDir = topDis / dis;
let leftPos = sl;
let topPos = st;
function getStopFlag () {
const isLeftBoundary = Math.abs(leftPos - tl) < 3;
const isTopBoundary = Math.abs(topPos - tt) < 3;
if (isUndefined(moveDir)) {
return isLeftBoundary || isTopBoundary;
} else if (moveDir === 'left') {
return isLeftBoundary;
} else if (moveDir === 'top') {
return isTopBoundary;
}
}
return new Promise(resolve => {
function step() {
if (sl < tl) {
leftPos += speed * leftDir;
} else {
leftPos -= speed * leftDir;
}
if (st < tt) {
topPos += speed * topDir;
} else {
topPos -= speed * topDir;
}
setPoistion(ele, leftPos, topPos);
if (isUndefined(moveDir)) {
}
const isStop = getStopFlag();
if (!isStop) {
window.requestAnimationFrame(step);
} else {
resolve();
}
}
window.requestAnimationFrame(step);
});
}
function exchange(arr, i, j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
print(arr);
}
function getElement(id) {
return document.querySelector(`#id-${id}`);
}
function getPos(ele) {
return ele.getBoundingClientRect();
}
function setVal(ele, value) {
ele.querySelector('span').innerHTML = value;
}
function hideCircle() {
document.querySelector('#circle').style.visibility = 'hidden';
}
function setTextClass(parent, className) {
const span = parent.querySelector('span');
addClass(span, className);
}
async function handleOpration(opt) {
const {type, data} = opt;
console.log('optation=========>', opt);
if (opt.type === 'exchange') {
const sourceValue = data[0];
const targetValue = data[1];
const value = data[2];
const sourceEle = getElement(sourceValue);
const targetEle = getElement(targetValue);
const source = getPos(sourceEle);
const target = getPos(targetEle);
source.value = value;
await moveByLine(source, target);
hideCircle();
setVal(targetEle, value);
setVal(sourceEle, binaryTree[targetValue]);
setTextClass(sourceEle, 'jump');
setTextClass(targetEle, 'jump');
await new Promise(resolve => {
setTimeout(() => {
setTextClass(sourceEle, 'jump');
setTextClass(targetEle, 'jump');
resolve();
}, 1000);
});
setTextClass(sourceEle, '');
setTextClass(targetEle, '');
exchange(binaryTree, sourceValue, targetValue);
}
if (opt.type === 'remove') {
const parent = Math.floor(data / 2);
const currentDom = getElement(data);
const parentDom = getElement(parent);
const lineDom = currentDom.previousSibling;
parentDom.removeChild(lineDom);
parentDom.removeChild(currentDom);
}
if (opt.type === 'heightLight') {
let texEle;
return new Promise(resolve => {
data.nodes.forEach(ele => {
const infoEle = data.infoEle || ele;
if (infoEle) {
texEle = infoEle.querySelector('.info');
texEle.innerHTML = data.info || '';
}
addClass(ele, 'height-light');
});
setTimeout(() => {
data.nodes.forEach(ele => {
if (!data.forevar) {
addClass(ele, 'height-light');
texEle.innerHTML = '';
}
});
resolve();
}, 2000);
});
}
if (opt.type === 'sorted') {
const ele = getElement(data);
addClass(ele, 'sorted');
}
}
async function render() {
while (animationList.length) {
const a = animationList.shift();
await handleOpration(a);
}
hideCircle();
clearList.forEach(i => i.call(null));
clearList = [];
}
function pushOpration(opt) {
animationList.push(opt);
}
function shuffle(arr) {
const getRange = (min, max) => min + Math.floor((max - min) * Math.random());
const len = arr.length;
for (let i = 0; i < len - 1; i++) {
exchange(arr, i, getRange(i, len));
}
}
function getRandomArr(len) {
const arr = Array.apply(null, {length: len}).map((i, index) => index);
shuffle(arr);
return arr;
}
function addClass(el, value) {
const hasClass = el.hasAttribute('class');
if (!hasClass) {
return el.setAttribute('class', value);
}
const className = el.getAttribute('class');
const classNameArr = className.split(' ').map(i => i.trim());
const index = classNameArr.findIndex(i => value === i);
if (index > -1) {
classNameArr.splice(index, 1);
el.setAttribute('class', classNameArr.join(' '));
return;
}
classNameArr.push(value);
el.setAttribute('class', classNameArr.join(' '));
}
function clearRootDom() {
const rootDom = document.querySelector('[data-root="true"]');
if (rootDom) {
document.body.removeChild(rootDom);
}
animationList.length = 0;
}