Skip to content

Instantly share code, notes, and snippets.

@andreisamoila74
Last active October 21, 2020 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreisamoila74/bca55271c3992c079eed018e5c95a1be to your computer and use it in GitHub Desktop.
Save andreisamoila74/bca55271c3992c079eed018e5c95a1be to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { Layout } from 'antd';
import { PlusSquareTwoTone } from '@ant-design/icons';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
import './View.css';
import AddComment from '../Comment/Add.js';
import PermissionsError from '../Errors/Permission.js';
import ViewComments from '../Comment/View.js';
function ViewCode() {
let { id } = useParams();
const [codeLanguage, setCodeLanguage] = useState('cpp');
const [codeRows, setCodeRows] = useState([]);
const [lineComments, setLineComments] = useState([]);
const [error, setError] = useState("");
function toggleLineCommentStatus(lineIndex) {
var auxState = { ...lineComments };
auxState[lineIndex] = auxState[lineIndex] ? 0 : 1;
setLineComments(auxState);
}
const rowStyle = {
padding: '0',
backgroundColor: 'white',
'whiteSpace': 'pre',
width: '100%'
};
const divStyle = {
margin: '0px 25px'
};
useEffect(() => {
fetch('/api/code/' + id + '/view')
.then(response => response.json())
.then(data => {
if (data.success === 1) {
setCodeLanguage(translateLanguage(data.code.language));
let rows = [];
data.code.source_code.split("\n").forEach((line, index) => {
rows.push(
<>
<div>
<tr key={index} className="line">
<td className="line-number">{index + 1}</td>
<td id={"plus" + index} className="plus-square-line">
<PlusSquareTwoTone className="plus-square"
onClick={() => toggleLineCommentStatus(index + 1)} />
</td>
<td id={"codeblock" + index}
className={'language-' + codeLanguage} style={rowStyle}>
{line}
</td>
</tr>
<div style={divStyle}>
{lineComments[index + 1]
?
<AddComment
id={id}
lineNumber={index + 1}
onCancelLineCommentShow={toggleLineCommentStatus}
/>
:
null
}
</div>
</div>
</>
);
});
setCodeRows(rows);
for (let i = 0; i < codeRows.length; ++i) {
hljs.highlightBlock(document.getElementById("codeblock" + i));
}
} else {
setError(data.error);
}
});
}, [codeRows.length, lineComments]);
return (
<>
{error
? <PermissionsError error={error} />
: <div>
<Layout className="container">
<table cellSpacing="0" cellPadding="0" style={rowStyle}>
<tbody>
{codeRows}
</tbody>
</table>
</Layout>
<ViewComments codeId={id} />
</div>
}
</>
);
export default ViewCode;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment