From 98d5b18422b097c8a2032cbe58d48fe60472aabd Mon Sep 17 00:00:00 2001 From: Dariusz L Date: Thu, 26 Jun 2025 05:03:17 +0200 Subject: [PATCH] Remove redundant comments and clean up logging code This commit removes unnecessary and redundant comments from multiple JavaScript modules, streamlining the code and improving readability. No functional changes were made; only comment cleanup and minor formatting adjustments. --- README_LOGGER.md | 4 +-- js/CanvasIO.js | 52 +++----------------------------- js/ErrorHandler.js | 28 ----------------- js/ImageCache.js | 2 -- js/db.js | 6 +--- js/logger.js | 67 +++++++---------------------------------- js/utils/ImageUtils.js | 20 +++++------- js/utils/LoggerUtils.js | 2 -- 8 files changed, 26 insertions(+), 155 deletions(-) diff --git a/README_LOGGER.md b/README_LOGGER.md index bc8ba7f..1316f10 100644 --- a/README_LOGGER.md +++ b/README_LOGGER.md @@ -228,13 +228,13 @@ class Canvas { this.width = 512; this.height = 512; } - + render() { log.debug(`Renderowanie canvas o wymiarach ${this.width}x${this.height}`); // Kod renderowania... log.info("Renderowanie zakończone"); } - + saveToServer(fileName) { log.info(`Zapisywanie do serwera: ${fileName}`); try { diff --git a/js/CanvasIO.js b/js/CanvasIO.js index e16ed1e..2fcd213 100644 --- a/js/CanvasIO.js +++ b/js/CanvasIO.js @@ -13,15 +13,12 @@ export class CanvasIO { } async saveToServer(fileName) { - // Globalna mapa do śledzenia zapisów dla wszystkich node-ów if (!window.canvasSaveStates) { window.canvasSaveStates = new Map(); } const nodeId = this.canvas.node.id; const saveKey = `${nodeId}_${fileName}`; - - // Sprawdź czy już trwa zapis dla tego node-a i pliku if (this._saveInProgress || window.canvasSaveStates.get(saveKey)) { log.warn(`Save already in progress for node ${nodeId}, waiting...`); return this._saveInProgress || window.canvasSaveStates.get(saveKey); @@ -30,8 +27,6 @@ export class CanvasIO { log.info(`Starting saveToServer with fileName: ${fileName} for node: ${nodeId}`); log.debug(`Canvas dimensions: ${this.canvas.width}x${this.canvas.height}`); log.debug(`Number of layers: ${this.canvas.layers.length}`); - - // Utwórz Promise dla aktualnego zapisu this._saveInProgress = this._performSave(fileName); window.canvasSaveStates.set(saveKey, this._saveInProgress); @@ -46,19 +41,13 @@ export class CanvasIO { } async _performSave(fileName) { - // Sprawdź czy są warstwy do zapisania if (this.canvas.layers.length === 0) { log.warn(`Node ${this.canvas.node.id} has no layers, creating empty canvas`); - // Zwróć sukces ale nie zapisuj pustego canvas-a na serwer return Promise.resolve(true); } - - // Zapisz stan do IndexedDB przed zapisem na serwer await this.canvas.saveStateToDB(true); - - // Dodaj krótkie opóźnienie dla różnych node-ów, aby uniknąć konfliktów const nodeId = this.canvas.node.id; - const delay = (nodeId % 10) * 50; // 0-450ms opóźnienia w zależności od ID node-a + const delay = (nodeId % 10) * 50; if (delay > 0) { await new Promise(resolve => setTimeout(resolve, delay)); } @@ -69,24 +58,16 @@ export class CanvasIO { tempCtx.fillStyle = '#ffffff'; tempCtx.fillRect(0, 0, this.canvas.width, this.canvas.height); - - // Tworzymy tymczasowy canvas do renderowania warstw i maski const visibilityCanvas = document.createElement('canvas'); visibilityCanvas.width = this.canvas.width; visibilityCanvas.height = this.canvas.height; const visibilityCtx = visibilityCanvas.getContext('2d', { alpha: true }); - - // Czarne tło (całkowicie przezroczyste w masce) - maskCtx.fillStyle = '#ffffff'; // Białe tło dla wolnych przestrzeni + maskCtx.fillStyle = '#ffffff'; maskCtx.fillRect(0, 0, this.canvas.width, this.canvas.height); log.debug(`Canvas contexts created, starting layer rendering`); - - // Rysowanie warstw const sortedLayers = this.canvas.layers.sort((a, b) => a.zIndex - b.zIndex); log.debug(`Processing ${sortedLayers.length} layers in order`); - - // Najpierw renderujemy wszystkie warstwy do głównego obrazu sortedLayers.forEach((layer, index) => { log.debug(`Processing layer ${index}: zIndex=${layer.zIndex}, size=${layer.width}x${layer.height}, pos=(${layer.x},${layer.y})`); log.debug(`Layer ${index}: blendMode=${layer.blendMode || 'normal'}, opacity=${layer.opacity !== undefined ? layer.opacity : 1}`); @@ -100,58 +81,39 @@ export class CanvasIO { tempCtx.restore(); log.debug(`Layer ${index} rendered successfully`); - - // Renderujemy również do canvas widoczności, aby śledzić, które piksele są widoczne visibilityCtx.save(); visibilityCtx.translate(layer.x + layer.width / 2, layer.y + layer.height / 2); visibilityCtx.rotate(layer.rotation * Math.PI / 180); visibilityCtx.drawImage(layer.image, -layer.width / 2, -layer.height / 2, layer.width, layer.height); visibilityCtx.restore(); }); - - // Teraz tworzymy maskę na podstawie widoczności pikseli, zachowując stopień przezroczystości const visibilityData = visibilityCtx.getImageData(0, 0, this.canvas.width, this.canvas.height); const maskData = maskCtx.getImageData(0, 0, this.canvas.width, this.canvas.height); - - // Używamy wartości alpha do określenia stopnia przezroczystości w masce for (let i = 0; i < visibilityData.data.length; i += 4) { const alpha = visibilityData.data[i + 3]; - // Odwracamy wartość alpha (255 - alpha), aby zachować logikę maski: - // - Przezroczyste piksele w obrazie (alpha = 0) -> białe w masce (255) - // - Nieprzezroczyste piksele w obrazie (alpha = 255) -> czarne w masce (0) - // - Częściowo przezroczyste piksele zachowują proporcjonalną wartość const maskValue = 255 - alpha; maskData.data[i] = maskData.data[i + 1] = maskData.data[i + 2] = maskValue; - maskData.data[i + 3] = 255; // Maska zawsze ma pełną nieprzezroczystość + maskData.data[i + 3] = 255; } maskCtx.putImageData(maskData, 0, 0); - - // Nałóż maskę z narzędzia MaskTool, uwzględniając przezroczystość pędzla const toolMaskCanvas = this.canvas.maskTool.getMask(); if (toolMaskCanvas) { - // Utwórz tymczasowy canvas, aby zachować wartości alpha maski z MaskTool const tempMaskCanvas = document.createElement('canvas'); tempMaskCanvas.width = this.canvas.width; tempMaskCanvas.height = this.canvas.height; const tempMaskCtx = tempMaskCanvas.getContext('2d'); tempMaskCtx.drawImage(toolMaskCanvas, 0, 0); const tempMaskData = tempMaskCtx.getImageData(0, 0, this.canvas.width, this.canvas.height); - - // Zachowaj wartości alpha, aby obszary narysowane pędzlem były nieprzezroczyste na masce for (let i = 0; i < tempMaskData.data.length; i += 4) { const alpha = tempMaskData.data[i + 3]; tempMaskData.data[i] = tempMaskData.data[i + 1] = tempMaskData.data[i + 2] = 255; - tempMaskData.data[i + 3] = alpha; // Zachowaj oryginalną przezroczystość pędzla + tempMaskData.data[i + 3] = alpha; } tempMaskCtx.putImageData(tempMaskData, 0, 0); - - // Nałóż maskę z MaskTool na maskę główną - maskCtx.globalCompositeOperation = 'source-over'; // Dodaje nieprzezroczystość tam, gdzie pędzel był użyty + maskCtx.globalCompositeOperation = 'source-over'; maskCtx.drawImage(tempMaskCanvas, 0, 0); } - - // Zapisz obraz bez maski const fileNameWithoutMask = fileName.replace('.png', '_without_mask.png'); log.info(`Saving image without mask as: ${fileNameWithoutMask}`); @@ -171,8 +133,6 @@ export class CanvasIO { log.error(`Error uploading image without mask:`, error); } }, "image/png"); - - // Zapisz obraz z maską log.info(`Saving main image as: ${fileName}`); tempCanvas.toBlob(async (blob) => { log.debug(`Created blob for main image, size: ${blob.size} bytes`); @@ -206,8 +166,6 @@ export class CanvasIO { if (maskResp.status === 200) { const data = await resp.json(); - // Ustaw widget.value na rzeczywistą nazwę zapisanego pliku (unikalną) - // aby node zwracał właściwy plik this.canvas.widget.value = fileName; log.info(`All files saved successfully, widget value set to: ${fileName}`); resolve(true); diff --git a/js/ErrorHandler.js b/js/ErrorHandler.js index 92c54a8..cdbf154 100644 --- a/js/ErrorHandler.js +++ b/js/ErrorHandler.js @@ -32,8 +32,6 @@ export class AppError extends Error { this.details = details; this.originalError = originalError; this.timestamp = new Date().toISOString(); - - // Zachowaj stack trace if (Error.captureStackTrace) { Error.captureStackTrace(this, AppError); } @@ -59,14 +57,8 @@ export class ErrorHandler { */ handle(error, context = 'Unknown', additionalInfo = {}) { const normalizedError = this.normalizeError(error, context, additionalInfo); - - // Loguj błąd this.logError(normalizedError, context); - - // Zapisz w historii this.recordError(normalizedError); - - // Zwiększ licznik this.incrementErrorCount(normalizedError.type); return normalizedError; @@ -117,38 +109,26 @@ export class ErrorHandler { */ categorizeError(error, context) { const message = error.message.toLowerCase(); - - // Błędy sieciowe if (message.includes('fetch') || message.includes('network') || message.includes('connection') || message.includes('timeout')) { return ErrorTypes.NETWORK; } - - // Błędy plików if (message.includes('file') || message.includes('read') || message.includes('write') || message.includes('path')) { return ErrorTypes.FILE_IO; } - - // Błędy walidacji if (message.includes('invalid') || message.includes('required') || message.includes('validation') || message.includes('format')) { return ErrorTypes.VALIDATION; } - - // Błędy przetwarzania obrazów if (message.includes('image') || message.includes('canvas') || message.includes('blob') || message.includes('tensor')) { return ErrorTypes.IMAGE_PROCESSING; } - - // Błędy stanu if (message.includes('state') || message.includes('cache') || message.includes('storage')) { return ErrorTypes.STATE_MANAGEMENT; } - - // Na podstawie kontekstu if (context.toLowerCase().includes('canvas')) { return ErrorTypes.CANVAS; } @@ -169,8 +149,6 @@ export class ErrorHandler { details: error.details, stack: error.stack }; - - // Różne poziomy logowania w zależności od typu błędu switch (error.type) { case ErrorTypes.VALIDATION: case ErrorTypes.USER_INPUT: @@ -195,8 +173,6 @@ export class ErrorHandler { message: error.message, context: error.details?.context }); - - // Ogranicz rozmiar historii if (this.errorHistory.length > this.maxHistorySize) { this.errorHistory.shift(); } @@ -248,8 +224,6 @@ export class ErrorHandler { log.info('Error history cleared'); } } - -// Singleton instance const errorHandler = new ErrorHandler(); /** @@ -372,7 +346,5 @@ export async function retryWithBackoff(operation, maxRetries = 3, baseDelay = 10 throw errorHandler.handle(lastError, context, { attempts: maxRetries + 1 }); } - -// Eksportuj singleton export { errorHandler }; export default errorHandler; diff --git a/js/ImageCache.js b/js/ImageCache.js index d53bc33..124ab5b 100644 --- a/js/ImageCache.js +++ b/js/ImageCache.js @@ -1,6 +1,4 @@ import {createModuleLogger} from "./utils/LoggerUtils.js"; - -// Inicjalizacja loggera dla modułu ImageCache const log = createModuleLogger('ImageCache'); export class ImageCache { diff --git a/js/db.js b/js/db.js index ddbd600..3140f6a 100644 --- a/js/db.js +++ b/js/db.js @@ -1,12 +1,10 @@ import {createModuleLogger} from "./utils/LoggerUtils.js"; - -// Inicjalizacja loggera dla modułu db const log = createModuleLogger('db'); const DB_NAME = 'CanvasNodeDB'; const STATE_STORE_NAME = 'CanvasState'; const IMAGE_STORE_NAME = 'CanvasImages'; -const DB_VERSION = 2; // Zwiększono wersję, aby wymusić aktualizację schematu +const DB_VERSION = 2; let db; @@ -21,8 +19,6 @@ let db; function createDBRequest(store, operation, data, errorMessage) { return new Promise((resolve, reject) => { let request; - - // Wybierz odpowiednią operację switch (operation) { case 'get': request = store.get(data); diff --git a/js/logger.js b/js/logger.js index 074f415..a14b200 100644 --- a/js/logger.js +++ b/js/logger.js @@ -8,8 +8,6 @@ * - Możliwość zapisywania logów do localStorage * - Możliwość eksportu logów */ - -// Poziomy logowania export const LogLevel = { DEBUG: 0, INFO: 1, @@ -17,27 +15,21 @@ export const LogLevel = { ERROR: 3, NONE: 4 }; - -// Konfiguracja domyślna const DEFAULT_CONFIG = { - globalLevel: LogLevel.INFO, // Domyślny poziom logowania - moduleSettings: {}, // Ustawienia per moduł - useColors: true, // Kolorowe logi w konsoli - saveToStorage: false, // Zapisywanie logów do localStorage - maxStoredLogs: 1000, // Maksymalna liczba przechowywanych logów - timestampFormat: 'HH:mm:ss', // Format znacznika czasu - storageKey: 'layerforge_logs' // Klucz localStorage + globalLevel: LogLevel.INFO, + moduleSettings: {}, + useColors: true, + saveToStorage: false, + maxStoredLogs: 1000, + timestampFormat: 'HH:mm:ss', + storageKey: 'layerforge_logs' }; - -// Kolory dla różnych poziomów logowania const COLORS = { - [LogLevel.DEBUG]: '#9e9e9e', // Szary - [LogLevel.INFO]: '#2196f3', // Niebieski - [LogLevel.WARN]: '#ff9800', // Pomarańczowy - [LogLevel.ERROR]: '#f44336', // Czerwony + [LogLevel.DEBUG]: '#9e9e9e', + [LogLevel.INFO]: '#2196f3', + [LogLevel.WARN]: '#ff9800', + [LogLevel.ERROR]: '#f44336', }; - -// Nazwy poziomów logowania const LEVEL_NAMES = { [LogLevel.DEBUG]: 'DEBUG', [LogLevel.INFO]: 'INFO', @@ -50,8 +42,6 @@ class Logger { this.config = { ...DEFAULT_CONFIG }; this.logs = []; this.enabled = true; - - // Załaduj konfigurację z localStorage, jeśli istnieje this.loadConfig(); } @@ -103,13 +93,9 @@ class Logger { */ isLevelEnabled(module, level) { if (!this.enabled) return false; - - // Sprawdź ustawienia modułu, jeśli istnieją if (this.config.moduleSettings[module] !== undefined) { return level >= this.config.moduleSettings[module]; } - - // W przeciwnym razie użyj globalnego poziomu return level >= this.config.globalLevel; } @@ -120,8 +106,6 @@ class Logger { formatTimestamp() { const now = new Date(); const format = this.config.timestampFormat; - - // Prosty formatter - można rozszerzyć o więcej opcji return format .replace('HH', String(now.getHours()).padStart(2, '0')) .replace('mm', String(now.getMinutes()).padStart(2, '0')) @@ -140,8 +124,6 @@ class Logger { const timestamp = this.formatTimestamp(); const levelName = LEVEL_NAMES[level]; - - // Przygotuj dane logu const logData = { timestamp, module, @@ -150,21 +132,13 @@ class Logger { args, time: new Date() }; - - // Dodaj do pamięci, jeśli zapisywanie jest włączone if (this.config.saveToStorage) { this.logs.push(logData); - - // Ogranicz liczbę przechowywanych logów if (this.logs.length > this.config.maxStoredLogs) { this.logs.shift(); } - - // Zapisz do localStorage this.saveLogs(); } - - // Wyświetl w konsoli this.printToConsole(logData); } @@ -174,18 +148,12 @@ class Logger { */ printToConsole(logData) { const { timestamp, module, level, levelName, args } = logData; - - // Przygotuj prefix logu const prefix = `[${timestamp}] [${module}] [${levelName}]`; - - // Użyj kolorów, jeśli są włączone if (this.config.useColors && typeof console.log === 'function') { const color = COLORS[level] || '#000000'; console.log(`%c${prefix}`, `color: ${color}; font-weight: bold;`, ...args); return; } - - // Fallback bez kolorów console.log(prefix, ...args); } @@ -195,13 +163,11 @@ class Logger { saveLogs() { if (typeof localStorage !== 'undefined' && this.config.saveToStorage) { try { - // Zapisz tylko niezbędne informacje const simplifiedLogs = this.logs.map(log => ({ t: log.timestamp, m: log.module, l: log.level, a: log.args.map(arg => { - // Konwertuj obiekty na stringi if (typeof arg === 'object') { try { return JSON.stringify(arg); @@ -295,15 +261,12 @@ class Logger { mimeType = 'application/json'; extension = 'json'; } else { - // Format tekstowy content = this.logs.map(log => `[${log.timestamp}] [${log.module}] [${log.levelName}] ${log.args.join(' ')}` ).join('\n'); mimeType = 'text/plain'; extension = 'txt'; } - - // Utwórz link do pobrania const blob = new Blob([content], { type: mimeType }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); @@ -314,8 +277,6 @@ class Logger { document.body.removeChild(a); URL.revokeObjectURL(url); } - - // Metody pomocnicze dla różnych poziomów logowania /** * Log na poziomie DEBUG @@ -353,17 +314,11 @@ class Logger { this.log(module, LogLevel.ERROR, ...args); } } - -// Eksportuj singleton export const logger = new Logger(); - -// Eksportuj funkcje pomocnicze export const debug = (module, ...args) => logger.debug(module, ...args); export const info = (module, ...args) => logger.info(module, ...args); export const warn = (module, ...args) => logger.warn(module, ...args); export const error = (module, ...args) => logger.error(module, ...args); - -// Dodaj do window dla łatwego dostępu z konsoli if (typeof window !== 'undefined') { window.LayerForgeLogger = logger; } diff --git a/js/utils/ImageUtils.js b/js/utils/ImageUtils.js index f8b05c3..b5392a1 100644 --- a/js/utils/ImageUtils.js +++ b/js/utils/ImageUtils.js @@ -1,7 +1,5 @@ import {createModuleLogger} from "./LoggerUtils.js"; import {withErrorHandling, createValidationError} from "../ErrorHandler.js"; - -// Inicjalizacja loggera dla modułu ImageUtils const log = createModuleLogger('ImageUtils'); export function validateImageData(data) { @@ -181,9 +179,9 @@ export const imageToTensor = withErrorHandling(async function(image) { for (let i = 0; i < imageData.data.length; i += 4) { const pixelIndex = i / 4; - data[pixelIndex * 3] = imageData.data[i] / 255; // R - data[pixelIndex * 3 + 1] = imageData.data[i + 1] / 255; // G - data[pixelIndex * 3 + 2] = imageData.data[i + 2] / 255; // B + data[pixelIndex * 3] = imageData.data[i] / 255; + data[pixelIndex * 3 + 1] = imageData.data[i + 1] / 255; + data[pixelIndex * 3 + 2] = imageData.data[i + 2] / 255; } return { @@ -218,10 +216,10 @@ export const tensorToImage = withErrorHandling(async function(tensor) { const pixelIndex = i * 4; const tensorIndex = i * channels; - imageData.data[pixelIndex] = Math.round(data[tensorIndex] * 255); // R - imageData.data[pixelIndex + 1] = Math.round(data[tensorIndex + 1] * 255); // G - imageData.data[pixelIndex + 2] = Math.round(data[tensorIndex + 2] * 255); // B - imageData.data[pixelIndex + 3] = 255; // A + imageData.data[pixelIndex] = Math.round(data[tensorIndex] * 255); + imageData.data[pixelIndex + 1] = Math.round(data[tensorIndex + 1] * 255); + imageData.data[pixelIndex + 2] = Math.round(data[tensorIndex + 2] * 255); + imageData.data[pixelIndex + 3] = 255; } ctx.putImageData(imageData, 0, 0); @@ -251,16 +249,12 @@ export const resizeImage = withErrorHandling(async function(image, maxWidth, max const originalWidth = image.width || image.naturalWidth; const originalHeight = image.height || image.naturalHeight; - - // Oblicz nowe wymiary z zachowaniem proporcji const scale = Math.min(maxWidth / originalWidth, maxHeight / originalHeight); const newWidth = Math.round(originalWidth * scale); const newHeight = Math.round(originalHeight * scale); canvas.width = newWidth; canvas.height = newHeight; - - // Użyj wysokiej jakości skalowania ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; diff --git a/js/utils/LoggerUtils.js b/js/utils/LoggerUtils.js index 1743818..d1cbdbc 100644 --- a/js/utils/LoggerUtils.js +++ b/js/utils/LoggerUtils.js @@ -12,7 +12,6 @@ import {logger, LogLevel} from "../logger.js"; * @returns {Object} Obiekt z metodami logowania */ export function createModuleLogger(moduleName, level = LogLevel.DEBUG) { - // Konfiguracja loggera dla modułu logger.setModuleLevel(moduleName, level); return { @@ -29,7 +28,6 @@ export function createModuleLogger(moduleName, level = LogLevel.DEBUG) { * @returns {Object} Obiekt z metodami logowania */ export function createAutoLogger(level = LogLevel.DEBUG) { - // Próba automatycznego wykrycia nazwy modułu z stack trace const stack = new Error().stack; const match = stack.match(/\/([^\/]+)\.js/); const moduleName = match ? match[1] : 'Unknown';