chore: remove unnecessary comments

This commit is contained in:
2026-02-04 23:52:00 +05:00
parent 49f427f3a0
commit dafc1bbfd2
13 changed files with 28 additions and 139 deletions
-2
View File
@@ -1,5 +1,3 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
-5
View File
@@ -28,7 +28,6 @@
});
function initializeCropper() {
// Remove verbose debug logging
if (!imageElement || !CropperJS) {
return;
}
@@ -52,7 +51,6 @@
throw new Error("Не удалось получить обрезанное изображение");
}
// Используем метод $toCanvas для получения HTMLCanvasElement
const canvas = await cropperCanvasElement.$toCanvas({
width: 320,
});
@@ -61,10 +59,8 @@
throw new Error("Не удалось получить canvas");
}
// Теперь canvas - это обычный HTMLCanvasElement
const croppedImage = canvas.toDataURL("image/png");
// Validate cropped image
const cropResult: ImageCropResult = {
success: true,
croppedImage,
@@ -171,7 +167,6 @@
background-color: #007bff;
}
/* Базовые стили для cropperjs */
:global(.cropper-container) {
direction: ltr;
font-size: 0;
-3
View File
@@ -24,7 +24,6 @@
errorMessage = undefined;
panels = panelStorage.getAllPanels();
// Если есть текущая панель в store, отмечаем её как выбранную
const currentPanel = $panelStore;
if (currentPanel) {
selectedPanelId = currentPanel.id;
@@ -47,12 +46,10 @@
if (result.success) {
panels = panels.filter((p) => p.id !== panelId);
// Если удалили выбранную панель, сбрасываем выбор
if (selectedPanelId === panelId) {
selectedPanelId = undefined;
}
// Уведомляем родительский компонент
onPanelDelete(panelId);
} else {
errorMessage = result.error || "Ошибка удаления панели";
+2 -30
View File
@@ -16,10 +16,8 @@
let konvaStage: KonvaStage | null = $state(null);
let stageComponent: any = $state(null);
// Get the Konva stage after component mounts
$effect(() => {
if (stageComponent) {
// According to svelte-konva docs, access the node property to get the underlying Konva Stage
konvaStage = stageComponent.node;
}
});
@@ -35,7 +33,6 @@
});
function loadImage(src: string) {
// Remove verbose logging - image data is too large for console
const img = document.createElement("img");
img.onload = () => {
backgroundImage = img;
@@ -47,50 +44,30 @@
}
function handleDownload() {
console.log("[PanelPreview] handleDownload called");
console.log("[PanelPreview] onDownload exists:", onDownload ? true : false);
console.log("[PanelPreview] konvaStage exists:", konvaStage ? true : false);
console.log("[PanelPreview] konvaStage value:", konvaStage);
console.log("[PanelPreview] stageComponent exists:", stageComponent ? true : false);
// Try different approaches to get the Konva stage for download
let stageToUse = konvaStage;
if (!stageToUse && stageComponent) {
console.log("[PanelPreview] konvaStage is null, trying to get stage from stageComponent");
// Try different properties that might contain the Konva stage
stageToUse = stageComponent.node || stageComponent.stage || stageComponent._stage || stageComponent;
// Check if this is actually a valid Konva stage
if (stageToUse && typeof stageToUse.toBlob === "function") {
console.log("[PanelPreview] Found valid Konva stage in stageComponent");
} else {
console.log("[PanelPreview] stageComponent itself might be the Konva stage");
// Maybe stageComponent IS the Konva stage - check if it has toBlob
if (typeof stageComponent.toBlob === "function") {
stageToUse = stageComponent;
console.log("[PanelPreview] ✅ stageComponent IS the Konva stage");
} else {
console.log("[PanelPreview] ❌ Could not find valid Konva stage");
}
}
}
if (onDownload && stageToUse) {
console.log("[PanelPreview] Calling onDownload with panel and stage");
onDownload(panel, stageToUse);
} else {
console.error("[PanelPreview] Cannot download - onDownload or valid stage is missing");
}
}
function getTextPosition(textItem: TextItem) {
const panelWidth = 320;
const paddingX = textItem.paddingX || 20; // Default padding
const paddingX = textItem.paddingX || 20;
const verticalOffset = textItem.verticalOffset || 0;
const centerY = panel.height / 2 + verticalOffset;
const textWidth = 300; // Width of the text area
const textWidth = 300;
let position;
switch (textItem.textAlign) {
@@ -98,12 +75,10 @@
position = { x: paddingX, y: centerY };
break;
case "right":
// For right alignment, position the right edge of text at panel edge minus padding
position = { x: panelWidth - textWidth - paddingX, y: centerY };
break;
case "center":
default:
// For center alignment, center the text area within the panel
position = { x: (panelWidth - textWidth) / 2, y: centerY };
break;
}
@@ -118,18 +93,15 @@
<Button variant="primary" size="sm" onclick={handleDownload}>Скачать</Button>
</div>
<div class="preview-sections">
<!-- Превью с текстом -->
<div class="preview-section">
<div class="canvas-container">
<Stage width={320} height={panel.height} bind:this={stageComponent}>
<!-- Background layer -->
<Layer>
{#if backgroundImage}
<Image image={backgroundImage} width={320} height={panel.height} />
{/if}
</Layer>
<!-- Text layer (renders above background) -->
<Layer>
{#if panel.text}
{@const textPosition = getTextPosition(panel.text)}
-4
View File
@@ -15,10 +15,8 @@
let newText = $state("");
let errorMessage = $state<string | undefined>(undefined);
// Use reactive store for text settings
let commonTextSettings = $derived($textSettingsStore);
// Список доступных шрифтов
const availableFonts = [
"Arial",
"Verdana",
@@ -89,7 +87,6 @@
{/if}
</div>
<!-- Список текстов -->
{#if texts.length > 0}
<div class="texts-list">
<h3>Созданные тексты ({texts.length})</h3>
@@ -112,7 +109,6 @@
</div>
{/if}
<!-- Общие настройки текста -->
<div class="common-settings-section">
<h3>Общие настройки текста</h3>
<p class="settings-note">Настройки применятся ко всем создаваемым панелям</p>
-1
View File
@@ -27,7 +27,6 @@
img.src = src;
}
// Вычисляем позицию текста на основе выравнивания и отступов
function getTextPosition() {
const panelWidth = 320;
const paddingX = textItem.paddingX || 0;
+1 -1
View File
@@ -1,6 +1,6 @@
import { ImageError } from "../types/errors";
export const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
export const MAX_FILE_SIZE = 10 * 1024 * 1024;
export const SUPPORTED_FORMATS = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/gif"];
export type ValidationResult =
+1 -31
View File
@@ -1,9 +1,8 @@
import type { Panel } from "../types/panel";
import { ImageError } from "../types/errors";
import { handleError, logError } from "./errorHandler";
const STORAGE_KEY = "twitch-panels";
const MAX_PANELS = 50; // Максимальное количество сохраненных панелей
const MAX_PANELS = 50;
export interface StorageResult {
success: boolean;
@@ -11,24 +10,17 @@ export interface StorageResult {
}
export class PanelStorage {
/**
* Сохраняет панель в localStorage
*/
savePanel(panel: Panel): StorageResult {
try {
const panels = this.getAllPanels();
// Проверяем, существует ли панель с таким ID
const existingIndex = panels.findIndex((p) => p.id === panel.id);
if (existingIndex >= 0) {
// Обновляем существующую панель
panels[existingIndex] = panel;
} else {
// Добавляем новую панель в начало списка
panels.unshift(panel);
// Проверяем лимит количества панелей
if (panels.length > MAX_PANELS) {
panels.length = MAX_PANELS;
}
@@ -48,9 +40,6 @@ export class PanelStorage {
}
}
/**
* Загружает все панели из localStorage
*/
getAllPanels(): Panel[] {
try {
const data = localStorage.getItem(STORAGE_KEY);
@@ -60,7 +49,6 @@ export class PanelStorage {
const panels: Panel[] = JSON.parse(data);
// Валидация загруженных панелей
return panels.filter((panel) => this.validatePanel(panel));
} catch (error) {
logError(error, "Failed to load panels");
@@ -68,9 +56,6 @@ export class PanelStorage {
}
}
/**
* Загружает панель по ID
*/
getPanelById(id: string): Panel | undefined {
try {
const panels = this.getAllPanels();
@@ -81,9 +66,6 @@ export class PanelStorage {
}
}
/**
* Удаляет панель по ID
*/
deletePanel(id: string): StorageResult {
try {
const panels = this.getAllPanels();
@@ -103,9 +85,6 @@ export class PanelStorage {
}
}
/**
* Очищает все сохраненные панели
*/
clearAll(): StorageResult {
try {
localStorage.removeItem(STORAGE_KEY);
@@ -122,9 +101,6 @@ export class PanelStorage {
}
}
/**
* Валидирует панель
*/
private validatePanel(panel: any): panel is Panel {
return (
typeof panel === "object" &&
@@ -139,16 +115,10 @@ export class PanelStorage {
);
}
/**
* Получает количество сохраненных панелей
*/
getPanelCount(): number {
return this.getAllPanels().length;
}
/**
* Проверяет, есть ли место для новой панели
*/
hasSpaceForNewPanel(): boolean {
return this.getPanelCount() < MAX_PANELS;
}
-9
View File
@@ -14,26 +14,20 @@
let texts = $state<Array<{ id: string; text: string }>>([]);
let backgroundImage = $state<string | undefined>(undefined);
// Create a derived store for text settings to avoid cyclic dependencies
let textSettings = $derived($textSettingsStore);
// Listen for text settings changes and update all panels
let previousSettings = $state<string>("");
$effect(() => {
// Only depend on the derived settings value
const currentSettings = textSettings;
const settingsString = JSON.stringify(currentSettings);
// Only update if settings actually changed
if (settingsString !== previousSettings) {
// Update panels with new settings
const updatedPanels = panels.map((panel) => ({
...panel,
text: { ...panel.text, ...currentSettings },
}));
// Use a microtask to avoid synchronous update issues
Promise.resolve().then(() => {
if (panels.length > 0) {
panels = updatedPanels;
@@ -45,14 +39,12 @@
});
onMount(async () => {
// Initialize with default texts for common Twitch panels
const defaultTexts = [
{ id: crypto.randomUUID(), text: "About" },
{ id: crypto.randomUUID(), text: "Links" },
];
texts = defaultTexts;
// Load background image
try {
const loadedBackground = await imageService.loadDefaultBackground();
backgroundImage = loadedBackground;
@@ -61,7 +53,6 @@
exportService.setErrorMessage("Не удалось загрузить фоновое изображение по умолчанию");
}
// Create panels from texts (with or without background)
const initialPanels = panelService.updatePanelsFromTexts(texts, [], backgroundImage || "");
panels = initialPanels;
});
+1 -18
View File
@@ -11,16 +11,12 @@ export interface ExportResult {
}
export class ExportService {
/**
* Экспортирует панель в изображение и сохраняет её
*/
async exportPanel(panel: Panel, konvaStage: Stage, filename?: string): Promise<ExportResult> {
try {
if (!konvaStage) {
throw new ImageError("Konva Stage не передан для экспорта");
}
// Используем toBlob метод Konva Stage напрямую
const blob = await this.exportKonvaStageToBlob(konvaStage);
if (!blob) {
@@ -42,9 +38,6 @@ export class ExportService {
}
}
/**
* Экспортирует Konva Stage в Blob используя встроенный метод toBlob
*/
private async exportKonvaStageToBlob(konvaStage: Stage): Promise<Blob | null> {
if (!konvaStage || typeof konvaStage.toBlob !== "function") {
throw new ImageError("Konva Stage не найден или не поддерживает toBlob");
@@ -65,10 +58,8 @@ export class ExportService {
/**
* Экспортирует несколько панелей в ZIP архив
* (будет реализовано позже для batch download)
*/
async exportPanels(panels: Panel[]): Promise<ExportResult> {
// TODO: Реализовать пакетный экспорт с использованием JSZip
return {
success: false,
error: "Пакетный экспорт еще не реализован",
@@ -77,7 +68,6 @@ export class ExportService {
/**
* Обработчик для скачивания одной панели
* Этот метод должен быть вызван из компонента PanelPreview с передачей konvaStage
*/
async handleDownload(panel: Panel, konvaStage: Stage): Promise<void> {
const result = await this.exportPanel(panel, konvaStage);
@@ -96,18 +86,11 @@ export class ExportService {
}
}
/**
* Получить сообщение об ошибке
*/
getErrorMessage(): string | null {
return null; // Реализовать при необходимости
return null;
}
/**
* Установить сообщение об ошибке
*/
setErrorMessage(message: string): void {
// Реализовать при необходимости
console.error("ExportService error:", message);
}
}
-4
View File
@@ -19,7 +19,6 @@ export class ImageService {
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
// TODO: look for a better handle non string
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(blob);
@@ -43,7 +42,6 @@ export class ImageService {
}
async handleFileUpload(file: File): Promise<any> {
// Convert file to base64
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () =>
@@ -69,7 +67,6 @@ export class ImageService {
};
}
// Find image item
let imageItem: DataTransferItem | undefined = undefined;
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
@@ -85,7 +82,6 @@ export class ImageService {
};
}
// Get file from clipboard item
const file = imageItem.getAsFile();
if (!file) {
return {
-3
View File
@@ -4,7 +4,6 @@ import { type Panel, type TextItem } from "../lib/types/panel";
export const panelStore: Writable<Panel | undefined> = writable(undefined);
// Store for common text settings that should apply to all texts
export const textSettingsStore = writable<Partial<TextItem>>({
fontSize: 18,
fontFamily: "Arial",
@@ -18,8 +17,6 @@ export const updateAllTextSettings = (settings: Partial<TextItem>) => {
textSettingsStore.update((current) => ({ ...current, ...settings }));
};
// Panel creation should go through panelService.updatePanelsFromTexts()
// These functions are kept for backward compatibility but should be avoided
export const createEmptyPanel = (height: number = 100): Panel => {
const defaultText: TextItem = {
id: uuidv4(),
-5
View File
@@ -14,9 +14,4 @@
"exactOptionalPropertyTypes": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// To make changes to top-level options such as include and exclude, we recommend extending
// the generated config; see https://svelte.dev/docs/kit/configuration#typescript
}