This commit is contained in:
2026-09-18 20:24:45 +03:00
parent 623478bff0
commit 51d86d49e3
5 changed files with 552 additions and 520 deletions

View File

@ -1,20 +1,24 @@
import * as pdfjsLib from 'pdfjs-dist'; import * as pdfjsLib from 'pdfjs-dist';
import PdfWorkerCtor from 'pdfjs-dist/build/pdf.worker.min.mjs?worker';
// Явно указываем путь к worker'у, чтобы избежать проблем с ?worker в PWA/Chromium
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url
).toString();
/** /**
* Загрузка PDF документа * Загрузка PDF документа
* @param {File} file * @param {File} file
*/ */
export async function loadPdfDocument(file) { export async function loadPdfDocument(file) {
try { try {
const arrayBuffer = await file.arrayBuffer(); const arrayBuffer = await file.arrayBuffer();
const worker = new pdfjsLib.PDFWorker({ port: new PdfWorkerCtor() }); const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });
const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer, worker }); return await loadingTask.promise;
return await loadingTask.promise; } catch (err) {
} catch (err) { console.error('PDF load error:', err);
console.error('PDF load error:', err); return null;
return null; }
}
} }
/** /**
@ -24,19 +28,18 @@ export async function loadPdfDocument(file) {
* @param {number} scale * @param {number} scale
*/ */
export async function renderPageToImage(pdfDoc, pageNum, scale = 1.0) { export async function renderPageToImage(pdfDoc, pageNum, scale = 1.0) {
const page = await pdfDoc.getPage(pageNum); const page = await pdfDoc.getPage(pageNum);
const viewport = page.getViewport({ scale }); const viewport = page.getViewport({ scale });
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const context = canvas.getContext('2d'); const context = canvas.getContext('2d');
const outputScale = window.devicePixelRatio || 1; const outputScale = window.devicePixelRatio || 1;
canvas.width = Math.floor(viewport.width * outputScale); canvas.width = Math.floor(viewport.width * outputScale);
canvas.height = Math.floor(viewport.height * outputScale); canvas.height = Math.floor(viewport.height * outputScale);
canvas.style.width = `${Math.floor(viewport.width)}px`; canvas.style.width = `${Math.floor(viewport.width)}px`;
canvas.style.height = `${Math.floor(viewport.height)}px`; canvas.style.height = `${Math.floor(viewport.height)}px`;
const transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : undefined; const transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : undefined;
await page.render({ canvasContext: context, viewport, transform }).promise;
await page.render({ canvasContext: context, viewport, transform }).promise; return canvas.toDataURL('image/jpeg', 0.85);
return canvas.toDataURL('image/jpeg', 0.85);
} }

View File

@ -205,5 +205,5 @@
<div class="version"> <div class="version">
<span>v{backendVersion}</span> <span>v{backendVersion}</span>
<span>v1.0.4</span> <span>v1.0.5</span>
</div> </div>

View File

