forked from preactjs/preact
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorder.jsx
104 lines (92 loc) · 2.26 KB
/
reorder.jsx
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
import { createElement, Component } from 'preact';
function createItems(count = 10) {
let items = [];
for (let i = 0; i < count; i++) {
items.push({
label: `Item #${i + 1}`,
key: i + 1
});
}
return items;
}
function random() {
return Math.random() < 0.5 ? 1 : -1;
}
export default class Reorder extends Component {
state = {
items: createItems(),
count: 1,
useKeys: false
};
shuffle = () => {
this.setState({ items: this.state.items.slice().sort(random) });
};
swapTwo = () => {
let items = this.state.items.slice(),
first = Math.floor(Math.random() * items.length),
second;
do {
second = Math.floor(Math.random() * items.length);
} while (second === first);
let other = items[first];
items[first] = items[second];
items[second] = other;
this.setState({ items });
};
reverse = () => {
this.setState({ items: this.state.items.slice().reverse() });
};
setCount = e => {
this.setState({ count: Math.round(e.target.value) });
};
rotate = () => {
let { items, count } = this.state;
items = items.slice(count).concat(items.slice(0, count));
this.setState({ items });
};
rotateBackward = () => {
let { items, count } = this.state,
len = items.length;
items = items.slice(len - count, len).concat(items.slice(0, len - count));
this.setState({ items });
};
toggleKeys = () => {
this.setState({ useKeys: !this.state.useKeys });
};
renderItem = item => (
<li key={this.state.useKeys ? item.key : null}>{item.label}</li>
);
render({}, { items, count, useKeys }) {
return (
<div class="reorder-demo">
<header>
<button onClick={this.shuffle}>Shuffle</button>
<button onClick={this.swapTwo}>Swap Two</button>
<button onClick={this.reverse}>Reverse</button>
<button onClick={this.rotate}>Rotate</button>
<button onClick={this.rotateBackward}>Rotate Backward</button>
<label>
<input
type="checkbox"
onClick={this.toggleKeys}
checked={useKeys}
/>{' '}
use keys?
</label>
<label>
<input
type="number"
step="1"
min="1"
style={{ width: '3em' }}
onInput={this.setCount}
value={count}
/>{' '}
count
</label>
</header>
<ul>{items.map(this.renderItem)}</ul>
</div>
);
}
}