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