refactor: pick out logic into services
This commit is contained in:
+23
-77
@@ -1,9 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { createPanelFromText, updatePanelText } from "../stores/panelStore";
|
||||
import { uiStore, setLoading, setCurrentStep } from "../stores/uiStore";
|
||||
|
||||
import { exportService } from "../lib/services/exportService";
|
||||
import { uiStore } from "../stores/uiStore";
|
||||
import { imageService } from "../services/imageService";
|
||||
import { panelService } from "../services/panelService";
|
||||
import { exportService } from "../services/exportService";
|
||||
import type { Panel } from "../lib/types/panel";
|
||||
|
||||
import AppHeader from "../components/AppHeader.svelte";
|
||||
@@ -15,122 +15,68 @@
|
||||
let uploadedImage = $state<string | null>(null);
|
||||
let panels = $state<Panel[]>([]);
|
||||
let texts = $state<Array<{ id: string; text: string }>>([]);
|
||||
let errorMessage = $state<string | null>(null);
|
||||
let backgroundImage = $state<string | null>(null);
|
||||
|
||||
onMount(async () => {
|
||||
// Загружаем фоновое изображение по умолчанию
|
||||
try {
|
||||
const defaultBackground = "/backgrounds/b1.jpg";
|
||||
const response = await fetch(defaultBackground);
|
||||
if (!response.ok) throw new Error("Не удалось загрузить фоновое изображение");
|
||||
const blob = await response.blob();
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
backgroundImage = reader.result as string;
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
backgroundImage = await imageService.loadDefaultBackground();
|
||||
} catch (error) {
|
||||
console.error("Ошибка загрузки фонового изображения:", error);
|
||||
errorMessage = "Не удалось загрузить фоновое изображение по умолчанию";
|
||||
exportService.setErrorMessage("Не удалось загрузить фоновое изображение по умолчанию");
|
||||
}
|
||||
});
|
||||
|
||||
function handleImageUpload(image: string) {
|
||||
uploadedImage = image;
|
||||
errorMessage = null;
|
||||
setCurrentStep("crop");
|
||||
imageService.handleImageUpload(image);
|
||||
}
|
||||
|
||||
function handleUploadNewImage() {
|
||||
setCurrentStep("upload");
|
||||
imageService.handleUploadNewImage();
|
||||
}
|
||||
|
||||
function handleCropComplete(croppedImage: string) {
|
||||
backgroundImage = croppedImage;
|
||||
// Обновляем все панели с новым фоновым изображением
|
||||
panels = panels.map(panel => ({
|
||||
...panel,
|
||||
backgroundImage: croppedImage,
|
||||
updatedAt: new Date(),
|
||||
}));
|
||||
setCurrentStep("text");
|
||||
uploadedImage = null;
|
||||
imageService.handleCropComplete(croppedImage);
|
||||
panels = panelService.updatePanelsBackground(panels, croppedImage);
|
||||
panels = panelService.updatePanelsFromTexts(texts, panels, croppedImage);
|
||||
}
|
||||
|
||||
function handleCropCancel() {
|
||||
uploadedImage = null;
|
||||
setCurrentStep("text");
|
||||
imageService.handleCropCancel();
|
||||
}
|
||||
|
||||
function handleAddText(text: string) {
|
||||
// Проверяем, что текст не пустой и не дублируется
|
||||
if (!text.trim()) return;
|
||||
if (texts.some(t => t.text === text)) return;
|
||||
|
||||
texts = [...texts, { id: crypto.randomUUID(), text }];
|
||||
updatePanelsFromTexts();
|
||||
texts = panelService.addText(texts, text);
|
||||
panels = panelService.updatePanelsFromTexts(texts, panels, backgroundImage!);
|
||||
}
|
||||
|
||||
function handleUpdateText(id: string, newText: string) {
|
||||
// Проверяем, что текст не пустой и не дублируется
|
||||
if (!newText.trim()) return;
|
||||
if (texts.some(t => t.id !== id && t.text === newText)) return;
|
||||
|
||||
texts = texts.map(t => t.id === id ? { ...t, text: newText } : t);
|
||||
updatePanelsFromTexts();
|
||||
texts = panelService.updateText(texts, id, newText);
|
||||
panels = panelService.updatePanelsFromTexts(texts, panels, backgroundImage!);
|
||||
}
|
||||
|
||||
function handleDeleteText(id: string) {
|
||||
texts = texts.filter(t => t.id !== id);
|
||||
updatePanelsFromTexts();
|
||||
}
|
||||
|
||||
function updatePanelsFromTexts() {
|
||||
if (!backgroundImage) return;
|
||||
panels = texts.map(textItem => {
|
||||
const existingPanel = panels.find(p => p.texts[0]?.text === textItem.text);
|
||||
if (existingPanel) {
|
||||
return updatePanelText(existingPanel, textItem.text);
|
||||
}
|
||||
return createPanelFromText(backgroundImage!, textItem.text);
|
||||
});
|
||||
texts = panelService.deleteText(texts, id);
|
||||
panels = panelService.updatePanelsFromTexts(texts, panels, backgroundImage!);
|
||||
}
|
||||
|
||||
async function handleDownload(panel: Panel) {
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await exportService.exportPanel(panel);
|
||||
|
||||
if (!result.success) {
|
||||
errorMessage = result.error || "Ошибка экспорта панели";
|
||||
}
|
||||
} catch (error) {
|
||||
errorMessage = error instanceof Error ? error.message : "Ошибка экспорта панели";
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
await exportService.handleDownload(panel);
|
||||
}
|
||||
|
||||
async function handleDownloadAll() {
|
||||
try {
|
||||
setLoading(true);
|
||||
for (const panel of panels) {
|
||||
await exportService.exportPanel(panel);
|
||||
}
|
||||
} catch (error) {
|
||||
errorMessage = error instanceof Error ? error.message : "Ошибка экспорта панелей";
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
await exportService.handleDownloadAll(panels);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="app-container">
|
||||
<AppHeader onUploadNewImage={handleUploadNewImage} />
|
||||
|
||||
{#if errorMessage}
|
||||
{#if exportService.getErrorMessage()}
|
||||
<div class="error-message">
|
||||
{errorMessage}
|
||||
{exportService.getErrorMessage()}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { uiStore } from "../stores/uiStore";
|
||||
import { imageService } from "../services/imageService";
|
||||
import { panelService } from "../services/panelService";
|
||||
import { exportService } from "../services/exportService";
|
||||
import type { Panel } from "../lib/types/panel";
|
||||
|
||||
import AppHeader from "../components/AppHeader.svelte";
|
||||
import ImageManager from "../components/ImageManager.svelte";
|
||||
import TextSection from "../components/TextSection.svelte";
|
||||
import BackgroundPreview from "../components/BackgroundPreview.svelte";
|
||||
import PanelsList from "../components/PanelsList.svelte";
|
||||
|
||||
let uploadedImage = $state<string | null>(null);
|
||||
let panels = $state<Panel[]>([]);
|
||||
let texts = $state<Array<{ id: string; text: string }>>([]);
|
||||
let backgroundImage = $state<string | null>(null);
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
backgroundImage = await imageService.loadDefaultBackground();
|
||||
} catch (error) {
|
||||
exportService.setErrorMessage("Не удалось загрузить фоновое изображение по умолчанию");
|
||||
}
|
||||
});
|
||||
|
||||
function handleImageUpload(image: string) {
|
||||
uploadedImage = image;
|
||||
imageService.handleImageUpload(image);
|
||||
}
|
||||
|
||||
function handleUploadNewImage() {
|
||||
imageService.handleUploadNewImage();
|
||||
}
|
||||
|
||||
function handleCropComplete(croppedImage: string) {
|
||||
backgroundImage = croppedImage;
|
||||
uploadedImage = null;
|
||||
imageService.handleCropComplete(croppedImage);
|
||||
panels = panelService.updatePanelsBackground(panels, croppedImage);
|
||||
panels = panelService.updatePanelsFromTexts(texts, panels, croppedImage);
|
||||
}
|
||||
|
||||
function handleCropCancel() {
|
||||
uploadedImage = null;
|
||||
imageService.handleCropCancel();
|
||||
}
|
||||
|
||||
function handleAddText(text: string) {
|
||||
// Проверяем, что текст не пустой и не дублируется
|
||||
if (!text.trim()) return;
|
||||
if (texts.some(t => t.text === text)) return;
|
||||
|
||||
texts = [...texts, { id: crypto.randomUUID(), text }];
|
||||
updatePanelsFromTexts();
|
||||
}
|
||||
|
||||
function handleUpdateText(id: string, newText: string) {
|
||||
// Проверяем, что текст не пустой и не дублируется
|
||||
if (!newText.trim()) return;
|
||||
if (texts.some(t => t.id !== id && t.text === newText)) return;
|
||||
|
||||
texts = texts.map(t => t.id === id ? { ...t, text: newText } : t);
|
||||
updatePanelsFromTexts();
|
||||
}
|
||||
|
||||
function handleDeleteText(id: string) {
|
||||
texts = texts.filter(t => t.id !== id);
|
||||
updatePanelsFromTexts();
|
||||
}
|
||||
|
||||
function updatePanelsFromTexts() {
|
||||
if (!backgroundImage) return;
|
||||
panels = texts.map(textItem => {
|
||||
const existingPanel = panels.find(p => p.texts[0]?.text === textItem.text);
|
||||
if (existingPanel) {
|
||||
return updatePanelText(existingPanel, textItem.text);
|
||||
}
|
||||
return createPanelFromText(backgroundImage!, textItem.text);
|
||||
});
|
||||
}
|
||||
|
||||
async function handleDownload(panel: Panel) {
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await exportService.exportPanel(panel);
|
||||
|
||||
if (!result.success) {
|
||||
errorMessage = result.error || "Ошибка экспорта панели";
|
||||
}
|
||||
} catch (error) {
|
||||
errorMessage = error instanceof Error ? error.message : "Ошибка экспорта панели";
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDownloadAll() {
|
||||
try {
|
||||
setLoading(true);
|
||||
for (const panel of panels) {
|
||||
await exportService.exportPanel(panel);
|
||||
}
|
||||
} catch (error) {
|
||||
errorMessage = error instanceof Error ? error.message : "Ошибка экспорта панелей";
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="app-container">
|
||||
<AppHeader onUploadNewImage={handleUploadNewImage} />
|
||||
|
||||
{#if errorMessage}
|
||||
<div class="error-message">
|
||||
{errorMessage}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="app-content">
|
||||
<div class="main-section">
|
||||
<ImageManager
|
||||
currentStep={$uiStore.currentStep}
|
||||
uploadedImage={uploadedImage}
|
||||
onImageUpload={handleImageUpload}
|
||||
onCropComplete={handleCropComplete}
|
||||
onCropCancel={handleCropCancel}
|
||||
/>
|
||||
{#if $uiStore.currentStep === "text"}
|
||||
<TextSection
|
||||
texts={texts}
|
||||
onTextAdd={handleAddText}
|
||||
onTextUpdate={handleUpdateText}
|
||||
onTextDelete={handleDeleteText}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="sidebar">
|
||||
{#if $uiStore.currentStep === "text"}
|
||||
<BackgroundPreview
|
||||
backgroundImage={backgroundImage}
|
||||
onUploadNewImage={handleUploadNewImage}
|
||||
/>
|
||||
<PanelsList
|
||||
panels={panels}
|
||||
onDownload={handleDownload}
|
||||
onDownloadAll={handleDownloadAll}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.app-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.app-content {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.main-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
background: #ffebee;
|
||||
color: #c62828;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #ffcdd2;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.app-content {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
order: -1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { Panel } from "../lib/types/panel";
|
||||
import { exportService as exportPanelService } from "../lib/services/exportService";
|
||||
import { setLoading } from "../stores/uiStore";
|
||||
|
||||
export class ExportService {
|
||||
private static instance: ExportService;
|
||||
private errorMessage: string | null = null;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): ExportService {
|
||||
if (!ExportService.instance) {
|
||||
ExportService.instance = new ExportService();
|
||||
}
|
||||
return ExportService.instance;
|
||||
}
|
||||
|
||||
getErrorMessage(): string | null {
|
||||
return this.errorMessage;
|
||||
}
|
||||
|
||||
setErrorMessage(message: string | null): void {
|
||||
this.errorMessage = message;
|
||||
}
|
||||
|
||||
async handleDownload(panel: Panel): Promise<void> {
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await exportPanelService.exportPanel(panel);
|
||||
|
||||
if (!result.success) {
|
||||
this.errorMessage = result.error || "Ошибка экспорта панели";
|
||||
}
|
||||
} catch (error) {
|
||||
this.errorMessage = error instanceof Error ? error.message : "Ошибка экспорта панели";
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async handleDownloadAll(panels: Panel[]): Promise<void> {
|
||||
try {
|
||||
setLoading(true);
|
||||
for (const panel of panels) {
|
||||
await exportPanelService.exportPanel(panel);
|
||||
}
|
||||
} catch (error) {
|
||||
this.errorMessage = error instanceof Error ? error.message : "Ошибка экспорта панелей";
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const exportService = ExportService.getInstance();
|
||||
@@ -0,0 +1,45 @@
|
||||
import { setCurrentStep } from "../stores/uiStore";
|
||||
|
||||
export class ImageService {
|
||||
private static instance: ImageService;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): ImageService {
|
||||
if (!ImageService.instance) {
|
||||
ImageService.instance = new ImageService();
|
||||
}
|
||||
return ImageService.instance;
|
||||
}
|
||||
|
||||
async loadDefaultBackground(): Promise<string> {
|
||||
const defaultBackground = "/backgrounds/b1.jpg";
|
||||
const response = await fetch(defaultBackground);
|
||||
if (!response.ok) throw new Error("Не удалось загрузить фоновое изображение");
|
||||
const blob = await response.blob();
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result as string);
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
|
||||
handleImageUpload(image: string): void {
|
||||
setCurrentStep("crop");
|
||||
}
|
||||
|
||||
handleUploadNewImage(): void {
|
||||
setCurrentStep("upload");
|
||||
}
|
||||
|
||||
handleCropComplete(croppedImage: string): void {
|
||||
setCurrentStep("text");
|
||||
}
|
||||
|
||||
handleCropCancel(): void {
|
||||
setCurrentStep("text");
|
||||
}
|
||||
}
|
||||
|
||||
export const imageService = ImageService.getInstance();
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { Panel } from "../lib/types/panel";
|
||||
import { createPanelFromText, updatePanelText } from "../stores/panelStore";
|
||||
|
||||
export class PanelService {
|
||||
private static instance: PanelService;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): PanelService {
|
||||
if (!PanelService.instance) {
|
||||
PanelService.instance = new PanelService();
|
||||
}
|
||||
return PanelService.instance;
|
||||
}
|
||||
|
||||
validateText(text: string): boolean {
|
||||
return text.trim().length > 0;
|
||||
}
|
||||
|
||||
isDuplicateText(texts: Array<{ id: string; text: string }>, text: string, excludeId?: string): boolean {
|
||||
return texts.some(t => t.id !== excludeId && t.text === text);
|
||||
}
|
||||
|
||||
addText(texts: Array<{ id: string; text: string }>, text: string): Array<{ id: string; text: string }> {
|
||||
if (!this.validateText(text)) return texts;
|
||||
if (this.isDuplicateText(texts, text)) return texts;
|
||||
|
||||
return [...texts, { id: crypto.randomUUID(), text }];
|
||||
}
|
||||
|
||||
updateText(texts: Array<{ id: string; text: string }>, id: string, newText: string): Array<{ id: string; text: string }> {
|
||||
if (!this.validateText(newText)) return texts;
|
||||
if (this.isDuplicateText(texts, newText, id)) return texts;
|
||||
|
||||
return texts.map(t => t.id === id ? { ...t, text: newText } : t);
|
||||
}
|
||||
|
||||
deleteText(texts: Array<{ id: string; text: string }>, id: string): Array<{ id: string; text: string }> {
|
||||
return texts.filter(t => t.id !== id);
|
||||
}
|
||||
|
||||
updatePanelsFromTexts(texts: Array<{ id: string; text: string }>, panels: Panel[], backgroundImage: string): Panel[] {
|
||||
return texts.map(textItem => {
|
||||
const existingPanel = panels.find(p => p.texts[0]?.text === textItem.text);
|
||||
if (existingPanel) {
|
||||
return updatePanelText(existingPanel, textItem.text);
|
||||
}
|
||||
return createPanelFromText(backgroundImage, textItem.text);
|
||||
});
|
||||
}
|
||||
|
||||
updatePanelsBackground(panels: Panel[], newBackground: string): Panel[] {
|
||||
return panels.map(panel => ({
|
||||
...panel,
|
||||
backgroundImage: newBackground,
|
||||
updatedAt: new Date(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export const panelService = PanelService.getInstance();
|
||||
Reference in New Issue
Block a user