document.addEventListener('DOMContentLoaded', () => {
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const uploadContent = document.getElementById('uploadContent');
const results = document.getElementById('results');
const resultsContent = document.getElementById('resultsContent');
const notificationContainer = document.getElementById('notification-container');
const categoriesContainer = document.getElementById('categoriesContainer');
const ratingDisplay = document.getElementById('ratingDisplay');
const copyGlobalAll = document.getElementById('copyGlobalAll');
const copyGlobalConfident = document.getElementById('copyGlobalConfident');
const settingsToggle = document.getElementById('settingsToggle');
const settingsMenu = document.getElementById('settingsMenu');
const closeSettings = document.getElementById('closeSettings');
const presetBtns = document.querySelectorAll('.preset-btn');
const customPanel = document.getElementById('customThresholdsPanel');
const customAllInput = document.getElementById('customAll');
const customConfidentInput = document.getElementById('customConfident');
const applyCustom = document.getElementById('applyCustom');
const formatOptions = document.querySelectorAll('.format-option');
const resetBtn = document.getElementById('resetSettings');
const themeOptions = document.querySelectorAll('.theme-option');
const maxTagBtns = document.querySelectorAll('.max-tag-option');
const eggContainer = document.getElementById('eggContainer');
const eggCreature = document.getElementById('eggCreature');
const helpBtn = document.getElementById('helpThresholdsBtn');
const helpModal = document.getElementById('helpModal');
const closeHelpModalBtn = document.querySelector('.close-help-modal');
const MAX_FILE_SIZE = 20 * 1024 * 1024;
const ALLOWED_MAX_TAGS = [50, 75, 100, 150, 200, 300];
const ratingTags = new Set(['safe', 'questionable', 'explicit']);
const creaturePaths = [
'/static/icons/egg/f1.png', '/static/icons/egg/f2.png', '/static/icons/egg/f3.png',
'/static/icons/egg/f4.png', '/static/icons/egg/f5.png', '/static/icons/egg/f6.png',
'/static/icons/egg/f7.png', '/static/icons/egg/f8.png', '/static/icons/egg/f9.png'
];
const categoryOrder = ['Copyright', 'Character', 'Species', 'Meta', 'General', 'Lore'];
let allTags = [];
let currentFormat = 'e621';
let savedFormat = 'e621';
let allThreshold = 0.55;
let confidentThreshold = 0.75;
let currentTheme = 'system';
let activePreset = 'standard';
let addedTags = new Set();
let removedTags = new Set();
let maxTags = 200;
let autoMetaTagSet = new Set();
let perTagAutoDisable = new Set();
const tagDescriptionCache = new Map();
let currentPopup = null;
let activePopupTagElement = null;
let pressBlockTap = false;
function preloadCreatures() {
creaturePaths.forEach(path => { new Image().src = path; });
}
preloadCreatures();
function loadSettings() {
const saved = localStorage.getItem('e621tagger-settings');
if (saved) {
try {
const settings = JSON.parse(saved);
allThreshold = settings.allThreshold ?? 0.55;
confidentThreshold = settings.confidentThreshold ?? 0.75;
savedFormat = settings.defaultFormat ?? 'e621';
currentFormat = savedFormat;
currentTheme = settings.theme ?? 'system';
activePreset = settings.activePreset ?? 'standard';
maxTags = settings.maxTags ?? 200;
if (!ALLOWED_MAX_TAGS.includes(maxTags)) maxTags = 200;
updateTheme(currentTheme);
updateLocalFormatUI();
updateSettingsFormatUI();
updateThresholdUI();
updateMaxTagsUI();
} catch (e) {
console.warn('Failed to load settings', e);
}
} else {
activePreset = 'standard';
maxTags = 200;
updateThresholdUI();
updateMaxTagsUI();
}
}
function saveSettings() {
localStorage.setItem('e621tagger-settings', JSON.stringify({
allThreshold, confidentThreshold, defaultFormat: savedFormat,
theme: currentTheme, activePreset, maxTags
}));
}
function updateMaxTagsUI() {
maxTagBtns.forEach(btn => {
const val = parseInt(btn.dataset.max);
btn.classList.toggle('active', val === maxTags);
});
updateToggleIndicator(document.querySelector('.max-tags-group'));
}
function updateTheme(theme) {
currentTheme = theme;
document.body.classList.remove('theme-light', 'theme-dark');
if (theme === 'light') document.body.classList.add('theme-light');
else if (theme === 'dark') document.body.classList.add('theme-dark');
themeOptions.forEach(opt => {
opt.classList.toggle('active', opt.dataset.theme === theme);
});
updateToggleIndicator(document.querySelector('.theme-toggle-group'));
}
function updateLocalFormatUI() {
const resultsGroups = document.querySelectorAll('.format-toggle-group[data-context="results"], .format-toggle-group[data-context="results-inline"]');
resultsGroups.forEach(resultsGroup => {
resultsGroup.querySelectorAll('.format-option').forEach(opt => {
opt.classList.toggle('active', opt.dataset.format === currentFormat);
});
updateToggleIndicator(resultsGroup);
});
}
function updateSettingsFormatUI() {
const settingsGroup = document.querySelector('.format-toggle-group[data-context="settings"]');
if (!settingsGroup) return;
settingsGroup.querySelectorAll('.format-option').forEach(opt => {
opt.classList.toggle('active', opt.dataset.format === savedFormat);
});
updateToggleIndicator(settingsGroup);
}
function updateThresholdUI() {
presetBtns.forEach(btn => {
btn.classList.toggle('active', btn.dataset.preset === activePreset);
});
customPanel.classList.toggle('open', activePreset === 'custom');
customAllInput.value = allThreshold.toFixed(2);
customConfidentInput.value = confidentThreshold.toFixed(2);
}
function updateToggleIndicator(group) {
if (!group) return;
const activeBtn = group.querySelector('.active');
if (!activeBtn) return;
let indicator = group.querySelector('.toggle-indicator');
if (!indicator) {
indicator = document.createElement('div');
indicator.className = 'toggle-indicator';
group.appendChild(indicator);
}
requestAnimationFrame(() => {
indicator.style.width = `${activeBtn.offsetWidth}px`;
indicator.style.height = `${activeBtn.offsetHeight}px`;
indicator.style.left = `${activeBtn.offsetLeft}px`;
indicator.style.top = `${activeBtn.offsetTop}px`;
});
}
function initToggleIndicators() {
updateToggleIndicator(document.querySelector('.theme-toggle-group'));
updateToggleIndicator(document.querySelector('.format-toggle-group[data-context="results"]'));
updateToggleIndicator(document.querySelector('.format-toggle-group[data-context="results-inline"]'));
updateToggleIndicator(document.querySelector('.format-toggle-group[data-context="settings"]'));
updateToggleIndicator(document.querySelector('.max-tags-group'));
}
function refreshTagClasses() {
document.querySelectorAll('.tag').forEach(el => {
const tagName = el.dataset.tag;
const tagObj = allTags.find(t => t.tag === tagName);
if (!tagObj) return;
el.removeAttribute('data-level');
if (addedTags.has(tagName)) {
el.setAttribute('data-level', 'added');
} else if (removedTags.has(tagName)) {
el.setAttribute('data-level', 'removed');
} else if (tagObj.prob >= confidentThreshold) {
el.setAttribute('data-level', 'confident');
} else if (tagObj.prob >= allThreshold) {
el.setAttribute('data-level', 'all');
}
});
updateCategoryButtonsDisabled();
}
function applyThresholds() {
if (allTags.length) {
refreshTagClasses();
setupCategoryCopyButtons();
}
updateThresholdUI();
saveSettings();
}
function toggleSettings(show) {
settingsMenu.classList.toggle('show', show);
settingsToggle.classList.toggle('open', show);
if (show) {
positionSettingsMenu();
initToggleIndicators();
}
}
function positionSettingsMenu() {
const toggleRect = settingsToggle.getBoundingClientRect();
const containerRect = document.querySelector('.container').getBoundingClientRect();
settingsMenu.style.left = (toggleRect.left - containerRect.left) + 'px';
settingsMenu.style.top = (toggleRect.bottom - containerRect.top + 5) + 'px';
}
function showNotification(message, type = 'error', duration = 3000) {
const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.textContent = message;
notificationContainer.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut 0.3s ease forwards';
setTimeout(() => notification.remove(), 300);
}, duration);
}
function escapeHtml(unsafe) {
if (!unsafe) return '';
return unsafe.replace(/[&<>]/g, m => m === '&' ? '&' : m === '<' ? '<' : '>');
}
function sanitizeHtml(html) {
if (!html) return '';
const dangerousAttrs = /\s+(on\w+|style\s*=\s*["']?(?:javascript:|expression\()[^"']*)/gi;
let previous;
do {
previous = html;
html = html.replace(/<(?!\/?(?:strong|em|u|sup|span|br)\b)[^>]*>/gi, (match) => {
return match.replace(//g, '>');
});
} while (html !== previous);
do {
previous = html;
html = html.replace(dangerousAttrs, '');
} while (html !== previous);
return html;
}
function parseDText(dtext) {
if (!dtext) return '';
let text = escapeHtml(dtext.slice(0, 1000));
text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
text = text.replace(/thumb\s+#\d+\s*/g, '');
text = text.replace(/\[section[^\]]*\]([\s\S]*?)\[\/section\]/g, '$1');
text = text.replace(/\[quote[^\]]*\]([\s\S]*?)\[\/quote\]/g, '$1');
text = text.replace(/\[table[^\]]*\]([\s\S]*?)\[\/table\]/g, '$1');
text = text.replace(/\[s\]([\s\S]*?)\[\/s\]/g, '$1');
text = text.replace(/\[color=([^\]]+)\]([\s\S]*?)\[\/color\]/g, '$2');
text = text.replace(/"([^"]+)"\s*:\s*(\S+)/g, (match, linkText) => `${linkText}`);
text = text.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, (match, target, display) => `${display}`);
text = text.replace(/\[\[([^\]]+)\]\]/g, (match, p1) => `${p1}`);
let lines = text.split('\n');
let processedLines = [];
for (let line of lines) {
let trimmed = line;
const headerMatch = trimmed.match(/^\s*h([1-6])(?:\.?\s*)(.*)$/i);
if (headerMatch) trimmed = `${headerMatch[2]}`;
else trimmed = trimmed.replace(/^(\*+)\s+/, '');
if (trimmed.trim() !== '') processedLines.push(trimmed);
}
text = processedLines.join('\n');
text = text.replace(/\[b\]([\s\S]*?)\[\/b\]/g, '$1');
text = text.replace(/\[i\]([\s\S]*?)\[\/i\]/g, '$1');
text = text.replace(/\[u\]([\s\S]*?)\[\/u\]/g, '$1');
text = text.replace(/\[sup\]([\s\S]*?)\[\/sup\]/g, '$1');
text = text.replace(/\n/g, '
');
text = text.replace(/(
){3,}/g, '
');
text = text.replace(/^(
)+/, '').replace(/(
)+$/, '');
if (dtext.length > 1000) text += '…';
return text;
}
async function fetchTagDescription(tagName) {
if (tagDescriptionCache.has(tagName)) return tagDescriptionCache.get(tagName);
const url = `https://e621.net/wiki_pages.json?search[title]=${encodeURIComponent(tagName)}&limit=1`;
try {
const response = await fetch(url, { headers: { 'User-Agent': 'e621tagger/1.0 (https://tagger.fenrir784.ru)' } });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
if (data && data.length) {
const wiki = data[0];
const result = { exists: true, title: wiki.title || tagName, body: wiki.body || 'No description available.' };
tagDescriptionCache.set(tagName, result);
return result;
} else {
const result = { exists: false, title: tagName, body: 'No description found on e621.' };
tagDescriptionCache.set(tagName, result);
return result;
}
} catch (err) {
console.warn(`Failed to fetch description for ${tagName}:`, err);
return { exists: false, title: tagName, body: 'Failed to load description. Please check your internet connection.' };
}
}
function closePopup() {
if (currentPopup) {
currentPopup.remove();
currentPopup = null;
}
activePopupTagElement = null;
}
function showTagPopup(tagObj, targetElement) {
if (currentPopup && activePopupTagElement === targetElement) return;
if (currentPopup) closePopup();
activePopupTagElement = targetElement;
const tagName = tagObj.tag;
const popup = document.createElement('div');
popup.className = 'tag-popup';
const wikiUrl = `https://e621.net/wiki_pages?title=${encodeURIComponent(tagName)}`;
popup.innerHTML = `