UNPKG

3.02 kBJavaScriptView Raw
1import React, {PureComponent, Children, cloneElement} from 'react';
2import PropTypes from 'prop-types';
3
4export default class MultiTable extends PureComponent {
5 static propTypes = {
6 children: PropTypes.any.isRequired
7 };
8
9 componentDidUpdate(prevProps) {
10 if (prevProps.children) {
11 const prevSelections = prevProps.children.map(element => element.props.selection);
12 const prevFocusedIndex = prevSelections.findIndex(selection => selection.getFocused());
13 const prevFocused = prevSelections[prevFocusedIndex];
14
15 const currentSelections = this.props.children.map(element => element.props.selection);
16 const currentFocused = currentSelections.filter(selection => selection.getFocused());
17
18 if (currentFocused.includes(prevFocused)) {
19 prevProps.children[prevFocusedIndex].props.onSelect(prevFocused.resetFocus());
20 }
21 }
22 }
23
24 onUpPress = () => {
25 const {children: tables} = this.props;
26
27 const tableIndex = tables.findIndex(({props: {selection}}) => selection.getFocused());
28 const currentTable = tables[tableIndex].props;
29 const prevTable = tables[tableIndex - 1] ? tables[tableIndex - 1].props : null;
30
31 let newSelection = currentTable.selection.moveUp();
32 if (newSelection) {
33 currentTable.onSelect(newSelection);
34 } else if (prevTable) {
35 currentTable.onSelect(currentTable.selection.resetFocus());
36 newSelection = prevTable.selection.moveUp();
37 if (newSelection) {
38 prevTable.onSelect(newSelection);
39 }
40 }
41
42 return false;
43 };
44
45 onDownPress = () => {
46 const {children: tables} = this.props;
47
48 const tableIndex = tables.findIndex(({props: {selection}}) => selection.getFocused());
49 const currentTable = tables[tableIndex].props;
50 const nextTable = tables[tableIndex + 1] ? tables[tableIndex + 1].props : null;
51
52 let newSelection = currentTable.selection.moveDown();
53 if (newSelection) {
54 currentTable.onSelect(newSelection);
55 } else if (nextTable) {
56 currentTable.onSelect(currentTable.selection.resetFocus());
57 newSelection = nextTable.selection.moveDown();
58 if (newSelection) {
59 nextTable.onSelect(newSelection);
60 }
61 }
62
63 return false;
64 };
65
66 onEscPress = () => {
67 const {children} = this.props;
68 Children.forEach(children, ({props: {selection, onSelect}}) => {
69 onSelect(selection.reset());
70 });
71 };
72
73 onCmdAPress = () => {
74 const {children} = this.props;
75 Children.forEach(children, ({props: {selection, onSelect}}) => {
76 onSelect(selection.selectAll());
77 });
78 return false;
79 };
80
81 shortcuts = {
82 up: this.onUpPress,
83 down: this.onDownPress,
84 esc: this.onEscPress,
85 'command+a': this.onCmdAPress,
86 'ctrl+a': this.onCmdAPress
87 };
88
89 render() {
90 return (
91 <div data-test="ring-multitable">{
92 Children.map(this.props.children, child => {
93 const props = {shortcuts: this.shortcuts};
94 return cloneElement(child, props);
95 })
96 }</div>
97 );
98 }
99}