d7cb6005a4bec8f33ee862c27c3daf5e4c78e472
[osm/UI.git] / skyquake / plugins / user_management / src / userProfile / userProfile.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 UserProfileStore from './userProfileStore.js';
9 import SkyquakeComponent from 'widgets/skyquake_container/skyquakeComponent.jsx';
10 import 'style/layout.scss';
11 import '../dashboard/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 UserProfileDashboard extends React.Component {
24     constructor(props) {
25         super(props);
26         this.Store = this.props.flux.stores.hasOwnProperty('UserProfileStore') ? this.props.flux.stores.UserProfileStore : this.props.flux.createStore(UserProfileStore);
27        this.state = this.Store.getState();
28        this.actions = this.state.actions;
29
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     editUser = () => {
76         this.actions.editUser(false);
77     }
78     cancelEditUser = () => {
79         this.actions.editUser(true)
80     }
81     osePanel = () => {
82         this.actions.handleCloseUserPanel();
83     }
84     // updateUser = (e) => {
85     //     e.preventDefault();
86     //     e.stopPropagation();
87
88     //     this.Store.updateUser();
89     // }
90     deleteUser = (e) => {
91         e.preventDefault();
92         e.stopPropagation();
93         this.Store.deleteUser({
94                 'user-name': this.state['user-name'],
95                 'user-domain': this.state['user-domain']
96             });
97     }
98     createUser = (e) => {
99         e.preventDefault();
100         e.stopPropagation();
101         if(this.state['new-password'] != this.state['confirm-password']) {
102             this.props.actions.showNotification('Passwords do not match')
103         } else {
104             this.Store.createUser({
105                 'user-name': this.state['user-name'],
106                 'user-domain': this.state['user-domain'],
107                 'password': this.state['new-password']
108                 // 'confirm-password': this.state['confirm-password']
109             });
110         }
111     }
112     updateUser = (e) => {
113         let self = this;
114         e.preventDefault();
115         e.stopPropagation();
116         let validatedPasswords = validatePasswordFields(this.state);
117         if(validatedPasswords) {
118             this.Store.updateUser(_.merge({
119                             'user-name': this.context.userProfile.userId,
120                             'user-domain': this.state['user-domain'],
121                             'password': this.state['new-password']
122                         }));
123         }
124         function validatePasswordFields(state) {
125             let oldOne = state['old-password'];
126             let newOne = state['new-password'];
127             let confirmOne = state['confirm-password'];
128             if(true) {
129                 if(oldOne == newOne) {
130                     self.props.actions.showNotification('Your new password must not match your old one');
131                     return false;
132                 }
133                 if(newOne != confirmOne) {
134                     self.props.actions.showNotification('Passwords do not match');
135                     return false;
136                 }
137                 return {
138                     // 'old-password': oldOne,
139                     'new-password': newOne,
140                     'confirm-password': confirmOne
141                 }
142             } else {
143                 return {};
144             }
145         }
146     }
147      evaluateSubmit = (e) => {
148         if (e.keyCode == 13) {
149             if (this.props.isEdit) {
150                 this.updateUser(e);
151             } else {
152                 this.createUser(e);
153             }
154             e.preventDefault();
155             e.stopPropagation();
156         }
157     }
158     onTransitionEnd = (e) => {
159         this.actions.handleHideColumns(e);
160         console.log('transition end')
161     }
162     disableChange = (e) => {
163         let value = e.target.value;
164         value = value.toUpperCase();
165         if (value=="TRUE") {
166             value = true;
167         } else {
168             value = false;
169         }
170         console.log(value)
171     }
172     render() {
173
174         let self = this;
175         const User = this.context.userProfile || {};
176         let html;
177         let props = this.props;
178         let state = this.state;
179         let passwordSectionHTML = null;
180         let formButtonsHTML = (
181             <ButtonGroup className="buttonGroup">
182                 <Button label="EDIT" type="submit" onClick={this.editUser} />
183             </ButtonGroup>
184         );
185         passwordSectionHTML = (
186             (
187                 <FormSection title="PASSWORD CHANGE">
188                     <Input label="NEW PASSWORD" type="password" value={state['new-password']}  onChange={this.updateInput.bind(null, 'new-password')}/>
189                     <Input label="REPEAT NEW PASSWORD" type="password"  value={state['confirm-password']}  onChange={this.updateInput.bind(null, 'confirm-password')}/>
190                 </FormSection>
191             )
192         );
193         formButtonsHTML = (
194                 <ButtonGroup className="buttonGroup">
195                     <Button label="Update" type="submit" onClick={this.updateUser} />
196                 </ButtonGroup>
197         )
198
199         html = (
200             <PanelWrapper column>
201                 <PanelWrapper className={`row userManagement ${!this.state.userOpen ? 'userList-open' : ''}`} style={{'flexDirection': 'row'}} >
202                     <PanelWrapper ref={(div) => { this.UserList = div}} className={`column userList expanded hideColumns`}>
203                         <Panel title={User.userId} style={{marginBottom: 0}} no-corners>
204                             <FormSection title="USER INFO">
205                                 <table className="userProfile-table">
206                                     <thead>
207                                         <tr>
208                                             <td>Project</td>
209                                             <td>Role</td>
210                                         </tr>
211                                     </thead>
212                                     <tbody>
213                                         {
214                                             User.data && User.data.projectId && User.data.projectId.map((p,i)=> {
215                                                 let project = User.data.project[p];
216                                                 let projectConfig = project && project.data['project-config'];
217                                                 let userRoles = [];
218                                                 return (
219                                                     <tr key={i}>
220                                                         <td>
221                                                             {p}
222                                                         </td>
223                                                         <td>
224                                                             {
225                                                                 project && Object.keys(project.role).map(function(k) {
226                                                                     return <div>{k}</div>
227                                                                 })
228                                                             }
229                                                         </td>
230                                                     </tr>
231                                                 )
232                                             })
233                                         }
234                                     </tbody>
235                                 </table>
236                             </FormSection>
237                             {passwordSectionHTML}
238
239                         </Panel>
240                          {formButtonsHTML}
241                     </PanelWrapper>
242
243                 </PanelWrapper>
244             </PanelWrapper>
245         );
246         return html;
247     }
248 }
249 // onClick={this.Store.update.bind(null, Account)}
250 UserProfileDashboard.contextTypes = {
251     router: React.PropTypes.object,
252     userProfile: React.PropTypes.object
253 };
254
255 UserProfileDashboard.defaultProps = {
256     userList: [],
257     selectedUser: {}
258 }
259
260 export default SkyquakeComponent(UserProfileDashboard);
261
262
263 function isElementInView(el) {
264     var rect = el && el.getBoundingClientRect() || {};
265
266     return (
267         rect.top >= 0 &&
268         rect.left >= 0 &&
269         rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
270         rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
271     );
272 }
273
274
275 // isReadOnly={state.isReadOnly} disabled={state.disabled} onChange={this.disableChange}
276
277 class isDisabled extends React.Component {
278     constructor(props) {
279         super(props);
280     }
281     render() {
282         let props = this.props;
283         return (<div/>)
284     }
285 }
286
287 /**
288  * AddItemFn:
289  */
290 class InputCollection extends React.Component {
291     constructor(props) {
292         super(props);
293         this.collection = props.collection;
294     }
295     buildTextInput(onChange, v, i) {
296         return (
297             <Input
298                 readonly={this.props.readonly}
299                 style={{flex: '1 1'}}
300                 key={i}
301                 value={v}
302                 onChange= {onChange.bind(null, i)}
303             />
304         )
305     }
306     buildSelectOption(initial, options, onChange, v, i) {
307         return (
308             <SelectOption
309                 readonly={this.props.readonly}
310                 key={`${i}-${v.replace(' ', '_')}`}
311                 intial={initial}
312                 defaultValue={v}
313                 options={options}
314                 onChange={onChange.bind(null, i)}
315             />
316         );
317     }
318     showInput() {
319
320     }
321     render() {
322         const props = this.props;
323         let inputType;
324         let className = "InputCollection";
325         if (props.className) {
326             className = `${className} ${props.className}`;
327         }
328         if (props.type == 'select') {
329             inputType = this.buildSelectOption.bind(this, props.initial, props.options, props.onChange);
330         } else {
331             inputType = this.buildTextInput.bind(this, props.onChange)
332         }
333         let html = (
334             <div className="InputCollection-wrapper">
335                 {props.collection.map((v,i) => {
336                     return (
337                         <div key={i} className={className} >
338                             {inputType(v, i)}
339                             {
340                                 props.readonly ? null : <span onClick={props.RemoveItemFn.bind(null, i)} className="removeInput"><img src={imgRemove} />Remove</span>}
341                         </div>
342                     )
343                 })}
344                 { props.readonly ? null : <span onClick={props.AddItemFn} className="addInput"><img src={imgAdd} />Add</span>}
345             </div>
346         );
347         return html;
348     }
349 }
350
351 InputCollection.defaultProps = {
352     input: Input,
353     collection: [],
354     onChange: function(i, e) {
355         console.log(`
356                         Updating with: ${e.target.value}
357                         At index of: ${i}
358                     `)
359     },
360     AddItemFn: function(e) {
361         console.log(`Adding a new item to collection`)
362     },
363     RemoveItemFn: function(i, e) {
364         console.log(`Removing item from collection at index of: ${i}`)
365     }
366 }
367
368 class FormSection extends React.Component {
369     render() {
370         let className = 'FormSection ' + this.props.className;
371         let html = (
372             <div
373                 style={this.props.style}
374                 className={className}
375             >
376                 <div className="FormSection-title">
377                     {this.props.title}
378                 </div>
379                 <div className="FormSection-body">
380                     {this.props.children}
381                 </div>
382             </div>
383         );
384         return html;
385     }
386 }
387
388 FormSection.defaultProps = {
389     className: ''
390 }