OSDN Git Service

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