Refactor code style and remove mask editor examples

This commit applies consistent code style changes (mainly spacing and formatting) across multiple JS files for improved readability and maintainability. Additionally, it removes the unused 'js/examples/mask_editor_examples.js' file.
This commit is contained in:
Dariusz L
2025-07-01 06:44:26 +02:00
parent a0ceb3b97c
commit b89956d2ba
10 changed files with 142 additions and 297 deletions

View File

@@ -1,5 +1,5 @@
import { app, ComfyApp } from "../../scripts/app.js"; import {app, ComfyApp} from "../../scripts/app.js";
import { api } from "../../scripts/api.js"; import {api} from "../../scripts/api.js";
import {removeImage} from "./db.js"; import {removeImage} from "./db.js";
import {MaskTool} from "./MaskTool.js"; import {MaskTool} from "./MaskTool.js";
import {CanvasState} from "./CanvasState.js"; import {CanvasState} from "./CanvasState.js";
@@ -9,7 +9,7 @@ import {CanvasRenderer} from "./CanvasRenderer.js";
import {CanvasIO} from "./CanvasIO.js"; import {CanvasIO} from "./CanvasIO.js";
import {ImageReferenceManager} from "./ImageReferenceManager.js"; import {ImageReferenceManager} from "./ImageReferenceManager.js";
import {createModuleLogger} from "./utils/LoggerUtils.js"; import {createModuleLogger} from "./utils/LoggerUtils.js";
import { mask_editor_showing, mask_editor_listen_for_cancel } from "./utils/mask_utils.js"; import {mask_editor_showing, mask_editor_listen_for_cancel} from "./utils/mask_utils.js";
const log = createModuleLogger('Canvas'); const log = createModuleLogger('Canvas');
@@ -110,7 +110,7 @@ export class Canvas {
} }
console.log("Setting computeSize to fixed height 250"); console.log("Setting computeSize to fixed height 250");
imagePreviewWidget.computeSize = function() { imagePreviewWidget.computeSize = function () {
return [0, 250]; // Szerokość 0 (auto), wysokość 250 return [0, 250]; // Szerokość 0 (auto), wysokość 250
}; };
@@ -128,7 +128,7 @@ export class Canvas {
imagePreviewWidget.hidden = true; imagePreviewWidget.hidden = true;
} }
imagePreviewWidget.computeSize = function() { imagePreviewWidget.computeSize = function () {
return [0, 0]; // Szerokość 0, wysokość 0 return [0, 0]; // Szerokość 0, wysokość 0
}; };
@@ -173,8 +173,6 @@ export class Canvas {
} }
/** /**
* Ładuje stan canvas z bazy danych * Ładuje stan canvas z bazy danych
*/ */
@@ -292,8 +290,6 @@ export class Canvas {
} }
/** /**
* Uruchamia edytor masek * Uruchamia edytor masek
* @param {Image|HTMLCanvasElement|null} predefinedMask - Opcjonalna maska do nałożenia po otwarciu editora * @param {Image|HTMLCanvasElement|null} predefinedMask - Opcjonalna maska do nałożenia po otwarciu editora
@@ -374,8 +370,6 @@ export class Canvas {
} }
/** /**
* Inicjalizuje podstawowe właściwości canvas * Inicjalizuje podstawowe właściwości canvas
*/ */
@@ -428,7 +422,7 @@ export class Canvas {
const mouseX_Canvas = mouseX_DOM * scaleX; const mouseX_Canvas = mouseX_DOM * scaleX;
const mouseY_Canvas = mouseY_DOM * scaleY; const mouseY_Canvas = mouseY_DOM * scaleY;
return { x: mouseX_Canvas, y: mouseY_Canvas }; return {x: mouseX_Canvas, y: mouseY_Canvas};
} }
/** /**
@@ -488,8 +482,6 @@ export class Canvas {
} }
/** /**
* Czeka na otwarcie mask editora i automatycznie nakłada predefiniowaną maskę * Czeka na otwarcie mask editora i automatycznie nakłada predefiniowaną maskę
*/ */
@@ -653,7 +645,7 @@ export class Canvas {
const maskCtx = maskCanvas.getContext('2d'); const maskCtx = maskCanvas.getContext('2d');
const maskColor = { r: 255, g: 255, b: 255 }; const maskColor = {r: 255, g: 255, b: 255};
const processedMask = await this.processMaskForEditor(maskData, maskCanvas.width, maskCanvas.height, maskColor); const processedMask = await this.processMaskForEditor(maskData, maskCanvas.width, maskCanvas.height, maskColor);
maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height); maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
@@ -673,9 +665,9 @@ export class Canvas {
const originalHeight = maskData.height || maskData.naturalHeight || this.height; const originalHeight = maskData.height || maskData.naturalHeight || this.height;
log.info("Processing mask for editor:", { log.info("Processing mask for editor:", {
originalSize: { width: originalWidth, height: originalHeight }, originalSize: {width: originalWidth, height: originalHeight},
targetSize: { width: targetWidth, height: targetHeight }, targetSize: {width: targetWidth, height: targetHeight},
canvasSize: { width: this.width, height: this.height } canvasSize: {width: this.width, height: this.height}
}); });
const tempCanvas = document.createElement('canvas'); const tempCanvas = document.createElement('canvas');
@@ -697,12 +689,12 @@ export class Canvas {
tempCtx.drawImage(maskData, offsetX, offsetY, scaledWidth, scaledHeight); tempCtx.drawImage(maskData, offsetX, offsetY, scaledWidth, scaledHeight);
log.info("Mask drawn scaled to original image size:", { log.info("Mask drawn scaled to original image size:", {
originalSize: { width: originalWidth, height: originalHeight }, originalSize: {width: originalWidth, height: originalHeight},
targetSize: { width: targetWidth, height: targetHeight }, targetSize: {width: targetWidth, height: targetHeight},
canvasSize: { width: this.width, height: this.height }, canvasSize: {width: this.width, height: this.height},
scaleToOriginal: scaleToOriginal, scaleToOriginal: scaleToOriginal,
finalSize: { width: scaledWidth, height: scaledHeight }, finalSize: {width: scaledWidth, height: scaledHeight},
offset: { x: offsetX, y: offsetY } offset: {x: offsetX, y: offsetY}
}); });
const imageData = tempCtx.getImageData(0, 0, targetWidth, targetHeight); const imageData = tempCtx.getImageData(0, 0, targetWidth, targetHeight);
@@ -826,8 +818,6 @@ export class Canvas {
} }
/** /**
* Zapisuje obecny stan maski przed otwarciem editora * Zapisuje obecny stan maski przed otwarciem editora
* @returns {Object} Zapisany stan maski * @returns {Object} Zapisany stan maski

View File

@@ -2,7 +2,7 @@ import {saveImage, removeImage} from "./db.js";
import {createModuleLogger} from "./utils/LoggerUtils.js"; import {createModuleLogger} from "./utils/LoggerUtils.js";
import {generateUUID, generateUniqueFileName} from "./utils/CommonUtils.js"; import {generateUUID, generateUniqueFileName} from "./utils/CommonUtils.js";
import {withErrorHandling, createValidationError} from "./ErrorHandler.js"; import {withErrorHandling, createValidationError} from "./ErrorHandler.js";
import { app, ComfyApp } from "../../scripts/app.js"; import {app, ComfyApp} from "../../scripts/app.js";
const log = createModuleLogger('CanvasLayers'); const log = createModuleLogger('CanvasLayers');

View File

@@ -1106,7 +1106,7 @@ async function createCanvasWidget(node, widget, app) {
if (showPreviewWidget) { if (showPreviewWidget) {
const originalCallback = showPreviewWidget.callback; const originalCallback = showPreviewWidget.callback;
showPreviewWidget.callback = function(value) { showPreviewWidget.callback = function (value) {
if (originalCallback) { if (originalCallback) {
originalCallback.call(this, value); originalCallback.call(this, value);
} }
@@ -1124,7 +1124,6 @@ async function createCanvasWidget(node, widget, app) {
} }
return { return {
canvas: canvas, canvas: canvas,
panel: controlPanel panel: controlPanel

View File

@@ -283,7 +283,6 @@ export class MaskTool {
setMask(image) { setMask(image) {
const destX = -this.x; const destX = -this.x;
const destY = -this.y; const destY = -this.y;

View File

@@ -1,141 +0,0 @@
/**
* Przykłady użycia automatycznego nakładania masek w mask editorze
*
* Te przykłady pokazują jak używać nowej funkcjonalności do automatycznego
* nakładania predefiniowanych masek po otwarciu mask editora ComfyUI.
*/
import {
start_mask_editor_with_predefined_mask,
create_mask_from_image_src,
canvas_to_mask_image
} from '../utils/mask_utils.js';
/**
* Przykład 1: Podstawowe użycie z obrazem maski
*/
async function example1_basic_usage(canvasInstance) {
const maskImage = await create_mask_from_image_src('/path/to/mask.png');
start_mask_editor_with_predefined_mask(canvasInstance, maskImage, true);
}
/**
* Przykład 2: Użycie z canvas jako maska
*/
async function example2_canvas_mask(canvasInstance) {
const maskCanvas = document.createElement('canvas');
maskCanvas.width = 512;
maskCanvas.height = 512;
const ctx = maskCanvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 512, 512);
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(256, 256, 100, 0, 2 * Math.PI);
ctx.fill();
const maskImage = await canvas_to_mask_image(maskCanvas);
start_mask_editor_with_predefined_mask(canvasInstance, maskImage, true);
}
/**
* Przykład 3: Bezpośrednie użycie metody Canvas
*/
async function example3_direct_canvas_method(canvasInstance) {
const maskImage = await create_mask_from_image_src('/path/to/mask.png');
await canvasInstance.startMaskEditor(maskImage, true);
}
/**
* Przykład 4: Tworzenie maski z danych binarnych
*/
async function example4_binary_data_mask(canvasInstance, binaryData) {
const blob = new Blob([binaryData], { type: 'image/png' });
const dataUrl = URL.createObjectURL(blob);
const maskImage = await create_mask_from_image_src(dataUrl);
start_mask_editor_with_predefined_mask(canvasInstance, maskImage, true);
URL.revokeObjectURL(dataUrl);
}
/**
* Przykład 5: Maska z gradientem
*/
async function example5_gradient_mask(canvasInstance) {
const maskCanvas = document.createElement('canvas');
maskCanvas.width = 512;
maskCanvas.height = 512;
const ctx = maskCanvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, 512, 0);
gradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); // Przezroczysty
gradient.addColorStop(1, 'rgba(255, 255, 255, 1)'); // Biały
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 512, 512);
const maskImage = await canvas_to_mask_image(maskCanvas);
start_mask_editor_with_predefined_mask(canvasInstance, maskImage, true);
}
/**
* Przykład 6: Obsługa błędów
*/
async function example6_error_handling(canvasInstance) {
try {
const maskImage = await create_mask_from_image_src('/path/to/nonexistent.png');
start_mask_editor_with_predefined_mask(canvasInstance, maskImage, true);
} catch (error) {
console.error('Błąd podczas ładowania maski:', error);
await canvasInstance.startMaskEditor();
}
}
/**
* Przykład 7: Maska z istniejącego elementu canvas na stronie
*/
async function example7_existing_canvas_element(canvasInstance, canvasElementId) {
const existingCanvas = document.getElementById(canvasElementId);
if (!existingCanvas) {
console.error('Canvas element not found:', canvasElementId);
return;
}
const maskImage = await canvas_to_mask_image(existingCanvas);
start_mask_editor_with_predefined_mask(canvasInstance, maskImage, true);
}
/**
* Przykład 8: Kombinowanie z istniejącą maską
*/
async function example8_combine_with_existing_mask(canvasInstance) {
const maskImage = await create_mask_from_image_src('/path/to/mask.png');
start_mask_editor_with_predefined_mask(canvasInstance, maskImage, false);
}
export {
example1_basic_usage,
example2_canvas_mask,
example3_direct_canvas_method,
example4_binary_data_mask,
example5_gradient_mask,
example6_error_handling,
example7_existing_canvas_element,
example8_combine_with_existing_mask
};

