import { getMemoryState, getHighlights } from '../core/table-system/manager.js'; import { extension_settings } from '/scripts/extensions.js'; import { extensionName } from '../utils/settings.js'; const TABLE_CONTAINER_ID = 'amily2-chat-table-container'; const isTouchDevice = () => window.matchMedia('(pointer: coarse)').matches; function renderTablesToHtml(tables, highlights) { if (!tables || tables.length === 0) { return ''; } let html = ''; tables.forEach((table, tableIndex) => { if (table.rows && table.rows.length > 0) { html += `
`; html += `${table.name}`; html += `
`; html += ''; html += ''; table.headers.forEach(header => { html += ``; }); html += ''; html += ''; table.rows.forEach((row, rowIndex) => { html += ''; row.forEach((cell, colIndex) => { const highlightKey = `${tableIndex}-${rowIndex}-${colIndex}`; const isHighlighted = highlights.has(highlightKey); const highlightClass = isHighlighted ? ' amily2-cell-highlight' : ''; html += ``; }); html += ''; }); html += ''; html += '
${header}
${cell}
'; html += '
'; html += `
`; } }); return html; } function removeTableContainer() { const existingContainer = document.getElementById(TABLE_CONTAINER_ID); if (existingContainer) { existingContainer.remove(); } } function bindSwipePreventer(container) { // Only apply this logic on mobile/touch devices if (!isTouchDevice()) { return; } let touchstartX = 0; let touchstartY = 0; container.addEventListener('touchstart', function(event) { touchstartX = event.changedTouches[0].screenX; touchstartY = event.changedTouches[0].screenY; }, { passive: true }); container.addEventListener('touchmove', function(event) { const touchendX = event.changedTouches[0].screenX; const touchendY = event.changedTouches[0].screenY; const deltaX = Math.abs(touchendX - touchstartX); const deltaY = Math.abs(touchendY - touchstartY); if (deltaX > deltaY) { event.stopPropagation(); } }, { passive: false }); } export function updateOrInsertTableInChat() { setTimeout(() => { const settings = extension_settings[extensionName]; removeTableContainer(); if (!settings || !settings.show_table_in_chat) { return; } const tables = getMemoryState(); if (!tables || tables.every(t => !t.rows || t.rows.length === 0)) { return; } const highlights = getHighlights(); const htmlContent = renderTablesToHtml(tables, highlights); if (!htmlContent) { return; } const lastMessage = document.querySelector('.last_mes .mes_text'); if (lastMessage) { const container = document.createElement('div'); container.id = TABLE_CONTAINER_ID; container.innerHTML = htmlContent; lastMessage.appendChild(container); bindSwipePreventer(container); // Bind the event listener to prevent swipe conflicts } else { console.warn('[Amily2] 未找到最后一条消息的容器,无法插入表格。'); } }, 0); }