add keyboard support

This commit is contained in:
infeng 2016-10-19 14:42:57 +08:00
parent 460e865ad3
commit ec29ae17df
2 changed files with 71 additions and 0 deletions

View File

@ -53,6 +53,18 @@ class App extends React.Component<any, any> {
| activeIndex | number | 0 | active image index | false |
| zIndex | number | 1000 | Viewer css z-index | false |
## Keyboard support
- `Esc`: Close viewer.
- `←`: View the previous image.
- `→`: View the next image.
- `↑`: Zoom in the image.
- `↓`: Zoom out the image.
- `Ctrl + 1`: Reset the image.
- `Ctrl + ←`: Rotate left the image.
- `Ctrl + →`: Rotate right the image.
## License
MIT

View File

@ -52,6 +52,7 @@ export default class ViewerCore extends React.Component<ViewerProps, ViewerCoreS
this.handleResize = this.handleResize.bind(this);
this.handleZoom = this.handleZoom.bind(this);
this.handleRotate = this.handleRotate.bind(this);
this.handleKeydown = this.handleKeydown.bind(this);
}
handleClose(e) {
@ -59,6 +60,7 @@ export default class ViewerCore extends React.Component<ViewerProps, ViewerCoreS
}
componentDidMount() {
this.bindEvent();
this.loadImg(this.state.activeIndex);
}
@ -173,10 +175,67 @@ export default class ViewerCore extends React.Component<ViewerProps, ViewerCoreS
this.loadImg(this.state.activeIndex);
}
handleKeydown(e) {
e.preventDefault();
let keyCode = e.keyCode || e.which || e.charCode;
switch (keyCode) {
// key: esc
case 27:
this.props.onClose();
break;
// key: ←
case 37:
if (e.ctrlKey) {
this.handleAction(ActionType.rotateLeft);
}else {
this.handleAction(ActionType.prev);
}
break;
// key: →
case 39:
if (e.ctrlKey) {
this.handleAction(ActionType.rotateRight);
}else {
this.handleAction(ActionType.next);
}
break;
// key: ↑
case 38:
this.handleAction(ActionType.zoomIn);
break;
// key: ↓
case 40:
this.handleAction(ActionType.zoomOut);
break;
// key: Ctrl + 1
case 49:
if (e.ctrlKey) {
this.loadImg(this.state.activeIndex);
}
break;
default:
break;
}
}
bindEvent(remove: boolean = false) {
let funcName = 'addEventListener';
if (remove) {
funcName = 'removeEventListener';
}
document[funcName]('keydown', this.handleKeydown, false);
}
componentWillReceiveProps(nextProps: ViewerProps) {
if (this.state.activeIndex !== nextProps.activeIndex || (!this.props.visible && nextProps.visible)) {
this.loadImg(nextProps.activeIndex);
}
if (!this.props.visible && nextProps.visible) {
this.bindEvent();
}
if (this.props.visible && !nextProps.visible) {
this.bindEvent(true);
}
}
render() {