Подключение кнопки Печать к бэкенду + временный прокси через vite.config.js
This commit is contained in:
@ -1,303 +1,372 @@
|
|||||||
<script>
|
<script>
|
||||||
import { onDestroy, tick } from 'svelte';
|
import { onDestroy, tick } from 'svelte';
|
||||||
import SelectionPage from './preview/SelectionPage.svelte';
|
import SelectionPage from './preview/SelectionPage.svelte';
|
||||||
import PreviewPage from './preview/PreviewPage.svelte';
|
import PreviewPage from './preview/PreviewPage.svelte';
|
||||||
|
|
||||||
let { onBack = () => {}, onPrint = () => {} } = $props();
|
let { onBack = () => {} } = $props();
|
||||||
|
|
||||||
// ── Модель данных ──
|
// ── Модель данных ──
|
||||||
/** @typedef {{ id: number, file: File, previewUrl: string | null, fileType: 'image' | 'pdf' | 'other', expanded: boolean, format: 'A4' | 'A5', colorMode: 'bw' | 'color', qualityIndex: number, copies: number, pageRange: string, totalPages: number, selectedPages: Set<number>, pdfDoc: any }} FileEntry */
|
/** @typedef {{ id: number, file: File, previewUrl: string | null, fileType: 'image' | 'pdf' | 'other', expanded: boolean, format: 'A4' | 'A5', colorMode: 'bw' | 'color', qualityIndex: number, copies: number, pageRange: string, totalPages: number, selectedPages: Set<number>, pdfDoc: any }} FileEntry */
|
||||||
/** @type {FileEntry[]} */
|
/** @type {FileEntry[]} */
|
||||||
let files = $state([]);
|
let files = $state([]);
|
||||||
|
|
||||||
// ── Общие состояния оверлея ──
|
// ── Общие состояния оверлея ──
|
||||||
/** @type {FileEntry | null} */
|
/** @type {FileEntry | null} */
|
||||||
let activeFile = $state(null);
|
let activeFile = $state(null);
|
||||||
/** Режим просмотра: 'gallery' (выбор страниц) или 'preview' (чтение) */
|
/** Режим просмотра: 'gallery' (выбор страниц) или 'preview' (чтение) */
|
||||||
let viewMode = $state(/** @type {'gallery' | 'preview'} */ ('gallery'));
|
let viewMode = $state(/** @type {'gallery' | 'preview'} */ ('gallery'));
|
||||||
|
|
||||||
// ── Данные для галереи (выбор страниц) ──
|
// ── Данные для галереи (выбор страниц) ──
|
||||||
let galleryThumbnails = $state([]);
|
let galleryThumbnails = $state([]);
|
||||||
let galleryLoading = $state(false);
|
let galleryLoading = $state(false);
|
||||||
|
|
||||||
// ── Данные для превью (чтение) ──
|
// ── Данные для превью (чтение) ──
|
||||||
/** Кэшированные URL больших страниц для превью */
|
/** Кэшированные URL больших страниц для превью */
|
||||||
let previewPagesCache = $state({});
|
let previewPagesCache = $state({});
|
||||||
let isPreviewRendering = $state(false);
|
let isPreviewRendering = $state(false);
|
||||||
|
|
||||||
let uid = 0;
|
// ── Состояние кнопки печати ──
|
||||||
|
let isPrinting = $state(false);
|
||||||
|
|
||||||
const qualities = [
|
let uid = 0;
|
||||||
{ id: 'low', label: 'Эконом' },
|
const PRICE_PER_PAGE = 9;
|
||||||
{ id: 'medium', label: 'Стандарт' },
|
|
||||||
{ id: 'high', label: 'Максимум' }
|
|
||||||
];
|
|
||||||
const formats = ['A4', 'A5'];
|
|
||||||
const colorModes = [
|
|
||||||
{ id: 'bw', label: 'Чб' },
|
|
||||||
{ id: 'color', label: 'Цвет' }
|
|
||||||
];
|
|
||||||
|
|
||||||
// ── PDF.js Core ──
|
const qualities = [
|
||||||
async function loadPdfDocument(entry) {
|
{ id: 'low', label: 'Эконом' },
|
||||||
if (entry.pdfDoc) return entry.pdfDoc;
|
{ id: 'medium', label: 'Стандарт' },
|
||||||
try {
|
{ id: 'high', label: 'Максимум' }
|
||||||
const pdfjsLib = await import('https://mozilla.github.io/pdf.js/build/pdf.mjs');
|
];
|
||||||
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.mjs';
|
const formats = ['A4', 'A5'];
|
||||||
|
const colorModes = [
|
||||||
|
{ id: 'bw', label: 'Чб' },
|
||||||
|
{ id: 'color', label: 'Цвет' }
|
||||||
|
];
|
||||||
|
|
||||||
const arrayBuffer = await entry.file.arrayBuffer();
|
// ── Вспомогательная функция для реактивного обновления ──
|
||||||
const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });
|
function updateFile(id, changes) {
|
||||||
const pdf = await loadingTask.promise;
|
files = files.map(f => f.id === id ? { ...f, ...changes } : f);
|
||||||
|
if (activeFile && activeFile.id === id) {
|
||||||
entry.pdfDoc = pdf;
|
activeFile = files.find(f => f.id === id);
|
||||||
entry.totalPages = pdf.numPages;
|
|
||||||
// Инициализируем выбранные страницы только если они еще не заданы
|
|
||||||
if (!entry.selectedPages || entry.selectedPages.size === 0) {
|
|
||||||
entry.selectedPages = new Set(Array.from({ length: pdf.numPages }, (_, i) => i + 1));
|
|
||||||
}
|
}
|
||||||
return pdf;
|
|
||||||
} catch (err) {
|
|
||||||
console.error('PDF load error:', err);
|
|
||||||
entry.totalPages = 0;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function renderPageToImage(pdfDoc, pageNum, scale = 1.0) {
|
|
||||||
const page = await pdfDoc.getPage(pageNum);
|
|
||||||
const viewport = page.getViewport({ scale });
|
|
||||||
const canvas = document.createElement('canvas');
|
|
||||||
const context = canvas.getContext('2d');
|
|
||||||
const outputScale = window.devicePixelRatio || 1;
|
|
||||||
|
|
||||||
canvas.width = Math.floor(viewport.width * outputScale);
|
|
||||||
canvas.height = Math.floor(viewport.height * outputScale);
|
|
||||||
canvas.style.width = `${Math.floor(viewport.width)}px`;
|
|
||||||
canvas.style.height = `${Math.floor(viewport.height)}px`;
|
|
||||||
|
|
||||||
const transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : undefined;
|
|
||||||
|
|
||||||
await page.render({
|
|
||||||
canvasContext: context,
|
|
||||||
viewport,
|
|
||||||
transform
|
|
||||||
}).promise;
|
|
||||||
|
|
||||||
return canvas.toDataURL('image/jpeg', 0.85);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Логика Галереи ──
|
|
||||||
async function openPageGallery(entry) {
|
|
||||||
activeFile = entry;
|
|
||||||
viewMode = 'gallery';
|
|
||||||
galleryThumbnails = [];
|
|
||||||
galleryLoading = true;
|
|
||||||
previewPagesCache = {};
|
|
||||||
|
|
||||||
await tick();
|
|
||||||
|
|
||||||
// Используем уже загруженный документ или загружаем при необходимости
|
|
||||||
if (!entry.pdfDoc) await loadPdfDocument(entry);
|
|
||||||
|
|
||||||
if (!entry.pdfDoc || entry.totalPages === 0) {
|
|
||||||
galleryLoading = false;
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const thumbs = [];
|
// ── PDF.js Core ──
|
||||||
for (let i = 1; i <= entry.totalPages; i++) {
|
async function loadPdfDocument(entry) {
|
||||||
|
if (entry.pdfDoc) return entry.pdfDoc;
|
||||||
try {
|
try {
|
||||||
const url = await renderPageToImage(entry.pdfDoc, i, 0.4);
|
const pdfjsLib = await import('https://mozilla.github.io/pdf.js/build/pdf.mjs');
|
||||||
thumbs.push(url);
|
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.mjs';
|
||||||
galleryThumbnails = [...thumbs];
|
const arrayBuffer = await entry.file.arrayBuffer();
|
||||||
|
const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });
|
||||||
|
const pdf = await loadingTask.promise;
|
||||||
|
|
||||||
|
entry.pdfDoc = pdf;
|
||||||
|
|
||||||
|
const numPages = pdf.numPages;
|
||||||
|
const allPages = new Set(Array.from({ length: numPages }, (_, i) => i + 1));
|
||||||
|
|
||||||
|
updateFile(entry.id, {
|
||||||
|
pdfDoc: pdf,
|
||||||
|
totalPages: numPages,
|
||||||
|
selectedPages: allPages
|
||||||
|
});
|
||||||
|
|
||||||
|
return pdf;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
thumbs.push('');
|
console.error('PDF load error:', err);
|
||||||
galleryThumbnails = [...thumbs];
|
updateFile(entry.id, { totalPages: 0 });
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
galleryLoading = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Логика Превью ──
|
async function renderPageToImage(pdfDoc, pageNum, scale = 1.0) {
|
||||||
async function openPreview(entry) {
|
const page = await pdfDoc.getPage(pageNum);
|
||||||
activeFile = entry;
|
const viewport = page.getViewport({ scale });
|
||||||
viewMode = 'preview';
|
const canvas = document.createElement('canvas');
|
||||||
previewPagesCache = {};
|
const context = canvas.getContext('2d');
|
||||||
galleryThumbnails = [];
|
const outputScale = window.devicePixelRatio || 1;
|
||||||
|
canvas.width = Math.floor(viewport.width * outputScale);
|
||||||
|
canvas.height = Math.floor(viewport.height * outputScale);
|
||||||
|
canvas.style.width = `${Math.floor(viewport.width)}px`;
|
||||||
|
canvas.style.height = `${Math.floor(viewport.height)}px`;
|
||||||
|
const transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : undefined;
|
||||||
|
await page.render({
|
||||||
|
canvasContext: context,
|
||||||
|
viewport,
|
||||||
|
transform
|
||||||
|
}).promise;
|
||||||
|
return canvas.toDataURL('image/jpeg', 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
await tick();
|
// ── Логика Галереи ──
|
||||||
|
async function openPageGallery(entry) {
|
||||||
|
activeFile = entry;
|
||||||
|
viewMode = 'gallery';
|
||||||
|
galleryThumbnails = [];
|
||||||
|
galleryLoading = true;
|
||||||
|
previewPagesCache = {};
|
||||||
|
await tick();
|
||||||
|
|
||||||
if (entry.fileType === 'pdf') {
|
let pdfDoc = entry.pdfDoc;
|
||||||
// Документ должен быть уже загружен при добавлении файла,
|
if (!pdfDoc) {
|
||||||
// но на всякий случай проверяем
|
pdfDoc = await loadPdfDocument(entry);
|
||||||
if (!entry.pdfDoc) await loadPdfDocument(entry);
|
|
||||||
|
|
||||||
// Берем totalPages из entry, которое было получено при добавлении файла
|
|
||||||
if (entry.totalPages > 0) {
|
|
||||||
preloadPreviewPages(entry, 1, 5);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function preloadPreviewPages(entry, startPage, count, direction = 'forward') {
|
if (!pdfDoc || entry.totalPages === 0) {
|
||||||
if (!entry.pdfDoc || isPreviewRendering) return;
|
galleryLoading = false;
|
||||||
isPreviewRendering = true;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let pagesToLoad = [];
|
const thumbs = [];
|
||||||
if (direction === 'around') {
|
for (let i = 1; i <= entry.totalPages; i++) {
|
||||||
const half = Math.floor(count / 2);
|
|
||||||
const from = Math.max(1, startPage - half);
|
|
||||||
const to = Math.min(entry.totalPages, startPage + half);
|
|
||||||
for(let i = from; i <= to; i++) pagesToLoad.push(i);
|
|
||||||
} else {
|
|
||||||
const endPage = Math.min(startPage + count - 1, entry.totalPages);
|
|
||||||
for (let i = startPage; i <= endPage; i++) pagesToLoad.push(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
pagesToLoad = pagesToLoad.filter(p => !previewPagesCache[p]);
|
|
||||||
|
|
||||||
if (pagesToLoad.length > 0) {
|
|
||||||
const newCacheEntries = {};
|
|
||||||
for (const pageNum of pagesToLoad) {
|
|
||||||
try {
|
try {
|
||||||
const url = await renderPageToImage(entry.pdfDoc, pageNum, 1.5);
|
const url = await renderPageToImage(pdfDoc, i, 0.4);
|
||||||
newCacheEntries[pageNum] = url;
|
thumbs.push(url);
|
||||||
} catch (e) {
|
galleryThumbnails = [...thumbs];
|
||||||
console.error(`Failed to render preview page ${pageNum}`, e);
|
} catch (err) {
|
||||||
|
thumbs.push('');
|
||||||
|
galleryThumbnails = [...thumbs];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Object.keys(newCacheEntries).length > 0) {
|
galleryLoading = false;
|
||||||
previewPagesCache = { ...previewPagesCache, ...newCacheEntries };
|
}
|
||||||
|
|
||||||
|
// ── Логика Превью ──
|
||||||
|
async function openPreview(entry) {
|
||||||
|
activeFile = entry;
|
||||||
|
viewMode = 'preview';
|
||||||
|
previewPagesCache = {};
|
||||||
|
galleryThumbnails = [];
|
||||||
|
await tick();
|
||||||
|
if (entry.fileType === 'pdf') {
|
||||||
|
let pdfDoc = entry.pdfDoc;
|
||||||
|
if (!pdfDoc) pdfDoc = await loadPdfDocument(entry);
|
||||||
|
|
||||||
|
if (entry.totalPages > 0) {
|
||||||
|
preloadPreviewPages(entry, 1, 5);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
isPreviewRendering = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function handlePreviewRequestPages(start, count, direction) {
|
async function preloadPreviewPages(entry, startPage, count, direction = 'forward') {
|
||||||
if (activeFile) preloadPreviewPages(activeFile, start, count, direction);
|
const currentFile = files.find(f => f.id === entry.id);
|
||||||
}
|
const pdfDoc = currentFile ? currentFile.pdfDoc : entry.pdfDoc;
|
||||||
|
|
||||||
// ── Общие функции закрытия ──
|
if (!pdfDoc || isPreviewRendering) return;
|
||||||
function closeOverlay() {
|
isPreviewRendering = true;
|
||||||
activeFile = null;
|
|
||||||
galleryThumbnails = [];
|
|
||||||
previewPagesCache = {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Управление выбором страниц ──
|
let pagesToLoad = [];
|
||||||
function togglePageSelection(pageNum) {
|
if (direction === 'around') {
|
||||||
if (!activeFile?.selectedPages) return;
|
const half = Math.floor(count / 2);
|
||||||
const newSet = new Set(activeFile.selectedPages);
|
const from = Math.max(1, startPage - half);
|
||||||
if (newSet.has(pageNum)) {
|
const to = Math.min(entry.totalPages, startPage + half);
|
||||||
if (newSet.size > 1) newSet.delete(pageNum);
|
for(let i = from; i <= to; i++) pagesToLoad.push(i);
|
||||||
} else {
|
} else {
|
||||||
newSet.add(pageNum);
|
const endPage = Math.min(startPage + count - 1, entry.totalPages);
|
||||||
|
for (let i = startPage; i <= endPage; i++) pagesToLoad.push(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
pagesToLoad = pagesToLoad.filter(p => !previewPagesCache[p]);
|
||||||
|
|
||||||
|
if (pagesToLoad.length > 0) {
|
||||||
|
const newCacheEntries = {};
|
||||||
|
for (const pageNum of pagesToLoad) {
|
||||||
|
try {
|
||||||
|
const url = await renderPageToImage(pdfDoc, pageNum, 1.5);
|
||||||
|
newCacheEntries[pageNum] = url;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`Failed to render preview page ${pageNum}`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Object.keys(newCacheEntries).length > 0) {
|
||||||
|
previewPagesCache = { ...previewPagesCache, ...newCacheEntries };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
isPreviewRendering = false;
|
||||||
}
|
}
|
||||||
activeFile.selectedPages = newSet;
|
|
||||||
}
|
|
||||||
|
|
||||||
function selectAllPages() {
|
function handlePreviewRequestPages(start, count, direction) {
|
||||||
if (!activeFile?.totalPages) return;
|
if (activeFile) preloadPreviewPages(activeFile, start, count, direction);
|
||||||
activeFile.selectedPages = new Set(Array.from({ length: activeFile.totalPages }, (_, i) => i + 1));
|
}
|
||||||
}
|
|
||||||
|
|
||||||
function deselectAllPages() {
|
// ── Общие функции закрытия ──
|
||||||
if (!activeFile) return;
|
function closeOverlay() {
|
||||||
activeFile.selectedPages = new Set([1]);
|
activeFile = null;
|
||||||
}
|
galleryThumbnails = [];
|
||||||
|
previewPagesCache = {};
|
||||||
|
}
|
||||||
|
|
||||||
function pagesLabel(entry) {
|
// ── Управление выбором страниц ──
|
||||||
if (!entry.totalPages || entry.totalPages === 0) return 'Все';
|
function togglePageSelection(pageNum) {
|
||||||
if (!entry.selectedPages || entry.selectedPages.size === 0) return 'Все';
|
if (!activeFile?.selectedPages) return;
|
||||||
if (entry.selectedPages.size === entry.totalPages) return 'Все';
|
const newSet = new Set(activeFile.selectedPages);
|
||||||
if (entry.selectedPages.size === 1) return `стр. ${[...entry.selectedPages][0]}`;
|
if (newSet.has(pageNum)) {
|
||||||
return `${entry.selectedPages.size} из ${entry.totalPages}`;
|
if (newSet.size > 1) newSet.delete(pageNum);
|
||||||
}
|
} else {
|
||||||
|
newSet.add(pageNum);
|
||||||
|
}
|
||||||
|
updateFile(activeFile.id, { selectedPages: newSet });
|
||||||
|
}
|
||||||
|
|
||||||
// ── Файловые операции ──
|
function selectAllPages() {
|
||||||
let fileInput;
|
if (!activeFile?.totalPages) return;
|
||||||
|
const allPages = new Set(Array.from({ length: activeFile.totalPages }, (_, i) => i + 1));
|
||||||
|
updateFile(activeFile.id, { selectedPages: allPages });
|
||||||
|
}
|
||||||
|
|
||||||
function detectFileType(file) {
|
function deselectAllPages() {
|
||||||
if (!file) return 'other';
|
if (!activeFile) return;
|
||||||
if (file.type.startsWith('image/')) return 'image';
|
updateFile(activeFile.id, { selectedPages: new Set([1]) });
|
||||||
if (file.type === 'application/pdf') return 'pdf';
|
}
|
||||||
return 'other';
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleFileSelect(event) {
|
function pagesLabel(entry) {
|
||||||
const input = /** @type {HTMLInputElement} */(event.target);
|
if (!entry.totalPages || entry.totalPages === 0) return '...';
|
||||||
const chosen = input.files;
|
if (!entry.selectedPages || entry.selectedPages.size === 0) return 'Нет';
|
||||||
if (!chosen || chosen.length === 0) return;
|
if (entry.selectedPages.size === entry.totalPages) return 'Все';
|
||||||
|
if (entry.selectedPages.size === 1) return `стр. ${[...entry.selectedPages][0]}`;
|
||||||
|
return `${entry.selectedPages.size} из ${entry.totalPages}`;
|
||||||
|
}
|
||||||
|
|
||||||
for (let i = 0; i < chosen.length; i++) {
|
// ── Файловые операции ──
|
||||||
const fType = detectFileType(chosen[i]);
|
let fileInput;
|
||||||
const entry = {
|
|
||||||
id: ++uid,
|
|
||||||
file: chosen[i],
|
|
||||||
previewUrl: URL.createObjectURL(chosen[i]),
|
|
||||||
fileType: fType,
|
|
||||||
expanded: false,
|
|
||||||
format: 'A4',
|
|
||||||
colorMode: 'bw',
|
|
||||||
qualityIndex: 1,
|
|
||||||
copies: 1,
|
|
||||||
pageRange: 'all',
|
|
||||||
totalPages: fType === 'image' ? 1 : 0,
|
|
||||||
selectedPages: fType === 'image' ? new Set([1]) : new Set(),
|
|
||||||
pdfDoc: null,
|
|
||||||
};
|
|
||||||
|
|
||||||
files.push(entry);
|
function detectFileType(file) {
|
||||||
|
if (!file) return 'other';
|
||||||
|
if (file.type.startsWith('image/')) return 'image';
|
||||||
|
if (file.type === 'application/pdf') return 'pdf';
|
||||||
|
return 'other';
|
||||||
|
}
|
||||||
|
|
||||||
// ВАЖНО: Загружаем PDF сразу при добавлении, чтобы сохранить totalPages
|
async function handleFileSelect(event) {
|
||||||
if (fType === 'pdf') {
|
const input = /** @type {HTMLInputElement} */(event.target);
|
||||||
loadPdfDocument(entry);
|
const chosen = input.files;
|
||||||
|
if (!chosen || chosen.length === 0) return;
|
||||||
|
|
||||||
|
const newFiles = [];
|
||||||
|
for (let i = 0; i < chosen.length; i++) {
|
||||||
|
const fType = detectFileType(chosen[i]);
|
||||||
|
const entry = {
|
||||||
|
id: ++uid,
|
||||||
|
file: chosen[i],
|
||||||
|
previewUrl: URL.createObjectURL(chosen[i]),
|
||||||
|
fileType: fType,
|
||||||
|
expanded: false,
|
||||||
|
format: 'A4',
|
||||||
|
colorMode: 'bw',
|
||||||
|
qualityIndex: 1,
|
||||||
|
copies: 1,
|
||||||
|
pageRange: 'all',
|
||||||
|
totalPages: fType === 'image' ? 1 : 0,
|
||||||
|
selectedPages: fType === 'image' ? new Set([1]) : new Set(),
|
||||||
|
pdfDoc: null,
|
||||||
|
};
|
||||||
|
newFiles.push(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
files = [...files, ...newFiles];
|
||||||
|
|
||||||
|
for (const entry of newFiles) {
|
||||||
|
if (entry.fileType === 'pdf') {
|
||||||
|
loadPdfDocument(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
input.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function triggerFileInput(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
fileInput.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleExpanded(file) {
|
||||||
|
updateFile(file.id, { expanded: !file.expanded });
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeFile(file) {
|
||||||
|
if (file.previewUrl) URL.revokeObjectURL(file.previewUrl);
|
||||||
|
files = files.filter((f) => f.id !== file.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Опции печати ──
|
||||||
|
function toggleFormat(file, f) { updateFile(file.id, { format: f }); }
|
||||||
|
function toggleColor(file, c) { updateFile(file.id, { colorMode: c.id }); }
|
||||||
|
function incrementCopies(file) { updateFile(file.id, { copies: file.copies + 1 }); }
|
||||||
|
function decrementCopies(file) { if (file.copies > 1) updateFile(file.id, { copies: file.copies - 1 }); }
|
||||||
|
function qualityFillFor(file) { return Math.round((file.qualityIndex / (qualities.length - 1)) * 100); }
|
||||||
|
function updateQuality(file, val) { updateFile(file.id, { qualityIndex: val }); }
|
||||||
|
|
||||||
|
// ── Расчет цены ──
|
||||||
|
const totalPrice = $derived(() => {
|
||||||
|
let sum = 0;
|
||||||
|
for (const f of files) {
|
||||||
|
const pagesCount = f.selectedPages ? f.selectedPages.size : 0;
|
||||||
|
sum += pagesCount * f.copies;
|
||||||
|
}
|
||||||
|
return sum * PRICE_PER_PAGE;
|
||||||
|
});
|
||||||
|
|
||||||
|
const extraCopies = $derived(files.reduce((sum, f) => sum + (f.copies - 1), 0));
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
files.forEach((f) => { if (f.previewUrl) URL.revokeObjectURL(f.previewUrl); });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Плюрализация ──
|
||||||
|
function pluralize(n, forms) {
|
||||||
|
const mod10 = n % 10, mod100 = n % 100;
|
||||||
|
if (mod10 === 1 && mod100 !== 11) return forms[0];
|
||||||
|
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 > 14)) return forms[1];
|
||||||
|
return forms[2];
|
||||||
|
}
|
||||||
|
const plFiles = (n) => pluralize(n, ['файл', 'файла', 'файлов']);
|
||||||
|
const plCopies = (n) => pluralize(n, ['копия', 'копии', 'копий']);
|
||||||
|
|
||||||
|
function handlePagesClick(file) {
|
||||||
|
if (file.fileType === 'pdf') openPageGallery(file);
|
||||||
|
else openPreview(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── НОВАЯ ФУНКЦИЯ: Отправка на сервер ──
|
||||||
|
async function submitPrint() {
|
||||||
|
if (files.length === 0 || isPrinting) return;
|
||||||
|
|
||||||
|
isPrinting = true;
|
||||||
|
const formData = new FormData();
|
||||||
|
|
||||||
|
for (const f of files) {
|
||||||
|
formData.append('files', f.file, f.file.name);
|
||||||
|
|
||||||
|
const settings = {
|
||||||
|
filename: f.file.name,
|
||||||
|
pages: f.selectedPages ? Array.from(f.selectedPages).sort((a, b) => a - b).join(',') : 'all',
|
||||||
|
copies: f.copies,
|
||||||
|
colorMode: f.colorMode,
|
||||||
|
format: f.format
|
||||||
|
};
|
||||||
|
formData.append('settings', JSON.stringify(settings));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/print', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
alert(`✅ Успешно отправлено в печать!\n${text}`);
|
||||||
|
} else {
|
||||||
|
alert(`❌ Ошибка печати (${response.status}):\n${text}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Print submission error:', error);
|
||||||
|
alert(`⚠️ Не удалось связаться с сервером печати.`);
|
||||||
|
} finally {
|
||||||
|
isPrinting = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
input.value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
function triggerFileInput(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
fileInput.click();
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleExpanded(file) { file.expanded = !file.expanded; }
|
|
||||||
|
|
||||||
function removeFile(file) {
|
|
||||||
if (file.previewUrl) URL.revokeObjectURL(file.previewUrl);
|
|
||||||
files = files.filter((f) => f.id !== file.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Опции печати ──
|
|
||||||
function toggleFormat(file, f) { file.format = f; }
|
|
||||||
function toggleColor(file, c) { file.colorMode = c.id; }
|
|
||||||
function incrementCopies(file) { file.copies += 1; }
|
|
||||||
function decrementCopies(file) { if (file.copies > 1) file.copies -= 1; }
|
|
||||||
function qualityFillFor(file) { return Math.round((file.qualityIndex / (qualities.length - 1)) * 100); }
|
|
||||||
function pageStubFor() { return 0; }
|
|
||||||
|
|
||||||
const totalPrice = $derived(`${files.reduce((sum, f) => sum + pageStubFor(f), 0)}₽`);
|
|
||||||
const extraCopies = $derived(files.reduce((sum, f) => sum + (f.copies - 1), 0));
|
|
||||||
|
|
||||||
onDestroy(() => {
|
|
||||||
files.forEach((f) => { if (f.previewUrl) URL.revokeObjectURL(f.previewUrl); });
|
|
||||||
});
|
|
||||||
|
|
||||||
// ── Плюрализация ──
|
|
||||||
function pluralize(n, forms) {
|
|
||||||
const mod10 = n % 10, mod100 = n % 100;
|
|
||||||
if (mod10 === 1 && mod100 !== 11) return forms[0];
|
|
||||||
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 > 14)) return forms[1];
|
|
||||||
return forms[2];
|
|
||||||
}
|
|
||||||
const plFiles = (n) => pluralize(n, ['файл', 'файла', 'файлов']);
|
|
||||||
const plCopies = (n) => pluralize(n, ['копия', 'копии', 'копий']);
|
|
||||||
|
|
||||||
function handlePagesClick(file) {
|
|
||||||
if (file.fileType === 'pdf') openPageGallery(file);
|
|
||||||
else openPreview(file);
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if !activeFile}
|
{#if !activeFile}
|
||||||
@ -366,7 +435,16 @@ function handlePagesClick(file) {
|
|||||||
|
|
||||||
<div class="option-sub quality-sub">
|
<div class="option-sub quality-sub">
|
||||||
<label class="option-title">Качество – {qualities[file.qualityIndex].label}</label>
|
<label class="option-title">Качество – {qualities[file.qualityIndex].label}</label>
|
||||||
<input type="range" min={0} max={qualities.length - 1} step={1} bind:value={file.qualityIndex} class="quality-slider" style="--fill: {qualityFillFor(file)}%" />
|
<input
|
||||||
|
type="range"
|
||||||
|
min={0}
|
||||||
|
max={qualities.length - 1}
|
||||||
|
step={1}
|
||||||
|
value={file.qualityIndex}
|
||||||
|
oninput={(e) => updateQuality(file, parseInt(e.target.value))}
|
||||||
|
class="quality-slider"
|
||||||
|
style="--fill: {qualityFillFor(file)}%"
|
||||||
|
/>
|
||||||
<div class="quality-marks-inline">
|
<div class="quality-marks-inline">
|
||||||
{#each qualities as q}<span class="quality-mark">{q.label}</span>{/each}
|
{#each qualities as q}<span class="quality-mark">{q.label}</span>{/each}
|
||||||
</div>
|
</div>
|
||||||
@ -375,7 +453,6 @@ function handlePagesClick(file) {
|
|||||||
{/if}
|
{/if}
|
||||||
</section>
|
</section>
|
||||||
{/each}
|
{/each}
|
||||||
|
|
||||||
<button type="button" class="add-file-btn" onclick={triggerFileInput}>+ Добавить файлы</button>
|
<button type="button" class="add-file-btn" onclick={triggerFileInput}>+ Добавить файлы</button>
|
||||||
{/if}
|
{/if}
|
||||||
</main>
|
</main>
|
||||||
@ -389,9 +466,17 @@ function handlePagesClick(file) {
|
|||||||
{/if}
|
{/if}
|
||||||
<div class="price-summary">
|
<div class="price-summary">
|
||||||
<span class="summary-itogo">Итого</span>
|
<span class="summary-itogo">Итого</span>
|
||||||
<span class="summary-price">{totalPrice}</span>
|
<span class="summary-price">{totalPrice()}₽</span>
|
||||||
</div>
|
</div>
|
||||||
<button type="button" class="action-btn secondary" onclick={onPrint}>Печать</button>
|
<!-- ИЗМЕНЕННАЯ КНОПКА -->
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="action-btn secondary"
|
||||||
|
onclick={submitPrint}
|
||||||
|
disabled={isPrinting || files.length === 0}
|
||||||
|
>
|
||||||
|
{isPrinting ? 'Отправка...' : 'Печать'}
|
||||||
|
</button>
|
||||||
<input type="file" bind:this={fileInput} accept="image/*,.pdf" multiple onchange={handleFileSelect} style="display:none" />
|
<input type="file" bind:this={fileInput} accept="image/*,.pdf" multiple onchange={handleFileSelect} style="display:none" />
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
@ -466,13 +551,13 @@ function handlePagesClick(file) {
|
|||||||
.add-file-btn { align-self: center; background: none; border: 1px dashed rgba(255, 255, 255, 0.18); color: #a9b0c0; font-size: 14px; font-weight: 600; padding: 12px 18px; border-radius: 14px; cursor: pointer; margin-top: 8px; }
|
.add-file-btn { align-self: center; background: none; border: 1px dashed rgba(255, 255, 255, 0.18); color: #a9b0c0; font-size: 14px; font-weight: 600; padding: 12px 18px; border-radius: 14px; cursor: pointer; margin-top: 8px; }
|
||||||
.actions { padding: 16px 20px 32px; display: flex; flex-direction: column; gap: 12px; }
|
.actions { padding: 16px 20px 32px; display: flex; flex-direction: column; gap: 12px; }
|
||||||
.file-count { color: #8b93a1; font-size: 13px; margin: 0; text-align: center; line-height: 1.4; }
|
.file-count { color: #8b93a1; font-size: 13px; margin: 0; text-align: center; line-height: 1.4; }
|
||||||
.action-btn { width: 100%; padding: 16px 24px; border-radius: 16px; font-size: 16px; font-weight: 700; cursor: pointer; border: none; color: #fff; }
|
.action-btn { width: 100%; padding: 16px 24px; border-radius: 16px; font-size: 16px; font-weight: 700; cursor: pointer; border: none; color: #fff; transition: opacity 0.2s; }
|
||||||
|
.action-btn:disabled { opacity: 0.6; cursor: wait; }
|
||||||
.action-btn.primary { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); box-shadow: 0 8px 24px -6px rgba(99, 102, 241, 0.5); }
|
.action-btn.primary { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); box-shadow: 0 8px 24px -6px rgba(99, 102, 241, 0.5); }
|
||||||
.action-btn.secondary { background: linear-gradient(135deg, #5b8cff 0%, #38c6ff 100%); box-shadow: 0 8px 24px -6px rgba(72, 150, 255, 0.4); }
|
.action-btn.secondary { background: linear-gradient(135deg, #5b8cff 0%, #38c6ff 100%); box-shadow: 0 8px 24px -6px rgba(72, 150, 255, 0.4); }
|
||||||
.price-summary { display: flex; justify-content: space-between; align-items: baseline; width: 100%; }
|
.price-summary { display: flex; justify-content: space-between; align-items: baseline; width: 100%; }
|
||||||
.summary-itogo { font-size: 30px; font-weight: 700; color: #8b93a1; }
|
.summary-itogo { font-size: 30px; font-weight: 700; color: #8b93a1; }
|
||||||
.summary-price { font-size: 38px; font-weight: 800; color: #fff; }
|
.summary-price { font-size: 38px; font-weight: 800; color: #fff; }
|
||||||
|
|
||||||
.overlay-backdrop {
|
.overlay-backdrop {
|
||||||
position: fixed; inset: 0; z-index: 1000;
|
position: fixed; inset: 0; z-index: 1000;
|
||||||
background: rgba(10, 12, 18, 0.92); backdrop-filter: blur(12px);
|
background: rgba(10, 12, 18, 0.92); backdrop-filter: blur(12px);
|
||||||
|
|||||||
@ -24,4 +24,13 @@ export default defineConfig({
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
],
|
],
|
||||||
|
server: {
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:3000',
|
||||||
|
changeOrigin: true,
|
||||||
|
rewrite: (path) => path.replace(/^\/api/, '')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user