SourceTable.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import React from 'react'
  2. import memoizeOne from 'memoize-one'
  3. import { Input, Select, Row, Col, Tree, Icon } from 'antd'
  4. import { AntTreeNode, AntTreeNodeSelectedEvent, AntTreeNodeExpandedEvent } from 'antd/lib/tree/Tree'
  5. const { Search } = Input
  6. const { Option } = Select
  7. const { TreeNode } = Tree
  8. import { ISource, IColumn, ISchema } from 'containers/Source/types'
  9. import { IView } from '../types'
  10. import { SQL_DATE_TYPES, SQL_NUMBER_TYPES, SQL_STRING_TYPES } from 'app/globalConstants'
  11. import { filterSelectOption } from 'app/utils/util'
  12. import utilStyles from 'assets/less/util.less'
  13. import Styles from 'containers/View/View.less'
  14. import { shallowEqual } from 'react-redux'
  15. interface ISourceTableProps {
  16. view: IView
  17. sources: ISource[]
  18. schema: ISchema
  19. onViewChange: (propName: keyof(IView), value: string | number) => void
  20. onSourceSelect: (sourceId: number) => void
  21. onDatabaseSelect: (sourceId: number, databaseName: string) => void
  22. onTableSelect: (sourceId: number, databaseName: string, tableName: string) => void
  23. }
  24. interface ISourceTableStates {
  25. filterKeyword: string
  26. expandedNodeKeys: string[]
  27. autoExpandTable: boolean
  28. }
  29. export class SourceTable extends React.Component<ISourceTableProps, ISourceTableStates> {
  30. public state: ISourceTableStates = {
  31. filterKeyword: '',
  32. expandedNodeKeys: [],
  33. autoExpandTable: true
  34. }
  35. private inputChange = (propName: keyof IView) => (e: React.ChangeEvent<HTMLInputElement>) => {
  36. this.props.onViewChange(propName, e.target.value)
  37. }
  38. private selectSource = (sourceId: number) => {
  39. const { onViewChange, onSourceSelect } = this.props
  40. this.setState({
  41. expandedNodeKeys: [],
  42. autoExpandTable: true
  43. })
  44. onViewChange('sourceId', sourceId)
  45. onSourceSelect(sourceId)
  46. }
  47. private iconDatabase = <Icon key="iconDatabase" title="数据库" type="database" />
  48. private iconTable = <Icon key="iconTable" title="数据表" type="table" />
  49. private iconDate = <Icon key="iconDate" title="日期" type="calendar" />
  50. private iconKey = <Icon key="iconKey" title="主键" type="key" />
  51. private iconText = <Icon key="iconText" title="文本" type="font-size" />
  52. private iconValue = <Icon key="iconValue" title="数值" type="calculator" />
  53. private getColumnIcons (col: IColumn, primaryKeys: string[]) {
  54. const { type: sqlType, name } = col
  55. if (primaryKeys.includes(name)) { return this.iconKey }
  56. if (SQL_STRING_TYPES.includes(sqlType)) { return this.iconText }
  57. if (SQL_NUMBER_TYPES.includes(sqlType)) { return this.iconValue }
  58. if (SQL_DATE_TYPES.includes(sqlType)) { return this.iconDate }
  59. }
  60. private highlightTitle (title: string, regex: RegExp) {
  61. if (!title || !regex) { return title }
  62. return (
  63. <span
  64. dangerouslySetInnerHTML={{
  65. __html: title.replace(regex, `<span class="${utilStyles.highlight}">$1</span>`)
  66. }}
  67. />
  68. )
  69. }
  70. private renderTableColumns = memoizeOne((
  71. sourceId: number, schema: ISchema, filterKeyword: string, onDatabaseSelect: ISourceTableProps['onDatabaseSelect']) => {
  72. const { mapDatabases, mapTables, mapColumns } = schema
  73. if (!sourceId) { return null }
  74. const databasesInfo = mapDatabases[sourceId]
  75. if (!databasesInfo) { return null }
  76. const filterReg = filterKeyword ? new RegExp(`(${filterKeyword})`, 'i') : null
  77. const treeNodes = databasesInfo.reduce((databaseNodes, dbName) => {
  78. const tablesInfo = mapTables[`${sourceId}_${dbName}`]
  79. if (!tablesInfo) {
  80. if (Object.values(databasesInfo).length === 1) {
  81. onDatabaseSelect(sourceId, dbName)
  82. return databaseNodes
  83. }
  84. databaseNodes.push(<TreeNode icon={this.iconDatabase} title={dbName} key={dbName} isLeaf={false} dataRef={['database', dbName]} />)
  85. return databaseNodes
  86. }
  87. let filterTables = tablesInfo.tables
  88. if (filterReg) {
  89. filterTables = filterTables.filter(({ name: tableName }) => {
  90. if (filterReg.test(tableName)) { return true }
  91. const columnsInfo = mapColumns[[sourceId, dbName, tableName].join('_')]
  92. if (!columnsInfo) { return false }
  93. const hasFilterColumns = columnsInfo.columns.some((col) => filterReg.test(col.name))
  94. return hasFilterColumns
  95. })
  96. }
  97. const tableNodes = filterTables.map(({ name: tableName }) => {
  98. const columnsInfo = mapColumns[[sourceId, dbName, tableName].join('_')]
  99. const columnNodes = !columnsInfo ? null : columnsInfo.columns.reduce((nodes, col) => {
  100. // if (filterReg && !filterReg.test(col.name)) { return nodes }
  101. const primaryKeysRemain = [...columnsInfo.primaryKeys]
  102. const icons = this.getColumnIcons(col, columnsInfo.primaryKeys)
  103. const columnTitle = this.highlightTitle(col.name, filterReg)
  104. const currentNode = (
  105. <TreeNode title={columnTitle} icon={icons} key={`${dbName}_${tableName}_${col.name}`} isLeaf={true} dataRef={['column']} />
  106. )
  107. if (primaryKeysRemain.includes(col.name)) {
  108. // make the primary key column be the top
  109. nodes.splice(columnsInfo.primaryKeys.length - primaryKeysRemain.length, 0, currentNode)
  110. primaryKeysRemain.splice(primaryKeysRemain.indexOf(col.name), 1)
  111. } else {
  112. nodes.push(currentNode)
  113. }
  114. return nodes
  115. }, [])
  116. return (<TreeNode icon={this.iconTable} title={tableName} key={`${dbName}_${tableName}`} isLeaf={false} dataRef={['table', dbName, tableName]}>{columnNodes}</TreeNode>)
  117. })
  118. const nodes = Object.values(databasesInfo).length === 1 ? tableNodes
  119. : (<TreeNode icon={this.iconDatabase} title={dbName} key={dbName} isLeaf={false} dataRef={['database']}>{tableNodes}</TreeNode>)
  120. databaseNodes.push(nodes)
  121. return databaseNodes
  122. }, [])
  123. return treeNodes
  124. }
  125. )
  126. private loadTreeData = (node: AntTreeNode) => new Promise<void>((resolve) => {
  127. const { dataRef } = node.props
  128. if (dataRef === 'column') {
  129. resolve()
  130. return
  131. }
  132. const { schema, view, onDatabaseSelect, onTableSelect } = this.props
  133. const { sourceId } = view
  134. const { mapTables, mapColumns } = schema
  135. const [nodeType, dbName, tableName] = dataRef
  136. switch (nodeType) {
  137. case 'database':
  138. if (!mapTables[`${sourceId}_${dbName}`]) {
  139. onDatabaseSelect(sourceId, dbName)
  140. }
  141. break
  142. case 'table':
  143. if (!mapColumns[`${sourceId}_${dbName}_${tableName}`]) {
  144. onTableSelect(sourceId, dbName, tableName)
  145. }
  146. break
  147. }
  148. resolve()
  149. })
  150. private treeNodeSelect = (_: string[], { node }: AntTreeNodeSelectedEvent) => {
  151. const { dataRef, eventKey: nodeKey } = node.props
  152. const [nodeType] = dataRef
  153. if (nodeType === 'column') { return }
  154. const { expandedNodeKeys } = this.state
  155. if (expandedNodeKeys.includes(nodeKey)) { return }
  156. this.setState({
  157. expandedNodeKeys: [...expandedNodeKeys, nodeKey],
  158. autoExpandTable: false
  159. })
  160. }
  161. private treeNodeExpand = (expandedNodeKeys: string[]) => {
  162. this.setState({
  163. expandedNodeKeys,
  164. autoExpandTable: false
  165. })
  166. }
  167. private filterKeywordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  168. const filterKeyword = e.target.value
  169. const { schema, view } = this.props
  170. const { mapTables, mapColumns } = schema
  171. const expandedNodeKeys = new Set<string>()
  172. if (filterKeyword) {
  173. const regex = new RegExp(`(${filterKeyword})`, 'gi')
  174. Object.values(mapTables).forEach((tablesInfo) => {
  175. if (!tablesInfo) { return }
  176. const { tables, dbName, sourceId } = tablesInfo
  177. if (sourceId !== view.sourceId) { return }
  178. const shouldExpand = regex.test(dbName) ||
  179. tables.some(({ name: tableName }) => regex.test(tableName))
  180. if (shouldExpand) {
  181. expandedNodeKeys.add(dbName)
  182. }
  183. })
  184. Object.values(mapColumns).forEach((columnsInfo) => {
  185. if (!columnsInfo) { return }
  186. const { columns, tableName, dbName, sourceId } = columnsInfo
  187. if (sourceId !== view.sourceId) { return }
  188. const shouldExpand = regex.test(tableName) ||
  189. columns.some(({ name: columnName }) => regex.test(columnName))
  190. if (shouldExpand) {
  191. expandedNodeKeys.add(`${dbName}_${tableName}`)
  192. expandedNodeKeys.add(`${dbName}`)
  193. }
  194. })
  195. }
  196. this.setState({
  197. filterKeyword,
  198. autoExpandTable: true,
  199. expandedNodeKeys: Array.from(expandedNodeKeys)
  200. })
  201. }
  202. // FIXED: sql 的改动会改变view,此组件依赖view,会进行多余的render,此处进行优化
  203. public shouldComponentUpdate(nextProps: ISourceTableProps, nextState: ISourceTableStates) {
  204. const {sources, schema, view: {name, description, sourceId}} = this.props
  205. if (
  206. !shallowEqual(nextState, this.state) ||
  207. nextProps.sources !== sources ||
  208. nextProps.schema !== schema ||
  209. nextProps.view.name !== name ||
  210. nextProps.view.description !== description ||
  211. nextProps.view.sourceId !== sourceId
  212. ) {
  213. return true
  214. }
  215. return false
  216. }
  217. public render () {
  218. const { view, sources, schema, onDatabaseSelect } = this.props
  219. const { filterKeyword, expandedNodeKeys } = this.state
  220. const { name: viewName, description: viewDesc, sourceId } = view
  221. return (
  222. <div className={Styles.sourceTable}>
  223. <Row gutter={16}>
  224. <Col span={24}>
  225. <Input placeholder="名称" value={viewName} onChange={this.inputChange('name')} />
  226. </Col>
  227. <Col span={24}>
  228. <Input placeholder="描述" value={viewDesc} onChange={this.inputChange('description')} />
  229. </Col>
  230. <Col span={24}>
  231. <Select
  232. showSearch
  233. dropdownMatchSelectWidth={false}
  234. placeholder="数据源"
  235. style={{width: '100%'}}
  236. value={sourceId}
  237. onChange={this.selectSource}
  238. filterOption={filterSelectOption}
  239. >
  240. {sources.map(({ id, name }) => (<Option key={id.toString()} value={id}>{name}</Option>))}
  241. </Select>
  242. </Col>
  243. <Col span={24}>
  244. <Search
  245. placeholder="搜索表/字段名称"
  246. value={filterKeyword}
  247. onChange={this.filterKeywordChange}
  248. />
  249. </Col>
  250. </Row>
  251. <div className={Styles.tree}>
  252. <Tree
  253. showIcon
  254. key={view.sourceId}
  255. loadData={this.loadTreeData}
  256. onSelect={this.treeNodeSelect}
  257. onExpand={this.treeNodeExpand}
  258. expandedKeys={expandedNodeKeys}
  259. >
  260. {this.renderTableColumns(sourceId, schema, filterKeyword, onDatabaseSelect)}
  261. </Tree>
  262. </div>
  263. </div>
  264. )
  265. }
  266. }
  267. export default SourceTable