View File

@@ -8,7 +8,7 @@
* @returns {string} UUID w formacie xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx * @returns {string} UUID w formacie xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
*/ */
export function generateUUID() { export function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16); return v.toString(16);
}); });
@@ -179,7 +179,7 @@ export function debounce(func, wait, immediate) {
*/ */
export function throttle(func, limit) { export function throttle(func, limit) {
let inThrottle; let inThrottle;
return function(...args) { return function (...args) {
if (!inThrottle) { if (!inThrottle) {
func.apply(this, args); func.apply(this, args);
inThrottle = true; inThrottle = true;
@@ -241,7 +241,7 @@ export function createCanvas(width, height, contextType = '2d', contextOptions =
if (width) canvas.width = width; if (width) canvas.width = width;
if (height) canvas.height = height; if (height) canvas.height = height;
const ctx = canvas.getContext(contextType, contextOptions); const ctx = canvas.getContext(contextType, contextOptions);
return { canvas, ctx }; return {canvas, ctx};
} }
/** /**

View File

@@ -1,5 +1,6 @@
import {createModuleLogger} from "./LoggerUtils.js"; import {createModuleLogger} from "./LoggerUtils.js";
import {withErrorHandling, createValidationError} from "../ErrorHandler.js"; import {withErrorHandling, createValidationError} from "../ErrorHandler.js";
const log = createModuleLogger('ImageUtils'); const log = createModuleLogger('ImageUtils');
export function validateImageData(data) { export function validateImageData(data) {
@@ -114,7 +115,7 @@ export function applyMaskToImageData(imageData, maskData) {
}; };
} }
export const prepareImageForCanvas = withErrorHandling(function(inputImage) { export const prepareImageForCanvas = withErrorHandling(function (inputImage) {
log.info("Preparing image for canvas:", inputImage); log.info("Preparing image for canvas:", inputImage);
if (Array.isArray(inputImage)) { if (Array.isArray(inputImage)) {
@@ -122,7 +123,7 @@ export const prepareImageForCanvas = withErrorHandling(function(inputImage) {
} }
if (!inputImage || !inputImage.shape || !inputImage.data) { if (!inputImage || !inputImage.shape || !inputImage.data) {
throw createValidationError("Invalid input image format", { inputImage }); throw createValidationError("Invalid input image format", {inputImage});
} }
const shape = inputImage.shape; const shape = inputImage.shape;
@@ -161,7 +162,7 @@ export const prepareImageForCanvas = withErrorHandling(function(inputImage) {
* @param {HTMLImageElement|HTMLCanvasElement} image - Obraz do konwersji * @param {HTMLImageElement|HTMLCanvasElement} image - Obraz do konwersji
* @returns {Promise<Object>} Tensor z danymi obrazu * @returns {Promise<Object>} Tensor z danymi obrazu
*/ */
export const imageToTensor = withErrorHandling(async function(image) { export const imageToTensor = withErrorHandling(async function (image) {
if (!image) { if (!image) {
throw createValidationError("Image is required"); throw createValidationError("Image is required");
} }
@@ -197,9 +198,9 @@ export const imageToTensor = withErrorHandling(async function(image) {
* @param {Object} tensor - Tensor z danymi obrazu * @param {Object} tensor - Tensor z danymi obrazu
* @returns {Promise<HTMLImageElement>} Obraz HTML * @returns {Promise<HTMLImageElement>} Obraz HTML
*/ */
export const tensorToImage = withErrorHandling(async function(tensor) { export const tensorToImage = withErrorHandling(async function (tensor) {
if (!tensor || !tensor.data || !tensor.shape) { if (!tensor || !tensor.data || !tensor.shape) {
throw createValidationError("Invalid tensor format", { tensor }); throw createValidationError("Invalid tensor format", {tensor});
} }
const [, height, width, channels] = tensor.shape; const [, height, width, channels] = tensor.shape;
@@ -239,7 +240,7 @@ export const tensorToImage = withErrorHandling(async function(tensor) {
* @param {number} maxHeight - Maksymalna wysokość * @param {number} maxHeight - Maksymalna wysokość
* @returns {Promise<HTMLImageElement>} Przeskalowany obraz * @returns {Promise<HTMLImageElement>} Przeskalowany obraz
*/ */
export const resizeImage = withErrorHandling(async function(image, maxWidth, maxHeight) { export const resizeImage = withErrorHandling(async function (image, maxWidth, maxHeight) {
if (!image) { if (!image) {
throw createValidationError("Image is required"); throw createValidationError("Image is required");
} }
@@ -274,7 +275,7 @@ export const resizeImage = withErrorHandling(async function(image, maxWidth, max
* @param {number} size - Rozmiar miniatury (kwadrat) * @param {number} size - Rozmiar miniatury (kwadrat)
* @returns {Promise<HTMLImageElement>} Miniatura * @returns {Promise<HTMLImageElement>} Miniatura
*/ */
export const createThumbnail = withErrorHandling(async function(image, size = 128) { export const createThumbnail = withErrorHandling(async function (image, size = 128) {
return resizeImage(image, size, size); return resizeImage(image, size, size);
}, 'createThumbnail'); }, 'createThumbnail');
@@ -285,7 +286,7 @@ export const createThumbnail = withErrorHandling(async function(image, size = 12
* @param {number} quality - Jakość (0-1) dla formatów stratnych * @param {number} quality - Jakość (0-1) dla formatów stratnych
* @returns {string} Base64 string * @returns {string} Base64 string
*/ */
export const imageToBase64 = withErrorHandling(function(image, format = 'png', quality = 0.9) { export const imageToBase64 = withErrorHandling(function (image, format = 'png', quality = 0.9) {
if (!image) { if (!image) {
throw createValidationError("Image is required"); throw createValidationError("Image is required");
} }
@@ -307,7 +308,7 @@ export const imageToBase64 = withErrorHandling(function(image, format = 'png', q
* @param {string} base64 - Base64 string * @param {string} base64 - Base64 string
* @returns {Promise<HTMLImageElement>} Obraz * @returns {Promise<HTMLImageElement>} Obraz
*/ */
export const base64ToImage = withErrorHandling(function(base64) { export const base64ToImage = withErrorHandling(function (base64) {
if (!base64) { if (!base64) {
throw createValidationError("Base64 string is required"); throw createValidationError("Base64 string is required");
} }
@@ -371,7 +372,7 @@ export function createImageFromSource(source) {
* @param {string} color - Kolor tła (CSS color) * @param {string} color - Kolor tła (CSS color)
* @returns {Promise<HTMLImageElement>} Pusty obraz * @returns {Promise<HTMLImageElement>} Pusty obraz
*/ */
export const createEmptyImage = withErrorHandling(function(width, height, color = 'transparent') { export const createEmptyImage = withErrorHandling(function (width, height, color = 'transparent') {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');

View File

@@ -43,7 +43,7 @@ export function createAutoLogger(level = LogLevel.DEBUG) {
* @returns {Function} Opakowana funkcja * @returns {Function} Opakowana funkcja
*/ */
export function withErrorLogging(operation, log, operationName) { export function withErrorLogging(operation, log, operationName) {
return async function(...args) { return async function (...args) {
try { try {
log.debug(`Starting ${operationName}`); log.debug(`Starting ${operationName}`);
const result = await operation.apply(this, args); const result = await operation.apply(this, args);
@@ -62,10 +62,10 @@ export function withErrorLogging(operation, log, operationName) {
* @param {string} methodName - Nazwa metody * @param {string} methodName - Nazwa metody
*/ */
export function logMethod(log, methodName) { export function logMethod(log, methodName) {
return function(target, propertyKey, descriptor) { return function (target, propertyKey, descriptor) {
const originalMethod = descriptor.value; const originalMethod = descriptor.value;
descriptor.value = async function(...args) { descriptor.value = async function (...args) {
try { try {
log.debug(`${methodName || propertyKey} started`); log.debug(`${methodName || propertyKey} started`);
const result = await originalMethod.apply(this, args); const result = await originalMethod.apply(this, args);

View File

@@ -130,7 +130,6 @@ class WebSocketManager {
log.warn("WebSocket not open. Queuing message."); log.warn("WebSocket not open. Queuing message.");
this.messageQueue.push(message); this.messageQueue.push(message);
if (!this.isConnecting) { if (!this.isConnecting) {
this.connect(); this.connect();
@@ -147,7 +146,6 @@ class WebSocketManager {
log.debug(`Flushing ${this.messageQueue.length} queued messages.`); log.debug(`Flushing ${this.messageQueue.length} queued messages.`);
while (this.messageQueue.length > 0) { while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift(); const message = this.messageQueue.shift();
this.socket.send(message); this.socket.send(message);

View File

@@ -142,7 +142,6 @@ export function start_mask_editor_auto(canvasInstance) {
} }
canvasInstance.startMaskEditor(); canvasInstance.startMaskEditor();
} }