OSDN Git Service

merge dashboard into electron
[bytom/bytom-electron.git] / src / features / shared / components / KeyValueTable / KeyValueTable.jsx
1 import React from 'react'
2 import styles from './KeyValueTable.scss'
3 import {Section} from 'features/shared/components'
4 import {Link} from 'react-router'
5 import {size, sample, isArray, isObject, toPairs} from 'lodash'
6
7 class KeyValueTable extends React.Component {
8   shouldUsePre(item) {
9     if (item.pre) return true
10
11     return item.value != null && (typeof item.value == 'object')
12   }
13
14   stringify(value) {
15     if (isObject(value) && size(value) == 1) {
16       // Random sample will always be the lone value here
17       let sampled = sample(value)
18
19       if (!isObject(sampled)) {
20         if (isArray(value)) return JSON.stringify(value)
21
22         // Manually construct single-key object stringify for better formatting
23         const pair = toPairs(value)[0]
24         return `{${JSON.stringify(pair[0])}: ${JSON.stringify(pair[1])}}`
25       }
26     }
27
28     return JSON.stringify(value, null, '  ')
29   }
30
31   renderValue(item) {
32     let value = item.value
33     if (this.shouldUsePre(item)) {
34       value = <pre className={styles.pre}>{this.stringify(item.value)}</pre>
35     }
36     if (item.link) {
37       value = <Link to={item.link}>{value}</Link>
38     }
39
40     if (value === undefined || value === null || value === '') {
41       value = '-'
42     }
43
44     return value
45   }
46
47   render() {
48     const lang = this.props.lang
49     return (
50       <Section
51         title={this.props.title}
52         actions={this.props.actions}>
53         <table className={styles.table}>
54           <tbody>
55           {this.props.items.map((item) => {
56             return <tr key={item.label}>
57               <td className={styles.label}>{item.label}</td>
58               <td className={styles.value}>{this.renderValue(item)}
59                 {item.editUrl && <Link to={item.editUrl} className={styles.edit}>
60                   <span
61                     className={`${styles.pencil} glyphicon glyphicon-pencil`}></span>{lang === 'zh' ? '编辑' : 'Edit'}
62                 </Link>}
63                 {item.program && <button  onClick={item.program} className={`${styles.detail} ${styles.edit} btn btn-link`}>
64                   { lang === 'zh' ? '合约程序': 'Program' }
65                 </button>}
66               </td>
67             </tr>
68           })}
69           </tbody>
70         </table>
71       </Section>
72     )
73   }
74 }
75
76 export default KeyValueTable