mirror of
https://github.com/ION606/static-site-hosting.git
synced 2026-05-14 22:16:54 +00:00
added better editing
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
.venv
|
.venv
|
||||||
instance
|
instance
|
||||||
sites
|
sites
|
||||||
|
__pycache__
|
||||||
|
|||||||
@@ -1,21 +1,22 @@
|
|||||||
from flask import (
|
from flask import (
|
||||||
Flask,
|
Flask,
|
||||||
render_template,
|
render_template,
|
||||||
request,
|
request,
|
||||||
redirect,
|
redirect,
|
||||||
url_for,
|
url_for,
|
||||||
send_from_directory,
|
send_from_directory,
|
||||||
flash,
|
flash,
|
||||||
abort,
|
abort,
|
||||||
|
jsonify,
|
||||||
)
|
)
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
from flask_login import (
|
from flask_login import (
|
||||||
LoginManager,
|
LoginManager,
|
||||||
UserMixin,
|
UserMixin,
|
||||||
login_user,
|
login_user,
|
||||||
logout_user,
|
logout_user,
|
||||||
login_required,
|
login_required,
|
||||||
current_user,
|
current_user,
|
||||||
)
|
)
|
||||||
from flask_apscheduler import APScheduler
|
from flask_apscheduler import APScheduler
|
||||||
from werkzeug.security import generate_password_hash, check_password_hash
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
@@ -35,23 +36,24 @@ db = SQLAlchemy(app)
|
|||||||
|
|
||||||
# Models
|
# Models
|
||||||
class User(UserMixin, db.Model):
|
class User(UserMixin, db.Model):
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
email = db.Column(db.String(100), unique=True)
|
email = db.Column(db.String(100), unique=True)
|
||||||
password_hash = db.Column(db.String(128)) # Renamed for clarity
|
password_hash = db.Column(db.String(128)) # Renamed for clarity
|
||||||
|
|
||||||
def set_password(self, password):
|
def set_password(self, password):
|
||||||
self.password_hash = generate_password_hash(password)
|
self.password_hash = generate_password_hash(password)
|
||||||
|
|
||||||
def check_password(self, password):
|
def check_password(self, password):
|
||||||
return check_password_hash(self.password_hash, password)
|
return check_password_hash(self.password_hash, password)
|
||||||
|
|
||||||
|
|
||||||
class Site(db.Model):
|
class Site(db.Model):
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
user_id = db.Column(db.Integer)
|
user_id = db.Column(db.Integer)
|
||||||
name = db.Column(db.String(100))
|
name = db.Column(db.String(100))
|
||||||
last_accessed = db.Column(db.DateTime)
|
slug = db.Column(db.String(100), unique=True)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
last_accessed = db.Column(db.DateTime)
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
|
||||||
# Auth setup
|
# Auth setup
|
||||||
@@ -62,7 +64,7 @@ login_manager.login_view = "login"
|
|||||||
|
|
||||||
@login_manager.user_loader
|
@login_manager.user_loader
|
||||||
def load_user(user_id):
|
def load_user(user_id):
|
||||||
return User.query.get(int(user_id))
|
return User.query.get(int(user_id))
|
||||||
|
|
||||||
|
|
||||||
# Scheduler for auto-deletion
|
# Scheduler for auto-deletion
|
||||||
@@ -71,244 +73,241 @@ scheduler.init_app(app)
|
|||||||
|
|
||||||
|
|
||||||
def delete_inactive_sites():
|
def delete_inactive_sites():
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
cutoff = datetime.utcnow() - timedelta(days=30)
|
cutoff = datetime.utcnow() - timedelta(days=30)
|
||||||
sites = Site.query.filter(Site.last_accessed < cutoff).all()
|
sites = Site.query.filter(Site.last_accessed < cutoff).all()
|
||||||
for site in sites:
|
for site in sites:
|
||||||
site_dir = os.path.join(
|
site_dir = os.path.join(
|
||||||
app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id)
|
app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id)
|
||||||
)
|
)
|
||||||
if os.path.exists(site_dir):
|
if os.path.exists(site_dir):
|
||||||
shutil.rmtree(site_dir)
|
shutil.rmtree(site_dir)
|
||||||
db.session.delete(site)
|
db.session.delete(site)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
if not scheduler.running:
|
if not scheduler.running:
|
||||||
scheduler.start()
|
scheduler.start()
|
||||||
scheduler.add_job(
|
scheduler.add_job(
|
||||||
id="delete_job", func=delete_inactive_sites, trigger="interval", days=1
|
id="delete_job", func=delete_inactive_sites, trigger="interval", days=1
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# Routes
|
# Routes
|
||||||
@app.route("/login", methods=["GET", "POST"])
|
@app.route("/login", methods=["GET", "POST"])
|
||||||
def login():
|
def login():
|
||||||
if request.method == "POST":
|
if request.method == "POST":
|
||||||
email = request.form.get("email")
|
email = request.form.get("email")
|
||||||
password = request.form.get("password")
|
password = request.form.get("password")
|
||||||
user = User.query.filter_by(email=email).first()
|
user = User.query.filter_by(email=email).first()
|
||||||
|
|
||||||
if user and user.check_password(password):
|
if user and user.check_password(password):
|
||||||
login_user(user)
|
login_user(user)
|
||||||
return redirect(url_for("dashboard"))
|
return redirect(url_for("dashboard"))
|
||||||
flash("Invalid email or password")
|
flash("Invalid email or password")
|
||||||
return render_template("login.html")
|
return render_template("login.html")
|
||||||
|
|
||||||
|
|
||||||
@app.route("/logout")
|
@app.route("/logout")
|
||||||
def logout():
|
def logout():
|
||||||
logout_user()
|
logout_user()
|
||||||
return redirect(url_for("home"))
|
return redirect(url_for("home"))
|
||||||
|
|
||||||
|
|
||||||
@app.route("/register", methods=["GET", "POST"])
|
@app.route("/register", methods=["GET", "POST"])
|
||||||
def register():
|
def register():
|
||||||
if request.method == "POST":
|
if request.method == "POST":
|
||||||
email = request.form.get("email")
|
email = request.form.get("email")
|
||||||
password = request.form.get("password")
|
password = request.form.get("password")
|
||||||
|
|
||||||
if User.query.filter_by(email=email).first():
|
if User.query.filter_by(email=email).first():
|
||||||
flash("Email already exists")
|
flash("Email already exists")
|
||||||
return redirect(url_for("register"))
|
return redirect(url_for("register"))
|
||||||
|
|
||||||
new_user = User(email=email)
|
new_user = User(email=email)
|
||||||
new_user.set_password(password)
|
new_user.set_password(password)
|
||||||
db.session.add(new_user)
|
db.session.add(new_user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
login_user(new_user)
|
login_user(new_user)
|
||||||
return redirect(url_for("dashboard"))
|
return redirect(url_for("dashboard"))
|
||||||
return render_template("register.html")
|
return render_template("register.html")
|
||||||
|
|
||||||
|
|
||||||
@app.route("/dashboard")
|
@app.route("/dashboard")
|
||||||
@login_required
|
@login_required
|
||||||
def dashboard():
|
def dashboard():
|
||||||
sites = Site.query.filter_by(user_id=current_user.id).all()
|
sites = Site.query.filter_by(user_id=current_user.id).all()
|
||||||
return render_template("dashboard.html", sites=sites)
|
return render_template("dashboard.html", sites=sites)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/upload", methods=["POST"])
|
@app.route("/upload", methods=["POST"])
|
||||||
@login_required
|
@login_required
|
||||||
def upload_site():
|
def upload_site():
|
||||||
site_name = request.form.get("name")
|
site_name = request.form.get("name")
|
||||||
if not site_name:
|
slug = request.form.get("slug").strip()
|
||||||
flash("Site name is required", "error")
|
|
||||||
return redirect(url_for("dashboard"))
|
|
||||||
|
|
||||||
# Check if index.html is included
|
if not site_name or not slug:
|
||||||
files = request.files.getlist("files")
|
flash("Site name and URL slug are required", "error")
|
||||||
if not any(file.filename == "index.html" for file in files):
|
return redirect(url_for("dashboard"))
|
||||||
flash("You must include an index.html file", "error")
|
|
||||||
return redirect(url_for("dashboard"))
|
|
||||||
|
|
||||||
# Create site directory
|
# Check slug availability
|
||||||
site = Site(user_id=current_user.id, name=site_name)
|
if Site.query.filter_by(slug=slug).first():
|
||||||
db.session.add(site)
|
flash("This URL is already taken", "error")
|
||||||
db.session.commit()
|
return redirect(url_for("dashboard"))
|
||||||
|
|
||||||
site_dir = os.path.join(
|
# Check if index.html is included
|
||||||
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
|
files = request.files.getlist("files")
|
||||||
)
|
if not any(file.filename == "index.html" for file in files):
|
||||||
os.makedirs(site_dir, exist_ok=True)
|
flash("You must include an index.html file", "error")
|
||||||
|
return redirect(url_for("dashboard"))
|
||||||
|
|
||||||
# Save uploaded files
|
# Create site directory
|
||||||
for file in files:
|
site = Site(user_id=current_user.id, name=site_name, slug=slug)
|
||||||
if file.filename == "":
|
db.session.add(site)
|
||||||
continue
|
db.session.commit()
|
||||||
file.save(os.path.join(site_dir, file.filename))
|
|
||||||
|
|
||||||
flash("Site created successfully!", "success")
|
site_dir = os.path.join(
|
||||||
return redirect(url_for("dashboard"))
|
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
|
||||||
|
)
|
||||||
|
os.makedirs(site_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# Save uploaded files
|
||||||
|
for file in files:
|
||||||
|
if file.filename == "":
|
||||||
|
continue
|
||||||
|
file.save(os.path.join(site_dir, file.filename))
|
||||||
|
|
||||||
|
flash("Site created successfully!", "success")
|
||||||
|
return redirect(url_for("dashboard"))
|
||||||
|
|
||||||
|
|
||||||
@app.route("/edit/<int:site_id>", methods=["GET", "POST"])
|
@app.route("/edit/<int:site_id>", methods=["GET", "POST"])
|
||||||
@login_required
|
@login_required
|
||||||
def edit_site(site_id):
|
def edit_site(site_id):
|
||||||
site = Site.query.get_or_404(site_id)
|
site = Site.query.get_or_404(site_id)
|
||||||
if site.user_id != current_user.id:
|
if site.user_id != current_user.id:
|
||||||
return "Unauthorized", 403
|
return "Unauthorized", 403
|
||||||
|
|
||||||
site_dir = os.path.join(
|
site_dir = os.path.join(
|
||||||
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
|
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
|
||||||
)
|
)
|
||||||
|
|
||||||
if request.method == "POST":
|
if request.method == "POST":
|
||||||
site.name = request.form.get("name", site.name)
|
site.name = request.form.get("name", site.name)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
for filename, content in request.form.items():
|
for filename, content in request.form.items():
|
||||||
if filename.endswith((".html", ".css", ".js")):
|
if filename.endswith((".html", ".css", ".js")):
|
||||||
filepath = os.path.join(site_dir, filename)
|
filepath = os.path.join(site_dir, filename)
|
||||||
with open(filepath, "w") as f:
|
with open(filepath, "w") as f:
|
||||||
f.write(content)
|
f.write(content)
|
||||||
|
|
||||||
return redirect(url_for("dashboard"))
|
if request.headers.get("X-Requested-With") == "XMLHttpRequest":
|
||||||
|
return jsonify({"success": True, "message": "Site updated successfully!"})
|
||||||
|
|
||||||
files = {}
|
flash("Site updated successfully!", "success")
|
||||||
for file in os.listdir(site_dir):
|
return redirect(url_for("edit_site", site_id=site.id))
|
||||||
with open(os.path.join(site_dir, file), "r") as f:
|
|
||||||
files[file] = f.read()
|
|
||||||
|
|
||||||
return render_template("edit.html", site=site, files=files)
|
files = {}
|
||||||
|
for file in os.listdir(site_dir):
|
||||||
|
with open(os.path.join(site_dir, file), "r") as f:
|
||||||
|
files[file] = f.read()
|
||||||
|
|
||||||
|
return render_template("edit.html", site=site, files=files)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/delete/<int:site_id>", methods=["POST"])
|
@app.route("/delete/<int:site_id>", methods=["POST"])
|
||||||
@login_required
|
@login_required
|
||||||
def delete_site(site_id):
|
def delete_site(site_id):
|
||||||
site = Site.query.get_or_404(site_id)
|
site = Site.query.get_or_404(site_id)
|
||||||
if site.user_id != current_user.id:
|
if site.user_id != current_user.id:
|
||||||
return "Unauthorized", 403
|
return "Unauthorized", 403
|
||||||
|
|
||||||
site_dir = os.path.join(
|
site_dir = os.path.join(
|
||||||
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
|
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
|
||||||
)
|
)
|
||||||
if os.path.exists(site_dir):
|
if os.path.exists(site_dir):
|
||||||
shutil.rmtree(site_dir)
|
shutil.rmtree(site_dir)
|
||||||
|
|
||||||
db.session.delete(site)
|
db.session.delete(site)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return redirect(url_for("dashboard"))
|
return redirect(url_for("dashboard"))
|
||||||
|
|
||||||
|
|
||||||
@app.route("/delete_file/<int:site_id>/<filename>", methods=["POST"])
|
@app.route("/delete_file/<int:site_id>/<filename>", methods=["POST"])
|
||||||
@login_required
|
@login_required
|
||||||
def delete_file(site_id, filename):
|
def delete_file(site_id, filename):
|
||||||
# Get the site and verify ownership
|
# Get the site and verify ownership
|
||||||
site = Site.query.get_or_404(site_id)
|
site = Site.query.get_or_404(site_id)
|
||||||
if site.user_id != current_user.id:
|
if site.user_id != current_user.id:
|
||||||
return "Unauthorized", 403
|
return "Unauthorized", 403
|
||||||
|
|
||||||
# Build the file path
|
# Build the file path
|
||||||
site_dir = os.path.join(
|
site_dir = os.path.join(
|
||||||
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
|
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
|
||||||
)
|
)
|
||||||
file_path = os.path.join(site_dir, filename)
|
file_path = os.path.join(site_dir, filename)
|
||||||
|
|
||||||
# Delete the file if it exists
|
# Delete the file if it exists
|
||||||
if os.path.exists(file_path):
|
if os.path.exists(file_path):
|
||||||
os.remove(file_path)
|
os.remove(file_path)
|
||||||
flash(f"File '{filename}' deleted successfully!", "success")
|
flash(f"File '{filename}' deleted successfully!", "success")
|
||||||
else:
|
else:
|
||||||
flash(f"File '{filename}' not found!", "error")
|
flash(f"File '{filename}' not found!", "error")
|
||||||
|
|
||||||
return redirect(url_for("dashboard"))
|
return redirect(url_for("dashboard"))
|
||||||
|
|
||||||
|
|
||||||
@app.route("/site/<int:user_id>/<int:site_id>")
|
@app.route("/site/<slug>/", defaults={"filename": "index.html"})
|
||||||
def redirect_to_slash(user_id, site_id):
|
@app.route("/site/<slug>/<path:filename>")
|
||||||
"""Redirect URLs without trailing slash to the slash version"""
|
def serve_site_content(slug, filename):
|
||||||
return redirect(
|
site = Site.query.filter_by(slug=slug).first_or_404()
|
||||||
url_for(
|
site.last_accessed = datetime.utcnow()
|
||||||
"serve_site_content",
|
db.session.commit()
|
||||||
user_id=user_id,
|
|
||||||
site_id=site_id,
|
|
||||||
filename="index.html",
|
|
||||||
),
|
|
||||||
code=301,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
site_dir = os.path.join(
|
||||||
|
app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id)
|
||||||
|
)
|
||||||
|
|
||||||
@app.route("/site/<int:user_id>/<int:site_id>/", defaults={"filename": "index.html"})
|
# Security check
|
||||||
@app.route("/site/<int:user_id>/<int:site_id>/<path:filename>")
|
if ".." in filename or filename.startswith("/") or not os.path.exists(site_dir):
|
||||||
def serve_site_content(user_id, site_id, filename):
|
abort(404)
|
||||||
# Update last accessed time
|
|
||||||
site = Site.query.get_or_404(site_id)
|
|
||||||
site.last_accessed = datetime.utcnow()
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
# Get site directory
|
try:
|
||||||
site_dir = os.path.join(app.config["UPLOAD_FOLDER"], str(user_id), str(site_id))
|
# First try to serve requested file
|
||||||
|
return send_from_directory(site_dir, filename)
|
||||||
# Security check
|
except NotFound:
|
||||||
if '..' in filename or filename.startswith('/') or not os.path.exists(site_dir):
|
# Handle extensionless URLs and SPA-style routing
|
||||||
abort(404)
|
if "." not in filename:
|
||||||
|
# Try with .html extension
|
||||||
try:
|
try:
|
||||||
# First try to serve requested file
|
return send_from_directory(site_dir, f"{filename}.html")
|
||||||
return send_from_directory(site_dir, filename)
|
except NotFound:
|
||||||
except NotFound:
|
# Fallback to index.html for client-side routing
|
||||||
# Handle extensionless URLs and SPA-style routing
|
return send_from_directory(site_dir, "index.html")
|
||||||
if "." not in filename:
|
abort(404)
|
||||||
# Try with .html extension
|
|
||||||
try:
|
|
||||||
return send_from_directory(site_dir, f"{filename}.html")
|
|
||||||
except NotFound:
|
|
||||||
# Fallback to index.html for client-side routing
|
|
||||||
return send_from_directory(site_dir, "index.html")
|
|
||||||
abort(404)
|
|
||||||
|
|
||||||
|
|
||||||
def list_files(directory):
|
def list_files(directory):
|
||||||
try:
|
try:
|
||||||
return os.listdir(directory)
|
return os.listdir(directory)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
@app.context_processor
|
@app.context_processor
|
||||||
def inject_utilities():
|
def inject_utilities():
|
||||||
return dict(list_files=list_files)
|
return dict(list_files=list_files)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
def home():
|
def home():
|
||||||
return render_template("home.html")
|
return render_template("home.html")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
|
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
db.create_all()
|
db.create_all()
|
||||||
serve(app, host="0.0.0.0", port=5121)
|
serve(app, host="0.0.0.0", port=5121)
|
||||||
|
|||||||
+110
-42
@@ -11,54 +11,74 @@ function formatOption(option) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function getAceMode(language) {
|
||||||
|
let aceMode = "ace/mode/html"; // default fallback
|
||||||
|
if (language === "css") {
|
||||||
|
aceMode = "ace/mode/css";
|
||||||
|
} else if (language === "javascript") {
|
||||||
|
aceMode = "ace/mode/javascript";
|
||||||
|
} else if (language === "htmlmixed") {
|
||||||
|
aceMode = "ace/mode/html";
|
||||||
|
}
|
||||||
|
return aceMode;
|
||||||
|
}
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", () => {
|
document.addEventListener("DOMContentLoaded", () => {
|
||||||
const storedTheme = localStorage.getItem('editortheme');
|
const storedTheme = localStorage.getItem('editortheme');
|
||||||
|
|
||||||
// for each textarea (one per file) replace with Ace Editor
|
// Initialize Ace editor instance on the container
|
||||||
const editors = Array.from(document.querySelectorAll('textarea')).map((textarea) => {
|
const editor = ace.edit("editor-container");
|
||||||
const language = textarea.dataset.language,
|
editor.setTheme("ace/theme/chrome");
|
||||||
themeStyle = document.querySelector('#theme-style'),
|
|
||||||
isDark = themeStyle.href.includes('dark-styles.css'),
|
|
||||||
aceTheme = isDark ? "ace/theme/twilight" : "ace/theme/chrome",
|
|
||||||
editorContainer = document.createElement('div');
|
|
||||||
|
|
||||||
editorContainer.style.width = "100%";
|
// Default mode as html mixed. It will be updated based on file type.
|
||||||
editorContainer.style.height = "400px";
|
editor.session.setMode("ace/mode/html");
|
||||||
|
|
||||||
// insert the container after the textarea
|
// To track the current file (index)
|
||||||
textarea.parentNode.insertBefore(editorContainer, textarea.nextSibling);
|
var currentFileIndex = null;
|
||||||
// hide the original textarea
|
|
||||||
textarea.style.display = "none";
|
|
||||||
|
|
||||||
const editor = ace.edit(editorContainer);
|
// Returns Ace mode based on file extension
|
||||||
editor.setTheme(storedTheme || aceTheme);
|
function getAceMode(filename) {
|
||||||
|
if (filename.endsWith('.css')) return "ace/mode/css";
|
||||||
|
if (filename.endsWith('.js')) return "ace/mode/javascript";
|
||||||
|
return "ace/mode/html";
|
||||||
|
}
|
||||||
|
|
||||||
let aceMode = "ace/mode/html"; // default fallback
|
// When a file card is clicked then load its content into the editor
|
||||||
if (language === "css") {
|
document.querySelectorAll('#file-list .file-card').forEach((card) => {
|
||||||
aceMode = "ace/mode/css";
|
card.addEventListener('click', () => {
|
||||||
} else if (language === "javascript") {
|
// Save changes of currently open file
|
||||||
aceMode = "ace/mode/javascript";
|
if (currentFileIndex !== null) document.getElementById(`textarea-${currentFileIndex}`).value = editor.getValue();
|
||||||
} else if (language === "htmlmixed") {
|
currentFileIndex = card.getAttribute("data-index");
|
||||||
aceMode = "ace/mode/html";
|
|
||||||
|
// Get filename and load content from corresponding hidden textarea
|
||||||
|
const filename = card.getAttribute("data-file");
|
||||||
|
editor.setValue(document.getElementById(`textarea-${currentFileIndex}`).value);
|
||||||
|
editor.session.setMode(getAceMode(filename));
|
||||||
|
|
||||||
|
// Show the editor container
|
||||||
|
document.getElementById("editor-container").classList.add("visible");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update the corresponding hidden textarea whenever the editor value changes
|
||||||
|
editor.session.on("change", function (e) {
|
||||||
|
if (currentFileIndex !== null) {
|
||||||
|
const ta = document.getElementById("textarea-" + currentFileIndex);
|
||||||
|
ta.value = editor.getValue();
|
||||||
}
|
}
|
||||||
editor.session.setMode(aceMode);
|
});
|
||||||
|
|
||||||
// set initial content from the textarea and add options
|
// Initialize Select2 for the theme selector
|
||||||
editor.session.setValue(textarea.value.trim());
|
$(document).ready(function () {
|
||||||
editor.setOptions({
|
$('#theme-selector').select2({
|
||||||
fontSize: "14px",
|
templateResult: formatOption,
|
||||||
tabSize: 4,
|
placeholder: 'Select a theme',
|
||||||
useSoftTabs: true,
|
allowClear: true
|
||||||
wrap: true,
|
}).on('change', function () {
|
||||||
showPrintMargin: false
|
const selectedTheme = $('#theme-selector').val();
|
||||||
|
localStorage.setItem('editortheme', selectedTheme);
|
||||||
|
editor.setTheme(selectedTheme);
|
||||||
});
|
});
|
||||||
|
|
||||||
// update the hidden textarea whenever the Ace content changes
|
|
||||||
editor.session.on('change', () => {
|
|
||||||
textarea.value = editor.getValue();
|
|
||||||
});
|
|
||||||
|
|
||||||
return editor;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Retrieve the list of available themes
|
// Retrieve the list of available themes
|
||||||
@@ -66,7 +86,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
|||||||
themes = ThemeList.themes,
|
themes = ThemeList.themes,
|
||||||
themeSelector = document.querySelector('#theme-selector');
|
themeSelector = document.querySelector('#theme-selector');
|
||||||
|
|
||||||
themes.forEach(function (theme) {
|
themes.forEach((theme) => {
|
||||||
var option = document.createElement('option');
|
var option = document.createElement('option');
|
||||||
option.value = theme.theme;
|
option.value = theme.theme;
|
||||||
option.textContent = theme.caption;
|
option.textContent = theme.caption;
|
||||||
@@ -81,7 +101,55 @@ document.addEventListener("DOMContentLoaded", () => {
|
|||||||
placeholder: 'Select a theme',
|
placeholder: 'Select a theme',
|
||||||
allowClear: true
|
allowClear: true
|
||||||
}).on('change', function (_) {
|
}).on('change', function (_) {
|
||||||
localStorage.setItem('editortheme', themeSelector.value)
|
const selectedTheme = $('#theme-selector').val();
|
||||||
editors.forEach(editor => editor.setTheme(themeSelector.value));
|
localStorage.setItem('editortheme', selectedTheme);
|
||||||
|
editor.setTheme(selectedTheme);
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
// Add event listener for Ctrl+S to save the current file
|
||||||
|
//TODO: save this
|
||||||
|
const editEl = document.querySelector('#editor-container');
|
||||||
|
|
||||||
|
document.addEventListener('keydown', (e) => {
|
||||||
|
if (e.ctrlKey && e.key === 's') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (currentFileIndex !== null) {
|
||||||
|
document.getElementById("textarea-" + currentFileIndex).value = editor.getValue();
|
||||||
|
document.querySelector("form").submit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (editEl.contains(e.target)) {
|
||||||
|
document.getElementById("textarea-" + currentFileIndex).value = editor.getValue();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// form submit intercept
|
||||||
|
document.querySelector("form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
document.querySelectorAll("[id^='textarea-']").forEach((textarea) => {
|
||||||
|
if (textarea.dataset.edited === "true") {
|
||||||
|
formData.append(textarea.name, textarea.value);
|
||||||
|
delete textarea.dataset.edited;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await fetch(window.location.href, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"X-Requested-With": "XMLHttpRequest"
|
||||||
|
},
|
||||||
|
body: formData
|
||||||
|
})
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
if (data.success) {
|
||||||
|
alert("Site updated successfully!"); // Or display a flash message
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error("Error:", error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -261,6 +261,29 @@ button:hover,
|
|||||||
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.15);
|
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.15);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.flash-messages {
|
||||||
|
margin: 10px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.flash-message {
|
||||||
|
padding: 10px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.flash-success {
|
||||||
|
color: #3c763d;
|
||||||
|
background-color: #dff0d8;
|
||||||
|
border-color: #d6e9c6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.flash-error {
|
||||||
|
color: #a94442;
|
||||||
|
background-color: #f2dede;
|
||||||
|
border-color: #ebccd1;
|
||||||
|
}
|
||||||
|
|
||||||
/* Theme Toggle */
|
/* Theme Toggle */
|
||||||
#theme-toggle {
|
#theme-toggle {
|
||||||
background-color: var(--card-bg);
|
background-color: var(--card-bg);
|
||||||
@@ -295,6 +318,23 @@ button:hover,
|
|||||||
background-color: #0056b3;
|
background-color: #0056b3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#editor-container {
|
||||||
|
width: 100%;
|
||||||
|
height: 400px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
margin-top: 20px;
|
||||||
|
transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
|
||||||
|
transform: translateY(-100%);
|
||||||
|
opacity: 0;
|
||||||
|
display: none; /* Initially hidden */
|
||||||
|
}
|
||||||
|
|
||||||
|
#editor-container.visible {
|
||||||
|
transform: translateY(0);
|
||||||
|
opacity: 1;
|
||||||
|
display: block; /* Display when visible */
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.file-grid {
|
.file-grid {
|
||||||
grid-template-columns: repeat(2, 1fr);
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
|||||||
@@ -12,10 +12,18 @@
|
|||||||
<input type="text" name="name" required>
|
<input type="text" name="name" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Add slug input -->
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Custom URL Slug:</label>
|
||||||
|
<input type="text" name="slug" required pattern="[a-zA-Z0-9\-_]+"
|
||||||
|
title="Letters, numbers, hyphens, and underscores only">
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="form-group" onclick="document.querySelector('#file-input').click()">
|
<div class="form-group" onclick="document.querySelector('#file-input').click()">
|
||||||
<label class="upload-label">
|
<label class="upload-label">
|
||||||
Upload Files
|
Upload Files
|
||||||
<input type="file" name="files" style="display: none;" id="file-input" multiple accept=".html,.css,.js" required>
|
<input type="file" name="files" style="display: none;" id="file-input" multiple accept=".html,.css,.js"
|
||||||
|
required>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -61,8 +69,7 @@
|
|||||||
<!-- Site Actions -->
|
<!-- Site Actions -->
|
||||||
<div class="site-actions">
|
<div class="site-actions">
|
||||||
<a href="{{ url_for('edit_site', site_id=site.id) }}" class="btn">Edit</a>
|
<a href="{{ url_for('edit_site', site_id=site.id) }}" class="btn">Edit</a>
|
||||||
<a href="{{ url_for('serve_site_content', user_id=current_user.id, site_id=site.id) }}" class="btn"
|
<a href="{{ url_for('serve_site_content', slug=site.slug) }}" class="btn" target="_blank">View Site</a>
|
||||||
target="_blank">View Site</a>
|
|
||||||
<form method="POST" action="{{ url_for('delete_site', site_id=site.id) }}" style="display: inline;">
|
<form method="POST" action="{{ url_for('delete_site', site_id=site.id) }}" style="display: inline;">
|
||||||
<button type="submit" class="btn btn-danger">Delete Site</button>
|
<button type="submit" class="btn btn-danger">Delete Site</button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
+29
-27
@@ -4,32 +4,42 @@
|
|||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<h2>Edit {{ site.name }}</h2>
|
<h2>Edit {{ site.name }}</h2>
|
||||||
<a href="{{ url_for('serve_site_content', user_id=current_user.id, site_id=site.id) }}" class="btn" target="_blank">View
|
<a href="{{ url_for('serve_site_content', slug=site.slug) }}" class="btn" target="_blank">View Site</a>
|
||||||
Site</a>
|
|
||||||
|
|
||||||
<div style="margin-bottom: 30px;"></div>
|
<div style="margin-bottom: 30px;"></div>
|
||||||
|
|
||||||
<label for="theme-selector">Select Theme:</label>
|
<label for="theme-selector">Select Theme:</label>
|
||||||
<select id="theme-selector" style="width: 200px;">
|
<select id="theme-selector" style="width: 200px;">
|
||||||
<!-- Theme options will be populated here -->
|
<!-- Theme options will be populated here -->
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
|
||||||
<form method="POST">
|
<form method="POST">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>Site Name:</label>
|
<label>Site Name:</label>
|
||||||
<input type="text" name="name" value="{{ site.name }}">
|
<input type="text" name="name" value="{{ site.name }}">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{% for filename, content in files.items() %}
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>{{ filename }}:</label>
|
<label>Files:</label>
|
||||||
<textarea name="{{ filename }}" rows="20"
|
<ul id="file-list" class="file-grid" style="padding-left: 0; list-style: none;">
|
||||||
data-language="{% if filename.endswith('.css') %}css{% elif filename.endswith('.js') %}javascript{% else %}htmlmixed{% endif %}">{{ content|trim }}</textarea>
|
{% for filename, content in files.items() %}
|
||||||
</div>
|
<li class="file-card" style="cursor: pointer;" data-index="{{ loop.index0 }}" data-file="{{ filename }}">
|
||||||
{% endfor %}
|
<div class="file-icon {% if filename.endswith('.html') %}html{% elif filename.endswith('.css') %}css{% elif filename.endswith('.js') %}js{% endif %}"></div>
|
||||||
|
<span class="file-name">{{ filename }}</span>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button type="submit">Save Changes</button>
|
<!-- Hidden textareas to retain file content (one per file) -->
|
||||||
|
{% for filename, content in files.items() %}
|
||||||
|
<textarea hidden name="{{ filename }}" id="textarea-{{ loop.index0 }}" data-filename="{{ filename }}">{{ content|trim }}</textarea>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
<!-- Ace Editor Container -->
|
||||||
|
<div id="editor-container" style="width: 100%; height: 400px; border: 1px solid #ddd; margin-top: 20px;"></div>
|
||||||
|
|
||||||
|
<button type="submit" class="btn" style="margin-top:20px;">Save Changes</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<!-- Ace Editor -->
|
<!-- Ace Editor -->
|
||||||
@@ -41,19 +51,11 @@
|
|||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
|
||||||
<script src="{{ url_for('static', filename='editor.js') }}"></script>
|
<script src="{{ url_for('static', filename='editor.js') }}"></script>
|
||||||
|
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
/* Style for the Select2 dropdown */
|
/* Style for the Select2 dropdown */
|
||||||
.select2-container {
|
.select2-container {
|
||||||
margin-bottom: 10px;
|
margin-bottom: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Ensure the editor has a defined height */
|
|
||||||
#editor {
|
|
||||||
width: 100%;
|
|
||||||
max-height: 500px;
|
|
||||||
border: 1px solid #ddd;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
Reference in New Issue
Block a user