-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutputFormatter.js
More file actions
460 lines (396 loc) · 13.5 KB
/
outputFormatter.js
File metadata and controls
460 lines (396 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// Output formatting - code packing, token counting, format generation
import { isTextFile, isMediaFile, estimateTokens } from './utils.js';
import { shouldExclude } from './exclusionManager.js';
import { updateStatistics, showStatus } from './uiController.js';
import { debounce } from './performance.js';
// Global state
export let packedCode = '';
export let currentFormat = 'plain'; // plain, xml, json, markdown, tree
export let filePriorities = {}; // Store file priorities {path: priority}
let fileWorker = null; // Web Worker for background processing
// Get packed code (used by uiController for copy/download)
export function getPackedCode() {
return packedCode;
}
// Get/Set current format
export function getCurrentFormat() {
return currentFormat;
}
export function setCurrentFormat(format) {
currentFormat = format;
// Save to localStorage
localStorage.setItem('outputFormat', format);
}
// Initialize format from localStorage
export function initializeFormat() {
const savedFormat = localStorage.getItem('outputFormat');
if (savedFormat) {
currentFormat = savedFormat;
}
}
// File priority management
export function setFilePriority(filePath, priority) {
if (priority === 0) {
delete filePriorities[filePath];
} else {
filePriorities[filePath] = priority;
}
// Save to localStorage
localStorage.setItem('filePriorities', JSON.stringify(filePriorities));
}
export function getFilePriority(filePath) {
return filePriorities[filePath] || 0;
}
export function clearFilePriorities() {
filePriorities = {};
localStorage.removeItem('filePriorities');
}
// Initialize priorities from localStorage
export function initializePriorities() {
const savedPriorities = localStorage.getItem('filePriorities');
if (savedPriorities) {
try {
filePriorities = JSON.parse(savedPriorities);
} catch (e) {
filePriorities = {};
}
}
}
// Initialize Web Worker
function initializeWorker() {
if (!fileWorker && typeof Worker !== 'undefined') {
try {
fileWorker = new Worker('fileWorker.js');
fileWorker.onerror = (error) => {
console.warn('Web Worker not available, falling back to main thread:', error);
fileWorker = null;
};
} catch (e) {
console.warn('Web Worker initialization failed, using main thread:', e);
fileWorker = null;
}
}
return fileWorker;
}
// Function to update token count with color-coding (debounced)
function updateTokenCountInternal(tokens) {
const tokenCountSpan = document.getElementById('token-count');
tokenCountSpan.textContent = tokens.toLocaleString();
// Remove all color classes
tokenCountSpan.classList.remove('token-green', 'token-yellow', 'token-orange', 'token-red');
// Add appropriate color class based on token count
if (tokens < 8000) {
tokenCountSpan.classList.add('token-green');
} else if (tokens < 32000) {
tokenCountSpan.classList.add('token-yellow');
} else if (tokens < 100000) {
tokenCountSpan.classList.add('token-orange');
} else {
tokenCountSpan.classList.add('token-red');
}
}
// Debounced version to prevent excessive updates
export const updateTokenCount = debounce(updateTokenCountInternal, 300);
// Function to update total lines of code
export async function updateTotalLines(projectFiles) {
let totalLines = 0;
for (const file of projectFiles) {
const filePath = file.webkitRelativePath;
if (!shouldExclude(filePath) && isTextFile(file.name)) {
await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
const lines = content.split('\n').length;
totalLines += lines;
resolve();
};
reader.readAsText(file);
});
}
}
document.getElementById('total-lines').textContent = totalLines.toLocaleString();
}
// Helper function to sort files by priority
function sortFilesByPriority(files) {
return files.sort((a, b) => {
const priorityA = getFilePriority(a.webkitRelativePath);
const priorityB = getFilePriority(b.webkitRelativePath);
// Higher priority first (5 > 4 > 3 > 2 > 1 > 0)
return priorityB - priorityA;
});
}
// Format generators for different output types
async function generatePlainTextFormat(projectFiles) {
let folderStructure = 'Folder Structure:\n';
let mediaFiles = '\nMedia/Binary Files (listed but not included):\n';
let codeContent = '\nCode Content:\n';
let hasMediaFiles = false;
// Collect all non-excluded files
const includedFiles = projectFiles.filter(file => !shouldExclude(file.webkitRelativePath));
// Add folder structure
for (const file of includedFiles) {
const filePath = file.webkitRelativePath;
const priority = getFilePriority(filePath);
const priorityIndicator = priority > 0 ? ` ⭐${priority}` : '';
folderStructure += `${filePath}${priorityIndicator}\n`;
// Detect media files
if (isMediaFile(file.name)) {
const fileSize = (file.size / 1024).toFixed(2);
mediaFiles += `${filePath} (${fileSize} KB)${priorityIndicator}\n`;
hasMediaFiles = true;
}
}
// Sort files by priority
const sortedFiles = sortFilesByPriority([...includedFiles]);
// Process text files for code content
for (const file of sortedFiles) {
const filePath = file.webkitRelativePath;
if (isTextFile(file.name) && !isMediaFile(file.name)) {
await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
const priority = getFilePriority(filePath);
const priorityIndicator = priority > 0 ? ` ⭐${priority}` : '';
codeContent += `\n--- ${filePath}${priorityIndicator} ---\n${content}\n`;
resolve();
};
reader.readAsText(file);
});
}
}
let output = folderStructure;
if (hasMediaFiles) {
output += mediaFiles;
}
output += codeContent;
return output;
}
async function generateXMLFormat(projectFiles) {
let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<codebase>\n';
const includedFiles = projectFiles.filter(file => !shouldExclude(file.webkitRelativePath));
const sortedFiles = sortFilesByPriority([...includedFiles]);
for (const file of sortedFiles) {
const filePath = file.webkitRelativePath;
const priority = getFilePriority(filePath);
if (isTextFile(file.name) && !isMediaFile(file.name)) {
await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
// Escape XML special characters
const escapedContent = content
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
const priorityAttr = priority > 0 ? ` priority="${priority}"` : '';
xml += ` <file path="${filePath}"${priorityAttr}>\n`;
xml += ` <content><![CDATA[${content}]]></content>\n`;
xml += ` </file>\n`;
resolve();
};
reader.readAsText(file);
});
} else if (isMediaFile(file.name)) {
const fileSize = (file.size / 1024).toFixed(2);
const priorityAttr = priority > 0 ? ` priority="${priority}"` : '';
xml += ` <media-file path="${filePath}" size="${fileSize}KB"${priorityAttr} />\n`;
}
}
xml += '</codebase>';
return xml;
}
async function generateJSONFormat(projectFiles) {
const files = [];
const includedFiles = projectFiles.filter(file => !shouldExclude(file.webkitRelativePath));
const sortedFiles = sortFilesByPriority([...includedFiles]);
for (const file of sortedFiles) {
const filePath = file.webkitRelativePath;
const priority = getFilePriority(filePath);
if (isTextFile(file.name) && !isMediaFile(file.name)) {
await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
const fileObj = {
path: filePath,
type: 'text',
content: content
};
if (priority > 0) {
fileObj.priority = priority;
}
files.push(fileObj);
resolve();
};
reader.readAsText(file);
});
} else if (isMediaFile(file.name)) {
const fileSize = (file.size / 1024).toFixed(2);
const fileObj = {
path: filePath,
type: 'media',
size: `${fileSize}KB`
};
if (priority > 0) {
fileObj.priority = priority;
}
files.push(fileObj);
}
}
return JSON.stringify(files, null, 2);
}
async function generateMarkdownFormat(projectFiles) {
let md = '# Codebase Contents\n\n';
md += '## Table of Contents\n\n';
const includedFiles = projectFiles.filter(file => !shouldExclude(file.webkitRelativePath));
const sortedFiles = sortFilesByPriority([...includedFiles]);
// Generate TOC
const textFiles = sortedFiles.filter(file => isTextFile(file.name) && !isMediaFile(file.name));
textFiles.forEach((file, index) => {
const priority = getFilePriority(file.webkitRelativePath);
const priorityIndicator = priority > 0 ? ` ⭐${priority}` : '';
md += `${index + 1}. [${file.webkitRelativePath}${priorityIndicator}](#file-${index})\n`;
});
md += '\n## Files\n\n';
// Process text files with collapsible sections
for (let i = 0; i < textFiles.length; i++) {
const file = textFiles[i];
const filePath = file.webkitRelativePath;
const priority = getFilePriority(filePath);
const priorityIndicator = priority > 0 ? ` ⭐${priority}` : '';
await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
const fileExt = file.name.split('.').pop();
md += `<details id="file-${i}">\n`;
md += `<summary><strong>${filePath}${priorityIndicator}</strong></summary>\n\n`;
md += `\`\`\`${fileExt}\n${content}\n\`\`\`\n\n`;
md += `</details>\n\n`;
resolve();
};
reader.readAsText(file);
});
}
// Add media files section
const mediaFilesList = sortedFiles.filter(file => isMediaFile(file.name));
if (mediaFilesList.length > 0) {
md += '## Media/Binary Files\n\n';
mediaFilesList.forEach(file => {
const fileSize = (file.size / 1024).toFixed(2);
const priority = getFilePriority(file.webkitRelativePath);
const priorityIndicator = priority > 0 ? ` ⭐${priority}` : '';
md += `- ${file.webkitRelativePath}${priorityIndicator} (${fileSize} KB)\n`;
});
}
return md;
}
async function generateTreeFormat(projectFiles) {
let output = 'Project Structure:\n\n';
const includedFiles = projectFiles.filter(file => !shouldExclude(file.webkitRelativePath));
const sortedFiles = sortFilesByPriority([...includedFiles]);
// Build tree structure
const tree = {};
sortedFiles.forEach(file => {
const parts = file.webkitRelativePath.split('/');
let current = tree;
parts.forEach((part, index) => {
if (!current[part]) {
current[part] = index === parts.length - 1 ? { __file: file } : {};
}
current = current[part];
});
});
// Render tree
function renderTree(node, prefix = '', isLast = true) {
const entries = Object.keys(node).filter(k => k !== '__file');
entries.forEach((key, index) => {
const isLastEntry = index === entries.length - 1;
const connector = isLastEntry ? '└── ' : '├── ';
const childPrefix = prefix + (isLastEntry ? ' ' : '│ ');
if (node[key].__file) {
const file = node[key].__file;
const priority = getFilePriority(file.webkitRelativePath);
const priorityIndicator = priority > 0 ? ` ⭐${priority}` : '';
const fileSize = (file.size / 1024).toFixed(2);
const isMedia = isMediaFile(file.name);
const fileType = isMedia ? ' [media]' : '';
output += `${prefix}${connector}${key}${priorityIndicator}${fileType} (${fileSize} KB)\n`;
} else {
output += `${prefix}${connector}${key}/\n`;
renderTree(node[key], childPrefix, isLastEntry);
}
});
}
renderTree(tree);
output += '\n\nFile Contents:\n\n';
// Add file contents
for (const file of sortedFiles) {
const filePath = file.webkitRelativePath;
if (isTextFile(file.name) && !isMediaFile(file.name)) {
await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
const priority = getFilePriority(filePath);
const priorityIndicator = priority > 0 ? ` ⭐${priority}` : '';
const lines = content.split('\n').length;
output += `━━━ ${filePath}${priorityIndicator} (${lines} lines) ━━━\n${content}\n\n`;
resolve();
};
reader.readAsText(file);
});
}
}
return output;
}
// Main pack code function with format support
export async function packCode(projectFiles) {
let output = '';
let includedCount = 0;
// Count included files
for (const file of projectFiles) {
if (!shouldExclude(file.webkitRelativePath)) {
includedCount++;
}
}
// Generate output based on current format
switch (currentFormat) {
case 'xml':
output = await generateXMLFormat(projectFiles);
break;
case 'json':
output = await generateJSONFormat(projectFiles);
break;
case 'markdown':
output = await generateMarkdownFormat(projectFiles);
break;
case 'tree':
output = await generateTreeFormat(projectFiles);
break;
case 'plain':
default:
output = await generatePlainTextFormat(projectFiles);
break;
}
packedCode = output;
document.getElementById('output-text').value = packedCode;
// Update token count
const tokens = estimateTokens(packedCode);
updateTokenCount(tokens);
// Update file count to show only included files
const totalFilesSpan = document.getElementById('total-files');
totalFilesSpan.textContent = includedCount;
// Enable buttons
document.getElementById('download-btn').disabled = false;
document.getElementById('copy-btn').disabled = false;
showStatus('Code packing complete!', 'success');
// Hide status after delay
setTimeout(() => {
document.getElementById('folder-status').style.display = 'none';
}, 3000);
}