// ─── Resizable panel drag logic ─────────────────────────────────────────────── (function() { const handle = document.getElementById('resize-handle'); const viewer = document.getElementById('viewer-section'); const library = document.getElementById('library-section'); const workspace = document.querySelector('.workspace'); let dragging = false, startY = 0, startVH = 0; handle.addEventListener('mousedown', (e) => { dragging = true; startY = e.clientY; startVH = viewer.getBoundingClientRect().height; document.body.style.cursor = 'row-resize'; document.body.style.userSelect = 'none'; handle.querySelector('div').style.background = 'var(--accent)'; e.preventDefault(); }); document.addEventListener('mousemove', (e) => { if (!dragging) return; const wsH = workspace.getBoundingClientRect().height; const delta = e.clientY - startY; let newVH = startVH + delta; // Clamp: viewer min 150px, library min 100px newVH = Math.max(150, Math.min(wsH - 100 - 5, newVH)); viewer.style.flex = 'none'; viewer.style.height = newVH + 'px'; library.style.flex = '1'; }); document.addEventListener('mouseup', () => { if (dragging) { dragging = false; document.body.style.cursor = ''; document.body.style.userSelect = ''; handle.querySelector('div').style.background = 'var(--border)'; } }); // Hover highlight handle.addEventListener('mouseenter', () => { handle.querySelector('div').style.background = 'var(--text-dim)'; }); handle.addEventListener('mouseleave', () => { if (!dragging) handle.querySelector('div').style.background = 'var(--border)'; }); })(); // ────────────────────────────────────────────────────────────────────────────── // 动态获取当前访问的域名或 IP,自动对齐 3000 端口 const BASE = `http://${window.location.hostname}:3000`; function _t(k) { return typeof window.t === 'function' ? window.t(k) : k; } let currentMode = 'image'; let pollInterval = null; let availableModels = []; let availableLoras = []; // 建议增加一个简单的调试日志,方便在控制台确认地址是否正确 console.log("Connecting to Backend API at:", BASE); // 模型扫描功能 async function scanModels() { try { const url = `${BASE}/api/models`; console.log("Scanning models from:", url); const res = await fetch(url); const data = await res.json().catch(() => ({})); console.log("Models response:", res.status, data); if (!res.ok) { const msg = data.message || data.error || res.statusText; addLog(`❌ 模型扫描失败 (${res.status}): ${msg}`); availableModels = []; updateModelDropdown(); updateBatchModelDropdown(); return; } availableModels = data.models || []; updateModelDropdown(); updateBatchModelDropdown(); if (availableModels.length > 0) { addLog(`📂 已扫描到 ${availableModels.length} 个模型: ${availableModels.map(m => m.name).join(', ')}`); } } catch (e) { console.log("Model scan error:", e); addLog(`❌ 模型扫描异常: ${e.message || e}`); } } function updateModelDropdown() { const select = document.getElementById('vid-model'); if (!select) return; select.innerHTML = ''; availableModels.forEach(model => { const opt = document.createElement('option'); opt.value = model.path; opt.textContent = model.name; select.appendChild(opt); }); } // LoRA 扫描功能 async function scanLoras() { try { const url = `${BASE}/api/loras`; console.log("Scanning LoRA from:", url); const res = await fetch(url); const data = await res.json().catch(() => ({})); console.log("LoRA response:", res.status, data); if (!res.ok) { const msg = data.message || data.error || res.statusText; addLog(`❌ LoRA 扫描失败 (${res.status}): ${msg}`); availableLoras = []; updateLoraDropdown(); updateBatchLoraDropdown(); return; } availableLoras = data.loras || []; updateLoraDropdown(); updateBatchLoraDropdown(); if (data.loras_dir) { const hintEl = document.getElementById('lora-placement-hint'); if (hintEl) { const tpl = _t('loraPlacementHintWithDir'); hintEl.innerHTML = tpl.replace( '{dir}', escapeHtmlAttr(data.models_dir || data.loras_dir) ); } } if (availableLoras.length > 0) { addLog(`📂 已扫描到 ${availableLoras.length} 个 LoRA: ${availableLoras.map(l => l.name).join(', ')}`); } } catch (e) { console.log("LoRA scan error:", e); addLog(`❌ LoRA 扫描异常: ${e.message || e}`); } } function updateLoraDropdown() { const select = document.getElementById('vid-lora'); if (!select) return; select.innerHTML = ''; availableLoras.forEach(lora => { const opt = document.createElement('option'); opt.value = lora.path; opt.textContent = lora.name; select.appendChild(opt); }); } function updateLoraStrength() { const select = document.getElementById('vid-lora'); const container = document.getElementById('lora-strength-container'); if (select && container) { container.style.display = select.value ? 'flex' : 'none'; } } // 更新批量模式的模型和LoRA下拉框 function updateBatchModelDropdown() { const select = document.getElementById('batch-model'); if (!select) return; select.innerHTML = ''; availableModels.forEach(model => { const opt = document.createElement('option'); opt.value = model.path; opt.textContent = model.name; select.appendChild(opt); }); } function updateBatchLoraDropdown() { const select = document.getElementById('batch-lora'); if (!select) return; select.innerHTML = ''; availableLoras.forEach(lora => { const opt = document.createElement('option'); opt.value = lora.path; opt.textContent = lora.name; select.appendChild(opt); }); } // 页面加载时更新批量模式的下拉框 function initBatchDropdowns() { updateBatchModelDropdown(); updateBatchLoraDropdown(); } // 已移除:模型/LoRA 目录自定义与浏览(保持后端默认路径扫描) // 页面加载时扫描模型和LoRA(使用后端默认目录规则) (function() { ['vid-quality', 'batch-quality'].forEach((id) => { const sel = document.getElementById(id); if (sel && sel.value === '544') sel.value = '540'; }); setTimeout(() => { scanModels(); scanLoras(); initBatchDropdowns(); }, 1500); })(); // 分辨率自动计算逻辑 function updateResPreview() { const q = document.getElementById('vid-quality').value; // "1080", "720", "540" const r = document.getElementById('vid-ratio').value; // 核心修复:后端解析器期待 "1080p", "720p", "540p" 这种标签格式 let resLabel = q === "1080" ? "1080p" : q === "720" ? "720p" : "540p"; /* 与后端一致:宽高均为 64 的倍数(LTX 内核要求) */ let resDisplay; if (r === "16:9") { resDisplay = q === "1080" ? "1920x1088" : q === "720" ? "1280x704" : "1024x576"; } else { resDisplay = q === "1080" ? "1088x1920" : q === "720" ? "704x1280" : "576x1024"; } document.getElementById('res-preview').innerText = `${_t('resPreviewPrefix')}: ${resLabel} (${resDisplay})`; return resLabel; } // 图片分辨率预览 function updateImgResPreview() { const w = document.getElementById('img-w').value; const h = document.getElementById('img-h').value; document.getElementById('img-res-preview').innerText = `${_t('resPreviewPrefix')}: ${w}x${h}`; } // 批量模式分辨率预览 function updateBatchResPreview() { const q = document.getElementById('batch-quality').value; const r = document.getElementById('batch-ratio').value; let resLabel = q === "1080" ? "1080p" : q === "720" ? "720p" : "540p"; let resDisplay; if (r === "16:9") { resDisplay = q === "1080" ? "1920x1088" : q === "720" ? "1280x704" : "1024x576"; } else { resDisplay = q === "1080" ? "1088x1920" : q === "720" ? "704x1280" : "576x1024"; } document.getElementById('batch-res-preview').innerText = `${_t('resPreviewPrefix')}: ${resLabel} (${resDisplay})`; return resLabel; } // 批量模式 LoRA 强度切换 function updateBatchLoraStrength() { const select = document.getElementById('batch-lora'); const container = document.getElementById('batch-lora-strength-container'); if (select && container) { container.style.display = select.value ? 'flex' : 'none'; } } // 切换图片预设分辨率 function applyImgPreset(val) { if (val === "custom") { document.getElementById('img-custom-res').style.display = 'flex'; } else { const [w, h] = val.split('x'); document.getElementById('img-w').value = w; document.getElementById('img-h').value = h; updateImgResPreview(); // 隐藏自定义区域或保持显示供微调 // document.getElementById('img-custom-res').style.display = 'none'; } } // 处理帧图片上传 async function handleFrameUpload(file, frameType) { if (!file) return; const preview = document.getElementById(`${frameType}-frame-preview`); const placeholder = document.getElementById(`${frameType}-frame-placeholder`); const clearOverlay = document.getElementById(`clear-${frameType}-frame-overlay`); const previewReader = new FileReader(); previewReader.onload = (e) => { preview.src = e.target.result; preview.style.display = 'block'; placeholder.style.display = 'none'; clearOverlay.style.display = 'flex'; }; previewReader.readAsDataURL(file); const reader = new FileReader(); reader.onload = async (e) => { const b64Data = e.target.result; addLog(`正在上传 ${frameType === 'start' ? '起始帧' : '结束帧'}: ${file.name}...`); try { const res = await fetch(`${BASE}/api/system/upload-image`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: b64Data, filename: file.name }) }); const data = await res.json(); if (res.ok && data.path) { document.getElementById(`${frameType}-frame-path`).value = data.path; addLog(`✅ ${frameType === 'start' ? '起始帧' : '结束帧'}上传成功`); } else { throw new Error(data.error || data.detail || "上传失败"); } } catch (e) { addLog(`❌ 帧图片上传失败: ${e.message}`); } }; reader.readAsDataURL(file); } function clearFrame(frameType) { document.getElementById(`${frameType}-frame-input`).value = ""; document.getElementById(`${frameType}-frame-path`).value = ""; document.getElementById(`${frameType}-frame-preview`).style.display = 'none'; document.getElementById(`${frameType}-frame-preview`).src = ""; document.getElementById(`${frameType}-frame-placeholder`).style.display = 'block'; document.getElementById(`clear-${frameType}-frame-overlay`).style.display = 'none'; addLog(`🧹 已清除${frameType === 'start' ? '起始帧' : '结束帧'}`); } // 处理图片上传 async function handleImageUpload(file) { if (!file) return; // 预览图片 const preview = document.getElementById('upload-preview'); const placeholder = document.getElementById('upload-placeholder'); const clearOverlay = document.getElementById('clear-img-overlay'); const previewReader = new FileReader(); preview.onload = () => { preview.style.display = 'block'; placeholder.style.display = 'none'; clearOverlay.style.display = 'flex'; }; previewReader.onload = (e) => preview.src = e.target.result; previewReader.readAsDataURL(file); // 使用 FileReader 转换为 Base64,绕过后端缺失 python-multipart 的问题 const reader = new FileReader(); reader.onload = async (e) => { const b64Data = e.target.result; addLog(`正在上传参考图: ${file.name}...`); try { const res = await fetch(`${BASE}/api/system/upload-image`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: b64Data, filename: file.name }) }); const data = await res.json(); if (res.ok && data.path) { document.getElementById('uploaded-img-path').value = data.path; addLog(`✅ 参考图上传成功: ${file.name}`); } else { const errMsg = data.error || data.detail || "上传失败"; throw new Error(typeof errMsg === 'string' ? errMsg : JSON.stringify(errMsg)); } } catch (e) { addLog(`❌ 图片上传失败: ${e.message}`); } }; reader.onerror = () => addLog("❌ 读取本地文件失败"); reader.readAsDataURL(file); } function clearUploadedImage() { document.getElementById('vid-image-input').value = ""; document.getElementById('uploaded-img-path').value = ""; document.getElementById('upload-preview').style.display = 'none'; document.getElementById('upload-preview').src = ""; document.getElementById('upload-placeholder').style.display = 'block'; document.getElementById('clear-img-overlay').style.display = 'none'; addLog("🧹 已清除参考图"); } // 处理音频上传 async function handleAudioUpload(file) { if (!file) return; const placeholder = document.getElementById('audio-upload-placeholder'); const statusDiv = document.getElementById('audio-upload-status'); const filenameStatus = document.getElementById('audio-filename-status'); const clearOverlay = document.getElementById('clear-audio-overlay'); placeholder.style.display = 'none'; filenameStatus.innerText = file.name; statusDiv.style.display = 'block'; clearOverlay.style.display = 'flex'; const reader = new FileReader(); reader.onload = async (e) => { const b64Data = e.target.result; addLog(`正在上传音频: ${file.name}...`); try { // 复用图片上传接口,后端已支持任意文件类型 const res = await fetch(`${BASE}/api/system/upload-image`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: b64Data, filename: file.name }) }); const data = await res.json(); if (res.ok && data.path) { document.getElementById('uploaded-audio-path').value = data.path; addLog(`✅ 音频上传成功: ${file.name}`); } else { const errMsg = data.error || data.detail || "上传失败"; throw new Error(typeof errMsg === 'string' ? errMsg : JSON.stringify(errMsg)); } } catch (e) { addLog(`❌ 音频上传失败: ${e.message}`); } }; reader.onerror = () => addLog("❌ 读取本地音频文件失败"); reader.readAsDataURL(file); } function clearUploadedAudio() { document.getElementById('vid-audio-input').value = ""; document.getElementById('uploaded-audio-path').value = ""; document.getElementById('audio-upload-placeholder').style.display = 'block'; document.getElementById('audio-upload-status').style.display = 'none'; document.getElementById('clear-audio-overlay').style.display = 'none'; addLog("🧹 已清除音频文件"); } // 处理超分视频上传 async function handleUpscaleVideoUpload(file) { if (!file) return; const placeholder = document.getElementById('upscale-placeholder'); const statusDiv = document.getElementById('upscale-status'); const filenameStatus = document.getElementById('upscale-filename'); const clearOverlay = document.getElementById('clear-upscale-overlay'); filenameStatus.innerText = file.name; placeholder.style.display = 'none'; statusDiv.style.display = 'block'; clearOverlay.style.display = 'flex'; const reader = new FileReader(); reader.onload = async (e) => { const b64Data = e.target.result; addLog(`正在上传待超分视频: ${file.name}...`); try { const res = await fetch(`${BASE}/api/system/upload-image`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: b64Data, filename: file.name }) }); const data = await res.json(); if (res.ok && data.path) { document.getElementById('upscale-video-path').value = data.path; addLog(`✅ 视频上传成功`); } else { throw new Error(data.error || "上传失败"); } } catch (e) { addLog(`❌ 视频上传失败: ${e.message}`); } }; reader.readAsDataURL(file); } function clearUpscaleVideo() { document.getElementById('upscale-video-input').value = ""; document.getElementById('upscale-video-path').value = ""; document.getElementById('upscale-placeholder').style.display = 'block'; document.getElementById('upscale-status').style.display = 'none'; document.getElementById('clear-upscale-overlay').style.display = 'none'; addLog("🧹 已清除待超分视频"); } // 初始化拖拽上传逻辑 function initDragAndDrop() { const audioDropZone = document.getElementById('audio-drop-zone'); const startFrameDropZone = document.getElementById('start-frame-drop-zone'); const endFrameDropZone = document.getElementById('end-frame-drop-zone'); const upscaleDropZone = document.getElementById('upscale-drop-zone'); const batchImagesDropZone = document.getElementById('batch-images-drop-zone'); const zones = [audioDropZone, startFrameDropZone, endFrameDropZone, upscaleDropZone, batchImagesDropZone]; ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { zones.forEach(zone => { if (!zone) return; zone.addEventListener(eventName, (e) => { e.preventDefault(); e.stopPropagation(); }, false); }); }); ['dragenter', 'dragover'].forEach(eventName => { zones.forEach(zone => { if (!zone) return; zone.addEventListener(eventName, () => zone.classList.add('dragover'), false); }); }); ['dragleave', 'drop'].forEach(eventName => { zones.forEach(zone => { if (!zone) return; zone.addEventListener(eventName, () => zone.classList.remove('dragover'), false); }); }); audioDropZone.addEventListener('drop', (e) => { const file = e.dataTransfer.files[0]; if (file && file.type.startsWith('audio/')) handleAudioUpload(file); }, false); startFrameDropZone.addEventListener('drop', (e) => { const file = e.dataTransfer.files[0]; if (file && file.type.startsWith('image/')) handleFrameUpload(file, 'start'); }, false); endFrameDropZone.addEventListener('drop', (e) => { const file = e.dataTransfer.files[0]; if (file && file.type.startsWith('image/')) handleFrameUpload(file, 'end'); }, false); upscaleDropZone.addEventListener('drop', (e) => { const file = e.dataTransfer.files[0]; if (file && file.type.startsWith('video/')) handleUpscaleVideoUpload(file); }, false); // 批量图片拖拽上传 if (batchImagesDropZone) { batchImagesDropZone.addEventListener('drop', (e) => { e.preventDefault(); e.stopPropagation(); batchImagesDropZone.classList.remove('dragover'); const files = Array.from(e.dataTransfer.files).filter(f => f.type.startsWith('image/')); if (files.length > 0) handleBatchImagesUpload(files); }, false); } } // 批量图片上传处理 let batchImages = []; /** 单次多关键帧:按 path 记引导强度;按段索引 0..n-2 记「上一张→本张」间隔秒数 */ const batchKfStrengthByPath = {}; const batchKfSegDurByIndex = {}; function escapeHtmlAttr(s) { return String(s) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/ { if (!img.path) return; const sEl = document.getElementById(`batch-kf-strength-${i}`); if (sEl) batchKfStrengthByPath[img.path] = sEl.value.trim(); }); const n = batchImages.length; for (let j = 0; j < n - 1; j++) { const el = document.getElementById(`batch-kf-seg-dur-${j}`); if (el) batchKfSegDurByIndex[j] = el.value.trim(); } } /** 读取间隔(秒),非法则回退为 minSeg */ function readBatchKfSegmentSeconds(n, minSeg) { const seg = []; for (let j = 0; j < n - 1; j++) { let v = parseFloat(document.getElementById(`batch-kf-seg-dur-${j}`)?.value); if (!Number.isFinite(v) || v < minSeg) v = minSeg; seg.push(v); } return seg; } function updateBatchKfTimelineDerivedUI() { if (!batchWorkflowIsSingle() || batchImages.length < 2) return; const n = batchImages.length; const minSeg = 0.1; const seg = readBatchKfSegmentSeconds(n, minSeg); let t = 0; for (let i = 0; i < n; i++) { const label = document.getElementById(`batch-kf-anchor-label-${i}`); if (!label) continue; if (i === 0) { label.textContent = `0.0 s · ${_t('batchAnchorStart')}`; } else { t += seg[i - 1]; label.textContent = i === n - 1 ? `${t.toFixed(1)} s · ${_t('batchAnchorEnd')}` : `${t.toFixed(1)} s`; } } const totalEl = document.getElementById('batch-kf-total-seconds'); if (totalEl) { const sum = seg.reduce((a, b) => a + b, 0); totalEl.textContent = sum.toFixed(1); } } async function handleBatchImagesUpload(files, append = true) { if (!files || files.length === 0) return; addLog(`正在上传 ${files.length} 张图片...`); for (let i = 0; i < files.length; i++) { const file = files[i]; const reader = new FileReader(); const imgData = await new Promise((resolve) => { reader.onload = async (e) => { const b64Data = e.target.result; try { const res = await fetch(`${BASE}/api/system/upload-image`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: b64Data, filename: file.name }) }); const data = await res.json(); if (res.ok && data.path) { resolve({ name: file.name, path: data.path, preview: e.target.result }); } else { resolve(null); } } catch (e) { resolve(null); } }; reader.readAsDataURL(file); }); if (imgData) { batchImages.push(imgData); addLog(`✅ 图片 ${i + 1}/${files.length} 上传成功: ${file.name}`); } } renderBatchImages(); updateBatchSegments(); } async function handleBatchBackgroundAudioUpload(file) { if (!file) return; const ph = document.getElementById('batch-audio-placeholder'); const st = document.getElementById('batch-audio-status'); const overlay = document.getElementById('clear-batch-audio-overlay'); const reader = new FileReader(); reader.onload = async (e) => { const b64Data = e.target.result; addLog(`正在上传成片配乐: ${file.name}...`); try { const res = await fetch(`${BASE}/api/system/upload-image`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: b64Data, filename: file.name }) }); const data = await res.json(); if (res.ok && data.path) { const hid = document.getElementById('batch-background-audio-path'); if (hid) hid.value = data.path; if (ph) ph.style.display = 'none'; if (st) { st.style.display = 'block'; st.textContent = '✓ ' + file.name; } if (overlay) overlay.style.display = 'flex'; addLog('✅ 成片配乐已上传(将覆盖各片段自带音轨)'); } else { addLog(`❌ 配乐上传失败: ${data.error || '未知错误'}`); } } catch (err) { addLog(`❌ 配乐上传失败: ${err.message}`); } }; reader.onerror = () => addLog('❌ 读取音频文件失败'); reader.readAsDataURL(file); } function clearBatchBackgroundAudio() { const hid = document.getElementById('batch-background-audio-path'); const inp = document.getElementById('batch-audio-input'); if (hid) hid.value = ''; if (inp) inp.value = ''; const ph = document.getElementById('batch-audio-placeholder'); const st = document.getElementById('batch-audio-status'); const overlay = document.getElementById('clear-batch-audio-overlay'); if (ph) ph.style.display = 'block'; if (st) { st.style.display = 'none'; st.textContent = ''; } if (overlay) overlay.style.display = 'none'; addLog('🧹 已清除成片配乐'); } function syncBatchDropZoneChrome() { const dropZone = document.getElementById('batch-images-drop-zone'); const placeholder = document.getElementById('batch-images-placeholder'); const stripWrap = document.getElementById('batch-thumb-strip-wrap'); if (batchImages.length === 0) { if (dropZone) { dropZone.classList.remove('has-images'); const mini = dropZone.querySelector('.upload-placeholder-mini'); if (mini) mini.remove(); } if (placeholder) placeholder.style.display = 'block'; if (stripWrap) stripWrap.style.display = 'none'; return; } if (placeholder) placeholder.style.display = 'none'; if (dropZone) dropZone.classList.add('has-images'); if (stripWrap) stripWrap.style.display = 'block'; if (dropZone && !dropZone.querySelector('.upload-placeholder-mini')) { const mini = document.createElement('div'); mini.className = 'upload-placeholder-mini'; mini.innerHTML = '' + _t('batchAddMore') + ''; dropZone.appendChild(mini); } } let batchDragPlaceholderEl = null; let batchPointerState = null; let batchPendingPhX = null; let batchPhMoveRaf = null; function batchRemoveFloatingGhost() { document.querySelectorAll('.batch-thumb-floating-ghost').forEach((n) => n.remove()); } function batchCancelPhMoveRaf() { if (batchPhMoveRaf != null) { cancelAnimationFrame(batchPhMoveRaf); batchPhMoveRaf = null; } batchPendingPhX = null; } function batchEnsurePlaceholder() { if (batchDragPlaceholderEl && batchDragPlaceholderEl.isConnected) return batchDragPlaceholderEl; const el = document.createElement('div'); el.className = 'batch-thumb-drop-slot'; el.setAttribute('aria-hidden', 'true'); batchDragPlaceholderEl = el; return el; } function batchRemovePlaceholder() { if (batchDragPlaceholderEl && batchDragPlaceholderEl.parentNode) { batchDragPlaceholderEl.parentNode.removeChild(batchDragPlaceholderEl); } } function batchComputeInsertIndex(container, placeholder) { let t = 0; for (const child of container.children) { if (child === placeholder) return t; if (child.classList && child.classList.contains('batch-image-wrapper')) { if (!child.classList.contains('batch-thumb--source')) t++; } } return t; } function batchMovePlaceholderFromPoint(container, clientX) { const ph = batchEnsurePlaceholder(); const wrappers = [...container.querySelectorAll('.batch-image-wrapper')]; let insertBefore = null; for (const w of wrappers) { if (w.classList.contains('batch-thumb--source')) continue; const r = w.getBoundingClientRect(); if (clientX < r.left + r.width / 2) { insertBefore = w; break; } } if (insertBefore === null) { const vis = wrappers.filter((w) => !w.classList.contains('batch-thumb--source')); const last = vis[vis.length - 1]; if (last) { if (last.nextSibling) { container.insertBefore(ph, last.nextSibling); } else { container.appendChild(ph); } } else { container.appendChild(ph); } } else { container.insertBefore(ph, insertBefore); } } function batchFlushPlaceholderMove() { batchPhMoveRaf = null; if (!batchPointerState || batchPendingPhX == null) return; batchMovePlaceholderFromPoint(batchPointerState.container, batchPendingPhX); } function handleBatchPointerMove(e) { if (!batchPointerState) return; e.preventDefault(); const st = batchPointerState; st.ghostTX = e.clientX - st.offsetX; st.ghostTY = e.clientY - st.offsetY; batchPendingPhX = e.clientX; if (batchPhMoveRaf == null) { batchPhMoveRaf = requestAnimationFrame(batchFlushPlaceholderMove); } } function batchGhostFrame() { const st = batchPointerState; if (!st || !st.ghostEl || !st.ghostEl.isConnected) { return; } const t = 0.42; st.ghostCX += (st.ghostTX - st.ghostCX) * t; st.ghostCY += (st.ghostTY - st.ghostCY) * t; st.ghostEl.style.transform = `translate3d(${st.ghostCX}px,${st.ghostCY}px,0) scale(1.06) rotate(-1deg)`; st.ghostRaf = requestAnimationFrame(batchGhostFrame); } function batchStartGhostLoop() { const st = batchPointerState; if (!st || !st.ghostEl) return; if (st.ghostRaf != null) cancelAnimationFrame(st.ghostRaf); st.ghostRaf = requestAnimationFrame(batchGhostFrame); } function batchEndPointerDrag(e) { if (!batchPointerState) return; if (e.pointerId !== batchPointerState.pointerId) return; const st = batchPointerState; batchCancelPhMoveRaf(); if (st.ghostRaf != null) { cancelAnimationFrame(st.ghostRaf); st.ghostRaf = null; } if (st.ghostEl && st.ghostEl.parentNode) { st.ghostEl.remove(); } batchPointerState = null; document.removeEventListener('pointermove', handleBatchPointerMove); document.removeEventListener('pointerup', batchEndPointerDrag); document.removeEventListener('pointercancel', batchEndPointerDrag); try { if (st.wrapperEl) st.wrapperEl.releasePointerCapture(st.pointerId); } catch (_) {} const { fromIndex, container, wrapperEl } = st; container.classList.remove('is-batch-settling'); if (!batchDragPlaceholderEl || !batchDragPlaceholderEl.parentNode) { if (wrapperEl) wrapperEl.classList.remove('batch-thumb--source'); renderBatchImages(); updateBatchSegments(); return; } const to = batchComputeInsertIndex(container, batchDragPlaceholderEl); batchRemovePlaceholder(); if (wrapperEl) wrapperEl.classList.remove('batch-thumb--source'); if (fromIndex !== to && fromIndex >= 0 && to >= 0) { const [item] = batchImages.splice(fromIndex, 1); batchImages.splice(to, 0, item); updateBatchSegments(); } renderBatchImages(); } function handleBatchPointerDown(e) { if (batchPointerState) return; if (e.button !== 0) return; if (e.target.closest && e.target.closest('.batch-thumb-remove')) return; const wrapper = e.currentTarget; const container = document.getElementById('batch-images-container'); if (!container) return; e.preventDefault(); e.stopPropagation(); const fromIndex = parseInt(wrapper.dataset.index, 10); if (Number.isNaN(fromIndex)) return; const rect = wrapper.getBoundingClientRect(); const offsetX = e.clientX - rect.left; const offsetY = e.clientY - rect.top; const startLeft = rect.left; const startTop = rect.top; const ghost = document.createElement('div'); ghost.className = 'batch-thumb-floating-ghost'; const gImg = document.createElement('img'); const srcImg = wrapper.querySelector('img'); gImg.src = srcImg ? srcImg.src : ''; gImg.alt = ''; ghost.appendChild(gImg); document.body.appendChild(ghost); batchPointerState = { fromIndex, pointerId: e.pointerId, wrapperEl: wrapper, container, ghostEl: ghost, offsetX, offsetY, ghostTX: e.clientX - offsetX, ghostTY: e.clientY - offsetY, ghostCX: startLeft, ghostCY: startTop, ghostRaf: null }; ghost.style.transform = `translate3d(${startLeft}px,${startTop}px,0) scale(1.06) rotate(-1deg)`; container.classList.add('is-batch-settling'); wrapper.classList.add('batch-thumb--source'); const ph = batchEnsurePlaceholder(); container.insertBefore(ph, wrapper.nextSibling); /* 不在 pointerdown 立刻重算槽位;双 rAF 后再恢复邻居 transition,保证先完成本帧布局再动画 */ requestAnimationFrame(() => { requestAnimationFrame(() => { container.classList.remove('is-batch-settling'); }); }); batchStartGhostLoop(); document.addEventListener('pointermove', handleBatchPointerMove, { passive: false }); document.addEventListener('pointerup', batchEndPointerDrag); document.addEventListener('pointercancel', batchEndPointerDrag); try { wrapper.setPointerCapture(e.pointerId); } catch (_) {} } function removeBatchImage(index) { if (index < 0 || index >= batchImages.length) return; batchImages.splice(index, 1); renderBatchImages(); updateBatchSegments(); } // 横向缩略图:Pointer 拖动排序(避免 HTML5 DnD 在 WebView/部分浏览器失效) function renderBatchImages() { const container = document.getElementById('batch-images-container'); if (!container) return; syncBatchDropZoneChrome(); batchRemovePlaceholder(); batchCancelPhMoveRaf(); batchRemoveFloatingGhost(); batchPointerState = null; container.classList.remove('is-batch-settling'); container.innerHTML = ''; batchImages.forEach((img, index) => { const wrapper = document.createElement('div'); wrapper.className = 'batch-image-wrapper'; wrapper.dataset.index = String(index); wrapper.title = _t('batchThumbDrag'); const imgWrap = document.createElement('div'); imgWrap.className = 'batch-thumb-img-wrap'; const im = document.createElement('img'); im.className = 'batch-thumb-img'; im.src = img.preview; im.alt = img.name || ''; im.draggable = false; imgWrap.appendChild(im); const del = document.createElement('button'); del.type = 'button'; del.className = 'batch-thumb-remove'; del.title = _t('batchThumbRemove'); del.setAttribute('aria-label', _t('batchThumbRemove')); del.textContent = '×'; del.addEventListener('pointerdown', (ev) => ev.stopPropagation()); del.addEventListener('click', (ev) => { ev.stopPropagation(); removeBatchImage(index); }); wrapper.appendChild(imgWrap); wrapper.appendChild(del); wrapper.addEventListener('pointerdown', handleBatchPointerDown); container.appendChild(wrapper); }); } function batchWorkflowIsSingle() { const r = document.querySelector('input[name="batch-workflow"]:checked'); return !!(r && r.value === 'single'); } function onBatchWorkflowChange() { updateBatchSegments(); } // 更新片段设置 UI(分段模式)或单次多关键帧设置 function updateBatchSegments() { const container = document.getElementById('batch-segments-container'); if (!container) return; if (batchImages.length < 2) { container.innerHTML = '
${escapeHtmlAttr(_t('batchPanelHint'))}