This commit is contained in:
2026-09-18 21:30:02 +03:00
parent 51d86d49e3
commit bf6fc2ee88
4 changed files with 296 additions and 214 deletions

View File

@ -1,10 +1,9 @@
import * as pdfjsLib from 'pdfjs-dist'; import * as pdfjsLib from 'pdfjs-dist';
// Явно указываем путь к worker'у, чтобы избежать проблем с ?worker в PWA/Chromium // Используем ?url-импорт Vite — он корректно резолвится и в dev, и в prod
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL( import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url pdfjsLib.GlobalWorkerOptions.workerSrc = workerUrl;
).toString();
/** /**
* Загрузка PDF документа * Загрузка PDF документа
@ -39,7 +38,10 @@ export async function renderPageToImage(pdfDoc, pageNum, scale = 1.0) {
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

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

@ -250,21 +250,20 @@ export function createPrintStore() {
} }
} }
async function refreshJob() { async function refreshJob() {
if (!job) return; if (!job) return;
try { try {
const res = await fetch(`/api/print/${job.job_id}`); const res = await fetch(`/api/print/${job.job_id}`);
if (!res.ok) return; if (!res.ok) return;
job = await res.json(); job = await res.json();
// Автопродолжение срабатывает ТОЛЬКО для awaiting_pickup if (job.phase === 'awaiting_pickup' && autoContinue) {
if (job.phase === 'awaiting_pickup' && autoContinue) { advanceJob();
advanceJob(); }
} } catch (e) {
} catch (e) { console.error('refresh error:', e);
console.error('refresh error:', e); }
} }
}
async function cancelJob() { async function cancelJob() {
if (!job) return; if (!job) return;

View File

@ -23,7 +23,6 @@ export default defineConfig({
injectRegister: 'auto', injectRegister: 'auto',
workbox: { workbox: {
clientsClaim: true, clientsClaim: true,
// Добавили mjs, чтобы pdf.worker.min.mjs попадал в precache Нужно для PDFJS
globPatterns: ['**/*.{js,mjs,css,html,ico,png,svg,wasm}'], globPatterns: ['**/*.{js,mjs,css,html,ico,png,svg,wasm}'],
navigateFallbackDenylist: [/^\/api\/version/], navigateFallbackDenylist: [/^\/api\/version/],
runtimeCaching: [ runtimeCaching: [
@ -41,7 +40,6 @@ export default defineConfig({
} }
} }
}, },
// Fallback кэширование для worker-файлов, если они не попали в precache
{ {
urlPattern: /\/assets\/.*\.(mjs|js)$/, urlPattern: /\/assets\/.*\.(mjs|js)$/,
handler: 'CacheFirst', handler: 'CacheFirst',
@ -87,5 +85,17 @@ export default defineConfig({
rewrite: (path) => path.replace(/^\/api/, '') rewrite: (path) => path.replace(/^\/api/, '')
} }
} }
} },
build: {
target: 'esnext',
rollupOptions: {
output: {
format: 'es',
},
},
},
worker: {
format: 'es',
},
}) })