Initial working state

This commit is contained in:
Max W. 2025-04-11 00:51:29 +02:00
commit 60149f73e2
7 changed files with 1955 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/node_modules

8
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

1137
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

17
package.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "dev",
"version": "1.0.0",
"description": "",
"license": "ISC",
"author": "",
"type": "commonjs",
"main": "index.js",
"scripts": {
"start": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"express": "^5.1.0",
"nodemon": "^3.1.9"
}
}

381
public/index.css Normal file
View File

@ -0,0 +1,381 @@
:root {
--bg-primary: #ffffff;
--bg-secondary: #f5f7fa;
--text-primary: #333333;
--text-secondary: #666666;
--border-color: #e0e0e0;
--accent-color: #4f46e5;
--accent-hover: #4338ca;
--line-numbers-bg: #f0f0f0;
--line-numbers-text: #888888;
--editor-bg: #f8f9fc;
--toast-bg: rgba(0, 0, 0, 0.8);
--toast-text: #ffffff;
--shadow-color: rgba(0, 0, 0, 0.1);
}
[data-theme="dark"] {
--bg-primary: #1a1a1a;
--bg-secondary: #252525;
--text-primary: #e0e0e0;
--text-secondary: #a0a0a0;
--border-color: #3a3a3a;
--accent-color: #6366f1;
--accent-hover: #818cf8;
--line-numbers-bg: #2a2a2a;
--line-numbers-text: #777777;
--editor-bg: #2d2d2d;
--toast-bg: rgba(255, 255, 255, 0.8);
--toast-text: #1a1a1a;
--shadow-color: rgba(0, 0, 0, 0.3);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', sans-serif;
background-color: var(--bg-primary);
color: var(--text-primary);
transition: background-color 0.3s, color 0.3s;
line-height: 1.6;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
}
header {
background-color: var(--bg-secondary);
border-bottom: 1px solid var(--border-color);
padding: 15px 0;
box-shadow: 0 1px 3px var(--shadow-color);
}
.header-content {
display: flex;
justify-content: space-between;
align-items: center;
}
.logo {
display: flex;
align-items: center;
gap: 10px;
font-weight: 700;
font-size: 1.5rem;
color: var(--accent-color);
}
.logo i {
font-size: 1.75rem;
}
.theme-toggle {
background: none;
border: none;
cursor: pointer;
color: var(--text-secondary);
font-size: 1.25rem;
padding: 8px;
border-radius: 50%;
transition: background-color 0.2s;
}
.theme-toggle:hover {
background-color: var(--border-color);
color: var(--text-primary);
}
main {
padding: 30px 0;
}
.editor-container {
display: flex;
flex-direction: column;
gap: 20px;
}
.editor-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.editor-header h2 {
font-weight: 600;
color: var(--text-primary);
}
.editor-wrapper {
display: flex;
border: 1px solid var(--border-color);
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 5px var(--shadow-color);
position: relative;
height: 500px;
}
.line-numbers {
background-color: var(--line-numbers-bg);
color: var(--line-numbers-text);
padding: 15px 10px;
text-align: right;
user-select: none;
overflow-y: hidden;
min-width: 50px;
font-family: 'Fira Code', monospace;
font-size: 0.9rem;
border-right: 1px solid var(--border-color);
}
.editor-area {
flex-grow: 1;
position: relative;
display: flex;
}
#editor {
width: 100%;
height: 100%;
padding: 15px;
background-color: var(--editor-bg);
color: var(--text-primary);
border: none;
resize: none;
font-family: 'Fira Code', monospace;
font-size: 0.9rem;
line-height: 1.5;
tab-size: 4;
outline: none;
}
.viewer-area {
width: 100%;
height: 100%;
padding: 15px;
background-color: var(--editor-bg);
color: var(--text-primary);
overflow: auto;
font-family: 'Fira Code', monospace;
font-size: 0.9rem;
line-height: 1.5;
white-space: pre;
tab-size: 4;
}
.code-viewer {
white-space: pre;
tab-size: 4;
}
.code-viewer pre,
.code-viewer code {
margin: 0;
padding: 0;
white-space: pre;
overflow-x: auto;
width: 100%;
font-family: 'Fira Code', monospace;
}
/* Ensure highlight.js doesn't add extra space */
.hljs {
padding: 0 !important;
background: transparent !important;
}
.action-buttons {
display: flex;
gap: 10px;
margin-top: 20px;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: 500;
font-size: 0.95rem;
transition: all 0.2s;
display: flex;
align-items: center;
gap: 8px;
}
.btn-primary {
background-color: var(--accent-color);
color: white;
}
.btn-primary:hover {
background-color: var(--accent-hover);
}
.btn-secondary {
background-color: var(--bg-secondary);
color: var(--text-primary);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
background-color: var(--border-color);
}
.toast {
position: fixed;
bottom: 20px;
right: 20px;
padding: 12px 20px;
background-color: var(--toast-bg);
color: var(--toast-text);
border-radius: 6px;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
transform: translateY(100px);
opacity: 0;
transition: all 0.3s;
z-index: 1000;
display: flex;
align-items: center;
gap: 10px;
}
.toast.show {
transform: translateY(0);
opacity: 1;
}
.loading-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 100;
display: none;
}
.spinner {
width: 50px;
height: 50px;
border: 5px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 1s linear infinite;
}
@keyframes spin {
100% {
transform: rotate(360deg);
}
}
.url-container {
display: flex;
flex-direction: row; /* Ensure horizontal layout */
align-items: stretch; /* Make items same height */
margin-top: 20px;
width: 100%;
}
.url-display {
flex: 1; /* Take up available space */
padding: 12px 15px;
background-color: var(--bg-secondary);
border: 1px solid var(--border-color);
border-right: none; /* Remove right border to connect with button */
border-radius: 6px 0 0 6px;
color: var(--text-primary);
font-family: 'Fira Code', monospace;
font-size: 0.9rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.copy-btn {
flex: 0 0 auto; /* Don't grow or shrink */
padding: 12px 15px;
background-color: var(--accent-color);
color: white;
border: none;
border-radius: 0 6px 6px 0;
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.copy-btn:hover {
background-color: var(--accent-hover);
}
footer {
background-color: var(--bg-secondary);
border-top: 1px solid var(--border-color);
padding: 20px 0;
text-align: center;
color: var(--text-secondary);
font-size: 0.9rem;
margin-top: 30px;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.editor-wrapper {
height: 400px;
}
.action-buttons {
flex-direction: column;
}
.btn {
width: 100%;
justify-content: center;
}
}
/* Custom styling for highlight.js themes */
[data-theme="light"] .hljs {
background: var(--editor-bg);
color: var(--text-primary);
}
[data-theme="dark"] .hljs {
background: var(--editor-bg);
color: var(--text-primary);
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: var(--bg-secondary);
}
::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-secondary);
}

