f97d6ffb33ca411b4e04bfb71180b930a39ab356
[ccsdk/features.git] / sdnr / wt / odlux / framework / src / views / about.tsx
1 /**
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt odlux
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  */
18 import * as React from 'react';
19 import * as marked from 'marked';
20 import * as hljs from 'highlight.js';
21 import { requestRestExt } from '../services/restService';
22 import { Button, Typography } from '@material-ui/core';
23 const defaultRenderer = new marked.Renderer();
24 defaultRenderer.link = (href, title, text) => (
25   `<a target="_blank" rel="noopener noreferrer" href="${href}" title="${title}">${text}</a>`
26 );
27 interface AboutState {
28   content: string | null;
29   isCopiedSuccessfully: boolean;
30   isContentLoadedSucessfully: boolean;
31 }
32
33 class AboutComponent extends React.Component<any, AboutState> {
34   textarea: React.RefObject<HTMLTextAreaElement>;
35
36
37   constructor(props: any) {
38     super(props);
39     this.state = { content: null, isCopiedSuccessfully:false, isContentLoadedSucessfully: false }
40     this.textarea = React.createRef();
41     this.loadAboutContent();
42   }
43   private getMarkOdluxVersionMarkdownTable(data:{version:string,build:string}|null|undefined):string{
44     if(!data) {
45       return "";
46     }
47     return `| | |\n| --- | --- |\n| Version | ${data.version} |\n| Build timestamp | ${data.build}|`
48   }
49   private loadAboutContent(): void {
50     const baseUri = window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/")+1);
51     const p1 = requestRestExt<string>('/about');
52     const p2 = requestRestExt<{version:string,build:string}>(`${baseUri}version.json`);
53     Promise.all([p1,p2]).then((responses) => {
54       const response = responses[0];
55       const response2 = responses[1];    
56       const content = response.status == 200 ? response.data : `${response.status} ${response.message}` || "Server error";
57       const content2 = `\n## ODLUX Version Info\n`+(response2.status == 200 ? this.getMarkOdluxVersionMarkdownTable(response2.data) : `${response2.status} ${response2.message}` || "ODLUX Server error");
58       const loadedSucessfully = response.status == 200 ? true : false;
59       this.setState({ content: (content + content2) || null, isContentLoadedSucessfully: loadedSucessfully });
60     }).catch((error) => {
61       this.setState({ content: error })
62     })
63   }
64
65   copyToClipboard = (e: React.MouseEvent<HTMLButtonElement>) =>{
66     e.preventDefault();
67
68     if(this.textarea.current!==null){
69       this.textarea.current.select();
70       document.execCommand('copy');
71       if(e.currentTarget != null){ // refocus on button, otherwhise the textarea would be focused
72         e.currentTarget.focus();
73       }
74       this.setState({isCopiedSuccessfully: true});
75       window.setTimeout(()=>{this.setState({isCopiedSuccessfully: false});},2000);
76     }
77   }
78
79   render() {
80
81     const markedOptions: marked.MarkedOptions = {
82       gfm: true,
83       breaks: false,
84       pedantic: false,
85       sanitize: true,
86       smartLists: true,
87       smartypants: false,
88       langPrefix: 'hljs ',
89       ...({}),
90       highlight: (code, lang) => {
91         if (!!(lang && hljs.getLanguage(lang))) {
92           return hljs.highlight(lang, code).value;
93         }
94         return code;
95       }
96     };
97
98
99     const className = "about-table"
100     const style: React.CSSProperties = {};
101     const containerStyle = { overflow: "auto", paddingRight: "20px" }
102
103     const html = (marked(this.state.content || 'loading', { renderer: markedOptions && markedOptions.renderer || defaultRenderer }));
104
105     return (
106       <div style={containerStyle}>
107         { this.state.isContentLoadedSucessfully &&
108         <div style={{float: "right", marginRight: "10px"}}>
109         <Button variant="contained" onClick={e => this.copyToClipboard(e)}>
110            Copy to clipboard
111         </Button>
112           {
113             this.state.isCopiedSuccessfully && 
114             <Typography variant="body1" style={{color: "green"}} align="center">
115              copied successfully
116             </Typography>
117           }
118         </div>
119       }
120        
121         <div
122           dangerouslySetInnerHTML={{ __html: html }}
123           className={className}
124           style={style}
125         />
126          <form>
127           <textarea
128            style={{opacity: ".01"}}
129             ref={this.textarea}
130             value={this.state.content || ''}
131           />
132         </form>
133       </div>
134     );
135   }
136 };
137
138 export const About = AboutComponent;
139 export default About;