fdac58b4023fd8f78c2523f3d153706659d04221
[osm/UI.git] / skyquake / plugins / user-management / src / dashboard / dashboard.jsx
1 /*
2  * STANDARD_RIFT_IO_COPYRIGHT
3  */
4
5 import React from 'react';
6 import ReactDOM from 'react-dom';
7 import AppHeader from 'widgets/header/header.jsx';
8 import UserManagementStore from './userMgmtStore.js';
9 import SkyquakeComponent from 'widgets/skyquake_container/skyquakeComponent.jsx';
10 import 'style/layout.scss';
11 import './userMgmt.scss';
12 import {Panel, PanelWrapper} from 'widgets/panel/panel';
13
14
15 import TextInput from 'widgets/form_controls/textInput.jsx';
16 import Input from 'widgets/form_controls/input.jsx';
17 import Button, {ButtonGroup} from 'widgets/button/sq-button.jsx';
18 import SelectOption from 'widgets/form_controls/selectOption.jsx';
19 import 'widgets/form_controls/formControls.scss';
20 import imgAdd from '../../node_modules/open-iconic/svg/plus.svg'
21 import imgRemove from '../../node_modules/open-iconic/svg/trash.svg'
22
23 class UserManagementDashboard extends React.Component {
24     constructor(props) {
25         super(props);
26         this.Store = this.props.flux.stores.hasOwnProperty('UserManagementStore') ? this.props.flux.stores.UserManagementStore : this.props.flux.createStore(UserManagementStore);
27         this.Store.getUsers();
28         this.state = this.Store.getState();
29         this.actions = this.state.actions;
30     }
31     componentDidUpdate() {
32         let self = this;
33         ReactDOM.findDOMNode(this.UserList).addEventListener('transitionend', this.onTransitionEnd, false);
34         setTimeout(function() {
35             let element = self[`user-ref-${self.state.activeIndex}`]
36             element && !isElementInView(element) && element.scrollIntoView({block: 'end', behavior: 'smooth'});
37         })
38     }
39     componentWillMount() {
40         this.Store.listen(this.updateState);
41     }
42     componentWillUnmount() {
43         this.Store.unlisten(this.updateState);
44     }
45     updateState = (state) => {
46         this.setState(state);
47     }
48     updateInput = (key, e) => {
49         let property = key;
50         this.actions.handleUpdateInput({
51             [property]:e.target.value
52         })
53     }
54     disabledChange = (e) => {
55         this.actions.handleDisabledChange(e.target.checked);
56     }
57     platformChange = (platformRole, e) => {
58         this.actions.handlePlatformRoleUpdate(platformRole, e.currentTarget.checked);
59     }
60     addProjectRole = (e) => {
61         this.actions.handleAddProjectItem();
62     }
63     removeProjectRole = (i, e) => {
64         this.actions.handleRemoveProjectItem(i);
65     }
66     updateProjectRole = (i, e) => {
67         this.actions.handleUpdateProjectRole(i, e)
68     }
69     addUser = () => {
70         this.actions.handleAddUser();
71     }
72     viewUser = (un, index) => {
73         this.actions.viewUser(un, index);
74     }
75     closePanel = () => {
76         this.actions.handleCloseUserPanel();
77     }
78     updateUser = (e) => {
79         e.preventDefault();
80         e.stopPropagation();
81
82         this.Store.updateUser();
83     }
84     deleteUser = (e) => {
85         e.preventDefault();
86         e.stopPropagation();
87         this.Store.deleteUser({
88                 'user-name': this.state['user-name'],
89                 'user-domain': this.state['user-domain']
90             });
91     }
92     createUser = (e) => {
93         e.preventDefault();
94         e.stopPropagation();
95         if(this.state['new-password'] != this.state['confirm-password']) {
96             this.props.actions.showNotification('Passwords do not match')
97         } else {
98             this.Store.createUser({
99                 'user-name': this.state['user-name'],
100                 'user-domain': this.state['user-domain'],
101                 'password': this.state['new-password']
102                 // 'confirm-password': this.state['confirm-password']
103             });
104         }
105     }
106      evaluateSubmit = (e) => {
107         if (e.keyCode == 13) {
108             if (this.props.isEdit) {
109                 this.updateUser(e);
110             } else {
111                 this.createUser(e);
112             }
113             e.preventDefault();
114             e.stopPropagation();
115         }
116     }
117     onTransitionEnd = (e) => {
118         this.actions.handleHideColumns(e);
119         console.log('transition end')
120     }
121     render() {
122         let self = this;
123         let html;
124         let props = this.props;
125         let state = this.state;
126         html = (
127             <PanelWrapper className={`row userManagement ${!this.state.userOpen ? 'userList-open' : ''}`} style={{'alignContent': 'center', 'flexDirection': 'row'}} >
128                 <PanelWrapper ref={(div) => { this.UserList = div}} className={`column userList expanded ${this.state.userOpen ? 'collapsed ' : ' '} ${this.state.hideColumns ? 'hideColumns ' : ' '}`}>
129                     <Panel title="User List" style={{marginBottom: 0}} no-corners>
130                         <div className="tableRow tableRow--header">
131                             <div className="userName">
132                                 Username
133                             </div>
134                             <div>
135                                 Domain
136                             </div>
137                         </div>
138                         {state.users && state.users.map((u, k) => {
139                             let platformRoles = [];
140                             for(let role in u.platformRoles) {
141                                 platformRoles.push(<div>{`${role}: ${u.platformRoles[role]}`}</div>)
142                             }
143                             return (
144                                 <div ref={(el) => this[`user-ref-${k}`] = el} className={`tableRow tableRow--data ${((self.state.activeIndex == k) && self.state.userOpen) ? 'tableRow--data-active' : ''}`} key={k}>
145                                     <div
146                                         className={`userName userName-header ${((self.state.activeIndex == k) && self.state.userOpen) ? 'activeUser' : ''}`}
147                                         onClick={self.viewUser.bind(null, u, k)}>
148                                         {u['user-name']}
149                                     </div>
150                                     <div>
151                                         {u['user-domain']}
152                                     </div>
153
154
155                                 </div>
156                             )
157                         })}
158                     </Panel>
159                     <ButtonGroup  className="buttonGroup" style={{margin: '0 0.5rem 0.5rem', background: '#ddd', paddingBottom: '0.5rem'}}>
160                         <Button label="Add User" onClick={this.addUser} />
161                     </ButtonGroup>
162                 </PanelWrapper>
163                 <PanelWrapper onKeyUp={this.evaluateSubmit}
164                     className={`userAdmin column`}>
165                     <Panel
166                         title={state.isEdit ? state['user-name'] : 'Create User'}
167                         style={{marginBottom: 0}}
168                         hasCloseButton={this.closePanel}
169                         no-corners>
170                         <FormSection title="USER INFO">
171                         {
172                             this.state.isEdit ?
173                                 null
174                                 : <Input label="Username" value={state['user-name']} onChange={this.updateInput.bind(null, 'user-name')} />
175                         }
176                             <Input label="Domain" value={state['user-domain']}  onChange={this.updateInput.bind(null, 'user-domain')}></Input>
177                             <Input label="Disabled" onChange={this.disabledChange} checked={state.disabled} type="checkbox" />
178                         </FormSection>
179                         <FormSection title="PLATFORM ROLES">
180                             <Input label="Super Admin" onChange={this.platformChange.bind(null, 'super_admin')} checked={state.platformRoles.super_admin} type="checkbox" />
181                             <Input label="Platform Admin" onChange={this.platformChange.bind(null, 'platform_admin')}  checked={state.platformRoles.platform_admin} type="checkbox" />
182                             <Input label="Platform Oper" onChange={this.platformChange.bind(null, 'platform_oper')}  checked={state.platformRoles.platform_oper} type="checkbox" />
183                         </FormSection>
184                         <FormSection title="PROJECT ROLES">
185                             <InputCollection
186                                 inital={true}
187                                 type='select'
188                                 options={state.projectRolesOptions}
189                                 collection={state.projectRoles}
190                                 onChange={this.updateProjectRole}
191                                 AddItemFn={this.addProjectRole}
192                                 RemoveItemFn={this.removeProjectRole}
193                                 />
194                         </FormSection>
195                         { this.state.isEdit ?
196                             (
197                                 <FormSection title="PASSWORD CHANGE">
198                                     <Input label="OLD PASSWORD" type="password" value={state['old-password']} onChange={this.updateInput.bind(null, 'old-password')} />
199                                     <Input label="NEW PASSWORD" type="password" value={state['new-password']}  onChange={this.updateInput.bind(null, 'new-password')}/>
200                                     <Input label="REPEAT NEW PASSWORD" type="password"  value={state['confirm-password']}  onChange={this.updateInput.bind(null, 'confirm-password')}/>
201                                 </FormSection>
202                             ) :
203                             (
204                                 <FormSection title="CREATE PASSWORD">
205                                     <Input label="CREATE PASSWORD" type="password" value={state.newPassword}  onChange={this.updateInput.bind(null, 'new-password')}/>
206                                     <Input label="REPEAT PASSWORD" type="password"  value={state.repeatNewPassword}  onChange={this.updateInput.bind(null, 'confirm-password')}/>
207                                 </FormSection>
208                             )
209                         }
210
211                     </Panel>
212
213                         {
214                             state.isEdit ?
215                             (
216                                 <ButtonGroup className="buttonGroup">
217                                     <Button label="Update" type="submit" onClick={this.updateUser} />
218                                     <Button label="Delete" onClick={this.deleteUser} />
219                                 </ButtonGroup>
220                             )
221                             : (
222                                 <ButtonGroup className="buttonGroup">
223                                     <Button label="Create" type="submit" onClick={this.createUser}  />
224                                 </ButtonGroup>
225                             )
226                         }
227                 </PanelWrapper>
228
229             </PanelWrapper>
230         );
231         return html;
232     }
233 }
234 // onClick={this.Store.update.bind(null, Account)}
235 UserManagementDashboard.contextTypes = {
236     router: React.PropTypes.object
237 };
238
239 UserManagementDashboard.defaultProps = {
240     userList: [],
241     selectedUser: {}
242 }
243
244 export default SkyquakeComponent(UserManagementDashboard);
245
246
247 function isElementInView(el) {
248     var rect = el && el.getBoundingClientRect() || {};
249
250     return (
251         rect.top >= 0 &&
252         rect.left >= 0 &&
253         rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
254         rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
255     );
256 }
257
258
259 /**
260  * AddItemFn:
261  */
262 class InputCollection extends React.Component {
263     constructor(props) {
264         super(props);
265         this.collection = props.collection;
266     }
267     buildTextInput(onChange, v, i) {
268         return (
269             <Input
270                 style={{flex: '1 1'}}
271                 key={i}
272                 value={v}
273                 onChange= {onChange.bind(null, i)}
274             />
275         )
276     }
277     buildSelectOption(initial, options, onChange, v, i) {
278         return (
279             <SelectOption
280                 key={`${i}-${v.replace(' ', '_')}`}
281                 intial={initial}
282                 defaultValue={v}
283                 options={options}
284                 onChange={onChange.bind(null, i)}
285             />
286         );
287     }
288     showInput() {
289
290     }
291     render() {
292         const props = this.props;
293         let inputType;
294         let className = "InputCollection";
295         if (props.className) {
296             className = `${className} ${props.className}`;
297         }
298         if (props.type == 'select') {
299             inputType = this.buildSelectOption.bind(this, props.initial, props.options, props.onChange);
300         } else {
301             inputType = this.buildTextInput.bind(this, props.onChange)
302         }
303         let html = (
304             <div className="InputCollection-wrapper">
305                 {props.collection.map((v,i) => {
306                     return (
307                         <div key={i} className={className} >
308                             {inputType(v, i)}
309                             <span onClick={props.RemoveItemFn.bind(null, i)} className="removeInput"><img src={imgRemove} />Remove</span>
310                         </div>
311                     )
312                 })}
313                 <span onClick={props.AddItemFn} className="addInput"><img src={imgAdd} />Add</span>
314             </div>
315         );
316         return html;
317     }
318 }
319
320 InputCollection.defaultProps = {
321     input: Input,
322     collection: [],
323     onChange: function(i, e) {
324         console.log(`
325                         Updating with: ${e.target.value}
326                         At index of: ${i}
327                     `)
328     },
329     AddItemFn: function(e) {
330         console.log(`Adding a new item to collection`)
331     },
332     RemoveItemFn: function(i, e) {
333         console.log(`Removing item from collection at index of: ${i}`)
334     }
335 }
336
337 class FormSection extends React.Component {
338     render() {
339         let className = 'FormSection ' + this.props.className;
340         let html = (
341             <div
342                 style={this.props.style}
343                 className={className}
344             >
345                 <div className="FormSection-title">
346                     {this.props.title}
347                 </div>
348                 <div className="FormSection-body">
349                     {this.props.children}
350                 </div>
351             </div>
352         );
353         return html;
354     }
355 }
356
357 FormSection.defaultProps = {
358     className: ''
359 }