a7868583c9553f9a1de6ae42842ccdc17b3c16ee
[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                         <div  className="buttonSection">
241                             {formButtonsHTML}
242                         </div>
243                     </PanelWrapper>
244
245                 </PanelWrapper>
246             </PanelWrapper>
247         );
248         return html;
249     }
250 }
251 // onClick={this.Store.update.bind(null, Account)}
252 UserProfileDashboard.contextTypes = {
253     router: React.PropTypes.object,
254     userProfile: React.PropTypes.object
255 };
256
257 UserProfileDashboard.defaultProps = {
258     userList: [],
259     selectedUser: {}
260 }
261
262 export default SkyquakeComponent(UserProfileDashboard);
263
264
265 function isElementInView(el) {
266     var rect = el && el.getBoundingClientRect() || {};
267
268     return (
269         rect.top >= 0 &&
270         rect.left >= 0 &&
271         rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
272         rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
273     );
274 }
275
276
277 // isReadOnly={state.isReadOnly} disabled={state.disabled} onChange={this.disableChange}
278
279 class isDisabled extends React.Component {
280     constructor(props) {
281         super(props);
282     }
283     render() {
284         let props = this.props;
285         return (<div/>)
286     }
287 }
288
289 /**
290  * AddItemFn:
291  */
292 class InputCollection extends React.Component {
293     constructor(props) {
294         super(props);
295         this.collection = props.collection;
296     }
297     buildTextInput(onChange, v, i) {
298         return (
299             <Input
300                 readonly={this.props.readonly}
301                 style={{flex: '1 1'}}
302                 key={i}
303                 value={v}
304                 onChange= {onChange.bind(null, i)}
305             />
306         )
307     }
308     buildSelectOption(initial, options, onChange, v, i) {
309         return (
310             <SelectOption
311                 readonly={this.props.readonly}
312                 key={`${i}-${v.replace(' ', '_')}`}
313                 intial={initial}
314                 defaultValue={v}
315                 options={options}
316                 onChange={onChange.bind(null, i)}
317             />
318         );
319     }
320     showInput() {
321
322     }
323     render() {
324         const props = this.props;
325         let inputType;
326         let className = "InputCollection";
327         if (props.className) {
328             className = `${className} ${props.className}`;
329         }
330         if (props.type == 'select') {
331             inputType = this.buildSelectOption.bind(this, props.initial, props.options, props.onChange);
332         } else {
333             inputType = this.buildTextInput.bind(this, props.onChange)
334         }
335         let html = (
336             <div className="InputCollection-wrapper">
337                 {props.collection.map((v,i) => {
338                     return (
339                         <div key={i} className={className} >
340                             {inputType(v, i)}
341                             {
342                                 props.readonly ? null : <span onClick={props.RemoveItemFn.bind(null, i)} className="removeInput"><img src={imgRemove} />Remove</span>}
343                         </div>
344                     )
345                 })}
346                 { props.readonly ? null : <span onClick={props.AddItemFn} className="addInput"><img src={imgAdd} />Add</span>}
347             </div>
348         );
349         return html;
350     }
351 }
352
353 InputCollection.defaultProps = {
354     input: Input,
355     collection: [],
356     onChange: function(i, e) {
357         console.log(`
358                         Updating with: ${e.target.value}
359                         At index of: ${i}
360                     `)
361     },
362     AddItemFn: function(e) {
363         console.log(`Adding a new item to collection`)
364     },
365     RemoveItemFn: function(i, e) {
366         console.log(`Removing item from collection at index of: ${i}`)
367     }
368 }
369
370 class FormSection extends React.Component {
371     render() {
372         let className = 'FormSection ' + this.props.className;
373         let html = (
374             <div
375                 style={this.props.style}
376                 className={className}
377             >
378                 <div className="FormSection-title">
379                     {this.props.title}
380                 </div>
381                 <div className="FormSection-body">
382                     {this.props.children}
383                 </div>
384             </div>
385         );
386         return html;
387     }
388 }
389
390 FormSection.defaultProps = {
391     className: ''
392 }