imageediting / templates /index.html
Ezmary's picture
Update templates/index.html
b372360 verified
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Photoshop Pro (IndexedDB Version)</title>
<link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root {
--app-font: 'Vazirmatn', sans-serif;
--app-bg: #F8F9FC;
--panel-bg: #FFFFFF;
--panel-border: #EAEFF7;
--input-bg: #F6F8FB;
--input-border: #E1E7EF;
--text-primary: #1A202C;
--text-secondary: #626F86;
--text-tertiary: #8A94A6;
--accent-primary: #4A6CFA;
--accent-primary-hover: #3553D6;
--accent-primary-glow: rgba(74, 108, 250, 0.25);
--accent-secondary: #0FD4A8;
--accent-premium: #FFC107;
--accent-premium-glow: rgba(255, 193, 7, 0.3);
--danger-color: #e53e3e;
--danger-color-hover: #c53030;
--shadow-sm: 0 1px 2px 0 rgba(26, 32, 44, 0.03);
--shadow-md: 0 4px 6px -1px rgba(26, 32, 44, 0.05), 0 2px 4px -2px rgba(26, 32, 44, 0.04);
--shadow-lg: 0 10px 15px -3px rgba(26, 32, 44, 0.06), 0 4px 6px -4px rgba(26, 32, 44, 0.05);
--shadow-xl: 0 20px 25px -5px rgba(26, 32, 44, 0.07), 0 8px 10px -6px rgba(26, 32, 44, 0.05);
--radius-card: 24px;
--radius-btn: 14px;
--radius-input: 12px;
--transition-smooth: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
@keyframes badge-fade-in { from { opacity: 0; transform: translateY(-10px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } }
body { font-family: var(--app-font); background-color: var(--app-bg); color: var(--text-primary); margin: 0; padding: 2.5rem 1rem; display: flex; justify-content: center; align-items: flex-start; min-height: 100vh; }
.container { max-width: 820px; width: 100%; }
header { position: relative; text-align: center; margin-bottom: 2.5rem; padding: 2rem 0; animation: fadeIn 0.8s 0.1s ease-out backwards; overflow: hidden; }
#neural-network-canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; }
h1, .subtitle, #subscription-status-badge { position: relative; z-index: 2; }
h1 { font-size: 2.8rem; font-weight: 800; margin: 0 0 0.8rem 0; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: -1px; }
.subtitle { font-size: 1.1rem; color: var(--text-secondary); margin-top: 0; }
#subscription-status-badge { display: none; padding: 6px 16px; border-radius: 20px; font-size: 0.9em; font-weight: 700; margin-top: 1.25rem; letter-spacing: 0.5px; animation: badge-fade-in 0.6s 0.5s ease-out backwards; }
#subscription-status-badge.free-badge { background: linear-gradient(45deg, #6c757d, #495057); color: white; box-shadow: 0 4px 10px rgba(108, 117, 125, 0.3); }
#subscription-status-badge.paid-badge { background: linear-gradient(45deg, var(--accent-premium), #ffca2c); color: #333; box-shadow: 0 4px 10px var(--accent-premium-glow); }
#credit-info-section { margin-top: 1.5rem; padding: 1rem; background-color: var(--input-bg); border-radius: var(--radius-input); text-align: center; font-size: 0.95rem; font-weight: 500; color: var(--text-secondary); border: 1px solid var(--input-border); display: none; }
#upgrade-button { margin-top: 1rem; width: 100%; padding: 1rem; font-size: 1.1rem; font-weight: 700; background: linear-gradient(95deg, #FFD54F, #FFC107 100%); color: #212529; border: none; border-radius: var(--radius-btn); cursor: pointer; box-shadow: 0 8px 20px -5px rgba(255, 193, 7, 0.3); display: none; }
main, .gallery-section { padding: 3rem; background-color: var(--panel-bg); border-radius: var(--radius-card); box-shadow: var(--shadow-xl); border: 1px solid var(--panel-border); animation: fadeIn 0.8s 0.3s ease-out backwards; }
.gallery-section { margin-top: 3rem; animation-delay: 0.5s; }
.form-group { margin-bottom: 2.5rem; }
.form-group:last-child { margin-bottom: 0; }
.form-label { display: flex; align-items: center; gap: 0.75rem; font-weight: 700; color: var(--text-primary); font-size: 1.2em; margin-bottom: 1.2rem; }
.form-label svg { width: 24px; height: 24px; color: var(--accent-primary); }
#upload-area { position: relative; border: 2px dashed var(--input-border); border-radius: var(--radius-input); padding: 2.5rem; text-align: center; cursor: pointer; transition: var(--transition-smooth); background-color: var(--input-bg); min-height: 200px; display: flex; flex-direction: column; justify-content: center; align-items: center; overflow: hidden; }
#upload-area.drag-over, #upload-area:hover:not(.has-file) { border-color: var(--accent-primary); background-color: #fff; box-shadow: 0 0 15px var(--accent-primary-glow); }
#upload-area.has-file { border-style: solid; border-color: var(--panel-border); padding: 0; cursor: default; }
#upload-content { display: flex; flex-direction: column; align-items: center; gap: 1rem; }
#upload-icon svg { width: 48px; height: 48px; color: var(--accent-primary); stroke-width: 1.5; opacity: 0.8; }
#upload-area p { margin: 0; color: var(--text-secondary); font-weight: 500; }
#preview-image-main { display: none; width: 100%; height: 100%; object-fit: contain; position: absolute; top: 0; left: 0; }
#remove-file-btn-main { display: none; position: absolute; top: 12px; right: 12px; background-color: rgba(26, 32, 44, 0.6); color: white; border: none; width: 32px; height: 32px; border-radius: 50%; cursor: pointer; font-size: 1.2rem; line-height: 1; z-index: 10; transition: var(--transition-smooth); padding: 0; }
#remove-file-btn-main:hover { background-color: var(--danger-color); transform: scale(1.1); }
#upload-area.has-file #upload-content { display: none; }
#upload-area.has-file #preview-image-main, #upload-area.has-file #remove-file-btn-main { display: block; }
textarea { width: 100%; padding: 1rem 1.2rem; border-radius: var(--radius-input); border: 1px solid var(--input-border); background-color: var(--input-bg); color: var(--text-primary); box-shadow: var(--shadow-sm) inset; font-family: var(--app-font); font-size: 1rem; box-sizing: border-box; transition: var(--transition-smooth); min-height: 90px; resize: vertical; }
textarea:focus { outline: none; border-color: var(--accent-primary); box-shadow: 0 0 0 3px var(--accent-primary-glow), var(--shadow-sm) inset; background-color: var(--panel-bg); }
#submit-btn { display: flex; align-items: center; justify-content: center; gap: 0.75rem; width: 100%; padding: 1.1rem; font-size: 1.2rem; font-weight: 700; background: linear-gradient(95deg, var(--accent-secondary) 0%, var(--accent-primary) 100%); color: #fff; border: none; border-radius: var(--radius-btn); cursor: pointer; transition: all 0.3s ease; box-shadow: 0 6px 12px -3px var(--accent-primary-glow), 0 6px 12px -3px rgba(15, 212, 168, 0.25); margin-top: 1rem; }
#submit-btn svg { width: 24px; height: 24px; margin-left: 4px; filter: drop-shadow(0 0 5px rgba(255,255,255,0.5)); }
#submit-btn:hover:not(:disabled) { transform: translateY(-5px) scale(1.02); box-shadow: 0 8px 20px -4px var(--accent-primary-glow), 0 8px 20px -4px rgba(15, 212, 168, 0.3); }
#submit-btn:disabled { background: var(--text-tertiary); cursor: not-allowed; box-shadow: none; opacity: 0.7; }
#submit-btn .spinner { width: 20px; height: 20px; border: 3px solid rgba(255, 255, 255, 0.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.8s linear infinite; display: none; }
#result-container { min-height: 350px; position: relative; padding: 1rem; background-color: var(--input-bg); border-radius: var(--radius-card); border: 2px dashed var(--input-border); box-shadow: var(--shadow-sm) inset; transition: var(--transition-smooth); display: flex; align-items: center; justify-content: center; }
#result-container.loading, #result-container.has-content { border-style: solid; border-color: var(--panel-border); }
#loading-placeholder { display: none; }
#result-container.loading #loading-placeholder { display: flex; animation: fadeIn 0.5s; justify-content: center; align-items: center; width: 100%; }
.generator-container { position: relative; width: 400px; max-width: 100%; height: 300px; border: 2px solid #38bdf8; border-radius: 20px; overflow: hidden; box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); animation: pulse 5s infinite cubic-bezier(0.4, 0, 0.6, 1); background-color: #161b22; color: #f0f6fc; }
@keyframes pulse { 0% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } 50% { box-shadow: 0 0 60px rgba(56, 189, 248, 0.7); } 100% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } }
.noise-layer, .sketch-layer, .building-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
.noise-layer { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect width="100" height="100" fill="none"/><filter id="noise"><feTurbulence type="fractalNoise" baseFrequency="0.5" numOctaves="4" stitchTiles="stitch"/></filter><rect width="100%" height="100%" filter="url(%23noise)" opacity="0.6"/></svg>') repeat; opacity: 1; animation: fade-noise 7s infinite ease-in-out; }
@keyframes fade-noise { 0% { opacity: 1; filter: blur(5px); } 30% { opacity: 0.8; filter: blur(2px); } 100% { opacity: 0; filter: blur(0px); } }
.sketch-layer { filter: grayscale(1) contrast(1.5) blur(3px); opacity: 0; animation: reveal-sketch 7s infinite ease-in-out; }
@keyframes reveal-sketch { 0% { opacity: 0; } 20% { opacity: 1; } 60% { opacity: 0.5; } 100% { opacity: 0; } }
.building-layer { filter: blur(15px); opacity: 0; animation: denoise-color 7s infinite ease-in-out; }
@keyframes denoise-color { 0% { opacity: 0; } 40% { opacity: 0.6; filter: blur(5px); } 100% { opacity: 1; filter: blur(0px); } }
.pixel-grid { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: repeating-linear-gradient(0deg, transparent 0 1px, rgba(255,255,255,0.1) 1px 2px), repeating-linear-gradient(90deg, transparent 0 1px, rgba(255,255,255,0.1) 1px 2px); opacity: 1; animation: dissolve-grid 7s infinite ease-in-out; }
@keyframes dissolve-grid { 0% { opacity: 1; } 70% { opacity: 0.5; } 100% { opacity: 0; } }
.particles { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(circle, rgba(56, 189, 248, 0.2) 0%, transparent 50%); animation: flow-particles 7s infinite cubic-bezier(0.4, 0, 0.6, 1); }
@keyframes flow-particles { 0% { transform: translate(0, 0) scale(1); } 50% { transform: translate(10px, -15px) scale(1.05); } 100% { transform: translate(0, 0) scale(1); } }
.text-overlay { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); font-size: 24px; font-weight: 700; text-shadow: 0 0 20px rgba(56, 189, 248, 0.8); animation: glow-text 7s infinite ease-in-out; font-family: var(--app-font); }
@keyframes glow-text { 0% { opacity: 0.7; } 50% { opacity: 1; } 100% { opacity: 0.7; } }
.progress-bar { position: absolute; bottom: 0; left: 0; width: 0%; height: 6px; background: linear-gradient(to right, #38bdf8, #bb86fc, #facc15); animation: progress 7s infinite linear; }
@keyframes progress { 0% { width: 0%; } 100% { width: 100%; } }
#result-grid { display: none; grid-template-columns: repeat(2, 1fr); gap: 1.5rem; width: 100%; }
#result-container.has-content #result-grid { display: grid; }
#result-grid img { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; border-radius: var(--radius-input); cursor: pointer; transition: var(--transition-smooth); box-shadow: var(--shadow-md); border: 1px solid var(--panel-border); }
#result-grid img:hover { transform: scale(1.05); box-shadow: var(--shadow-lg); z-index: 10; position: relative; }
#error-message { color: var(--danger-color); text-align: center; margin-top: 1rem; display: none; font-weight: 500; }
.gallery-header { display: flex; justify-content: space-between; align-items: center; }
#clear-history-btn { background: none; border: 1px solid var(--panel-border); color: var(--text-secondary); padding: 0.5rem 1rem; border-radius: var(--radius-btn); cursor: pointer; display: none; align-items: center; gap: 0.5rem; font-family: var(--app-font); font-weight: 500; transition: all 0.2s; }
#clear-history-btn:hover { border-color: var(--danger-color); color: var(--danger-color); }
#clear-history-btn svg { width: 18px; height: 18px; }
#history-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1.5rem; margin-top: 1.5rem; }
#history-grid:empty::before { content: 'هنوز تصویری خلق نکرده‌اید. اولین ویرایش شما اینجا ذخیره خواهد شد.'; color: var(--text-secondary); grid-column: 1 / -1; text-align: center; padding: 3rem 1rem; background-color: var(--input-bg); border-radius: var(--radius-card); }
.history-item { position: relative; background-color: var(--input-bg); border-radius: var(--radius-card); border: 1px solid var(--panel-border); padding: 1rem; transition: var(--transition-smooth); }
.history-item:hover { transform: translateY(-5px); box-shadow: var(--shadow-lg); }
.history-item-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 0.75rem; }
.history-item-grid img { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; border-radius: var(--radius-input); cursor: pointer; transition: transform 0.2s ease, box-shadow 0.2s ease; border: 1px solid var(--panel-border); }
.history-item-grid img:hover { transform: scale(1.1); box-shadow: var(--shadow-md); z-index: 5; position: relative; }
.history-delete-btn { position: absolute; top: 0.75rem; right: 0.75rem; background: none; border: none; cursor: pointer; padding: 0.5rem; border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; color: var(--text-tertiary); transition: var(--transition-smooth); z-index: 5; }
.history-delete-btn:hover { background-color: var(--panel-border); color: var(--danger-color); }
#lightbox { position: fixed; inset: 0; background-color: rgba(18, 24, 38, 0.6); backdrop-filter: blur(10px) saturate(150%); display: flex; align-items: center; justify-content: center; z-index: 1000; opacity: 0; transition: opacity 0.3s; pointer-events: none; }
#lightbox.visible { opacity: 1; pointer-events: auto; }
#lightbox-content { position: relative; animation: fadeIn 0.3s ease; display: flex; align-items: center; justify-content: center; }
#lightbox-img { max-width: 85vw; max-height: 80vh; object-fit: contain; border-radius: var(--radius-card); box-shadow: var(--shadow-xl); }
.lightbox-btn { position: absolute; background-color: rgba(255, 255, 255, 0.1); color: white; border: 1px solid rgba(255,255,255,0.2); width: 44px; height: 44px; border-radius: 50%; cursor: pointer; display: flex; justify-content: center; align-items: center; transition: all 0.2s; text-decoration: none; font-size: 24px; }
.lightbox-btn:hover { background-color: rgba(255, 255, 255, 0.2); transform: scale(1.1); }
#lightbox-close { top: -50px; right: 0; }
#lightbox-download { top: -50px; left: 0; }
#lightbox-next { right: -60px; top: 50%; transform: translateY(-50%); }
#lightbox-download svg { width: 22px; height: 22px; }
#lightbox-download .spinner { width: 20px; height: 20px; border: 3px solid rgba(255, 255, 255, 0.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.8s linear infinite; display: none; }
#confirmation-modal { position: fixed; inset: 0; background-color: rgba(18, 24, 38, 0.6); backdrop-filter: blur(10px); display: flex; align-items: center; justify-content: center; z-index: 2000; opacity: 0; transition: opacity 0.3s; pointer-events: none; }
#confirmation-modal.visible { opacity: 1; pointer-events: auto; }
.modal-dialog { background: var(--panel-bg); color: var(--text-primary); border-radius: var(--radius-card); padding: 2rem; width: 90%; max-width: 400px; text-align: center; box-shadow: var(--shadow-xl); animation: fadeIn 0.3s ease-out backwards; }
.modal-icon { width: 48px; height: 48px; margin: 0 auto 1.5rem; color: var(--danger-color); }
.modal-dialog h3 { font-size: 1.5rem; margin: 0 0 0.75rem; font-weight: 700; }
.modal-dialog p { font-size: 1rem; color: var(--text-secondary); margin: 0 0 2rem; }
.modal-buttons { display: flex; gap: 1rem; }
.modal-btn { flex: 1; padding: 0.8rem 1rem; border-radius: var(--radius-btn); border: none; cursor: pointer; font-family: var(--app-font); font-weight: 600; font-size: 1rem; transition: var(--transition-smooth); }
.modal-btn.confirm-btn { background-color: var(--danger-color); color: white; }
.modal-btn.confirm-btn:hover { background-color: var(--danger-color-hover); transform: translateY(-2px); }
.modal-btn.cancel-btn { background-color: var(--input-bg); color: var(--text-secondary); border: 1px solid var(--input-border); }
.modal-btn.cancel-btn:hover { background-color: var(--panel-border); color: var(--text-primary); }
@media (max-width: 768px) { main, .gallery-section { padding: 1.5rem; } h1 { font-size: 2.2rem; } #lightbox-next { right: 5px; background-color: rgba(26, 32, 44, 0.5); } }
</style>
</head>
<body>
<div class="container">
<header>
<canvas id="neural-network-canvas"></canvas>
<h1>فتوشاپ هوش مصنوعی ✨</h1>
<p class="subtitle">تصاویر خود را با قدرت هوش مصنوعی و به زبان ساده ویرایش کنید</p>
<div id="subscription-status-badge" style="display:inline-block;"></div>
</header>
<main>
<div class="form-group">
<div class="form-label">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg>
۱. تصویر خود را انتخاب کنید
</div>
<label id="upload-area" for="file-input">
<div id="upload-content">
<div id="upload-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg></div>
<p>فایل تصویر را اینجا بکشید یا برای انتخاب کلیک کنید</p>
</div>
<img id="preview-image-main" src="" alt="Preview">
<button type="button" id="remove-file-btn-main" title="حذف تصویر">&times;</button>
</label>
<input type="file" id="file-input" accept="image/*" hidden>
</div>
<div class="form-group">
<label for="prompt-input" class="form-label">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
۲. دستور ویرایش را بنویسید
</label>
<textarea id="prompt-input" rows="3" placeholder="مثال: پس‌زمینه را حذف کن و یک ساحل آفتابی قرار بده"></textarea>
<div id="credit-info-section"></div>
<button id="upgrade-button">⭐️ ارتقا به نسخه کامل و نامحدود</button>
<button id="submit-btn" disabled>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/></svg>
<span id="btn-text">ایجاد کن</span>
<div class="spinner"></div>
</button>
<p id="error-message"></p>
</div>
<div class="form-group">
<div class="form-label">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/><path d="M21 14l-1.5 3-3-1.5 3-3 1.5 3z"/><path d="M19.5 2.5l-3 1.5 1.5 3 3-1.5-1.5-3z"/></svg>
۳. نتیجه را ببینید
</div>
<div id="result-container">
<div id="loading-placeholder">
<div class="generator-container">
<div class="noise-layer"></div><div class="sketch-layer"></div><div class="building-layer"></div><div class="pixel-grid"></div><div class="particles"></div>
<div class="text-overlay">در حال ویرایش تصویر...</div>
<div class="progress-bar"></div>
</div>
</div>
<div id="result-grid"></div>
</div>
</div>
</main>
<section class="gallery-section">
<div class="gallery-header">
<div class="form-label">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M9 21V9"/></svg>
گالری و تاریخچه شما
</div>
<button id="clear-history-btn">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
<span>پاک کردن همه</span>
</button>
</div>
<div id="history-grid"></div>
</section>
</div>
<div id="lightbox">
<div id="lightbox-content">
<img id="lightbox-img" src="">
<button id="lightbox-close" class="lightbox-btn" title="بستن">&times;</button>
<button id="lightbox-download" title="دانلود تصویر" class="lightbox-btn">
<svg fill="white" viewBox="0 0 24 24"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg>
<div class="spinner"></div>
</button>
<button id="lightbox-next" title="بعدی" class="lightbox-btn">
<svg fill="white" viewBox="0 0 24 24" width="24" height="24"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6-6-6z"/></svg>
</button>
</div>
</div>
<div id="confirmation-modal">
<div class="modal-dialog">
<div class="modal-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg></div>
<h3>تایید حذف</h3>
<p id="modal-message-text">آیا از انجام این عمل مطمئن هستید؟</p>
<div class="modal-buttons">
<button id="modal-cancel-btn" class="modal-btn cancel-btn">انصراف</button>
<button id="modal-confirm-btn" class="modal-btn confirm-btn">بله، حذف کن</button>
</div>
</div>
</div>
<script>
// === START: بخش مدیریت کاربر و ارتباط با والد ===
let userSubscriptionStatus = 'free'; let userFingerprint = null; let countdownInterval = null; const PREMIUM_PAGE_ID = '1149636';
async function getBrowserFingerprint() { const components = [navigator.userAgent, navigator.language, screen.width + 'x' + screen.height, new Date().getTimezoneOffset()]; try { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx.fillText("a1b2c3d4e5f6g7h8i9j0", 2, 15); components.push(canvas.toDataURL()); } catch (e) { components.push("canvas-error"); } const fingerprintString = components.join('---'); let hash = 0; for (let i = 0; i < fingerprintString.length; i++) { hash = ((hash << 5) - hash) + fingerprintString.charCodeAt(i); hash |= 0; } return 'fp_' + Math.abs(hash).toString(16); }
function isUserPaid(userObject) { return userObject && userObject.isLogin && userObject.accessible_pages && (userObject.accessible_pages.includes(PREMIUM_PAGE_ID) || userObject.accessible_pages.includes(parseInt(PREMIUM_PAGE_ID))); }
function updateUIForSubscriptionStatus(status) { userSubscriptionStatus = status; const creditInfoDiv = document.getElementById('credit-info-section'); const upgradeBtn = document.getElementById('upgrade-button'); const subscriptionBadge = document.getElementById('subscription-status-badge'); if (status === 'paid') { subscriptionBadge.textContent = 'نسخه نامحدود'; subscriptionBadge.className = 'paid-badge'; creditInfoDiv.style.display = 'none'; upgradeBtn.style.display = 'none'; if(countdownInterval) clearInterval(countdownInterval); checkFormState(); } else { subscriptionBadge.textContent = 'نسخه رایگان'; subscriptionBadge.className = 'free-badge'; checkFreeUserCredit(); } subscriptionBadge.style.display = 'inline-block'; }
async function checkFreeUserCredit() { if (!userFingerprint) return; const creditInfoDiv = document.getElementById('credit-info-section'); const upgradeBtn = document.getElementById('upgrade-button'); const genBtn = document.getElementById('submit-btn'); try { const response = await fetch('/api/check-credit', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) }); const result = await response.json(); creditInfoDiv.style.display = 'block'; if (result.limit_reached) { upgradeBtn.style.display = 'block'; startCountdown(result.reset_timestamp); checkFormState(); } else { upgradeBtn.style.display = 'none'; if(countdownInterval) clearInterval(countdownInterval); creditInfoDiv.textContent = `شما ${result.credits_remaining} اعتبار ویرایش رایگان در این هفته دارید.`; checkFormState(); } } catch (error) { creditInfoDiv.textContent = "خطا در بررسی اعتبار."; genBtn.disabled = true; } }
function startCountdown(resetTimestamp) { if (countdownInterval) clearInterval(countdownInterval); const creditInfoDiv = document.getElementById('credit-info-section'); const updateTimer = () => { const timeLeft = Math.max(0, resetTimestamp - (Date.now() / 1000)); if (timeLeft === 0) { clearInterval(countdownInterval); creditInfoDiv.textContent = 'در حال بروزرسانی اعتبار...'; setTimeout(checkFreeUserCredit, 2000); return; } const d = Math.floor(timeLeft / 86400); const h = Math.floor((timeLeft % 86400) / 3600); const m = Math.floor((timeLeft % 3600) / 60); creditInfoDiv.textContent = `اعتبار شما تمام شده. زمان باقی‌مانده: ${d} روز و ${h} ساعت و ${m} دقیقه`; }; updateTimer(); countdownInterval = setInterval(updateTimer, 60000); }
window.addEventListener('message', (event) => { if (event.data && event.data.type === 'USER_DATA_RESPONSE') { if (event.data.error || !event.data.payload) { updateUIForSubscriptionStatus('free'); return; } try { const userObject = JSON.parse(event.data.payload); const status = isUserPaid(userObject) ? 'paid' : 'free'; updateUIForSubscriptionStatus(status); } catch (e) { updateUIForSubscriptionStatus('free'); } } });
document.getElementById('upgrade-button').addEventListener('click', () => { parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM' }, '*'); });
// === START: منطق اصلی برنامه ===
const API_URL = 'https://alfa-editor-worker.onrender.com/api/edit';
const uploadArea = document.getElementById('upload-area'); const fileInput = document.getElementById('file-input'); const previewImage = document.getElementById('preview-image-main'); const removeFileBtn = document.getElementById('remove-file-btn-main'); const promptInput = document.getElementById('prompt-input'); const submitBtn = document.getElementById('submit-btn'); const resultContainer = document.getElementById('result-container'); const resultGrid = document.getElementById('result-grid'); const errorMessage = document.getElementById('error-message'); const lightbox = document.getElementById('lightbox'); const lightboxImg = document.getElementById('lightbox-img'); const lightboxClose = document.getElementById('lightbox-close'); const lightboxDownload = document.getElementById('lightbox-download'); const lightboxNext = document.getElementById('lightbox-next'); const historyGrid = document.getElementById('history-grid'); const clearHistoryBtn = document.getElementById('clear-history-btn'); const confirmationModal = document.getElementById('confirmation-modal'); const modalMessageText = document.getElementById('modal-message-text'); const modalConfirmBtn = document.getElementById('modal-confirm-btn'); const modalCancelBtn = document.getElementById('modal-cancel-btn');
let uploadedFile = null; let currentLightboxUrl = null; let currentLightboxGroup = []; let currentLightboxIndex = 0;
// --- START: IndexedDB Handler ---
const dbHandler = {
db: null,
dbName: 'aiPhotoshopDB',
storeName: 'history',
initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, 1);
request.onerror = (event) => {
console.error("IndexedDB error:", event.target.error);
reject("Error opening DB");
};
request.onsuccess = (event) => {
this.db = event.target.result;
resolve();
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
const store = db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true });
store.createIndex('timestamp', 'timestamp', { unique: false });
};
});
},
add(item) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.add(item);
request.onsuccess = () => resolve();
request.onerror = (event) => reject(event.target.error);
});
},
getAll() {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readonly');
const store = transaction.objectStore(this.storeName);
const request = store.getAll();
request.onsuccess = () => {
// Sort by timestamp descending (newest first)
resolve(request.result.sort((a, b) => b.timestamp - a.timestamp));
};
request.onerror = (event) => reject(event.target.error);
});
},
delete(id) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.delete(id);
request.onsuccess = () => resolve();
request.onerror = (event) => reject(event.target.error);
});
},
clear() {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.clear();
request.onsuccess = () => resolve();
request.onerror = (event) => reject(event.target.error);
});
},
deleteOlderThan(timestamp) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const index = store.index('timestamp');
// Create a key range for all items with a timestamp less than the provided one
const keyRange = IDBKeyRange.upperBound(timestamp);
const request = index.openCursor(keyRange);
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
store.delete(cursor.primaryKey); // Delete the item
cursor.continue(); // Move to the next item
} else {
resolve(); // No more items to delete
}
};
request.onerror = (event) => reject(event.target.error);
});
}
};
// --- END: IndexedDB Handler ---
const convertToPNG = (file) => new Promise((resolve, reject) => { const image = new Image(); const reader = new FileReader(); image.onload = () => { const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); canvas.toBlob((blob) => { if (!blob) { reject(new Error('تبدیل به PNG ناموفق بود.')); return; } const originalName = file.name.substring(0, file.name.lastIndexOf('.')) || file.name; const pngFile = new File([blob], `${originalName}.png`, { type: 'image/png' }); resolve(pngFile); }, 'image/png', 1.0); }; image.onerror = () => reject(new Error('فایل تصویر قابل خواندن نیست.')); reader.onload = e => { image.src = e.target.result; }; reader.onerror = () => reject(new Error('خطا در خواندن فایل.')); reader.readAsDataURL(file); });
const handleFile = async (file) => { if (!file || !file.type.startsWith('image/')) { displayError('لطفا یک فایل تصویری معتبر انتخاب کنید.'); return; } let fileToProcess = file; if (file.type !== 'image/png' && file.type !== 'image/jpeg') { try { fileToProcess = await convertToPNG(file); } catch (error) { console.error('Image conversion failed:', error); displayError('خطا در تبدیل فرمت تصویر.'); resetUploader(); return; } } uploadedFile = fileToProcess; const reader = new FileReader(); reader.onload = (e) => { previewImage.src = e.target.result; }; reader.readAsDataURL(file); uploadArea.classList.add('has-file'); checkFormState(); clearResult(); };
const resetUploader = () => { uploadedFile = null; fileInput.value = ''; previewImage.src = ''; uploadArea.classList.remove('has-file'); checkFormState(); };
const checkFormState = () => { const isReady = uploadedFile && promptInput.value.trim() !== ''; if (userSubscriptionStatus === 'free' && document.getElementById('upgrade-button').style.display === 'block') { submitBtn.disabled = true; } else { submitBtn.disabled = !isReady; } };
const setLoading = (isLoading) => { const btnSpinner = submitBtn.querySelector('.spinner'); const btnText = document.getElementById('btn-text'); const btnIcon = submitBtn.querySelector('svg'); if (isLoading) { resultContainer.classList.remove('has-content'); resultContainer.classList.add('loading'); btnSpinner.style.display = 'inline-block'; btnIcon.style.display = 'none'; btnText.textContent = 'در حال پردازش...'; submitBtn.disabled = true; resultGrid.innerHTML = ''; errorMessage.style.display = 'none'; } else { resultContainer.classList.remove('loading'); btnSpinner.style.display = 'none'; btnIcon.style.display = 'inline-block'; btnText.textContent = 'ایجاد کن'; checkFormState(); } };
const displayResult = (imageUrls) => {
resultGrid.innerHTML = '';
imageUrls.forEach((url) => {
const img = document.createElement('img');
img.src = `/api/proxy?url=${encodeURIComponent(url)}`;
img.alt = 'تصویر ویرایش شده';
img.addEventListener('click', () => openLightbox(url, imageUrls));
resultGrid.appendChild(img);
});
resultContainer.classList.add('has-content');
};
const clearResult = () => { resultGrid.innerHTML = ''; errorMessage.style.display = 'none'; resultContainer.classList.remove('has-content'); };
const displayError = (message) => { errorMessage.textContent = message; errorMessage.style.display = 'block'; };
const openLightbox = (clickedUrl, urlGroup) => { currentLightboxGroup = urlGroup; currentLightboxIndex = urlGroup.indexOf(clickedUrl); updateLightboxImage(); lightboxNext.style.display = urlGroup.length > 1 ? 'flex' : 'none'; lightbox.classList.add('visible'); };
const closeLightbox = () => { lightbox.classList.remove('visible'); };
const updateLightboxImage = () => {
const newUrl = currentLightboxGroup[currentLightboxIndex];
lightboxImg.src = `/api/proxy?url=${encodeURIComponent(newUrl)}`;
currentLightboxUrl = newUrl;
};
const handleDownload = () => { if (!currentLightboxUrl) return; parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: currentLightboxUrl }, '*'); };
const addToHistory = async (item) => {
const newItem = { ...item, timestamp: Date.now() };
try {
await dbHandler.add(newItem);
// Limit history to 15 items by deleting the oldest if count exceeds 15
const history = await dbHandler.getAll();
if (history.length > 15) {
await dbHandler.delete(history[history.length - 1].id); // Oldest is last due to sorting
}
} catch (error) {
console.error("Failed to add to history:", error);
}
await renderHistory();
};
const showConfirmationModal = (message, onConfirm) => { modalMessageText.textContent = message; confirmationModal.classList.add('visible'); modalConfirmBtn.onclick = () => { onConfirm(); hideConfirmationModal(); }; modalCancelBtn.onclick = () => { hideConfirmationModal(); }; };
const hideConfirmationModal = () => { confirmationModal.classList.remove('visible'); };
const handleClearHistory = () => {
showConfirmationModal('آیا از پاک کردن تمام تاریخچه مطمئن هستید؟', async () => {
await dbHandler.clear();
await renderHistory();
});
};
const handleDeleteItem = (id) => {
showConfirmationModal('آیا از حذف این مورد مطمئن هستید؟', async () => {
await dbHandler.delete(id);
await renderHistory();
});
};
const renderHistory = async () => {
try {
const expirationTime = 23 * 60 * 60 * 1000; // 23 hours in milliseconds
const expirationTimestamp = Date.now() - expirationTime;
// Clean up old entries first
await dbHandler.deleteOlderThan(expirationTimestamp);
const history = await dbHandler.getAll();
historyGrid.innerHTML = '';
clearHistoryBtn.style.display = history.length > 0 ? 'flex' : 'none';
history.forEach((item) => {
const card = document.createElement('div'); card.className = 'history-item';
const deleteBtn = document.createElement('button'); deleteBtn.className = 'history-delete-btn'; deleteBtn.title = 'حذف'; deleteBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`;
// Pass the item's unique ID from the database
deleteBtn.onclick = () => handleDeleteItem(item.id);
card.appendChild(deleteBtn);
const imageGrid = document.createElement('div'); imageGrid.className = 'history-item-grid';
item.urls.forEach(url => {
const img = document.createElement('img');
img.src = `/api/proxy?url=${encodeURIComponent(url)}`;
img.alt = 'تصویر تاریخچه';
img.addEventListener('click', () => openLightbox(url, item.urls));
imageGrid.appendChild(img);
});
card.appendChild(imageGrid);
historyGrid.appendChild(card);
});
} catch (error) {
console.error("Could not render history:", error);
historyGrid.innerHTML = '<p style="color: var(--danger-color); grid-column: 1 / -1; text-align: center;">خطا در بارگذاری تاریخچه.</p>';
}
};
const proceedWithImageGeneration = async () => {
if (submitBtn.disabled) return; setLoading(true);
const formData = new FormData(); formData.append('image', uploadedFile); formData.append('prompt', promptInput.value.trim());
try {
const response = await fetch(API_URL, { method: 'POST', body: formData });
if (!response.ok) { const errorData = await response.json().catch(() => ({ error: `خطای سرور: ${response.statusText}` })); throw new Error(errorData.error || `یک خطای ناشناخته رخ داد.`); }
const result = await response.json();
if (result.image_urls && Array.isArray(result.image_urls) && result.image_urls.length > 0) {
if (userSubscriptionStatus === 'free') {
await fetch('/api/use-credit', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) });
checkFreeUserCredit();
}
displayResult(result.image_urls);
await addToHistory({ prompt: promptInput.value.trim(), urls: result.image_urls });
} else { throw new Error('پاسخ معتبری از سرور دریافت نشد.'); }
} catch (error) { displayError(error.message); } finally { setLoading(false); }
};
submitBtn.addEventListener('click', async () => {
if (userSubscriptionStatus === 'paid') {
await proceedWithImageGeneration();
} else {
try {
const response = await fetch('/api/check-credit', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) });
const result = await response.json();
if (result.limit_reached) { updateUIForSubscriptionStatus('free'); return; }
await proceedWithImageGeneration();
} catch (err) { displayError(`خطا در سیستم اعتبار: ${err.message}`); }
}
});
// Event Listeners
document.addEventListener('DOMContentLoaded', async () => {
try {
await dbHandler.initDB();
await renderHistory();
} catch (error) {
console.error("Failed to initialize the application:", error);
displayError("خطا در راه اندازی اولیه برنامه. لطفا صفحه را رفرش کنید.");
}
userFingerprint = await getBrowserFingerprint();
parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*');
checkFormState();
});
removeFileBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); resetUploader(); });
fileInput.addEventListener('change', (e) => handleFile(e.target.files[0]));
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(e => { uploadArea.addEventListener(e, p => { p.preventDefault(); p.stopPropagation(); }); });
['dragenter', 'dragover'].forEach(e => { uploadArea.addEventListener(e, () => { if (!uploadArea.classList.contains('has-file')) uploadArea.classList.add('drag-over'); }); });
['dragleave', 'drop'].forEach(e => { uploadArea.addEventListener(e, () => uploadArea.classList.remove('drag-over')); });
uploadArea.addEventListener('drop', e => { if (!uploadArea.classList.contains('has-file')) handleFile(e.dataTransfer.files[0]); });
promptInput.addEventListener('input', checkFormState);
lightboxClose.addEventListener('click', closeLightbox);
lightbox.addEventListener('click', (e) => { if (e.target === lightbox) closeLightbox(); });
lightboxDownload.addEventListener('click', handleDownload);
lightboxNext.addEventListener('click', () => { currentLightboxIndex = (currentLightboxIndex + 1) % currentLightboxGroup.length; updateLightboxImage(); });
clearHistoryBtn.addEventListener('click', handleClearHistory);
</script>
<script>
// --- Header Animation Script (Unchanged) ---
document.addEventListener('DOMContentLoaded', () => { const canvas = document.getElementById('neural-network-canvas'); if (!canvas) return; const header = canvas.parentElement; const ctx = canvas.getContext('2d'); let particles = []; const particleCount = 20; const maxDistance = 100; const computedStyles = getComputedStyle(document.documentElement); const particleColor = computedStyles.getPropertyValue('--accent-primary').trim(); const lineColor = computedStyles.getPropertyValue('--text-tertiary').trim(); function resizeCanvas() { canvas.width = header.clientWidth; canvas.height = header.clientHeight; init(); } class Particle { constructor() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.vx = (Math.random() - 0.5) * 0.3; this.vy = (Math.random() - 0.5) * 0.3; this.radius = 1.2; } update() { this.x += this.vx; this.y += this.vy; if (this.x < 0 || this.x > canvas.width) this.vx *= -1; if (this.y < 0 || this.y > canvas.height) this.vy *= -1; } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = particleColor; ctx.fill(); } } function init() { particles = []; for (let i = 0; i < particleCount; i++) { particles.push(new Particle()); } } function connectParticles() { for (let i = 0; i < particles.length; i++) { for (let j = i + 1; j < particles.length; j++) { const dx = particles[i].x - particles[j].x; const dy = particles[i].y - particles[j].y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < maxDistance) { ctx.beginPath(); ctx.moveTo(particles[i].x, particles[i].y); ctx.lineTo(particles[j].x, particles[j].y); ctx.strokeStyle = lineColor; ctx.lineWidth = 0.2; ctx.globalAlpha = 1 - distance / maxDistance; ctx.stroke(); } } } ctx.globalAlpha = 1; } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(particle => { particle.update(); particle.draw(); }); connectParticles(); requestAnimationFrame(animate); } window.addEventListener('resize', resizeCanvas); resizeCanvas(); animate(); });
</script>
</body>
</html>