| <!DOCTYPE html>
|
| <html lang="en" class="dark">
|
| <head>
|
| <meta charset="UTF-8">
|
| <meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| <title>Dataset Caption Tag Manager</title>
|
| <script src="https://cdn.tailwindcss.com"></script>
|
|
|
| <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
|
| <script>
|
| tailwind.config = {
|
| darkMode: 'class',
|
| theme: {
|
| extend: {
|
| colors: {
|
| dark: { 900: '#11111b', 800: '#1e1e2e', 700: '#313244', 600: '#45475a', 500: '#585b70' },
|
| accent: { primary: '#89b4fa', secondary: '#cba6f7', danger: '#f38ba8', success: '#a6e3a1' }
|
| }
|
| }
|
| }
|
| }
|
| </script>
|
| <style>
|
|
|
| ::-webkit-scrollbar { width: 8px; height: 8px; }
|
| ::-webkit-scrollbar-track { background: #1e1e2e; }
|
| ::-webkit-scrollbar-thumb { background: #45475a; border-radius: 4px; }
|
| ::-webkit-scrollbar-thumb:hover { background: #585b70; }
|
|
|
| body { font-family: system-ui, -apple-system, sans-serif; background-color: #11111b; color: #cdd6f4; overflow: hidden; }
|
|
|
| .img-card { transition: transform 0.1s, box-shadow 0.1s; }
|
| .img-card.selected { box-shadow: 0 0 0 4px #89b4fa; transform: scale(0.98); }
|
|
|
| .tag-pill { display: inline-flex; align-items: center; background: #313244; padding: 2px 8px; border-radius: 12px; font-size: 0.85rem; margin: 2px; border: 1px solid #cba6f7; cursor: pointer; transition: background 0.2s;}
|
| .tag-pill:hover { background: #45475a; }
|
|
|
| #lightbox { display: none; background: rgba(0,0,0,0.85); backdrop-filter: blur(4px); z-index: 50; }
|
| #lightbox.active { display: flex; }
|
| #lightbox img { max-height: 90vh; max-width: 90vw; object-fit: contain; }
|
|
|
| #custom-modal { display: none; background: rgba(0,0,0,0.6); backdrop-filter: blur(2px); z-index: 60; }
|
| #custom-modal.active { display: flex; }
|
|
|
| .drop-zone-overlay { display: none; background: rgba(137, 180, 250, 0.2); border: 4px dashed #89b4fa; z-index: 40;}
|
| body.dragover .drop-zone-overlay { display: flex; }
|
| </style>
|
| </head>
|
| <body class="h-screen flex flex-col">
|
|
|
|
|
| <header class="bg-dark-800 border-b border-dark-700 p-3 flex flex-wrap items-center justify-between gap-4 shrink-0">
|
| <div class="flex items-center gap-2">
|
| <h1 class="text-xl font-bold text-accent-primary mr-4">TagManager</h1>
|
|
|
| <button id="btn-load-folder" class="bg-dark-700 hover:bg-dark-600 text-white px-3 py-1.5 rounded text-sm flex items-center gap-2 transition" title="Requires Chromium">
|
| <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"></path></svg>
|
| Load Folder
|
| </button>
|
| <span class="text-dark-500 text-xs">-or-</span>
|
| <input type="file" id="btn-load-files" multiple accept="image/*,.txt" class="text-sm text-gray-400 file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-sm file:bg-dark-700 file:text-white hover:file:bg-dark-600 cursor-pointer" title="Fallback for Firefox or specific files">
|
|
|
| <div class="w-px h-6 bg-dark-600 mx-2"></div>
|
|
|
| <button id="btn-undo" class="bg-dark-700 hover:bg-dark-600 text-white px-3 py-1.5 rounded text-sm flex items-center gap-2 transition disabled:opacity-50 disabled:cursor-not-allowed">
|
| <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"></path></svg>
|
| Undo (<span id="undo-count">0</span>)
|
| </button>
|
|
|
|
|
| <button id="btn-sort-lines" class="bg-dark-700 hover:bg-dark-600 text-white border border-transparent px-3 py-1.5 rounded text-sm flex items-center gap-2 transition" title="Toggle sorting order of the master list">
|
| <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"></path></svg>
|
| <span id="sort-label">Sort: Time</span>
|
| </button>
|
| </div>
|
|
|
| <div class="flex items-center gap-3">
|
| <div class="flex items-center gap-1">
|
| <label class="text-xs text-dark-400">Prefix:</label>
|
| <input type="text" id="global-prefix" class="bg-dark-900 border border-dark-600 rounded px-2 py-1 text-sm w-32 focus:border-accent-primary outline-none" placeholder="e.g. triggerword,">
|
| </div>
|
| <div class="flex items-center gap-1">
|
| <label class="text-xs text-dark-400">Suffix:</label>
|
| <input type="text" id="global-suffix" class="bg-dark-900 border border-dark-600 rounded px-2 py-1 text-sm w-32 focus:border-accent-primary outline-none" placeholder="e.g. masterpiece">
|
| </div>
|
|
|
| <label class="flex items-center gap-2 text-sm cursor-pointer ml-2">
|
| <input type="checkbox" id="toggle-uncaptioned" class="rounded bg-dark-900 border-dark-600 text-accent-primary focus:ring-accent-primary">
|
| Uncaptioned Only
|
| </label>
|
|
|
|
|
| <div class="flex items-center gap-1 ml-1">
|
| <button id="btn-select-all" class="text-xs bg-dark-700 hover:bg-dark-600 px-2 py-1.5 rounded text-dark-300 hover:text-white transition" title="Select all currently visible images">Select All</button>
|
| <button id="btn-deselect-all" class="text-xs bg-dark-700 hover:bg-dark-600 px-2 py-1.5 rounded text-dark-300 hover:text-white transition" title="Deselect all images">Deselect</button>
|
| </div>
|
|
|
| <div class="w-px h-6 bg-dark-600 mx-2"></div>
|
|
|
| <button id="btn-export-folder" class="bg-accent-primary hover:bg-blue-400 text-dark-900 font-medium px-3 py-1.5 rounded text-sm flex items-center gap-2 transition" title="Overwrites/Saves .txt directly (Chromium Only)">
|
| <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path></svg>
|
| Save to Folder
|
| </button>
|
| <button id="btn-export-zip" class="bg-dark-700 hover:bg-dark-600 text-white border border-dark-500 px-3 py-1.5 rounded text-sm flex items-center gap-2 transition" title="Downloads a .zip of all .txt files (All Browsers)">
|
| <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path></svg>
|
| Export ZIP
|
| </button>
|
| </div>
|
| </header>
|
|
|
|
|
| <main class="flex-1 flex overflow-hidden">
|
|
|
| <div id="grid-container" class="flex-1 overflow-y-auto p-4 relative">
|
| <div class="flex justify-between items-center mb-4 text-sm text-dark-400">
|
| <span id="status-text">0 Images Loaded</span>
|
| <span class="italic text-xs">Shift+Click to multi-select. Ctrl+Click to toggle.</span>
|
| </div>
|
| <div id="image-grid" class="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-4">
|
|
|
| </div>
|
| </div>
|
|
|
|
|
| <div class="w-80 bg-dark-800 border-l border-dark-700 flex flex-col shrink-0">
|
|
|
| <div class="flex-1 flex flex-col min-h-0">
|
| <div class="p-3 bg-dark-700 font-semibold text-sm flex justify-between items-center">
|
| <span>Sentences / Lines</span>
|
| <span class="text-xs text-dark-400 font-normal">Click to apply selected</span>
|
| </div>
|
| <div class="p-2 border-b border-dark-600 flex gap-2">
|
| <input type="text" id="input-new-line" class="flex-1 bg-dark-900 border border-dark-600 rounded px-2 py-1 text-sm focus:border-accent-secondary outline-none" placeholder="New line (Enter)">
|
| <button id="btn-add-line" class="bg-dark-600 hover:bg-dark-500 px-2 rounded">+</button>
|
| </div>
|
| <div id="list-lines" class="flex-1 overflow-y-auto p-2 flex flex-col gap-1">
|
|
|
| </div>
|
| </div>
|
| </div>
|
| </main>
|
|
|
|
|
| <div class="drop-zone-overlay absolute inset-0 items-center justify-center pointer-events-none">
|
| <div class="bg-dark-800 p-8 rounded-xl border border-accent-primary shadow-2xl flex flex-col items-center">
|
| <svg class="w-16 h-16 text-accent-primary mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path></svg>
|
| <h2 class="text-2xl font-bold">Drop Images/Folders Here</h2>
|
| </div>
|
| </div>
|
|
|
| <div id="lightbox" class="fixed inset-0 items-center justify-center">
|
| <img id="lightbox-img" src="" alt="High-res preview">
|
| </div>
|
|
|
|
|
| <div id="custom-modal" class="fixed inset-0 items-center justify-center">
|
| <div class="bg-dark-800 border border-dark-600 rounded-lg shadow-xl w-96 p-5 flex flex-col gap-4">
|
| <h3 id="modal-title" class="text-lg font-bold">Title</h3>
|
| <p id="modal-desc" class="text-sm text-dark-400">Description</p>
|
| <input type="text" id="modal-input" class="bg-dark-900 border border-dark-600 rounded px-3 py-2 text-sm focus:border-accent-primary outline-none">
|
| <div class="flex justify-end gap-2 mt-2">
|
| <button id="modal-cancel" class="px-4 py-2 rounded text-sm bg-dark-700 hover:bg-dark-600 transition">Cancel</button>
|
| <button id="modal-confirm" class="px-4 py-2 rounded text-sm bg-accent-primary text-dark-900 font-bold hover:bg-blue-400 transition">Confirm</button>
|
| </div>
|
| </div>
|
| </div>
|
|
|
| <script>
|
|
|
| const imageStore = {};
|
| let directoryHandle = null;
|
|
|
| let state = {
|
| imageOrder: [],
|
| imageTags: {},
|
| tags: {},
|
| selected: [],
|
| globalPrefix: "",
|
| globalSuffix: "",
|
| showUncaptioned: false
|
| };
|
|
|
| const history = [];
|
| let lastSelectedIdx = -1;
|
|
|
| let isSortedAlphabetically = false;
|
|
|
|
|
| const generateId = () => Math.random().toString(36).substr(2, 9);
|
|
|
| const pushState = () => {
|
| history.push(JSON.parse(JSON.stringify(state)));
|
| if (history.length > 3) history.shift();
|
| updateUndoUI();
|
| };
|
|
|
| const popState = () => {
|
| if (history.length === 0) return;
|
| state = history.pop();
|
| lastSelectedIdx = -1;
|
| updateUndoUI();
|
| renderAll();
|
| };
|
|
|
| const updateUndoUI = () => {
|
| const btn = document.getElementById('btn-undo');
|
| const count = document.getElementById('undo-count');
|
| count.textContent = history.length;
|
| btn.disabled = history.length === 0;
|
| };
|
|
|
| const createTag = (text) => {
|
| text = text.trim();
|
| if (!text) return null;
|
|
|
| for (const [id, tag] of Object.entries(state.tags)) {
|
| if (tag.text.toLowerCase() === text.toLowerCase()) return id;
|
| }
|
| const id = generateId();
|
| state.tags[id] = { text };
|
| return id;
|
| };
|
|
|
|
|
| const renderAll = () => {
|
| renderGrid();
|
| renderSidebar();
|
| updateStatus();
|
| document.getElementById('global-prefix').value = state.globalPrefix;
|
| document.getElementById('global-suffix').value = state.globalSuffix;
|
| document.getElementById('toggle-uncaptioned').checked = state.showUncaptioned;
|
| };
|
|
|
| const updateStatus = () => {
|
| document.getElementById('status-text').textContent =
|
| `${state.imageOrder.length} Images Loaded | ${state.selected.length} Selected`;
|
| };
|
|
|
| const renderSidebar = () => {
|
| const listLines = document.getElementById('list-lines');
|
| listLines.innerHTML = '';
|
|
|
| const lines = [];
|
| for (const [id, tag] of Object.entries(state.tags)) {
|
| lines.push({id, ...tag});
|
| }
|
|
|
|
|
| if (isSortedAlphabetically) {
|
| lines.sort((a, b) => a.text.localeCompare(b.text));
|
| }
|
|
|
| lines.forEach(l => {
|
| const el = document.createElement('div');
|
| el.className = 'bg-dark-900 border border-dark-600 rounded p-2 text-sm text-dark-300 hover:border-accent-secondary cursor-pointer group relative flex items-center min-h-[40px]';
|
| el.innerHTML = `
|
| <p class="pr-12 break-words whitespace-normal">${l.text}</p>
|
| <div class="absolute right-2 top-1/2 -translate-y-1/2 hidden group-hover:flex gap-2">
|
| <button class="hover:text-accent-primary" onclick="editTag(event, '${l.id}')"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg></button>
|
| <button class="text-accent-danger hover:text-red-400" onclick="deleteMasterTag(event, '${l.id}')"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg></button>
|
| </div>
|
| `;
|
| el.onclick = () => applyTagToSelected(l.id);
|
| listLines.appendChild(el);
|
| });
|
| };
|
|
|
| const renderGrid = () => {
|
| const grid = document.getElementById('image-grid');
|
| grid.innerHTML = '';
|
|
|
| let visibleOrder = state.imageOrder;
|
| if (state.showUncaptioned) {
|
| visibleOrder = visibleOrder.filter(id => state.imageTags[id].length === 0);
|
| }
|
|
|
| visibleOrder.forEach((id, displayIdx) => {
|
| const imgData = imageStore[id];
|
| const isSelected = state.selected.includes(id);
|
| const tagIds = state.imageTags[id];
|
|
|
| const card = document.createElement('div');
|
| card.className = `img-card bg-dark-800 rounded-lg overflow-hidden border border-dark-700 flex flex-col ${isSelected ? 'selected' : ''}`;
|
| card.dataset.id = id;
|
| card.dataset.idx = state.imageOrder.indexOf(id);
|
|
|
|
|
| const imgWrap = document.createElement('div');
|
| imgWrap.className = 'relative h-48 w-full cursor-pointer bg-dark-900 group';
|
| imgWrap.innerHTML = `
|
| <img src="${imgData.url}" loading="lazy" class="w-full h-full object-contain">
|
| <div class="absolute inset-0 bg-black/50 hidden group-hover:flex items-center justify-center pointer-events-none">
|
| <span class="text-white text-xs bg-dark-900/80 px-2 py-1 rounded border border-dark-600">Select</span>
|
| </div>
|
| <button class="absolute top-2 right-2 bg-dark-900/80 p-1 rounded hidden group-hover:block hover:bg-accent-primary text-white hover:text-dark-900 transition z-10" onclick="openLightbox(event, '${imgData.url}')" title="Zoom">
|
| <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"></path></svg>
|
| </button>
|
| <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2 text-xs truncate pointer-events-none">${imgData.name}</div>
|
| `;
|
| imgWrap.onclick = (e) => handleImageSelect(e, id, state.imageOrder.indexOf(id));
|
|
|
|
|
| const tagsWrap = document.createElement('div');
|
| tagsWrap.className = 'p-2 flex-1 flex flex-col gap-2 min-h-[80px] bg-dark-800';
|
|
|
| const pillsContainer = document.createElement('div');
|
| pillsContainer.className = 'flex flex-wrap gap-1 flex-1 content-start';
|
|
|
| tagIds.forEach(tagId => {
|
| const tagDef = state.tags[tagId];
|
| if (!tagDef) return;
|
| const pill = document.createElement('span');
|
| pill.className = `tag-pill group flex items-start text-left`;
|
|
|
| const textDisplay = `<span class="break-words whitespace-normal leading-tight py-0.5">${tagDef.text}</span>`;
|
|
|
| pill.innerHTML = `${textDisplay} <button class="ml-1 text-dark-400 group-hover:text-accent-danger flex-shrink-0" onclick="removeTagFromImage(event, '${id}', '${tagId}')">×</button>`;
|
| pillsContainer.appendChild(pill);
|
| });
|
|
|
|
|
| const inputWrap = document.createElement('div');
|
| inputWrap.innerHTML = `<input type="text" class="w-full bg-dark-900 border border-dark-600 rounded px-2 py-1 text-xs outline-none focus:border-accent-primary" placeholder="Add sentence/line to this image (Enter)" onkeydown="handleImageInputKey(event, '${id}')">`;
|
|
|
| tagsWrap.appendChild(pillsContainer);
|
| tagsWrap.appendChild(inputWrap);
|
|
|
| card.appendChild(imgWrap);
|
| card.appendChild(tagsWrap);
|
| grid.appendChild(card);
|
| });
|
| };
|
|
|
|
|
| const handleImageSelect = (e, id, idx) => {
|
| pushState();
|
| if (e.shiftKey && lastSelectedIdx !== -1) {
|
|
|
| const start = Math.min(lastSelectedIdx, idx);
|
| const end = Math.max(lastSelectedIdx, idx);
|
| for (let i = start; i <= end; i++) {
|
| const currId = state.imageOrder[i];
|
| if (!state.selected.includes(currId)) state.selected.push(currId);
|
| }
|
| } else if (e.ctrlKey || e.metaKey) {
|
|
|
| const sIdx = state.selected.indexOf(id);
|
| if (sIdx > -1) state.selected.splice(sIdx, 1);
|
| else state.selected.push(id);
|
| lastSelectedIdx = idx;
|
| } else {
|
|
|
| if (state.selected.length === 1 && state.selected[0] === id) {
|
| state.selected = [];
|
| lastSelectedIdx = -1;
|
| } else {
|
| state.selected = [id];
|
| lastSelectedIdx = idx;
|
| }
|
| }
|
| renderGridClasses();
|
| updateStatus();
|
| };
|
|
|
| const renderGridClasses = () => {
|
| document.querySelectorAll('.img-card').forEach(card => {
|
| if (state.selected.includes(card.dataset.id)) card.classList.add('selected');
|
| else card.classList.remove('selected');
|
| });
|
| }
|
|
|
| const applyTagToSelected = (tagId) => {
|
| if (state.selected.length === 0) {
|
| showModal("Info", "Select one or more images first to apply this line.", null, false);
|
| return;
|
| }
|
| pushState();
|
| let applied = 0;
|
| state.selected.forEach(imgId => {
|
| if (!state.imageTags[imgId].includes(tagId)) {
|
| state.imageTags[imgId].push(tagId);
|
| applied++;
|
| }
|
| });
|
| if (applied > 0) renderGrid();
|
| };
|
|
|
| const removeTagFromImage = (e, imgId, tagId) => {
|
| e.stopPropagation();
|
| pushState();
|
| state.imageTags[imgId] = state.imageTags[imgId].filter(t => t !== tagId);
|
| renderGrid();
|
| };
|
|
|
| const handleImageInputKey = (e, imgId) => {
|
| if (e.key === 'Enter' && e.target.value.trim()) {
|
| pushState();
|
| const text = e.target.value.trim();
|
| const tagId = createTag(text);
|
| if (!state.imageTags[imgId].includes(tagId)) {
|
| state.imageTags[imgId].push(tagId);
|
| }
|
| e.target.value = '';
|
| renderAll();
|
| }
|
| };
|
|
|
| const deleteMasterTag = (e, tagId) => {
|
| e.stopPropagation();
|
| pushState();
|
|
|
| delete state.tags[tagId];
|
|
|
| for (const imgId of state.imageOrder) {
|
| state.imageTags[imgId] = state.imageTags[imgId].filter(t => t !== tagId);
|
| }
|
| renderAll();
|
| };
|
|
|
| const editTag = (e, tagId) => {
|
| e.stopPropagation();
|
| const tag = state.tags[tagId];
|
| showModal("Edit Line", "Modify the text. Changes will reflect on all linked images.", (newVal) => {
|
| if (newVal) {
|
| pushState();
|
| state.tags[tagId].text = newVal;
|
| renderAll();
|
| }
|
| }, true, tag.text);
|
| };
|
|
|
|
|
| const processFiles = async (filesArray) => {
|
| const images = [];
|
| const texts = {};
|
|
|
| for (const file of filesArray) {
|
| if (!file || !file.name) continue;
|
| const name = file.name;
|
| const ext = name.slice((name.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
|
| if (['jpg', 'jpeg', 'png', 'webp'].includes(ext)) {
|
| images.push(file);
|
| } else if (ext === 'txt') {
|
| const baseName = name.replace(/\.[^/.]+$/, "").toLowerCase();
|
| const text = await file.text();
|
| texts[baseName] = text;
|
| }
|
| }
|
|
|
| if (images.length === 0) return;
|
| pushState();
|
|
|
| images.forEach(imgFile => {
|
| const baseName = imgFile.name.replace(/\.[^/.]+$/, "");
|
| const hash = imgFile.name + imgFile.size;
|
|
|
|
|
| let isDup = false;
|
| for (const existingId of state.imageOrder) {
|
| if (imageStore[existingId].hash === hash) { isDup = true; break; }
|
| }
|
| if (isDup) return;
|
|
|
| const id = generateId();
|
| imageStore[id] = {
|
| file: imgFile,
|
| url: URL.createObjectURL(imgFile),
|
| name: imgFile.name,
|
| hash: hash,
|
| baseName: baseName
|
| };
|
| state.imageOrder.push(id);
|
| state.imageTags[id] = [];
|
|
|
|
|
| if (texts[baseName.toLowerCase()]) {
|
| const content = texts[baseName.toLowerCase()];
|
|
|
| const parts = content.split(',').map(s => s.trim()).filter(s => s);
|
| parts.forEach(part => {
|
| const tagId = createTag(part);
|
| if (!state.imageTags[id].includes(tagId)) {
|
| state.imageTags[id].push(tagId);
|
| }
|
| });
|
| }
|
| });
|
|
|
| renderAll();
|
| };
|
|
|
|
|
|
|
|
|
| document.getElementById('input-new-line').addEventListener('keydown', (e) => {
|
| if (e.key === 'Enter') document.getElementById('btn-add-line').click();
|
| });
|
| document.getElementById('btn-add-line').addEventListener('click', () => {
|
| const inp = document.getElementById('input-new-line');
|
| if(inp.value.trim()) { pushState(); createTag(inp.value); inp.value = ''; renderSidebar(); }
|
| });
|
|
|
|
|
| document.getElementById('btn-sort-lines').addEventListener('click', (e) => {
|
| isSortedAlphabetically = !isSortedAlphabetically;
|
| const btn = e.currentTarget;
|
| const label = document.getElementById('sort-label');
|
|
|
| if (isSortedAlphabetically) {
|
| label.textContent = 'Sort: A-Z';
|
| btn.classList.replace('text-white', 'text-accent-primary');
|
| btn.classList.replace('border-transparent', 'border-accent-primary');
|
| } else {
|
| label.textContent = 'Sort: Time';
|
| btn.classList.replace('text-accent-primary', 'text-white');
|
| btn.classList.replace('border-accent-primary', 'border-transparent');
|
| }
|
| renderSidebar();
|
| });
|
|
|
|
|
| document.getElementById('global-prefix').addEventListener('input', e => state.globalPrefix = e.target.value);
|
| document.getElementById('global-suffix').addEventListener('input', e => state.globalSuffix = e.target.value);
|
|
|
| document.getElementById('toggle-uncaptioned').addEventListener('change', e => {
|
| state.showUncaptioned = e.target.checked;
|
| renderGrid();
|
| });
|
|
|
| document.getElementById('btn-select-all').addEventListener('click', () => {
|
| if (state.imageOrder.length === 0) return;
|
| pushState();
|
| let visibleOrder = state.imageOrder;
|
| if (state.showUncaptioned) {
|
| visibleOrder = visibleOrder.filter(id => state.imageTags[id].length === 0);
|
| }
|
| state.selected = [...visibleOrder];
|
| renderGridClasses();
|
| updateStatus();
|
| });
|
|
|
| document.getElementById('btn-deselect-all').addEventListener('click', () => {
|
| if (state.selected.length === 0) return;
|
| pushState();
|
| state.selected = [];
|
| lastSelectedIdx = -1;
|
| renderGridClasses();
|
| updateStatus();
|
| });
|
|
|
| document.getElementById('btn-undo').addEventListener('click', popState);
|
|
|
|
|
| const lightbox = document.getElementById('lightbox');
|
| const openLightbox = (e, url) => {
|
| e.stopPropagation();
|
| document.getElementById('lightbox-img').src = url;
|
| lightbox.classList.add('active');
|
| };
|
| lightbox.addEventListener('click', () => lightbox.classList.remove('active'));
|
|
|
|
|
| document.getElementById('btn-load-files').addEventListener('change', (e) => {
|
| processFiles(Array.from(e.target.files));
|
| e.target.value = '';
|
| });
|
|
|
|
|
| document.getElementById('btn-load-folder').addEventListener('click', async () => {
|
| if (!window.showDirectoryPicker) {
|
| showModal("Browser Unsupported", "Direct folder access is only available in Chromium browsers (Chrome, Edge, Brave). Please use the 'Load Files' fallback button next to it.", null, false);
|
| return;
|
| }
|
| try {
|
| directoryHandle = await window.showDirectoryPicker({ mode: 'readwrite' });
|
| const files = [];
|
| for await (const entry of directoryHandle.values()) {
|
| if (entry.kind === 'file') {
|
| files.push(await entry.getFile());
|
| }
|
| }
|
| processFiles(files);
|
| } catch (err) {
|
| console.warn(err);
|
| }
|
| });
|
|
|
|
|
| document.body.addEventListener('dragover', e => { e.preventDefault(); document.body.classList.add('dragover'); });
|
| document.body.addEventListener('dragleave', e => { if (e.target === document.body || e.relatedTarget === null) document.body.classList.remove('dragover'); });
|
| document.body.addEventListener('drop', e => {
|
| e.preventDefault();
|
| document.body.classList.remove('dragover');
|
|
|
| const files = [];
|
| const dirEntries = [];
|
|
|
| if (e.dataTransfer.items) {
|
|
|
| for (let i = 0; i < e.dataTransfer.items.length; i++) {
|
| const item = e.dataTransfer.items[i];
|
| if (item.kind === 'file') {
|
| const entry = item.webkitGetAsEntry ? item.webkitGetAsEntry() : null;
|
| if (entry && entry.isDirectory) {
|
| dirEntries.push(entry);
|
| } else {
|
| const file = item.getAsFile();
|
| if (file) files.push(file);
|
| }
|
| }
|
| }
|
| } else if (e.dataTransfer.files) {
|
| for (let i = 0; i < e.dataTransfer.files.length; i++) {
|
| files.push(e.dataTransfer.files[i]);
|
| }
|
| }
|
|
|
|
|
| if (dirEntries.length === 0) {
|
| if (files.length > 0) processFiles(files);
|
| return;
|
| }
|
|
|
|
|
| const readDir = (dirEntry) => {
|
| return new Promise(resolve => {
|
| const dirReader = dirEntry.createReader();
|
| const allEntries = [];
|
|
|
| const readBatch = () => {
|
| dirReader.readEntries(async (entries) => {
|
| if (entries.length === 0) {
|
|
|
| const filePromises = allEntries.map(ent => {
|
| return new Promise(res => {
|
| if (ent.isFile) {
|
| ent.file(f => res(f), () => res(null));
|
| } else if (ent.isDirectory) {
|
| readDir(ent).then(res);
|
| } else {
|
| res(null);
|
| }
|
| });
|
| });
|
| const nestedFiles = await Promise.all(filePromises);
|
| resolve(nestedFiles.flat().filter(f => f !== null));
|
| } else {
|
| allEntries.push(...entries);
|
| readBatch();
|
| }
|
| }, () => resolve([]));
|
| };
|
| readBatch();
|
| });
|
| };
|
|
|
|
|
| Promise.all(dirEntries.map(readDir)).then(results => {
|
| files.push(...results.flat());
|
| if (files.length > 0) processFiles(files);
|
| });
|
| });
|
|
|
|
|
| const getCaptionString = (id) => {
|
| const tagIds = state.imageTags[id];
|
| let elements = [];
|
| if (state.globalPrefix) elements.push(state.globalPrefix.trim());
|
|
|
| tagIds.forEach(tid => {
|
| if(state.tags[tid]) elements.push(state.tags[tid].text);
|
| });
|
|
|
| if (state.globalSuffix) elements.push(state.globalSuffix.trim());
|
|
|
|
|
| return elements.join(', ').replace(/,\s*,/g, ',').trim();
|
| };
|
|
|
|
|
| document.getElementById('btn-export-zip').addEventListener('click', async () => {
|
| if (state.imageOrder.length === 0) return showModal("Info", "No images loaded.", null, false);
|
|
|
| const zip = new JSZip();
|
| let count = 0;
|
| state.imageOrder.forEach(id => {
|
| const text = getCaptionString(id);
|
| if (text) {
|
| const baseName = imageStore[id].baseName;
|
| zip.file(`${baseName}.txt`, text);
|
| count++;
|
| }
|
| });
|
|
|
| if (count === 0) return showModal("Info", "No captions to export.", null, false);
|
|
|
| const btn = document.getElementById('btn-export-zip');
|
| const originalText = btn.innerHTML;
|
| btn.innerHTML = 'Generating...';
|
|
|
| zip.generateAsync({type:"blob"}).then(function(content) {
|
| const a = document.createElement("a");
|
| a.href = URL.createObjectURL(content);
|
| a.download = "captions_export.zip";
|
| a.click();
|
| btn.innerHTML = originalText;
|
| });
|
| });
|
|
|
|
|
| document.getElementById('btn-export-folder').addEventListener('click', async () => {
|
| if (!window.showDirectoryPicker) {
|
| showModal("Browser Unsupported", "Saving directly to a folder requires a Chromium browser. Please use 'Export ZIP' instead.", null, false);
|
| return;
|
| }
|
| if (state.imageOrder.length === 0) return showModal("Info", "No images loaded.", null, false);
|
|
|
| let handleToUse = directoryHandle;
|
| if (!handleToUse) {
|
| try {
|
| handleToUse = await window.showDirectoryPicker({ mode: 'readwrite' });
|
| } catch(e) { return; }
|
| }
|
|
|
| const btn = document.getElementById('btn-export-folder');
|
| const originalText = btn.innerHTML;
|
| btn.innerHTML = 'Saving...';
|
|
|
| let count = 0;
|
| try {
|
| for (const id of state.imageOrder) {
|
| const text = getCaptionString(id);
|
| if (text) {
|
| const baseName = imageStore[id].baseName;
|
| const fileHandle = await handleToUse.getFileHandle(`${baseName}.txt`, { create: true });
|
| const writable = await fileHandle.createWritable();
|
|
|
| await writable.write(new Blob([text], {type: 'text/plain;charset=utf-8'}));
|
| await writable.close();
|
| count++;
|
| }
|
| }
|
| showModal("Success", `Saved ${count} caption files directly to folder.`, null, false);
|
| } catch (err) {
|
| showModal("Error", "Permission to write denied or folder access lost. " + err.message, null, false);
|
| } finally {
|
| btn.innerHTML = originalText;
|
| }
|
| });
|
|
|
|
|
| const modal = document.getElementById('custom-modal');
|
| const modalTitle = document.getElementById('modal-title');
|
| const modalDesc = document.getElementById('modal-desc');
|
| const modalInput = document.getElementById('modal-input');
|
| const btnCancel = document.getElementById('modal-cancel');
|
| const btnConfirm = document.getElementById('modal-confirm');
|
| let modalConfirmCallback = null;
|
|
|
| const showModal = (title, desc, onConfirm, showInput = false, defaultVal = "") => {
|
| modalTitle.textContent = title;
|
| modalDesc.textContent = desc;
|
|
|
| if (showInput) {
|
| modalInput.style.display = 'block';
|
| modalInput.value = defaultVal;
|
| } else {
|
| modalInput.style.display = 'none';
|
| }
|
|
|
| btnCancel.style.display = onConfirm ? 'block' : 'none';
|
| modalConfirmCallback = onConfirm;
|
|
|
| modal.classList.add('active');
|
| if (showInput) modalInput.focus();
|
| };
|
|
|
| const closeModal = () => {
|
| modal.classList.remove('active');
|
| modalConfirmCallback = null;
|
| };
|
|
|
| btnCancel.addEventListener('click', closeModal);
|
| btnConfirm.addEventListener('click', () => {
|
| const val = modalInput.value.trim();
|
| if (modalConfirmCallback) modalConfirmCallback(val);
|
| closeModal();
|
| });
|
| modalInput.addEventListener('keydown', e => {
|
| if (e.key === 'Enter') btnConfirm.click();
|
| });
|
|
|
| </script>
|
| </body>
|
| </html> |