@ -1,211 +1,234 @@
<!-- lib/pages/print/PrintProgress.svelte --> <!-- lib/pages/print/PrintProgress.svelte -->
<script> <script>
const currentStatus = $derived.by(() => { const currentStatus = $derived.by(() => {
if (!store.job) return 'idle'; if (!store.job) return 'idle';
const f = store.job.files.find(f => f.status === 'printing'); const f = store.job.files.find(f => f.status === 'printing');
if (f) return 'printing'; if (f) return 'printing';
const q = store.job.files.find(f => f.status === 'queued'); const q = store.job.files.find(f => f.status === 'queued');
return q ? 'queued' : store.job.phase; return q ? 'queued' : store.job.phase;
}); });
let { store, onBack = () => {} } = $props(); let { store, onBack = () => {} } = $props();
const OFFICE_EXT = ['DOC', 'DOCX', 'ODT', 'XLS', 'XLSX', 'ODS', 'PPT', 'PPTX', 'ODP'];
const OFFICE_EXT = ['DOC', 'DOCX', 'ODT', 'XLS', 'XLSX', 'ODS', 'PPT', 'PPTX', 'ODP']; const STATUS_LABEL = {
const STATUS_LABEL = { queued: 'В очереди',
queued: 'Ожидает', printing: 'Отправка...',
printing: 'Печатается…', sent: 'Отправлен',
awaiting_flip: 'Переложите бумагу', awaiting_clear_output: 'Уберите распечатанные листы',
done: 'Готово', awaiting_flip: 'Переложите бумагу',
error: 'Ошибка', awaiting_pickup: 'Заберите документ',
cancelled: 'Отменено' done: 'Готов',
}; error: 'Ошибка',
cancelled: 'Отменено'
};
function badge(name) { function badge(name) {
const e = (name.split('.').pop() || '').toUpperCase(); const e = (name.split('.').pop() || '').toUpperCase();
return OFFICE_EXT.includes(e) ? e : null; return OFFICE_EXT.includes(e) ? e : null;
} }
// Опрос статуса задания, пока оно активно $effect(() => {
$effect(() => { if (!store.jobActive) return;
if (!store.jobActive) return; const int = setInterval(() => store.refreshJob(), 1000);
const int = setInterval(() => store.refreshJob(), 1000); return () => clearInterval(int);
return () => clearInterval(int); });
});
// ── Отмена удержанием (защита от миссклика) ── // Проверка, можно ли отменить (есть ли файлы в очереди или печатающиеся)
const HOLD_MS = 1500; const canCancel = $derived(store.job?.files.some(f => f.status === 'queued' || f.status === 'printing'));
let hold = $state(0);
let raf = 0;
let t0 = 0;
function startHold(e) { const HOLD_MS = 1500;
if (!store.jobActive) return; let hold = $state(0);
e.preventDefault(); let raf = 0;
e.currentTarget.setPointerCapture?.(e.pointerId); let t0 = 0;
t0 = performance.now();
const step = (now) => {
hold = Math.min(1, (now - t0) / HOLD_MS);
if (hold >= 1) {
raf = 0;
hold = 0;
store.cancelJob();
return;
}
raf = requestAnimationFrame(step);
};
raf = requestAnimationFrame(step);
}
function endHold() {
if (raf) cancelAnimationFrame(raf);
raf = 0;
hold = 0;
}
function finish() { function startHold(e) {
store.resetJob(); if (!store.jobActive || !canCancel) return;
onBack(); e.preventDefault();
} e.currentTarget.setPointerCapture?.(e.pointerId);
t0 = performance.now();
const step = (now) => {
hold = Math.min(1, (now - t0) / HOLD_MS);
if (hold >= 1) {
raf = 0;
hold = 0;
store.cancelJob();
return;
}
raf = requestAnimationFrame(step);
};
raf = requestAnimationFrame(step);
}
function endHold() {
if (raf) cancelAnimationFrame(raf);
raf = 0;
hold = 0;
}
function finish() {
store.resetJob();
onBack();
}
</script> </script>
<div class="page-container"> <div class="page-container">
<header class="header"> <header class="header">
<button class="back-btn" disabled={store.jobActive} onclick={finish}></button> <button class="back-btn" disabled={store.jobActive} onclick={finish}></button>
<h1>Печать</h1> <h1>Печать</h1>
</header> </header>
<main class="list">
{#if store.job}
{#each store.job.files as f, i (i + '-' + f.name)}
{@const b = badge(f.name)}
{@const isLastDone = f.status === 'done' && !store.job.files.slice(i + 1).some(f => f.status === 'printing' || f.status === 'queued')}
{@const hasNextQueued = store.job.files.slice(i + 1).some(f => f.status === 'queued')}
<section class="file-card" class:current={f.status === 'awaiting_flip' || f.status === 'awaiting_clear_output' || f.status === 'printing' || isLastDone}>
<div class="file-row">
{#if b}<span class="type-badge">{b}</span>{/if}
<span class="file-name" title={f.name}>{f.name}</span>
<span class="file-status st-{f.status}">{STATUS_LABEL[f.status] ?? f.status}</span>
</div>
{#if f.status === 'awaiting_clear_output'}
<ol class="pickup-hint clear-hint">
<li>Уберите распечатанные листы из выходного лотка</li>
<li>Нажмите кнопку ниже для запуска двусторонней печати</li>
</ol>
{:else if f.status === 'awaiting_flip'}
<ol class="pickup-hint flip-hint">
<li>Не переворачивая, положите остальные листы в слот ручной подачи</li>
</ol>
{:else if isLastDone && hasNextQueued && !store.autoContinue}
<ol class="pickup-hint">
<li>Возьмите готовый документ</li>
<li>Нажмите далее</li>
</ol>
{/if}
{#if f.error}
<p class="file-error">{f.error}</p>
{/if}
</section>
{/each}
{/if}
</main>
<footer class="actions">
<label class="auto-row">
<input
type="checkbox"
checked={store.autoContinue}
onchange={(e) => store.setAutoContinue(e.target.checked)}
/>
<span>Автоматически продолжать печать</span>
</label>
{#if store.autoContinue}
<p class="auto-warning">⚠️ Отправленные файлы нельзя будет отменить</p>
{/if}
<main class="list"> {#if store.jobActive}
{#if store.job} {#if store.job?.phase === 'awaiting_clear_output'}
{#each store.job.files as f, i (i + '-' + f.name)} <button class="next-btn next-btn-clear" onclick={store.advanceJob}>
{@const b = badge(f.name)} Убрал листы — печатать
{@const isLastDone = f.status === 'done' && !store.job.files.slice(i + 1).some(f => f.status === 'printing' || f.status === 'queued')} </button>
{@const hasNextQueued = store.job.files.slice(i + 1).some(f => f.status === 'queued')} {:else if store.job?.phase === 'awaiting_flip'}
<section class="file-card" class:current={f.status === 'awaiting_flip' || f.status === 'printing' || isLastDone}> <button class="next-btn next-btn-flip" onclick={store.advanceJob}>
<div class="file-row"> Переложил — печатать обратную сторону
{#if b}<span class="type-badge">{b}</span>{/if} </button>
<span class="file-name" title={f.name}>{f.name}</span> {:else if store.job?.phase === 'awaiting_pickup'}
<span class="file-status st-{f.status}">{STATUS_LABEL[f.status] ?? f.status}</span> <button class="next-btn" onclick={store.advanceJob}>Забрал далее</button>
</div> {:else}
<button class="next-btn next-btn-disabled" disabled>
{currentStatus === 'printing' ? 'Отправка...' : 'Ожидание...'}
</button>
{/if}
<!-- ── Инструкция для РУЧНОГО ДУПЛЕКСА (после 1-го прохода) ── --> <button
{#if f.status === 'awaiting_flip'} class="cancel-btn"
<ol class="pickup-hint flip-hint"> disabled={!canCancel}
<li>Не переворачивая, положите остальные листы в слот ручной подачи</li> onpointerdown={canCancel ? startHold : null}
</ol> onpointerup={endHold}
{/if} onpointercancel={endHold}
onpointerleave={endHold}
<!-- ── Инструкция для обычного «забери документ» ── --> oncontextmenu={(e) => e.preventDefault()}
{#if isLastDone && hasNextQueued} >
<ol class="pickup-hint"> <span class="cancel-fill" style:width="{hold * 100}%"></span>
<li>Возьмите готовый документ</li> <span class="cancel-label">{canCancel ? 'Отмена' : 'Отмена недоступна'}</span>
<li>Нажмите далее</li> </button>
</ol> {#if canCancel}
{/if} <p class="hold-hint">Удерживайте для отмены печати</p>
{/if}
{#if f.error} {:else}
<p class="file-error">{f.error}</p> <button class="home-btn" onclick={finish}>На главную</button>
{/if} {/if}
</section> </footer>
{/each}
{/if}
</main>
<footer class="actions">
<label class="auto-row">
<input
type="checkbox"
checked={store.autoContinue}
onchange={(e) => store.setAutoContinue(e.target.checked)}
/>
<span>Автоматически продолжать печать</span>
</label>
{#if store.jobActive}
{#if store.job?.phase === 'awaiting_flip'}
<!-- Ручной дуплекс: пользователь переложил бумагу -->
<button class="next-btn next-btn-flip" onclick={store.advanceJob}>
Готово — печатать обратную сторону
</button>
{:else if store.job?.phase === 'awaiting_pickup' && store.job.files.some(f => f.status === 'queued')}
<!-- Обычное: забрал документ → следующий (только если есть следующий) -->
<button class="next-btn" onclick={store.advanceJob}>Далее</button>
{:else}
<!-- Кнопка видна, но серая и disabled пока сервер не допечатал -->
<button class="next-btn next-btn-disabled" disabled>
{currentStatus === 'printing' ? 'Печатается…' : 'Ожидание печати…'}
</button>
{/if}
<!-- Кнопка отмены (оригинальный код) -->
<button
class="cancel-btn"
onpointerdown={startHold}
onpointerup={endHold}
onpointercancel={endHold}
onpointerleave={endHold}
oncontextmenu={(e) => e.preventDefault()}
>
<span class="cancel-fill" style:width="{hold * 100}%"></span>
<span class="cancel-label">Отмена</span>
</button>
<p class="hold-hint">Удерживайте для отмены печати</p>
{:else}
<button class="home-btn" onclick={finish}>На главную</button>
{/if}
</footer>
</div> </div>
<style> <style>
.st-awaiting_flip { color: #f59e0b; } .st-awaiting_clear_output { color: #f59e0b; }
.st-awaiting_flip { color: #f59e0b; }
.st-sent { color: #8b93a1; }
.st-awaiting_pickup { color: #a5b4fc; }
.clear-hint { color: #f59e0b; }
.flip-hint { color: #f59e0b; }
.next-btn-clear {
background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
box-shadow: 0 8px 24px -6px rgba(245, 158, 11, 0.4);
}
.auto-warning {
margin: -4px 0 8px;
text-align: center;
color: #f59e0b;
font-size: 13px;
font-weight: 600;
}
.flip-hint { .page-container { width: 100%; min-height: 100dvh; display: flex; flex-direction: column; background: radial-gradient(120% 60% at 50% -10%, rgba(99,102,241,0.18) 0%, transparent 60%); font-family: system-ui, -apple-system, sans-serif; color: #f5f7fa; }
color: #f59e0b; .header { padding: 24px 20px 8px; display: flex; align-items: center; position: relative; }
} .back-btn { background: none; border: none; color: #6366f1; font-size: 15px; font-weight: 600; cursor: pointer; padding: 8px 4px; margin-right: auto; min-height: 44px; }
.back-btn:disabled { opacity: 0.3; cursor: not-allowed; }
.next-btn-flip { .header h1 { margin: 0; font-size: 28px; font-weight: 700; position: absolute; left: 50%; transform: translateX(-50%); white-space: nowrap; }
background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); .list { flex: 1; padding: 24px 20px 16px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; }
box-shadow: 0 8px 24px -6px rgba(245, 158, 11, 0.4); .file-card { border-radius: 16px; background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08); padding: 14px; display: flex; flex-direction: column; gap: 8px; transition: border-color 0.2s ease, background 0.2s ease; }
} .file-card.current { border-color: rgba(99,102,241,0.45); background: rgba(99,102,241,0.07); }
.page-container { width: 100%; min-height: 100dvh; display: flex; flex-direction: column; background: radial-gradient(120% 60% at 50% -10%, rgba(99,102,241,0.18) 0%, transparent 60%); font-family: system-ui, -apple-system, sans-serif; color: #f5f7fa; } .file-row { display: flex; align-items: center; gap: 12px; min-width: 0; }
.header { padding: 24px 20px 8px; display: flex; align-items: center; position: relative; } .file-name { flex: 1; min-width: 0; font-size: 15px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.back-btn { background: none; border: none; color: #6366f1; font-size: 15px; font-weight: 600; cursor: pointer; padding: 8px 4px; margin-right: auto; min-height: 44px; } .file-status { flex-shrink: 0; font-size: 14px; font-weight: 700; }
.back-btn:disabled { opacity: 0.3; cursor: not-allowed; } .st-done { color: #22c55e; }
.header h1 { margin: 0; font-size: 28px; font-weight: 700; position: absolute; left: 50%; transform: translateX(-50%); white-space: nowrap; } .st-queued { color: #8b93a1; }
.st-printing { color: #a5b4fc; }
.list { flex: 1; padding: 24px 20px 16px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; } .st-error { color: #ef4444; }
.st-cancelled { color: #6b7280; }
.file-card { border-radius: 16px; background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08); padding: 14px; display: flex; flex-direction: column; gap: 8px; transition: border-color 0.2s ease, background 0.2s ease; } .type-badge { flex-shrink: 0; padding: 3px 7px; border-radius: 6px; background: rgba(99,102,241,0.2); border: 1px solid rgba(99,102,241,0.35); color: #a5b4fc; font-size: 10px; font-weight: 700; letter-spacing: 0.04em; line-height: 1.2; user-select: none; }
.file-card.current { border-color: rgba(99,102,241,0.45); background: rgba(99,102,241,0.07); } .pickup-hint { margin: 0; padding-left: 22px; color: #eab308; font-size: 14px; line-height: 1.6; font-weight: 600; }
.file-row { display: flex; align-items: center; gap: 12px; min-width: 0; } .file-error { margin: 0; color: #fca5a5; font-size: 12px; line-height: 1.4; }
.file-name { flex: 1; min-width: 0; font-size: 15px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .actions { padding: 16px 20px 32px; display: flex; flex-direction: column; gap: 12px; }
.file-status { flex-shrink: 0; font-size: 14px; font-weight: 700; } .auto-row { display: flex; align-items: center; justify-content: center; gap: 10px; color: #a9b0c0; font-size: 14px; font-weight: 600; user-select: none; cursor: pointer; }
.st-done { color: #22c55e; } .auto-row input { width: 18px; height: 18px; accent-color: #6366f1; cursor: pointer; }
.st-queued { color: #8b93a1; } .next-btn { width: 100%; padding: 16px 24px; border-radius: 16px; font-size: 16px; font-weight: 700; cursor: pointer; border: none; color: #fff; background: linear-gradient(135deg, #5b8cff 0%, #38c6ff 100%); box-shadow: 0 8px 24px -6px rgba(72,150,255,0.4); }
.st-printing { color: #a5b4fc; } .next-btn-flip {
.st-error { color: #ef4444; } background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
.st-cancelled { color: #6b7280; } box-shadow: 0 8px 24px -6px rgba(245, 158, 11, 0.4);
}
.type-badge { flex-shrink: 0; padding: 3px 7px; border-radius: 6px; background: rgba(99,102,241,0.2); border: 1px solid rgba(99,102,241,0.35); color: #a5b4fc; font-size: 10px; font-weight: 700; letter-spacing: 0.04em; line-height: 1.2; user-select: none; } .next-btn-disabled {
opacity: 0.5;
.pickup-hint { margin: 0; padding-left: 22px; color: #eab308; font-size: 14px; line-height: 1.6; font-weight: 600; } cursor: wait;
.file-error { margin: 0; color: #fca5a5; font-size: 12px; line-height: 1.4; } pointer-events: none;
background: linear-gradient(135deg, #475569 0%, #64748b 100%);
.actions { padding: 16px 20px 32px; display: flex; flex-direction: column; gap: 12px; } box-shadow: none;
.auto-row { display: flex; align-items: center; justify-content: center; gap: 10px; color: #a9b0c0; font-size: 14px; font-weight: 600; user-select: none; cursor: pointer; } }
.auto-row input { width: 18px; height: 18px; accent-color: #6366f1; cursor: pointer; } .cancel-btn { position: relative; overflow: hidden; width: 100%; padding: 16px 24px; border-radius: 16px; border: 1px solid rgba(239,68,68,0.35); background: rgba(239,68,68,0.08); color: #fca5a5; font-size: 16px; font-weight: 700; cursor: pointer; touch-action: none; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; }
.cancel-btn:disabled {
.next-btn { width: 100%; padding: 16px 24px; border-radius: 16px; font-size: 16px; font-weight: 700; cursor: pointer; border: none; color: #fff; background: linear-gradient(135deg, #5b8cff 0%, #38c6ff 100%); box-shadow: 0 8px 24px -6px rgba(72,150,255,0.4); } opacity: 0.4;
.next-btn-disabled { cursor: not-allowed;
opacity: 0.5; pointer-events: none;
cursor: wait; }
pointer-events: none; .cancel-fill { position: absolute; left: 0; top: 0; bottom: 0; width: 0%; background: rgba(239,68,68,0.35); pointer-events: none; }
background: linear-gradient(135deg, #475569 0%, #64748b 100%); .cancel-label { position: relative; }
box-shadow: none; .hold-hint { margin: -4px 0 0; text-align: center; color: rgba(139,147,161,0.6); font-size: 11px; }
} .home-btn { width: 100%; padding: 16px 24px; border-radius: 16px; font-size: 16px; font-weight: 700; cursor: pointer; border: none; color: #fff; background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); box-shadow: 0 8px 24px -6px rgba(34,197,94,0.4); }
.cancel-btn { position: relative; overflow: hidden; width: 100%; padding: 16px 24px; border-radius: 16px; border: 1px solid rgba(239,68,68,0.35); background: rgba(239,68,68,0.08); color: #fca5a5; font-size: 16px; font-weight: 700; cursor: pointer; touch-action: none; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; }
.cancel-fill { position: absolute; left: 0; top: 0; bottom: 0; width: 0%; background: rgba(239,68,68,0.35); pointer-events: none; }
.cancel-label { position: relative; }
.hold-hint { margin: -4px 0 0; text-align: center; color: rgba(139,147,161,0.6); font-size: 11px; }
.home-btn { width: 100%; padding: 16px 24px; border-radius: 16px; font-size: 16px; font-weight: 700; cursor: pointer; border: none; color: #fff; background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); box-shadow: 0 8px 24px -6px rgba(34,197,94,0.4); }
</style> </style>

View File

@ -13,325 +13,322 @@ import { loadPdfDocument, renderPageToImage } from '$lib/common/services/pdf.ser
* dpi: string, totalPages: number, * dpi: string, totalPages: number,
* selectedPages: Set<number>, pdfDoc: any * selectedPages: Set<number>, pdfDoc: any
* }} FileEntry * }} FileEntry
* @typedef {{ name: string, status: 'queued'|'printing'|'awaiting'|'done'|'error'|'cancelled', error: (string|null) }} JobFileView * @typedef {{ name: string, status: 'queued'|'printing'|'sent'|'awaiting_clear_output'|'awaiting_flip'|'awaiting_pickup'|'done'|'error'|'cancelled', error: (string|null) }} JobFileView
* @typedef {{ job_id: string, phase: 'waiting_start'|'printing'|'awaiting_pickup'|'finished'|'cancelled', files: JobFileView[] }} JobView * @typedef {{ job_id: string, phase: 'waiting_start'|'printing'|'awaiting_clear_output'|'awaiting_flip'|'awaiting_pickup'|'finished'|'cancelled', files: JobFileView[] }} JobView
*/ */
export function createPrintStore() { export function createPrintStore() {
let files = $state(/** @type {FileEntry[]} */ ([])); let files = $state(/** @type {FileEntry[]} */ ([]));
let activeFile = $state(/** @type {FileEntry | null} */ (null)); let activeFile = $state(/** @type {FileEntry | null} */ (null));
let viewMode = $state(/** @type {'gallery' | 'preview'} */ ('gallery')); let viewMode = $state(/** @type {'gallery' | 'preview'} */ ('gallery'));
let showPayment = $state(false); let showPayment = $state(false);
let isPrinting = $state(false); let isPrinting = $state(false);
let galleryThumbnails = $state([]); let galleryThumbnails = $state([]);
let galleryLoading = $state(false); let galleryLoading = $state(false);
let previewPagesCache = $state({}); let previewPagesCache = $state({});
let isPreviewRendering = $state(false); let isPreviewRendering = $state(false);
// ── Задание печати (страница прогресса) ── let job = $state(/** @type {JobView | null} */ (null));
let job = $state(/** @type {JobView | null} */ (null)); let autoContinue = $state(false);
let autoContinue = $state(false); let advancing = false;
let advancing = false;
const jobActive = $derived(!!job && job.phase !== 'finished' && job.phase !== 'cancelled'); const jobActive = $derived(!!job && job.phase !== 'finished' && job.phase !== 'cancelled');
let uid = 0;
let uid = 0; const totalPrice = $derived(
files.reduce((sum, f) => {
const pages = f.selectedPages?.size || 0;
return sum + pages * f.copies * getPricePerPage(pages);
}, 0)
);
const extraCopies = $derived(files.reduce((sum, f) => sum + (f.copies - 1), 0));
const totalPrice = $derived( function updateFile(id, changes) {
files.reduce((sum, f) => { files = files.map((f) => (f.id === id ? { ...f, ...changes } : f));
const pages = f.selectedPages?.size || 0; if (activeFile?.id === id) {
return sum + pages * f.copies * getPricePerPage(pages); activeFile = files.find((f) => f.id === id);
}, 0) }
); }
const extraCopies = $derived(files.reduce((sum, f) => sum + (f.copies - 1), 0));
function updateFile(id, changes) { async function ensurePdfLoaded(entry) {
files = files.map((f) => (f.id === id ? { ...f, ...changes } : f)); if (entry.pdfDoc) return entry.pdfDoc;
if (activeFile?.id === id) { const pdf = await loadPdfDocument(entry.file);
activeFile = files.find((f) => f.id === id); if (pdf) {
} const numPages = pdf.numPages;
} updateFile(entry.id, {
pdfDoc: pdf,
totalPages: numPages,
selectedPages: new Set(Array.from({ length: numPages }, (_, i) => i + 1))
});
} else {
updateFile(entry.id, { totalPages: 0 });
}
return pdf;
}
async function ensurePdfLoaded(entry) { async function addFiles(fileList) {
if (entry.pdfDoc) return entry.pdfDoc; if (!fileList || fileList.length === 0) return;
const pdf = await loadPdfDocument(entry.file); const newFiles = [];
if (pdf) { for (let i = 0; i < fileList.length; i++) {
const numPages = pdf.numPages; const file = fileList[i];
updateFile(entry.id, { const fType = detectFileType(file);
pdfDoc: pdf, const isOffice = fType === 'office';
totalPages: numPages, newFiles.push({
selectedPages: new Set(Array.from({ length: numPages }, (_, i) => i + 1)) id: ++uid,
}); file,
} else { previewUrl: isOffice ? null : URL.createObjectURL(file),
updateFile(entry.id, { totalPages: 0 }); fileType: fType,
} expanded: false,
return pdf; format: 'Авто',
} colorMode: 'bw',
qualityIndex: 1,
copies: 1,
sides: 'Односторонняя',
dpi: 'Авто',
totalPages: (fType === 'image' || isOffice) ? 1 : 0,
selectedPages: (fType === 'image' || isOffice) ? new Set([1]) : new Set(),
pdfDoc: null
});
}
files = [...files, ...newFiles];
for (const entry of newFiles) {
if (entry.fileType === 'pdf') ensurePdfLoaded(entry);
}
}
async function addFiles(fileList) { function removeFile(id) {
if (!fileList || fileList.length === 0) return; const f = files.find((x) => x.id === id);
const newFiles = []; if (f?.previewUrl) URL.revokeObjectURL(f.previewUrl);
for (let i = 0; i < fileList.length; i++) { files = files.filter((x) => x.id !== id);
const file = fileList[i]; }
const fType = detectFileType(file);
const isOffice = fType === 'office';
newFiles.push({
id: ++uid,
file,
previewUrl: isOffice ? null : URL.createObjectURL(file),
fileType: fType,
expanded: false,
format: 'Авто',
colorMode: 'bw',
qualityIndex: 1,
copies: 1,
sides: 'Односторонняя',
dpi: 'Авто',
totalPages: (fType === 'image' || isOffice) ? 1 : 0,
selectedPages: (fType === 'image' || isOffice) ? new Set([1]) : new Set(),
pdfDoc: null
});
}
files = [...files, ...newFiles];
for (const entry of newFiles) {
if (entry.fileType === 'pdf') ensurePdfLoaded(entry);
}
}
function removeFile(id) { function toggleExpand(id) {
const f = files.find((x) => x.id === id); updateFile(id, { expanded: !files.find((f) => f.id === id)?.expanded });
if (f?.previewUrl) URL.revokeObjectURL(f.previewUrl); }
files = files.filter((x) => x.id !== id);
}
function toggleExpand(id) {
updateFile(id, { expanded: !files.find((f) => f.id === id)?.expanded });
}
async function openGallery(entry) { async function openGallery(entry) {
activeFile = entry; activeFile = entry;
viewMode = 'gallery'; viewMode = 'gallery';
galleryThumbnails = []; galleryThumbnails = [];
galleryLoading = true; galleryLoading = true;
previewPagesCache = {}; previewPagesCache = {};
await tick(); await tick();
const pdf = await ensurePdfLoaded(entry); const pdf = await ensurePdfLoaded(entry);
if (!pdf || entry.totalPages === 0) { if (!pdf || entry.totalPages === 0) {
galleryLoading = false; galleryLoading = false;
return; return;
} }
const thumbs = []; const thumbs = [];
for (let i = 1; i <= entry.totalPages; i++) { for (let i = 1; i <= entry.totalPages; i++) {
try { try {
thumbs.push(await renderPageToImage(pdf, i, 0.4)); thumbs.push(await renderPageToImage(pdf, i, 0.4));
} catch { } catch {
thumbs.push(''); thumbs.push('');
} }
galleryThumbnails = [...thumbs]; }
} galleryThumbnails = [...thumbs];
galleryLoading = false; galleryLoading = false;
} }
async function openPreview(entry) { async function openPreview(entry) {
activeFile = entry; activeFile = entry;
viewMode = 'preview'; viewMode = 'preview';
previewPagesCache = {}; previewPagesCache = {};
galleryThumbnails = []; galleryThumbnails = [];
await tick(); await tick();
if (entry.fileType === 'pdf') { if (entry.fileType === 'pdf') {
const pdf = await ensurePdfLoaded(entry); const pdf = await ensurePdfLoaded(entry);
if (pdf && entry.totalPages > 0) { if (pdf && entry.totalPages > 0) {
preloadPreviewPages(entry, 1, 5); preloadPreviewPages(entry, 1, 5);
} }
} }
} }
async function preloadPreviewPages(entry, startPage, count) { async function preloadPreviewPages(entry, startPage, count) {
const currentFile = files.find((f) => f.id === entry.id); const currentFile = files.find((f) => f.id === entry.id);
const pdf = currentFile?.pdfDoc || entry.pdfDoc; const pdf = currentFile?.pdfDoc || entry.pdfDoc;
if (!pdf || isPreviewRendering) return; if (!pdf || isPreviewRendering) return;
isPreviewRendering = true; isPreviewRendering = true;
const endPage = Math.min(startPage + count - 1, entry.totalPages); const endPage = Math.min(startPage + count - 1, entry.totalPages);
const newCache = {}; const newCache = {};
for (let i = startPage; i <= endPage; i++) { for (let i = startPage; i <= endPage; i++) {
if (previewPagesCache[i]) continue; if (previewPagesCache[i]) continue;
try { try {
newCache[i] = await renderPageToImage(pdf, i, 1.5); newCache[i] = await renderPageToImage(pdf, i, 1.5);
} catch (e) { } catch (e) {
console.error(`Failed to render preview page ${i}`, e); console.error(`Failed to render preview page ${i}`, e);
} }
} }
if (Object.keys(newCache).length > 0) { if (Object.keys(newCache).length > 0) {
previewPagesCache = { ...previewPagesCache, ...newCache }; previewPagesCache = { ...previewPagesCache, ...newCache };
} }
isPreviewRendering = false; isPreviewRendering = false;
} }
function togglePageSelection(pageNum) { function togglePageSelection(pageNum) {
if (!activeFile?.selectedPages) return; if (!activeFile?.selectedPages) return;
const newSet = new Set(activeFile.selectedPages); const newSet = new Set(activeFile.selectedPages);
if (newSet.has(pageNum)) { if (newSet.has(pageNum)) {
if (newSet.size > 1) newSet.delete(pageNum); if (newSet.size > 1) newSet.delete(pageNum);
} else { } else {
newSet.add(pageNum); newSet.add(pageNum);
} }
updateFile(activeFile.id, { selectedPages: newSet }); updateFile(activeFile.id, { selectedPages: newSet });
} }
function selectAllPages() {
if (!activeFile?.totalPages) return;
updateFile(activeFile.id, {
selectedPages: new Set(Array.from({ length: activeFile.totalPages }, (_, i) => i + 1))
});
}
function deselectAllPages() {
if (!activeFile) return;
updateFile(activeFile.id, { selectedPages: new Set([1]) });
}
// ─────────────── Отправка на печать + job-протокол ─────────────── function selectAllPages() {
if (!activeFile?.totalPages) return;
updateFile(activeFile.id, {
selectedPages: new Set(Array.from({ length: activeFile.totalPages }, (_, i) => i + 1))
});
}
async function submitPrint() { function deselectAllPages() {
if (files.length === 0 || isPrinting) return; if (!activeFile) return;
isPrinting = true; updateFile(activeFile.id, { selectedPages: new Set([1]) });
const formData = new FormData(); }
for (const f of files) {
formData.append('files', f.file, f.file.name);
const pagesValue =
f.fileType === 'office'
? 'all'
: f.selectedPages && f.selectedPages.size > 0
? Array.from(f.selectedPages).sort((a, b) => a - b).join(',')
: 'all';
formData.append(
'settings',
JSON.stringify({
filename: f.file.name,
pages: pagesValue,
copies: f.copies,
colorMode: f.colorMode,
format: f.fileType === 'office' ? 'auto' : f.format,
sides: f.sides ?? 'Односторонняя',
quality: f.qualityIndex,
dpi: f.dpi ?? 'Авто'
})
);
}
try {
const res = await fetch('/api/print', { method: 'POST', body: formData });
const text = await res.text();
if (!res.ok) {
alert(`❌ Ошибка (${res.status}):\n${text}`);
return;
}
let data;
try {
data = JSON.parse(text);
} catch {
alert('⚠️ Некорректный ответ сервера печати.');
return;
}
job = data;
showPayment = false;
await advanceJob(); // старт первого файла
} catch {
alert('⚠️ Не удалось связаться с сервером печати.');
} finally {
isPrinting = false;
}
}
/** Подтверждение: старт первого файла / «забрал документ → печатай следующий» */ async function submitPrint() {
async function advanceJob() { if (files.length === 0 || isPrinting) return;
if (!job || advancing) return; isPrinting = true;
advancing = true; const formData = new FormData();
try { for (const f of files) {
const res = await fetch(`/api/print/${job.job_id}/advance`, { method: 'POST' }); formData.append('files', f.file, f.file.name);
if (res.ok) job = await res.json(); const pagesValue =
} catch (e) { f.fileType === 'office'
console.error('advance error:', e); ? 'all'
} finally { : f.selectedPages && f.selectedPages.size > 0
advancing = false; ? Array.from(f.selectedPages).sort((a, b) => a - b).join(',')
} : 'all';
} formData.append(
'settings',
JSON.stringify({
filename: f.file.name,
pages: pagesValue,
copies: f.copies,
colorMode: f.colorMode,
format: f.fileType === 'office' ? 'auto' : f.format,
sides: f.sides ?? 'Односторонняя',
quality: f.qualityIndex,
dpi: f.dpi ?? 'Авто'
})
);
}
try {
const res = await fetch('/api/print', { method: 'POST', body: formData });
const text = await res.text();
if (!res.ok) {
alert(`❌ Ошибка (${res.status}):\n${text}`);
return;
}
let data;
try {
data = JSON.parse(text);
} catch {
alert('⚠️ Некорректный ответ сервера печати.');
return;
}
job = data;
showPayment = false;
await advanceJob();
} catch {
alert('⚠️ Не удалось связаться с сервером печати.');
} finally {
isPrinting = false;
}
}
/** Поллинг статуса; при autoContinue сами шлём подтверждение */ async function advanceJob() {
async function refreshJob() { if (!job || advancing) return;
if (!job) return; advancing = true;
try { try {
const res = await fetch(`/api/print/${job.job_id}`); const res = await fetch(`/api/print/${job.job_id}/advance`, { method: 'POST' });
if (!res.ok) return; if (res.ok) job = await res.json();
job = await res.json(); } catch (e) {
if (job.phase === 'waiting_start') { console.error('advance error:', e);
advanceJob(); } finally {
} else if (job.phase === 'awaiting_pickup' && autoContinue) { advancing = false;
advanceJob(); }
} }
} catch (e) {
console.error('refresh error:', e);
}
}
async function cancelJob() { async function refreshJob() {
if (!job) return; if (!job) return;
try { try {
const res = await fetch(`/api/print/${job.job_id}/cancel`, { method: 'POST' }); const res = await fetch(`/api/print/${job.job_id}`);
if (res.ok) job = await res.json(); if (!res.ok) return;
} catch (e) { job = await res.json();
console.error('cancel error:', e);
} // Автопродолжение срабатывает ТОЛЬКО для awaiting_pickup
} if (job.phase === 'awaiting_pickup' && autoContinue) {
advanceJob();
}
} catch (e) {
console.error('refresh error:', e);
}
}
function resetJob() { async function cancelJob() {
job = null; if (!job) return;
autoContinue = false; try {
files.forEach((f) => f.previewUrl && URL.revokeObjectURL(f.previewUrl)); const res = await fetch(`/api/print/${job.job_id}/cancel`, { method: 'POST' });
files = []; if (res.ok) job = await res.json();
activeFile = null; } catch (e) {
galleryThumbnails = []; console.error('cancel error:', e);
previewPagesCache = {}; }
showPayment = false; }
}
function setAutoContinue(v) { function resetJob() {
autoContinue = !!v; job = null;
} autoContinue = false;
files.forEach((f) => f.previewUrl && URL.revokeObjectURL(f.previewUrl));
files = [];
activeFile = null;
galleryThumbnails = [];
previewPagesCache = {};
showPayment = false;
}
onDestroy(() => { function setAutoContinue(v) {
files.forEach((f) => f.previewUrl && URL.revokeObjectURL(f.previewUrl)); autoContinue = !!v;
}); }
return { onDestroy(() => {
get files() { return files; }, files.forEach((f) => f.previewUrl && URL.revokeObjectURL(f.previewUrl));
get activeFile() { return activeFile; }, });
get viewMode() { return viewMode; },
get showPayment() { return showPayment; }, return {
get isPrinting() { return isPrinting; }, get files() { return files; },
get totalPrice() { return totalPrice; }, get activeFile() { return activeFile; },
get extraCopies() { return extraCopies; }, get viewMode() { return viewMode; },
get galleryThumbnails() { return galleryThumbnails; }, get showPayment() { return showPayment; },
get galleryLoading() { return galleryLoading; }, get isPrinting() { return isPrinting; },
get previewPagesCache() { return previewPagesCache; }, get totalPrice() { return totalPrice; },
get isPreviewRendering() { return isPreviewRendering; }, get extraCopies() { return extraCopies; },
get job() { return job; }, get galleryThumbnails() { return galleryThumbnails; },
get jobActive() { return jobActive; }, get galleryLoading() { return galleryLoading; },
get autoContinue() { return autoContinue; }, get previewPagesCache() { return previewPagesCache; },
addFiles, get isPreviewRendering() { return isPreviewRendering; },
removeFile, get job() { return job; },
toggleExpand, get jobActive() { return jobActive; },
updateFile, get autoContinue() { return autoContinue; },
openGallery, addFiles,
openPreview, removeFile,
closeOverlay: () => { activeFile = null; galleryThumbnails = []; previewPagesCache = {}; }, toggleExpand,
openPayment: () => { if (files.length > 0 && !isPrinting) showPayment = true; }, updateFile,
hidePayment: () => { showPayment = false; }, openGallery,
submitPrint, openPreview,
advanceJob, closeOverlay: () => { activeFile = null; galleryThumbnails = []; previewPagesCache = {}; },
refreshJob, openPayment: () => { if (files.length > 0 && !isPrinting) showPayment = true; },
cancelJob, hidePayment: () => { showPayment = false; },
resetJob, submitPrint,
setAutoContinue, advanceJob,
togglePageSelection, refreshJob,
selectAllPages, cancelJob,
deselectAllPages, resetJob,
requestPreviewPages: (start, count) => { if (activeFile) preloadPreviewPages(activeFile, start, count); }, setAutoContinue,
pagesLabel: _pagesLabel togglePageSelection,
}; selectAllPages,
deselectAllPages,
requestPreviewPages: (start, count) => { if (activeFile) preloadPreviewPages(activeFile, start, count); },
pagesLabel: _pagesLabel
};
} }

View File

@ -8,8 +8,8 @@ export default defineConfig({
svelte({ svelte({
onwarn(warning, handler) { onwarn(warning, handler) {
if ( if (
warning.code.startsWith('a11y_') || warning.code.startsWith('a11y_') ||
warning.code === 'slot_element_deprecated' || warning.code === 'slot_element_deprecated' ||
warning.code === 'svelte_self_deprecated' || warning.code === 'svelte_self_deprecated' ||
warning.code === 'non_reactive_update' warning.code === 'non_reactive_update'
) { ) {
@ -22,9 +22,9 @@ export default defineConfig({
registerType: 'prompt', registerType: 'prompt',
injectRegister: 'auto', injectRegister: 'auto',
workbox: { workbox: {
clientsClaim: true, // Необходимо для PDF SW clientsClaim: true,
globPatterns: ['**/*.{js,css,html,ico,png,svg,wasm}'], // Добавили mjs, чтобы pdf.worker.min.mjs попадал в precache Нужно для PDFJS
// Важно: не кэшируем API endpoint версии globPatterns: ['**/*.{js,mjs,css,html,ico,png,svg,wasm}'],
navigateFallbackDenylist: [/^\/api\/version/], navigateFallbackDenylist: [/^\/api\/version/],
runtimeCaching: [ runtimeCaching: [
{ {
@ -34,12 +34,21 @@ export default defineConfig({
cacheName: 'google-fonts-cache', cacheName: 'google-fonts-cache',
expiration: { expiration: {
maxEntries: 10, maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 * 365 // 1 год maxAgeSeconds: 60 * 60 * 24 * 365
}, },
cacheableResponse: { cacheableResponse: {
statuses: [0, 200] statuses: [0, 200]
} }
} }
},
// Fallback кэширование для worker-файлов, если они не попали в precache
{
urlPattern: /\/assets\/.*\.(mjs|js)$/,
handler: 'CacheFirst',
options: {
cacheName: 'worker-cache',
expiration: { maxEntries: 20, maxAgeSeconds: 60 * 60 * 24 * 30 }
}
} }
] ]
}, },