// ==UserScript== // @name LibTV 创作增强与任务监控 // @namespace https://www.liblib.tv/ // @version 6.6.26 // @description 任务监控与画布增强;支持批量修改选中视频节点的生成模型、比例和清晰度,记住上次选择,并保留常驻图片替换素材按钮。 // @match https://www.liblib.tv/* // @match https://liblib.tv/* // @run-at document-start // @grant none // @license GPL-3.0 // ==/UserScript== (() => { 'use strict'; // 在安装 Turbopack 队列钩子前初始化标记,避免页面已有 chunk 队列时触发 TDZ。 let turbopackImportHookInstalled = false; const capturedCanvasAuthHeaders = Object.create(null); let capturedCanvasSessionId = ''; try { installTurbopackImportHook(); } catch (_) {} const CREATE_PATH = '/api/task/generation/create'; const PROGRESS_PATH = '/api/task/generation/progress'; const CONTEXT_PATHS = [ '/api/canvas/project/heartbeat', '/api/canvas/nodes/batch', '/api/canvas/project/draft/update' ]; const TASK_STORAGE_KEY = 'libtv_task_monitor_v6_tasks'; const SETTINGS_STORAGE_KEY = 'libtv_task_monitor_v6_settings'; const REMOVED_STORAGE_KEY = 'libtv_task_monitor_v6_removed_tasks'; const PROMPT_TEMPLATES_KEY = 'libtv_task_monitor_v6_prompt_templates'; const NODE_MARKS_PREFIX = 'libtv_task_monitor_v6_node_marks_'; const PROMPT_SIZE_STYLE_ID = 'libtv-task-monitor-prompt-size-style'; const IMAGE_REPLACE_BUTTON_STYLE_ID = 'libtv-task-monitor-image-replace-button-style'; const BATCH_SETTINGS_UI_ID = 'libtv-batch-video-settings-ui'; const BATCH_SETTINGS_PANEL_ID = 'libtv-batch-video-settings-panel'; const BATCH_SETTINGS_PREFS_KEY = 'libtv_batch_video_settings_last_used_v1'; const BATCH_SETTINGS_TOAST_ID = 'libtv-batch-video-settings-toast'; const BATCH_MODEL_SCHEMA_PATH = '/api/tool_spec/list?env=online'; let batchVideoModelsCache = null; let batchVideoModelsPromise = null; const PROMPT_POSITION_STYLE_ID = 'libtv-task-monitor-prompt-position-style'; const PROMPT_TEMPLATE_LAYOUT_KEY = 'libtv_task_monitor_v6_prompt_template_layout'; const NODE_MARK_STYLE_ID = 'libtv-task-monitor-node-mark-style'; const NODE_COST_STYLE_ID = 'libtv-task-monitor-node-cost-style'; const NODE_MARK_MENU_ID = 'libtv-task-monitor-node-mark-menu'; const PRESENCE_PREFIX = 'libtv_task_monitor_v6_presence_'; const PENDING_LOCATE_KEY = 'libtv_task_monitor_v6_pending_locate'; const PROJECT_LABELS_KEY = 'libtv_task_monitor_v6_project_labels'; const MAX_TASKS = 120; const ACTIVE_MAX_AGE = 7 * 24 * 60 * 60 * 1000; const PRESENCE_INTERVAL_MS = 2500; // 只在收到明确的 pagehide(非 BFCache)事件后才允许清理。 // 给刷新/页面导航留出重载窗口,避免瞬时离线被误判为关闭。 const PRESENCE_CLOSE_GRACE_MS = 20000; const pageUrlKey = normalizePageUrl(location.href); const tabId = getTabId(); let currentSpaceId = getSpaceIdFromUrl() || getSavedSessionValue('libtv_task_monitor_v6_space_id'); let currentProjectId = getProjectIdFromUrl() || getSavedSessionValue('libtv_task_monitor_v6_project_id'); let selectedSiteKey = ''; let userSelectedSite = false; let tasks = []; let taskById = new Map(); let latestProgress = new Map(); let removedTaskKeys = new Set(); let presenceTimer = null; let lastAutoCleanupAt = 0; let permissionPromptAttempted = false; let nextLocalId = 1; let host = null; let shadow = null; let audioContext = null; let noticeTimer = null; let renderTimer = null; let canvasSyncTimer = null; let nodeMarkObserver = null; let nodeCostObserver = null; let nodeCostRenderTimer = null; let videoDownloadObserver = null; let videoPlaybackObserver = null; let activeVideoNode = null; let videoPlaybackShortcutsInstalled = false; let videoPlaybackSpeedHoldTimeout = null; let videoPlaybackSpeedHoldInterval = null; let videoPlaybackSpeedHoldKey = ''; let videoPlaybackSpeedHoldNode = null; let pendingLocateResumeInFlight = false; let projectLabelIndexCache = null; let projectLabelIndexRaw = null; const videoPlaybackStates = new WeakMap(); let nativeVideoChromeWatchdogTimer = null; // 分离记录浏览器原始 autoplay 状态,确保“视频不自动播放”可以独立启停。 const videoAutoplayOriginals = new WeakMap(); let markMenuEl = null; let nodeMarks = {}; let nodeMarksSpaceId = ''; let promptTemplates = []; let editingPromptTemplateId = ''; let lastPromptEditor = null; let promptSearchObserver = null; let promptViewportObserver = null; let promptViewportObserverTarget = null; let promptViewportSyncFrame = 0; let pendingNativeMarkContext = null; let canvasPageActive = false; const nodeObservers = new Map(); const nodeRetryTimers = new Map(); const restoringControlUntil = { connections: 0, minimap: 0 }; // 提示词模板库中的 Ctrl+V 必须优先留给自己的 input/textarea,不能被 LibTV 画布的粘贴快捷键接管。 window.addEventListener('keydown', interceptPromptTemplatePasteShortcut, true); window.addEventListener('paste', interceptPromptTemplatePaste, true); let settings = { soundEnabled: true, notificationsEnabled: true, largeThumbnailsEnabled: true, persistentVideoDownloadEnabled: true, nodeMarkingEnabled: true, duplicateVersionNamingEnabled: true, promptSizeEnabled: true, promptTemplatesEnabled: true, promptSearchReplaceEnabled: true, promptSendButtonEnabled: true, canvasStatsEnabled: true, globalDefaultsVersion: 2, connectionsBySite: {}, minimapBySite: {} }; function safeString(value) { return value == null ? '' : String(value); } function normalizeText(value) { return safeString(value).replace(/\s+/g, ' ').trim(); } function normalizePageUrl(url) { try { const parsed = new URL(url, location.href); parsed.hash = ''; return parsed.origin + parsed.pathname + parsed.search; } catch (_) { return safeString(url).split('#')[0]; } } function getTabId() { const key = 'libtv_task_monitor_v6_tab_id'; try { let id = sessionStorage.getItem(key); if (id) return id; id = `tab-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 9)}`; sessionStorage.setItem(key, id); return id; } catch (_) { return `tab-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 9)}`; } } function getSavedSessionValue(key) { try { return sessionStorage.getItem(key) || ''; } catch (_) { return ''; } } function getSpaceIdFromUrl() { try { const parsed = new URL(location.href); const queryValue = parsed.searchParams.get('spaceId') || parsed.searchParams.get('space_id'); if (queryValue) return String(queryValue); const hash = parsed.hash || ''; const match = hash.match(/[?&](?:spaceId|space_id)=(\w+)/i) || hash.match(/(?:^|[/#])space(?:Id)?[=/](\w+)/i); if (match) return match[1]; } catch (_) {} try { const value = document.documentElement && document.documentElement.getAttribute('data-space-id'); if (value) return value; const bodyValue = document.body && document.body.getAttribute('data-space-id'); if (bodyValue) return bodyValue; const any = document.querySelector('[data-space-id],[data-spaceid]'); if (any) return any.getAttribute('data-space-id') || any.getAttribute('data-spaceid') || ''; const historyIds = idsFrom(window.history && window.history.state); if (historyIds.spaceId) return historyIds.spaceId; } catch (_) {} return ''; } function getProjectIdFromUrl() { try { const parsed = new URL(location.href); const queryValue = parsed.searchParams.get('projectId') || parsed.searchParams.get('project_id'); if (queryValue) return String(queryValue); const hash = parsed.hash || ''; const match = hash.match(/[?&](?:projectId|project_id)=([^&#/]+)/i) || hash.match(/(?:^|[/#])project(?:Id)?[=/]([A-Za-z0-9_-]+)/i); if (match) return match[1]; } catch (_) {} try { const value = document.documentElement && (document.documentElement.getAttribute('data-project-id') || document.documentElement.getAttribute('data-projectid')); if (value) return value; const bodyValue = document.body && (document.body.getAttribute('data-project-id') || document.body.getAttribute('data-projectid')); if (bodyValue) return bodyValue; const any = document.querySelector('[data-project-id],[data-projectid]'); if (any) return any.getAttribute('data-project-id') || any.getAttribute('data-projectid') || ''; const historyIds = idsFrom(window.history && window.history.state); if (historyIds.projectId) return historyIds.projectId; } catch (_) {} return ''; } function getCurrentProjectName() { try { const input = document.querySelector('input[aria-label="项目名称"],input[aria-label*="项目名称"]'); return normalizeText(input && (input.value || input.getAttribute('value')) || ''); } catch (_) { return ''; } } function getCurrentCanvasName() { try { const chip = document.querySelector('button[class*="canvas-chip"]'); if (!chip) return ''; const label = chip.querySelector('span'); return normalizeText(label ? (label.innerText || label.textContent) : (chip.innerText || chip.textContent)); } catch (_) { return ''; } } function readProjectLabelIndex() { try { const raw = localStorage.getItem(PROJECT_LABELS_KEY) || '{}'; if (projectLabelIndexCache && raw === projectLabelIndexRaw) return projectLabelIndexCache; const value = JSON.parse(raw); projectLabelIndexRaw = raw; projectLabelIndexCache = value && typeof value === 'object' && !Array.isArray(value) ? value : {}; return projectLabelIndexCache; } catch (_) { return projectLabelIndexCache || {}; } } function rememberProjectLabel(projectId, projectName, canvasName) { const id = safeString(projectId); const project = normalizeText(projectName); const canvas = normalizeText(canvasName); if (!id || !project || !canvas) return; try { const records = readProjectLabelIndex(); const existing = records[id]; if (existing && normalizeText(existing.projectName) === project && normalizeText(existing.canvasName) === canvas) return; records[id] = { projectName: project, canvasName: canvas, updatedAt: Date.now() }; const ids = Object.keys(records); if (ids.length > 200) { ids.sort((a, b) => (Number(records[a] && records[a].updatedAt) || 0) - (Number(records[b] && records[b].updatedAt) || 0)); for (const oldId of ids.slice(0, ids.length - 160)) delete records[oldId]; } const raw = JSON.stringify(records); localStorage.setItem(PROJECT_LABELS_KEY, raw); projectLabelIndexCache = records; projectLabelIndexRaw = raw; } catch (_) {} } function savedProjectLabel(projectId) { if (!projectId) return null; const record = readProjectLabelIndex()[safeString(projectId)]; return record && typeof record === 'object' ? record : null; } function getTaskCanvasName(task) { if (task && task.canvasName) return normalizeText(task.canvasName); const known = savedProjectLabel(task && task.projectId); if (known && known.canvasName) return normalizeText(known.canvasName); const label = normalizeText(task && task.siteLabel); const separator = label.indexOf('·'); if (separator >= 0 && separator < label.length - 1) return normalizeText(label.slice(separator + 1)); return ''; } function getTaskSiteLabel(task) { const known = savedProjectLabel(task && task.projectId); const projectName = normalizeText(task && task.projectName) || normalizeText(known && known.projectName); const canvasName = getTaskCanvasName(task); if (projectName && canvasName) return `${projectName}·${canvasName}`; if (task && task.siteLabel) return task.siteLabel; return task && task.spaceId ? `画布 ${task.spaceId}` : '其他 LibTV 页面'; } function getPageLabel(title = document.title) { const projectName = getCurrentProjectName(); const canvasName = getCurrentCanvasName(); if (projectName && canvasName) return `${projectName}·${canvasName}`; let label = normalizeText(title); label = label.replace(/\s*[-||]\s*LibTV.*$/i, '').trim(); label = label.replace(/\s*[-||]\s*专业视频创作工具.*$/i, '').trim(); if (label && !/^LibTV$/i.test(label)) return label; if (currentProjectId) return `项目 ${currentProjectId.slice(-6)}`; if (currentSpaceId) return `画布 ${currentSpaceId}`; return 'LibTV 画布'; } function makeSiteKey(spaceId = currentSpaceId, projectId = currentProjectId, urlKey = pageUrlKey) { // 一个 space 下可以有多个独立画布;分组与每画布设置优先按 projectId 区分。 if (projectId) return `project:${projectId}`; if (spaceId) return `space:${spaceId}`; return `url:${urlKey}`; } function currentSiteKey() { return makeSiteKey(currentSpaceId, currentProjectId, pageUrlKey); } function keyForTask(task) { if (task.projectId) return `project:${task.projectId}`; if (task.spaceId) return `space:${task.spaceId}`; return `url:${task.pageUrlKey || pageUrlKey}`; } function shortId(value) { const text = safeString(value); return text.length > 9 ? text.slice(-6) : text; } function routeFor(url) { const raw = safeString(url); if (raw.includes(CREATE_PATH)) return 'create'; if (raw.includes(PROGRESS_PATH)) return 'progress'; if (CONTEXT_PATHS.some(path => raw.includes(path))) return 'context'; return ''; } function parseBody(body) { if ( body && typeof body === 'object' && !(body instanceof URLSearchParams) && !(typeof FormData !== 'undefined' && body instanceof FormData) ) return body; if (typeof body === 'string') { try { return JSON.parse(body); } catch (_) { return null; } } if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) { const result = {}; for (const [key, value] of body.entries()) { try { result[key] = JSON.parse(value); } catch (_) { result[key] = value; } } return result; } return null; } function findFirstKey(value, wantedKeys, seen = new Set()) { if (!value || typeof value !== 'object' || seen.has(value)) return undefined; seen.add(value); const keys = Array.isArray(wantedKeys) ? wantedKeys : [wantedKeys]; if (!Array.isArray(value)) { for (const key of keys) { if (Object.prototype.hasOwnProperty.call(value, key)) { const found = value[key]; if (found !== undefined && found !== null && found !== '') return found; } } } for (const key of Object.keys(value)) { const found = findFirstKey(value[key], keys, seen); if (found !== undefined) return found; } return undefined; } function idsFrom(value) { return { spaceId: safeString(findFirstKey(value, ['spaceId', 'space_id', 'spaceID'])), projectId: safeString(findFirstKey(value, ['project_id', 'projectId', 'projectID'])) }; } function readSettings() { try { const parsed = JSON.parse(localStorage.getItem(SETTINGS_STORAGE_KEY) || '{}'); // v6 初版默认关闭提示音/通知;旧设置升级时默认开启一次,后续保留用户自己的开关选择。 const settingsVersion = Number(parsed.globalDefaultsVersion) || 0; settings = { soundEnabled: settingsVersion >= 2 ? parsed.soundEnabled !== false : true, notificationsEnabled: settingsVersion >= 2 ? parsed.notificationsEnabled !== false : true, largeThumbnailsEnabled: parsed.largeThumbnailsEnabled !== false, persistentVideoDownloadEnabled: parsed.persistentVideoDownloadEnabled !== false, videoPlaybackControlsEnabled: parsed.videoPlaybackControlsEnabled !== false, videoAutoplayDisabled: parsed.videoAutoplayDisabled !== false, nodeMarkingEnabled: parsed.nodeMarkingEnabled !== false, duplicateVersionNamingEnabled: parsed.duplicateVersionNamingEnabled !== false, promptSizeEnabled: parsed.promptSizeEnabled !== false, promptEditorPosition: ['bottom', 'top', 'left', 'right', 'free'].includes(parsed.promptEditorPosition) ? parsed.promptEditorPosition : 'bottom', promptEditorWidth: Number.isFinite(Number(parsed.promptEditorWidth)) ? Math.max(480, Math.min(1400, Number(parsed.promptEditorWidth))) : 720, promptEditorHeight: Number.isFinite(Number(parsed.promptEditorHeight)) ? Math.max(220, Math.min(1100, Number(parsed.promptEditorHeight))) : 400, promptEditorFontSize: Number.isFinite(Number(parsed.promptEditorFontSize)) ? Math.max(12, Math.min(28, Number(parsed.promptEditorFontSize))) : 14, promptEditorFreeLeft: typeof parsed.promptEditorFreeLeft === 'number' && Number.isFinite(parsed.promptEditorFreeLeft) ? parsed.promptEditorFreeLeft : null, promptEditorFreeTop: typeof parsed.promptEditorFreeTop === 'number' && Number.isFinite(parsed.promptEditorFreeTop) ? parsed.promptEditorFreeTop : null, promptTemplatesEnabled: parsed.promptTemplatesEnabled !== false, promptSearchReplaceEnabled: parsed.promptSearchReplaceEnabled !== false, promptSendButtonEnabled: parsed.promptSendButtonEnabled !== false, canvasStatsEnabled: parsed.canvasStatsEnabled !== false, globalDefaultsVersion: 2, connectionsBySite: parsed.connectionsBySite && typeof parsed.connectionsBySite === 'object' ? parsed.connectionsBySite : {}, minimapBySite: parsed.minimapBySite && typeof parsed.minimapBySite === 'object' ? parsed.minimapBySite : {} }; if (settingsVersion < 2) saveSettings(); } catch (_) { settings = { soundEnabled: true, notificationsEnabled: true, largeThumbnailsEnabled: true, persistentVideoDownloadEnabled: true, videoPlaybackControlsEnabled: true, videoAutoplayDisabled: true, nodeMarkingEnabled: true, duplicateVersionNamingEnabled: true, promptSizeEnabled: true, promptEditorPosition: 'bottom', promptEditorWidth: 720, promptEditorHeight: 400, promptEditorFontSize: 14, promptEditorFreeLeft: null, promptEditorFreeTop: null, promptTemplatesEnabled: true, promptSearchReplaceEnabled: true, promptSendButtonEnabled: true, canvasStatsEnabled: true, globalDefaultsVersion: 2, connectionsBySite: {}, minimapBySite: {} }; saveSettings(); } } function saveSettings() { settings.globalDefaultsVersion = 2; try { localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(settings)); } catch (_) {} } function migrateLegacyControlSettings() { if (!currentSpaceId || !currentProjectId) return; const legacyKey = `space:${currentSpaceId}`; const projectKey = `project:${currentProjectId}`; let changed = false; for (const keyName of ['connectionsBySite', 'minimapBySite']) { const store = settings[keyName]; if (store && store[legacyKey] !== undefined && store[projectKey] === undefined) { store[projectKey] = store[legacyKey]; changed = true; } } if (changed) saveSettings(); } function readRemovedTaskKeys() { try { const value = JSON.parse(localStorage.getItem(REMOVED_STORAGE_KEY) || '[]'); removedTaskKeys = new Set(Array.isArray(value) ? value.map(safeString) : []); } catch (_) { removedTaskKeys = new Set(); } } function saveRemovedTaskKeys() { // 限制墓碑数量,避免长期使用后 localStorage 不断增长。 if (removedTaskKeys.size > 1000) removedTaskKeys = new Set(Array.from(removedTaskKeys).slice(-800)); try { localStorage.setItem(REMOVED_STORAGE_KEY, JSON.stringify(Array.from(removedTaskKeys))); } catch (_) {} } function taskStorageId(task) { return task.taskId ? `id:${task.taskId}` : `local:${task.sourceTabId || ''}:${task.localId || ''}:${task.createdAt || ''}`; } function serializeTask(task) { return { localId: task.localId, taskId: task.taskId, nodeId: task.nodeId, nodeTitle: task.nodeTitle, projectId: task.projectId, spaceId: task.spaceId, siteKey: keyForTask(task), siteLabel: task.siteLabel, projectName: task.projectName || '', canvasName: task.canvasName || '', pageUrl: task.pageUrl, pageUrlKey: task.pageUrlKey, sourceTabId: task.sourceTabId, model: task.model, taskType: task.taskType, costCredits: task.costCredits == null ? null : task.costCredits, costSource: task.costSource || '', createdAt: task.createdAt, startedAt: task.startedAt, startedAtKnown: task.startedAtKnown, finishedAt: task.finishedAt, durationMs: task.durationMs, state: task.state, rawStatus: task.rawStatus, alertedState: task.alertedState || '', errorMessage: task.errorMessage, recovered: task.recovered, updatedAt: task.updatedAt }; } function isTerminal(state) { return state === 'success' || state === 'failed' || state === 'cancelled'; } function normalizeStoredTask(source) { if (!source || typeof source !== 'object') return null; const now = Date.now(); const createdAt = Number(source.createdAt) || now; const updatedAt = Number(source.updatedAt) || createdAt; let state = safeString(source.state) || 'unknown'; let errorMessage = safeString(source.errorMessage); let startedAt = Number(source.startedAt) || 0; let startedAtKnown = source.startedAtKnown === true; if (!isTerminal(state) && now - updatedAt > ACTIVE_MAX_AGE) { state = 'unknown'; errorMessage = '任务记录超过 7 天未更新,状态标为未知'; startedAt = 0; startedAtKnown = false; } return { localId: Number(source.localId) || nextLocalId++, taskId: safeString(source.taskId), nodeId: safeString(source.nodeId), nodeTitle: safeString(source.nodeTitle), projectId: safeString(source.projectId), spaceId: safeString(source.spaceId), siteLabel: safeString(source.siteLabel) || 'LibTV 画布', projectName: safeString(source.projectName), canvasName: safeString(source.canvasName), pageUrl: safeString(source.pageUrl), pageUrlKey: safeString(source.pageUrlKey), sourceTabId: safeString(source.sourceTabId), model: safeString(source.model), taskType: safeString(source.taskType) || '生成任务', costCredits: source.costCredits == null || source.costCredits === '' || !Number.isFinite(Number(source.costCredits)) ? null : Number(source.costCredits), costSource: safeString(source.costSource), createdAt, startedAt, startedAtKnown, finishedAt: Number(source.finishedAt) || 0, durationMs: Number.isFinite(source.durationMs) ? source.durationMs : null, state, rawStatus: source.rawStatus == null ? null : source.rawStatus, alertedState: safeString(source.alertedState) || (source.alerted === true ? state : ''), errorMessage, recovered: source.recovered === true, updatedAt, needsStatusRefresh: !isTerminal(state) && state !== 'unknown' }; } function readTaskRecords() { try { const raw = JSON.parse(localStorage.getItem(TASK_STORAGE_KEY) || '[]'); return Array.isArray(raw) ? raw : []; } catch (_) { return []; } } function mergeRecordsIntoMemory(records) { readRemovedTaskKeys(); tasks = tasks.filter(item => !removedTaskKeys.has(taskStorageId(item))); for (const source of records) { const incoming = normalizeStoredTask(source); if (!incoming) continue; const key = taskStorageId(incoming); if (removedTaskKeys.has(key)) continue; const existing = tasks.find(item => taskStorageId(item) === key); if (!existing) { tasks.push(incoming); nextLocalId = Math.max(nextLocalId, incoming.localId + 1); } else if (incoming.updatedAt > existing.updatedAt) { Object.assign(existing, incoming); } } tasks.sort((a, b) => b.createdAt - a.createdAt); rebuildTaskIndex(); pruneTasks(); } function rebuildTaskIndex() { taskById = new Map(); for (const task of tasks) { if (!task.taskId) continue; const previous = taskById.get(task.taskId); if (!previous || task.updatedAt >= previous.updatedAt) taskById.set(task.taskId, task); } } function loadTasks() { mergeRecordsIntoMemory(readTaskRecords()); } function saveTasks() { try { const merged = new Map(); readRemovedTaskKeys(); for (const stored of readTaskRecords()) { const normal = normalizeStoredTask(stored); if (normal && !removedTaskKeys.has(taskStorageId(normal))) merged.set(taskStorageId(normal), serializeTask(normal)); } for (const task of tasks) { const key = taskStorageId(task); if (removedTaskKeys.has(key)) continue; const old = merged.get(key); if (!old || (Number(task.updatedAt) || 0) >= (Number(old.updatedAt) || 0)) { merged.set(key, serializeTask(task)); } } const result = Array.from(merged.values()) .sort((a, b) => (Number(b.createdAt) || 0) - (Number(a.createdAt) || 0)) .slice(0, MAX_TASKS); localStorage.setItem(TASK_STORAGE_KEY, JSON.stringify(result)); mergeRecordsIntoMemory(result); } catch (_) {} } function pruneTasks() { tasks.sort((a, b) => b.createdAt - a.createdAt); while (tasks.length > MAX_TASKS) { let removeIndex = -1; for (let i = tasks.length - 1; i >= 0; i--) { if (isTerminal(tasks[i].state) || tasks[i].state === 'unknown') { removeIndex = i; break; } } if (removeIndex < 0) break; tasks.splice(removeIndex, 1); } rebuildTaskIndex(); } function touch(task) { task.updatedAt = Date.now(); } function cleanTitleCandidate(value) { let title = normalizeText(value); if (!title) return ''; title = title.replace(/^([▶▷▸►⯈]\s*)+/, ''); title = title.split(/\s*(?:1280\s*[×x]\s*720|1920\s*[×x]\s*1080|\d{3,4}\s*[×x]\s*\d{3,4})\s*/i)[0]; title = title.split(/\s+(?:生成中|排队中|已完成|生成失败|取消|重试)\b/)[0]; title = normalizeText(title); if (!title || title.length > 90) return ''; if (/^(?:生成中|排队中|已完成|生成失败|取消|重试|视频|图片|音频|节点)$/i.test(title)) return ''; if (/\b\d+%\b/.test(title)) return ''; return title; } function cssAttributeValue(value) { return safeString(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\a '); } function findNodeElement(nodeId) { if (!nodeId || !document.documentElement) return null; const value = cssAttributeValue(nodeId); const selectors = [ `.react-flow__node[data-id="${value}"]`, `[data-node-id="${value}"]`, `[data-nodeid="${value}"]`, `[data-id="${value}"]`, `[id="${value}"]` ]; for (const selector of selectors) { try { const node = document.querySelector(selector); if (node) return node; } catch (_) {} } return null; } function findNodeTitle(nodeId) { const root = findNodeElement(nodeId); if (!root) return ''; const selectors = [ '[data-node-title]', '[data-title]', '[data-label]', 'h1', 'h2', 'h3', 'h4', '[class*="node-title"]', '[class*="NodeTitle"]' ]; for (const selector of selectors) { let elements = []; try { elements = root.matches(selector) ? [root] : Array.from(root.querySelectorAll(selector)); } catch (_) {} for (const element of elements.slice(0, 12)) { const title = cleanTitleCandidate( element.getAttribute('data-node-title') || element.getAttribute('data-title') || element.getAttribute('data-label') || element.textContent ); if (title && title.length >= 2 && title !== nodeId && !/定位到节点/.test(title)) return title; } } let text = ''; try { text = root.innerText || root.textContent || ''; } catch (_) {} for (const line of text.split(/\n+/).slice(0, 5)) { const title = cleanTitleCandidate(line); if (title && title.length >= 2 && title !== nodeId && !/定位到节点/.test(title)) return title; } return ''; } // 节点 ID 是任务与画布节点之间的主键。标题只作为实时显示值,不再作为任务身份。 function resolveTaskNodeTitle(taskOrNodeId) { const task = taskOrNodeId && typeof taskOrNodeId === 'object' ? taskOrNodeId : null; const nodeId = safeString(task ? task.nodeId : taskOrNodeId); if (!nodeId) return task ? safeString(task.nodeTitle) : ''; const liveTitle = findNodeTitle(nodeId); const override = versionNameOverrides.get(nodeId); if (override && override.spaceId === currentSpaceId) { const live = normalizeText(liveTitle); const intended = normalizeText(override.title); if (!live) return override.title; if (live === intended) return liveTitle; // 若画布标题仍是原生的“名称 - 副本”,面板先按该 nodeId 显示已分配版本名。 if (matchesPreviousVersionTitle(liveTitle, override)) return override.title; // 与副本原名不相符,说明用户后来手动改名;尊重实际名称并放弃旧覆盖。 versionNameOverrides.delete(nodeId); saveVersionNameOverrides(); return liveTitle; } return liveTitle || (task ? safeString(task.nodeTitle) : ''); } function taskName(task) { if (task && task.nodeId) { const liveTitle = resolveTaskNodeTitle(task); if (liveTitle) { task.nodeTitle = liveTitle; return liveTitle; } if (task.nodeTitle) return task.nodeTitle; const id = safeString(task.nodeId); return `节点 ${id.length > 18 ? `${id.slice(0, 8)}…${id.slice(-5)}` : id}`; } if (task && task.nodeTitle) return task.nodeTitle; return task.model || task.taskType || '生成任务'; } let taskNodeNameObserver = null; let taskNodeNameSyncPending = false; const taskNodeNameSyncQueuedIds = new Set(); function syncTaskNamesForNodeId(nodeId, shouldRender = true) { const id = safeString(nodeId); if (!id) return false; const related = tasks.filter(task => safeString(task.nodeId) === id); if (!related.length) return false; const title = resolveTaskNodeTitle(id); if (!title) return false; let changed = false; for (const task of related) { if (safeString(task.nodeTitle) !== title) { task.nodeTitle = title; task.updatedAt = Date.now(); changed = true; } } if (changed) { saveTasks(); if (shouldRender) render(); } return changed; } function installTaskNodeNameSyncObserver() { if (taskNodeNameObserver || !document.documentElement) return; taskNodeNameObserver = new MutationObserver(mutations => { const ids = new Set(); const addNodeIdFromElement = element => { if (!(element instanceof Element)) return; const node = element.closest('.react-flow__node[data-id],.react-flow__node[data-node-id],.react-flow__node[data-nodeid]'); if (!node) return; const id = nodeIdFromElement(node); if (id && tasks.some(task => safeString(task.nodeId) === id)) ids.add(id); }; for (const mutation of mutations) { addNodeIdFromElement(mutation.target instanceof Element ? mutation.target : mutation.target && mutation.target.parentElement); if (mutation.type === 'childList') { for (const added of mutation.addedNodes || []) { if (!(added instanceof Element)) continue; addNodeIdFromElement(added); try { added.querySelectorAll('.react-flow__node[data-id],.react-flow__node[data-node-id],.react-flow__node[data-nodeid]').forEach(node => { const id = nodeIdFromElement(node); if (id && tasks.some(task => safeString(task.nodeId) === id)) ids.add(id); }); } catch (_) {} } } } for (const id of ids) taskNodeNameSyncQueuedIds.add(id); if (!taskNodeNameSyncQueuedIds.size || taskNodeNameSyncPending) return; taskNodeNameSyncPending = true; queueMicrotask(() => { taskNodeNameSyncPending = false; const queuedIds = Array.from(taskNodeNameSyncQueuedIds); taskNodeNameSyncQueuedIds.clear(); let changed = false; for (const id of queuedIds) changed = syncTaskNamesForNodeId(id, false) || changed; if (changed) render(); // 如果执行期间又收到了新节点变更,下一轮继续处理。 if (taskNodeNameSyncQueuedIds.size) { taskNodeNameSyncPending = true; queueMicrotask(() => { taskNodeNameSyncPending = false; const retryIds = Array.from(taskNodeNameSyncQueuedIds); taskNodeNameSyncQueuedIds.clear(); let retryChanged = false; for (const id of retryIds) retryChanged = syncTaskNamesForNodeId(id, false) || retryChanged; if (retryChanged) render(); }); } }); }); taskNodeNameObserver.observe(document.documentElement, { childList: true, characterData: true, attributes: true, attributeFilter: ['data-node-title', 'data-title', 'data-label'], subtree: true }); } function setCurrentContext(values = {}) { const oldKey = currentSiteKey(); const incomingSpace = safeString(values.spaceId); const incomingProject = safeString(values.projectId); if (incomingSpace) { currentSpaceId = incomingSpace; try { sessionStorage.setItem('libtv_task_monitor_v6_space_id', incomingSpace); } catch (_) {} } if (incomingProject) { currentProjectId = incomingProject; try { sessionStorage.setItem('libtv_task_monitor_v6_project_id', incomingProject); } catch (_) {} } const newKey = currentSiteKey(); if (incomingSpace && incomingSpace !== nodeMarksSpaceId) { nodeMarksSpaceId = ''; nodeMarks = {}; loadNodeMarks(); } if (oldKey !== newKey) { // 同一标签当前页的任务迁移到确定的 spaceId;历史刷新页通过 projectId 补齐。 for (const task of tasks) { const sameCurrentTab = task.sourceTabId === tabId && (!task.spaceId || !currentSpaceId || task.spaceId === currentSpaceId); const sameProjectWithoutSpace = Boolean(currentProjectId && task.projectId === currentProjectId && !task.spaceId); const unassignedSameUrl = !task.spaceId && !task.projectId && task.pageUrlKey === pageUrlKey; if (sameCurrentTab || sameProjectWithoutSpace || unassignedSameUrl) { if (currentSpaceId && (!task.spaceId || task.spaceId === currentSpaceId)) task.spaceId = currentSpaceId; if (!task.projectId && currentProjectId) task.projectId = currentProjectId; task.updatedAt = Date.now(); } } if (!userSelectedSite && (!selectedSiteKey || selectedSiteKey === oldKey)) { selectedSiteKey = newKey; } // 迁移本页旧的项目设置,避免从 URL fallback 切换成 spaceId 时丢失记忆。 for (const keyName of ['connectionsBySite', 'minimapBySite']) { if (settings[keyName][oldKey] !== undefined && settings[keyName][newKey] === undefined) { settings[keyName][newKey] = settings[keyName][oldKey]; } } saveSettings(); saveTasks(); render(); scheduleControlRestore(); } } function createTask(meta, taskId, initialState = 'queued', options = {}) { const id = safeString(taskId); if (id && removedTaskKeys.has(`id:${id}`)) return null; const spaceId = safeString(meta && meta.spaceId) || currentSpaceId; const projectId = safeString(meta && meta.projectId) || currentProjectId; const projectName = getCurrentProjectName(); const canvasName = getCurrentCanvasName(); const currentLabel = projectName && canvasName ? `${projectName}·${canvasName}` : getPageLabel(); rememberProjectLabel(projectId, projectName, canvasName); if (spaceId || projectId) setCurrentContext({ spaceId, projectId }); if (id && taskById.has(id)) { const existing = taskById.get(id); if (meta && meta.nodeId) existing.nodeId = safeString(meta.nodeId); if (meta && meta.nodeTitle) existing.nodeTitle = safeString(meta.nodeTitle); if (meta && meta.model) existing.model = safeString(meta.model); if (meta && meta.taskType) existing.taskType = safeString(meta.taskType); if (meta && meta.costCredits != null) { existing.costCredits = Number(meta.costCredits); existing.costSource = safeString(meta.costSource) || existing.costSource || ''; } if (spaceId) existing.spaceId = spaceId; if (projectId) existing.projectId = projectId; existing.siteLabel = currentLabel; if (projectName) existing.projectName = projectName; if (canvasName) existing.canvasName = canvasName; existing.pageUrl = location.href; existing.pageUrlKey = pageUrlKey; existing.sourceTabId = tabId; touch(existing); saveTasks(); watchTaskNode(existing); render(); return existing; } const nodeId = safeString(meta && meta.nodeId); const title = safeString(meta && meta.nodeTitle) || findNodeTitle(nodeId); const now = options.createdAt || Date.now(); const task = { localId: nextLocalId++, taskId: id, nodeId, nodeTitle: title, projectId, spaceId, siteLabel: currentLabel, projectName, canvasName, pageUrl: location.href, pageUrlKey, sourceTabId: tabId, model: safeString(meta && meta.model), taskType: safeString(meta && meta.taskType) || '生成任务', costCredits: meta && meta.costCredits != null ? Number(meta.costCredits) : null, costSource: safeString(meta && meta.costSource), createdAt: now, startedAt: 0, startedAtKnown: false, finishedAt: 0, durationMs: null, state: initialState, rawStatus: null, alertedState: '', errorMessage: '', recovered: options.recovered === true, updatedAt: Date.now(), needsStatusRefresh: false }; tasks.unshift(task); if (id) taskById.set(id, task); if (!userSelectedSite) selectedSiteKey = keyForTask(task); pruneTasks(); saveTasks(); watchTaskNode(task); render(); if (id && latestProgress.has(id)) { const latest = latestProgress.get(id); applyStatus(task, latest.status, latest.item || null); } return task; } function normalizeStatus(raw) { const text = safeString(raw).trim().toLowerCase(); const numeric = Number(text); if (text !== '' && Number.isFinite(numeric)) { if (numeric === 0) return 'queued'; if (numeric === 1) return 'running'; if (numeric === 2) return 'success'; return 'unknown'; } if (/success|succeeded|complete|completed|finished|done/.test(text)) return 'success'; if (/fail|failed|failure|error|rejected/.test(text)) return 'failed'; if (/cancel|cancelled|canceled/.test(text)) return 'cancelled'; if (/queue|queued|pending|wait/.test(text)) return 'queued'; if (/run|running|process|processing|generating/.test(text)) return 'running'; return 'unknown'; } function markTaskFailed(task, reason = '节点显示生成失败') { if (!task || task.state === 'failed') return; if (isTerminal(task.state) && task.state !== 'success') return; task.state = 'failed'; task.finishedAt = Date.now(); task.durationMs = task.startedAtKnown && task.startedAt ? Math.max(0, task.finishedAt - task.startedAt) : null; task.errorMessage = reason; task.needsStatusRefresh = false; touch(task); saveTasks(); disconnectNodeObserver(task); render(); alertTask(task); } function hasFailureText(node) { if (!node) return false; let text = ''; try { text = normalizeText(node.innerText || node.textContent || ''); } catch (_) {} if (/(生成失败|生成出错|生成错误|任务失败|任务出错|生成异常|generation failed|failed to generate)/i.test(text)) { return true; } try { const redStatus = node.querySelector('span[class*="text-red"], [class*="text-red-400"], [class*="text-red-500"]'); if (redStatus && /(失败|错误|异常|failed|error)/i.test(normalizeText(redStatus.textContent))) return true; } catch (_) {} return false; } function observerKey(task) { return task.taskId ? `task:${task.taskId}` : `local:${task.localId}`; } function disconnectNodeObserver(task) { const key = observerKey(task); const observer = nodeObservers.get(key); if (observer) observer.disconnect(); nodeObservers.delete(key); const timer = nodeRetryTimers.get(key); if (timer) clearTimeout(timer); nodeRetryTimers.delete(key); } function watchTaskNode(task) { if (!task || !task.nodeId || isTerminal(task.state)) return; const key = observerKey(task); if (nodeObservers.has(key) || nodeRetryTimers.has(key)) return; let tries = 0; const attach = () => { nodeRetryTimers.delete(key); if (isTerminal(task.state)) return; const root = findNodeElement(task.nodeId); if (!root) { if (tries++ < 18) { nodeRetryTimers.set(key, setTimeout(attach, 250)); } return; } if (!task.nodeTitle) { task.nodeTitle = findNodeTitle(task.nodeId); saveTasks(); render(); } // 只检查此任务对应的节点,不监听整张画布。 if (hasFailureText(root)) { markTaskFailed(task); return; } const observer = new MutationObserver(() => { if (hasFailureText(root)) markTaskFailed(task); }); try { observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['class', 'aria-label'] }); nodeObservers.set(key, observer); } catch (_) {} }; attach(); } function applyProgressMetadata(task, item) { if (!task || !item || typeof item !== 'object') return false; let changed = false; const power = numericCredits(item.power); if (power != null && (task.costCredits !== power || task.costSource !== 'api-power')) { task.costCredits = power; task.costSource = 'api-power'; changed = true; } const startedAt = normalizeApiTimestamp(item.startTimeMs); if (startedAt && (!task.startedAtKnown || task.startedAt !== startedAt)) { task.startedAt = startedAt; task.startedAtKnown = true; changed = true; } const finishedAt = normalizeApiTimestamp(item.endTimeMs); if (finishedAt && task.finishedAt !== finishedAt) { task.finishedAt = finishedAt; changed = true; } if (task.startedAtKnown && task.startedAt && task.finishedAt && task.finishedAt >= task.startedAt) { const duration = task.finishedAt - task.startedAt; if (task.durationMs !== duration) { task.durationMs = duration; changed = true; } } return changed; } function applyStatus(task, raw, progressItem = null) { if (!task) return; const metadataChanged = applyProgressMetadata(task, progressItem); const next = normalizeStatus(raw); // 节点明确显示失败后,较晚返回的 status=1/2 不应把失败覆盖掉;但仍允许保存接口确认的耗时/积分。 if (task.state === 'failed') { if (metadataChanged) { touch(task); saveTasks(); render(); } return; } if (task.state === 'success' && next !== 'failed') { if (metadataChanged) { touch(task); saveTasks(); render(); } return; } task.rawStatus = raw; task.updatedAt = Date.now(); task.needsStatusRefresh = false; if (next === 'unknown') { if (task.state === 'submitting') task.state = 'unknown'; saveTasks(); render(); return; } if (next === 'queued' && task.state === 'running') { saveTasks(); return; } const previous = task.state; task.state = next; if (next === 'running' && !task.startedAt) { if (!task.recovered) { task.startedAt = Date.now(); task.startedAtKnown = true; } } if (isTerminal(next)) { if (!task.finishedAt) task.finishedAt = Date.now(); task.durationMs = task.startedAtKnown && task.startedAt ? Math.max(0, task.finishedAt - task.startedAt) : null; disconnectNodeObserver(task); } else if (task.nodeId) { watchTaskNode(task); } if (task.nodeId && !task.nodeTitle) task.nodeTitle = findNodeTitle(task.nodeId); touch(task); saveTasks(); render(); if ((next === 'success' || next === 'failed') && task.alertedState !== next) alertTask(task); if (previous !== task.state && task.state === 'running') watchTaskNode(task); } function extractProgressItems(payload, out = [], seen = new Set()) { if (!payload || typeof payload !== 'object' || seen.has(payload)) return out; seen.add(payload); if (Array.isArray(payload)) { for (const item of payload) extractProgressItems(item, out, seen); return out; } for (const key of Object.keys(payload)) { const value = payload[key]; if (key === 'progresses' && Array.isArray(value)) { for (const item of value) { if (item && typeof item === 'object' && item.taskId != null && item.status != null) out.push(item); } } else if (value && typeof value === 'object') { extractProgressItems(value, out, seen); } } return out; } function numericCredits(value) { if (value == null || value === '') return null; if (typeof value === 'number') return Number.isFinite(value) && value >= 0 && value < 1e9 ? value : null; const text = safeString(value).replace(/[,,\s]/g, '').match(/-?\d+(?:\.\d+)?/); if (!text) return null; const number = Number(text[0]); return Number.isFinite(number) && number >= 0 && number < 1e9 ? number : null; } function explicitCostFromPayload(payload) { const raw = findFirstKey(payload, [ 'consumed_points', 'consumedPoints', 'consume_points', 'consumePoints', 'points_used', 'pointsUsed', 'used_points', 'usedPoints', 'credit_cost', 'creditCost', 'cost_credits', 'costCredits', 'actual_cost', 'actualCost', 'actual_points', 'actualPoints', 'deduct_points', 'deductPoints', 'point_cost', 'pointCost' ]); return numericCredits(raw); } // LibTV 当前接口明确使用 power 表示本次生成消耗的积分。 // 优先读取 response.data.power / progress item.power,避免把请求参数里的同名字段误当成消耗。 function powerFromPayload(payload, seen = new Set()) { if (!payload || typeof payload !== 'object' || seen.has(payload)) return null; seen.add(payload); if (!Array.isArray(payload) && Object.prototype.hasOwnProperty.call(payload, 'power')) { const direct = numericCredits(payload.power); if (direct != null) return direct; } if (!Array.isArray(payload) && payload.data && typeof payload.data === 'object') { const nestedData = powerFromPayload(payload.data, seen); if (nestedData != null) return nestedData; } if (Array.isArray(payload)) { for (const item of payload) { const found = powerFromPayload(item, seen); if (found != null) return found; } return null; } for (const key of Object.keys(payload)) { if (key === 'data') continue; const value = payload[key]; if (value && typeof value === 'object') { const found = powerFromPayload(value, seen); if (found != null) return found; } } return null; } function apiCostFromPayload(payload) { const power = powerFromPayload(payload); if (power != null) return { costCredits: power, costSource: 'api-power' }; const otherCost = explicitCostFromPayload(payload); if (otherCost != null) return { costCredits: otherCost, costSource: 'api' }; return { costCredits: null, costSource: '' }; } function normalizeApiTimestamp(value) { if (value == null || value === '') return 0; const numeric = Number(value); if (!Number.isFinite(numeric) || numeric <= 0) return 0; if (numeric >= 1e12) return numeric; if (numeric >= 1e9) return numeric * 1000; return 0; } function isVisibleElement(element) { if (!element || !element.isConnected) return false; try { const style = getComputedStyle(element); const rect = element.getBoundingClientRect(); return style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity || '1') > 0 && rect.width > 0 && rect.height > 0; } catch (_) { return false; } } function readGeneratorPanelCost(nodeId = '') { let cards = []; const node = nodeId ? findNodeElement(nodeId) : null; if (node) { const card = node.querySelector('[data-generator-card]'); if (card) cards.push(card); } if (!cards.length) { try { cards = Array.from(document.querySelectorAll('[data-generator-card]')).filter(isVisibleElement); } catch (_) {} } for (const card of cards) { const struck = card.querySelector('[class*="line-through"]'); if (!struck || !struck.parentElement) continue; const siblings = Array.from(struck.parentElement.children || []); for (const sibling of siblings) { if (sibling === struck || (sibling.className && String(sibling.className).includes('line-through'))) continue; const value = numericCredits(sibling.textContent); if (value != null && /^\s*[\d,,]+(?:\.\d+)?\s*$/.test(safeString(sibling.textContent))) { return value; } } } return null; } function collectTaskCost(payload, nodeId = '') { const apiCost = explicitCostFromPayload(payload); if (apiCost != null) return { costCredits: apiCost, costSource: 'api' }; const uiCost = readGeneratorPanelCost(nodeId); if (uiCost != null) return { costCredits: uiCost, costSource: 'ui-estimate' }; return { costCredits: null, costSource: '' }; } function metaFromProgress(item) { const ids = idsFrom(item); const costs = apiCostFromPayload(item); return { spaceId: ids.spaceId || currentSpaceId, projectId: ids.projectId || currentProjectId, nodeId: safeString(findFirstKey(item, ['node_id', 'nodeId', 'nodeID'])), model: safeString(findFirstKey(item, ['model', 'model_name', 'modelName'])), taskType: safeString(findFirstKey(item, ['taskType', 'task_type'])) || '生成任务', nodeTitle: safeString(findFirstKey(item, ['node_title', 'nodeTitle', 'node_name', 'nodeName'])), ...costs }; } function processProgress(payload) { if (!canvasPageActive && !getSpaceIdFromUrl()) return; const ids = idsFrom(payload); if (ids.spaceId || ids.projectId) setCurrentContext(ids); for (const item of extractProgressItems(payload)) { const id = safeString(item.taskId); if (!id) continue; const progressSnapshot = { taskId: id, status: item.status, power: item.power, startTimeMs: item.startTimeMs, endTimeMs: item.endTimeMs, node_id: item.node_id || item.nodeId || item.nodeID, node_title: item.node_title || item.nodeTitle || item.node_name || item.nodeName, model: item.model || item.model_name || item.modelName, taskType: item.taskType || item.task_type, spaceId: item.spaceId || item.space_id, projectId: item.project_id || item.projectId }; latestProgress.set(id, { status: item.status, time: Date.now(), item: progressSnapshot }); let task = taskById.get(id); const status = normalizeStatus(item.status); if (!task && currentSpaceId && (status === 'queued' || status === 'running')) { task = createTask(metaFromProgress(item), id, status, { recovered: true }); if (status === 'running') { task.startedAt = 0; task.startedAtKnown = false; } } if (task) applyStatus(task, item.status, progressSnapshot); } while (latestProgress.size > 200) latestProgress.delete(latestProgress.keys().next().value); } function responseTaskId(payload) { const id = findFirstKey(payload, ['taskId', 'task_id']); return id == null ? '' : safeString(id); } function getMeta(body, payload = null) { const data = parseBody(body) || {}; const metadata = data.metadata || {}; const params = data.params || {}; const provider = data.provider || {}; const combined = { data, payload }; const ids = idsFrom(combined); const nodeId = safeString(metadata.node_id || metadata.nodeId || data.node_id || data.nodeId || ''); // 创建接口的 response.data.power 是服务端返回的本次积分;不使用请求面板标价作为实际消耗。 const costs = apiCostFromPayload(payload); return { spaceId: ids.spaceId || currentSpaceId, projectId: safeString(metadata.project_id || metadata.projectId || data.project_id || data.projectId || ids.projectId || currentProjectId), nodeId, nodeTitle: safeString(metadata.node_title || metadata.nodeTitle || metadata.node_name || metadata.nodeName || metadata.label || ''), model: safeString(params.model || provider.model || data.model || ''), taskType: safeString(data.taskType || data.task_type || params.taskType || '生成任务'), ...costs }; } function processCreateResponse(body, payload, httpStatus, requestMeta = null) { if (!canvasPageActive && !getSpaceIdFromUrl()) return; const responseMeta = getMeta(body, payload); const meta = { ...responseMeta }; if (requestMeta && typeof requestMeta === 'object') { for (const key of ['spaceId', 'projectId', 'nodeId', 'nodeTitle', 'model', 'taskType']) { if (!meta[key] && requestMeta[key]) meta[key] = requestMeta[key]; } if (meta.costCredits == null && requestMeta.costCredits != null) { meta.costCredits = requestMeta.costCredits; meta.costSource = requestMeta.costSource || 'ui-estimate'; } } const id = responseTaskId(payload); if (httpStatus >= 200 && httpStatus < 300 && id) { createTask(meta, id, 'queued'); return; } if (httpStatus < 200 || httpStatus >= 300) { const task = createTask(meta, '', 'failed'); task.finishedAt = Date.now(); task.durationMs = null; task.errorMessage = `提交请求失败(HTTP ${httpStatus || '网络错误'})`; touch(task); saveTasks(); render(); alertTask(task); return; } // HTTP 200 不代表生成成功;节点局部监控负责识别“生成失败”等终态。 if (meta.nodeId) { const temp = createTask(meta, '', 'submitting'); watchTaskNode(temp); setNotice('任务已提交,但未识别到任务编号;正在观察该节点状态。'); } } function captureContext(body, payload) { const fromBody = idsFrom(parseBody(body)); const fromPayload = idsFrom(payload); const urlSpace = getSpaceIdFromUrl(); setCurrentContext({ spaceId: fromBody.spaceId || fromPayload.spaceId || urlSpace, projectId: fromBody.projectId || fromPayload.projectId }); } function safeXhrPayload(xhr) { try { const value = xhr.response; if (value && typeof value === 'object') return value; if (typeof value === 'string' && value) { try { return JSON.parse(value); } catch (_) {} } const text = xhr.responseText; if (typeof text === 'string' && text) { try { return JSON.parse(text); } catch (_) {} } } catch (_) {} return null; } // 仅在目标 XHR 的 loadend 上读取数据;不改写原始请求/响应。 try { const xhrMeta = new WeakMap(); const proto = XMLHttpRequest.prototype; const nativeOpen = proto.open; const nativeSend = proto.send; const nativeSetRequestHeader = proto.setRequestHeader; if (!proto.__libtvStatusMonitorV6) { proto.setRequestHeader = function(name, value) { try { const key = safeString(name).toLowerCase(); if (key === 'token' || key === 'webid' || key === 'x-language') capturedCanvasAuthHeaders[key] = safeString(value); } catch (_) {} return nativeSetRequestHeader.apply(this, arguments); }; proto.open = function(method, url) { xhrMeta.set(this, { route: routeFor(url), method: safeString(method).toUpperCase(), url: safeString(url) }); return nativeOpen.apply(this, arguments); }; proto.send = function(body) { const info = xhrMeta.get(this); if (!info || !info.route) return nativeSend.apply(this, arguments); if (info.route === 'context') { try { const sentPayload = parseBody(body); if (sentPayload && sentPayload.sessionId) capturedCanvasSessionId = safeString(sentPayload.sessionId); } catch (_) {} } if (info.route === 'create') { // 在提交瞬间读取对应节点生成器面板上显示的当前积分价,作为估算备用值。 info.requestMeta = getMeta(body, null); if (info.requestMeta.costCredits == null) { const shownCost = readGeneratorPanelCost(info.requestMeta.nodeId); if (shownCost != null) { info.requestMeta.costCredits = shownCost; info.requestMeta.costSource = 'ui-estimate'; } } this.addEventListener('loadend', () => { const payload = safeXhrPayload(this); captureContext(body, payload); processCreateResponse(body, payload, this.status, info.requestMeta); }, { once: true }); } else if (info.route === 'progress') { this.addEventListener('loadend', () => { if (this.status >= 200 && this.status < 300) { const payload = safeXhrPayload(this); captureContext(body, payload); processProgress(payload); } }, { once: true }); } else if (info.route === 'context') { this.addEventListener('loadend', () => { if (this.status >= 200 && this.status < 300) captureContext(body, safeXhrPayload(this)); if (this.status >= 200 && this.status < 300 && info.versionNameNodeIds && info.versionNameNodeIds.length) { markVersionNamesPersisted(info.versionNameNodeIds); } }, { once: true }); } try { const sendArgs = Array.from(arguments); if (info.route === 'context' && isCanvasDraftWriteUrl(info.url) && typeof sendArgs[0] === 'string' && settings.duplicateVersionNamingEnabled) { // 在节点批量创建请求发出前修改名称;后续 update/draft 请求也同步相同版本名。 const prepared = prepareVersionNameRequestBody(info.url, sendArgs[0]); if (prepared.changed) sendArgs[0] = prepared.body; const allVersionNodeIds = new Set([...(info.versionNameNodeIds || []), ...prepared.nodeIds]); if (allVersionNodeIds.size) { info.versionNameNodeIds = Array.from(allVersionNodeIds); synchronizeVersionNameIdsIntoCanvasStore(Array.from(allVersionNodeIds)); } } return nativeSend.apply(this, sendArgs); } catch (error) { if (info.route === 'create') { const task = createTask(getMeta(body), '', 'failed'); task.finishedAt = Date.now(); task.errorMessage = '生成请求未能发送'; touch(task); saveTasks(); alertTask(task); } throw error; } }; Object.defineProperty(proto, '__libtvStatusMonitorV6', { value: true, configurable: false }); } } catch (_) {} // ---------- 节点连线/小地图:滑块直接控制并持久化 ---------- function getConnectionsButton() { try { return document.querySelector( 'button[aria-label="显示节点连线"],button[aria-label="隐藏节点连线"],button[aria-label*="节点连线"]' ); } catch (_) { return null; } } function readConnectionsVisible() { const button = getConnectionsButton(); if (!button) return null; const label = normalizeText(button.getAttribute('aria-label')); if (label.includes('显示节点连线')) return false; if (label.includes('隐藏节点连线')) return true; const pressed = button.getAttribute('aria-pressed'); if (pressed === 'true') return true; if (pressed === 'false') return false; return null; } function getMinimapButton() { try { return document.querySelector('button[aria-label="切换小地图"]'); } catch (_) { return null; } } function readMinimapVisible() { const selectors = [ '.react-flow__minimap', '[data-testid*="minimap"]', '[class*="react-flow__minimap"]', '[class*="MiniMap"]', '[class*="minimap"]' ]; let sawCandidate = false; const checked = new Set(); for (const selector of selectors) { let elements = []; try { elements = Array.from(document.querySelectorAll(selector)); } catch (_) {} for (const element of elements) { if (checked.has(element) || (element.matches && element.matches('button'))) continue; if (element.closest && element.closest('#libtv-task-monitor-host-v6')) continue; checked.add(element); sawCandidate = true; try { const style = getComputedStyle(element); const rect = element.getBoundingClientRect(); if (style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity || '1') > 0 && rect.width > 10 && rect.height > 10) return true; } catch (_) {} } } if (sawCandidate) return false; if (getMinimapButton()) return false; return null; } function stateStoreFor(kind) { return kind === 'connections' ? settings.connectionsBySite : settings.minimapBySite; } function readControlState(kind) { return kind === 'connections' ? readConnectionsVisible() : readMinimapVisible(); } function nativeControlButton(kind) { return kind === 'connections' ? getConnectionsButton() : getMinimapButton(); } function saveControlState(kind, value) { if (value === null || value === undefined) return; const key = currentSiteKey(); stateStoreFor(kind)[key] = Boolean(value); saveSettings(); renderControls(); } function applyNativeControl(kind, desired, options = {}) { const key = currentSiteKey(); const store = stateStoreFor(kind); if (options.persist !== false) { store[key] = Boolean(desired); saveSettings(); } let tries = 0; const step = () => { const actual = readControlState(kind); if (actual === desired) { renderControls(); return; } const button = nativeControlButton(kind); if (actual === null || !button) { if (tries++ < 12) { setTimeout(step, 250); } else if (options.userInitiated) { setNotice(kind === 'connections' ? '当前页面未找到节点连线按钮。' : '当前页面未找到小地图按钮。'); } return; } restoringControlUntil[kind] = Date.now() + 1200; try { button.click(); } catch (_) {} tries++; if (tries < 12) setTimeout(step, 140); else renderControls(); }; step(); } function restoreControl(kind) { const key = currentSiteKey(); const store = stateStoreFor(kind); const saved = store[key]; const actual = readControlState(kind); if (saved === undefined) { if (actual !== null) { store[key] = actual; saveSettings(); } renderControls(); return; } if (actual !== null && actual !== saved) { applyNativeControl(kind, saved, { persist: false }); } else { renderControls(); } } function restoreCanvasControls() { restoreControl('connections'); restoreControl('minimap'); } function scheduleControlRestore() { [100, 300, 650, 1200, 2200, 3800].forEach(delay => setTimeout(restoreCanvasControls, delay)); } function onNativeCanvasControlClick(event) { const target = event.target; if (!target || typeof target.closest !== 'function') return; const connection = target.closest('button[aria-label="显示节点连线"],button[aria-label="隐藏节点连线"],button[aria-label*="节点连线"]'); const minimap = target.closest('button[aria-label="切换小地图"]'); const kind = connection ? 'connections' : minimap ? 'minimap' : ''; if (!kind) return; setTimeout(() => { if (Date.now() < restoringControlUntil[kind]) return; const actual = readControlState(kind); if (actual !== null) saveControlState(kind, actual); }, 160); } document.addEventListener('click', onNativeCanvasControlClick, true); // ---------- 原生定位与资产管理 ---------- function isVisible(element) { if (!element || !element.isConnected) return false; try { const style = getComputedStyle(element); const rect = element.getBoundingClientRect(); return style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity || '1') > 0 && rect.width > 0 && rect.height > 0; } catch (_) { return false; } } function findNativeLocateButton(title) { const target = normalizeText(title); if (!target) return null; let buttons = []; try { buttons = Array.from(document.querySelectorAll('button[aria-label^="定位到节点 "]')); } catch (_) {} const exactLabel = `定位到节点 ${target}`; const exact = buttons.find(button => isVisible(button) && normalizeText(button.getAttribute('aria-label')) === exactLabel); if (exact) return exact; return buttons.find(button => isVisible(button) && normalizeText(button.getAttribute('aria-label')).replace(/^定位到节点\s*/, '') === target) || null; } function findNativeLocateButtonForTask(task) { if (!task) return null; const nodeId = safeString(task.nodeId); // 第一选择:若原生资产条目暴露节点 ID,则直接按 ID 识别对应的原生定位按钮。 if (nodeId) { let buttons = []; try { buttons = Array.from(document.querySelectorAll('button[aria-label^="定位到节点 "]')); } catch (_) {} for (const button of buttons) { if (!isVisible(button)) continue; let parent = button; for (let depth = 0; parent && depth < 8; depth++, parent = parent.parentElement) { const associatedId = safeString( parent.getAttribute('data-node-id') || parent.getAttribute('data-nodeid') || parent.getAttribute('data-node-key') || parent.getAttribute('data-nodekey') || (parent.classList && parent.classList.contains('react-flow__node') ? nodeIdFromElement(parent) : '') ); if (associatedId && associatedId === nodeId) return button; } } } // 原生按钮目前按名称暴露 aria-label:从 nodeId 读取最新名称后,继续调用原生定位按钮。 const currentTitle = resolveTaskNodeTitle(task); if (currentTitle) { const button = findNativeLocateButton(currentTitle); if (button) return button; } // 兼容标题正在编辑/资产面板尚未同步的短暂窗口。先用当前 DOM 标题,再退回任务缓存名。 const rawTitle = nodeId ? findNodeTitle(nodeId) : ''; if (rawTitle && normalizeText(rawTitle) !== normalizeText(currentTitle)) { const button = findNativeLocateButton(rawTitle); if (button) return button; } const cachedTitle = safeString(task.nodeTitle); return cachedTitle ? findNativeLocateButton(cachedTitle) : null; } function findAssetManagementButton() { try { return document.querySelector('button[data-academy-guide-anchor="workspace-asset-management"],button[aria-label="资产管理"]'); } catch (_) { return null; } } function isAssetManagementOpen() { try { const locateButtons = Array.from(document.querySelectorAll('button[aria-label^="定位到节点 "]')); if (locateButtons.some(isVisible)) return true; const button = findAssetManagementButton(); if (!button) return null; if (button.getAttribute('aria-pressed') === 'true') return true; if (button.getAttribute('data-state') === 'open') return true; if (button.classList.contains('bg-canvas-controls-active') || button.classList.contains('active')) return true; return false; } catch (_) { return null; } } function currentPageMatchesTask(task) { if (task.spaceId && currentSpaceId && task.spaceId !== currentSpaceId) return false; if (task.projectId && currentProjectId && task.projectId !== currentProjectId) return false; // 有 spaceId 的历史任务,而当前页面尚无法识别 spaceId/projectId 时,宁可提示切换页面,也不冒险定位到同名节点。 if (task.spaceId && !currentSpaceId && !currentProjectId) return false; if (!task.spaceId && !currentSpaceId && !task.projectId && task.pageUrlKey && task.pageUrlKey !== pageUrlKey) return false; return true; } async function waitForLocateButton(task, maxWaitMs = 2200) { const started = Date.now(); while (Date.now() - started <= maxWaitMs) { if (task.nodeId) { const liveTitle = resolveTaskNodeTitle(task); if (liveTitle && liveTitle !== task.nodeTitle) task.nodeTitle = liveTitle; } const title = taskName(task); const button = findNativeLocateButtonForTask(task) || findNativeLocateButton(title); if (button) return button; await new Promise(resolve => setTimeout(resolve, 140)); } return null; } function findCanvasPickerButton() { try { return document.querySelector('button[class*="canvas-chip"]'); } catch (_) { return null; } } function canvasOptionHasProjectId(element, targetProjectId) { const projectId = safeString(targetProjectId).trim(); if (!element || !projectId) return false; const idAttrs = [ 'data-project-id', 'data-projectid', 'data-project_id', 'data-id', 'data-value', 'data-canvas-id', 'data-canvasid', 'value', 'href', 'aria-label', 'title', 'id' ]; for (let item = element, depth = 0; item && item !== document.body && depth < 5; item = item.parentElement, depth++) { for (const attr of idAttrs) { const value = safeString(item.getAttribute && item.getAttribute(attr)); if (!value) continue; if (value === projectId || value.includes(projectId)) return true; try { const parsed = new URL(value, location.href); for (const key of ['projectId', 'project_id', 'canvasId', 'canvas_id', 'id']) { if (parsed.searchParams.get(key) === projectId) return true; } const hashMatch = (parsed.hash || '').match(/[?&](?:projectId|project_id|canvasId|canvas_id)=([^&#]+)/i); if (hashMatch && decodeURIComponent(hashMatch[1]) === projectId) return true; } catch (_) {} } } return false; } function canvasOptionMatchScore(element, targetName, targetProjectId) { const text = normalizeText(element && (element.innerText || element.textContent)); if (!text) return Infinity; const target = normalizeText(targetName); const projectId = safeString(targetProjectId).trim(); const short = shortId(projectId); let identityScore = 2; if (projectId && canvasOptionHasProjectId(element, projectId)) identityScore = 0; else if (projectId && short.length >= 5 && (text === short || text.includes(`(${short})`) || text.includes(`(${short})`) || text.includes(`[${short}]`))) identityScore = 0.5; let nameScore = 3; if (target && text === target) nameScore = 0; else if (target && text.includes(target) && text.length <= target.length + 36) nameScore = 1; else if (/未命名画布|未命名/.test(target) && /未命名画布|未命名/.test(text) && text.length <= 50) nameScore = 1; else if (!target) nameScore = 2; else return Infinity; let actionScore = 2; if (element.matches && element.matches('button,[role="option"],[role="menuitem"],[role="button"],a,[data-value]')) actionScore = 0; else if (element.matches && element.matches('[tabindex]:not([tabindex="-1"]),[class*="cursor-pointer"]')) actionScore = 1; return identityScore * 10000 + nameScore * 1000 + actionScore * 100 + Math.min(text.length, 99) + Math.min(element.querySelectorAll ? element.querySelectorAll('*').length : 0, 99) / 100; } function findCanvasPickerOption(targetName, targetProjectId = '') { const target = normalizeText(targetName); const projectId = safeString(targetProjectId).trim(); if (!target && !projectId) return null; const picker = findCanvasPickerButton(); const pickerOpen = Boolean(picker && (picker.getAttribute('aria-expanded') === 'true' || picker.getAttribute('data-state') === 'open')); const popupSelector = [ '[role="dialog"]', '[role="menu"]', '[role="listbox"]', '[role="option"]', '[class*="mantine-Popover-dropdown"]', '[class*="mantine-Menu-dropdown"]', '[class*="mantine-Modal-content"]', '[class*="Popover-content"]', '[class*="popover-content"]', '[class*="dropdown"]', '[class*="Dropdown"]', '[data-radix-popper-content-wrapper]', '[data-floating-ui-portal]', '[data-state="open"]' ].join(','); const popupRoots = Array.from(document.querySelectorAll(popupSelector)).filter(root => isVisibleElement(root)); // Some LibTV builds do not attach role/class markers to the popover. Do not search the entire page until the canvas picker has been opened. if (!popupRoots.length && !pickerOpen) return null; const roots = popupRoots.length ? popupRoots : [document]; const selector = 'button,[role="option"],[role="menuitem"],[role="button"],a,[tabindex]:not([tabindex="-1"]),li,[class*="cursor-pointer"],[data-value]'; let candidates = []; for (const root of roots) { try { candidates.push(...root.querySelectorAll(selector)); } catch (_) {} } candidates = [...new Set(candidates)].filter(element => { if (!isVisibleElement(element) || element === picker || (picker && picker.contains(element))) return false; if (element.closest('#libtv-task-monitor-host-v6,[data-libtv-task-monitor]')) return false; const txt = normalizeText(element.innerText || element.textContent); return Boolean(txt) && txt.length <= 180; }); if (!candidates.length) return null; // 先以完整 projectId / 菜单暴露的短 ID 匹配;再按画布名称匹配。 const explicitIdMatches = candidates.filter(element => canvasOptionHasProjectId(element, projectId)); let pool = explicitIdMatches; if (!pool.length && projectId) { const short = shortId(projectId); if (short.length >= 5) { pool = candidates.filter(element => { const text = normalizeText(element.innerText || element.textContent); return text === short || text.includes(`(${short})`) || text.includes(`(${short})`) || text.includes(`[${short}]`); }); } } if (!pool.length) { const wantUnnamed = !target || /未命名画布|未命名/.test(target); pool = candidates.filter(element => { const text = normalizeText(element.innerText || element.textContent); if (wantUnnamed) return /未命名画布|未命名/.test(text) && text.length <= 50; return text === target || (text.includes(target) && text.length <= target.length + 36); }); } if (!pool.length) return null; // Prefer semantic clickable controls and the smallest matching label. const priority = element => { if (element.matches('button,[role="option"],[role="menuitem"],[role="button"],a,[data-value]')) return 0; if (element.matches('[tabindex]:not([tabindex="-1"]),[class*="cursor-pointer"]')) return 1; return 2; }; pool.sort((a, b) => { const ta = normalizeText(a.innerText || a.textContent); const tb = normalizeText(b.innerText || b.textContent); const exactA = target && ta === target ? 0 : 1; const exactB = target && tb === target ? 0 : 1; return exactA - exactB || priority(a) - priority(b) || ta.length - tb.length || a.querySelectorAll('*').length - b.querySelectorAll('*').length; }); const chosen = pool[0]; const chosenText = normalizeText(chosen.innerText || chosen.textContent); const chosenPriority = priority(chosen); // When the project ID is not exposed in the DOM, don't guess between multiple identically named canvases. if (!explicitIdMatches.length && !(projectId && pool.some(element => { const text = normalizeText(element.innerText || element.textContent); const short = shortId(projectId); return short.length >= 5 && (text === short || text.includes(`(${short})`) || text.includes(`(${short})`) || text.includes(`[${short}]`)); }))) { const equallyPlausible = pool.filter(element => normalizeText(element.innerText || element.textContent) === chosenText && priority(element) === chosenPriority ); // Nested duplicate representations of the same entry are OK; separate peer controls with the same label are ambiguous. const distinctPeers = equallyPlausible.filter(element => !equallyPlausible.some(other => other !== element && other.contains(element))); if (distinctPeers.length > 1) return null; } return chosen; } async function waitForCanvasPickerOption(targetName, targetProjectId = '', maxWaitMs = 4500) { const started = Date.now(); while (Date.now() - started < maxWaitMs) { const option = findCanvasPickerOption(targetName, targetProjectId); if (option) return option; await new Promise(resolve => setTimeout(resolve, 140)); } return null; } function savePendingLocate(task, canvasName) { try { sessionStorage.setItem(PENDING_LOCATE_KEY, JSON.stringify({ taskKey: taskStorageId(task), taskId: task.taskId || '', localId: task.localId || 0, projectId: task.projectId || '', spaceId: task.spaceId || '', canvasName: canvasName || getTaskCanvasName(task), requestedAt: Date.now() })); return true; } catch (_) { return false; } } function clearPendingLocate() { try { sessionStorage.removeItem(PENDING_LOCATE_KEY); } catch (_) {} } async function requestCanvasSwitch(task, targetCanvasName) { const picker = findCanvasPickerButton(); if (!picker || !task.projectId) return false; // 历史任务可能没有保存画布名称;LibTV 的菜单常只显示“未命名画布”,不暴露 projectId 属性。 // 因此按 projectId 精确匹配失败时,允许用唯一的“未命名画布”菜单项兜底,但不在多个同名项间猜测。 const targetName = normalizeText(targetCanvasName) || '未命名画布'; let option = findCanvasPickerOption(targetName, task.projectId); if (!option) { const isOpen = picker.getAttribute('aria-expanded') === 'true' || picker.getAttribute('data-state') === 'open'; if (!isOpen) { try { picker.click(); } catch (_) { return false; } } // 等待框架把画布列表挂载进 DOM,再按 projectId / 名称匹配菜单项。 option = await waitForCanvasPickerOption(targetName, task.projectId, 5000); } if (!option) return false; if (!savePendingLocate(task, targetCanvasName || targetName)) return false; try { option.click(); setNotice(`正在切换到画布「${targetCanvasName || `未命名画布(${shortId(task.projectId)})`}」,切换完成后会继续定位节点。`); return true; } catch (_) { clearPendingLocate(); return false; } } function resumePendingLocateIfReady() { if (pendingLocateResumeInFlight || !canvasPageActive) return; let pending = null; try { pending = JSON.parse(sessionStorage.getItem(PENDING_LOCATE_KEY) || 'null'); } catch (_) {} if (!pending || typeof pending !== 'object') return; if (Date.now() - (Number(pending.requestedAt) || 0) > 30000) { clearPendingLocate(); setNotice(`未能自动切换到画布「${safeString(pending.canvasName) || '目标画布'}」,请手动切换画布后重新定位。`); return; } if (!pending.projectId || currentProjectId !== pending.projectId) return; if (pending.spaceId && currentSpaceId && pending.spaceId !== currentSpaceId) { clearPendingLocate(); window.alert('该节点属于另一个项目,请手动切换到对应项目后再定位。'); return; } const task = tasks.find(item => taskStorageId(item) === pending.taskKey) || (pending.taskId ? taskById.get(String(pending.taskId)) : null) || tasks.find(item => item.projectId === pending.projectId && item.nodeId); if (!task) return; pendingLocateResumeInFlight = true; clearPendingLocate(); setTimeout(async () => { try { await locateTask(task); } finally { pendingLocateResumeInFlight = false; } }, 350); } async function locateTask(task) { if (!task) return; if (task.spaceId && currentSpaceId && task.spaceId !== currentSpaceId) { const owner = getTaskSiteLabel(task); const message = `该节点属于另一个项目「${owner}」,请手动切换到对应项目后再定位。`; setNotice(message); window.alert(message); return; } if (task.projectId && currentProjectId && task.projectId !== currentProjectId) { const sameSpace = Boolean(task.spaceId && currentSpaceId && task.spaceId === currentSpaceId); if (!sameSpace) { const message = `该节点属于另一个项目「${getTaskSiteLabel(task)}」,请手动切换到对应项目后再定位。`; setNotice(message); window.alert(message); return; } const targetCanvasName = getTaskCanvasName(task); const targetCanvasLabel = targetCanvasName || `未命名画布(${shortId(task.projectId)})`; const confirmed = window.confirm(`该节点属于画布「${targetCanvasLabel}」。是否跳转到画布:${targetCanvasLabel}?`); if (!confirmed) return; const switched = await requestCanvasSwitch(task, targetCanvasName); if (!switched) { const message = `未能自动切换到画布「${targetCanvasLabel}」。请从顶部画布选择器手动切换后,再次点击定位。`; setNotice(message); window.alert(message); } return; } if (!currentPageMatchesTask(task)) { const owner = getTaskSiteLabel(task) || (task.spaceId ? `画布 ${task.spaceId}` : '对应的 LibTV 页面'); setNotice(`此任务属于“${owner}”。请切换到对应的 LibTV 页面后再定位。`); return; } if (task.nodeId) { const liveTitle = resolveTaskNodeTitle(task); if (liveTitle && liveTitle !== task.nodeTitle) { task.nodeTitle = liveTitle; saveTasks(); render(); } } let title = taskName(task); let button = findNativeLocateButtonForTask(task) || findNativeLocateButton(title); if (!button) { const isOpen = isAssetManagementOpen(); if (!isOpen) { const assetButton = findAssetManagementButton(); if (!assetButton) { setNotice('找不到 LibTV 的“资产管理”按钮,无法自动开启定位面板。'); return; } try { assetButton.click(); } catch (_) { setNotice('无法开启资产管理面板,请手动打开后再定位。'); return; } } button = await waitForLocateButton(task, 2500); } if (!button) { setNotice(`已尝试开启资产管理,但没有找到“定位到节点 ${title}”按钮。请确认此节点仍存在于当前画布。`); return; } try { button.click(); setNotice(`已调用 LibTV 原生定位:${title}`); } catch (_) { setNotice('触发原生定位失败,请确认对应节点仍存在。'); } } // ---------- 音效/通知 ---------- function getAudioContext() { if (!audioContext) { const AudioContextClass = window.AudioContext || window.webkitAudioContext; if (!AudioContextClass) return null; audioContext = new AudioContextClass(); } return audioContext; } function playTone() { if (!settings.soundEnabled) return; try { const ctx = getAudioContext(); if (!ctx) return; if (ctx.state === 'suspended') ctx.resume().catch(() => {}); const base = ctx.currentTime + 0.025; [880, 1174].forEach((frequency, index) => { const start = base + index * 0.22; const oscillator = ctx.createOscillator(); const gain = ctx.createGain(); oscillator.type = 'sine'; oscillator.frequency.setValueAtTime(frequency, start); gain.gain.setValueAtTime(0.0001, start); gain.gain.exponentialRampToValueAtTime(0.14, start + 0.025); gain.gain.setValueAtTime(0.14, start + 0.13); gain.gain.exponentialRampToValueAtTime(0.0001, start + 0.19); oscillator.connect(gain); gain.connect(ctx.destination); oscillator.start(start); oscillator.stop(start + 0.2); }); } catch (_) {} } function notifyDesktop(title, body) { if (!settings.notificationsEnabled) return; try { if ('Notification' in window && Notification.permission === 'granted') { new Notification(title, { body, silent: true }); } } catch (_) {} } function alertTask(task) { const state = task.state; if (task.alertedState === state) return; task.alertedState = state; touch(task); saveTasks(); const success = state === 'success'; const title = success ? 'LibTV 生成完成' : 'LibTV 生成失败'; const taskTitle = `${task.siteLabel ? `${task.siteLabel} · ` : ''}${taskName(task)}`; const elapsed = displayedDuration(task); const body = `${taskTitle}\n耗时:${elapsed}`; playTone(); notifyDesktop(title, body); setNotice(`${title}:${taskTitle} · 耗时 ${elapsed}`); } function removeTaskRecords(targets, noticeText = '') { if (!targets || !targets.length) { if (noticeText) setNotice(noticeText); return; } for (const task of targets) { const key = taskStorageId(task); removedTaskKeys.add(key); disconnectNodeObserver(task); } saveRemovedTaskKeys(); tasks = tasks.filter(task => !removedTaskKeys.has(taskStorageId(task))); rebuildTaskIndex(); saveTasks(); render(); if (noticeText) setNotice(noticeText); } function removeOneTask(task) { if (!task) return; removeTaskRecords([task], `已移除记录:${taskName(task)}(不会取消实际生成任务)`); } function clearHistory() { const history = tasks.filter(task => isTerminal(task.state) || task.state === 'unknown'); if (!history.length) { setNotice('没有可清理的历史记录;进行中的任务已保留。'); return; } removeTaskRecords(history, `已清理 ${history.length} 条历史记录;进行中的任务已保留。`); } // 每个页面定期写入心跳,但“心跳过期”仅表示页面可能被冻结,不能作为关闭依据。 // 只有 pagehide 明确报告页面离开且不是进入 BFCache,才会启动关闭确认倒计时。 function writePresenceAndCleanup() { const now = Date.now(); const ownKey = PRESENCE_PREFIX + tabId; const projectName = getCurrentProjectName(); const canvasName = getCurrentCanvasName(); rememberProjectLabel(getProjectIdFromUrl() || currentProjectId, projectName, canvasName); try { // 写入活动状态会清除之前由刷新/导航触发的关闭标记。 localStorage.setItem(ownKey, JSON.stringify({ tabId, lastSeen: now, spaceId: currentSpaceId || getSpaceIdFromUrl() || '', projectId: currentProjectId || getProjectIdFromUrl() || '', projectName, canvasName, pageUrl: location.href, pageUrlKey, closeRequestedAt: 0, bfcacheSuspended: false })); } catch (_) {} if (now - lastAutoCleanupAt < 1800) return; lastAutoCleanupAt = now; const confirmedClosedTabs = new Set(); const confirmedClosedKeys = []; try { for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (!key || !key.startsWith(PRESENCE_PREFIX) || key === ownKey) continue; try { const raw = localStorage.getItem(key); const presence = JSON.parse(raw || '{}'); const closeRequestedAt = Number(presence.closeRequestedAt) || 0; // 不按 lastSeen 超时清理:后台冻结/节流页面可能很久不写心跳。 if (!presence.tabId || !closeRequestedAt || now - closeRequestedAt < PRESENCE_CLOSE_GRACE_MS) continue; // 再读一次,避免把已恢复并重新注册的标签页误删。 const latestRaw = localStorage.getItem(key); if (latestRaw !== raw) continue; const latest = JSON.parse(latestRaw || '{}'); if (String(latest.tabId || '') !== String(presence.tabId) || Number(latest.closeRequestedAt || 0) !== closeRequestedAt || latest.bfcacheSuspended === true) continue; confirmedClosedTabs.add(String(presence.tabId)); confirmedClosedKeys.push({ key, raw }); } catch (_) {} } } catch (_) {} if (!confirmedClosedTabs.size) return; const closedTabTasks = tasks.filter(task => task.sourceTabId && confirmedClosedTabs.has(String(task.sourceTabId))); if (closedTabTasks.length) { removeTaskRecords(closedTabTasks, `已确认 ${confirmedClosedTabs.size} 个页面关闭,清理 ${closedTabTasks.length} 条任务记录。`); } // 只删除仍保留同一关闭标记的 presence;若标签页已重载,则保留其新状态。 for (const item of confirmedClosedKeys) { try { if (localStorage.getItem(item.key) === item.raw) localStorage.removeItem(item.key); } catch (_) {} } render(); } function markPageHide(event) { const now = Date.now(); const key = PRESENCE_PREFIX + tabId; try { const previous = JSON.parse(localStorage.getItem(key) || '{}'); if (event && event.persisted) { // 进入浏览器前进/后退缓存不等于关闭;恢复时 pageshow 会重新登记活动状态。 localStorage.setItem(key, JSON.stringify({ ...previous, tabId, lastSeen: now, bfcacheSuspended: true, closeRequestedAt: 0 })); } else { localStorage.setItem(key, JSON.stringify({ ...previous, tabId, lastSeen: now, pageUrl: location.href, pageUrlKey, bfcacheSuspended: false, closeRequestedAt: now })); } } catch (_) {} } // ---------- 渲染 ---------- function formatTime(value) { if (!value) return '未知'; try { return new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); } catch (_) { return ''; } } function formatDuration(ms) { if (ms == null || !Number.isFinite(ms) || ms < 0) return '—'; const total = Math.floor(ms / 1000); const hours = Math.floor(total / 3600); const minutes = Math.floor((total % 3600) / 60); const seconds = total % 60; const pad = value => String(value).padStart(2, '0'); return hours > 0 ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}` : `${pad(minutes)}:${pad(seconds)}`; } function displayedDuration(task) { if (isTerminal(task.state)) return formatDuration(task.durationMs); if (task.startedAtKnown && task.startedAt) return formatDuration(Date.now() - task.startedAt); return '—'; } function stateLabel(task) { let label = '状态未知'; if (task.state === 'submitting') label = '提交中'; else if (task.state === 'queued') label = '排队中'; else if (task.state === 'running') label = '生成中'; else if (task.state === 'success') label = '已完成'; else if (task.state === 'failed') label = '生成失败'; else if (task.state === 'cancelled') label = '已取消'; else if (task.rawStatus != null) label = `未知状态(${task.rawStatus})`; if (task.needsStatusRefresh && !isTerminal(task.state)) label += ' · 等待更新'; return label; } function currentSiteLabel() { return getPageLabel(); } function buildGroups() { const groups = new Map(); const key = currentSiteKey(); const currentHasIdentity = Boolean(currentSpaceId || currentProjectId); const currentAlreadyRepresented = tasks.some(task => task.pageUrlKey === pageUrlKey && ( keyForTask(task) === key || (!currentHasIdentity && (task.projectId || task.spaceId)) ) ); // 如果刷新后的页面尚未重新识别 spaceId/projectId,而历史任务已存在, // 暂不额外生成一个 URL fallback Tab,避免同一画布看起来重复。 if (currentHasIdentity || !currentAlreadyRepresented) { groups.set(key, { key, label: currentSiteLabel(), projectName: getCurrentProjectName(), canvasName: getCurrentCanvasName(), spaceId: currentSpaceId, projectId: currentProjectId, pageUrl: location.href, latest: Date.now() }); } for (const task of tasks) { const groupKey = keyForTask(task); const existing = groups.get(groupKey); if (!existing) { groups.set(groupKey, { key: groupKey, label: getTaskSiteLabel(task), projectName: task.projectName || '', canvasName: getTaskCanvasName(task), spaceId: task.spaceId || '', projectId: task.projectId || '', pageUrl: task.pageUrl || '', latest: task.createdAt || 0 }); } else if ((task.createdAt || 0) >= existing.latest) { existing.latest = task.createdAt || 0; if (task.projectName) existing.projectName = task.projectName; if (task.canvasName) existing.canvasName = task.canvasName; existing.label = getTaskSiteLabel(task); if (task.spaceId) existing.spaceId = task.spaceId; if (task.projectId) existing.projectId = task.projectId; if (task.pageUrl) existing.pageUrl = task.pageUrl; } } return Array.from(groups.values()).sort((a, b) => { if (a.key === currentSiteKey() && groups.has(currentSiteKey())) return -1; if (b.key === currentSiteKey() && groups.has(currentSiteKey())) return 1; return b.latest - a.latest; }); } function groupTabLabel(group) { if (group.projectName && group.canvasName) return `${normalizeText(group.projectName)}·${normalizeText(group.canvasName)}`; return group.label || '其他 LibTV 页面'; } function visibleTasks() { return selectedSiteKey === '__all__' ? [...tasks] : tasks.filter(task => keyForTask(task) === selectedSiteKey); } function setNotice(message) { if (!shadow) return; const element = shadow.getElementById('notice'); if (!element) return; element.textContent = message; element.hidden = false; if (noticeTimer) clearTimeout(noticeTimer); noticeTimer = setTimeout(() => { if (element) element.hidden = true; noticeTimer = null; }, 7000); } function renderControls() { if (!shadow) return; const key = currentSiteKey(); const connectionsActual = readConnectionsVisible(); const minimapActual = readMinimapVisible(); const connInput = shadow.getElementById('connections-toggle'); const mapInput = shadow.getElementById('minimap-toggle'); if (connInput) { const saved = settings.connectionsBySite[key]; connInput.checked = connectionsActual === null ? saved === true : connectionsActual; } if (mapInput) { const saved = settings.minimapBySite[key]; mapInput.checked = minimapActual === null ? saved === true : minimapActual; } const sound = shadow.getElementById('sound-toggle'); const notify = shadow.getElementById('notify-toggle'); if (sound) sound.checked = settings.soundEnabled; if (notify) notify.checked = settings.notificationsEnabled; const thumbnail = shadow.getElementById('thumbnail-toggle'); if (thumbnail) thumbnail.checked = settings.largeThumbnailsEnabled; const videoDownload = shadow.getElementById('video-download-toggle'); if (videoDownload) videoDownload.checked = settings.persistentVideoDownloadEnabled; const videoPlayback = shadow.getElementById('video-playback-toggle'); if (videoPlayback) videoPlayback.checked = settings.videoPlaybackControlsEnabled; const videoAutoplay = shadow.getElementById('video-autoplay-toggle'); if (videoAutoplay) videoAutoplay.checked = settings.videoAutoplayDisabled; const marks = shadow.getElementById('mark-toggle'); if (marks) marks.checked = settings.nodeMarkingEnabled; const duplicateNaming = shadow.getElementById('duplicate-version-toggle'); if (duplicateNaming) duplicateNaming.checked = settings.duplicateVersionNamingEnabled; const promptSize = shadow.getElementById('prompt-size-toggle'); if (promptSize) promptSize.checked = settings.promptSizeEnabled; const promptPosition = shadow.getElementById('prompt-position-select'); if (promptPosition) promptPosition.value = settings.promptEditorPosition || 'bottom'; const templates = shadow.getElementById('templates-toggle'); if (templates) templates.checked = settings.promptTemplatesEnabled; const promptFind = shadow.getElementById('prompt-find-toggle'); if (promptFind) promptFind.checked = settings.promptSearchReplaceEnabled; const promptSend = shadow.getElementById('prompt-send-toggle'); if (promptSend) promptSend.checked = settings.promptSendButtonEnabled; const stats = shadow.getElementById('stats-toggle'); if (stats) stats.checked = settings.canvasStatsEnabled; const templateButton = shadow.getElementById('prompt-templates'); if (templateButton) templateButton.hidden = !settings.promptTemplatesEnabled; const statsBox = shadow.getElementById('canvas-stats'); if (statsBox) statsBox.hidden = !settings.canvasStatsEnabled; } function renderTabs() { const tabs = shadow && shadow.getElementById('site-tabs'); if (!tabs) return; tabs.replaceChildren(); const groups = buildGroups(); if (!selectedSiteKey) selectedSiteKey = currentSiteKey(); if (selectedSiteKey !== '__all__' && !groups.some(group => group.key === selectedSiteKey)) { selectedSiteKey = groups.some(group => group.key === currentSiteKey()) ? currentSiteKey() : (groups[0] ? groups[0].key : currentSiteKey()); } const all = document.createElement('button'); all.type = 'button'; all.className = `site-tab ${selectedSiteKey === '__all__' ? 'active' : ''}`; all.textContent = '全部'; all.addEventListener('click', () => { selectedSiteKey = '__all__'; userSelectedSite = true; render(); }); tabs.appendChild(all); for (const group of groups) { const button = document.createElement('button'); button.type = 'button'; button.className = `site-tab ${selectedSiteKey === group.key ? 'active' : ''}`; button.textContent = groupTabLabel(group); button.title = `${group.label}${group.spaceId ? `\nspaceId: ${group.spaceId}` : ''}${group.projectId ? `\nprojectId: ${group.projectId}` : ''}${group.pageUrl ? `\n${group.pageUrl}` : ''}`; button.addEventListener('click', () => { selectedSiteKey = group.key; userSelectedSite = true; render(); }); tabs.appendChild(button); } } // ---------- 成功节点耗时 / 积分标签 ---------- const NODE_COST_LABEL_CLASS = 'libtv-task-cost-label'; function injectNodeCostLabelStyle() { if (!document.documentElement || document.getElementById(NODE_COST_STYLE_ID)) return; const style = document.createElement('style'); style.id = NODE_COST_STYLE_ID; style.textContent = ` .react-flow__node[data-libtv-task-cost-enabled="1"]{overflow:visible!important} .react-flow__node .${NODE_COST_LABEL_CLASS}{position:absolute;top:calc(100% + 5px);left:50%;transform:translateX(-50%);z-index:10000;pointer-events:none;white-space:nowrap;display:block;max-width:360px;overflow:hidden;text-overflow:ellipsis;padding:3px 7px;border-radius:5px;background:rgba(13,20,30,.84);border:1px solid rgba(133,173,220,.48);box-shadow:0 2px 8px rgba(0,0,0,.28);color:#e8f2ff;font:600 11px/1.35 system-ui,-apple-system,"Segoe UI",sans-serif;letter-spacing:.1px} `; document.documentElement.appendChild(style); } function humanDuration(ms) { if (ms == null || !Number.isFinite(ms) || ms < 0) return '未知'; const total = Math.floor(ms / 1000); const hours = Math.floor(total / 3600); const minutes = Math.floor((total % 3600) / 60); const seconds = total % 60; if (hours > 0) return `${hours}时${minutes}分${seconds}秒`; if (minutes > 0) return `${minutes}分${seconds}秒`; return `${seconds}秒`; } function currentCanvasTasksForLabels() { if (currentSpaceId) return tasks.filter(task => task.spaceId === currentSpaceId); return tasks.filter(task => task.pageUrlKey === pageUrlKey); } function renderNodeCostLabels() { if (!canvasPageActive || !settings.canvasStatsEnabled || !currentSpaceId) { document.querySelectorAll(`.${NODE_COST_LABEL_CLASS}`).forEach(label => label.remove()); document.querySelectorAll('.react-flow__node[data-libtv-task-cost-enabled="1"]').forEach(node => node.removeAttribute('data-libtv-task-cost-enabled')); return; } injectNodeCostLabelStyle(); const newestSuccessByNode = new Map(); for (const task of currentCanvasTasksForLabels()) { if (task.state !== 'success' || !task.nodeId) continue; const previous = newestSuccessByNode.get(task.nodeId); if (!previous || task.createdAt > previous.createdAt) newestSuccessByNode.set(task.nodeId, task); } const nodeSelector = '.react-flow__node[data-id],.react-flow__node[data-node-id],.react-flow__node[data-nodeid]'; let nodes = []; try { nodes = Array.from(document.querySelectorAll(nodeSelector)); } catch (_) {} for (const node of nodes) { const id = nodeIdFromElement(node); if (!id) continue; const task = newestSuccessByNode.get(id); let label = node.querySelector(`:scope > .${NODE_COST_LABEL_CLASS}`); if (!task) { if (label) label.remove(); node.removeAttribute('data-libtv-task-cost-enabled'); continue; } node.setAttribute('data-libtv-task-cost-enabled', '1'); if (!label) { label = document.createElement('div'); label.className = NODE_COST_LABEL_CLASS; label.setAttribute('aria-hidden', 'true'); node.appendChild(label); } const duration = humanDuration(task.durationMs); const credits = task.costCredits != null && (task.costSource === 'api' || task.costSource === 'api-power') ? Number(task.costCredits).toLocaleString() : '待确认'; const labelText = `耗时 ${duration} · 积分 ${credits}`; if (label.textContent !== labelText) { label.textContent = labelText; label.title = `${taskName(task)}\n${labelText}`; } } } function scheduleNodeCostLabelRender() { if (nodeCostRenderTimer) clearTimeout(nodeCostRenderTimer); nodeCostRenderTimer = setTimeout(() => { nodeCostRenderTimer = null; renderNodeCostLabels(); }, 100); } function ensureNodeCostLabelObserver() { if (!canvasPageActive || !settings.canvasStatsEnabled || !document.documentElement) return; injectNodeCostLabelStyle(); if (nodeCostObserver) return; nodeCostObserver = new MutationObserver(mutations => { let shouldRender = false; const nodeSelector = '.react-flow__node[data-id],.react-flow__node[data-node-id],.react-flow__node[data-nodeid]'; for (const mutation of mutations) { if (mutation.type !== 'childList') continue; const target = mutation.target instanceof Element ? mutation.target : mutation.target && mutation.target.parentElement; // 画布“已聚焦到所选节点”提示不是节点内容,不应触发整画布扫描;本脚本自己的积分标签也忽略。 if (target && target.closest(`[data-canvas-viewport-toast],.${NODE_COST_LABEL_CLASS}`)) continue; const added = Array.from(mutation.addedNodes || []); const removed = Array.from(mutation.removedNodes || []); const elements = added.concat(removed).filter(node => node instanceof Element); const onlyCostLabels = elements.length === added.length + removed.length && elements.length > 0 && elements.every(node => node.matches(`.${NODE_COST_LABEL_CLASS}`) || node.closest(`.${NODE_COST_LABEL_CLASS}`)); if (onlyCostLabels) continue; if (target && target.closest(nodeSelector)) { if (target.closest(`.${NODE_COST_LABEL_CLASS}`)) continue; shouldRender = true; break; } const touchesNode = elements.some(node => !node.closest('[data-canvas-viewport-toast]') && (node.matches(nodeSelector) || !!node.querySelector(nodeSelector)) ); if (touchesNode) { shouldRender = true; break; } } if (shouldRender) scheduleNodeCostLabelRender(); }); nodeCostObserver.observe(document.documentElement, { childList: true, subtree: true }); scheduleNodeCostLabelRender(); } function stopNodeCostLabelObserver() { if (nodeCostObserver) { nodeCostObserver.disconnect(); nodeCostObserver = null; } if (nodeCostRenderTimer) { clearTimeout(nodeCostRenderTimer); nodeCostRenderTimer = null; } renderNodeCostLabels(); } function renderTasks() { const list = shadow && shadow.getElementById('task-list'); const count = shadow && shadow.getElementById('task-count'); if (!list || !count) return; const active = tasks.filter(task => !isTerminal(task.state)).length; count.textContent = active ? `${active} 个进行中` : `${tasks.length} 条记录`; list.replaceChildren(); const items = visibleTasks().sort((a, b) => { const diff = Number(isTerminal(a.state)) - Number(isTerminal(b.state)); return diff || b.createdAt - a.createdAt; }).slice(0, 30); if (!items.length) { const empty = document.createElement('div'); empty.className = 'empty'; empty.textContent = selectedSiteKey === '__all__' ? '暂无任务记录。开始生成后会自动记录。' : '该画布暂无任务记录。'; list.appendChild(empty); return; } for (const task of items) { const card = document.createElement('div'); card.className = `task ${isTerminal(task.state) ? 'terminal' : ''}`; const row = document.createElement('div'); row.className = 'task-first'; const name = document.createElement('div'); name.className = 'task-name'; name.textContent = taskName(task); const status = document.createElement('span'); status.className = `status ${task.state}`; status.textContent = stateLabel(task); row.append(name, status); const details = document.createElement('div'); details.className = 'task-details-row'; const duration = document.createElement('div'); duration.className = 'duration'; duration.textContent = `耗时 ${displayedDuration(task)}${task.state === 'success' && task.costCredits != null && (task.costSource === 'api' || task.costSource === 'api-power') ? ` · 积分 ${Number(task.costCredits).toLocaleString()}` : ''}`; const times = document.createElement('div'); times.className = 'task-meta'; const timeParts = [`开始 ${task.startedAtKnown && task.startedAt ? formatTime(task.startedAt) : '未知'}`]; if (isTerminal(task.state)) timeParts.push(`结束 ${formatTime(task.finishedAt)}`); else if (task.recovered && !task.startedAtKnown) timeParts.push('刷新后恢复,开始时间未知'); times.textContent = timeParts.join(' · '); const actions = document.createElement('div'); actions.className = 'task-actions'; const locate = document.createElement('button'); locate.type = 'button'; locate.className = 'locate'; locate.textContent = '定位'; locate.title = '定位到对应节点'; locate.addEventListener('click', event => { event.stopPropagation(); locateTask(task); }); const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'remove-record'; remove.textContent = '移除'; remove.title = '仅移除监控记录,不会取消实际生成任务'; remove.addEventListener('click', event => { event.stopPropagation(); removeOneTask(task); }); actions.append(locate, remove); details.append(duration, times, actions); card.append(row, details); if (task.errorMessage) { const error = document.createElement('div'); error.className = 'task-error'; error.textContent = task.errorMessage; card.appendChild(error); } card.addEventListener('dblclick', event => { event.preventDefault(); locateTask(task); }); list.appendChild(card); } } function getPromptTemplateControlFromEvent(event) { const path = event && typeof event.composedPath === 'function' ? event.composedPath() : [event && event.target]; for (const item of path) { if (!(item instanceof Element)) continue; if (item.id === 'template-content' || item.id === 'template-name') return item; } return null; } function interceptPromptTemplatePasteShortcut(event) { const control = getPromptTemplateControlFromEvent(event); if (!control || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'v') return; // 不 preventDefault:让浏览器继续发出 paste 事件,再由下方处理器把纯文本直接插入当前模板输入框。 event.stopImmediatePropagation(); event.stopPropagation(); } function interceptPromptTemplatePaste(event) { const control = getPromptTemplateControlFromEvent(event); if (!control || !(control instanceof HTMLInputElement || control instanceof HTMLTextAreaElement)) return; let text = ''; try { text = event.clipboardData ? event.clipboardData.getData('text/plain') : ''; } catch (_) {} if (typeof text !== 'string') return; event.preventDefault(); event.stopImmediatePropagation(); event.stopPropagation(); const start = Number.isInteger(control.selectionStart) ? control.selectionStart : control.value.length; const end = Number.isInteger(control.selectionEnd) ? control.selectionEnd : start; try { control.setRangeText(text, start, end, 'end'); } catch (_) { control.value = control.value.slice(0, start) + text + control.value.slice(end); } try { control.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, inputType: 'insertFromPaste', data: text })); } catch (_) { control.dispatchEvent(new Event('input', { bubbles: true, composed: true })); } } function loadPromptTemplates() { try { const data = JSON.parse(localStorage.getItem(PROMPT_TEMPLATES_KEY) || '[]'); promptTemplates = Array.isArray(data) ? data.filter(item => item && typeof item.name === 'string' && typeof item.content === 'string').slice(0, 200) : []; } catch (_) { promptTemplates = []; } } function savePromptTemplates() { try { localStorage.setItem(PROMPT_TEMPLATES_KEY, JSON.stringify(promptTemplates)); } catch (_) {} } function promptEditorSelector() { return '.node-floating-ui [data-generator-card] [contenteditable="true"][role="textbox"][aria-multiline="true"], [data-generator-card] [contenteditable="true"][role="textbox"][aria-multiline="true"]'; } function readPromptEditor(editor) { if (!editor) return ''; return safeString(editor.innerText || editor.textContent).replace(/\u00a0/g, ' '); } function findPromptEditor() { if (lastPromptEditor && lastPromptEditor.isConnected && isVisibleElement(lastPromptEditor)) return lastPromptEditor; let editors = []; try { editors = Array.from(document.querySelectorAll(promptEditorSelector())).filter(isVisibleElement); } catch (_) {} if (!editors.length) return null; editors.sort((a, b) => { const ar = a.getBoundingClientRect(); const br = b.getBoundingClientRect(); return (br.width * br.height) - (ar.width * ar.height); }); lastPromptEditor = editors[0]; return lastPromptEditor; } function rememberPromptEditor(event) { const target = event && event.target; if (!(target instanceof Element)) return; const editor = target.matches && target.matches(promptEditorSelector()) ? target : (target.closest ? target.closest(promptEditorSelector()) : null); if (editor) lastPromptEditor = editor; } function applyPromptTemplate(content, mode = 'replace') { const editor = findPromptEditor(); if (!editor) { setNotice('没有找到当前可用的节点提示词输入框,请先展开节点生成器。'); return; } const text = safeString(content); try { editor.focus({ preventScroll: true }); const selection = window.getSelection(); const range = document.createRange(); if (mode === 'append') { range.selectNodeContents(editor); range.collapse(false); } else { range.selectNodeContents(editor); } selection.removeAllRanges(); selection.addRange(range); const insertion = mode === 'append' ? `\n${text}` : text; let inserted = false; try { inserted = document.execCommand('insertText', false, insertion); } catch (_) {} if (!inserted) { // 回退方案使用 Range 插入文本节点,不用 textContent 覆盖整个编辑器,避免丢失素材引用标签。 const activeSelection = window.getSelection(); let insertRange = activeSelection && activeSelection.rangeCount ? activeSelection.getRangeAt(0) : null; if (!insertRange || !editor.contains(insertRange.commonAncestorContainer)) { insertRange = document.createRange(); insertRange.selectNodeContents(editor); insertRange.collapse(mode !== 'append'); } insertRange.deleteContents(); const fragment = document.createDocumentFragment(); const lines = insertion.split('\n'); lines.forEach((line, index) => { if (index) fragment.appendChild(document.createElement('br')); // 非断行空格用来保留连续空格的视觉效果;读取文本时会还原为空格。 const chunks = line.split(/( {2,})/); for (const chunk of chunks) { if (!chunk) continue; fragment.appendChild(document.createTextNode(/^ {2,}$/.test(chunk) ? chunk.replace(/ /g, '\u00a0') : chunk)); } }); const lastInserted = fragment.lastChild; insertRange.insertNode(fragment); if (activeSelection) { const caret = document.createRange(); if (lastInserted && lastInserted.parentNode) { caret.setStartAfter(lastInserted); caret.collapse(true); } else { caret.selectNodeContents(editor); caret.collapse(false); } activeSelection.removeAllRanges(); activeSelection.addRange(caret); } } try { editor.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: insertion })); } catch (_) { editor.dispatchEvent(new Event('input', { bubbles: true })); } editor.dispatchEvent(new Event('change', { bubbles: true })); lastPromptEditor = editor; setNotice(mode === 'append' ? '模板已追加到当前提示词末尾。' : '模板已替换当前提示词。请检查特殊素材引用是否符合预期。'); } catch (_) { setNotice('无法自动写入当前提示词框。可使用模板行的“复制”按钮手动粘贴。'); } } function resetPromptTemplateEditor() { editingPromptTemplateId = ''; const nameInput = shadow && shadow.getElementById('template-name'); const contentInput = shadow && shadow.getElementById('template-content'); const saveButton = shadow && shadow.getElementById('template-save'); const cancelButton = shadow && shadow.getElementById('template-cancel-edit'); if (nameInput) nameInput.value = ''; if (contentInput) contentInput.value = ''; if (saveButton) saveButton.textContent = '保存模板'; if (cancelButton) cancelButton.hidden = true; } function renderPromptTemplateList() { const list = shadow && shadow.getElementById('template-list'); if (!list) return; list.replaceChildren(); loadPromptTemplates(); if (!promptTemplates.length) { const empty = document.createElement('div'); empty.className = 'template-empty'; empty.textContent = '还没有模板。可以先在节点中写好常用提示词,再点击“读取当前提示词”并保存。'; list.appendChild(empty); return; } for (const item of promptTemplates) { const row = document.createElement('div'); row.className = 'template-row'; const title = document.createElement('div'); title.className = 'template-row-title'; title.textContent = item.name; const content = document.createElement('div'); content.className = 'template-row-content'; content.textContent = item.content; const actions = document.createElement('div'); actions.className = 'template-row-actions'; const makeButton = (label, handler, danger = false) => { const button = document.createElement('button'); button.type = 'button'; button.textContent = label; if (danger) { button.style.color = '#ffcfca'; button.style.borderColor = '#69484a'; } button.addEventListener('click', handler); return button; }; actions.append( makeButton('编辑', () => { editingPromptTemplateId = item.id; shadow.getElementById('template-name').value = item.name; shadow.getElementById('template-content').value = item.content; shadow.getElementById('template-save').textContent = '保存修改'; shadow.getElementById('template-cancel-edit').hidden = false; shadow.getElementById('template-name').focus(); setNotice(`正在编辑模板:${item.name}`); }), makeButton('替换提示词', () => applyPromptTemplate(item.content, 'replace')), makeButton('追加到末尾', () => applyPromptTemplate(item.content, 'append')), makeButton('复制', () => { try { navigator.clipboard.writeText(item.content).then(() => setNotice('模板已复制。')).catch(() => setNotice('复制失败,请手动选择模板内容。')); } catch (_) { setNotice('浏览器不允许自动复制,请手动复制。'); } }), makeButton('删除', () => { promptTemplates = promptTemplates.filter(entry => entry.id !== item.id); if (editingPromptTemplateId === item.id) resetPromptTemplateEditor(); savePromptTemplates(); renderPromptTemplateList(); setNotice('模板已删除。'); }, true) ); row.append(title, content, actions); list.appendChild(row); } } const PROMPT_SEARCH_STYLE_ID = 'libtv-task-monitor-prompt-search-style'; const PROMPT_SEARCH_TOOLBAR_CLASS = 'libtv-prompt-search-replace-toolbar'; function promptTextNodes(editor) { const result = []; if (!editor) return result; const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT, { acceptNode(node) { if (!node.nodeValue) return NodeFilter.FILTER_REJECT; const parent = node.parentElement; if (!parent || parent.closest('[contenteditable="false"],.libtv-prompt-search-replace-toolbar')) return NodeFilter.FILTER_REJECT; return NodeFilter.FILTER_ACCEPT; } }); let node; while ((node = walker.nextNode())) result.push(node); return result; } function promptMatches(editor, needle, caseSensitive) { if (!needle) return []; const matches = []; const query = caseSensitive ? needle : needle.toLocaleLowerCase(); for (const node of promptTextNodes(editor)) { const text = node.nodeValue || ''; const haystack = caseSensitive ? text : text.toLocaleLowerCase(); let from = 0; while (from <= haystack.length - query.length) { const index = haystack.indexOf(query, from); if (index < 0) break; matches.push({ node, start: index, end: index + query.length }); from = index + Math.max(1, query.length); } } return matches; } const PROMPT_SEARCH_HIGHLIGHT_ALL = 'libtv-prompt-search-all'; const PROMPT_SEARCH_HIGHLIGHT_CURRENT = 'libtv-prompt-search-current'; function clearPromptSearchHighlights() { if (typeof CSS === 'undefined' || !CSS.highlights) return; try { CSS.highlights.delete(PROMPT_SEARCH_HIGHLIGHT_ALL); } catch (_) {} try { CSS.highlights.delete(PROMPT_SEARCH_HIGHLIGHT_CURRENT); } catch (_) {} } function applyPromptSearchHighlights(matches, currentIndex = -1) { clearPromptSearchHighlights(); if (typeof CSS === 'undefined' || !CSS.highlights || typeof Highlight !== 'function' || !matches.length) return; try { const all = new Highlight(); for (const match of matches) { const range = document.createRange(); range.setStart(match.node, match.start); range.setEnd(match.node, match.end); all.add(range); } CSS.highlights.set(PROMPT_SEARCH_HIGHLIGHT_ALL, all); if (currentIndex >= 0 && currentIndex < matches.length) { const match = matches[currentIndex]; const range = document.createRange(); range.setStart(match.node, match.start); range.setEnd(match.node, match.end); CSS.highlights.set(PROMPT_SEARCH_HIGHLIGHT_CURRENT, new Highlight(range)); } } catch (_) {} } function updatePromptSearchStatus(toolbar, matches = [], currentIndex = -1) { const status = toolbar.querySelector('[data-role="status"]'); if (!status) return; const findInput = toolbar.querySelector('[data-role="find"]'); const query = findInput ? findInput.value : ''; if (!query) { status.textContent = ''; return; } if (!matches.length) { status.textContent = '0 处'; return; } status.textContent = currentIndex >= 0 ? `${currentIndex + 1}/${matches.length}` : `共 ${matches.length} 处`; } function refreshPromptSearchHighlights(toolbar) { const editor = editorForSearchToolbar(toolbar); const findInput = toolbar.querySelector('[data-role="find"]'); const needle = findInput ? findInput.value : ''; toolbar.dataset.matchIndex = '-1'; toolbar._lastMatch = null; if (!editor || !needle) { clearPromptSearchHighlights(); updatePromptSearchStatus(toolbar, [], -1); return []; } const matches = promptMatches(editor, needle, false); applyPromptSearchHighlights(matches, -1); updatePromptSearchStatus(toolbar, matches, -1); return matches; } function scrollPromptSearchMatchIntoView(range, editor) { if (!range || !range.startContainer) return; const textParent = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement; if (!textParent) return; // 从文本节点往上找真正的滚动祖先,LibTV 提示词通常用 Mantine ScrollArea viewport。 const containers = []; let el = textParent; while (el && el !== document.body && el !== document.documentElement) { let style = null; try { style = getComputedStyle(el); } catch (_) {} if (style && /(auto|scroll|overlay)/.test(style.overflowY) && el.scrollHeight > el.clientHeight + 2) { containers.push(el); } el = el.parentElement; } if (editor && !containers.includes(editor) && editor.scrollHeight > editor.clientHeight + 2) { containers.unshift(editor); } if (!containers.length) return; // 内层先滚;每滚一层重新读取 Range 坐标,避免外层用旧位置。 for (const container of containers) { const rect = range.getBoundingClientRect(); if (!rect || (!rect.height && !rect.width)) continue; const containerRect = container.getBoundingClientRect(); const target = container.scrollTop + (rect.top - containerRect.top) - Math.max(8, (container.clientHeight - Math.min(rect.height, container.clientHeight)) / 2); const max = Math.max(0, container.scrollHeight - container.clientHeight); const next = Math.max(0, Math.min(max, target)); if (Math.abs(next - container.scrollTop) > 1) container.scrollTop = next; } } function selectPromptSearchMatch(editor, matches, index, toolbar) { const match = matches[index]; if (!match) return; editor.focus({ preventScroll: true }); const range = document.createRange(); range.setStart(match.node, match.start); range.setEnd(match.node, match.end); const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); applyPromptSearchHighlights(matches, index); updatePromptSearchStatus(toolbar, matches, index); scrollPromptSearchMatchIntoView(range, editor); toolbar._lastMatch = match; } function dispatchPromptInput(editor, text = '') { lastPromptEditor = editor; try { editor.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertReplacementText', data: text })); } catch (_) { editor.dispatchEvent(new Event('input', { bubbles: true })); } editor.dispatchEvent(new Event('change', { bubbles: true })); } function editorForSearchToolbar(toolbar) { const generator = toolbar.closest('[data-quick-guide-anchor="generator-prompt"]'); if (generator) { const editor = generator.querySelector(promptEditorSelector()); if (editor && isVisibleElement(editor)) return editor; } return findPromptEditor(); } function runPromptSearch(toolbar, action) { const editor = editorForSearchToolbar(toolbar); if (!editor) { setNotice('没有找到关联的提示词编辑框。'); return; } const findInput = toolbar.querySelector('[data-role="find"]'); const replaceInput = toolbar.querySelector('[data-role="replace"]'); const needle = findInput ? findInput.value : ''; const replacement = replaceInput ? replaceInput.value : ''; if (!needle) { clearPromptSearchHighlights(); updatePromptSearchStatus(toolbar, [], -1); setNotice('请先输入要查找的文本。'); return; } const matches = promptMatches(editor, needle, false); if (!matches.length) { clearPromptSearchHighlights(); updatePromptSearchStatus(toolbar, [], -1); setNotice('没有找到匹配文本。'); return; } if (action === 'find' || action === 'next' || action === 'prev') { let current = Number(toolbar.dataset.matchIndex); if (!Number.isFinite(current)) current = -1; let index; if (action === 'prev') { index = current <= -1 ? matches.length - 1 : current - 1; if (index < 0) index = matches.length - 1; } else { index = current < 0 ? 0 : current + 1; if (index >= matches.length) index = 0; } toolbar.dataset.matchIndex = String(index); selectPromptSearchMatch(editor, matches, index, toolbar); setNotice(`第 ${index + 1}/${matches.length} 处匹配。`); return; } if (action === 'replace-one') { let match = toolbar._lastMatch; const current = Number(toolbar.dataset.matchIndex); if ((!match || !match.node.isConnected || !editor.contains(match.node)) && current >= 0 && current < matches.length) { match = matches[current]; } if (!match || !match.node.isConnected || !editor.contains(match.node)) { setNotice('请先点击“上一个”或“下一个”定位匹配。'); return; } const value = match.node.nodeValue || ''; if (value.slice(match.start, match.end).toLocaleLowerCase() !== needle.toLocaleLowerCase()) { toolbar._lastMatch = null; setNotice('匹配位置已变化,请重新查找。'); return; } match.node.nodeValue = value.slice(0, match.start) + replacement + value.slice(match.end); dispatchPromptInput(editor, replacement); toolbar._lastMatch = null; toolbar.dataset.matchIndex = '-1'; refreshPromptSearchHighlights(toolbar); setNotice('已替换当前匹配。'); return; } if (action === 'replace-all') { let count = 0; for (const node of promptTextNodes(editor)) { const source = node.nodeValue || ''; const lowerSource = source.toLocaleLowerCase(); const lowerNeedle = needle.toLocaleLowerCase(); if (!lowerSource.includes(lowerNeedle)) continue; let out = ''; let cursor = 0; while (cursor < source.length) { const index = lowerSource.indexOf(lowerNeedle, cursor); if (index < 0) { out += source.slice(cursor); break; } out += source.slice(cursor, index) + replacement; cursor = index + needle.length; count++; } node.nodeValue = out; } dispatchPromptInput(editor, replacement); toolbar._lastMatch = null; toolbar.dataset.matchIndex = '-1'; clearPromptSearchHighlights(); updatePromptSearchStatus(toolbar, [], -1); setNotice(`全部替换完成,共替换 ${count} 处。`); } } function ensurePromptSearchStyle() { if (document.getElementById(PROMPT_SEARCH_STYLE_ID)) return; const style = document.createElement('style'); style.id = PROMPT_SEARCH_STYLE_ID; style.textContent = ` .node-floating-ui [data-quick-guide-anchor="generator-prompt"]{overflow:visible!important;min-width:0} .${PROMPT_SEARCH_TOOLBAR_CLASS}{display:flex;flex-wrap:wrap;align-items:center;gap:4px;margin:5px 0 1px;padding:5px;border:1px solid rgba(130,145,165,.35);border-radius:7px;background:rgba(18,24,34,.92);color:#e9eef7;font:11px/1.3 system-ui,sans-serif;position:relative;z-index:30} .${PROMPT_SEARCH_TOOLBAR_CLASS}[hidden]{display:none!important} .${PROMPT_SEARCH_TOOLBAR_CLASS} input{box-sizing:border-box;min-width:70px;width:clamp(70px,14vw,150px);height:27px;padding:4px 7px;border:1px solid rgba(130,145,165,.48);border-radius:5px;background:rgba(255,255,255,.06);color:inherit;font:11px/1.3 system-ui,sans-serif;outline:none} .${PROMPT_SEARCH_TOOLBAR_CLASS} input:focus{border-color:#65aee8;box-shadow:0 0 0 1px rgba(101,174,232,.2)} .${PROMPT_SEARCH_TOOLBAR_CLASS} button{height:27px;padding:3px 7px;border:1px solid rgba(130,145,165,.42);border-radius:5px;background:rgba(255,255,255,.08);color:inherit;font:11px/1.2 system-ui,sans-serif;white-space:nowrap;cursor:pointer} .${PROMPT_SEARCH_TOOLBAR_CLASS} button:hover{background:rgba(255,255,255,.16)} .${PROMPT_SEARCH_TOOLBAR_CLASS} [data-role="status"]{min-width:42px;padding-left:2px;color:#8fd0ff;font-size:10px;line-height:1.2;text-align:center;white-space:nowrap} ::highlight(${PROMPT_SEARCH_HIGHLIGHT_ALL}){background-color:rgba(255,206,69,.42);color:inherit} ::highlight(${PROMPT_SEARCH_HIGHLIGHT_CURRENT}){background-color:#ffb52e;color:#111} `; (document.head || document.documentElement).appendChild(style); } function installPromptSearchReplace() { if (!document.documentElement) return; if (!settings.promptSearchReplaceEnabled || !canvasPageActive) { document.querySelectorAll('.' + PROMPT_SEARCH_TOOLBAR_CLASS).forEach(el => el.remove()); clearPromptSearchHighlights(); return; } ensurePromptSearchStyle(); const anchors = document.querySelectorAll('[data-quick-guide-anchor="generator-prompt"]'); for (const anchor of anchors) { if (!anchor.querySelector(promptEditorSelector()) || anchor.querySelector('.' + PROMPT_SEARCH_TOOLBAR_CLASS)) continue; const toolbar = document.createElement('div'); toolbar.className = PROMPT_SEARCH_TOOLBAR_CLASS; toolbar.innerHTML = ''; toolbar.hidden = true; toolbar.setAttribute('aria-hidden', 'true'); toolbar.addEventListener('click', event => { const button = event.target.closest('button[data-action]'); if (!button) return; event.preventDefault(); event.stopPropagation(); if (button.dataset.action === 'close') { toolbar.hidden = true; toolbar.setAttribute('aria-hidden', 'true'); clearPromptSearchHighlights(); updatePromptSearchStatus(toolbar, [], -1); return; } runPromptSearch(toolbar, button.dataset.action); }); toolbar.addEventListener('input', event => { if (event.target.matches('[data-role="find"]')) refreshPromptSearchHighlights(toolbar); }); toolbar.addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); toolbar.hidden = true; toolbar.setAttribute('aria-hidden', 'true'); clearPromptSearchHighlights(); updatePromptSearchStatus(toolbar, [], -1); return; } if (event.key === 'Enter' && event.target.matches('[data-role="find"]')) { event.preventDefault(); event.stopPropagation(); runPromptSearch(toolbar, event.shiftKey ? 'prev' : 'next'); } }); anchor.appendChild(toolbar); } } function onPromptFindShortcut(event) { if (!settings.promptSearchReplaceEnabled || !canvasPageActive || !event.ctrlKey || event.altKey || event.metaKey || event.shiftKey || safeString(event.key).toLowerCase() !== 'f') return; if (!(event.target instanceof Element)) return; const editor = event.target.matches(promptEditorSelector()) ? event.target : event.target.closest(promptEditorSelector()); if (!editor || !editor.isConnected) return; const active = document.activeElement; if (!(active === editor || (active instanceof Element && editor.contains(active)))) return; const anchor = editor.closest('[data-quick-guide-anchor="generator-prompt"]'); if (!anchor) return; if (!anchor.querySelector('.' + PROMPT_SEARCH_TOOLBAR_CLASS)) installPromptSearchReplace(); const toolbar = anchor.querySelector('.' + PROMPT_SEARCH_TOOLBAR_CLASS); if (!toolbar) return; // 只在提示词编辑器获得焦点时接管 Ctrl+F;画布空白处和节点上的 Ctrl+F 原样交给 LibTV。 event.preventDefault(); event.stopPropagation(); const opening = toolbar.hidden; toolbar.hidden = !opening; toolbar.setAttribute('aria-hidden', opening ? 'false' : 'true'); if (opening) { refreshPromptSearchHighlights(toolbar); const findInput = toolbar.querySelector('[data-role="find"]'); if (findInput) { findInput.focus(); try { findInput.select(); } catch (_) {} } } else { clearPromptSearchHighlights(); updatePromptSearchStatus(toolbar, [], -1); } } const PROMPT_SEND_STYLE_ID = 'libtv-task-monitor-prompt-send-style'; const PROMPT_SEND_BUTTON_ATTR = 'data-libtv-task-monitor-prompt-send'; function ensurePromptSendStyle() { if (document.getElementById(PROMPT_SEND_STYLE_ID)) return; const style = document.createElement('style'); style.id = PROMPT_SEND_STYLE_ID; style.textContent = ` button[${PROMPT_SEND_BUTTON_ATTR}="1"]{display:inline-flex;align-items:center;justify-content:center;gap:5px;min-height:27px;margin:0 2px 0 4px;padding:4px 12px;border:1px solid rgba(117,177,228,.68);border-radius:999px;background:rgba(54,127,186,.22);color:var(--color-text, #e8f4ff);font:600 12px/1.2 system-ui,sans-serif;cursor:pointer;white-space:nowrap;transition:background 140ms ease,border-color 140ms ease,transform 140ms ease} button[${PROMPT_SEND_BUTTON_ATTR}="1"]:hover{background:rgba(54,127,186,.4);border-color:rgba(145,205,255,.9)} button[${PROMPT_SEND_BUTTON_ATTR}="1"]:active{transform:translateY(1px)} button[${PROMPT_SEND_BUTTON_ATTR}="1"]:disabled{opacity:.45;cursor:not-allowed} `; (document.head || document.documentElement).appendChild(style); } function installPromptSendButtons(root = document) { if (!document.documentElement) return; if (!settings.promptSendButtonEnabled || !canvasPageActive) { document.querySelectorAll('[' + PROMPT_SEND_BUTTON_ATTR + '="1"]').forEach(button => button.remove()); const style = document.getElementById(PROMPT_SEND_STYLE_ID); if (style) style.remove(); return; } ensurePromptSendStyle(); const chips = []; if (root instanceof Element && root.matches('[data-generator-action-chips]')) chips.push(root); if (root && root.querySelectorAll) chips.push(...root.querySelectorAll('[data-generator-action-chips]')); if (root === document) chips.push(...document.querySelectorAll('[data-generator-action-chips]')); for (const chipRow of new Set(chips)) { if (!chipRow.isConnected) continue; if (chipRow.querySelector('[' + PROMPT_SEND_BUTTON_ATTR + '="1"]')) { installPromptPositionMenu(chipRow); continue; } const button = document.createElement('button'); button.type = 'button'; button.textContent = '发送 ↗'; button.title = '使用此节点的原生发送按钮提交任务;原有发送按钮仍保留'; button.setAttribute(PROMPT_SEND_BUTTON_ATTR, '1'); button.setAttribute('aria-label', '快捷发送当前节点的生成任务'); button.addEventListener('pointerdown', event => { event.preventDefault(); event.stopPropagation(); }); button.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); const card = chipRow.closest('[data-generator-card]') || chipRow.closest('.node-floating-ui'); const submit = card && card.querySelector('button[data-quick-guide-anchor="generator-submit"],button[data-practice-anchor="gen.submit"]'); if (!submit) { setNotice('未找到此节点的原生发送按钮,请展开生成器后重试。'); return; } if (submit.disabled || submit.getAttribute('aria-disabled') === 'true') { setNotice('当前节点暂时不能发送,请检查提示词或参数。'); return; } submit.click(); }); chipRow.appendChild(button); installPromptPositionMenu(chipRow); } } const PROMPT_POSITION_BUTTON_ATTR = 'data-libtv-task-monitor-prompt-position'; const PROMPT_POSITION_MENU_ATTR = 'data-libtv-task-monitor-prompt-position-menu'; function installPromptPositionMenu(chipRow) { if (!chipRow || !chipRow.isConnected || chipRow.querySelector('[' + PROMPT_POSITION_BUTTON_ATTR + '="1"]')) return; const button = document.createElement('button'); button.type = 'button'; button.textContent = '位置 ▾'; button.title = '设置提示词输入框位置'; button.setAttribute(PROMPT_POSITION_BUTTON_ATTR, '1'); button.style.cssText = 'display:inline-flex;align-items:center;justify-content:center;min-height:27px;margin:0 2px 0 4px;padding:4px 10px;border:1px solid rgba(170,180,198,.45);border-radius:999px;background:rgba(90,100,118,.18);color:var(--color-text,#e8f4ff);font:400 12px/1.2 system-ui,sans-serif;cursor:pointer;white-space:nowrap;'; button.addEventListener('pointerdown', event => { event.preventDefault(); event.stopPropagation(); }); button.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); document.querySelectorAll('[' + PROMPT_POSITION_MENU_ATTR + '="1"]').forEach(menu => menu.remove()); const menu = document.createElement('div'); menu.setAttribute(PROMPT_POSITION_MENU_ATTR, '1'); menu.style.cssText = 'position:absolute;z-index:2147483002;right:0;bottom:calc(100% + 8px);display:flex;flex-direction:column;gap:3px;min-width:142px;padding:6px;border:1px solid var(--canvas-controls-border,rgba(255,255,255,.2));border-radius:10px;background:var(--canvas-controls-bg,#20242c);box-shadow:0 8px 26px rgba(0,0,0,.35);'; const options = [['left','左侧'],['right','右侧'],['top','上侧'],['bottom','默认'],['free','自由移动']]; for (const [value, label] of options) { const item = document.createElement('button'); item.type = 'button'; item.textContent = (settings.promptEditorPosition === value ? '✓ ' : '') + label; item.style.cssText = 'text-align:left;padding:7px 9px;border:0;border-radius:6px;background:transparent;color:var(--canvas-controls-text,#f4f6fa);font:400 12px/1.3 system-ui,sans-serif;cursor:pointer;'; item.addEventListener('mouseenter', () => { item.style.background = 'var(--canvas-controls-hover,rgba(255,255,255,.1))'; }); item.addEventListener('mouseleave', () => { item.style.background = 'transparent'; }); item.addEventListener('click', ev => { ev.preventDefault(); ev.stopPropagation(); settings.promptEditorPosition = value; saveSettings(); applyPromptEditorPosition(); menu.remove(); button.textContent = `位置:${label} ▾`; setNotice(({left:'提示词输入框已移至左侧。',right:'提示词输入框已移至右侧。',top:'提示词输入框已移至上侧。',bottom:'提示词输入框已恢复默认位置。',free:'已开启自由移动模式,可拖动提示词框顶部把手。'})[value]); }); menu.appendChild(item); } const wrap = document.createElement('span'); wrap.style.cssText = 'position:relative;display:inline-flex;align-items:center;'; button.replaceWith(wrap); wrap.append(button, menu); const close = ev => { if (!wrap.contains(ev.target)) { menu.remove(); document.removeEventListener('pointerdown', close, true); } }; setTimeout(() => document.addEventListener('pointerdown', close, true), 0); }); // 与用户新增的“发送”按钮相邻,插在它后面。 const send = chipRow.querySelector('[' + PROMPT_SEND_BUTTON_ATTR + '="1"]'); if (send) send.insertAdjacentElement('afterend', button); else chipRow.appendChild(button); } function applyPromptSearchReplacePreference() { installPromptSearchReplace(); } function renderCanvasStats() { const target = shadow && shadow.getElementById('canvas-stats'); if (!target) return; const items = visibleTasks(); const completed = items.filter(task => task.state === 'success').length; const failed = items.filter(task => task.state === 'failed').length; const durationValues = items.map(task => { if (task.durationMs != null && Number.isFinite(task.durationMs)) return task.durationMs; if (!isTerminal(task.state) && task.startedAtKnown && task.startedAt) return Math.max(0, Date.now() - task.startedAt); return null; }).filter(value => value != null); const durationSum = durationValues.reduce((sum, value) => sum + value, 0); const completedDurations = items.filter(task => isTerminal(task.state) && task.durationMs != null && Number.isFinite(task.durationMs)); const avg = completedDurations.length ? completedDurations.reduce((sum, task) => sum + task.durationMs, 0) / completedDurations.length : null; // 只累计已成功任务的接口积分;失败任务、运行中的任务和 UI 标价估算一律不纳入总分。 const apiCosts = items.filter(task => task.state === 'success' && task.costCredits != null && (task.costSource === 'api' || task.costSource === 'api-power')); const apiSum = apiCosts.reduce((sum, task) => sum + task.costCredits, 0); const creditsText = apiCosts.length ? `成功任务实际积分 ${apiSum.toLocaleString()}(已确认 ${apiCosts.length}/${completed} 个成功任务)` : `成功任务实际积分 暂无接口数据(${completed} 个成功任务)`; target.innerHTML = `任务 ${items.length} 条 · 成功 ${completed} · 失败 ${failed}
${creditsText}
累计耗时 ${formatDuration(durationSum)} · 平均耗时 ${avg == null ? '—' : formatDuration(avg)}`; } function render() { if (!shadow) return; renderTabs(); renderTasks(); renderControls(); renderCanvasStats(); scheduleNodeCostLabelRender(); } function switchMarkup(id, label, checked, title) { return ``; } function mountPanel() { if (host || !document.documentElement) return; host = document.createElement('div'); host.id = 'libtv-task-monitor-host-v6'; host.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:2147483647;pointer-events:none;'; shadow = host.attachShadow({ mode: 'open' }); shadow.innerHTML = `
LibTV 任务监控0 条记录
`; document.documentElement.appendChild(host); const panel = shadow.getElementById('panel'); const mini = shadow.getElementById('mini'); // 窗口级捕获优先阻止 LibTV 画布处理 Ctrl+V;控件自身再注册一层,兼容不穿透 Shadow DOM 的粘贴事件。 for (const control of [shadow.getElementById('template-content'), shadow.getElementById('template-name')]) { if (!control) continue; control.addEventListener('keydown', interceptPromptTemplatePasteShortcut, true); control.addEventListener('paste', interceptPromptTemplatePaste, true); } // 提示音和桌面通知的开关都是全局默认开启;首次与面板交互时,借用户手势申请通知权限。 panel.addEventListener('pointerdown', () => { if (settings.soundEnabled) { try { const ctx = getAudioContext(); if (ctx && ctx.state === 'suspended') ctx.resume().catch(() => {}); } catch (_) {} } if (permissionPromptAttempted || !settings.notificationsEnabled || !('Notification' in window) || Notification.permission !== 'default') return; permissionPromptAttempted = true; try { Notification.requestPermission().then(permission => { if (permission === 'granted') setNotice('桌面通知权限已开启。'); else if (permission === 'denied') setNotice('浏览器已阻止桌面通知,请在网站权限中允许。'); else setNotice('尚未获得桌面通知权限。'); }).catch(() => setNotice('无法申请桌面通知权限,请检查浏览器网站设置。')); } catch (_) { setNotice('无法申请桌面通知权限,请检查浏览器网站设置。'); } }, { once: true }); mini.addEventListener('click', event => { event.stopPropagation(); panel.classList.toggle('mini'); mini.textContent = panel.classList.contains('mini') ? '+' : '−'; }); const settingsToggle = shadow.getElementById('settings-toggle'); const settingsPanel = shadow.getElementById('settings-panel'); settingsToggle.addEventListener('click', event => { event.stopPropagation(); settingsPanel.hidden = !settingsPanel.hidden; settingsToggle.setAttribute('aria-expanded', settingsPanel.hidden ? 'false' : 'true'); settingsToggle.textContent = settingsPanel.hidden ? '设置 ▾' : '设置 ▴'; }); shadow.getElementById('clear-history').addEventListener('click', event => { event.stopPropagation(); clearHistory(); }); shadow.getElementById('prompt-templates').addEventListener('click', event => { event.stopPropagation(); loadPromptTemplates(); renderPromptTemplateList(); if (!settings.promptTemplatesEnabled) return; shadow.getElementById('template-modal').hidden = false; }); shadow.getElementById('template-close').addEventListener('click', () => { shadow.getElementById('template-modal').hidden = true; }); // 提示词库作为独立浮窗使用:点击外部不关闭,按标题栏自由拖动。 const templateDialog = shadow.getElementById('template-modal').querySelector('.template-dialog'); const templateHead = shadow.getElementById('template-modal').querySelector('.template-head'); const saveTemplateDialogLayout = () => { try { const rect = templateDialog.getBoundingClientRect(); localStorage.setItem(PROMPT_TEMPLATE_LAYOUT_KEY, JSON.stringify({ width: rect.width, height: rect.height, left: rect.left, top: rect.top })); } catch (_) {} }; try { const savedLayout = JSON.parse(localStorage.getItem(PROMPT_TEMPLATE_LAYOUT_KEY) || 'null'); if (savedLayout && typeof savedLayout === 'object') { const width = Number(savedLayout.width), height = Number(savedLayout.height), left = Number(savedLayout.left), top = Number(savedLayout.top); if (Number.isFinite(width) && width >= 300) templateDialog.style.width = `${Math.min(width, window.innerWidth - 12)}px`; if (Number.isFinite(height) && height >= 240) templateDialog.style.height = `${Math.min(height, window.innerHeight - 12)}px`; if (Number.isFinite(left)) templateDialog.style.left = `${Math.max(0, Math.min(window.innerWidth - templateDialog.offsetWidth, left))}px`; if (Number.isFinite(top)) templateDialog.style.top = `${Math.max(0, Math.min(window.innerHeight - templateDialog.offsetHeight, top))}px`; } } catch (_) {} let templateDrag = null; templateHead.addEventListener('pointerdown', event => { if (event.target.closest('button') || event.button !== 0) return; const rect = templateDialog.getBoundingClientRect(); templateDrag = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, left: rect.left, top: rect.top }; try { templateHead.setPointerCapture(event.pointerId); } catch (_) {} event.preventDefault(); }); templateHead.addEventListener('pointermove', event => { if (!templateDrag || templateDrag.pointerId !== event.pointerId) return; const maxLeft = Math.max(0, window.innerWidth - templateDialog.offsetWidth); const maxTop = Math.max(0, window.innerHeight - templateDialog.offsetHeight); templateDialog.style.left = `${Math.max(0, Math.min(maxLeft, templateDrag.left + event.clientX - templateDrag.x))}px`; templateDialog.style.top = `${Math.max(0, Math.min(maxTop, templateDrag.top + event.clientY - templateDrag.y))}px`; }); const stopTemplateDrag = event => { if (!templateDrag || (event.pointerId != null && event.pointerId !== templateDrag.pointerId)) return; templateDrag = null; saveTemplateDialogLayout(); }; templateHead.addEventListener('pointerup', stopTemplateDrag); templateHead.addEventListener('pointercancel', stopTemplateDrag); // 提示词模板库八方向缩放,宽高和位置均以视口像素计算。 const templateResizeHandles = shadow.querySelectorAll('.template-resize-handle[data-template-resize]'); templateResizeHandles.forEach(handle => { let resize = null; handle.addEventListener('pointerdown', event => { if (event.button !== 0) return; const rect = templateDialog.getBoundingClientRect(); resize = { pointerId: event.pointerId, edge: handle.dataset.templateResize, x: event.clientX, y: event.clientY, width: rect.width, height: rect.height, left: rect.left, top: rect.top }; try { handle.setPointerCapture(event.pointerId); } catch (_) {} event.preventDefault(); event.stopPropagation(); }); handle.addEventListener('pointermove', event => { if (!resize || resize.pointerId !== event.pointerId) return; const st = resize, dx = event.clientX - st.x, dy = event.clientY - st.y; const west = st.edge.includes('w'), east = st.edge.includes('e'), north = st.edge.includes('n'), south = st.edge.includes('s'); const minW = Math.min(460, Math.max(280, window.innerWidth - 20)); const minH = Math.min(420, Math.max(240, window.innerHeight - 20)); const maxW = Math.max(minW, window.innerWidth - 12), maxH = Math.max(minH, window.innerHeight - 12); const width = Math.max(minW, Math.min(maxW, west ? st.width - dx : east ? st.width + dx : st.width)); const height = Math.max(minH, Math.min(maxH, north ? st.height - dy : south ? st.height + dy : st.height)); const left = Math.max(0, Math.min(window.innerWidth - width, st.left + (west ? st.width - width : 0))); const top = Math.max(0, Math.min(window.innerHeight - height, st.top + (north ? st.height - height : 0))); templateDialog.style.width = `${width}px`; templateDialog.style.height = `${height}px`; templateDialog.style.left = `${left}px`; templateDialog.style.top = `${top}px`; event.preventDefault(); event.stopPropagation(); }); const stop = event => { if (!resize || (event.pointerId != null && resize.pointerId !== event.pointerId)) return; resize = null; saveTemplateDialogLayout(); }; handle.addEventListener('pointerup', stop); handle.addEventListener('pointercancel', stop); handle.addEventListener('lostpointercapture', stop); }); shadow.getElementById('template-read-current').addEventListener('click', () => { const editor = findPromptEditor(); if (!editor) { setNotice('请先打开一个节点的提示词编辑框。'); return; } shadow.getElementById('template-content').value = readPromptEditor(editor); if (!shadow.getElementById('template-name').value.trim()) shadow.getElementById('template-name').value = `提示词模板 ${promptTemplates.length + 1}`; setNotice('已读取当前节点提示词;引用素材会以可见文字保存,不保留特殊引用对象。'); }); shadow.getElementById('template-cancel-edit').addEventListener('click', () => { resetPromptTemplateEditor(); setNotice('已取消模板编辑。'); }); shadow.getElementById('template-save').addEventListener('click', () => { const name = shadow.getElementById('template-name').value.trim(); const content = shadow.getElementById('template-content').value; if (!name || !content.trim()) { setNotice('请填写模板名称和提示词内容。'); return; } const editing = editingPromptTemplateId ? promptTemplates.find(item => item.id === editingPromptTemplateId) : null; const duplicate = promptTemplates.find(item => item.name.toLowerCase() === name.toLowerCase() && item.id !== editingPromptTemplateId); if (editing && duplicate) { setNotice('已有其他模板使用这个名称,请换一个名称。'); return; } if (editing) { editing.name = name; editing.content = content; editing.updatedAt = Date.now(); savePromptTemplates(); resetPromptTemplateEditor(); renderPromptTemplateList(); setNotice('提示词模板已修改并保存。'); return; } const existing = duplicate; if (existing) { existing.content = content; existing.updatedAt = Date.now(); } else promptTemplates.unshift({ id: `tpl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`, name, content, createdAt: Date.now(), updatedAt: Date.now() }); promptTemplates = promptTemplates.slice(0, 200); savePromptTemplates(); resetPromptTemplateEditor(); renderPromptTemplateList(); setNotice(existing ? '已更新同名提示词模板。' : '提示词模板已保存。'); }); shadow.getElementById('sound-toggle').addEventListener('change', async event => { settings.soundEnabled = event.currentTarget.checked; saveSettings(); if (settings.soundEnabled) { const ctx = getAudioContext(); if (ctx && ctx.state === 'suspended') { try { await ctx.resume(); } catch (_) {} } setNotice('完成提示音已开启。'); } else setNotice('完成提示音已关闭。'); }); shadow.getElementById('notify-toggle').addEventListener('change', async event => { const input = event.currentTarget; if (!input.checked) { settings.notificationsEnabled = false; saveSettings(); setNotice('桌面通知已关闭。'); return; } if (!('Notification' in window)) { settings.notificationsEnabled = false; input.checked = false; saveSettings(); setNotice('当前浏览器不支持桌面通知。'); return; } try { let permission = Notification.permission; if (permission !== 'granted' && permission !== 'denied') permission = await Notification.requestPermission(); if (permission === 'granted') { settings.notificationsEnabled = true; saveSettings(); setNotice('桌面通知已开启。'); } else { settings.notificationsEnabled = false; input.checked = false; saveSettings(); setNotice(permission === 'denied' ? '浏览器已阻止桌面通知,请在网站权限中允许。' : '未获得桌面通知权限。'); } } catch (_) { settings.notificationsEnabled = false; input.checked = false; saveSettings(); setNotice('无法启用桌面通知。'); } }); shadow.getElementById('thumbnail-toggle').addEventListener('change', event => { settings.largeThumbnailsEnabled = event.currentTarget.checked; saveSettings(); applyThumbnailPreference(); setNotice(settings.largeThumbnailsEnabled ? '大尺寸高清悬浮预览已开启;小缩略图仍保持 50px。' : '大尺寸高清悬浮预览已关闭。'); }); shadow.getElementById('video-download-toggle').addEventListener('change', event => { settings.persistentVideoDownloadEnabled = event.currentTarget.checked; saveSettings(); installPersistentVideoDownloadButtons(document); setNotice(settings.persistentVideoDownloadEnabled ? '视频节点常驻下载按钮已开启。' : '视频节点常驻下载按钮已关闭。'); }); shadow.getElementById('video-playback-toggle').addEventListener('change', event => { settings.videoPlaybackControlsEnabled = event.currentTarget.checked; saveSettings(); if (!settings.videoPlaybackControlsEnabled) stopVideoPlaybackSpeedHold(); installVideoPlaybackControls(document); setNotice(settings.videoPlaybackControlsEnabled ? '视频界面修改已开启。' : '视频界面修改已关闭。'); }); shadow.getElementById('video-autoplay-toggle').addEventListener('change', event => { settings.videoAutoplayDisabled = event.currentTarget.checked; saveSettings(); installVideoPlaybackControls(document); setNotice(settings.videoAutoplayDisabled ? '视频自动播放已禁止。' : '已恢复视频原本的自动播放设置。'); }); shadow.getElementById('connections-toggle').addEventListener('change', event => { applyNativeControl('connections', event.currentTarget.checked, { persist: true, userInitiated: true }); }); shadow.getElementById('minimap-toggle').addEventListener('change', event => { applyNativeControl('minimap', event.currentTarget.checked, { persist: true, userInitiated: true }); }); shadow.getElementById('mark-toggle').addEventListener('change', event => { settings.nodeMarkingEnabled = event.currentTarget.checked; saveSettings(); installNodeMarking(); setNotice(settings.nodeMarkingEnabled ? '节点分类标签已开启。' : '节点分类标签已关闭。'); }); shadow.getElementById('duplicate-version-toggle').addEventListener('change', event => { settings.duplicateVersionNamingEnabled = event.currentTarget.checked; saveSettings(); installDuplicateVersionNaming(); setNotice(settings.duplicateVersionNamingEnabled ? '复制副本自动版本命名已开启。' : '复制副本自动版本命名已关闭。'); }); shadow.getElementById('prompt-size-toggle').addEventListener('change', event => { settings.promptSizeEnabled = event.currentTarget.checked; saveSettings(); injectPromptSizeEnhancement(); enhancePromptEditorUIs(); setNotice(settings.promptSizeEnabled ? '提示词编辑区域可调整大小;可拖动四边与四角缩放。' : '提示词编辑区域已恢复页面默认尺寸。'); }); shadow.getElementById('prompt-position-select').addEventListener('change', event => { settings.promptEditorPosition = ['bottom', 'top', 'left', 'right', 'free'].includes(event.currentTarget.value) ? event.currentTarget.value : 'bottom'; saveSettings(); applyPromptEditorPosition(); setNotice(({ bottom: '提示词输入框将显示在节点下方。', top: '提示词输入框将显示在节点上方。', left: '提示词输入框将显示在节点左侧。', right: '提示词输入框将显示在节点右侧。', free: '已开启自由浮动模式,可拖动提示词框顶部的小把手自由移动。' })[settings.promptEditorPosition]); }); shadow.getElementById('templates-toggle').addEventListener('change', event => { settings.promptTemplatesEnabled = event.currentTarget.checked; saveSettings(); const button = shadow.getElementById('prompt-templates'); const modal = shadow.getElementById('template-modal'); if (button) button.hidden = !settings.promptTemplatesEnabled; if (!settings.promptTemplatesEnabled && modal) modal.hidden = true; setNotice(settings.promptTemplatesEnabled ? '提示词模板库已开启。' : '提示词模板库已关闭。'); }); shadow.getElementById('prompt-find-toggle').addEventListener('change', event => { settings.promptSearchReplaceEnabled = event.currentTarget.checked; saveSettings(); applyPromptSearchReplacePreference(); setNotice(settings.promptSearchReplaceEnabled ? '提示词搜索替换已开启;提示词编辑区内按 Ctrl+F 可切换工具栏。' : '提示词搜索替换已关闭。'); }); shadow.getElementById('prompt-send-toggle').addEventListener('change', event => { settings.promptSendButtonEnabled = event.currentTarget.checked; saveSettings(); installPromptSendButtons(); setNotice(settings.promptSendButtonEnabled ? '提示词快捷发送按钮已开启。' : '提示词快捷发送按钮已关闭。'); }); shadow.getElementById('stats-toggle').addEventListener('change', event => { settings.canvasStatsEnabled = event.currentTarget.checked; saveSettings(); const stats = shadow.getElementById('canvas-stats'); if (stats) stats.hidden = !settings.canvasStatsEnabled; if (settings.canvasStatsEnabled) ensureNodeCostLabelObserver(); else stopNodeCostLabelObserver(); scheduleNodeCostLabelRender(); setNotice(settings.canvasStatsEnabled ? '画布成本统计已开启(包含节点耗时与积分标签)。' : '画布成本统计已关闭。'); }); const dragbar = shadow.getElementById('dragbar'); let dragState = null; dragbar.addEventListener('pointerdown', event => { if (event.target && event.target.closest && event.target.closest('button')) return; dragState = { pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, left: parseFloat(host.style.left || '16px'), bottom: parseFloat(host.style.bottom || '16px') }; try { dragbar.setPointerCapture(event.pointerId); } catch (_) {} event.preventDefault(); }); dragbar.addEventListener('pointermove', event => { if (!dragState || dragState.pointerId !== event.pointerId) return; host.style.left = `${Math.max(0, dragState.left + (event.clientX - dragState.startX))}px`; host.style.bottom = `${Math.max(0, dragState.bottom - (event.clientY - dragState.startY))}px`; }); const stopDrag = event => { if (!dragState || (event && event.pointerId !== undefined && dragState.pointerId !== event.pointerId)) return; dragState = null; }; dragbar.addEventListener('pointerup', stopDrag); dragbar.addEventListener('pointercancel', stopDrag); // 八方向拖拽缩放:四条边与四个角均可操作。宽高由面板本身控制,内容区域用 flex 自适应。 const resizeHandles = shadow.querySelectorAll('.resize-handle[data-resize]'); const clamp = (value, min, max) => Math.max(min, Math.min(max, value)); resizeHandles.forEach(handle => { let resizeState = null; handle.addEventListener('pointerdown', event => { if (panel.classList.contains('mini') || event.button !== 0) return; const rect = panel.getBoundingClientRect(); resizeState = { pointerId: event.pointerId, edge: handle.dataset.resize, x: event.clientX, y: event.clientY, width: rect.width, height: rect.height, left: parseFloat(host.style.left || '16px'), bottom: parseFloat(host.style.bottom || '16px') }; try { handle.setPointerCapture(event.pointerId); } catch (_) {} event.preventDefault(); event.stopPropagation(); }); handle.addEventListener('pointermove', event => { if (!resizeState || resizeState.pointerId !== event.pointerId) return; const st = resizeState; const dx = event.clientX - st.x; const dy = event.clientY - st.y; const hasWest = st.edge.includes('w'); const hasEast = st.edge.includes('e'); const hasNorth = st.edge.includes('n'); const hasSouth = st.edge.includes('s'); const maxWidth = Math.max(290, Math.min(window.innerWidth * 0.94, 1200)); const maxHeight = Math.max(220, Math.min(window.innerHeight * 0.90, 1000)); const nextWidth = hasWest ? st.width - dx : hasEast ? st.width + dx : st.width; const nextHeight = hasNorth ? st.height - dy : hasSouth ? st.height + dy : st.height; const width = clamp(nextWidth, 290, maxWidth); const height = clamp(nextHeight, 220, maxHeight); panel.style.width = `${width}px`; panel.style.height = `${height}px`; // 面板锚定左下角:拖左边时移动 left 以固定右边;拖上边时固定 bottom;拖下边时移动 bottom 以固定上边。 host.style.left = `${Math.max(0, st.left + (hasWest ? st.width - width : 0))}px`; host.style.bottom = `${Math.max(0, st.bottom - (hasSouth ? height - st.height : 0))}px`; event.preventDefault(); }); const finishResize = event => { if (!resizeState || (event && event.pointerId !== undefined && resizeState.pointerId !== event.pointerId)) return; resizeState = null; }; handle.addEventListener('pointerup', finishResize); handle.addEventListener('pointercancel', finishResize); handle.addEventListener('lostpointercapture', finishResize); }); render(); scheduleControlRestore(); } // 画布节点里的小缩略图保持原始 w_50 和 48px;悬浮后,仅放大匹配的预览弹层,并请求 w_800 高清图。 const THUMBNAIL_CONTAINER_SELECTOR = 'div.group.relative.size-12.flex-none.cursor-pointer'; const THUMBNAIL_EXCLUDED_AREA_SELECTOR = '.mantine-Drawer-body'; const UPLOAD_IMAGE_SELECTOR = 'img[src*="libtv-res.liblib.art/upload-images/"], img[srcset*="libtv-res.liblib.art/upload-images/"], img[data-libtv-task-monitor-original-src*="libtv-res.liblib.art/upload-images/"], img[data-libtv-task-monitor-preview-original-src*="libtv-res.liblib.art/upload-images/"]'; const THUMBNAIL_IMG_SELECTOR = `${THUMBNAIL_CONTAINER_SELECTOR} img[src*="libtv-res.liblib.art/upload-images/"]`; const THUMBNAIL_ORIGINAL_ATTR = 'data-libtv-task-monitor-original-src'; const PREVIEW_ORIGINAL_ATTR = 'data-libtv-task-monitor-preview-original-src'; const PREVIEW_ORIGINAL_SRCSET_ATTR = 'data-libtv-task-monitor-preview-original-srcset'; const PREVIEW_SOURCE_ORIGINAL_SRCSET_ATTR = 'data-libtv-task-monitor-preview-source-original-srcset'; const PREVIEW_CONTEXT_SELECTOR = [ '[role="dialog"]', '[aria-modal="true"]', '[role="tooltip"]', '.mantine-Popover-dropdown', '.mantine-Modal-content', '.mantine-Modal-root', '.mantine-HoverCard-dropdown', '[data-floating-ui-portal]', '[data-radix-popper-content-wrapper]', '[data-popper-placement]', '[data-state="open"]' ].join(','); // 放大时优先标记真正的悬浮卡片/弹层,避免误改 48px 的节点缩略图。 const PREVIEW_ROOT_SELECTOR = [ '.mantine-HoverCard-dropdown', '.mantine-Popover-dropdown', '[data-popper-placement]', '[data-radix-popper-content-wrapper]', '[role="tooltip"]', '[role="dialog"]', '[aria-modal="true"]', '.mantine-Modal-content', '.mantine-Modal-root' ].join(','); const PREVIEW_TARGET_TTL_MS = 20000; const PREVIEW_STYLE_ID = 'libtv-task-monitor-preview-size-style'; const PREVIEW_ROOT_ATTR = 'data-libtv-task-monitor-large-preview-root'; const PREVIEW_WRAPPER_ATTR = 'data-libtv-task-monitor-large-preview-wrapper'; const PREVIEW_IMAGE_ATTR = 'data-libtv-task-monitor-large-preview-image'; let thumbnailObserver = null; let thumbnailObserverStopTimer = null; let thumbnailScanTimers = []; let thumbnailHandlersInstalled = false; let lastHoveredThumbnail = null; function ensurePreviewSizeStyle() { if (!document.documentElement || document.getElementById(PREVIEW_STYLE_ID)) return; const style = document.createElement('style'); style.id = PREVIEW_STYLE_ID; style.textContent = ` /* 悬浮卡片柔和淡入;不设置 transform,避免覆盖浮层库用于定位的 transform。 */ @keyframes libtvTaskMonitorPreviewFadeIn { from { opacity: .15; } to { opacity: 1; } } @keyframes libtvTaskMonitorPreviewImageIn { from { opacity: .78; filter: blur(.7px); } to { opacity: 1; filter: blur(0); } } /* 仅作用于与最近悬浮节点图片匹配的预览弹层,不影响画布上的 50px 小图。 */ [${PREVIEW_ROOT_ATTR}="1"] { box-sizing: border-box !important; width: max-content !important; min-width: 0 !important; max-width: min(680px, 78vw) !important; height: auto !important; max-height: 82vh !important; overflow: visible !important; animation: libtvTaskMonitorPreviewFadeIn 190ms cubic-bezier(.22,.8,.25,1) both !important; transition: opacity 190ms cubic-bezier(.22,.8,.25,1), max-width 220ms cubic-bezier(.22,.8,.25,1) !important; will-change: opacity; } [${PREVIEW_WRAPPER_ATTR}="1"] { box-sizing: border-box !important; width: auto !important; min-width: 0 !important; max-width: min(680px, 78vw) !important; height: auto !important; max-height: 82vh !important; overflow: visible !important; transition: width 220ms cubic-bezier(.22,.8,.25,1), height 220ms cubic-bezier(.22,.8,.25,1), max-width 220ms cubic-bezier(.22,.8,.25,1), max-height 220ms cubic-bezier(.22,.8,.25,1) !important; } img[${PREVIEW_IMAGE_ATTR}="1"] { display: block !important; box-sizing: border-box !important; width: min(640px, 72vw) !important; height: auto !important; min-width: 0 !important; max-width: min(640px, 72vw) !important; max-height: 72vh !important; object-fit: contain !important; flex: 0 0 auto !important; animation: libtvTaskMonitorPreviewImageIn 230ms cubic-bezier(.22,.8,.25,1) both !important; transition: opacity 200ms ease-out, max-width 220ms cubic-bezier(.22,.8,.25,1), filter 200ms ease-out !important; will-change: opacity, filter; } @media (prefers-reduced-motion: reduce) { [${PREVIEW_ROOT_ATTR}="1"], img[${PREVIEW_IMAGE_ATTR}="1"] { animation: none !important; transition: none !important; } } `; document.documentElement.appendChild(style); } function isInThumbnailExcludedArea(element) { try { return !!(element && element.closest && element.closest(THUMBNAIL_EXCLUDED_AREA_SELECTOR)); } catch (_) { return false; } } function findPreviewRoot(img) { if (isInThumbnailExcludedArea(img)) return null; if (!(img instanceof HTMLImageElement)) return null; let root = img.closest(PREVIEW_ROOT_SELECTOR); if (root) return root; // 不同版本的页面可能不会给弹层添加 role/class;退回查找图片外层的定位容器。 let node = img.parentElement; while (node && node !== document.body && node !== document.documentElement) { let computed = null; try { computed = window.getComputedStyle(node); } catch (_) {} if (computed && (computed.position === 'fixed' || computed.position === 'absolute')) return node; node = node.parentElement; } return img.parentElement; } function expandPreviewDisplay(img) { if (!(img instanceof HTMLImageElement) || isInThumbnailExcludedArea(img) || isThumbnailTrigger(img)) return; ensurePreviewSizeStyle(); const root = findPreviewRoot(img); if (!root || root === document.body || root === document.documentElement) { img.setAttribute(PREVIEW_IMAGE_ATTR, '1'); return; } root.setAttribute(PREVIEW_ROOT_ATTR, '1'); img.setAttribute(PREVIEW_IMAGE_ATTR, '1'); let parent = img.parentElement; while (parent && parent !== root) { parent.setAttribute(PREVIEW_WRAPPER_ATTR, '1'); parent = parent.parentElement; } } function clearPreviewDisplayMarks() { if (!document.documentElement) return; document.querySelectorAll( `[${PREVIEW_ROOT_ATTR}], [${PREVIEW_WRAPPER_ATTR}], [${PREVIEW_IMAGE_ATTR}]` ).forEach(element => { element.removeAttribute(PREVIEW_ROOT_ATTR); element.removeAttribute(PREVIEW_WRAPPER_ATTR); element.removeAttribute(PREVIEW_IMAGE_ATTR); }); } function force800InOssProcess(url) { // 处理 OSS 图片样式,例如 resize,w_50,m_lfit 或 resize,m_lfit,w_50。 // 不依赖 w_ 在 resize 后紧跟出现,避免不同参数顺序时漏改。 return safeString(url).replace(/resize,([^/?#&\s]+)/ig, (match, options) => { const parts = options.split(',').filter(Boolean); const widthIndex = parts.findIndex(part => /^w_\d+$/i.test(part)); if (widthIndex >= 0) parts[widthIndex] = 'w_800'; else parts.unshift('w_800'); return 'resize,' + parts.join(','); }); } function largeThumbnailUrl(url) { // 固定请求 w_800;保留 OSS 同一 resize 操作的其他参数及后续 format 等操作。 return force800InOssProcess(url); } function largeThumbnailSrcset(srcset) { // 在整个 srcset 字符串中逐个修改 OSS resize 参数,避免按逗号拆分 URL 时破坏含逗号的查询参数。 return force800InOssProcess(srcset); } function applyPictureSourceResolution(img, enabled) { if (!(img instanceof HTMLImageElement)) return; const picture = img.closest('picture'); if (!picture) return; picture.querySelectorAll('source[srcset], source[' + PREVIEW_SOURCE_ORIGINAL_SRCSET_ATTR + ']').forEach(source => { const current = source.getAttribute('srcset') || ''; const stored = source.getAttribute(PREVIEW_SOURCE_ORIGINAL_SRCSET_ATTR); const storedUpgrade = stored !== null ? largeThumbnailSrcset(stored) : null; const storedStillApplies = stored !== null && (current === stored || current === storedUpgrade); if (!enabled) { if (stored !== null) { // React 若已把 source 复用为另一张图,不要把旧图 URL 错误恢复上去。 if (storedStillApplies) { if (stored) source.setAttribute('srcset', stored); else source.removeAttribute('srcset'); } source.removeAttribute(PREVIEW_SOURCE_ORIGINAL_SRCSET_ATTR); } return; } if (!lastHoveredThumbnail || Date.now() - lastHoveredThumbnail.time > PREVIEW_TARGET_TTL_MS) { if (stored === null) return; } // 当 React 把 picture 复用于另一张图片时,以新的 srcset 作为新原图,而不是沿用旧缓存。 const original = storedStillApplies ? stored : current; if (!original) return; if (stored !== original) source.setAttribute(PREVIEW_SOURCE_ORIGINAL_SRCSET_ATTR, original); const desired = largeThumbnailSrcset(original); if (desired !== current) source.setAttribute('srcset', desired); }); } function uploadImageKey(url) { try { const parsed = new URL(safeString(url), location.href); return parsed.pathname.includes('/upload-images/') ? parsed.pathname : ''; } catch (_) { return ''; } } function getImageRawUrl(img) { return img && (img.getAttribute('src') || img.src) || ''; } function getOriginalImageUrl(img, attrName) { const raw = getImageRawUrl(img); const stored = img.getAttribute(attrName); if (stored !== null) { if (raw === stored || raw === largeThumbnailUrl(stored)) return stored; } return raw; } function isThumbnailTrigger(img) { return !!(img && img.closest && img.closest(THUMBNAIL_CONTAINER_SELECTOR)); } function keepThumbnailSmall(img) { if (!(img instanceof HTMLImageElement) || isInThumbnailExcludedArea(img) || !isThumbnailTrigger(img)) return; const raw = getImageRawUrl(img); if (!uploadImageKey(raw) && !img.hasAttribute(THUMBNAIL_ORIGINAL_ATTR)) return; const original = getOriginalImageUrl(img, THUMBNAIL_ORIGINAL_ATTR); if (!original) return; if (img.getAttribute(THUMBNAIL_ORIGINAL_ATTR) !== original) { img.setAttribute(THUMBNAIL_ORIGINAL_ATTR, original); } // 小图无论开关状态都使用页面原始 URL(通常为 w_50)。 if (getImageRawUrl(img) !== original) img.setAttribute('src', original); } function isLikelyPreviewImage(img) { if (!(img instanceof HTMLImageElement) || isInThumbnailExcludedArea(img) || isThumbnailTrigger(img)) return false; const rect = img.getBoundingClientRect(); const isLargeEnough = rect.width >= 72 || rect.height >= 72; const isPopupContent = !!(img.closest && img.closest(PREVIEW_CONTEXT_SELECTOR)); return isPopupContent || isLargeEnough; } function applyPreviewImage(img) { if (!(img instanceof HTMLImageElement) || isInThumbnailExcludedArea(img) || isThumbnailTrigger(img)) return; const raw = getImageRawUrl(img); const stored = img.getAttribute(PREVIEW_ORIGINAL_ATTR); const original = stored !== null ? getOriginalImageUrl(img, PREVIEW_ORIGINAL_ATTR) : raw; if (!settings.largeThumbnailsEnabled) { // 关闭开关时,恢复 img 与 picture/source 的原始 srcset。 if (stored !== null && raw !== original) img.setAttribute('src', original); const savedSrcset = img.getAttribute(PREVIEW_ORIGINAL_SRCSET_ATTR); if (savedSrcset !== null) { if (savedSrcset) img.setAttribute('srcset', savedSrcset); else img.removeAttribute('srcset'); img.removeAttribute(PREVIEW_ORIGINAL_SRCSET_ATTR); } applyPictureSourceResolution(img, false); img.removeAttribute(PREVIEW_IMAGE_ATTR); return; } const hasRecentTarget = !!lastHoveredThumbnail && Date.now() - lastHoveredThumbnail.time <= PREVIEW_TARGET_TTL_MS; const candidateKey = uploadImageKey(original) || uploadImageKey(raw); const matchesRecentTarget = hasRecentTarget && candidateKey === lastHoveredThumbnail.key; // 已标记的预览图即使打开超过 TTL,切换开关时也能继续处理;新图则必须匹配最近悬浮的节点。 if (!candidateKey || (!matchesRecentTarget && stored === null) || !isLikelyPreviewImage(img)) return; // React 若复用同一个 img 展示另一张图,丢弃旧图保存的 srcset,重新记录当前值。 if (stored !== null && original !== stored) img.removeAttribute(PREVIEW_ORIGINAL_SRCSET_ATTR); if (img.getAttribute(PREVIEW_ORIGINAL_ATTR) !== original) { img.setAttribute(PREVIEW_ORIGINAL_ATTR, original); } if (!img.hasAttribute(PREVIEW_ORIGINAL_SRCSET_ATTR)) { img.setAttribute(PREVIEW_ORIGINAL_SRCSET_ATTR, img.getAttribute('srcset') || ''); } // 不只处理 img.src:如果 img 带 srcset,也将其中 OSS 候选地址全部提升到 w_800。 // 否则浏览器仍可能挑选低分辨率候选资源。 const imgSrcset = img.getAttribute('srcset'); if (imgSrcset) { const desiredSrcset = largeThumbnailSrcset(imgSrcset); if (desiredSrcset !== imgSrcset) img.setAttribute('srcset', desiredSrcset); } // picture 内的 source[srcset] 优先级可能高于 img.src;同步提升这些候选地址。 applyPictureSourceResolution(img, true); // 同时提升资源分辨率并放大弹层;悬浮前的小缩略图始终使用原始 w_50。 expandPreviewDisplay(img); const desired = largeThumbnailUrl(original); if (desired !== raw) img.setAttribute('src', desired); } function handleUploadImage(img) { if (!(img instanceof HTMLImageElement) || isInThumbnailExcludedArea(img)) return; if (isThumbnailTrigger(img)) { keepThumbnailSmall(img); return; } applyPreviewImage(img); } function upgradeThumbnailTree(root) { if (!root || isInThumbnailExcludedArea(root)) return; if (root.nodeType === Node.ELEMENT_NODE) { if (root instanceof HTMLImageElement && (root.matches(UPLOAD_IMAGE_SELECTOR) || root.hasAttribute(PREVIEW_ORIGINAL_ATTR))) { handleUploadImage(root); } if (root.querySelectorAll) root.querySelectorAll(UPLOAD_IMAGE_SELECTOR).forEach(handleUploadImage); } else if (root.querySelectorAll) { root.querySelectorAll(UPLOAD_IMAGE_SELECTOR).forEach(handleUploadImage); } } function stopThumbnailObserver() { if (thumbnailObserverStopTimer) { clearTimeout(thumbnailObserverStopTimer); thumbnailObserverStopTimer = null; } if (thumbnailObserver) { thumbnailObserver.disconnect(); thumbnailObserver = null; } } function scanForHoveredPreview() { if (!document.documentElement || !lastHoveredThumbnail || Date.now() - lastHoveredThumbnail.time > PREVIEW_TARGET_TTL_MS) return; // 只查询匹配的图片元素,不再递归遍历整棵画布 DOM 树。 const images = document.querySelectorAll(UPLOAD_IMAGE_SELECTOR); for (const img of images) { if (!(img instanceof HTMLImageElement) || isInThumbnailExcludedArea(img)) continue; if (isThumbnailTrigger(img)) { keepThumbnailSmall(img); continue; } const raw = getImageRawUrl(img); const stored = img.getAttribute(PREVIEW_ORIGINAL_ATTR); const original = stored !== null ? getOriginalImageUrl(img, PREVIEW_ORIGINAL_ATTR) : raw; const candidateKey = uploadImageKey(original) || uploadImageKey(raw); if (candidateKey === lastHoveredThumbnail.key || stored !== null) handleUploadImage(img); } } function scheduleThumbnailScans() { for (const timer of thumbnailScanTimers) clearTimeout(timer); thumbnailScanTimers = []; // 弹层挂载通常很快,少量延迟扫描即可覆盖 React / portal 的异步挂载。 for (const delay of [80, 220, 500, 900, 1400]) { thumbnailScanTimers.push(setTimeout(() => { scanForHoveredPreview(); }, delay)); } } function beginShortThumbnailObserver() { if (!document.documentElement) return; stopThumbnailObserver(); thumbnailObserver = new MutationObserver(mutations => { if (!lastHoveredThumbnail || Date.now() - lastHoveredThumbnail.time > 2600) return; // 限制单次回调处理量,避免画布批量挂载/滚动时同步处理海量 DOM 变更。 const limit = Math.min(mutations.length, 120); let addedRootsHandled = 0; for (let i = 0; i < limit; i++) { const mutation = mutations[i]; if (mutation.type === 'attributes') { const target = mutation.target; if (target instanceof HTMLImageElement) { if (isInThumbnailExcludedArea(target)) continue; const raw = getImageRawUrl(target); const stored = target.getAttribute(PREVIEW_ORIGINAL_ATTR); const original = stored !== null ? getOriginalImageUrl(target, PREVIEW_ORIGINAL_ATTR) : raw; if (isThumbnailTrigger(target) || uploadImageKey(original) === lastHoveredThumbnail.key || stored !== null) { handleUploadImage(target); } } else if (target instanceof HTMLSourceElement) { if (isInThumbnailExcludedArea(target)) continue; const picture = target.closest('picture'); const pictureImg = picture && picture.querySelector('img'); if (pictureImg) { const raw = getImageRawUrl(pictureImg); const stored = pictureImg.getAttribute(PREVIEW_ORIGINAL_ATTR); const original = stored !== null ? getOriginalImageUrl(pictureImg, PREVIEW_ORIGINAL_ATTR) : raw; if (uploadImageKey(original) === lastHoveredThumbnail.key || stored !== null) handleUploadImage(pictureImg); } } continue; } for (const node of mutation.addedNodes || []) { if (addedRootsHandled >= 24) break; if (!(node instanceof Element) || isInThumbnailExcludedArea(node) || node.matches(THUMBNAIL_EXCLUDED_AREA_SELECTOR)) continue; // 避免对每一个新增子节点重复扫描;只处理图像本身、含图像的新增容器。 if (node.matches(UPLOAD_IMAGE_SELECTOR) || node.matches(THUMBNAIL_CONTAINER_SELECTOR) || node.querySelector(UPLOAD_IMAGE_SELECTOR)) { upgradeThumbnailTree(node); addedRootsHandled++; } } } }); thumbnailObserver.observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ['src', 'srcset'] }); // 核心改变:观察器仅在用户悬浮缩略图后短暂开启,不再永久监听整页。 thumbnailObserverStopTimer = setTimeout(stopThumbnailObserver, 1800); } function rememberHoveredThumbnail(event) { const target = event.target; if (!(target instanceof Element) || isInThumbnailExcludedArea(target)) return; const container = target.closest(THUMBNAIL_CONTAINER_SELECTOR); if (!container) return; // 鼠标在同一缩略图内部经过子元素时,不重复启动扫描与观察器。 if (event.relatedTarget instanceof Node && container.contains(event.relatedTarget)) return; const img = container.querySelector('img[src*="libtv-res.liblib.art/upload-images/"], img[data-libtv-task-monitor-original-src*="libtv-res.liblib.art/upload-images/"]'); if (!img) return; const original = getOriginalImageUrl(img, THUMBNAIL_ORIGINAL_ATTR); const key = uploadImageKey(original || getImageRawUrl(img)); if (!key) return; if (lastHoveredThumbnail && lastHoveredThumbnail.key === key && Date.now() - lastHoveredThumbnail.time < 1600) return; lastHoveredThumbnail = { key, time: Date.now() }; scheduleThumbnailScans(); beginShortThumbnailObserver(); } function applyThumbnailPreference() { if (!document.documentElement) return; ensurePreviewSizeStyle(); document.querySelectorAll(THUMBNAIL_IMG_SELECTOR + ', img[' + THUMBNAIL_ORIGINAL_ATTR + '], img[' + PREVIEW_ORIGINAL_ATTR + ']').forEach(img => { if (isThumbnailTrigger(img)) keepThumbnailSmall(img); else applyPreviewImage(img); }); if (!settings.largeThumbnailsEnabled) clearPreviewDisplayMarks(); scanForHoveredPreview(); } function installThumbnailUrlUpgrade() { if (!document.documentElement || thumbnailHandlersInstalled) return; applyThumbnailPreference(); // pointerover 已覆盖现代浏览器;不再重复监听 mouseover,避免双倍触发。 document.addEventListener('pointerover', rememberHoveredThumbnail, true); thumbnailHandlersInstalled = true; } window.addEventListener('storage', event => { if (event.key && event.key.startsWith(NODE_MARKS_PREFIX) && event.key === markStorageKey()) { loadNodeMarks(); applyNodeMarks(document); } else if (event.key === TASK_STORAGE_KEY || event.key === REMOVED_STORAGE_KEY) { readRemovedTaskKeys(); mergeRecordsIntoMemory(readTaskRecords()); // 恢复当前页面中活动任务的节点失败观察。 for (const task of tasks) { if (!isTerminal(task.state) && task.nodeId && currentPageMatchesTask(task)) watchTaskNode(task); } render(); } else if (event.key === SETTINGS_STORAGE_KEY) { readSettings(); renderControls(); applyThumbnailPreference(); scheduleControlRestore(); injectPromptSizeEnhancement(); applyPromptEditorPosition(); enhancePromptEditorUIs(); installNodeMarking(); applyPromptSearchReplacePreference(); installPromptSendButtons(); } }); document.addEventListener('focusin', rememberPromptEditor, true); document.addEventListener('pointerdown', rememberPromptEditor, true); document.addEventListener('keydown', onPromptFindShortcut, true); function observePromptSearchDom() { if (!document.documentElement || promptSearchObserver) return; promptSearchObserver = new MutationObserver(mutations => { if (!canvasPageActive) return; let promptAreaAdded = false; let actionRowAdded = false; const promptFloatingRoots = new Set(); for (const mutation of mutations) { const mutationTarget = mutation.target instanceof Element ? mutation.target : mutation.target && mutation.target.parentElement; const possibleFloating = mutationTarget && mutationTarget.closest ? mutationTarget.closest('.node-floating-ui') : null; if (possibleFloating && possibleFloating.querySelector('[data-generator-card]')) promptFloatingRoots.add(possibleFloating); if (mutationTarget && (mutationTarget.matches('[data-quick-guide-anchor="generator-prompt"]') || mutationTarget.closest('[data-quick-guide-anchor="generator-prompt"]'))) promptAreaAdded = true; if (mutationTarget && (mutationTarget.matches('[data-generator-action-chips]') || mutationTarget.closest('[data-generator-action-chips]'))) actionRowAdded = true; for (const added of mutation.addedNodes || []) { if (!(added instanceof Element)) continue; if (added.matches('.node-floating-ui') && added.querySelector('[data-generator-card]')) promptFloatingRoots.add(added); if (added.matches('[data-generator-card]')) { const floating = added.closest('.node-floating-ui'); if (floating) promptFloatingRoots.add(floating); } if (added.querySelectorAll) added.querySelectorAll('.node-floating-ui').forEach(floating => { if (floating.querySelector('[data-generator-card]')) promptFloatingRoots.add(floating); }); if (added.matches('[data-quick-guide-anchor="generator-prompt"]') || added.querySelector('[data-quick-guide-anchor="generator-prompt"]')) promptAreaAdded = true; if (added.matches('[data-generator-action-chips]') || added.querySelector('[data-generator-action-chips]')) actionRowAdded = true; } if (promptAreaAdded && actionRowAdded) break; } if (promptAreaAdded && settings.promptSearchReplaceEnabled) installPromptSearchReplace(); if (actionRowAdded && settings.promptSendButtonEnabled) installPromptSendButtons(); for (const floating of promptFloatingRoots) enhancePromptEditorUIs(floating); }); promptSearchObserver.observe(document.documentElement, { childList: true, subtree: true }); } function injectPromptSizeEnhancement() { if (!document.documentElement) return; ensurePromptEditorPositionStyle(); installPromptViewportSync(); const existing = document.getElementById(PROMPT_SIZE_STYLE_ID); if (!settings.promptSizeEnabled) { if (existing) existing.remove(); document.querySelectorAll('.node-floating-ui .libtv-prompt-resize-handle').forEach(handle => handle.remove()); applyPromptEditorPosition(); enhancePromptEditorUIs(); return; } if (!existing) { const style = document.createElement('style'); style.id = PROMPT_SIZE_STYLE_ID; style.textContent = ` /* 每个提示词浮窗使用自己的 CSS 变量;尺寸只施加到实际卡片,不能把 React Flow 的 NodeToolbar 外壳一起拉宽。 */ .node-floating-ui:has([data-generator-card]){width:auto!important;min-width:0!important;max-width:none!important;overflow:visible!important;pointer-events:none!important} .node-floating-ui:has([data-generator-card]) [data-generator-card]{position:relative!important;width:var(--ltv-prompt-width,720px)!important;min-width:var(--ltv-prompt-width,720px)!important;max-width:var(--ltv-prompt-width,720px)!important;overflow:visible!important;pointer-events:auto!important} .node-floating-ui [data-generator-card] .generator-prompt-scroll-region{height:var(--ltv-prompt-height,400px)!important;min-height:var(--ltv-prompt-height,400px)!important;max-height:var(--ltv-prompt-height,400px)!important} .node-floating-ui [data-generator-card] .generator-prompt-scroll-region > div{height:var(--ltv-prompt-height,400px)!important;min-height:var(--ltv-prompt-height,400px)!important;max-height:var(--ltv-prompt-height,400px)!important} .node-floating-ui [data-generator-card] .generator-prompt-scroll-region .mantine-ScrollArea-root{height:var(--ltv-prompt-height,400px)!important;min-height:var(--ltv-prompt-height,400px)!important;max-height:var(--ltv-prompt-height,400px)!important} .node-floating-ui [data-generator-card] .generator-prompt-scroll-region .mantine-ScrollArea-viewport{height:var(--ltv-prompt-height,400px)!important;max-height:var(--ltv-prompt-height,400px)!important;overflow-y:auto!important} .node-floating-ui [data-generator-card] .generator-prompt-scroll-region [contenteditable="true"][role="textbox"]{min-height:calc(var(--ltv-prompt-height,400px) - 20px)!important;white-space:pre-wrap!important} .node-floating-ui [data-generator-card] [contenteditable="true"][role="textbox"][aria-multiline="true"], .node-floating-ui [data-generator-card] [contenteditable="true"][role="textbox"][aria-multiline="true"] *{font-size:var(--ltv-prompt-font-size,14px)!important} .node-floating-ui [data-generator-card] .libtv-prompt-resize-handle,.node-floating-ui [data-generator-card] .libtv-prompt-move-handle{box-sizing:border-box!important} `; document.documentElement.appendChild(style); } enhancePromptEditorUIs(); } function ensurePromptEditorPositionStyle() { if (!document.documentElement || document.getElementById(PROMPT_POSITION_STYLE_ID)) return; const style = document.createElement('style'); style.id = PROMPT_POSITION_STYLE_ID; style.textContent = ` /* 底部模式完全不覆盖 LibTV 原生定位。NodeToolbar 外壳保持透明、不可命中;只有实际提示词卡片接收指针事件,避免变换后在旧位置留下透明命中区。 */ /* 提示词卡片允许溢出节点,但不允许把整个页面撑出滚动区;否则中键拖动画布时浏览器会滚页面,出现灰底和画布跳动。 */ html,body{overflow:hidden!important;overscroll-behavior:none!important} .react-flow{overscroll-behavior:none!important} .react-flow,.react-flow__renderer,.react-flow__viewport,.react-flow__pane,.react-flow__nodes,.react-flow__node,.node-floating-ui{overflow:visible!important} .node-floating-ui:has([data-generator-card]){pointer-events:none!important;width:auto!important;min-width:0!important;max-width:none!important;overflow:visible!important;z-index:2147482000!important} .node-floating-ui:has([data-generator-card]) [data-generator-card]{pointer-events:auto!important;overflow:visible!important;max-height:none!important} .node-floating-ui.ltv-prompt-pos-top [data-generator-card], .node-floating-ui.ltv-prompt-pos-left [data-generator-card], .node-floating-ui.ltv-prompt-pos-right [data-generator-card], .node-floating-ui.ltv-prompt-pos-free [data-generator-card]{transform:translate3d(var(--ltv-prompt-dx,0px),var(--ltv-prompt-dy,0px),0)!important;will-change:transform} .node-floating-ui:has([data-generator-card]) [data-generator-card]{position:relative!important;overflow:visible!important} /* 28px 图标按钮,放在 LibTV 原生 right-2/top-2/size-7 按钮左侧,二者间距约 4px。 */ .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-size-reset{position:absolute!important;right:40px!important;top:8px!important;z-index:10!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;width:28px!important;height:28px!important;min-width:28px!important;min-height:28px!important;padding:0!important;border:1px solid var(--canvas-controls-border,rgba(159,180,208,.4))!important;border-radius:8px!important;color:var(--color-fg-muted,var(--fg-muted,#aeb9c9))!important;font:inherit!important;white-space:nowrap!important;cursor:pointer!important;box-shadow:none!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-size-reset:hover{filter:brightness(1.12)!important;border-color:var(--canvas-controls-border,rgba(159,180,208,.75))!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-font-size-button{position:absolute!important;right:72px!important;top:8px!important;z-index:10!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;width:28px!important;height:28px!important;min-width:28px!important;min-height:28px!important;padding:0!important;border:1px solid var(--canvas-controls-border,rgba(159,180,208,.4))!important;border-radius:8px!important;color:var(--color-fg-muted,var(--fg-muted,#aeb9c9))!important;background:var(--color-panel-background,rgba(25,32,43,.96))!important;font:inherit!important;cursor:pointer!important;box-shadow:none!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-font-size-button:hover{filter:brightness(1.12)!important;border-color:var(--canvas-controls-border,rgba(159,180,208,.75))!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-font-menu{position:absolute!important;right:72px!important;top:40px!important;z-index:30!important;display:grid!important;grid-template-columns:repeat(3,minmax(0,1fr))!important;gap:4px!important;width:164px!important;padding:6px!important;border:1px solid rgba(130,145,165,.55)!important;border-radius:8px!important;background:rgba(23,30,41,.98)!important;box-shadow:0 8px 24px rgba(0,0,0,.35)!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-font-menu[hidden]{display:none!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-font-option{display:inline-flex!important;align-items:center!important;justify-content:center!important;min-width:0!important;height:26px!important;padding:3px 5px!important;border:1px solid rgba(130,145,165,.35)!important;border-radius:5px!important;background:rgba(255,255,255,.05)!important;color:#e8edf4!important;font:11px/1.2 system-ui,sans-serif!important;cursor:pointer!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-font-option[aria-pressed="true"]{border-color:#65aee8!important;background:rgba(72,144,204,.25)!important;color:#fff!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-font-option:hover{background:rgba(255,255,255,.14)!important} .node-floating-ui.ltv-prompt-pos-free [data-generator-action-chips][data-ltv-prompt-drag-target="1"]{cursor:grab!important} .node-floating-ui.ltv-prompt-pos-free [data-generator-action-chips][data-ltv-prompt-drag-target="1"]:active{cursor:grabbing!important} .node-floating-ui.ltv-prompt-pos-free [data-generator-action-chips][data-ltv-prompt-drag-flex="1"]::after{content:"";display:block;flex:1 1 32px;min-width:32px;min-height:22px;align-self:stretch;cursor:grab;pointer-events:auto} .node-floating-ui.ltv-prompt-pos-free [data-generator-action-chips][data-ltv-prompt-drag-flex="1"]::after:active{cursor:grabbing} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-handle, .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-move-handle{box-sizing:border-box!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-handle{position:absolute!important;z-index:2147483000!important;display:block!important;touch-action:none!important;user-select:none!important;-webkit-user-select:none!important;pointer-events:auto!important;background:transparent!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-handle:hover{background:rgba(117,174,235,.2)!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-n, .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-s{height:7px!important;left:10px!important;right:10px!important;cursor:ns-resize!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-n{top:0!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-s{bottom:0!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-e, .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-w{width:7px!important;top:10px!important;bottom:10px!important;cursor:ew-resize!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-e{right:0!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-w{left:0!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-nw, .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-ne, .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-sw, .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-se{width:12px!important;height:12px!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-nw{top:0!important;left:0!important;cursor:nwse-resize!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-ne{top:0!important;right:0!important;cursor:nesw-resize!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-sw{bottom:0!important;left:0!important;cursor:nesw-resize!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-resize-se{bottom:0!important;right:0!important;cursor:nwse-resize!important} .node-floating-ui:has([data-generator-card]) [data-generator-card] .libtv-prompt-move-handle{position:absolute!important;z-index:2147483001!important;display:none;left:calc(50% - 34px)!important;top:-11px!important;width:68px!important;height:9px!important;border-radius:5px!important;background:rgba(121,164,218,.8)!important;border:1px solid rgba(235,245,255,.75)!important;cursor:move!important;touch-action:none!important;pointer-events:auto!important} .node-floating-ui.ltv-prompt-pos-free [data-generator-card] .libtv-prompt-move-handle{display:block!important} .node-floating-ui.ltv-prompt-pos-free [data-generator-card] .libtv-prompt-move-handle:hover{background:#9ac9ff!important} `; document.documentElement.appendChild(style); } const PROMPT_EDITOR_POSITION_CLASSES = ['ltv-prompt-pos-bottom', 'ltv-prompt-pos-top', 'ltv-prompt-pos-left', 'ltv-prompt-pos-right', 'ltv-prompt-pos-free']; const PROMPT_RESIZE_EDGES = ['n', 's', 'e', 'w', 'nw', 'ne', 'sw', 'se']; function getPromptFloatingRoot(element) { if (!(element instanceof Element)) return null; const root = element.matches('.node-floating-ui') ? element : element.closest('.node-floating-ui'); if (root && root.querySelector('[data-generator-card]')) return root; if (element.matches('[data-generator-card]')) return element.closest('.node-floating-ui') || element; return null; } function getPromptAnchorNode(floating, card) { const nodeSelector = '.react-flow__node[data-id],.react-flow__node[data-node-id],.react-flow__node[data-nodeid]'; const nodes = [...document.querySelectorAll(nodeSelector)]; const findId = id => id ? nodes.find(node => node.getAttribute('data-id') === String(id) || node.getAttribute('data-node-id') === String(id) || node.getAttribute('data-nodeid') === String(id)) : null; const remembered = findId(floating.dataset.ltvPromptAnchorNodeId); if (remembered) return remembered; for (const element of [floating, card]) { if (!element) continue; const directId = element.getAttribute('data-node-id') || element.getAttribute('data-nodeid') || element.getAttribute('data-id'); const byId = findId(directId); if (byId) { floating.dataset.ltvPromptAnchorNodeId = byId.getAttribute('data-id') || byId.getAttribute('data-node-id') || byId.getAttribute('data-nodeid') || ''; return byId; } const ancestor = element.closest && element.closest(nodeSelector); if (ancestor) { floating.dataset.ltvPromptAnchorNodeId = ancestor.getAttribute('data-id') || ancestor.getAttribute('data-node-id') || ancestor.getAttribute('data-nodeid') || ''; return ancestor; } } const selected = nodes.filter(node => node.classList.contains('selected') || node.classList.contains('react-flow__node--selected') || node.getAttribute('aria-selected') === 'true'); if (selected.length === 1) { const node = selected[0]; floating.dataset.ltvPromptAnchorNodeId = node.getAttribute('data-id') || node.getAttribute('data-node-id') || node.getAttribute('data-nodeid') || ''; return node; } // 回退策略:LibTV 原生模式把生成卡片放在关联节点下方,取与该锚点距离最近的可见节点。 if (!(card instanceof Element)) return null; const rect = card.getBoundingClientRect(); let best = null, bestScore = Infinity; for (const node of nodes) { const nr = node.getBoundingClientRect(); if (nr.width < 1 || nr.height < 1) continue; const horizontal = Math.abs((nr.left + nr.width / 2) - (rect.left + rect.width / 2)); const vertical = Math.abs(nr.bottom - rect.top); const score = horizontal + vertical * 0.85; if (score < bestScore) { bestScore = score; best = node; } } if (best) floating.dataset.ltvPromptAnchorNodeId = best.getAttribute('data-id') || best.getAttribute('data-node-id') || best.getAttribute('data-nodeid') || ''; return best; } function promptOffset(card, name) { const value = parseFloat(card.style.getPropertyValue(name)); return Number.isFinite(value) ? value : 0; } function setPromptOffset(card, dx, dy) { card.style.setProperty('--ltv-prompt-dx', `${Math.round(dx * 100) / 100}px`); card.style.setProperty('--ltv-prompt-dy', `${Math.round(dy * 100) / 100}px`); } function findPromptFlowInstance() { const root = document.querySelector('.react-flow'); if (!root) return null; const fiberKey = Object.keys(root).find(key => key.startsWith('__reactFiber$')); let fiber = fiberKey ? root[fiberKey] : null; const isInstance = value => !!value && typeof value === 'object' && typeof value.setViewport === 'function' && typeof value.getViewport === 'function'; const search = (value, depth, seen) => { if (!value || depth > 4) return null; if (isInstance(value)) return value; if (typeof value !== 'object' && typeof value !== 'function') return null; if (seen.has(value)) return null; seen.add(value); let keys = []; try { keys = Object.keys(value); } catch (_) { return null; } for (const key of keys.slice(0, 60)) { if (key === 'return' || key === 'child' || key === 'sibling' || key === 'stateNode' || key === 'alternate') continue; try { const found = search(value[key], depth + 1, seen); if (found) return found; } catch (_) {} } return null; }; for (let depth = 0; fiber && depth < 80; depth++, fiber = fiber.return) { for (const field of ['memoizedProps', 'memoizedState']) { try { const found = search(fiber[field], 0, new WeakSet()); if (found) return found; } catch (_) {} } } return null; } function revealPromptPanel(floating, card, node) { if (!(floating instanceof Element) || !(card instanceof Element) || !(node instanceof Element)) return; const mode = settings.promptEditorPosition; if (!['top', 'left', 'right'].includes(mode)) return; const rect = card.getBoundingClientRect(); const nr = node.getBoundingClientRect(); if (rect.width < 1 || rect.height < 1 || nr.width < 1 || nr.height < 1) return; const canvas = document.querySelector('.react-flow'); const bounds = canvas ? canvas.getBoundingClientRect() : null; if (!bounds || bounds.width < 2 || bounds.height < 2) return; const margin = 14; const gap = 12; // 只允许移动到“节点本身仍在画布内”的范围,避免把画布推到空白区。 const maxLeftShift = Math.max(0, nr.left - (bounds.left + margin)); const maxRightShift = Math.max(0, (bounds.right - margin) - nr.right); const maxUpShift = Math.max(0, nr.top - (bounds.top + margin)); const maxDownShift = Math.max(0, (bounds.bottom - margin) - nr.bottom); let dx = 0; let dy = 0; const fixVertical = () => { if (rect.bottom > bounds.bottom - margin) dy = -Math.min(rect.bottom - (bounds.bottom - margin), maxUpShift); else if (rect.top < bounds.top + margin) dy = Math.min((bounds.top + margin) - rect.top, maxDownShift); }; const fixHorizontal = () => { if (rect.right > bounds.right - margin) dx = -Math.min(rect.right - (bounds.right - margin), maxLeftShift); else if (rect.left < bounds.left + margin) dx = Math.min((bounds.left + margin) - rect.left, maxRightShift); }; if (mode === 'right') { const needed = nr.right + gap + rect.width + margin - bounds.right; if (needed > 0) dx = -Math.min(needed, maxLeftShift); fixVertical(); } else if (mode === 'left') { const needed = (bounds.left + margin) - (nr.left - gap - rect.width); if (needed > 0) dx = Math.min(needed, maxRightShift); fixVertical(); } else if (mode === 'top') { const needed = (bounds.top + margin) - (nr.top - gap - rect.height); if (needed > 0) dy = Math.min(needed, maxDownShift); fixHorizontal(); } if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return; const instance = findPromptFlowInstance(); if (!instance) return; let viewport = null; try { viewport = instance.getViewport(); } catch (_) {} if (!viewport || !Number.isFinite(viewport.x) || !Number.isFinite(viewport.y) || !Number.isFinite(viewport.zoom) || viewport.zoom <= 0) return; // 低缩放时面板是屏幕尺寸,侧放空间常常不足;此时不再自动推画布,避免漂移到空白区。 if (viewport.zoom < 0.33) return; // 同一面板/尺寸只自动平移一次;签名不含 zoom,缩放动画期间不会反复推画布。 const nodeId = node.getAttribute('data-id') || node.getAttribute('data-node-id') || node.getAttribute('data-nodeid') || ''; const signature = [ mode, nodeId, Math.round(rect.width), Math.round(rect.height), Math.round(bounds.width), Math.round(bounds.height) ].join('|'); if (floating.__ltvPromptRevealSignature === signature) return; floating.__ltvPromptRevealSignature = signature; const next = { x: viewport.x + dx / viewport.zoom, y: viewport.y + dy / viewport.zoom, zoom: viewport.zoom }; try { instance.setViewport(next); } catch (_) {} } function schedulePromptPanelReveal() { // 画布自动平移已移除:只保留缩放/拖动画布时面板重新贴合节点。 } function schedulePromptViewportSync() { if (promptViewportSyncFrame) return; promptViewportSyncFrame = requestAnimationFrame(() => { promptViewportSyncFrame = 0; const mode = settings.promptEditorPosition; if (!['top', 'left', 'right'].includes(mode)) return; for (const floating of document.querySelectorAll('.node-floating-ui')) { const card = floating.querySelector('[data-generator-card]'); if (!card || floating.dataset.ltvPromptPosition !== mode) continue; alignPromptCardToNode(floating, mode, { reveal: false }); } }); } function installPromptViewportSync() { const viewport = document.querySelector('.react-flow__viewport'); if (!viewport) return; if (promptViewportObserver && promptViewportObserverTarget === viewport && viewport.isConnected) return; if (promptViewportObserver) promptViewportObserver.disconnect(); promptViewportObserverTarget = viewport; promptViewportObserver = new MutationObserver(schedulePromptViewportSync); promptViewportObserver.observe(viewport, { attributes: true, attributeFilter: ['style'] }); } function alignPromptCardToNode(floating, mode = settings.promptEditorPosition, options = {}) { if (!(floating instanceof Element) || !['top', 'left', 'right'].includes(mode)) return; const card = floating.querySelector('[data-generator-card]'); if (!card) return; const node = getPromptAnchorNode(floating, card); if (!node) return; const nr = node.getBoundingClientRect(); const cr = card.getBoundingClientRect(); if (nr.width < 1 || nr.height < 1 || cr.width < 1 || cr.height < 1) return; const oldDx = promptOffset(card, '--ltv-prompt-dx'); const oldDy = promptOffset(card, '--ltv-prompt-dy'); // 去掉当前卡片自身的平移,恢复其由 LibTV 原生锚点决定的基准坐标。 const baseLeft = cr.left - oldDx; const baseTop = cr.top - oldDy; const gap = 12; // 左/右/上侧按节点坐标直接定位,不按画布边界夹紧;允许提示词卡片超出画布区域。 let targetLeft = baseLeft, targetTop = baseTop; if (mode === 'right') { targetLeft = nr.right + gap; targetTop = nr.top; } else if (mode === 'left') { targetLeft = nr.left - gap - cr.width; targetTop = nr.top; } else if (mode === 'top') { targetLeft = nr.left + (nr.width - cr.width) / 2; targetTop = nr.top - gap - cr.height; } setPromptOffset(card, targetLeft - baseLeft, targetTop - baseTop); if (options.reveal !== false) schedulePromptPanelReveal(floating); } function alignPromptFreeToSavedPoint(floating) { if (!(floating instanceof Element)) return; const card = floating.querySelector('[data-generator-card]'); if (!card) return; const rect = card.getBoundingClientRect(); const dx = promptOffset(card, '--ltv-prompt-dx'); const dy = promptOffset(card, '--ltv-prompt-dy'); const baseLeft = rect.left - dx; const baseTop = rect.top - dy; let wantedLeft = Number.isFinite(settings.promptEditorFreeLeft) ? settings.promptEditorFreeLeft : rect.left; let wantedTop = Number.isFinite(settings.promptEditorFreeTop) ? settings.promptEditorFreeTop : rect.top; const point = clampFreePromptPoint(wantedLeft, wantedTop, rect.width, rect.height); if (!Number.isFinite(settings.promptEditorFreeLeft) || !Number.isFinite(settings.promptEditorFreeTop)) { settings.promptEditorFreeLeft = point.left; settings.promptEditorFreeTop = point.top; saveSettings(); } setPromptOffset(card, point.left - baseLeft, point.top - baseTop); } function schedulePromptPositionAlignment(floating) { if (!(floating instanceof Element) || !['top', 'left', 'right', 'free'].includes(settings.promptEditorPosition)) return; if (floating.__ltvPromptAlignFrame) return; floating.__ltvPromptAlignFrame = requestAnimationFrame(() => { floating.__ltvPromptAlignFrame = 0; if (!floating.isConnected) return; if (settings.promptEditorPosition === 'free') alignPromptFreeToSavedPoint(floating); else alignPromptCardToNode(floating, settings.promptEditorPosition); }); } function schedulePromptPanelSettle(floating) { if (!(floating instanceof Element)) return; if (floating.__ltvPromptSettleTimers) return; const mode = settings.promptEditorPosition; if (!['top', 'left', 'right'].includes(mode)) return; const run = () => { if (!floating.isConnected) return; const currentMode = settings.promptEditorPosition; if (!['top', 'left', 'right'].includes(currentMode)) return; alignPromptCardToNode(floating, currentMode, { reveal: false }); }; const timers = [0, 60, 180, 420, 800].map(delay => setTimeout(run, delay)); floating.__ltvPromptSettleTimers = timers; setTimeout(() => { if (floating.__ltvPromptSettleTimers === timers) floating.__ltvPromptSettleTimers = null; }, 900); } function clampFreePromptPoint(left, top, width = 720, height = 400) { return { left: Math.max(8, Math.min(Math.max(8, window.innerWidth - width - 8), left)), top: Math.max(8, Math.min(Math.max(8, window.innerHeight - height - 8), top)) }; } function applyPromptEditorPosition(root = document) { const roots = new Set(); if (root instanceof Element) { const parent = getPromptFloatingRoot(root); if (parent) roots.add(parent); if (root.matches('.node-floating-ui') && root.querySelector('[data-generator-card]')) roots.add(root); root.querySelectorAll && root.querySelectorAll('.node-floating-ui').forEach(item => { if (item.querySelector('[data-generator-card]')) roots.add(item); }); if (root.matches('[data-generator-card]')) { const item = root.closest('.node-floating-ui'); if (item) roots.add(item); } } else if (root && root.querySelectorAll) { root.querySelectorAll('.node-floating-ui').forEach(item => { if (item.querySelector('[data-generator-card]')) roots.add(item); }); } for (const floating of roots) { const card = floating.querySelector('[data-generator-card]'); if (!card) continue; const next = ['bottom', 'top', 'left', 'right', 'free'].includes(settings.promptEditorPosition) ? settings.promptEditorPosition : 'bottom'; const previous = floating.dataset.ltvPromptPosition || 'bottom'; const classesForMode = next === 'bottom' ? [] : [`ltv-prompt-pos-${next}`]; const isModeApplied = next === 'bottom' ? !PROMPT_EDITOR_POSITION_CLASSES.some(cls => floating.classList.contains(cls)) : floating.classList.contains(`ltv-prompt-pos-${next}`); if (previous === next && isModeApplied) { ensurePromptEditorHandles(floating); schedulePromptPanelSettle(floating); continue; } // 捕获切换前的实际视觉位置;首次启用自由模式时保留原位置,而不是跳回原点。 const beforeRect = card.getBoundingClientRect(); floating.__ltvPromptRevealSignature = ''; if (next !== 'bottom') getPromptAnchorNode(floating, card); floating.classList.remove(...PROMPT_EDITOR_POSITION_CLASSES); setPromptOffset(card, 0, 0); if (next === 'bottom') { // 不覆盖 translate/transform/定位样式,让 LibTV 原生的 NodeToolbar 吸附逻辑完全接管。 card.style.removeProperty('--ltv-prompt-dx'); card.style.removeProperty('--ltv-prompt-dy'); floating.dataset.ltvPromptPosition = 'bottom'; ensurePromptEditorHandles(floating); continue; } floating.classList.add(...classesForMode); if (next === 'free') { const baseRect = card.getBoundingClientRect(); let wantedLeft = settings.promptEditorFreeLeft; let wantedTop = settings.promptEditorFreeTop; if (!Number.isFinite(wantedLeft) || !Number.isFinite(wantedTop)) { // 第一次开启自由浮动,延续切换前的视觉坐标,并将它保存下来。 wantedLeft = beforeRect.left; wantedTop = beforeRect.top; const point = clampFreePromptPoint(wantedLeft, wantedTop, baseRect.width, baseRect.height); wantedLeft = point.left; wantedTop = point.top; settings.promptEditorFreeLeft = wantedLeft; settings.promptEditorFreeTop = wantedTop; saveSettings(); } else { const point = clampFreePromptPoint(wantedLeft, wantedTop, baseRect.width, baseRect.height); wantedLeft = point.left; wantedTop = point.top; } setPromptOffset(card, wantedLeft - baseRect.left, wantedTop - baseRect.top); } else { alignPromptCardToNode(floating, next); } floating.dataset.ltvPromptPosition = next; ensurePromptEditorHandles(floating); schedulePromptPanelSettle(floating); } } function ensurePromptEditorHandles(root) { if (!(root instanceof Element)) return; const floating = getPromptFloatingRoot(root); if (!floating) return; const card = floating.querySelector('[data-generator-card]'); if (!card) return; if (!floating.__ltvPromptResizeObserver && typeof ResizeObserver === 'function') { const observer = new ResizeObserver(() => schedulePromptPositionAlignment(floating)); observer.observe(card); floating.__ltvPromptResizeObserver = observer; } if (settings.promptSizeEnabled) { if (!floating.style.getPropertyValue('--ltv-prompt-width')) floating.style.setProperty('--ltv-prompt-width', `${settings.promptEditorWidth || 720}px`); if (!floating.style.getPropertyValue('--ltv-prompt-height')) floating.style.setProperty('--ltv-prompt-height', `${settings.promptEditorHeight || 400}px`); floating.style.setProperty('--ltv-prompt-font-size', `${settings.promptEditorFontSize || 14}px`); if (!card.querySelector('.libtv-prompt-size-reset')) { const reset = document.createElement('button'); reset.type = 'button'; reset.className = 'bg-panel-background absolute top-2 z-10 flex size-7 shrink-0 items-center justify-center rounded-lg libtv-prompt-size-reset'; reset.innerHTML = ''; reset.title = '恢复提示词输入框默认大小(720 × 400)'; reset.setAttribute('aria-label', '恢复提示词输入框默认大小'); reset.addEventListener('pointerdown', event => { event.preventDefault(); event.stopPropagation(); }); reset.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); settings.promptEditorWidth = 720; settings.promptEditorHeight = 400; floating.style.setProperty('--ltv-prompt-width', '720px'); floating.style.setProperty('--ltv-prompt-height', '400px'); saveSettings(); if (['top', 'left', 'right', 'free'].includes(settings.promptEditorPosition)) schedulePromptPositionAlignment(floating); setNotice('提示词输入框已恢复默认大小(720 × 400)。'); }); card.appendChild(reset); } let fontButton = card.querySelector('.libtv-prompt-font-size-button'); if (!fontButton) { fontButton = document.createElement('button'); fontButton.type = 'button'; fontButton.className = 'bg-panel-background absolute top-2 z-10 flex size-7 shrink-0 items-center justify-center rounded-lg libtv-prompt-font-size-button'; fontButton.innerHTML = ''; fontButton.title = `修改提示词字体大小(当前 ${settings.promptEditorFontSize || 14}px)`; fontButton.setAttribute('aria-label', '修改提示词字体大小'); fontButton.setAttribute('aria-haspopup', 'true'); fontButton.setAttribute('aria-expanded', 'false'); fontButton.addEventListener('pointerdown', event => { event.preventDefault(); event.stopPropagation(); }); fontButton.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); const menu = card.querySelector('.libtv-prompt-font-menu'); if (!menu) return; menu.hidden = !menu.hidden; fontButton.setAttribute('aria-expanded', String(!menu.hidden)); }); card.appendChild(fontButton); } fontButton.title = `修改提示词字体大小(当前 ${settings.promptEditorFontSize || 14}px)`; let fontMenu = card.querySelector('.libtv-prompt-font-menu'); if (!fontMenu) { fontMenu = document.createElement('div'); fontMenu.className = 'libtv-prompt-font-menu'; fontMenu.hidden = true; fontMenu.setAttribute('role', 'group'); fontMenu.setAttribute('aria-label', '提示词字体大小'); for (const size of [12, 14, 16, 18, 20, 22, 24, 26, 28]) { const option = document.createElement('button'); option.type = 'button'; option.className = 'libtv-prompt-font-option'; option.textContent = `${size}px`; option.dataset.fontSize = String(size); option.addEventListener('pointerdown', event => { event.preventDefault(); event.stopPropagation(); }); option.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); const chosenSize = Number(option.dataset.fontSize); if (!Number.isFinite(chosenSize)) return; settings.promptEditorFontSize = Math.max(12, Math.min(28, chosenSize)); saveSettings(); document.querySelectorAll('.node-floating-ui').forEach(otherFloating => { if (otherFloating.querySelector('[data-generator-card]')) otherFloating.style.setProperty('--ltv-prompt-font-size', `${settings.promptEditorFontSize}px`); }); document.querySelectorAll('.libtv-prompt-font-option').forEach(item => item.setAttribute('aria-pressed', String(Number(item.dataset.fontSize) === settings.promptEditorFontSize))); document.querySelectorAll('.libtv-prompt-font-size-button').forEach(button => { button.title = `修改提示词字体大小(当前 ${settings.promptEditorFontSize}px)`; }); fontMenu.hidden = true; fontButton.setAttribute('aria-expanded', 'false'); setNotice(`提示词字体大小已设置为 ${settings.promptEditorFontSize}px,并已记住该设置。`); }); fontMenu.appendChild(option); } card.appendChild(fontMenu); card.addEventListener('click', event => { if (!event.target.closest('.libtv-prompt-font-size-button,.libtv-prompt-font-menu')) { fontMenu.hidden = true; fontButton.setAttribute('aria-expanded', 'false'); } }); } fontMenu.querySelectorAll('.libtv-prompt-font-option').forEach(option => option.setAttribute('aria-pressed', String(Number(option.dataset.fontSize) === (settings.promptEditorFontSize || 14)))); } else { card.querySelectorAll('.libtv-prompt-resize-handle,.libtv-prompt-size-reset,.libtv-prompt-font-size-button,.libtv-prompt-font-menu').forEach(handle => handle.remove()); } // 自由浮动改用生成器操作芯片行的空白区域拖动,不再插入额外的拖动条。 card.querySelectorAll('.libtv-prompt-move-handle').forEach(handle => handle.remove()); const actionRows = [...new Set([ ...floating.querySelectorAll('[data-generator-action-chips]'), ...card.querySelectorAll('[data-generator-action-chips]') ])]; for (const row of actionRows) { if (settings.promptEditorPosition === 'free') { row.setAttribute('data-ltv-prompt-drag-target', '1'); const display = getComputedStyle(row).display; if (display === 'flex' || display === 'inline-flex') row.setAttribute('data-ltv-prompt-drag-flex', '1'); else row.removeAttribute('data-ltv-prompt-drag-flex'); } else { row.removeAttribute('data-ltv-prompt-drag-target'); row.removeAttribute('data-ltv-prompt-drag-flex'); } if (row.dataset.ltvPromptDragBound === '1') continue; row.dataset.ltvPromptDragBound = '1'; let drag = null; let queuedPoint = null; let moveFrame = 0; const applyDragPoint = () => { moveFrame = 0; if (!drag || !queuedPoint) return; const point = clampFreePromptPoint(queuedPoint.left, queuedPoint.top, drag.width, drag.height); setPromptOffset(card, point.left - drag.baseLeft, point.top - drag.baseTop); queuedPoint = null; }; const queueDragPoint = (left, top) => { queuedPoint = { left, top }; if (!moveFrame) moveFrame = requestAnimationFrame(applyDragPoint); }; row.addEventListener('pointerdown', event => { // 只在操作芯片行自身的空白区域开始拖动;按钮、标签、输入框仍保留各自行为。 if (settings.promptEditorPosition !== 'free' || event.button !== 0 || event.target !== row) return; const rect = card.getBoundingClientRect(); const dx = promptOffset(card, '--ltv-prompt-dx'); const dy = promptOffset(card, '--ltv-prompt-dy'); drag = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, startLeft: rect.left, startTop: rect.top, baseLeft: rect.left - dx, baseTop: rect.top - dy, width: rect.width, height: rect.height }; try { row.setPointerCapture(event.pointerId); } catch (_) {} event.preventDefault(); event.stopPropagation(); }); row.addEventListener('pointermove', event => { if (!drag || drag.pointerId !== event.pointerId) return; queueDragPoint(drag.startLeft + event.clientX - drag.x, drag.startTop + event.clientY - drag.y); event.preventDefault(); event.stopPropagation(); }); const stopDrag = event => { if (!drag || (event.pointerId != null && event.pointerId !== drag.pointerId)) return; if (moveFrame) { cancelAnimationFrame(moveFrame); moveFrame = 0; applyDragPoint(); } drag = null; queuedPoint = null; const rect = card.getBoundingClientRect(); const point = clampFreePromptPoint(rect.left, rect.top, rect.width, rect.height); settings.promptEditorFreeLeft = Math.round(point.left); settings.promptEditorFreeTop = Math.round(point.top); saveSettings(); if (event && event.stopPropagation) event.stopPropagation(); }; row.addEventListener('pointerup', stopDrag); row.addEventListener('pointercancel', stopDrag); row.addEventListener('lostpointercapture', stopDrag); } if (!settings.promptSizeEnabled) { card.querySelectorAll('.libtv-prompt-resize-handle').forEach(handle => handle.remove()); return; } for (const edge of PROMPT_RESIZE_EDGES) { if (card.querySelector(`.libtv-prompt-resize-${edge}`)) continue; const handle = document.createElement('div'); handle.className = `libtv-prompt-resize-handle libtv-prompt-resize-${edge}`; handle.dataset.promptResize = edge; handle.title = '拖动调整提示词输入框大小'; card.appendChild(handle); let resize = null; handle.addEventListener('pointerdown', event => { if (event.button !== 0) return; // 只按实际卡片的可视尺寸计算,不读取 NodeToolbar 外壳的矩形;外壳在非底部模式下不应参与布局/命中。 const rect = card.getBoundingClientRect(); const width = parseFloat(floating.style.getPropertyValue('--ltv-prompt-width')) || rect.width || 720; const height = parseFloat(floating.style.getPropertyValue('--ltv-prompt-height')) || rect.height || 400; resize = { pointerId: event.pointerId, edge, x: event.clientX, y: event.clientY, width, height }; try { handle.setPointerCapture(event.pointerId); } catch (_) {} event.preventDefault(); event.stopPropagation(); }); handle.addEventListener('pointermove', event => { if (!resize || resize.pointerId !== event.pointerId) return; const st = resize, dx = event.clientX - st.x, dy = event.clientY - st.y; const west = edge.includes('w'), east = edge.includes('e'), north = edge.includes('n'), south = edge.includes('s'); const maxWidth = Math.max(520, Math.min(1400, window.innerWidth - 24)); const maxHeight = Math.max(260, Math.min(1100, window.innerHeight - 24)); const width = Math.max(480, Math.min(maxWidth, west ? st.width - dx : east ? st.width + dx : st.width)); const height = Math.max(220, Math.min(maxHeight, north ? st.height - dy : south ? st.height + dy : st.height)); floating.style.setProperty('--ltv-prompt-width', `${Math.round(width)}px`); floating.style.setProperty('--ltv-prompt-height', `${Math.round(height)}px`); if (['top', 'left', 'right', 'free'].includes(settings.promptEditorPosition)) schedulePromptPositionAlignment(floating); event.preventDefault(); event.stopPropagation(); }); const stopResize = event => { if (!resize || (event.pointerId != null && event.pointerId !== resize.pointerId)) return; resize = null; settings.promptEditorWidth = Math.max(480, Math.min(1400, parseFloat(floating.style.getPropertyValue('--ltv-prompt-width')) || 720)); settings.promptEditorHeight = Math.max(220, Math.min(1100, parseFloat(floating.style.getPropertyValue('--ltv-prompt-height')) || 400)); saveSettings(); if (['top', 'left', 'right', 'free'].includes(settings.promptEditorPosition)) schedulePromptPositionAlignment(floating); }; handle.addEventListener('pointerup', stopResize); handle.addEventListener('pointercancel', stopResize); handle.addEventListener('lostpointercapture', stopResize); } } function enhancePromptEditorUIs(root = document) { if (!(root instanceof Element) && !(root && root.querySelectorAll)) return; if (root instanceof Element && root.matches('.node-floating-ui') && root.querySelector('[data-generator-card]')) { applyPromptEditorPosition(root); ensurePromptEditorHandles(root); } if (root instanceof Element && root.matches('[data-generator-card]')) { const floating = root.closest('.node-floating-ui'); if (floating) { applyPromptEditorPosition(floating); ensurePromptEditorHandles(floating); } } if (root.querySelectorAll) root.querySelectorAll('.node-floating-ui').forEach(floating => { if (!floating.querySelector('[data-generator-card]')) return; applyPromptEditorPosition(floating); ensurePromptEditorHandles(floating); }); } // ---------- 视频节点常驻下载按钮 ---------- const PERSISTENT_VIDEO_DOWNLOAD_ATTR = 'data-libtv-persistent-video-download'; const VIDEO_NODE_SELECTOR = '.react-flow__node[data-id],.react-flow__node[data-node-id],.react-flow__node[data-nodeid]'; const NATIVE_VIDEO_DOWNLOAD_SELECTOR = 'button[data-feature-id="video.download"][data-auth-download-trigger="true"],button[data-feature-id="video.download"],button[aria-label="下载"],button[title="下载"]'; function nodeHasVideoOutput(node) { if (!(node instanceof Element) || !node.matches('.react-flow__node')) return false; const videos = Array.from(node.querySelectorAll('video[src],video source[src]')); const hasVideo = videos.some(video => { if (video.closest('.node-floating-ui,[data-generator-card],[contenteditable="true"]')) return false; const src = safeString(video.getAttribute('src') || video.src || ''); return /\.(?:mp4|webm|mov|m4v)(?:[?#]|$)/i.test(src) || /\/genius_playground\/video\//i.test(src); }); if (hasVideo) return true; // 结果视频节点首屏往往只有视频快照图,没有