forked from wikiwi/reassemble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwithKeyboardFocus.tsx
83 lines (72 loc) · 2.23 KB
/
withKeyboardFocus.tsx
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
/* tslint:disable: no-console */
/* tslint:disable: no-var-requires */
/* tslint:disable: only-arrow-functions */
import * as Benchmark from "benchmark";
import * as recompose from "recompose";
import * as recompact from "recompact";
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as reassemble from "../src";
require("../test/setupDOM");
const suite = new Benchmark.Suite();
const Component: React.StatelessComponent<any> = () => null;
const container = document.createElement("div");
document.body.appendChild(container);
function render(node: React.ReactElement<any>) {
ReactDOM.render(node, container);
}
function cleanup() {
ReactDOM.unmountComponentAtNode(container);
}
// This is a real life example that determines whether the user
// focused on a component using the keyboard instead of the mouse or touch.
const create = (lib: any) => {
const {withState, withHandlers, compose} = lib;
let lastMouseDownTime = 0;
return compose(
withState("keyboardFocus", "setKeyboardFocus", false),
withHandlers({
onFocus: ({onFocus, setKeyboardFocus}: any) => (event: any) => {
if (onFocus) { onFocus(event); }
let now = new Date().getTime();
if (now - lastMouseDownTime > 750) {
setKeyboardFocus(true);
}
},
onBlur: ({onBlur, setKeyboardFocus}: any) => (event: any) => {
if (onBlur) { onBlur(event); }
setKeyboardFocus(false);
},
onMouseDown: ({onMouseDown}: any) => (event: any) => {
if (onMouseDown) { onMouseDown(event); }
lastMouseDownTime = new Date().getTime();
},
}),
);
};
const Composed = create(recompose)(Component);
const Compacted = create(recompact)(Component);
const Assembled = create(reassemble)(Component);
// add tests
suite
.add("recompose", () => {
render(<Composed />);
cleanup();
})
.add("recompact", () => {
render(<Compacted />);
cleanup();
})
.add("reassemble", () => {
render(<Assembled />);
cleanup();
})
// add listeners
.on("cycle", (event: any) => {
console.log(String(event.target));
})
.on("complete", function() {
console.log("Fastest is " + this.filter("fastest").map("name"));
})
// run async
.run({ async: true });