308
public/index.html Normal file
View File

@ -0,0 +1,308 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeShare - Modern Pastebin</title>
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<!-- Highlight.js for syntax highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<!-- Google Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Fira+Code:wght@400;500&display=swap">
<link rel="stylesheet" href="/index.css">
</head>
<body data-theme="light">
<header>
<div class="container header-content">
<div class="logo">
<i class="fas fa-code"></i>
<span>CodeShare</span>
</div>
<button class="theme-toggle" id="themeToggle" aria-label="Toggle theme">
<i class="fas fa-moon"></i>
</button>
</div>
</header>
<main class="container">
<div class="editor-container">
<div class="editor-header">
<h2 id="pageTitle">Create New Paste</h2>
<div id="viewControls" style="display:none;">
<button class="btn btn-secondary" id="newPasteBtn">
<i class="fas fa-plus"></i> New Paste
</button>
</div>
</div>
<div class="editor-wrapper">
<div class="line-numbers" id="lineNumbers"></div>
<div class="editor-area">
<textarea id="editor" placeholder="Paste or type your code here..."></textarea>
<div class="viewer-area code-viewer" id="codeViewer">
<pre><code id="highlightedCode"></code></pre>
</div>
<div class="loading-overlay" id="loadingOverlay">
<div class="spinner"></div>
</div>
</div>
</div>
<div class="action-buttons" id="actionButtons">
<button class="btn btn-primary" id="saveBtn">
<i class="fas fa-save"></i> Save Paste
</button>
</div>
<div class="url-container" id="urlContainer">
<div class="url-display" id="urlDisplay"></div>
<button class="copy-btn" id="copyBtn">
<i class="fas fa-copy"></i>
</button>
</div>
</div>
</main>
<div class="toast" id="toast">
<i class="fas fa-info-circle"></i>
<span id="toastMessage"></span>
</div>
<footer>
<div class="container">
<p>&copy; 2025 CodeShare. A modern pastebin application.</p>
</div>
</footer>
<script>
$(document).ready(function() {
// API Endpoint (adjust based on your server settings)
const baseUrl = window.location.origin;
const API_BASE_URL = baseUrl + '/api';
// Theme toggle functionality
$('#themeToggle').on('click', function() {
const currentTheme = $('body').attr('data-theme');
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
$('body').attr('data-theme', newTheme);
// Update icon
if (newTheme === 'dark') {
$(this).html('<i class="fas fa-sun"></i>');
} else {
$(this).html('<i class="fas fa-moon"></i>');
}
// Store preference
localStorage.setItem('theme', newTheme);
});
// Check for saved theme preference
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
$('body').attr('data-theme', savedTheme);
if (savedTheme === 'dark') {
$('#themeToggle').html('<i class="fas fa-sun"></i>');
}
}
// Line numbers functionality
function updateLineNumbers() {
const text = $('#editor').val();
const lines = text.split('\n');
const lineCount = lines.length;
let lineNumbersHtml = '';
for (let i = 1; i <= lineCount; i++) {
lineNumbersHtml += i + '<br>';
}
$('#lineNumbers').html(lineNumbersHtml);
}
// Update line numbers on input
$('#editor').on('input scroll keyup', function() {
updateLineNumbers();
// Sync scroll position between textarea and line numbers
$('#lineNumbers').scrollTop($(this).scrollTop());
});
// Initialize line numbers
updateLineNumbers();
// Save paste functionality
$('#saveBtn').on('click', function() {
const content = $('#editor').val();
if (!content.trim()) {
showToast('Please enter some content first!', 'warning');
return;
}
$('#loadingOverlay').fadeIn(200);
$.ajax({
url: `${API_BASE_URL}/pastes`,
method: 'POST',
data: content,
contentType: 'text/plain',
success: function(response) {
const pasteUrl = `${window.location.origin}${window.location.pathname}?id=${response.id}`;
$('#urlDisplay').text(pasteUrl);
$('#urlContainer').fadeIn();
showToast('Paste created successfully!', 'success');
// Update URL without reloading page
history.pushState({}, '', `?id=${response.id}`);
// Copy to clipboard automatically
copyToClipboard(pasteUrl);
},
error: function(xhr) {
console.error('Error creating paste:', xhr);
showToast('Failed to create paste. Please try again.', 'error');
},
complete: function() {
$('#loadingOverlay').fadeOut(200);
}
});
});
// Copy URL functionality
$('#copyBtn').on('click', function() {
const url = $('#urlDisplay').text();
copyToClipboard(url);
});
function copyToClipboard(text) {
navigator.clipboard.writeText(text)
.then(function() {
showToast('URL copied to clipboard!', 'success');
})
.catch(function(err) {
console.error('Failed to copy: ', err);
showToast('Failed to copy URL.', 'error');
});
}
// Toast notification
function showToast(message, type = 'info') {
let icon = 'fa-info-circle';
switch(type) {
case 'success':
icon = 'fa-check-circle';
break;
case 'error':
icon = 'fa-exclamation-circle';
break;
case 'warning':
icon = 'fa-exclamation-triangle';
break;
}
$('#toast').html(`<i class="fas ${icon}"></i><span>${message}</span>`);
$('#toast').addClass('show');
setTimeout(function() {
$('#toast').removeClass('show');
}, 3000);
}
// Check for paste ID in URL
function getParameterByName(name) {
const url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
const results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
const pasteId = getParameterByName('id');
if (pasteId) {
// We're viewing an existing paste
$('#pageTitle').text('Viewing Paste');
$('#editor').hide();
$('#codeViewer').show();
$('#actionButtons').hide();
$('#viewControls').show();
$('#loadingOverlay').fadeIn(200);
$.ajax({
url: `${API_BASE_URL}/pastes/${pasteId}`,
method: 'GET',
success: function(response) {
const code = response;
// Clear any existing content first
$('#highlightedCode').empty();
// Use .text() to safely set the content without HTML interpretation
$('#highlightedCode').text(code);
// Apply syntax highlighting
hljs.highlightAll();
// Update line numbers for the viewer
const lines = code.split('\n');
const lineCount = lines.length;
let lineNumbersHtml = '';
for (let i = 1; i <= lineCount; i++) {
lineNumbersHtml += i + '<br>';
}
$('#lineNumbers').html(lineNumbersHtml);
},
error: function(xhr) {
console.error('Error fetching paste:', xhr);
showToast('Failed to load paste. It may have expired.', 'error');
// Redirect to new paste creation after a delay
setTimeout(function() {
window.location.href = window.location.pathname;
}, 2000);
},
complete: function() {
$('#loadingOverlay').fadeOut(200);
}
});
}
// New paste button
$('#newPasteBtn').on('click', function() {
window.location.href = window.location.pathname;
});
// Handle tab key in textarea
$('#editor').on('keydown', function(e) {
if (e.key === 'Tab') {
e.preventDefault();
const start = this.selectionStart;
const end = this.selectionEnd;
// Insert tab character
this.value = this.value.substring(0, start) + ' ' + this.value.substring(end);
// Move cursor position
this.selectionStart = this.selectionEnd = start + 4;
// Update line numbers
updateLineNumbers();
}
});
});
</script>
</body>
</html>

