|
| 1 | +import React from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | + |
| 4 | +import { safeClick, stopPropagation } from '../utils/event-handlers'; |
| 5 | +import { isFunction } from '../utils/types'; |
| 6 | + |
| 7 | +export function TableActions({ doc, docIndex, actions }) { |
| 8 | + if (!actions) { |
| 9 | + return null; |
| 10 | + } |
| 11 | + |
| 12 | + const normalizedActions = normalizeAction(actions, doc, docIndex); |
| 13 | + |
| 14 | + return ( |
| 15 | + <td className="text-center"> |
| 16 | + {normalizedActions.map((action, actionIndex) => ( |
| 17 | + <span key={actionIndex} className={actionIndex > 0 ? 'ml-2' : ''}> |
| 18 | + <TableAction doc={doc} docIndex={docIndex} action={action} /> |
| 19 | + </span> |
| 20 | + ))} |
| 21 | + </td> |
| 22 | + ); |
| 23 | +} |
| 24 | + |
| 25 | +TableActions.propTypes = { |
| 26 | + doc: PropTypes.object.isRequired, |
| 27 | + docIndex: PropTypes.number.isRequired, |
| 28 | + actions: PropTypes.oneOfType([PropTypes.func, PropTypes.arrayOf(PropTypes.object)]), |
| 29 | +}; |
| 30 | + |
| 31 | +function TableAction({ doc, docIndex, action }) { |
| 32 | + if (isFunction(action)) { |
| 33 | + return action(doc, docIndex) || null; |
| 34 | + } |
| 35 | + |
| 36 | + if (action.onClick || action.link) { |
| 37 | + return ( |
| 38 | + <a title={action.title} {...getActionProps(action, doc, docIndex)}> |
| 39 | + {action.content} |
| 40 | + </a> |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + return action.content; |
| 45 | +} |
| 46 | + |
| 47 | +TableAction.propTypes = { |
| 48 | + doc: PropTypes.object.isRequired, |
| 49 | + docIndex: PropTypes.number.isRequired, |
| 50 | + action: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired, |
| 51 | +}; |
| 52 | + |
| 53 | +function getActionProps(action, doc, docIndex) { |
| 54 | + const props = {}; |
| 55 | + |
| 56 | + if (action.onClick) { |
| 57 | + props.href = ''; |
| 58 | + props.onClick = safeClick(action.onClick, doc, docIndex); |
| 59 | + } else if (action.link) { |
| 60 | + props.onClick = stopPropagation; |
| 61 | + props.href = action.link(doc, docIndex); |
| 62 | + } |
| 63 | + |
| 64 | + return props; |
| 65 | +} |
| 66 | + |
| 67 | +function normalizeAction(actions, doc, docIndex) { |
| 68 | + if (isFunction(actions)) { |
| 69 | + return actions(doc, docIndex); |
| 70 | + } |
| 71 | + |
| 72 | + return actions; |
| 73 | +} |
0 commit comments