notatio/static/build/editor.js

393 lines
12 KiB
JavaScript

document.addEventListener('DOMContentLoaded', function () {
formatAllTables();
document.body.addEventListener("click", focusOnEditor);
});
function formatAllTables() {
var tables = document.getElementsByTagName('table');
for (var i = 0; i < tables.length; i++)
formatTable(tables[i]);
}
function formatText(tag, data) {
if (tag === 'heading') {
var headingTag = document.createElement(data);
var selection = window.getSelection();
var range = selection.getRangeAt(0);
headingTag.appendChild(range.extractContents());
range.insertNode(headingTag);
} else {
document.execCommand(tag, false, data);
}
}
function formatTable(table) {
// Add Bootstrap classes to the table
table.classList.add('table', 'table-striped', 'table-hover');
// Add Bootstrap classes to the table header cells
var headerCells = table.getElementsByTagName('th');
for (var i = 0; i < headerCells.length; i++) {
headerCells[i].classList.add('');
}
// Add Bootstrap classes to the table rows
var rows = table.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
rows[i].classList.add('');
// Add event listener to the last cell of each row
var cells = rows[i].getElementsByTagName('td');
var lastCell = cells[cells.length - 1];
lastCell.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
// Check if it's the last cell in the last row
var lastRow = rows[rows.length - 1];
if (this.parentNode === lastRow && this === lastRow.lastElementChild) {
event.preventDefault();
var newParagraph = document.createElement('p');
newParagraph.textContent = '\u00A0'; // Insert a non-breaking space to maintain table structure
table.parentNode.insertBefore(newParagraph, table.nextSibling);
document.getElementById('editor').focus();
}
}
});
}
// Add Bootstrap classes to the table data cells
var cells = table.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cells[i].classList.add('align-middle');
}
}
function saveForm() {
console.log("Saving file");
var editedContent = document.getElementById("editor").innerHTML;
var editedFilename = document.getElementById("filename").innerText;
// Set the editor content as the value of the editor-form-content textarea
document.getElementById("editor-form-content").value = editedContent;
document.getElementById("filename-form-content").value = editedFilename;
// Submit the form
document.getElementById("save-form").submit();
}
function confirmOverwrite() {
if (confirm("Are you sure you want to overwrite the file contents?")) {
document.getElementById("template-modal").style.display = "block";
// Close the modal when the close button or outside of the modal is clicked
window.addEventListener("click", function (e) {
if (e.target == document.getElementById("template-modal")) {
document.getElementById("template-modal").style.display = "none";
}
});
}
}
function confirmDeletion() {
if (confirm("Are you sure you want to delete {{.Filename}}?")) {
const filename = "{{.Filename}}";
deleteFile(filename);
}
}
// Function to focus on the editor when body is clicked
function focusOnEditor() {
// Check if the clicked element is inside the body div
if (event.target === document.body) { // Set the cursor position in the editor
setCursorPosition(document.getElementById("editor"));
}
}
// Add event listener to the body element
function redirectToTemplate(templateURL) {
window.location.href = templateURL;
}
function editFileName() {
var fileNameElement = document.getElementById("filename");
var fileName = fileNameElement.innerText.trim();
var extension = fileName.substring(fileName.lastIndexOf("."));
// Remove the file extension
fileName = fileName.replace(extension, "");
// Allow editing the filename
fileNameElement.contentEditable = "true";
fileNameElement.innerText = fileName;
fileNameElement.focus();
// Disable the enter key to prevent adding new lines
fileNameElement.addEventListener("keydown", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
fileNameElement.blur();
}
});
// Update the filename when the user finishes editing
fileNameElement.onblur = function () {
fileName = fileNameElement.innerText.trim();
// Add the file extension back
fileName += extension;
fileNameElement.innerText = fileName;
fileNameElement.contentEditable = "false";
fileNameElement.removeEventListener("keydown");
};
}
// Show the table size modal
function addTable() {
document.getElementById("tableModal").style.display = "block";
return
}
function createTable() {
var tableRowsInput = document.getElementById('tableRows');
var tableColumnsInput = document.getElementById('tableColumns');
var tableRows = parseInt(tableRowsInput.value);
var tableColumns = parseInt(tableColumnsInput.value);
if (!isNaN(tableRows) && !isNaN(tableColumns)) {
// Create a new table-responsive div
var tableResponsiveDiv = document.createElement('div');
tableResponsiveDiv.classList.add('table-responsive');
// Create a new table element
var table = document.createElement('table');
table.classList.add('table', 'table-striped', 'table-bordered');
// Create the table header
var thead = document.createElement('thead');
var headerRow = document.createElement('tr');
for (var j = 0; j < tableColumns; j++) {
var headerCell = document.createElement('th');
var headerText = document.createTextNode('Header ' + (j + 1));
headerCell.appendChild(headerText);
headerRow.appendChild(headerCell);
}
thead.appendChild(headerRow);
// Create the table body
var tbody = document.createElement('tbody');
for (var i = 0; i < tableRows; i++) {
var row = document.createElement('tr');
for (var j = 0; j < tableColumns; j++) {
var cell = document.createElement('td');
var cellText = document.createTextNode('Cell ' + (i + 1) + '-' + (j + 1));
cell.appendChild(cellText);
row.appendChild(cell);
}
tbody.appendChild(row);
}
// Append the thead and tbody to the table
table.appendChild(thead);
table.appendChild(tbody);
// Append the table to the table-responsive div
tableResponsiveDiv.appendChild(table);
// Insert the table-responsive div into the editor
var editor = document.getElementById('editor');
editor.appendChild(tableResponsiveDiv);
// Create a new <div> element
var paragraphDiv = document.createElement('div');
// Create a new <p> element
var paragraph = document.createElement('p');
// Set the text content of the paragraph
var paragraphText = document.createTextNode('');
paragraph.appendChild(paragraphText);
// Append the paragraph to the paragraph div
paragraphDiv.appendChild(paragraph);
// Insert the paragraph div after the table-responsive div
editor.appendChild(paragraphDiv);
// Reset the modal inputs
tableRowsInput.value = '3';
tableColumnsInput.value = '3';
// Close the modal
document.getElementById('tableModal').style.display = 'none';
}
}
function addVideo() {
var url = prompt("Enter the video URL:");
if (url !== null) {
var videoElement = document.createElement('video');
videoElement.controls = true;
videoElement.src = url;
document.getElementById('editor').appendChild(videoElement);
var paragraphElement = document.createElement('p');
paragraphElement.textContent = 'Type your text here';
document.getElementById('editor').appendChild(paragraphElement);
}
}
function deleteFile(filename) {
// Send a POST request to the server to delete the specified file
fetch("/delete", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ files: [filename] }),
})
.then(response => {
if (response.ok) {
window.location.replace("/home");
} else {
// Handle the error, e.g., display an error message
console.error("Error deleting file");
}
})
.catch(error => {
console.error("Error deleting file:", error);
});
}
function insertLink() {
var url = prompt('Enter the URL:');
// Check if the URL is null or empty
if (url === null || url === '') {
console.log('URL is empty. Aborting link creation.');
return;
}
var label = '';
// Get the user's selection
var selection = window.getSelection();
// Check if the user has made a selection
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
// Get the selected text
var selectedText = range.toString().trim();
// Prompt for the label only if there is no selection
if (selectedText.length === 0) {
label = prompt('Please enter the Link Text:');
} else {
label = selectedText;
}
}
// Check if the URL or label is empty
if (url === '' || label === '') {
console.log('URL or label is empty. Aborting link creation.');
return;
}
// Create the link HTML
var val = '<a href="' + url + '" target="_blank">' + label + '</a>';
// Insert the link HTML at the current selection or caret position
document.execCommand('insertHTML', false, val);
}
function undo() {
document.execCommand('undo', false, null);
}
function redo() {
document.execCommand('redo', false, null);
}
function selectAll() {
document.execCommand('selectAll', false, null);
}
function insertImage() {
var url = prompt('Enter the image URL:');
if (url !== null) {
document.execCommand('insertImage', false, url);
}
}
function setCursorPosition(element) {
var range = document.createRange();
range.selectNodeContents(element);
range.collapse(false);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
document.addEventListener('keydown', function (event) {
if ((event.ctrlKey || event.metaKey)) {
switch (event.key.toLowerCase()) {
case 'b':
event.preventDefault();
formatText('bold');
break;
case 'i':
event.preventDefault();
formatText('italic');
break;
case 'u':
event.preventDefault();
formatText('underline');
break;
case 'l':
event.preventDefault();
insertLink();
break;
case 'z':
event.preventDefault();
undo();
break;
case 'y':
event.preventDefault();
redo();
break;
case 'd':
event.preventDefault();
confirmDeletion();
break;
case 'p':
event.preventDefault();
insertImage();
break;
case 't':
event.preventDefault();
confirmOverwrite();
break;
case 's':
event.preventDefault();
saveForm();
break;
case 'f':
event.preventDefault();
formatText('removeFormat');
break;
case 'T':
event.preventDefault();
addTable();
break;
case 'm':
event.preventDefault();
addVideo();
break;
}
}
});