103
server.js Normal file
View File

@ -0,0 +1,103 @@
// Import necessary modules
const express = require('express');
const path = require('path');
// --- Configuration ---
const PORT = process.env.PORT || 3000; // Use environment variable or default to 3000
const PASTE_TTL_HOURS = 2;
const PASTE_TTL_MS = PASTE_TTL_HOURS * 60 * 60 * 1000; // Time-to-live in milliseconds
// --- In-Memory Storage ---
// Using a Map for efficient key-based storage and deletion
const pastes = new Map(); // Stores { id: content }
// --- Express App Setup ---
const app = express();
// Middleware to parse plain text request bodies (like Hastebin)
// Limit set to 1MB, adjust as needed
app.use(express.text({ limit: '1mb', type: 'text/plain' }));
app.use(express.json()); // For JSON API responses
// Serve static files from the 'public' directory
app.use(express.static('public'));
// Function to generate a unique ID without crypto
function generateUniqueId() {
const timestamp = Date.now().toString(36);
const randomPart = Math.random().toString(36).substring(2, 10);
return `${timestamp}-${randomPart}`;
}
// --- API Routes ---
/**
* POST /api/pastes
* Creates a new paste.
* Expects the raw text content in the request body.
* Responds with the generated ID for the paste.
*/
app.post('/api/pastes', (req, res) => {
const content = req.body;
// Basic validation: Ensure content is present and is a string
if (!content || typeof content !== 'string' || content.trim() === '') {
return res.status(400).json({ error: 'Paste content cannot be empty.' });
}
// Generate a unique ID without using crypto
const id = generateUniqueId();
// Store the paste content in the map
pastes.set(id, content);
console.log(`[${new Date().toISOString()}] Paste created with ID: ${id}`);
// Schedule the paste for deletion after the TTL
setTimeout(() => {
if (pastes.has(id)) {
pastes.delete(id);
console.log(`[${new Date().toISOString()}] Paste expired and deleted: ${id}`);
}
}, PASTE_TTL_MS);
// Respond with the ID
res.status(201).json({ id: id });
});
/**
* GET /api/pastes/:id
* Retrieves the content of a specific paste by its ID.
* Responds with the raw text content or 404 if not found.
*/
app.get('/api/pastes/:id', (req, res) => {
const id = req.params.id;
if (pastes.has(id)) {
const content = pastes.get(id);
// Send raw text content
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.status(200).send(content);
} else {
res.status(404).json({ error: 'Paste not found or has expired.' });
}
});
// Serve the main HTML page for all other routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// --- Start Server ---
app.listen(PORT, () => {
console.log(`Paste server listening on port ${PORT}`);
console.log(`Pastes will be stored for ${PASTE_TTL_HOURS} hours.`);
console.log(`Open http://localhost:${PORT} in your browser to use the application`);
});
// --- Graceful Shutdown (Optional but Recommended) ---
// Handles CTRL+C in the terminal
process.on('SIGINT', () => {
console.log('\nShutting down server...');
// Perform any cleanup here if needed (though in-memory storage is lost anyway)
process.exit(0);
});