Explore const socket = io(); document.getElementById('add-note').addEventListener('click', () =>… Save Share Download ▾ Reportconst socket = io();
document.getElementById('add-note').addEventListener('click', () => {
const x = Math.floor(Math.random() * window.innerWidth);
const y = Math.floor(Math.random() * window.innerHeight);
const width = 200; // Ширина по умолчанию
const height = 40; // Высота по умолчанию
socket.emit('create_note', { text: 'New Comment', x, y, width, height });
});
document.getElementById('add-image').addEventListener('click', () => {
const formHtml = <div id="image-form" style="position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); background:white; padding:20px; border-radius:8px; box-shadow:0 0 10px rgba(0,0,0,0.1); z-index: 1000;"> <label for="image-url" style="display:block; margin-bottom:8px;">Image URL:</label> <input type="text" id="image-url" placeholder="Enter image URL" style="width: calc(100% - 22px); padding:10px; margin-bottom:12px; border:1px solid #ccc; border-radius:4px;"><br> <label for="image-file" style="display:block; margin-bottom:8px;">Or Upload File:</label> <input type="file" id="image-file" accept="image/*" style="margin-bottom:12px;"><br> <button id="add-image-submit" style="padding:10px 20px; background-color:#007bff; color:white; border:none; border-radius:4px; cursor:pointer; margin-right:8px;">Add Image</button> <button id="cancel-image" style="padding:10px 20px; background-color:#ccc; color:white; border:none; border-radius:4px; cursor:pointer;">Cancel</button> </div> ;
document.body.insertAdjacentHTML('beforeend', formHtml);
code Copy code
document.getElementById('add-image-submit').addEventListener('click', async () => {
const url = document.getElementById('image-url').value;
const fileInput = document.getElementById('image-file');
let imageUrl;
if (url) {
imageUrl = url;
} else if (fileInput.files.length > 0) {
const file = fileInput.files[0];
imageUrl = await uploadFile(file);
}
if (imageUrl) {
const x = Math.floor(Math.random() * window.innerWidth);
const y = Math.floor(Math.random() * window.innerHeight);
const img = new Image();
img.src = imageUrl;
img.onload = () => {
const maxWidth = 720;
const maxHeight = 720;
let width = img.naturalWidth;
let height = img.naturalHeight;
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height);
width *= ratio;
height *= ratio;
}
socket.emit('create_image', { url: imageUrl, x, y, width, height });
closeModal();
};
}
});
document.getElementById('cancel-image').addEventListener('click', closeModal);
function closeModal() {
const form = document.getElementById('image-form');
if (form) {
form.remove();
}
}
Show full message · 671 lines Assistant2024-10-30 05:43 UTC Copy response
Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Oct 30, 2024
Added to archive Nov 16, 2026
ID 01m7h422hw58k4h6s41950qazmSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: f5b5a058d03a5e63603607c3215bb82d
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
async function uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
code Copy code
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const data = await response.json();
return data.url;
socket.on('new_note', (data) => {
const note = createNoteElement(data);
document.getElementById('board').appendChild(note);
});
socket.on('updated_note', (data) => {
const note = document.querySelector(.note[data-id="${data.id}"]);
if (note) {
note.style.left = ${data.x}px;
note.style.top = ${data.y}px;
note.style.width = ${data.width}px;
note.style.height = ${data.height}px;
note.querySelector('textarea').value = data.text;
}
});
socket.on('new_image', (data) => {
const image = createImageElement(data);
document.getElementById('board').appendChild(image);
});
socket.on('updated_image', (data) => {
const image = document.querySelector(.image[data-id="${data.id}"]);
if (image) {
image.style.left = ${data.x}px;
image.style.top = ${data.y}px;
image.style.width = ${data.width}px;
image.style.height = ${data.height}px;
image.querySelector('img').src = data.url;
}
});
socket.on('element_deleted', (data) => {
const element = document.querySelector(.${data.type}[data-id="${data.id}"]);
if (element) {
element.remove();
}
});
function createNoteElement(data) {
const note = document.createElement('div');
note.className = 'note';
note.dataset.id = data.id;
note.style.left = ${data.x}px;
note.style.top = ${data.y}px;
note.style.width = ${data.width}px;
note.style.height = ${data.height}px;
code Copy code
const textarea = document.createElement('textarea');
textarea.value = data.text;
textarea.addEventListener('input', () => {
const x = note.offsetLeft;
const y = note.offsetTop;
const width = note.offsetWidth;
const height = note.offsetHeight;
socket.emit('update_note', { id: data.id, text: textarea.value, x, y, width, height });
});
textarea.addEventListener('mousedown', (e) => {
e.stopPropagation();
});
note.appendChild(textarea);
addNoteEventListeners(note, data.id);
return note;
function createImageElement(data) {
const image = document.createElement('div');
image.className = 'image';
image.dataset.id = data.id;
image.style.left = ${data.x}px;
image.style.top = ${data.y}px;
image.style.width = ${data.width}px;
image.style.height = ${data.height}px;
code Copy code
const img = document.createElement('img');
img.src = data.url;
img.style.width = '100%';
img.style.height = '100%';
img.style.objectFit = 'contain'; // Это свойство сохраняет соотношение сторон изображения
image.appendChild(img);
addImageEventListeners(image, data.id);
return image;
function addNoteEventListeners(note, id) {
note.addEventListener('mousedown', (e) => {
if (e.button !== 0) return; // Проверка на левую кнопку мыши
e.preventDefault();
e.stopPropagation();
const startX = e.clientX;
const startY = e.clientY;
const startLeft = parseFloat(note.style.left) || 0;
const startTop = parseFloat(note.style.top) || 0;
code Copy code
function moveNote(e) {
const deltaX = (e.clientX - startX) / scale;
const deltaY = (e.clientY - startY) / scale;
note.style.left = `${startLeft + deltaX}px`;
note.style.top = `${startTop + deltaY}px`;
const x = parseFloat(note.style.left) || 0;
const y = parseFloat(note.style.top) || 0;
const width = note.offsetWidth;
const height = note.offsetHeight;
socket.emit('update_note', { id, text: note.querySelector('textarea').value, x, y, width, height });
}
document.addEventListener('mousemove', moveNote);
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', moveNote);
}, { once: true });
});
note.addEventListener('touchstart', (e) => {
e.preventDefault();
e.stopPropagation();
const startX = e.touches[0].clientX;
const startY = e.touches[0].clientY;
const startLeft = parseFloat(note.style.left) || 0;
const startTop = parseFloat(note.style.top) || 0;
function moveNote(e) {
const deltaX = (e.touches[0].clientX - startX) / scale;
const deltaY = (e.touches[0].clientY - startY) / scale;
note.style.left = `${startLeft + deltaX}px`;
note.style.top = `${startTop + deltaY}px`;
const x = parseFloat(note.style.left) || 0;
const y = parseFloat(note.style.top) || 0;
const width = note.offsetWidth;
const height = note.offsetHeight;
socket.emit('update_note', { id, text: note.querySelector('textarea').value, x, y, width, height });
}
document.addEventListener('touchmove', moveNote);
document.addEventListener('touchend', () => {
document.removeEventListener('touchmove', moveNote);
}, { once: true });
});
note.addEventListener('dblclick', (e) => {
e.preventDefault();
e.stopPropagation();
showContextMenu(note, id, e.clientX, e.clientY);
});
note.addEventListener('touchstart', (e) => {
if (e.touches.length === 2) {
e.preventDefault();
e.stopPropagation();
showContextMenu(note, id, e.touches[0].clientX, e.touches[0].clientY);
}
});
addResizeListeners(note, id, 'note');
function addImageEventListeners(image, id) {
image.addEventListener('mousedown', (e) => {
if (e.button !== 0) return; // Проверка на левую кнопку мыши
e.preventDefault();
e.stopPropagation();
const startX = e.clientX;
const startY = e.clientY;
const startLeft = parseFloat(image.style.left) || 0;
const startTop = parseFloat(image.style.top) || 0;
code Copy code
function moveImage(e) {
const deltaX = (e.clientX - startX) / scale;
const deltaY = (e.clientY - startY) / scale;
image.style.left = `${startLeft + deltaX}px`;
image.style.top = `${startTop + deltaY}px`;
const x = parseFloat(image.style.left) || 0;
const y = parseFloat(image.style.top) || 0;
const width = image.offsetWidth;
const height = image.offsetHeight;
socket.emit('update_image', { id, url: image.querySelector('img').src, x, y, width, height });
}
document.addEventListener('mousemove', moveImage);
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', moveImage);
}, { once: true });
});
image.addEventListener('touchstart', (e) => {
e.preventDefault();
e.stopPropagation();
const startX = e.touches[0].clientX;
const startY = e.touches[0].clientY;
const startLeft = parseFloat(image.style.left) || 0;
const startTop = parseFloat(image.style.top) || 0;
function moveImage(e) {
const deltaX = (e.touches[0].clientX - startX) / scale;
const deltaY = (e.touches[0].clientY - startY) / scale;
image.style.left = `${startLeft + deltaX}px`;
image.style.top = `${startTop + deltaY}px`;
const x = parseFloat(image.style.left) || 0;
const y = parseFloat(image.style.top) || 0;
const width = image.offsetWidth;
const height = image.offsetHeight;
socket.emit('update_image', { id, url: image.querySelector('img').src, x, y, width, height });
}
document.addEventListener('touchmove', moveImage);
document.addEventListener('touchend', () => {
document.removeEventListener('touchmove', moveImage);
}, { once: true });
});
image.addEventListener('dblclick', (e) => {
e.preventDefault();
e.stopPropagation();
showContextMenu(image, id, e.clientX, e.clientY);
});
image.addEventListener('touchstart', (e) => {
if (e.touches.length === 2) {
e.preventDefault();
e.stopPropagation();
showContextMenu(image, id, e.touches[0].clientX, e.touches[0].clientY);
}
});
addResizeListeners(image, id, 'image');
function showContextMenu(element, id, x, y) {
const contextMenu = document.createElement('div');
contextMenu.className = 'context-menu';
contextMenu.style.position = 'absolute';
contextMenu.style.left = ${x}px;
contextMenu.style.top = ${y}px;
contextMenu.style.backgroundColor = 'white';
contextMenu.style.borderRadius = '4px';
contextMenu.style.border = '1px solid #ccc';
contextMenu.style.boxShadow = '0 0 10px rgba(0,0,0,0.1)';
contextMenu.style.zIndex = '1000';
code Copy code
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.style.padding = '5px 10px';
deleteButton.style.border = 'none';
deleteButton.style.backgroundColor = '#ff4d4d';
deleteButton.style.color = 'white';
deleteButton.style.borderRadius = '4px';
deleteButton.style.cursor = 'pointer';
deleteButton.style.width = '100%';
deleteButton.style.textAlign = 'left';
deleteButton.addEventListener('click', () => {
element.remove();
socket.emit('delete_element', { id: id, type: element.classList.contains('note') ? 'note' : 'image' });
contextMenu.remove();
});
contextMenu.appendChild(deleteButton);
document.body.appendChild(contextMenu);
// Закрытие контекстного меню при клике вне его
document.addEventListener('click', (e) => {
if (!contextMenu.contains(e.target)) {
contextMenu.remove();
}
}, { once: true });
function addResizeListeners(element, id, type) {
const resizeHandle = document.createElement('div');
resizeHandle.className = 'resize-handle';
element.appendChild(resizeHandle);
code Copy code
resizeHandle.addEventListener('mousedown', (e) => {
if (e.button !== 0) return; // Проверка на левую кнопку мыши
e.stopPropagation(); // Предотвращаем срабатывание обработчика перемещения
e.preventDefault();
let startX = e.clientX;
let startY = e.clientY;
let startWidth = element.offsetWidth;
let startHeight = element.offsetHeight;
function resizeElement(e) {
const deltaX = e.clientX - startX;
const deltaY = e.clientY - startY;
if (type === 'note') {
element.style.width = `${startWidth + deltaX}px`;
element.style.height = `${startHeight + deltaY}px`;
} else if (type === 'image') {
const ratio = startWidth / startHeight;
const newWidth = startWidth + deltaX;
const newHeight = newWidth / ratio;
element.style.width = `${newWidth}px`;
element.style.height = `${newHeight}px`;
}
const x = element.offsetLeft;
const y = element.offsetTop;
const width = element.offsetWidth;
const height = element.offsetHeight;
if (type === 'note') {
socket.emit('update_note', { id, text: element.querySelector('textarea').value, x, y, width, height });
} else if (type === 'image') {
socket.emit('update_image', { id, url: element.querySelector('img').src, x, y, width, height });
}
}
document.addEventListener('mousemove', resizeElement);
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', resizeElement);
}, { once: true });
});
resizeHandle.addEventListener('touchstart', (e) => {
e.stopPropagation(); // Предотвращаем срабатывание обработчика перемещения
e.preventDefault();
let startX = e.touches[0].clientX;
let startY = e.touches[0].clientY;
let startWidth = element.offsetWidth;
let startHeight = element.offsetHeight;
function resizeElement(e) {
const deltaX = e.touches[0].clientX - startX;
const deltaY = e.touches[0].clientY - startY;
if (type === 'note') {
element.style.width = `${startWidth + deltaX}px`;
element.style.height = `${startHeight + deltaY}px`;
} else if (type === 'image') {
const ratio = startWidth / startHeight;
const newWidth = startWidth + deltaX;
const newHeight = newWidth / ratio;
element.style.width = `${newWidth}px`;
element.style.height = `${newHeight}px`;
}
const x = element.offsetLeft;
const y = element.offsetTop;
const width = element.offsetWidth;
const height = element.offsetHeight;
if (type === 'note') {
socket.emit('update_note', { id, text: element.querySelector('textarea').value, x, y, width, height });
} else if (type === 'image') {
socket.emit('update_image', { id, url: element.querySelector('img').src, x, y, width, height });
}
}
document.addEventListener('touchmove', resizeElement);
document.addEventListener('touchend', () => {
document.removeEventListener('touchmove', resizeElement);
}, { once: true });
});
function handleExistingNotes() {
document.querySelectorAll('.note').forEach(note => {
const id = note.dataset.id;
const text = note.querySelector('textarea').value;
const x = note.offsetLeft;
const y = note.offsetTop;
const width = note.offsetWidth;
const height = note.offsetHeight;
code Copy code
note.querySelector('textarea').addEventListener('input', () => {
const x = note.offsetLeft;
const y = note.offsetTop;
const width = note.offsetWidth;
const height = note.offsetHeight;
socket.emit('update_note', { id, text: note.querySelector('textarea').value, x, y, width, height });
});
note.querySelector('textarea').addEventListener('mousedown', (e) => {
e.stopPropagation();
});
note.addEventListener('dblclick', (e) => {
e.preventDefault();
e.stopPropagation();
showContextMenu(note, id, e.clientX, e.clientY);
});
addNoteEventListeners(note, id);
});
function handleExistingImages() {
document.querySelectorAll('.image').forEach(image => {
const id = image.dataset.id;
const url = image.querySelector('img').src;
const x = image.offsetLeft;
const y = image.offsetTop;
const width = image.offsetWidth;
const height = image.offsetHeight;
code Copy code
image.addEventListener('dblclick', (e) => {
e.preventDefault();
e.stopPropagation();
showContextMenu(image, id, e.clientX, e.clientY);
});
addImageEventListeners(image, id);
});
// Вызовем функции для обработки существующих заметок и изображений при загрузке страницы
handleExistingNotes();
handleExistingImages();
let scale = 0.5; // Начальный масштаб 50%
let translateX = 0;
let translateY = 0;
const board = document.getElementById('board');
const boardWrapper = document.getElementById('board-wrapper');
// Новые значения для минимального и максимального масштаба
const MIN_SCALE = 0.1; // Минимальный масштаб
const MAX_SCALE = 5; // Максимальный масштаб
const ZOOM_FACTOR = 0.1; // Скорость зума
// Применяем начальный масштаб
board.style.transform = translate(${translateX}px, ${translateY}px) scale(${scale});
boardWrapper.style.backgroundPosition = ${translateX}px ${translateY}px;
// Показываем изображения после установки масштаба
document.querySelectorAll('.image').forEach(img => {
img.classList.remove('hidden');
});
boardWrapper.addEventListener('wheel', (e) => {
e.preventDefault();
code Copy code
const previousScale = scale;
scale += e.deltaY < 0 ? ZOOM_FACTOR : -ZOOM_FACTOR;
scale = Math.min(Math.max(MIN_SCALE, scale), MAX_SCALE);
// Calculate cursor position relative to the board
const rect = board.getBoundingClientRect();
const offsetX = (e.clientX - rect.left) / previousScale;
const offsetY = (e.clientY - rect.top) / previousScale;
// Adjust translate to keep cursor point in the same position
translateX -= offsetX * (scale - previousScale);
translateY -= offsetY * (scale - previousScale);
board.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
boardWrapper.style.backgroundPosition = `${translateX}px ${translateY}px`;
boardWrapper.addEventListener('touchstart', (e) => {
if (e.touches.length === 2) {
e.preventDefault();
const touch1 = e.touches[0];
const touch2 = e.touches[1];
const startDistance = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
const startScale = scale;
code Copy code
function zoom(e) {
const touch1 = e.touches[0];
const touch2 = e.touches[1];
const currentDistance = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
const newScale = startScale * (currentDistance / startDistance);
scale = Math.min(Math.max(MIN_SCALE, newScale), MAX_SCALE);
// Calculate cursor position relative to the board
const rect = board.getBoundingClientRect();
const offsetX = (touch1.clientX + touch2.clientX) / 2 - rect.left;
const offsetY = (touch1.clientY + touch2.clientY) / 2 - rect.top;
// Adjust translate to keep cursor point in the same position
translateX -= offsetX * (scale - startScale);
translateY -= offsetY * (scale - startScale);
board.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
boardWrapper.style.backgroundPosition = `${translateX}px ${translateY}px`;
}
document.addEventListener('touchmove', zoom);
document.addEventListener('touchend', () => {
document.removeEventListener('touchmove', zoom);
}, { once: true });
}
let isPanning = false;
let startX, startY;
boardWrapper.addEventListener('mousedown', (e) => {
if (e.button === 2) {
isPanning = true;
startX = e.clientX - translateX;
startY = e.clientY - translateY;
boardWrapper.style.cursor = 'grabbing';
}
});
boardWrapper.addEventListener('mouseup', (e) => {
if (e.button === 2) {
isPanning = false;
boardWrapper.style.cursor = 'grab';
}
});
boardWrapper.addEventListener('mousemove', (e) => {
if (!isPanning) return;
e.preventDefault();
translateX = e.clientX - startX;
translateY = e.clientY - startY;
board.style.transform = translate(${translateX}px, ${translateY}px) scale(${scale});
boardWrapper.style.backgroundPosition = ${translateX}px ${translateY}px;
});
// Добавляем поддержку тач-событий для перемещения доски
boardWrapper.addEventListener('touchstart', (e) => {
isPanning = true;
startX = e.touches[0].clientX - translateX;
startY = e.touches[0].clientY - translateY;
boardWrapper.style.cursor = 'grabbing';
});
boardWrapper.addEventListener('touchend', (e) => {
isPanning = false;
boardWrapper.style.cursor = 'grab';
});
boardWrapper.addEventListener('touchmove', (e) => {
if (!isPanning) return;
e.preventDefault();
translateX = e.touches[0].clientX - startX;
translateY = e.touches[0].clientY - startY;
board.style.transform = translate(${translateX}px, ${translateY}px) scale(${scale});
boardWrapper.style.backgroundPosition = ${translateX}px ${translateY}px;
});
// Предотвращаем контекстное меню при нажатии правой кнопки мыши
boardWrapper.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
Помоги мне разделить код по файлам, что бы было удобнее читать код. Обязательно проверь что бы было перенесено все и никакой функционал не пропущен. Например всю логику связанную с заметками мы выносим в один файл, все что связано с управлением доской в другой файл и так далее.
Organizing your code into multiple files can significantly improve readability, maintainability, and scalability. Below is a suggested structure to separate your JavaScript and HTML code based on functionality. This approach ensures that each component handles a specific part of your application, making it easier to manage and extend in the future.
Proposed Directory Structure
code Copy code
project/
├── static/
│ ├── css/
│ │ └── style.css
│ └── js/
│ ├── main.js
│ ├── board.js
│ ├── notes.js
│ ├── images.js
│ ├── contextMenu.js
│ └── utils.js
├── templates/
│ └── index.html
└── server.py (or your server entry point)
1. HTML (templates/index.html)
Start by updating your HTML to reference the newly separated JavaScript files. Ensure that the scripts are loaded in an order that respects their dependencies.
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Miro Clone</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<style>
.hidden {
visibility: hidden;
}
/* Add styles for context menu and resize handle */
.context-menu {
position: absolute;
background-color: white;
border-radius: 4px;
border: 1px solid #ccc;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
z-index: 1000;
}
.context-menu button {
padding: 5px 10px;
border: none;
background-color: #ff4d4d;
color: white;
border-radius: 4px;
cursor: pointer;
width: 100%;
text-align: left;
}
.resize-handle {
position: absolute;
width: 10px;
height: 10px;
background-color: #007bff;
right: 0;
bottom: 0;
cursor: se-resize;
}
</style>
</head>
<body>
<div id="board-wrapper">
<div id="board">
{% for note in notes %}
<div class="note" data-id="{{ note.id }}" style="left: {{ note.x }}px; top: {{ note.y }}px; width: {{ note.width }}px; height: {{ note.height }}px;">
<textarea>{{ note.text }}</textarea>
</div>
{% endfor %}
{% for image in images %}
<div class="image hidden" data-id="{{ image.id }}" style="left: {{ image.x }}px; top: {{ image.y }}px; width: {{ image.width }}px; height: {{ image.height }}px;">
<img src="{{ image.url }}" style="width: 100%; height: 100%; object-fit: contain;">
</div>
{% endfor %}
</div>
</div>
<button id="add-note">Add Comment</button>
<button id="add-image">Add Image</button>
<!-- Load Socket.io -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<!-- Load JavaScript Files -->
<script src="{{ url_for('static', filename='js/utils.js') }}"></script>
<script src="{{ url_for('static', filename='js/contextMenu.js') }}"></script>
<script src="{{ url_for('static', filename='js/notes.js') }}"></script>
<script src="{{ url_for('static', filename='js/images.js') }}"></script>
<script src="{{ url_for('static', filename='js/board.js') }}"></script>
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
</body>
</html>
2. JavaScript Files
a. main.js
This file initializes the socket connection and sets up the event listeners for adding notes and images. It also handles the initialization of existing elements on the board.
javascript Copy code
// static/js/main.js
const socket = io();
// Initialize Board Controls
initializeBoardControls(socket);
// Initialize Notes and Images
initializeNotes(socket);
initializeImages(socket);
initializeContextMenu(socket);
initializeUtils();
// Event Listener for Adding a New Note
document.getElementById('add-note').addEventListener('click', () => {
const x = Math.floor(Math.random() * window.innerWidth);
const y = Math.floor(Math.random() * window.innerHeight);
const width = 200; // Default width
const height = 40; // Default height
socket.emit('create_note', { text: 'New Comment', x, y, width, height });
});
// Event Listener for Adding a New Image
document.getElementById('add-image').addEventListener('click', () => {
showImageForm(socket);
});
// Socket Event Handlers
socket.on('new_note', (data) => {
const note = createNoteElement(data);
document.getElementById('board').appendChild(note);
});
socket.on('updated_note', (data) => {
updateNoteElement(data);
});
socket.on('new_image', (data) => {
const image = createImageElement(data);
document.getElementById('board').appendChild(image);
});
socket.on('updated_image', (data) => {
updateImageElement(data);
});
socket.on('element_deleted', (data) => {
deleteElement(data);
});
// Handle Existing Elements on Page Load
document.addEventListener('DOMContentLoaded', () => {
handleExistingNotes(socket);
handleExistingImages(socket);
});
b. board.js
This file manages the board's panning and zooming functionalities.
c. notes.js
This file manages all functionalities related to notes, including creation, updating, dragging, resizing, and event listeners.
d. images.js
This file manages all functionalities related to images, including creation, updating, dragging, resizing, and event listeners.
e. contextMenu.js
This file manages the context menu functionality, allowing users to delete elements.
javascript Copy code
// static/js/contextMenu.js
function showContextMenu(element, id, x, y) {
const contextMenu = document.createElement('div');
contextMenu.className = 'context-menu';
contextMenu.style.left = `${x}px`;
contextMenu.style.top = `${y}px`;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', () => {
element.remove();
socket.emit('delete_element', { id: id, type: element.classList.contains('note') ? 'note' : 'image' });
contextMenu.remove();
});
contextMenu.appendChild(deleteButton);
document.body.appendChild(contextMenu);
// Close context menu when clicking outside
document.addEventListener('click', (e) => {
if (!contextMenu.contains(e.target)) {
contextMenu.remove();
}
}, { once: true });
}
Note: Ensure that the socket object is accessible within this file. Since main.js initializes the socket and other files are included after main.js, you can make socket a global variable by attaching it to the window object.
Update main.js:
javascript Copy code
// At the beginning of main.js
window.socket = io();
// Replace all instances of 'socket' with 'window.socket' in contextMenu.js and other files if necessary
Alternatively, if you are using ES6 modules, you can export and import the socket object accordingly. For simplicity, attaching it to the window object ensures global accessibility.
f. utils.js
This file contains utility functions, such as file uploads.
javascript Copy code
// static/js/utils.js
async function uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const data = await response.json();
return data.url;
}
function initializeUtils() {
// Any utility initialization if needed
}
g. contextMenu.js (Updated for Socket Accessibility)
To ensure that the socket object is accessible within contextMenu.js, update the showContextMenu function accordingly.
javascript Copy code
// static/js/contextMenu.js
function showContextMenu(element, id, x, y) {
const contextMenu = document.createElement('div');
contextMenu.className = 'context-menu';
contextMenu.style.left = `${x}px`;
contextMenu.style.top = `${y}px`;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', () => {
element.remove();
window.socket.emit('delete_element', { id: id, type: element.classList.contains('note') ? 'note' : 'image' });
contextMenu.remove();
});
contextMenu.appendChild(deleteButton);
document.body.appendChild(contextMenu);
// Close context menu when clicking outside
document.addEventListener('click', (e) => {
if (!contextMenu.contains(e.target)) {
contextMenu.remove();
}
}, { once: true });
}
3. Additional Adjustments
a. resize.js (Optional)
If you prefer to handle resizing in a separate file, you can create a resize.js to manage the resize functionality for both notes and images. However, in the current structure, resizing is handled within notes.js and images.js through the addResizeListeners function.
b. Ensuring All Functionalities Are Included
Review each separated file to verify that all functionalities are correctly transferred:
Adding Notes and Images: Handled in main.js through event listeners that emit socket events.
Creating Elements: createNoteElement in notes.js and createImageElement in images.js.
Updating Elements: Socket event handlers in main.js call updateNoteElement and updateImageElement.
Deleting Elements: Managed by contextMenu.js.
Dragging and Resizing: Integrated within notes.js and images.js via addNoteEventListeners and addImageEventListeners.
Board Controls (Pan and Zoom): Handled in board.js.
Utility Functions: Located in utils.js.
4. CSS (static/css/style.css)
Ensure that all necessary styles are included. You might want to move inline styles from the HTML into the CSS file for better separation. Here's an example of what to include:
css Copy code
/* static/css/style.css */
/* Board and Wrapper Styles */
#board-wrapper {
width: 100vw;
height: 100vh;
overflow: hidden;
position: relative;
background-color: #f0f0f0;
cursor: grab;
}
#board {
position: absolute;
top: 0;
left: 0;
transform-origin: top left;
}
/* Note Styles */
.note {
position: absolute;
background-color: #fff176;
border: 1px solid #fdd835;
border-radius: 4px;
padding: 5px;
box-sizing: border-box;
cursor: move;
}
.note textarea {
width: 100%;
height: 100%;
border: none;
resize: none;
background: transparent;
outline: none;
font-family: sans-serif;
}
/* Image Styles */
.image {
position: absolute;
cursor: move;
}
.image img {
display: block;
}
/* Context Menu and Resize Handle are styled inline in HTML */
button {
margin: 10px;
padding: 10px 20px;
border: none;
background-color: #007bff;
color: white;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
Note: Adjust the styles as per your design requirements. Moving inline styles to the CSS file will make the code cleaner and easier to manage.
5. Server-Side Adjustments
Ensure that your server is set up to serve the new static files correctly. For example, if you're using Flask, your directory structure should align with Flask's static file serving conventions.
python Copy code
# server.py (Example for Flask)
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit
import os
import uuid
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
# In-memory storage for notes and images
notes = []
images = []
@app.route('/')
def index():
return render_template('index.html', notes=notes, images=images)
@app.route('/upload', methods=['POST'])
def upload():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
# Save the file and return its URL
filename = str(uuid.uuid4()) + os.path.splitext(file.filename)[1]
filepath = os.path.join('static', 'uploads', filename)
file.save(filepath)
url = f'/static/uploads/{filename}'
return jsonify({'url': url})
@socketio.on('create_note')
def handle_create_note(data):
note = {
'id': str(uuid.uuid4()),
'text': data['text'],
'x': data['x'],
'y': data['y'],
'width': data['width'],
'height': data['height']
}
notes.append(note)
emit('new_note', note, broadcast=True)
@socketio.on('update_note')
def handle_update_note(data):
for note in notes:
if note['id'] == data['id']:
note.update(data)
break
emit('updated_note', data, broadcast=True)
@socketio.on('create_image')
def handle_create_image(data):
image = {
'id': str(uuid.uuid4()),
'url': data['url'],
'x': data['x'],
'y': data['y'],
'width': data['width'],
'height': data['height']
}
images.append(image)
emit('new_image', image, broadcast=True)
@socketio.on('update_image')
def handle_update_image(data):
for image in images:
if image['id'] == data['id']:
image.update(data)
break
emit('updated_image', data, broadcast=True)
@socketio.on('delete_element')
def handle_delete_element(data):
if data['type'] == 'note':
global notes
notes = [note for note in notes if note['id'] != data['id']]
elif data['type'] == 'image':
global images
images = [image for image in images if image['id'] != data['id']]
emit('element_deleted', data, broadcast=True)
if __name__ == '__main__':
socketio.run(app, debug=True)
Note: Ensure that the /upload route correctly handles file uploads and that the static/uploads directory exists and is writable.
6. Summary of Steps
Create Directory Structure: Organize your project with separate folders for static assets and templates.
Separate JavaScript Files:
main.js: Initialization and global event listeners.
board.js: Board manipulation (panning and zooming).
notes.js: Note creation, updating, dragging, and resizing.
images.js: Image creation, updating, dragging, and resizing.
contextMenu.js: Context menu for deleting elements.
utils.js: Utility functions like file uploads.
Update HTML References: Modify your HTML to include the separated JavaScript files in the correct order.
Move Inline Styles to CSS: Enhance readability by transferring inline styles to your CSS files.
Adjust Server-Side Code: Ensure that your server serves the new static files and handles routes appropriately.
Test Functionality: After restructuring, thoroughly test each feature to ensure that no functionality is lost during the separation process.
By following this structured approach, your codebase will become more organized, making it easier to maintain and scale your Miro Clone application.
Show full message · 968 lines Copy first response
Not yet included in a published release.
// static/js/board.js
let scale = 0.5; // Initial scale 50%
let translateX = 0;
let translateY = 0;
const board = document.getElementById('board');
const boardWrapper = document.getElementById('board-wrapper');
// Constants for Zoom
const MIN_SCALE = 0.1; // Minimum scale
const MAX_SCALE = 5; // Maximum scale
const ZOOM_FACTOR = 0.1; // Zoom speed
// Apply initial scale
board.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
boardWrapper.style.backgroundPosition = `${translateX}px ${translateY}px`;
// Show images after setting scale
document.querySelectorAll('.image').forEach(img => {
img.classList.remove('hidden');
});
// Zoom with Mouse Wheel
boardWrapper.addEventListener('wheel', (e) => {
e.preventDefault();
const previousScale = scale;
scale += e.deltaY < 0 ? ZOOM_FACTOR : -ZOOM_FACTOR;
scale = Math.min(Math.max(MIN_SCALE, scale), MAX_SCALE);
// Calculate cursor position relative to the board
const rect = board.getBoundingClientRect();
const offsetX = (e.clientX - rect.left) / previousScale;
const offsetY = (e.clientY - rect.top) / previousScale;
// Adjust translate to keep cursor point in the same position
translateX -= offsetX * (scale - previousScale);
translateY -= offsetY * (scale - previousScale);
board.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
boardWrapper.style.backgroundPosition = `${translateX}px ${translateY}px`;
});
// Zoom with Touch Gestures
boardWrapper.addEventListener('touchstart', (e) => {
if (e.touches.length === 2) {
e.preventDefault();
const touch1 = e.touches[0];
const touch2 = e.touches[1];
const startDistance = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
const startScale = scale;
function zoom(e) {
const touch1 = e.touches[0];
const touch2 = e.touches[1];
const currentDistance = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
const newScale = startScale * (currentDistance / startDistance);
scale = Math.min(Math.max(MIN_SCALE, newScale), MAX_SCALE);
// Calculate cursor position relative to the board
const rect = board.getBoundingClientRect();
const offsetX = ((touch1.clientX + touch2.clientX) / 2 - rect.left) / startScale;
const offsetY = ((touch1.clientY + touch2.clientY) / 2 - rect.top) / startScale;
// Adjust translate to keep cursor point in the same position
translateX -= offsetX * (scale - startScale);
translateY -= offsetY * (scale - startScale);
board.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
boardWrapper.style.backgroundPosition = `${translateX}px ${translateY}px`;
}
document.addEventListener('touchmove', zoom);
document.addEventListener('touchend', () => {
document.removeEventListener('touchmove', zoom);
}, { once: true });
}
}, { passive: false });
// Panning with Mouse Drag
let isPanning = false;
let startX, startY;
boardWrapper.addEventListener('mousedown', (e) => {
if (e.button === 2) { // Right mouse button
isPanning = true;
startX = e.clientX - translateX;
startY = e.clientY - translateY;
boardWrapper.style.cursor = 'grabbing';
}
});
boardWrapper.addEventListener('mouseup', (e) => {
if (e.button === 2) { // Right mouse button
isPanning = false;
boardWrapper.style.cursor = 'grab';
}
});
boardWrapper.addEventListener('mousemove', (e) => {
if (!isPanning) return;
e.preventDefault();
translateX = e.clientX - startX;
translateY = e.clientY - startY;
board.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
boardWrapper.style.backgroundPosition = `${translateX}px ${translateY}px`;
});
// Panning with Touch Drag
boardWrapper.addEventListener('touchstart', (e) => {
if (e.touches.length === 1) {
isPanning = true;
startX = e.touches[0].clientX - translateX;
startY = e.touches[0].clientY - translateY;
boardWrapper.style.cursor = 'grabbing';
}
});
boardWrapper.addEventListener('touchend', (e) => {
isPanning = false;
boardWrapper.style.cursor = 'grab';
});
boardWrapper.addEventListener('touchmove', (e) => {
if (!isPanning) return;
e.preventDefault();
translateX = e.touches[0].clientX - startX;
translateY = e.touches[0].clientY - startY;
board.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
boardWrapper.style.backgroundPosition = `${translateX}px ${translateY}px`;
});
// Prevent Default Context Menu
boardWrapper.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
// static/js/notes.js
function initializeNotes(socket) {
// Any initialization if needed
}
function createNoteElement(data) {
const note = document.createElement('div');
note.className = 'note';
note.dataset.id = data.id;
note.style.left = `${data.x}px`;
note.style.top = `${data.y}px`;
note.style.width = `${data.width}px`;
note.style.height = `${data.height}px`;
const textarea = document.createElement('textarea');
textarea.value = data.text;
textarea.addEventListener('input', () => {
const x = note.offsetLeft;
const y = note.offsetTop;
const width = note.offsetWidth;
const height = note.offsetHeight;
socket.emit('update_note', { id: data.id, text: textarea.value, x, y, width, height });
});
textarea.addEventListener('mousedown', (e) => {
e.stopPropagation();
});
note.appendChild(textarea);
addNoteEventListeners(note, data.id, socket);
return note;
}
function updateNoteElement(data) {
const note = document.querySelector(`.note[data-id="${data.id}"]`);
if (note) {
note.style.left = `${data.x}px`;
note.style.top = `${data.y}px`;
note.style.width = `${data.width}px`;
note.style.height = `${data.height}px`;
note.querySelector('textarea').value = data.text;
}
}
function handleExistingNotes(socket) {
document.querySelectorAll('.note').forEach(note => {
const id = note.dataset.id;
const text = note.querySelector('textarea').value;
const x = note.offsetLeft;
const y = note.offsetTop;
const width = note.offsetWidth;
const height = note.offsetHeight;
note.querySelector('textarea').addEventListener('input', () => {
socket.emit('update_note', { id, text: note.querySelector('textarea').value, x, y, width, height });
});
note.querySelector('textarea').addEventListener('mousedown', (e) => {
e.stopPropagation();
});
addNoteEventListeners(note, id, socket);
});
}
function addNoteEventListeners(note, id, socket) {
note.addEventListener('mousedown', (e) => {
if (e.button !== 0) return; // Left mouse button
e.preventDefault();
e.stopPropagation();
const startX = e.clientX;
const startY = e.clientY;
const startLeft = parseFloat(note.style.left) || 0;
const startTop = parseFloat(note.style.top) || 0;
function moveNote(e) {
const deltaX = (e.clientX - startX) / scale;
const deltaY = (e.clientY - startY) / scale;
note.style.left = `${startLeft + deltaX}px`;
note.style.top = `${startTop + deltaY}px`;
const x = parseFloat(note.style.left) || 0;
const y = parseFloat(note.style.top) || 0;
const width = note.offsetWidth;
const height = note.offsetHeight;
socket.emit('update_note', { id, text: note.querySelector('textarea').value, x, y, width, height });
}
document.addEventListener('mousemove', moveNote);
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', moveNote);
}, { once: true });
});
note.addEventListener('touchstart', (e) => {
e.preventDefault();
e.stopPropagation();
const startX = e.touches[0].clientX;
const startY = e.touches[0].clientY;
const startLeft = parseFloat(note.style.left) || 0;
const startTop = parseFloat(note.style.top) || 0;
function moveNote(e) {
const deltaX = (e.touches[0].clientX - startX) / scale;
const deltaY = (e.touches[0].clientY - startY) / scale;
note.style.left = `${startLeft + deltaX}px`;
note.style.top = `${startTop + deltaY}px`;
const x = parseFloat(note.style.left) || 0;
const y = parseFloat(note.style.top) || 0;
const width = note.offsetWidth;
const height = note.offsetHeight;
socket.emit('update_note', { id, text: note.querySelector('textarea').value, x, y, width, height });
}
document.addEventListener('touchmove', moveNote);
document.addEventListener('touchend', () => {
document.removeEventListener('touchmove', moveNote);
}, { once: true });
});
note.addEventListener('dblclick', (e) => {
e.preventDefault();
e.stopPropagation();
showContextMenu(note, id, e.clientX, e.clientY);
});
note.addEventListener('touchstart', (e) => {
if (e.touches.length === 2) {
e.preventDefault();
e.stopPropagation();
showContextMenu(note, id, e.touches[0].clientX, e.touches[0].clientY);
}
});
addResizeListeners(note, id, 'note', socket);
}
// static/js/images.js
async function showImageForm(socket) {
const formHtml = `
<div id="image-form" style="position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); background:white; padding:20px; border-radius:8px; box-shadow:0 0 10px rgba(0,0,0,0.1); z-index: 1000;">
<label for="image-url" style="display:block; margin-bottom:8px;">Image URL:</label>
<input type="text" id="image-url" placeholder="Enter image URL" style="width: calc(100% - 22px); padding:10px; margin-bottom:12px; border:1px solid #ccc; border-radius:4px;"><br>
<label for="image-file" style="display:block; margin-bottom:8px;">Or Upload File:</label>
<input type="file" id="image-file" accept="image/*" style="margin-bottom:12px;"><br>
<button id="add-image-submit" style="padding:10px 20px; background-color:#007bff; color:white; border:none; border-radius:4px; cursor:pointer; margin-right:8px;">Add Image</button>
<button id="cancel-image" style="padding:10px 20px; background-color:#ccc; color:white; border:none; border-radius:4px; cursor:pointer;">Cancel</button>
</div>
`;
document.body.insertAdjacentHTML('beforeend', formHtml);
document.getElementById('add-image-submit').addEventListener('click', async () => {
const url = document.getElementById('image-url').value;
const fileInput = document.getElementById('image-file');
let imageUrl;
if (url) {
imageUrl = url;
} else if (fileInput.files.length > 0) {
const file = fileInput.files[0];
imageUrl = await uploadFile(file);
}
if (imageUrl) {
const x = Math.floor(Math.random() * window.innerWidth);
const y = Math.floor(Math.random() * window.innerHeight);
const img = new Image();
img.src = imageUrl;
img.onload = () => {
const maxWidth = 720;
const maxHeight = 720;
let width = img.naturalWidth;
let height = img.naturalHeight;
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height);
width *= ratio;
height *= ratio;
}
socket.emit('create_image', { url: imageUrl, x, y, width, height });
closeModal();
};
}
});
document.getElementById('cancel-image').addEventListener('click', closeModal);
function closeModal() {
const form = document.getElementById('image-form');
if (form) {
form.remove();
}
}
}
function initializeImages(socket) {
// Any initialization if needed
}
function createImageElement(data) {
const image = document.createElement('div');
image.className = 'image';
image.dataset.id = data.id;
image.style.left = `${data.x}px`;
image.style.top = `${data.y}px`;
image.style.width = `${data.width}px`;
image.style.height = `${data.height}px`;
const img = document.createElement('img');
img.src = data.url;
img.style.width = '100%';
img.style.height = '100%';
img.style.objectFit = 'contain'; // Maintains aspect ratio
image.appendChild(img);
addImageEventListeners(image, data.id, socket);
return image;
}
function updateImageElement(data) {
const image = document.querySelector(`.image[data-id="${data.id}"]`);
if (image) {
image.style.left = `${data.x}px`;
image.style.top = `${data.y}px`;
image.style.width = `${data.width}px`;
image.style.height = `${data.height}px`;
image.querySelector('img').src = data.url;
}
}
function handleExistingImages(socket) {
document.querySelectorAll('.image').forEach(image => {
const id = image.dataset.id;
const url = image.querySelector('img').src;
const x = image.offsetLeft;
const y = image.offsetTop;
const width = image.offsetWidth;
const height = image.offsetHeight;
image.addEventListener('dblclick', (e) => {
e.preventDefault();
e.stopPropagation();
showContextMenu(image, id, e.clientX, e.clientY);
});
addImageEventListeners(image, id, socket);
});
}
function addImageEventListeners(image, id, socket) {
image.addEventListener('mousedown', (e) => {
if (e.button !== 0) return; // Left mouse button
e.preventDefault();
e.stopPropagation();
const startX = e.clientX;
const startY = e.clientY;
const startLeft = parseFloat(image.style.left) || 0;
const startTop = parseFloat(image.style.top) || 0;
function moveImage(e) {
const deltaX = (e.clientX - startX) / scale;
const deltaY = (e.clientY - startY) / scale;
image.style.left = `${startLeft + deltaX}px`;
image.style.top = `${startTop + deltaY}px`;
const x = parseFloat(image.style.left) || 0;
const y = parseFloat(image.style.top) || 0;
const width = image.offsetWidth;
const height = image.offsetHeight;
socket.emit('update_image', { id, url: image.querySelector('img').src, x, y, width, height });
}
document.addEventListener('mousemove', moveImage);
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', moveImage);
}, { once: true });
});
image.addEventListener('touchstart', (e) => {
e.preventDefault();
e.stopPropagation();
const startX = e.touches[0].clientX;
const startY = e.touches[0].clientY;
const startLeft = parseFloat(image.style.left) || 0;
const startTop = parseFloat(image.style.top) || 0;
function moveImage(e) {
const deltaX = (e.touches[0].clientX - startX) / scale;
const deltaY = (e.touches[0].clientY - startY) / scale;
image.style.left = `${startLeft + deltaX}px`;
image.style.top = `${startTop + deltaY}px`;
const x = parseFloat(image.style.left) || 0;
const y = parseFloat(image.style.top) || 0;
const width = image.offsetWidth;
const height = image.offsetHeight;
socket.emit('update_image', { id, url: image.querySelector('img').src, x, y, width, height });
}
document.addEventListener('touchmove', moveImage);
document.addEventListener('touchend', () => {
document.removeEventListener('touchmove', moveImage);
}, { once: true });
});
image.addEventListener('dblclick', (e) => {
e.preventDefault();
e.stopPropagation();
showContextMenu(image, id, e.clientX, e.clientY);
});
image.addEventListener('touchstart', (e) => {
if (e.touches.length === 2) {
e.preventDefault();
e.stopPropagation();
showContextMenu(image, id, e.touches[0].clientX, e.touches[0].clientY);
}
});
addResizeListeners(image, id, 'image', socket);
}