Andyx1976 commited on
Commit
c511686
·
verified ·
1 Parent(s): b607269

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +795 -19
index.html CHANGED
@@ -1,19 +1,795 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en" class="dark">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Dataset Caption Tag Manager</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <!-- JSZip for Firefox/Fallback Export -->
9
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
10
+ <script>
11
+ tailwind.config = {
12
+ darkMode: 'class',
13
+ theme: {
14
+ extend: {
15
+ colors: {
16
+ dark: { 900: '#11111b', 800: '#1e1e2e', 700: '#313244', 600: '#45475a', 500: '#585b70' },
17
+ accent: { primary: '#89b4fa', secondary: '#cba6f7', danger: '#f38ba8', success: '#a6e3a1' }
18
+ }
19
+ }
20
+ }
21
+ }
22
+ </script>
23
+ <style>
24
+ /* Custom Scrollbar */
25
+ ::-webkit-scrollbar { width: 8px; height: 8px; }
26
+ ::-webkit-scrollbar-track { background: #1e1e2e; }
27
+ ::-webkit-scrollbar-thumb { background: #45475a; border-radius: 4px; }
28
+ ::-webkit-scrollbar-thumb:hover { background: #585b70; }
29
+
30
+ body { font-family: system-ui, -apple-system, sans-serif; background-color: #11111b; color: #cdd6f4; overflow: hidden; }
31
+
32
+ .img-card { transition: transform 0.1s, box-shadow 0.1s; }
33
+ .img-card.selected { box-shadow: 0 0 0 4px #89b4fa; transform: scale(0.98); }
34
+
35
+ .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;}
36
+ .tag-pill:hover { background: #45475a; }
37
+
38
+ #lightbox { display: none; background: rgba(0,0,0,0.85); backdrop-filter: blur(4px); z-index: 50; }
39
+ #lightbox.active { display: flex; }
40
+ #lightbox img { max-height: 90vh; max-width: 90vw; object-fit: contain; }
41
+
42
+ #custom-modal { display: none; background: rgba(0,0,0,0.6); backdrop-filter: blur(2px); z-index: 60; }
43
+ #custom-modal.active { display: flex; }
44
+
45
+ .drop-zone-overlay { display: none; background: rgba(137, 180, 250, 0.2); border: 4px dashed #89b4fa; z-index: 40;}
46
+ body.dragover .drop-zone-overlay { display: flex; }
47
+ </style>
48
+ </head>
49
+ <body class="h-screen flex flex-col">
50
+
51
+ <!-- Top Navigation Bar -->
52
+ <header class="bg-dark-800 border-b border-dark-700 p-3 flex flex-wrap items-center justify-between gap-4 shrink-0">
53
+ <div class="flex items-center gap-2">
54
+ <h1 class="text-xl font-bold text-accent-primary mr-4">TagManager</h1>
55
+
56
+ <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">
57
+ <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>
58
+ Load Folder
59
+ </button>
60
+ <span class="text-dark-500 text-xs">-or-</span>
61
+ <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">
62
+
63
+ <div class="w-px h-6 bg-dark-600 mx-2"></div>
64
+
65
+ <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">
66
+ <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>
67
+ Undo (<span id="undo-count">0</span>)
68
+ </button>
69
+
70
+ <!-- New Sort Lines Button -->
71
+ <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">
72
+ <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>
73
+ <span id="sort-label">Sort: Time</span>
74
+ </button>
75
+ </div>
76
+
77
+ <div class="flex items-center gap-3">
78
+ <div class="flex items-center gap-1">
79
+ <label class="text-xs text-dark-400">Prefix:</label>
80
+ <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,">
81
+ </div>
82
+ <div class="flex items-center gap-1">
83
+ <label class="text-xs text-dark-400">Suffix:</label>
84
+ <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">
85
+ </div>
86
+
87
+ <label class="flex items-center gap-2 text-sm cursor-pointer ml-2">
88
+ <input type="checkbox" id="toggle-uncaptioned" class="rounded bg-dark-900 border-dark-600 text-accent-primary focus:ring-accent-primary">
89
+ Uncaptioned Only
90
+ </label>
91
+
92
+ <!-- Select/Deselect All Buttons -->
93
+ <div class="flex items-center gap-1 ml-1">
94
+ <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>
95
+ <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>
96
+ </div>
97
+
98
+ <div class="w-px h-6 bg-dark-600 mx-2"></div>
99
+
100
+ <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)">
101
+ <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>
102
+ Save to Folder
103
+ </button>
104
+ <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)">
105
+ <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>
106
+ Export ZIP
107
+ </button>
108
+ </div>
109
+ </header>
110
+
111
+ <!-- Main Layout -->
112
+ <main class="flex-1 flex overflow-hidden">
113
+ <!-- Image Grid -->
114
+ <div id="grid-container" class="flex-1 overflow-y-auto p-4 relative">
115
+ <div class="flex justify-between items-center mb-4 text-sm text-dark-400">
116
+ <span id="status-text">0 Images Loaded</span>
117
+ <span class="italic text-xs">Shift+Click to multi-select. Ctrl+Click to toggle.</span>
118
+ </div>
119
+ <div id="image-grid" class="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-4">
120
+ <!-- Images will be injected here -->
121
+ </div>
122
+ </div>
123
+
124
+ <!-- Right Sidebar (Master List) -->
125
+ <div class="w-80 bg-dark-800 border-l border-dark-700 flex flex-col shrink-0">
126
+ <!-- Lines Section -->
127
+ <div class="flex-1 flex flex-col min-h-0">
128
+ <div class="p-3 bg-dark-700 font-semibold text-sm flex justify-between items-center">
129
+ <span>Sentences / Lines</span>
130
+ <span class="text-xs text-dark-400 font-normal">Click to apply selected</span>
131
+ </div>
132
+ <div class="p-2 border-b border-dark-600 flex gap-2">
133
+ <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)">
134
+ <button id="btn-add-line" class="bg-dark-600 hover:bg-dark-500 px-2 rounded">+</button>
135
+ </div>
136
+ <div id="list-lines" class="flex-1 overflow-y-auto p-2 flex flex-col gap-1">
137
+ <!-- Lines will be injected here -->
138
+ </div>
139
+ </div>
140
+ </div>
141
+ </main>
142
+
143
+ <!-- Overlay UI -->
144
+ <div class="drop-zone-overlay absolute inset-0 items-center justify-center pointer-events-none">
145
+ <div class="bg-dark-800 p-8 rounded-xl border border-accent-primary shadow-2xl flex flex-col items-center">
146
+ <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>
147
+ <h2 class="text-2xl font-bold">Drop Images/Folders Here</h2>
148
+ </div>
149
+ </div>
150
+
151
+ <div id="lightbox" class="fixed inset-0 items-center justify-center">
152
+ <img id="lightbox-img" src="" alt="High-res preview">
153
+ </div>
154
+
155
+ <!-- Custom Modal -->
156
+ <div id="custom-modal" class="fixed inset-0 items-center justify-center">
157
+ <div class="bg-dark-800 border border-dark-600 rounded-lg shadow-xl w-96 p-5 flex flex-col gap-4">
158
+ <h3 id="modal-title" class="text-lg font-bold">Title</h3>
159
+ <p id="modal-desc" class="text-sm text-dark-400">Description</p>
160
+ <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">
161
+ <div class="flex justify-end gap-2 mt-2">
162
+ <button id="modal-cancel" class="px-4 py-2 rounded text-sm bg-dark-700 hover:bg-dark-600 transition">Cancel</button>
163
+ <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>
164
+ </div>
165
+ </div>
166
+ </div>
167
+
168
+ <script>
169
+ // --- State Management ---
170
+ const imageStore = {}; // { id: { file, url, name, hash } }
171
+ let directoryHandle = null; // For File System API saving
172
+
173
+ let state = {
174
+ imageOrder: [], // [id1, id2]
175
+ imageTags: {}, // { id: [tagId1, tagId2] }
176
+ tags: {}, // { tagId: { text: "cat" } }
177
+ selected: [], // [id1, id2]
178
+ globalPrefix: "",
179
+ globalSuffix: "",
180
+ showUncaptioned: false
181
+ };
182
+
183
+ const history = []; // Stack of cloned states (max 3)
184
+ let lastSelectedIdx = -1;
185
+
186
+ let isSortedAlphabetically = false; // View state for sidebar sorting
187
+
188
+ // --- Core Functions ---
189
+ const generateId = () => Math.random().toString(36).substr(2, 9);
190
+
191
+ const pushState = () => {
192
+ history.push(JSON.parse(JSON.stringify(state)));
193
+ if (history.length > 3) history.shift();
194
+ updateUndoUI();
195
+ };
196
+
197
+ const popState = () => {
198
+ if (history.length === 0) return;
199
+ state = history.pop();
200
+ lastSelectedIdx = -1;
201
+ updateUndoUI();
202
+ renderAll();
203
+ };
204
+
205
+ const updateUndoUI = () => {
206
+ const btn = document.getElementById('btn-undo');
207
+ const count = document.getElementById('undo-count');
208
+ count.textContent = history.length;
209
+ btn.disabled = history.length === 0;
210
+ };
211
+
212
+ const createTag = (text) => {
213
+ text = text.trim();
214
+ if (!text) return null;
215
+ // Check if exists
216
+ for (const [id, tag] of Object.entries(state.tags)) {
217
+ if (tag.text.toLowerCase() === text.toLowerCase()) return id;
218
+ }
219
+ const id = generateId();
220
+ state.tags[id] = { text };
221
+ return id;
222
+ };
223
+
224
+ // --- UI & Rendering ---
225
+ const renderAll = () => {
226
+ renderGrid();
227
+ renderSidebar();
228
+ updateStatus();
229
+ document.getElementById('global-prefix').value = state.globalPrefix;
230
+ document.getElementById('global-suffix').value = state.globalSuffix;
231
+ document.getElementById('toggle-uncaptioned').checked = state.showUncaptioned;
232
+ };
233
+
234
+ const updateStatus = () => {
235
+ document.getElementById('status-text').textContent =
236
+ `${state.imageOrder.length} Images Loaded | ${state.selected.length} Selected`;
237
+ };
238
+
239
+ const renderSidebar = () => {
240
+ const listLines = document.getElementById('list-lines');
241
+ listLines.innerHTML = '';
242
+
243
+ const lines = [];
244
+ for (const [id, tag] of Object.entries(state.tags)) {
245
+ lines.push({id, ...tag});
246
+ }
247
+
248
+ // Apply Sort filter if enabled
249
+ if (isSortedAlphabetically) {
250
+ lines.sort((a, b) => a.text.localeCompare(b.text));
251
+ }
252
+
253
+ lines.forEach(l => {
254
+ const el = document.createElement('div');
255
+ 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]';
256
+ el.innerHTML = `
257
+ <p class="pr-12 break-words whitespace-normal">${l.text}</p>
258
+ <div class="absolute right-2 top-1/2 -translate-y-1/2 hidden group-hover:flex gap-2">
259
+ <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>
260
+ <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>
261
+ </div>
262
+ `;
263
+ el.onclick = () => applyTagToSelected(l.id);
264
+ listLines.appendChild(el);
265
+ });
266
+ };
267
+
268
+ const renderGrid = () => {
269
+ const grid = document.getElementById('image-grid');
270
+ grid.innerHTML = '';
271
+
272
+ let visibleOrder = state.imageOrder;
273
+ if (state.showUncaptioned) {
274
+ visibleOrder = visibleOrder.filter(id => state.imageTags[id].length === 0);
275
+ }
276
+
277
+ visibleOrder.forEach((id, displayIdx) => {
278
+ const imgData = imageStore[id];
279
+ const isSelected = state.selected.includes(id);
280
+ const tagIds = state.imageTags[id];
281
+
282
+ const card = document.createElement('div');
283
+ card.className = `img-card bg-dark-800 rounded-lg overflow-hidden border border-dark-700 flex flex-col ${isSelected ? 'selected' : ''}`;
284
+ card.dataset.id = id;
285
+ card.dataset.idx = state.imageOrder.indexOf(id);
286
+
287
+ // Thumbnail area
288
+ const imgWrap = document.createElement('div');
289
+ imgWrap.className = 'relative h-48 w-full cursor-pointer bg-dark-900 group';
290
+ imgWrap.innerHTML = `
291
+ <img src="${imgData.url}" loading="lazy" class="w-full h-full object-contain">
292
+ <div class="absolute inset-0 bg-black/50 hidden group-hover:flex items-center justify-center pointer-events-none">
293
+ <span class="text-white text-xs bg-dark-900/80 px-2 py-1 rounded border border-dark-600">Select</span>
294
+ </div>
295
+ <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">
296
+ <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>
297
+ </button>
298
+ <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>
299
+ `;
300
+ imgWrap.onclick = (e) => handleImageSelect(e, id, state.imageOrder.indexOf(id));
301
+
302
+ // Tags area
303
+ const tagsWrap = document.createElement('div');
304
+ tagsWrap.className = 'p-2 flex-1 flex flex-col gap-2 min-h-[80px] bg-dark-800';
305
+
306
+ const pillsContainer = document.createElement('div');
307
+ pillsContainer.className = 'flex flex-wrap gap-1 flex-1 content-start';
308
+
309
+ tagIds.forEach(tagId => {
310
+ const tagDef = state.tags[tagId];
311
+ if (!tagDef) return; // safety
312
+ const pill = document.createElement('span');
313
+ pill.className = `tag-pill group flex items-start text-left`;
314
+
315
+ const textDisplay = `<span class="break-words whitespace-normal leading-tight py-0.5">${tagDef.text}</span>`;
316
+
317
+ pill.innerHTML = `${textDisplay} <button class="ml-1 text-dark-400 group-hover:text-accent-danger flex-shrink-0" onclick="removeTagFromImage(event, '${id}', '${tagId}')">&times;</button>`;
318
+ pillsContainer.appendChild(pill);
319
+ });
320
+
321
+ // Input to add tag to specific image
322
+ const inputWrap = document.createElement('div');
323
+ 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}')">`;
324
+
325
+ tagsWrap.appendChild(pillsContainer);
326
+ tagsWrap.appendChild(inputWrap);
327
+
328
+ card.appendChild(imgWrap);
329
+ card.appendChild(tagsWrap);
330
+ grid.appendChild(card);
331
+ });
332
+ };
333
+
334
+ // --- Interaction Logic ---
335
+ const handleImageSelect = (e, id, idx) => {
336
+ pushState();
337
+ if (e.shiftKey && lastSelectedIdx !== -1) {
338
+ // Range select
339
+ const start = Math.min(lastSelectedIdx, idx);
340
+ const end = Math.max(lastSelectedIdx, idx);
341
+ for (let i = start; i <= end; i++) {
342
+ const currId = state.imageOrder[i];
343
+ if (!state.selected.includes(currId)) state.selected.push(currId);
344
+ }
345
+ } else if (e.ctrlKey || e.metaKey) {
346
+ // Toggle
347
+ const sIdx = state.selected.indexOf(id);
348
+ if (sIdx > -1) state.selected.splice(sIdx, 1);
349
+ else state.selected.push(id);
350
+ lastSelectedIdx = idx;
351
+ } else {
352
+ // Single select (or deselect all if clicking already selected)
353
+ if (state.selected.length === 1 && state.selected[0] === id) {
354
+ state.selected = [];
355
+ lastSelectedIdx = -1;
356
+ } else {
357
+ state.selected = [id];
358
+ lastSelectedIdx = idx;
359
+ }
360
+ }
361
+ renderGridClasses();
362
+ updateStatus();
363
+ };
364
+
365
+ const renderGridClasses = () => {
366
+ document.querySelectorAll('.img-card').forEach(card => {
367
+ if (state.selected.includes(card.dataset.id)) card.classList.add('selected');
368
+ else card.classList.remove('selected');
369
+ });
370
+ }
371
+
372
+ const applyTagToSelected = (tagId) => {
373
+ if (state.selected.length === 0) {
374
+ showModal("Info", "Select one or more images first to apply this line.", null, false);
375
+ return;
376
+ }
377
+ pushState();
378
+ let applied = 0;
379
+ state.selected.forEach(imgId => {
380
+ if (!state.imageTags[imgId].includes(tagId)) {
381
+ state.imageTags[imgId].push(tagId);
382
+ applied++;
383
+ }
384
+ });
385
+ if (applied > 0) renderGrid();
386
+ };
387
+
388
+ const removeTagFromImage = (e, imgId, tagId) => {
389
+ e.stopPropagation();
390
+ pushState();
391
+ state.imageTags[imgId] = state.imageTags[imgId].filter(t => t !== tagId);
392
+ renderGrid();
393
+ };
394
+
395
+ const handleImageInputKey = (e, imgId) => {
396
+ if (e.key === 'Enter' && e.target.value.trim()) {
397
+ pushState();
398
+ const text = e.target.value.trim();
399
+ const tagId = createTag(text);
400
+ if (!state.imageTags[imgId].includes(tagId)) {
401
+ state.imageTags[imgId].push(tagId);
402
+ }
403
+ e.target.value = '';
404
+ renderAll();
405
+ }
406
+ };
407
+
408
+ const deleteMasterTag = (e, tagId) => {
409
+ e.stopPropagation();
410
+ pushState();
411
+ // Remove from master list
412
+ delete state.tags[tagId];
413
+ // Remove from all images
414
+ for (const imgId of state.imageOrder) {
415
+ state.imageTags[imgId] = state.imageTags[imgId].filter(t => t !== tagId);
416
+ }
417
+ renderAll();
418
+ };
419
+
420
+ const editTag = (e, tagId) => {
421
+ e.stopPropagation();
422
+ const tag = state.tags[tagId];
423
+ showModal("Edit Line", "Modify the text. Changes will reflect on all linked images.", (newVal) => {
424
+ if (newVal) {
425
+ pushState();
426
+ state.tags[tagId].text = newVal;
427
+ renderAll();
428
+ }
429
+ }, true, tag.text);
430
+ };
431
+
432
+ // --- File Handling & Importing ---
433
+ const processFiles = async (filesArray) => {
434
+ const images = [];
435
+ const texts = {}; // lowercase basename -> content
436
+
437
+ for (const file of filesArray) {
438
+ if (!file || !file.name) continue;
439
+ const name = file.name;
440
+ const ext = name.slice((name.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
441
+ if (['jpg', 'jpeg', 'png', 'webp'].includes(ext)) {
442
+ images.push(file);
443
+ } else if (ext === 'txt') {
444
+ const baseName = name.replace(/\.[^/.]+$/, "").toLowerCase();
445
+ const text = await file.text();
446
+ texts[baseName] = text;
447
+ }
448
+ }
449
+
450
+ if (images.length === 0) return;
451
+ pushState();
452
+
453
+ images.forEach(imgFile => {
454
+ const baseName = imgFile.name.replace(/\.[^/.]+$/, "");
455
+ const hash = imgFile.name + imgFile.size; // Basic dup check
456
+
457
+ // Skip duplicates
458
+ let isDup = false;
459
+ for (const existingId of state.imageOrder) {
460
+ if (imageStore[existingId].hash === hash) { isDup = true; break; }
461
+ }
462
+ if (isDup) return;
463
+
464
+ const id = generateId();
465
+ imageStore[id] = {
466
+ file: imgFile,
467
+ url: URL.createObjectURL(imgFile),
468
+ name: imgFile.name,
469
+ hash: hash,
470
+ baseName: baseName
471
+ };
472
+ state.imageOrder.push(id);
473
+ state.imageTags[id] = [];
474
+
475
+ // Import logic: Check if matching txt exists
476
+ if (texts[baseName.toLowerCase()]) {
477
+ const content = texts[baseName.toLowerCase()];
478
+ // Split by comma for tags
479
+ const parts = content.split(',').map(s => s.trim()).filter(s => s);
480
+ parts.forEach(part => {
481
+ const tagId = createTag(part);
482
+ if (!state.imageTags[id].includes(tagId)) {
483
+ state.imageTags[id].push(tagId);
484
+ }
485
+ });
486
+ }
487
+ });
488
+
489
+ renderAll();
490
+ };
491
+
492
+ // --- Event Listeners ---
493
+
494
+ // Add Master Lines
495
+ document.getElementById('input-new-line').addEventListener('keydown', (e) => {
496
+ if (e.key === 'Enter') document.getElementById('btn-add-line').click();
497
+ });
498
+ document.getElementById('btn-add-line').addEventListener('click', () => {
499
+ const inp = document.getElementById('input-new-line');
500
+ if(inp.value.trim()) { pushState(); createTag(inp.value); inp.value = ''; renderSidebar(); }
501
+ });
502
+
503
+ // Toggle Sorting Logic
504
+ document.getElementById('btn-sort-lines').addEventListener('click', (e) => {
505
+ isSortedAlphabetically = !isSortedAlphabetically;
506
+ const btn = e.currentTarget;
507
+ const label = document.getElementById('sort-label');
508
+
509
+ if (isSortedAlphabetically) {
510
+ label.textContent = 'Sort: A-Z';
511
+ btn.classList.replace('text-white', 'text-accent-primary');
512
+ btn.classList.replace('border-transparent', 'border-accent-primary');
513
+ } else {
514
+ label.textContent = 'Sort: Time';
515
+ btn.classList.replace('text-accent-primary', 'text-white');
516
+ btn.classList.replace('border-accent-primary', 'border-transparent');
517
+ }
518
+ renderSidebar();
519
+ });
520
+
521
+ // Top Bar inputs & Toggles
522
+ document.getElementById('global-prefix').addEventListener('input', e => state.globalPrefix = e.target.value);
523
+ document.getElementById('global-suffix').addEventListener('input', e => state.globalSuffix = e.target.value);
524
+
525
+ document.getElementById('toggle-uncaptioned').addEventListener('change', e => {
526
+ state.showUncaptioned = e.target.checked;
527
+ renderGrid();
528
+ });
529
+
530
+ document.getElementById('btn-select-all').addEventListener('click', () => {
531
+ if (state.imageOrder.length === 0) return;
532
+ pushState();
533
+ let visibleOrder = state.imageOrder;
534
+ if (state.showUncaptioned) {
535
+ visibleOrder = visibleOrder.filter(id => state.imageTags[id].length === 0);
536
+ }
537
+ state.selected = [...visibleOrder];
538
+ renderGridClasses();
539
+ updateStatus();
540
+ });
541
+
542
+ document.getElementById('btn-deselect-all').addEventListener('click', () => {
543
+ if (state.selected.length === 0) return;
544
+ pushState();
545
+ state.selected = [];
546
+ lastSelectedIdx = -1;
547
+ renderGridClasses();
548
+ updateStatus();
549
+ });
550
+
551
+ document.getElementById('btn-undo').addEventListener('click', popState);
552
+
553
+ // Lightbox
554
+ const lightbox = document.getElementById('lightbox');
555
+ const openLightbox = (e, url) => {
556
+ e.stopPropagation();
557
+ document.getElementById('lightbox-img').src = url;
558
+ lightbox.classList.add('active');
559
+ };
560
+ lightbox.addEventListener('click', () => lightbox.classList.remove('active'));
561
+
562
+ // Load folder via standard input fallback
563
+ document.getElementById('btn-load-files').addEventListener('change', (e) => {
564
+ processFiles(Array.from(e.target.files));
565
+ e.target.value = ''; // reset
566
+ });
567
+
568
+ // Load folder via API (Chromium)
569
+ document.getElementById('btn-load-folder').addEventListener('click', async () => {
570
+ if (!window.showDirectoryPicker) {
571
+ 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);
572
+ return;
573
+ }
574
+ try {
575
+ directoryHandle = await window.showDirectoryPicker({ mode: 'readwrite' });
576
+ const files = [];
577
+ for await (const entry of directoryHandle.values()) {
578
+ if (entry.kind === 'file') {
579
+ files.push(await entry.getFile());
580
+ }
581
+ }
582
+ processFiles(files);
583
+ } catch (err) {
584
+ console.warn(err);
585
+ }
586
+ });
587
+
588
+ // --- Chromium-Proof Drag and Drop ---
589
+ document.body.addEventListener('dragover', e => { e.preventDefault(); document.body.classList.add('dragover'); });
590
+ document.body.addEventListener('dragleave', e => { if (e.target === document.body || e.relatedTarget === null) document.body.classList.remove('dragover'); });
591
+ document.body.addEventListener('drop', e => {
592
+ e.preventDefault();
593
+ document.body.classList.remove('dragover');
594
+
595
+ const files = [];
596
+ const dirEntries = [];
597
+
598
+ if (e.dataTransfer.items) {
599
+ // Parse synchronously! Chromium will clear e.dataTransfer.items if we yield/await here.
600
+ for (let i = 0; i < e.dataTransfer.items.length; i++) {
601
+ const item = e.dataTransfer.items[i];
602
+ if (item.kind === 'file') {
603
+ const entry = item.webkitGetAsEntry ? item.webkitGetAsEntry() : null;
604
+ if (entry && entry.isDirectory) {
605
+ dirEntries.push(entry);
606
+ } else {
607
+ const file = item.getAsFile();
608
+ if (file) files.push(file);
609
+ }
610
+ }
611
+ }
612
+ } else if (e.dataTransfer.files) {
613
+ for (let i = 0; i < e.dataTransfer.files.length; i++) {
614
+ files.push(e.dataTransfer.files[i]);
615
+ }
616
+ }
617
+
618
+ // Fast path for normal file drops
619
+ if (dirEntries.length === 0) {
620
+ if (files.length > 0) processFiles(files);
621
+ return;
622
+ }
623
+
624
+ // Complex path for dropped folders (Recursive reading)
625
+ const readDir = (dirEntry) => {
626
+ return new Promise(resolve => {
627
+ const dirReader = dirEntry.createReader();
628
+ const allEntries = [];
629
+
630
+ const readBatch = () => {
631
+ dirReader.readEntries(async (entries) => {
632
+ if (entries.length === 0) {
633
+ // Batch finished, now process the collected entries
634
+ const filePromises = allEntries.map(ent => {
635
+ return new Promise(res => {
636
+ if (ent.isFile) {
637
+ ent.file(f => res(f), () => res(null));
638
+ } else if (ent.isDirectory) {
639
+ readDir(ent).then(res); // Recurse inside
640
+ } else {
641
+ res(null);
642
+ }
643
+ });
644
+ });
645
+ const nestedFiles = await Promise.all(filePromises);
646
+ resolve(nestedFiles.flat().filter(f => f !== null));
647
+ } else {
648
+ allEntries.push(...entries);
649
+ readBatch(); // Fetch next batch of 100 entries
650
+ }
651
+ }, () => resolve([])); // Error fallback
652
+ };
653
+ readBatch();
654
+ });
655
+ };
656
+
657
+ // Process all dropped directory entries
658
+ Promise.all(dirEntries.map(readDir)).then(results => {
659
+ files.push(...results.flat());
660
+ if (files.length > 0) processFiles(files);
661
+ });
662
+ });
663
+
664
+ // Get Caption String for an Image
665
+ const getCaptionString = (id) => {
666
+ const tagIds = state.imageTags[id];
667
+ let elements = [];
668
+ if (state.globalPrefix) elements.push(state.globalPrefix.trim());
669
+
670
+ tagIds.forEach(tid => {
671
+ if(state.tags[tid]) elements.push(state.tags[tid].text);
672
+ });
673
+
674
+ if (state.globalSuffix) elements.push(state.globalSuffix.trim());
675
+
676
+ // Join properly avoiding double commas
677
+ return elements.join(', ').replace(/,\s*,/g, ',').trim();
678
+ };
679
+
680
+ // Export ZIP
681
+ document.getElementById('btn-export-zip').addEventListener('click', async () => {
682
+ if (state.imageOrder.length === 0) return showModal("Info", "No images loaded.", null, false);
683
+
684
+ const zip = new JSZip();
685
+ let count = 0;
686
+ state.imageOrder.forEach(id => {
687
+ const text = getCaptionString(id);
688
+ if (text) {
689
+ const baseName = imageStore[id].baseName;
690
+ zip.file(`${baseName}.txt`, text);
691
+ count++;
692
+ }
693
+ });
694
+
695
+ if (count === 0) return showModal("Info", "No captions to export.", null, false);
696
+
697
+ const btn = document.getElementById('btn-export-zip');
698
+ const originalText = btn.innerHTML;
699
+ btn.innerHTML = 'Generating...';
700
+
701
+ zip.generateAsync({type:"blob"}).then(function(content) {
702
+ const a = document.createElement("a");
703
+ a.href = URL.createObjectURL(content);
704
+ a.download = "captions_export.zip";
705
+ a.click();
706
+ btn.innerHTML = originalText;
707
+ });
708
+ });
709
+
710
+ // Export to Folder (Direct API)
711
+ document.getElementById('btn-export-folder').addEventListener('click', async () => {
712
+ if (!window.showDirectoryPicker) {
713
+ showModal("Browser Unsupported", "Saving directly to a folder requires a Chromium browser. Please use 'Export ZIP' instead.", null, false);
714
+ return;
715
+ }
716
+ if (state.imageOrder.length === 0) return showModal("Info", "No images loaded.", null, false);
717
+
718
+ let handleToUse = directoryHandle;
719
+ if (!handleToUse) {
720
+ try {
721
+ handleToUse = await window.showDirectoryPicker({ mode: 'readwrite' });
722
+ } catch(e) { return; } // User cancelled
723
+ }
724
+
725
+ const btn = document.getElementById('btn-export-folder');
726
+ const originalText = btn.innerHTML;
727
+ btn.innerHTML = 'Saving...';
728
+
729
+ let count = 0;
730
+ try {
731
+ for (const id of state.imageOrder) {
732
+ const text = getCaptionString(id);
733
+ if (text) {
734
+ const baseName = imageStore[id].baseName;
735
+ const fileHandle = await handleToUse.getFileHandle(`${baseName}.txt`, { create: true });
736
+ const writable = await fileHandle.createWritable();
737
+ // Flux standard dictates utf-8
738
+ await writable.write(new Blob([text], {type: 'text/plain;charset=utf-8'}));
739
+ await writable.close();
740
+ count++;
741
+ }
742
+ }
743
+ showModal("Success", `Saved ${count} caption files directly to folder.`, null, false);
744
+ } catch (err) {
745
+ showModal("Error", "Permission to write denied or folder access lost. " + err.message, null, false);
746
+ } finally {
747
+ btn.innerHTML = originalText;
748
+ }
749
+ });
750
+
751
+ // --- Custom Modal UI ---
752
+ const modal = document.getElementById('custom-modal');
753
+ const modalTitle = document.getElementById('modal-title');
754
+ const modalDesc = document.getElementById('modal-desc');
755
+ const modalInput = document.getElementById('modal-input');
756
+ const btnCancel = document.getElementById('modal-cancel');
757
+ const btnConfirm = document.getElementById('modal-confirm');
758
+ let modalConfirmCallback = null;
759
+
760
+ const showModal = (title, desc, onConfirm, showInput = false, defaultVal = "") => {
761
+ modalTitle.textContent = title;
762
+ modalDesc.textContent = desc;
763
+
764
+ if (showInput) {
765
+ modalInput.style.display = 'block';
766
+ modalInput.value = defaultVal;
767
+ } else {
768
+ modalInput.style.display = 'none';
769
+ }
770
+
771
+ btnCancel.style.display = onConfirm ? 'block' : 'none';
772
+ modalConfirmCallback = onConfirm;
773
+
774
+ modal.classList.add('active');
775
+ if (showInput) modalInput.focus();
776
+ };
777
+
778
+ const closeModal = () => {
779
+ modal.classList.remove('active');
780
+ modalConfirmCallback = null;
781
+ };
782
+
783
+ btnCancel.addEventListener('click', closeModal);
784
+ btnConfirm.addEventListener('click', () => {
785
+ const val = modalInput.value.trim();
786
+ if (modalConfirmCallback) modalConfirmCallback(val);
787
+ closeModal();
788
+ });
789
+ modalInput.addEventListener('keydown', e => {
790
+ if (e.key === 'Enter') btnConfirm.click();
791
+ });
792
+
793
+ </script>
794
+ </body>
795
+ </html>