app.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /**
  2. * @author oldj
  3. * @blog http://oldj.net
  4. */
  5. 'use strict'
  6. import React from 'react'
  7. import Panel from './panel/panel'
  8. import Content from './content/content'
  9. //import SudoPrompt from './frame/sudo'
  10. import EditPrompt from './frame/edit'
  11. //import PreferencesPrompt from './frame/preferences'
  12. import Agent from './Agent'
  13. import {reg as events_reg} from './events/index'
  14. import './app.less'
  15. export default class App extends React.Component {
  16. constructor (props) {
  17. super(props)
  18. this.state = {
  19. list: [], // 用户的 hosts 列表
  20. sys_hosts: {}, // 系统 hosts
  21. current: {}, // 当前 hosts
  22. lang: {} // 语言
  23. }
  24. this.loadHosts()
  25. Agent.pact('getLang').then(lang => {
  26. this.setState({lang})
  27. })
  28. events_reg(this)
  29. }
  30. loadHosts () {
  31. Agent.pact('getHosts').then(data => {
  32. this.setState({
  33. list: data.list,
  34. sys_hosts: data.sys_hosts,
  35. current: data.sys_hosts
  36. })
  37. })
  38. }
  39. setCurrent (hosts) {
  40. if (hosts.is_sys) {
  41. Agent.pact('getSysHosts')
  42. .then(_hosts => {
  43. this.setState({
  44. sys_hosts: _hosts,
  45. current: _hosts
  46. })
  47. })
  48. } else {
  49. this.setState({
  50. current: hosts
  51. })
  52. }
  53. }
  54. static isReadOnly (hosts) {
  55. return !hosts || hosts.is_sys || hosts.where === 'remote' ||
  56. hosts.where === 'group'
  57. }
  58. toSave () {
  59. clearTimeout(this._t)
  60. this._t = setTimeout(() => {
  61. Agent.emit('save', this.state.list)
  62. }, 1000)
  63. }
  64. setHostsContent (v) {
  65. if (this.state.current.content === v) return // not changed
  66. this.state.current.content = v || ''
  67. this.toSave()
  68. }
  69. componentDidMount () {
  70. window.addEventListener('keydown', (e) => {
  71. if (e.keyCode === 27) {
  72. Agent.emit('esc')
  73. }
  74. }, false)
  75. }
  76. render () {
  77. let current = this.state.current
  78. return (
  79. <div id="app" className={'platform-' + Agent.platform}>
  80. <Panel
  81. list={this.state.list}
  82. sys_hosts={this.state.sys_hosts}
  83. current={current}
  84. setCurrent={this.setCurrent.bind(this)}
  85. lang={this.state.lang}
  86. />
  87. <Content
  88. current={current}
  89. readonly={App.isReadOnly(current)}
  90. setHostsContent={this.setHostsContent.bind(this)}
  91. lang={this.state.lang}
  92. />
  93. <div className="frames">
  94. {/*<SudoPrompt/>*/}
  95. <EditPrompt lang={this.state.lang} list={this.state.list}/>
  96. {/*<PreferencesPrompt/>*/}
  97. </div>
  98. </div>
  99. )
  100. }
  101. }