# JavaScript Reference Documentation This document provides a comprehensive reference for all methods, variables, and configurations in `static/js/script.js` (935 lines). It is designed for agent systems to understand and interact with the e621tagger frontend. --- ## File Overview | Attribute | Value | |-----------|-------| | Location | `static/js/script.js` | | Lines | 935 | | Framework | Vanilla JavaScript | | Purpose | Frontend UI functionality | | Dependencies | Hammer.js (touch events), escapeHtml/sanitizeHtml/XSS protection | ### File Structure Flow ``` script.js (935 lines) ├── 1. Constants (27-45) - Configuration values ├── 2. State Variables (47-68) - Runtime application state ├── 3. DOM Cached (2-25) - DOM element references ├── 4. preloadCreatures (70-73) - Preload easter egg images ├── 5. loadSettings (75-109) - Load from localStorage ├── 6. saveSettings (111-116) - Save to localStorage ├── 7. UI Functions (118-195) - Theme, notifications, popups ├── 8. XSS Protection (240-294) - escapeHtml, sanitizeHtml, parseDText ├── 9. Tag Functions (395-623) - Handle, display, filter tags ├── 10. Copy Functions (444-520) - Clipboard, format conversion ├── 11. File Handling (627-706) - Drag/drop, preview, validation ├── 12. Fullscreen Image (194-235) - Fullscreen modal functions ├── 13. Help Modal (745-765) - Help modal functions ├── 14. initHammer (772-870) - Hammer.js touch setup ├── 15. Event Listeners (872-915) - Attach all listeners └── 16. Final Init (917-935) - Final setup ``` --- ## 1. Constants ```javascript const MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB 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 copyCategoryOrder = ['Copyright', 'Character', 'Species', 'Meta', 'General', 'Lore']; const displayCategoryOrder = [ 'General', 'Artist', 'Contributor', 'Copyright', 'Character', 'Species', 'Invalid', 'Meta', 'Accessories, Items, Clothing', 'Actions, Positions, State', 'Body Features', 'Effects, Fluids', 'Fetishes, Specifics, Interactions', 'Genders, Demographics', 'Locations, Backgrounds, Setting', 'Poses, Scenarios, Situations', 'Style, Perspective', 'Text, Symbols, UI, Vocalization', 'Other', 'Body Color', 'Lore' ]; const tagDescriptionCache = new Map(); // Cache for e621 wiki tag descriptions ``` | Constant | Value | Description | |----------|-------|-------------| | `MAX_FILE_SIZE` | 20MB | Maximum upload file size | | `ALLOWED_MAX_TAGS` | [50,75,100,150,200,300] | Valid top_k values | | `ratingTags` | {safe, questionable, explicit} | Rating tag names | | `creaturePaths` | 9 image paths | Easter egg creature images | | `copyCategoryOrder` | 6 categories | e621 category order for copy action (100-111 merged into General) | | `displayCategoryOrder` | 21 categories | Visual order for site display (Body Color and Lore at bottom) | | `tagDescriptionCache` | Map | Caches wiki descriptions to reduce API calls | --- ## 2. State Variables ```javascript let allTags = []; // Tag predictions from API let currentFormat = 'e621'; // 'e621' for danbooru format, any other for PostyBirb let savedFormat = 'e621'; // 'e621' for danbooru format, any other for PostyBirb let allThreshold = 0.60; // Lower threshold (include) let confidentThreshold = 0.70; // Upper threshold (confident) let currentTheme = 'system'; // 'system', 'light', 'dark' let activePreset = 'standard'; // 'conservative'/'standard'/'liberal'/'custom' let addedTags = new Set(); // User-added tags let removedTags = new Set(); // User-removed tags let hiddenCategories = new Set(); // Session-hidden categories (per upload, non-persistent) let alwaysHiddenCategories = new Set(); // Persisted hidden categories (localStorage) let maxTags = 200; // Max tags to request let autoMetaTagSet = new Set(); // Auto-detected meta tags let perTagAutoDisable = new Set(); // Per-tag auto disable let currentPopup = null; // Active popup DOM element let activePopupTagElement = null; // Popup trigger element let pressBlockTap = false; // Press event blocking flag let fullscreenImageModal = null; // Fullscreen modal DOM element let isFullscreenActive = false; // Fullscreen modal state ``` | Variable | Type | Default | Description | |----------|------|---------|-------------| | `allTags` | Array | [] | Tag predictions from API | | `currentFormat` | string | 'e621' | Runtime output format | | `savedFormat` | string | 'e621' | Persisted default format | | `allThreshold` | float | 0.60 | Include threshold | | `confidentThreshold` | float | 0.70 | High confidence threshold | | `currentTheme` | string | 'system' | UI theme | | `activePreset` | string | 'standard' | Threshold preset | | `addedTags` | Set | - | User-added tags | | `removedTags` | Set | - | User-removed tags | | `hiddenCategories` | Set | - | Session-only hidden categories (per upload, non-persistent) | | `alwaysHiddenCategories` | Set | - | Persistently hidden categories from localStorage | | `maxTags` | int | 200 | API top_k parameter | | `autoMetaTagSet` | Set | - | Auto meta tags | | `perTagAutoDisable` | Set | - | Disabled auto tags | | `addCurrentYearTag` | boolean | true | Whether to include current year meta tag | ### Threshold Presets ```javascript const presets = { conservative: { all: 0.70, confident: 0.80 }, standard: { all: 0.60, confident: 0.70 }, liberal: { all: 0.50, confident: 0.60 } }; ``` | Preset | allThreshold | confidentThreshold | |--------|------------|-----------------| | conservative | 0.70 | 0.80 | | standard | 0.60 | 0.70 | | liberal | 0.50 | 0.60 | | custom | user-defined | user-defined | --- ## 3. DOM Cached Elements | Variable | Element ID / Selector | Usage | |----------|----------------------|-------| | `dropZone` | `dropZone` | File upload area | | `fileInput` | `fileInput` | Hidden file input | | `uploadContent` | `uploadContent` | Upload prompt text | | `results` | `results` | Results container | | `resultsContent` | `resultsContent` | Tags display area | | `notificationContainer` | `notification-container` | Toast notifications | | `categoriesContainer` | `categoriesContainer` | Category tag groups | | `ratingDisplay` | `ratingDisplay` | Rating badge | | `copyGlobalAll` | `copyGlobalAll` | Copy all button | | `copyGlobalConfident` | `copyGlobalConfident` | Copy confident button | | `settingsToggle` | `settingsToggle` | Settings toggle button | | `settingsMenu` | `settingsMenu` | Settings panel | | `closeSettings` | `closeSettings` | Close settings button | | `presetBtns` | `.preset-btn` | Threshold preset buttons | | `customPanel` | `customThresholdsPanel` | Custom thresholds panel | | `customAllInput` | `customAll` | Custom all threshold input | | `customConfidentInput` | `customConfident` | Custom confident threshold input | | `applyCustom` | `applyCustom` | Apply custom button | | `resetBtn` | `resetSettings` | Reset button | | `eggContainer` | `eggContainer` | Easter egg container | | `eggCreature` | `eggCreature` | Easter egg image | | `helpBtn` | `helpThresholdsBtn` | Help button | | `helpModal` | `helpModal` | Help modal | | `closeHelpModalBtn` | `.close-help-modal` | Close help modal button | | `yearTagToggle` | `yearTagToggle` | Year switch checkbox (Apple-style) | --- ## 4. Settings Functions ### preloadCreatures() Preloads easter egg creature images for instant display. ```javascript function preloadCreatures() { creaturePaths.forEach(path => { new Image().src = path; }); } preloadCreatures(); // Called at initialization ``` ### loadSettings() Loads persisted settings from localStorage. ```javascript function loadSettings() { const saved = localStorage.getItem('e621tagger-settings'); if (saved) { try { const settings = JSON.parse(saved); allThreshold = settings.allThreshold ?? 0.60; confidentThreshold = settings.confidentThreshold ?? 0.70; 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; alwaysHiddenCategories = new Set(settings.alwaysHiddenCategories || []); addCurrentYearTag = settings.addCurrentYearTag ?? true; document.querySelectorAll('#themeToggle .theme-option').forEach(btn => { btn.classList.toggle('active', btn.dataset.value === currentTheme); }); document.querySelectorAll('#maxTagsToggle .max-tag-option').forEach(btn => { btn.classList.toggle('active', btn.dataset.value === String(maxTags)); }); const yearTagToggle = document.getElementById('yearTagToggle'); if (yearTagToggle) yearTagToggle.checked = addCurrentYearTag; updateTheme(currentTheme); updateThresholdUI(); } catch (e) { console.warn('Failed to load settings', e); } } else { activePreset = 'standard'; maxTags = 200; updateThresholdUI(); } } ``` **IMPORTANT:** LocalStorage key is `e621tagger-settings` as a JSON string. | localStorage Key | State Variable | |----------------|--------------| | allThreshold | allThreshold | | confidentThreshold | confidentThreshold | | defaultFormat | savedFormat, currentFormat | | theme | currentTheme | | activePreset | activePreset | | maxTags | maxTags | | alwaysHiddenCategories | alwaysHiddenCategories | | addCurrentYearTag | addCurrentYearTag | ### saveSettings() Persists settings to localStorage. ```javascript function saveSettings() { localStorage.setItem('e621tagger-settings', JSON.stringify({ allThreshold, confidentThreshold, defaultFormat: savedFormat, theme: currentTheme, activePreset, maxTags, alwaysHiddenCategories: [...alwaysHiddenCategories], addCurrentYearTag })); } ``` ### updateTheme(theme) Applies theme class to document body. ```javascript 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'); } ``` ### toggleSettings(show) Shows or hides the settings panel. ```javascript function toggleSettings(show) { settingsMenu.classList.toggle('show', show); settingsToggle.classList.toggle('open', show); if (show) positionSettingsMenu(); } 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'; } ``` ### updateThresholdUI() Updates UI to reflect current threshold state. ```javascript 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); } ``` ### updateLocalFormatUI() Updates format toggle UI. ```javascript function updateLocalFormatUI() { document.querySelectorAll('#resultsFormatToggle .format-option').forEach(btn => { btn.classList.toggle('active', btn.dataset.value === currentFormat); }); } ``` --- ## 5. XSS Protection Functions ### escapeHtml(unsafe) Escapes HTML entities for safe display. ```javascript function escapeHtml(unsafe) { if (!unsafe) return ''; return unsafe.replace(/[&<>"']/g, m => m === '&' ? '&' : m === '<' ? '<' : m === '>' ? '>' : m === '"' ? '"' : '''); } ``` ### sanitizeHtml(html) Removes dangerous HTML (event handlers, javascript:). ```javascript 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; } ``` ### parseDText(dtext) Parses e621 wiki DText markup to HTML. ```javascript 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; } ``` --- ## 6. Notification Functions ### showNotification(message, type, duration) Shows a toast notification. ```javascript 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); } ``` | Type | CSS Class | Duration | |------|----------|----------| | error | .notification.error | 3000ms | | success | .notification.success | 3000ms | | info | .notification.info | 5000ms | --- ## 7. Tag Popup Functions ### fetchTagDescription(tagName) Fetches tag description from e621 wiki API. ```javascript 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.app)' } }); 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.' }; } } ``` **IMPORTANT:** Uses `/wiki_pages.json` endpoint, NOT `autocomplete.json`. ### showTagPopup(tagObj, targetElement) Shows tag details popup with description. ```javascript 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 = `
${escapeHtml(tagName)} read more
Loading description...
`; document.body.appendChild(popup); currentPopup = popup; const rect = targetElement.getBoundingClientRect(); const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; popup.style.visibility = 'hidden'; popup.style.position = 'absolute'; const popupRect = popup.getBoundingClientRect(); popup.style.visibility = ''; let top = rect.bottom + 8; let left = rect.left + (rect.width / 2) - (popupRect.width / 2); if (top + popupRect.height > viewportHeight - 10) top = rect.top - popupRect.height - 8; left = Math.max(10, Math.min(left, viewportWidth - popupRect.width - 10)); popup.style.top = `${top + window.scrollY}px`; popup.style.left = `${left + window.scrollX}px`; const closeBtn = popup.querySelector('.close-popup'); closeBtn.addEventListener('click', () => closePopup()); const copyBtn = popup.querySelector('.tag-popup-copy-btn'); copyBtn.addEventListener('click', async (e) => { e.stopPropagation(); if (copyBtn._copyTimeout) clearTimeout(copyBtn._copyTimeout); try { if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(tagName); } else { const ta = document.createElement('textarea'); ta.value = tagName; ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); } copyBtn.classList.add('copied'); copyBtn._copyTimeout = setTimeout(() => copyBtn.classList.remove('copied'), 1000); } catch {} }); fetchTagDescription(tagName).then(desc => { const content = popup.querySelector('.tag-popup-content'); if (desc.exists) content.innerHTML = `
${sanitizeHtml(parseDText(desc.body))}
`; else content.innerHTML = `
${escapeHtml(desc.body)}
`; }).catch(() => { popup.querySelector('.tag-popup-content').innerHTML = '
Failed to load description.
'; }); } ``` ### closePopup() Closes the active tag popup. ```javascript function closePopup() { if (currentPopup) { currentPopup.remove(); currentPopup = null; } activePopupTagElement = null; } ``` --- ## 8. Tag Handling Functions ### handleTagClick(tagObj) Handles tag click to toggle include/exclude state. ```javascript function handleTagClick(tagObj) { if (pressBlockTap) return; const tag = tagObj.tag; const prob = tagObj.prob; const isConfident = prob >= confidentThreshold; const isAll = prob >= allThreshold; const wasAdded = addedTags.has(tag); const wasRemoved = removedTags.has(tag); if (isConfident) { if (!wasAdded && !wasRemoved) removedTags.add(tag); else if (wasRemoved) removedTags.delete(tag); else if (wasAdded) addedTags.delete(tag); } else if (isAll) { if (!wasAdded && !wasRemoved) addedTags.add(tag); else if (wasAdded) { addedTags.delete(tag); removedTags.add(tag); } else if (wasRemoved) removedTags.delete(tag); } else { if (!wasAdded && !wasRemoved) addedTags.add(tag); else if (wasAdded) addedTags.delete(tag); else if (wasRemoved) removedTags.delete(tag); } document.querySelectorAll(`.tag[data-tag="${tag}"]`).forEach(el => updateTagElement(el, tagObj)); refreshTagClasses(); } ``` | Current State | isConfident | isAll | Action | |---------------|-------------|-------|--------| | None | yes | - | Add to removedTags | | None | - | yes | Add to addedTags | | None | no | no | Add to addedTags | | addedTags | yes | - | Remove from addedTags | | addedTags | no | yes | Move to removedTags | | removedTags | any | - | Remove from removedTags | ### updateTagElement(el, tagObj) Updates a single tag element's data-level attribute while preserving data-original-level. ```javascript function updateTagElement(el, tagObj) { const origLevel = el.dataset.originalLevel; el.removeAttribute('data-level'); if (addedTags.has(tagObj.tag)) { el.setAttribute('data-level', 'added'); if (origLevel) el.setAttribute('data-original-level', origLevel); } else if (removedTags.has(tagObj.tag)) { el.setAttribute('data-level', 'removed'); if (origLevel) el.setAttribute('data-original-level', origLevel); } } ``` ### refreshTagClasses() Refreshes all tag elements' data-level attributes when thresholds change. Updates data-original-level to reflect current baseline so that manual toggles afterward preserve bold correctly. ```javascript 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'); el.setAttribute('data-original-level', 'confident'); } else if (tagObj.prob >= allThreshold) { el.setAttribute('data-level', 'all'); el.setAttribute('data-original-level', 'all'); } }); } ``` ### isTagIncluded(tagObj, threshold) Determines if a tag should be included in output. ```javascript function isTagIncluded(tagObj, threshold) { if (perTagAutoDisable.has(tagObj.tag)) return false; const tag = tagObj.tag; if (removedTags.has(tag)) return false; if (addedTags.has(tag)) return true; return tagObj.prob >= threshold; } ``` ### filterTags(threshold) Filters tags by probability threshold and excludes tags from hidden categories. ```javascript function filterTags(threshold) { return allTags.filter(t => !ratingTags.has(t.tag) && !hiddenCategories.has(t.category) && isTagIncluded(t, threshold)); } ``` ### displayTags(tags) Main tag rendering function - creates DOM elements. ```javascript function displayTags(tags) { let rating = null; const nonRatingTags = []; tags.forEach(t => { if (ratingTags.has(t.tag)) { if (!rating || t.prob > rating.prob) rating = t; } else nonRatingTags.push(t); }); if (rating) { ratingDisplay.textContent = `Rating: ${rating.tag}`; ratingDisplay.className = 'rating-display ' + rating.tag; ratingDisplay.style.display = 'inline-block'; } else ratingDisplay.style.display = 'none'; const grouped = {}; nonRatingTags.sort((a, b) => b.prob - a.prob); nonRatingTags.forEach(item => { const cat = item.category || 'Other'; if (!grouped[cat]) grouped[cat] = []; grouped[cat].push(item); }); categoriesContainer.innerHTML = ''; Object.keys(grouped).sort((a, b) => { const aAlways = alwaysHiddenCategories.has(a); const bAlways = alwaysHiddenCategories.has(b); if (aAlways && !bAlways) return 1; if (!aAlways && bAlways) return -1; const ia = displayCategoryOrder.indexOf(a); const ib = displayCategoryOrder.indexOf(b); if (ia !== -1 && ib !== -1) return ia - ib; if (ia !== -1) return -1; if (ib !== -1) return 1; return a.localeCompare(b); }).forEach(cat => { const catTags = grouped[cat]; const isHidden = hiddenCategories.has(cat); const isAlways = alwaysHiddenCategories.has(cat); const catDiv = document.createElement('div'); catDiv.className = 'category-block' + (isHidden ? ' category-hidden' : ''); catDiv.innerHTML = `
${escapeHtml(cat)}
Always hide
`; const tagsContainer = catDiv.querySelector('.category-tags'); catTags.forEach(item => { const tagEl = document.createElement('span'); tagEl.className = 'tag'; tagEl.setAttribute('data-tag', item.tag); tagEl.textContent = item.tag; if (addedTags.has(item.tag)) { tagEl.setAttribute('data-level', 'added'); } else if (removedTags.has(item.tag)) { tagEl.setAttribute('data-level', 'removed'); } else if (item.prob >= confidentThreshold) { tagEl.setAttribute('data-level', 'confident'); tagEl.setAttribute('data-original-level', 'confident'); } else if (item.prob >= allThreshold) { tagEl.setAttribute('data-level', 'all'); tagEl.setAttribute('data-original-level', 'all'); } attachTagEvents(tagEl, item); tagsContainer.appendChild(tagEl); }); const toggleBtn = catDiv.querySelector('.category-toggle-btn'); toggleBtn.addEventListener('click', (e) => { e.stopPropagation(); if (hiddenCategories.has(cat)) { hiddenCategories.delete(cat); catDiv.classList.remove('category-hidden'); toggleBtn.textContent = '✕'; alwaysHideEl.style.display = 'none'; } else { hiddenCategories.add(cat); catDiv.classList.add('category-hidden'); toggleBtn.textContent = '✓'; alwaysHideEl.style.display = 'inline'; } }); const alwaysHideEl = catDiv.querySelector('.category-always-hide'); alwaysHideEl.addEventListener('click', (e) => { e.stopPropagation(); if (alwaysHiddenCategories.has(cat)) { alwaysHiddenCategories.delete(cat); alwaysHideEl.classList.remove('active'); } else { alwaysHiddenCategories.add(cat); hiddenCategories.add(cat); catDiv.classList.add('category-hidden'); toggleBtn.textContent = '✓'; alwaysHideEl.style.display = 'inline'; alwaysHideEl.classList.add('active'); } saveSettings(); }); categoriesContainer.appendChild(catDiv); }); } ``` ### Category Toggle Functions The toggle button (✕/✓) and "Always hide" text are rendered inside each `.category-header` by `displayTags()`. #### Toggle Button Handler The toggle and always-hide logic is handled inline within `displayTags()` via direct `addEventListener` calls on the rendered elements: **Toggle button (✕/✓)**: ```javascript toggleBtn.addEventListener('click', (e) => { e.stopPropagation(); if (hiddenCategories.has(cat)) { hiddenCategories.delete(cat); catDiv.classList.remove('category-hidden'); toggleBtn.textContent = '✕'; alwaysHideEl.style.display = 'none'; } else { hiddenCategories.add(cat); catDiv.classList.add('category-hidden'); toggleBtn.textContent = '✓'; alwaysHideEl.style.display = 'inline'; } }); ``` **Always hide text**: ```javascript alwaysHideEl.addEventListener('click', (e) => { e.stopPropagation(); if (alwaysHiddenCategories.has(cat)) { alwaysHiddenCategories.delete(cat); alwaysHideEl.classList.remove('active'); } else { alwaysHiddenCategories.add(cat); hiddenCategories.add(cat); catDiv.classList.add('category-hidden'); toggleBtn.textContent = '✓'; alwaysHideEl.style.display = 'inline'; alwaysHideEl.classList.add('active'); } saveSettings(); }); ``` #### displayTags Integration `displayTags()` renders each `.category-header` with a `.category-header-actions` flex container on the right side containing: - A `.category-toggle-btn` (✕ when visible, ✓ when hidden) - A `.category-always-hide` span (only present when category is hidden; gets `.active` class and purple underline when persisted) The function determines `isHidden` and `isAlways` state per category on each render call. The `.category-block` receives `.category-hidden` class when `isHidden` is true. Tags inside hidden blocks are made non-interactive via CSS `pointer-events: none`. #### State Flow ``` uploadImage() → hiddenCategories = new Set(alwaysHiddenCategories) → displayTags() ↓ Click ✕ → hiddenCategories.add(cat) → DOM: add class, ✓, show always-hide ↓ Click ✓ → hiddenCategories.delete(cat) → DOM: remove class, ✕, hide always-hide ↓ Always hide click → toggles alwaysHiddenCategories, saves → DOM: add/remove .active class ``` --- ## 9. Tag States (CSS data-level) **IMPORTANT:** Tags use `data-level` attribute, NOT CSS classes. Tag bold font is preserved when manually adding/removing tags by storing original confidence level in `data-original-level` attribute. This allows CSS to keep bold font for tags that were originally confident even after threshold changes or manual state toggles. ```javascript // Setting data-level attribute el.setAttribute('data-level', 'confident'); // High confidence el.setAttribute('data-level', 'all'); // Above all threshold el.setAttribute('data-level', 'added'); // User added el.setAttribute('data-level', 'removed'); // User removed // Preserving original level for bold font el.setAttribute('data-original-level', 'confident'); // Preserve bold when manually toggling el.setAttribute('data-original-level', 'all'); // Preserve normal weight ``` | data-level | Condition | CSS Variable | |-----------|----------|-------------| | confident | prob >= confidentThreshold | --confident-bg (purple) | | all | prob >= allThreshold | --all-bg (blue) | | added | addedTags.has(tag) | --added-bg (green) | | removed | removedTags.has(tag) | --removed-bg (red) | | (none) | Below allThreshold | --low-bg (gray) | | data-original-level | CSS Effect | |--------------------|-----------| | confident | font-weight: 600 (bold) | | all | font-weight: 400 (normal) | --- ## 10. Copy Functions ### formatTags(tags) Formats tags for clipboard output. ```javascript function formatTags(tags) { if (currentFormat === 'e621') { const grouped = {}; tags.forEach(t => { let cat = t.category || 'Other'; if (cat === 'Body Color') cat = 'General'; else if (cat === 'Accessories, Items, Clothing') cat = 'General'; else if (cat === 'Actions, Positions, State') cat = 'General'; else if (cat === 'Body Features') cat = 'General'; else if (cat === 'Effects, Fluids') cat = 'General'; else if (cat === 'Fetishes, Specifics, Interactions') cat = 'General'; else if (cat === 'Genders, Demographics') cat = 'General'; else if (cat === 'Locations, Backgrounds, Setting') cat = 'General'; else if (cat === 'Poses, Scenarios, Situations') cat = 'General'; else if (cat === 'Style, Perspective') cat = 'General'; else if (cat === 'Text, Symbols, UI, Vocalization') cat = 'General'; else if (cat === 'Other') cat = 'General'; if (!grouped[cat]) grouped[cat] = []; grouped[cat].push(t.tag); }); const sortedCats = Object.keys(grouped).sort((a, b) => { const ia = copyCategoryOrder.indexOf(a); const ib = copyCategoryOrder.indexOf(b); if (ia !== -1 && ib !== -1) return ia - ib; if (ia !== -1) return -1; if (ib !== -1) return 1; return a.localeCompare(b); }); return sortedCats.map(cat => grouped[cat].join(' ')).join('\n'); } else { return tags.map(t => t.tag.replace(/_/g, ' ')).join(', '); } } ``` | Format | Internal Value | Separator | Example Output | |--------|---------------|-----------|-------------| | e621 | `'e621'` (danbooru) | space | `female anthro solo` (per line) | | PostyBirb | any other value | comma | `female, anthro, solo` | ### copyToClipboard(text, count, format, btn) Copies text to clipboard with auto-meta tags. ```javascript async function copyToClipboard(text, count, format, btn) { if (navigator.clipboard && navigator.clipboard.writeText) { try { let finalText = text; if (autoMetaTagSet && autoMetaTagSet.size > 0) { const extras = []; autoMetaTagSet.forEach(t => { if (perTagAutoDisable.has(t)) return; if (text.includes(t) || text.includes(t.replace(/_/g, ' '))) return; extras.push(t); }); if (extras.length > 0) { const joiner = (format === 'e621') ? ' ' : ', '; finalText = finalText ? finalText + (joiner) + extras.join(joiner) : extras.join(joiner); } } await navigator.clipboard.writeText(finalText); showCopySuccess(btn, count, format); } catch { fallbackCopy(text, btn, count, format); } } else { fallbackCopy(text, btn, count, format); } } ``` ### fallbackCopy(text, btn, count, format) Fallback clipboard copy for older browsers. ```javascript function fallbackCopy(text, btn, count, format) { const textarea = document.createElement('textarea'); textarea.value = text; textarea.style.position = 'fixed'; textarea.style.opacity = '0'; document.body.appendChild(textarea); textarea.select(); try { if (document.execCommand('copy')) showCopySuccess(btn, count, format); else showNotification('Unable to copy.', 'error'); } catch { showNotification('Copy failed.', 'error'); } document.body.removeChild(textarea); } ``` ### showCopySuccess(btn, count, format) Shows copy success state on button. ```javascript function showCopySuccess(btn, count, format) { if (btn._copyTimeout) clearTimeout(btn._copyTimeout); btn.classList.add('copied'); const displayName = format === 'e621' ? 'e621' : 'PostyBirb'; showNotification(`📋 Copied ${count} ${count === 1 ? 'tag' : 'tags'} • ${displayName}`, 'success'); btn._copyTimeout = setTimeout(() => btn.classList.remove('copied'), 1000); } ``` --- ## 11. File Handling Functions ### handleFiles(files) Processes uploaded files. ```javascript function handleFiles(files) { if (files.length === 0) return; const file = files[0]; if (!file.type.startsWith('image/')) { showNotification('Please select an image file.', 'error'); return; } if (file.size > MAX_FILE_SIZE) { showNotification(`File too large. Maximum size is ${MAX_FILE_SIZE / (1024*1024)}MB.`, 'error'); return; } uploadImage(file); } ``` ### showPreview(file) Shows image preview and fetches tags. ```javascript function showPreview(file) { const existingImg = dropZone.querySelector('img'); if (existingImg) existingImg.remove(); uploadContent.style.display = 'none'; const img = document.createElement('img'); img.src = URL.createObjectURL(file); img.alt = 'Preview'; img.onload = function() { img.width = img.naturalWidth; img.height = img.naturalHeight; }; dropZone.appendChild(img); dropZone.classList.add('has-image'); } ``` ### uploadImage(file) Uploads image to API and processes response. ```javascript async function uploadImage(file) { showPreview(file); dropZone.classList.add('uploading'); const wasVisible = results.classList.contains('visible'); if (wasVisible) await hideResults(); const formData = new FormData(); formData.append('image', file); formData.append('top_k', maxTags.toString()); try { const response = await fetch('/predict', { method: 'POST', body: formData }); if (!response.ok) { let errorMsg = 'Server error. Please try again later.'; try { const data = await response.json(); errorMsg = data.error || errorMsg; } catch (e) {} throw new Error(errorMsg); } const data = await response.json(); if (data.success) { const baseTags = data.tags || []; const autoMeta = data.auto_meta || []; const merged = baseTags.slice(); const currentYearTag = String(new Date().getFullYear()); autoMeta.forEach(t => { if (!merged.find(x => x.tag === t)) { if (t === currentYearTag && !addCurrentYearTag) return; merged.push({ tag: t, prob: 1.0, category: 'Meta' }); } }); allTags = merged; autoMetaTagSet = new Set(autoMeta); addedTags.clear(); removedTags.clear(); hiddenCategories = new Set(alwaysHiddenCategories); // Re-apply persistent hidden currentFormat = savedFormat; updateLocalFormatUI(); displayTags(allTags); await showResults(); } else showNotification(data.error || 'Failed to generate tags.', 'error'); } catch (err) { showNotification(err.message || 'Network error. Please try again.', 'error'); } finally { dropZone.classList.remove('uploading'); } } ``` --- ## 12. Fullscreen Image Functions ### State Variables ```javascript let fullscreenImageModal = null; // Modal DOM element (dynamically created) let isFullscreenActive = false; // Current state ``` ### createFullscreenModal() Creates the fullscreen modal DOM element dynamically. Called on first use. ```javascript function createFullscreenModal() { const modal = document.createElement('div'); modal.id = 'fullscreenImageModal'; modal.className = 'fullscreen-image-modal'; modal.innerHTML = `
Fullscreen preview
`; document.body.appendChild(modal); modal.addEventListener('click', hideFullscreenImage); return modal; } ``` ### showFullscreenImage(src) Shows the fullscreen modal with the provided image source. ```javascript function showFullscreenImage(src) { if (!fullscreenImageModal) { fullscreenImageModal = createFullscreenModal(); } fullscreenImageModal.style.display = 'flex'; const img = document.getElementById('fullscreenImage'); img.src = src; document.body.classList.add('modal-open'); requestAnimationFrame(() => fullscreenImageModal.classList.add('show')); isFullscreenActive = true; } ``` ### hideFullscreenImage() Hides the fullscreen modal and resets state. Uses transition cleanup to properly hide the modal after fade animation completes. ```javascript function hideFullscreenImage() { if (!fullscreenImageModal) return; fullscreenImageModal.classList.remove('show'); const cleanup = () => { if (!fullscreenImageModal.classList.contains('show')) { fullscreenImageModal.style.display = 'none'; document.body.classList.remove('modal-open'); } fullscreenImageModal.removeEventListener('transitionend', cleanup); }; fullscreenImageModal.addEventListener('transitionend', cleanup, { once: true }); isFullscreenActive = false; } ``` ### Keyboard Shortcuts > **Note:** Uses `e.code` for layout-independent key detection (works on all keyboard layouts). | Key | Action | |-----|--------| | `F` (or `KeyF` position) | Toggle fullscreen (open/close) | | `ESC` | Close fullscreen | ### Modal Click Clicking anywhere within the fullscreen modal (overlay or image) closes it. ### LocalStorage None - fullscreen state is ephemeral and not persisted. --- ## 13. Help Modal Functions ### openHelpModal() ```javascript function openHelpModal() { if (settingsMenu.classList.contains('show')) toggleSettings(false); helpModal.style.display = 'flex'; document.body.classList.add('modal-open'); requestAnimationFrame(() => helpModal.classList.add('show')); } ``` ### closeHelpModal() ```javascript function closeHelpModal() { helpModal.classList.remove('show'); const cleanup = () => { if (!helpModal.classList.contains('show')) { helpModal.style.display = 'none'; document.body.classList.remove('modal-open'); } helpModal.removeEventListener('transitionend', cleanup); }; helpModal.addEventListener('transitionend', cleanup, { once: true }); setTimeout(() => { if (helpModal.style.display === 'flex') cleanup(); }, 500); } ``` --- ## 14. Hammer.js Setup Functions ### attachHammerTap(element, handler) Attaches Hammer.js tap event handler. ```javascript function attachHammerTap(element, handler) { const hammer = new Hammer(element); hammer.on('tap', handler); } ``` ### initHammer() Initializes Hammer.js for all interactive elements. ```javascript function initHammer() { attachHammerTap(dropZone, () => fileInput.click()); attachHammerTap(eggContainer, () => { const isOpen = eggContainer.classList.contains('open'); if (!isOpen) { const randomIndex = Math.floor(Math.random() * creaturePaths.length); eggCreature.src = creaturePaths[randomIndex]; } eggContainer.classList.toggle('open'); }); attachHammerTap(settingsToggle, (e) => { settingsToggle.classList.add('pressed'); setTimeout(() => { settingsToggle.classList.remove('pressed'); }, 100); toggleSettings(!settingsMenu.classList.contains('show')); }); attachHammerTap(closeSettings, () => toggleSettings(false)); attachHammerTap(applyCustom, () => { const all = parseFloat(customAllInput.value); const conf = parseFloat(customConfidentInput.value); if (isNaN(all) || isNaN(conf) || all < 0 || all > 1 || conf < 0 || conf > 1) { showNotification('Please enter valid numbers between 0 and 1.', 'error'); return; } allThreshold = all; confidentThreshold = conf; activePreset = 'custom'; applyThresholds(); }); attachHammerTap(resetBtn, () => { allThreshold = 0.60; confidentThreshold = 0.70; savedFormat = 'e621'; currentFormat = savedFormat; currentTheme = 'system'; activePreset = 'standard'; maxTags = 200; alwaysHiddenCategories.clear(); hiddenCategories.clear(); document.querySelectorAll('#themeToggle .theme-option').forEach(btn => { btn.classList.toggle('active', btn.dataset.value === 'system'); }); document.querySelectorAll('#maxTagsToggle .max-tag-option').forEach(btn => { btn.classList.toggle('active', btn.dataset.value === '200'); }); updateTheme('system'); applyThresholds(); saveSettings(); if (allTags.length) displayTags(allTags); }); presetBtns.forEach(btn => { attachHammerTap(btn, () => { const preset = btn.dataset.preset; if (preset === 'custom') { activePreset = 'custom'; updateThresholdUI(); saveSettings(); return; } activePreset = preset; switch (preset) { case 'conservative': allThreshold = 0.70; confidentThreshold = 0.80; break; case 'standard': allThreshold = 0.60; confidentThreshold = 0.70; break; case 'liberal': allThreshold = 0.50; confidentThreshold = 0.60; break; } customAllInput.value = allThreshold.toFixed(2); customConfidentInput.value = confidentThreshold.toFixed(2); applyThresholds(); }); }); document.querySelectorAll('#themeToggle .theme-option').forEach(btn => { attachHammerTap(btn, () => { document.querySelectorAll('#themeToggle .theme-option').forEach(b => b.classList.remove('active')); btn.classList.add('active'); currentTheme = btn.dataset.value; updateTheme(currentTheme); saveSettings(); }); }); document.querySelectorAll('#defaultFormatToggle .format-option').forEach(btn => { attachHammerTap(btn, () => { document.querySelectorAll('#defaultFormatToggle .format-option').forEach(b => b.classList.remove('active')); btn.classList.add('active'); savedFormat = btn.dataset.value; currentFormat = savedFormat; saveSettings(); }); }); document.querySelectorAll('#resultsFormatToggle .format-option').forEach(btn => { attachHammerTap(btn, () => { document.querySelectorAll('#resultsFormatToggle .format-option').forEach(b => b.classList.remove('active')); btn.classList.add('active'); currentFormat = btn.dataset.value; }); }); document.querySelectorAll('#maxTagsToggle .max-tag-option').forEach(btn => { attachHammerTap(btn, () => { document.querySelectorAll('#maxTagsToggle .max-tag-option').forEach(b => b.classList.remove('active')); btn.classList.add('active'); maxTags = parseInt(btn.dataset.value); saveSettings(); }); }); const yearTagToggle = document.getElementById('yearTagToggle'); if (yearTagToggle) { yearTagToggle.addEventListener('change', () => { addCurrentYearTag = yearTagToggle.checked; const currentYearTag = String(new Date().getFullYear()); if (addCurrentYearTag) { perTagAutoDisable.delete(currentYearTag); } else { perTagAutoDisable.add(currentYearTag); } saveSettings(); }); } } ``` --- ## 15. Results Display Functions ### hideResults() Hides results container with animation. ```javascript async function hideResults() { if (!results.classList.contains('visible')) return Promise.resolve(); results.classList.remove('visible'); return new Promise(resolve => { const onTransitionEnd = () => { results.style.display = 'none'; results.removeEventListener('transitionend', onTransitionEnd); resolve(); }; results.addEventListener('transitionend', onTransitionEnd, { once: true }); }); } ``` ### showResults() Shows results container. ```javascript async function showResults() { if (results.classList.contains('visible')) return Promise.resolve(); results.style.display = 'block'; results.offsetHeight; results.classList.add('visible'); return Promise.resolve(); } ``` ### applyThresholds() Applies threshold settings and re-renders. ```javascript function applyThresholds() { if (allTags.length) { refreshTagClasses(); } updateThresholdUI(); saveSettings(); } ``` --- ## 16. Event Listeners ### File Input Events ```javascript // Prevent defaults ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => dropZone.addEventListener(eventName, preventDefaults, false)); ['dragenter', 'dragover'].forEach(eventName => dropZone.addEventListener(eventName, () => dropZone.classList.add('dragover'), false)); ['dragleave', 'drop'].forEach(eventName => dropZone.addEventListener(eventName, () => dropZone.classList.remove('dragover'), false)); dropZone.addEventListener('drop', (e) => { const dt = e.dataTransfer; const files = dt.files; if (files.length) handleFiles(files); }); fileInput.addEventListener('change', () => handleFiles(fileInput.files)); document.addEventListener('paste', (e) => { const items = e.clipboardData?.items; if (!items) return; for (let i = 0; i < items.length; i++) { const item = items[i]; if (item.type.startsWith('image/')) { const file = item.getAsFile(); if (file) { handleFiles([file]); e.preventDefault(); break; } } } }); document.addEventListener('click', (e) => { if (currentPopup && !currentPopup.contains(e.target) && (!activePopupTagElement || !activePopupTagElement.contains(e.target))) closePopup(); if (!settingsMenu.contains(e.target) && !settingsToggle.contains(e.target)) toggleSettings(false); if (helpModal && helpModal.style.display === 'flex') { const modalContent = helpModal.querySelector('.help-modal-content'); if (e.target === helpModal || (helpModal.contains(e.target) && modalContent && !modalContent.contains(e.target))) closeHelpModal(); } }); window.addEventListener('resize', () => { if (settingsMenu.classList.contains('show')) positionSettingsMenu(); }); document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { if (helpModal && helpModal.style.display === 'flex') closeHelpModal(); if (settingsMenu.classList.contains('show')) toggleSettings(false); if (isFullscreenActive) hideFullscreenImage(); } if (e.code === 'KeyF' && !e.ctrlKey && !e.metaKey) { if (isFullscreenActive) { hideFullscreenImage(); } else { const currentImg = dropZone.querySelector('img'); if (currentImg && currentImg.src) { showFullscreenImage(currentImg.src); } } } }); if (helpBtn && helpModal) { helpBtn.addEventListener('click', (e) => { e.stopPropagation(); openHelpModal(); }); if (closeHelpModalBtn) closeHelpModalBtn.addEventListener('click', closeHelpModal); } if ('serviceWorker' in navigator) { navigator.serviceWorker.addEventListener('message', event => { if (event.data && event.data.action === 'offline') { showNotification('You are offline. Check your network connection.', 'info', 5000); } }); } ``` --- ## 17. Final Initialization ```javascript results.style.display = 'none'; loadSettings(); initHammer(); setupGlobalCopyButton(copyGlobalConfident, () => confidentThreshold); setupGlobalCopyButton(copyGlobalAll, () => allThreshold); ``` --- ## 18. API Reference ### /predict Endpoint | Method | Path | Purpose | |--------|------|---------| | POST | /predict | Tag image | ### Request Format ``` POST /predict Content-Type: multipart/form-data image: top_k: (optional, default 200) ``` ### Response Format ```json { "success": true, "tags": [ { "tag": "string", "prob": 0.0-1.0, "category": "string" } ], "auto_meta": ["string"] } ``` ### API Response Structure | Field | Type | Description | |-------|------|-------------| | success | boolean | Success status | | tags | array | Tag predictions | | tags[].tag | string | Tag name | | tags[].prob | float | Probability (0-1) | | tags[].category | string | e621 category | | auto_meta | array | Auto-detected tags | --- ## 19. Quick Reference for Agents ### LocalStorage | Key | Type | Description | |-----|------|-------------| | e621tagger-settings | JSON | All persisted settings | **IMPORTANT:** The key is `e621tagger-settings` (single JSON key), NOT individual keys. ### Error Handling | Error | Message | |-------|----------| | Not an image | "Please select an image file." | | File too large | "File too large. Maximum size is 20MB." | | API error | Shows result.error | ### Tag States | data-level | CSS Variable | Color | |-----------|-----------|-------| | confident | --confident-bg | Purple | | all | --all-bg | Blue | | added | --added-bg | Green | | removed | --removed-bg | Red | | (none) | --low-bg | Gray | ### HTML Element IDs | ID | Element | |----|---------| | dropZone | File drop area | | fileInput | Hidden file input | | results | Results container | | categoriesContainer | Category tags | | ratingDisplay | Rating badges | | settingsMenu | Settings panel | | helpModal | Help overlay | | notification-container | Toast container |