add progress print page
This commit is contained in:
@ -1,97 +1,97 @@
|
|||||||
<!-- lib/pages/print/PrintMenu.svelte -->
|
<!-- lib/pages/print/PrintMenu.svelte -->
|
||||||
<script>
|
<script>
|
||||||
import { createPrintStore } from './store.svelte.js';
|
import { createPrintStore } from './store.svelte.js';
|
||||||
import PrintUI from './PrintUI.svelte';
|
import PrintUI from './PrintUI.svelte';
|
||||||
import PreviewOverlay from './PreviewOverlay.svelte';
|
import PreviewOverlay from './PreviewOverlay.svelte';
|
||||||
import PaymentPage from '$lib/common/ui/PaymentPage.svelte';
|
import PrintProgress from './PrintProgress.svelte';
|
||||||
import { plFiles, plCopies } from '$lib/common/utils/pricing.util.js';
|
import PaymentPage from '$lib/common/ui/PaymentPage.svelte';
|
||||||
|
import { plFiles, plCopies } from '$lib/common/utils/pricing.util.js';
|
||||||
|
|
||||||
let { onBack = () => {} } = $props();
|
let { onBack = () => {} } = $props();
|
||||||
const store = createPrintStore();
|
const store = createPrintStore();
|
||||||
let fileInput = $state(null);
|
let fileInput = $state(null);
|
||||||
|
|
||||||
function handleFileSelect(event) {
|
function handleFileSelect(event) {
|
||||||
store.addFiles(event.target.files);
|
store.addFiles(event.target.files);
|
||||||
event.target.value = '';
|
event.target.value = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasTierSmall = $derived(store.files.some((f) => (f.selectedPages?.size || 0) < 25));
|
const hasTierSmall = $derived(store.files.some((f) => (f.selectedPages?.size || 0) < 25));
|
||||||
const hasTierMedium = $derived(store.files.some((f) => {
|
const hasTierMedium = $derived(store.files.some((f) => {
|
||||||
const s = f.selectedPages?.size || 0;
|
const s = f.selectedPages?.size || 0;
|
||||||
return s >= 25 && s < 1000;
|
return s >= 25 && s < 1000;
|
||||||
}));
|
}));
|
||||||
const hasTierLarge = $derived(store.files.some((f) => (f.selectedPages?.size || 0) >= 1000));
|
const hasTierLarge = $derived(store.files.some((f) => (f.selectedPages?.size || 0) >= 1000));
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if store.showPayment}
|
{#if store.job}
|
||||||
<PaymentPage
|
<!-- Страница прогресса печати (после оплаты) -->
|
||||||
totalPrice={store.totalPrice}
|
<PrintProgress {store} onBack={onBack} />
|
||||||
filesCount={store.files.length}
|
{:else if store.showPayment}
|
||||||
onBack={store.hidePayment}
|
<PaymentPage
|
||||||
onConfirmPayment={store.submitPrint}
|
totalPrice={store.totalPrice}
|
||||||
/>
|
filesCount={store.files.length}
|
||||||
|
onBack={store.hidePayment}
|
||||||
|
onConfirmPayment={store.submitPrint}
|
||||||
|
/>
|
||||||
|
{:else if !store.activeFile}
|
||||||
|
<div class="page-container">
|
||||||
|
<header class="header">
|
||||||
|
<button class="back-btn" onclick={onBack}>←</button>
|
||||||
|
<h1>Печать</h1>
|
||||||
|
</header>
|
||||||
|
<main class="options">
|
||||||
|
{#if store.files.length === 0}
|
||||||
|
<PrintUI as="upload-zone" onSelect={() => fileInput.click()} />
|
||||||
|
{:else}
|
||||||
|
{#each store.files as file (file.id)}
|
||||||
|
<PrintUI
|
||||||
|
as="file-card"
|
||||||
|
{file}
|
||||||
|
onToggle={store.toggleExpand}
|
||||||
|
onRemove={store.removeFile}
|
||||||
|
onUpdate={store.updateFile}
|
||||||
|
onPreview={(f) => store.openPreview(f)}
|
||||||
|
onPageSelect={(f) => (f.fileType === 'pdf' ? store.openGallery(f) : store.openPreview(f))}
|
||||||
|
pagesLabel={store.pagesLabel}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
<button class="add-file-btn" onclick={() => fileInput.click()}>+ Добавить файлы</button>
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
|
<PrintUI
|
||||||
|
as="footer"
|
||||||
|
totalPrice={store.totalPrice}
|
||||||
|
filesCount={store.files.length}
|
||||||
|
extraCopies={store.extraCopies}
|
||||||
|
isPrinting={store.isPrinting}
|
||||||
|
onSubmit={store.openPayment}
|
||||||
|
hasTierSmall={hasTierSmall}
|
||||||
|
hasTierMedium={hasTierMedium}
|
||||||
|
hasTierLarge={hasTierLarge}
|
||||||
|
plFiles={plFiles}
|
||||||
|
plCopies={plCopies}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
bind:this={fileInput}
|
||||||
|
accept="image/*,.pdf,.doc,.docx,.odt,.xls,.xlsx,.ods,.ppt,.pptx,.odp"
|
||||||
|
multiple
|
||||||
|
onchange={handleFileSelect}
|
||||||
|
hidden
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
{#if !store.activeFile && !store.showPayment}
|
{#if !store.job}
|
||||||
<div class="page-container">
|
<PreviewOverlay {store} />
|
||||||
<header class="header">
|
|
||||||
<button class="back-btn" onclick={onBack}>←</button>
|
|
||||||
<h1>Печать</h1>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main class="options">
|
|
||||||
{#if store.files.length === 0}
|
|
||||||
<PrintUI as="upload-zone" onSelect={() => fileInput.click()} />
|
|
||||||
{:else}
|
|
||||||
{#each store.files as file (file.id)}
|
|
||||||
<PrintUI
|
|
||||||
as="file-card"
|
|
||||||
{file}
|
|
||||||
onToggle={store.toggleExpand}
|
|
||||||
onRemove={store.removeFile}
|
|
||||||
onUpdate={store.updateFile}
|
|
||||||
onPreview={(f) => store.openPreview(f)}
|
|
||||||
onPageSelect={(f) => (f.fileType === 'pdf' ? store.openGallery(f) : store.openPreview(f))}
|
|
||||||
pagesLabel={store.pagesLabel}
|
|
||||||
/>
|
|
||||||
{/each}
|
|
||||||
<button class="add-file-btn" onclick={() => fileInput.click()}>+ Добавить файлы</button>
|
|
||||||
{/if}
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<PrintUI
|
|
||||||
as="footer"
|
|
||||||
totalPrice={store.totalPrice}
|
|
||||||
filesCount={store.files.length}
|
|
||||||
extraCopies={store.extraCopies}
|
|
||||||
isPrinting={store.isPrinting}
|
|
||||||
onSubmit={store.openPayment}
|
|
||||||
hasTierSmall={hasTierSmall}
|
|
||||||
hasTierMedium={hasTierMedium}
|
|
||||||
hasTierLarge={hasTierLarge}
|
|
||||||
plFiles={plFiles}
|
|
||||||
plCopies={plCopies}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<!-- ✅ Расширенный accept -->
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
bind:this={fileInput}
|
|
||||||
accept="image/*,.pdf,.doc,.docx,.odt,.xls,.xlsx,.ods,.ppt,.pptx,.odp"
|
|
||||||
multiple
|
|
||||||
onchange={handleFileSelect}
|
|
||||||
hidden
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<PreviewOverlay {store} />
|
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.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; }
|
.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; }
|
||||||
.header { padding: 24px 20px 8px; display: flex; align-items: center; position: relative; }
|
.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 { background: none; border: none; color: #6366f1; font-size: 15px; font-weight: 600; cursor: pointer; padding: 8px 4px; margin-right: auto; min-height: 44px; }
|
||||||
.header h1 { margin: 0; font-size: 28px; font-weight: 700; position: absolute; left: 50%; transform: translateX(-50%); white-space: nowrap; }
|
.header h1 { margin: 0; font-size: 28px; font-weight: 700; position: absolute; left: 50%; transform: translateX(-50%); white-space: nowrap; }
|
||||||
.options { flex: 1; padding: 24px 20px 16px; display: flex; flex-direction: column; gap: 14px; }
|
.options { flex: 1; padding: 24px 20px 16px; display: flex; flex-direction: column; gap: 14px; }
|
||||||
.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; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
184
src/lib/pages/print/PrintProgress.svelte
Normal file
184
src/lib/pages/print/PrintProgress.svelte
Normal file
@ -0,0 +1,184 @@
|
|||||||
|
<!-- lib/pages/print/PrintProgress.svelte -->
|
||||||
|
<script>
|
||||||
|
|
||||||
|
const currentStatus = $derived.by(() => {
|
||||||
|
if (!store.job) return 'idle';
|
||||||
|
const f = store.job.files.find(f => f.status === 'printing');
|
||||||
|
if (f) return 'printing';
|
||||||
|
const q = store.job.files.find(f => f.status === 'queued');
|
||||||
|
return q ? 'queued' : store.job.phase;
|
||||||
|
});
|
||||||
|
|
||||||
|
let { store, onBack = () => {} } = $props();
|
||||||
|
|
||||||
|
const OFFICE_EXT = ['DOC', 'DOCX', 'ODT', 'XLS', 'XLSX', 'ODS', 'PPT', 'PPTX', 'ODP'];
|
||||||
|
const STATUS_LABEL = {
|
||||||
|
queued: 'В очереди',
|
||||||
|
printing: 'Печатается…',
|
||||||
|
awaiting: 'Далее',
|
||||||
|
done: 'Готово',
|
||||||
|
error: 'Ошибка',
|
||||||
|
cancelled: 'Отменено'
|
||||||
|
};
|
||||||
|
|
||||||
|
function badge(name) {
|
||||||
|
const e = (name.split('.').pop() || '').toUpperCase();
|
||||||
|
return OFFICE_EXT.includes(e) ? e : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Опрос статуса задания, пока оно активно
|
||||||
|
$effect(() => {
|
||||||
|
if (!store.jobActive) return;
|
||||||
|
const int = setInterval(() => store.refreshJob(), 1000);
|
||||||
|
return () => clearInterval(int);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Отмена удержанием (защита от миссклика) ──
|
||||||
|
const HOLD_MS = 1500;
|
||||||
|
let hold = $state(0);
|
||||||
|
let raf = 0;
|
||||||
|
let t0 = 0;
|
||||||
|
|
||||||
|
function startHold(e) {
|
||||||
|
if (!store.jobActive) return;
|
||||||
|
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>
|
||||||
|
|
||||||
|
<div class="page-container">
|
||||||
|
<header class="header">
|
||||||
|
<button class="back-btn" disabled={store.jobActive} onclick={finish}>←</button>
|
||||||
|
<h1>Печать</h1>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="list">
|
||||||
|
{#if store.job}
|
||||||
|
{#each store.job.files as f, i (i + '-' + f.name)}
|
||||||
|
{@const b = badge(f.name)}
|
||||||
|
<section class="file-card" class:current={f.status === 'awaiting' || f.status === 'printing'}>
|
||||||
|
<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'}
|
||||||
|
<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.jobActive}
|
||||||
|
{#if store.job?.phase === 'awaiting_pickup'}
|
||||||
|
<button class="next-btn" onclick={store.advanceJob}>Далее</button>
|
||||||
|
{:else}
|
||||||
|
<!-- Кнопка видна, но серая и disabled пока сервер не допечатал -->
|
||||||
|
<button class="next-btn next-btn-disabled" disabled>
|
||||||
|
{store.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>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.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; }
|
||||||
|
.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; }
|
||||||
|
.header h1 { margin: 0; font-size: 28px; font-weight: 700; position: absolute; left: 50%; transform: translateX(-50%); white-space: nowrap; }
|
||||||
|
|
||||||
|
.list { flex: 1; padding: 24px 20px 16px; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; }
|
||||||
|
|
||||||
|
.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); }
|
||||||
|
.file-row { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||||
|
.file-name { flex: 1; min-width: 0; font-size: 15px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.file-status { flex-shrink: 0; font-size: 14px; font-weight: 700; }
|
||||||
|
.st-done { color: #22c55e; }
|
||||||
|
.st-awaiting { color: #fbbf24; }
|
||||||
|
.st-printing { color: #a5b4fc; }
|
||||||
|
.st-queued { color: #8b93a1; }
|
||||||
|
.st-error { color: #ef4444; }
|
||||||
|
.st-cancelled { color: #6b7280; }
|
||||||
|
|
||||||
|
.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; }
|
||||||
|
|
||||||
|
.pickup-hint { margin: 0; padding-left: 22px; color: #eab308; font-size: 14px; line-height: 1.6; font-weight: 600; }
|
||||||
|
.file-error { margin: 0; color: #fca5a5; font-size: 12px; line-height: 1.4; }
|
||||||
|
|
||||||
|
.actions { padding: 16px 20px 32px; display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.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; }
|
||||||
|
|
||||||
|
.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); }
|
||||||
|
.next-btn-disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: wait;
|
||||||
|
pointer-events: none;
|
||||||
|
background: linear-gradient(135deg, #475569 0%, #64748b 100%);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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>
|
||||||
@ -1,5 +1,4 @@
|
|||||||
// lib/pages/print/store.svelte.js
|
// lib/pages/print/store.svelte.js
|
||||||
|
|
||||||
import { onDestroy, tick } from 'svelte';
|
import { onDestroy, tick } from 'svelte';
|
||||||
import { getPricePerPage } from '$lib/common/utils/pricing.util.js';
|
import { getPricePerPage } from '$lib/common/utils/pricing.util.js';
|
||||||
import { detectFileType, pagesLabel as _pagesLabel } from '$lib/common/utils/file.util.js';
|
import { detectFileType, pagesLabel as _pagesLabel } from '$lib/common/utils/file.util.js';
|
||||||
@ -14,261 +13,325 @@ 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 {{ job_id: string, phase: 'waiting_start'|'printing'|'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 uid = 0;
|
|
||||||
|
|
||||||
const totalPrice = $derived(
|
// ── Задание печати (страница прогресса) ──
|
||||||
files.reduce((sum, f) => {
|
let job = $state(/** @type {JobView | null} */ (null));
|
||||||
const pages = f.selectedPages?.size || 0;
|
let autoContinue = $state(false);
|
||||||
return sum + pages * f.copies * getPricePerPage(pages);
|
let advancing = false;
|
||||||
}, 0)
|
|
||||||
);
|
|
||||||
|
|
||||||
const extraCopies = $derived(files.reduce((sum, f) => sum + (f.copies - 1), 0));
|
const jobActive = $derived(!!job && job.phase !== 'finished' && job.phase !== 'cancelled');
|
||||||
|
|
||||||
function updateFile(id, changes) {
|
let uid = 0;
|
||||||
files = files.map((f) => (f.id === id ? { ...f, ...changes } : f));
|
|
||||||
if (activeFile?.id === id) {
|
|
||||||
activeFile = files.find((f) => f.id === id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ensurePdfLoaded(entry) {
|
const totalPrice = $derived(
|
||||||
if (entry.pdfDoc) return entry.pdfDoc;
|
files.reduce((sum, f) => {
|
||||||
const pdf = await loadPdfDocument(entry.file);
|
const pages = f.selectedPages?.size || 0;
|
||||||
if (pdf) {
|
return sum + pages * f.copies * getPricePerPage(pages);
|
||||||
const numPages = pdf.numPages;
|
}, 0)
|
||||||
updateFile(entry.id, {
|
);
|
||||||
pdfDoc: pdf,
|
const extraCopies = $derived(files.reduce((sum, f) => sum + (f.copies - 1), 0));
|
||||||
totalPages: numPages,
|
|
||||||
selectedPages: new Set(Array.from({ length: numPages }, (_, i) => i + 1))
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
updateFile(entry.id, { totalPages: 0 });
|
|
||||||
}
|
|
||||||
return pdf;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function addFiles(fileList) {
|
function updateFile(id, changes) {
|
||||||
if (!fileList || fileList.length === 0) return;
|
files = files.map((f) => (f.id === id ? { ...f, ...changes } : f));
|
||||||
const newFiles = [];
|
if (activeFile?.id === id) {
|
||||||
|
activeFile = files.find((f) => f.id === id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (let i = 0; i < fileList.length; i++) {
|
async function ensurePdfLoaded(entry) {
|
||||||
const file = fileList[i];
|
if (entry.pdfDoc) return entry.pdfDoc;
|
||||||
const fType = detectFileType(file);
|
const pdf = await loadPdfDocument(entry.file);
|
||||||
const isOffice = fType === 'office';
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
newFiles.push({
|
async function addFiles(fileList) {
|
||||||
id: ++uid,
|
if (!fileList || fileList.length === 0) return;
|
||||||
file,
|
const newFiles = [];
|
||||||
// Для офисных файлов превью не создаём
|
for (let i = 0; i < fileList.length; i++) {
|
||||||
previewUrl: isOffice ? null : URL.createObjectURL(file),
|
const file = fileList[i];
|
||||||
fileType: fType,
|
const fType = detectFileType(file);
|
||||||
expanded: false,
|
const isOffice = fType === 'office';
|
||||||
format: 'Авто',
|
newFiles.push({
|
||||||
colorMode: 'bw',
|
id: ++uid,
|
||||||
qualityIndex: 1,
|
file,
|
||||||
copies: 1,
|
previewUrl: isOffice ? null : URL.createObjectURL(file),
|
||||||
sides: 'Односторонняя',
|
fileType: fType,
|
||||||
dpi: 'Авто',
|
expanded: false,
|
||||||
// Для офисных файлов: 1 «страница» для расчёта цены,
|
format: 'Авто',
|
||||||
// реальное кол-во определит CUPS
|
colorMode: 'bw',
|
||||||
totalPages: (fType === 'image' || isOffice) ? 1 : 0,
|
qualityIndex: 1,
|
||||||
selectedPages: (fType === 'image' || isOffice) ? new Set([1]) : new Set(),
|
copies: 1,
|
||||||
pdfDoc: null
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
files = [...files, ...newFiles];
|
function removeFile(id) {
|
||||||
|
const f = files.find((x) => x.id === id);
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
|
||||||
for (const entry of newFiles) {
|
async function openGallery(entry) {
|
||||||
if (entry.fileType === 'pdf') ensurePdfLoaded(entry);
|
activeFile = entry;
|
||||||
// office и image — ничего дополнительно не загружаем
|
viewMode = 'gallery';
|
||||||
}
|
galleryThumbnails = [];
|
||||||
}
|
galleryLoading = true;
|
||||||
|
previewPagesCache = {};
|
||||||
|
await tick();
|
||||||
|
const pdf = await ensurePdfLoaded(entry);
|
||||||
|
if (!pdf || entry.totalPages === 0) {
|
||||||
|
galleryLoading = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const thumbs = [];
|
||||||
|
for (let i = 1; i <= entry.totalPages; i++) {
|
||||||
|
try {
|
||||||
|
thumbs.push(await renderPageToImage(pdf, i, 0.4));
|
||||||
|
} catch {
|
||||||
|
thumbs.push('');
|
||||||
|
}
|
||||||
|
galleryThumbnails = [...thumbs];
|
||||||
|
}
|
||||||
|
galleryLoading = false;
|
||||||
|
}
|
||||||
|
|
||||||
function removeFile(id) {
|
async function openPreview(entry) {
|
||||||
const f = files.find((x) => x.id === id);
|
activeFile = entry;
|
||||||
if (f?.previewUrl) URL.revokeObjectURL(f.previewUrl);
|
viewMode = 'preview';
|
||||||
files = files.filter((x) => x.id !== id);
|
previewPagesCache = {};
|
||||||
}
|
galleryThumbnails = [];
|
||||||
|
await tick();
|
||||||
|
if (entry.fileType === 'pdf') {
|
||||||
|
const pdf = await ensurePdfLoaded(entry);
|
||||||
|
if (pdf && entry.totalPages > 0) {
|
||||||
|
preloadPreviewPages(entry, 1, 5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function toggleExpand(id) {
|
async function preloadPreviewPages(entry, startPage, count) {
|
||||||
updateFile(id, { expanded: !files.find((f) => f.id === id)?.expanded });
|
const currentFile = files.find((f) => f.id === entry.id);
|
||||||
}
|
const pdf = currentFile?.pdfDoc || entry.pdfDoc;
|
||||||
|
if (!pdf || isPreviewRendering) return;
|
||||||
|
isPreviewRendering = true;
|
||||||
|
const endPage = Math.min(startPage + count - 1, entry.totalPages);
|
||||||
|
const newCache = {};
|
||||||
|
for (let i = startPage; i <= endPage; i++) {
|
||||||
|
if (previewPagesCache[i]) continue;
|
||||||
|
try {
|
||||||
|
newCache[i] = await renderPageToImage(pdf, i, 1.5);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`Failed to render preview page ${i}`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Object.keys(newCache).length > 0) {
|
||||||
|
previewPagesCache = { ...previewPagesCache, ...newCache };
|
||||||
|
}
|
||||||
|
isPreviewRendering = false;
|
||||||
|
}
|
||||||
|
|
||||||
async function openGallery(entry) {
|
function togglePageSelection(pageNum) {
|
||||||
activeFile = entry;
|
if (!activeFile?.selectedPages) return;
|
||||||
viewMode = 'gallery';
|
const newSet = new Set(activeFile.selectedPages);
|
||||||
galleryThumbnails = [];
|
if (newSet.has(pageNum)) {
|
||||||
galleryLoading = true;
|
if (newSet.size > 1) newSet.delete(pageNum);
|
||||||
previewPagesCache = {};
|
} else {
|
||||||
await tick();
|
newSet.add(pageNum);
|
||||||
|
}
|
||||||
|
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]) });
|
||||||
|
}
|
||||||
|
|
||||||
const pdf = await ensurePdfLoaded(entry);
|
// ─────────────── Отправка на печать + job-протокол ───────────────
|
||||||
if (!pdf || entry.totalPages === 0) {
|
|
||||||
galleryLoading = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const thumbs = [];
|
async function submitPrint() {
|
||||||
for (let i = 1; i <= entry.totalPages; i++) {
|
if (files.length === 0 || isPrinting) return;
|
||||||
try {
|
isPrinting = true;
|
||||||
thumbs.push(await renderPageToImage(pdf, i, 0.4));
|
const formData = new FormData();
|
||||||
} catch {
|
for (const f of files) {
|
||||||
thumbs.push('');
|
formData.append('files', f.file, f.file.name);
|
||||||
}
|
const pagesValue =
|
||||||
galleryThumbnails = [...thumbs];
|
f.fileType === 'office'
|
||||||
}
|
? 'all'
|
||||||
galleryLoading = false;
|
: 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 openPreview(entry) {
|
/** Подтверждение: старт первого файла / «забрал документ → печатай следующий» */
|
||||||
activeFile = entry;
|
async function advanceJob() {
|
||||||
viewMode = 'preview';
|
if (!job || advancing) return;
|
||||||
previewPagesCache = {};
|
advancing = true;
|
||||||
galleryThumbnails = [];
|
try {
|
||||||
await tick();
|
const res = await fetch(`/api/print/${job.job_id}/advance`, { method: 'POST' });
|
||||||
|
if (res.ok) job = await res.json();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('advance error:', e);
|
||||||
|
} finally {
|
||||||
|
advancing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (entry.fileType === 'pdf') {
|
/** Поллинг статуса; при autoContinue сами шлём подтверждение */
|
||||||
const pdf = await ensurePdfLoaded(entry);
|
async function refreshJob() {
|
||||||
if (pdf && entry.totalPages > 0) {
|
if (!job) return;
|
||||||
preloadPreviewPages(entry, 1, 5);
|
try {
|
||||||
}
|
const res = await fetch(`/api/print/${job.job_id}`);
|
||||||
}
|
if (!res.ok) return;
|
||||||
}
|
job = await res.json();
|
||||||
|
if (job.phase === 'waiting_start') {
|
||||||
|
advanceJob();
|
||||||
|
} else if (job.phase === 'awaiting_pickup' && autoContinue) {
|
||||||
|
advanceJob();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('refresh error:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function preloadPreviewPages(entry, startPage, count) {
|
async function cancelJob() {
|
||||||
const currentFile = files.find((f) => f.id === entry.id);
|
if (!job) return;
|
||||||
const pdf = currentFile?.pdfDoc || entry.pdfDoc;
|
try {
|
||||||
if (!pdf || isPreviewRendering) return;
|
const res = await fetch(`/api/print/${job.job_id}/cancel`, { method: 'POST' });
|
||||||
|
if (res.ok) job = await res.json();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('cancel error:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
isPreviewRendering = true;
|
function resetJob() {
|
||||||
const endPage = Math.min(startPage + count - 1, entry.totalPages);
|
job = null;
|
||||||
const newCache = {};
|
autoContinue = false;
|
||||||
|
files.forEach((f) => f.previewUrl && URL.revokeObjectURL(f.previewUrl));
|
||||||
|
files = [];
|
||||||
|
activeFile = null;
|
||||||
|
galleryThumbnails = [];
|
||||||
|
previewPagesCache = {};
|
||||||
|
showPayment = false;
|
||||||
|
}
|
||||||
|
|
||||||
for (let i = startPage; i <= endPage; i++) {
|
function setAutoContinue(v) {
|
||||||
if (previewPagesCache[i]) continue;
|
autoContinue = !!v;
|
||||||
try {
|
}
|
||||||
newCache[i] = await renderPageToImage(pdf, i, 1.5);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`Failed to render preview page ${i}`, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Object.keys(newCache).length > 0) {
|
onDestroy(() => {
|
||||||
previewPagesCache = { ...previewPagesCache, ...newCache };
|
files.forEach((f) => f.previewUrl && URL.revokeObjectURL(f.previewUrl));
|
||||||
}
|
});
|
||||||
isPreviewRendering = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function togglePageSelection(pageNum) {
|
return {
|
||||||
if (!activeFile?.selectedPages) return;
|
get files() { return files; },
|
||||||
const newSet = new Set(activeFile.selectedPages);
|
get activeFile() { return activeFile; },
|
||||||
if (newSet.has(pageNum)) {
|
get viewMode() { return viewMode; },
|
||||||
if (newSet.size > 1) newSet.delete(pageNum);
|
get showPayment() { return showPayment; },
|
||||||
} else {
|
get isPrinting() { return isPrinting; },
|
||||||
newSet.add(pageNum);
|
get totalPrice() { return totalPrice; },
|
||||||
}
|
get extraCopies() { return extraCopies; },
|
||||||
updateFile(activeFile.id, { selectedPages: newSet });
|
get galleryThumbnails() { return galleryThumbnails; },
|
||||||
}
|
get galleryLoading() { return galleryLoading; },
|
||||||
|
get previewPagesCache() { return previewPagesCache; },
|
||||||
function selectAllPages() {
|
get isPreviewRendering() { return isPreviewRendering; },
|
||||||
if (!activeFile?.totalPages) return;
|
get job() { return job; },
|
||||||
updateFile(activeFile.id, {
|
get jobActive() { return jobActive; },
|
||||||
selectedPages: new Set(Array.from({ length: activeFile.totalPages }, (_, i) => i + 1))
|
get autoContinue() { return autoContinue; },
|
||||||
});
|
addFiles,
|
||||||
}
|
removeFile,
|
||||||
|
toggleExpand,
|
||||||
function deselectAllPages() {
|
updateFile,
|
||||||
if (!activeFile) return;
|
openGallery,
|
||||||
updateFile(activeFile.id, { selectedPages: new Set([1]) });
|
openPreview,
|
||||||
}
|
closeOverlay: () => { activeFile = null; galleryThumbnails = []; previewPagesCache = {}; },
|
||||||
|
openPayment: () => { if (files.length > 0 && !isPrinting) showPayment = true; },
|
||||||
async function submitPrint() {
|
hidePayment: () => { showPayment = false; },
|
||||||
if (files.length === 0 || isPrinting) return;
|
submitPrint,
|
||||||
isPrinting = true;
|
advanceJob,
|
||||||
|
refreshJob,
|
||||||
const formData = new FormData();
|
cancelJob,
|
||||||
for (const f of files) {
|
resetJob,
|
||||||
formData.append('files', f.file, f.file.name);
|
setAutoContinue,
|
||||||
|
togglePageSelection,
|
||||||
// Для офисных файлов всегда отправляем все страницы —
|
selectAllPages,
|
||||||
// CUPS сам разберётся
|
deselectAllPages,
|
||||||
const pagesValue =
|
requestPreviewPages: (start, count) => { if (activeFile) preloadPreviewPages(activeFile, start, count); },
|
||||||
f.fileType === 'office'
|
pagesLabel: _pagesLabel
|
||||||
? '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();
|
|
||||||
alert(res.ok ? `✅ Успешно!\n${text}` : `❌ Ошибка (${res.status}):\n${text}`);
|
|
||||||
} catch {
|
|
||||||
alert('⚠️ Не удалось связаться с сервером печати.');
|
|
||||||
} finally {
|
|
||||||
isPrinting = false;
|
|
||||||
showPayment = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onDestroy(() => {
|
|
||||||
files.forEach((f) => f.previewUrl && URL.revokeObjectURL(f.previewUrl));
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
get files() { return files; },
|
|
||||||
get activeFile() { return activeFile; },
|
|
||||||
get viewMode() { return viewMode; },
|
|
||||||
get showPayment() { return showPayment; },
|
|
||||||
get isPrinting() { return isPrinting; },
|
|
||||||
get totalPrice() { return totalPrice; },
|
|
||||||
get extraCopies() { return extraCopies; },
|
|
||||||
get galleryThumbnails() { return galleryThumbnails; },
|
|
||||||
get galleryLoading() { return galleryLoading; },
|
|
||||||
get previewPagesCache() { return previewPagesCache; },
|
|
||||||
get isPreviewRendering() { return isPreviewRendering; },
|
|
||||||
addFiles,
|
|
||||||
removeFile,
|
|
||||||
toggleExpand,
|
|
||||||
updateFile,
|
|
||||||
openGallery,
|
|
||||||
openPreview,
|
|
||||||
closeOverlay: () => { activeFile = null; galleryThumbnails = []; previewPagesCache = {}; },
|
|
||||||
openPayment: () => { if (files.length > 0 && !isPrinting) showPayment = true; },
|
|
||||||
hidePayment: () => { showPayment = false; },
|
|
||||||
submitPrint,
|
|
||||||
togglePageSelection,
|
|
||||||
selectAllPages,
|
|
||||||
deselectAllPages,
|
|
||||||
requestPreviewPages: (start, count) => { if (activeFile) preloadPreviewPages(activeFile, start, count); },
|
|
||||||
pagesLabel: _pagesLabel
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user