add more documents format support
This commit is contained in:
@ -3,12 +3,23 @@
|
||||
/**
|
||||
* Определение типа файла
|
||||
* @param {File} file
|
||||
* @returns {'image' | 'pdf' | 'other'}
|
||||
* @returns {'image' | 'pdf' | 'office' | 'other'}
|
||||
*/
|
||||
export function detectFileType(file) {
|
||||
if (!file) return 'other';
|
||||
if (file.type.startsWith('image/')) return 'image';
|
||||
if (file.type === 'application/pdf') return 'pdf';
|
||||
|
||||
// Офисные документы — определяем по расширению,
|
||||
// т.к. MIME может быть пустым или некорректным
|
||||
const ext = (file.name || '').toLowerCase().split('.').pop() || '';
|
||||
const officeExts = [
|
||||
'doc', 'docx', 'odt', // текст
|
||||
'xls', 'xlsx', 'ods', // таблицы
|
||||
'ppt', 'pptx', 'odp', // презентации (на всякий случай)
|
||||
];
|
||||
if (officeExts.includes(ext)) return 'office';
|
||||
|
||||
return 'other';
|
||||
}
|
||||
|
||||
|
||||
@ -73,7 +73,15 @@
|
||||
plCopies={plCopies}
|
||||
/>
|
||||
|
||||
<input type="file" bind:this={fileInput} accept="image/*,.pdf" multiple onchange={handleFileSelect} hidden />
|
||||
<!-- ✅ Расширенный 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}
|
||||
|
||||
|
||||
@ -16,9 +16,7 @@
|
||||
/** @type {'button' | 'icon-button' | 'counter' | 'toggle-group' | 'file-card' | 'upload-zone' | 'footer'} */
|
||||
let { as, ...props } = $props();
|
||||
|
||||
// локально на экземпляр карточки файла
|
||||
let formatOpen = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (!props.file?.expanded) formatOpen = false;
|
||||
});
|
||||
@ -33,6 +31,11 @@
|
||||
if (!file.format || file.format === 'Авто') return `Авто (${file.autoFormat ?? 'A4'})`;
|
||||
return file.format;
|
||||
}
|
||||
|
||||
/** Является ли файл офисным документом */
|
||||
function isOffice(file) {
|
||||
return file?.fileType === 'office';
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if as === 'button'}
|
||||
@ -83,18 +86,63 @@
|
||||
<section class="file-card" class:expanded={file.expanded}>
|
||||
<div class="file-row" onclick={() => props.onToggle?.(file.id)}>
|
||||
<span class="chevron">{file.expanded ? '▼' : '►'}</span>
|
||||
|
||||
<!-- Бейдж типа файла -->
|
||||
{#if isOffice(file)}
|
||||
<span class="type-badge">
|
||||
{file.file.name.split('.').pop()?.toUpperCase() ?? 'DOC'}
|
||||
</span>
|
||||
{/if}
|
||||
|
||||
<span class="file-name" title={file.file.name}>{file.file.name}</span>
|
||||
|
||||
<span class="file-row-actions" onclick={(e) => e.stopPropagation()}>
|
||||
{#if file.previewUrl}
|
||||
<!-- Превью только для image/pdf -->
|
||||
{#if file.previewUrl && !isOffice(file)}
|
||||
<svelte:self as="icon-button" onclick={() => props.onPreview?.(file)} title="Предпросмотр">🔍</svelte:self>
|
||||
{/if}
|
||||
<svelte:self as="icon-button" variant="danger" onclick={() => props.onRemove?.(file.id)} title="Удалить">✕</svelte:self>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{#if file.expanded}
|
||||
<div class="file-options">
|
||||
<!-- 1. Кнопки с настройками -->
|
||||
<!-- 2. Переключатели — сразу под кнопками настроек -->
|
||||
|
||||
{#if isOffice(file)}
|
||||
<!-- ═══ Офисный документ: упрощённые настройки ═══ -->
|
||||
<p class="office-hint">
|
||||
Документ будет распечатан как есть — конвертация выполняется на сервере.
|
||||
</p>
|
||||
|
||||
<div class="duo-group">
|
||||
<div class="duo-row">
|
||||
<ToggleOption
|
||||
label="Печать"
|
||||
options={SIDES_OPTIONS}
|
||||
value={file.sides ?? 'Односторонняя'}
|
||||
onchange={(v) => props.onUpdate?.(file.id, { sides: v })}
|
||||
/>
|
||||
<ToggleOption
|
||||
label="Цветность"
|
||||
options={COLOR_LABELS}
|
||||
value={COLOR_LABELS[Math.max(0, COLOR_MODES.findIndex((c) => c.id === file.colorMode))]}
|
||||
onchange={(v, i) => props.onUpdate?.(file.id, { colorMode: COLOR_MODES[i]?.id })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="slider-options">
|
||||
<SliderOption
|
||||
label="Качество"
|
||||
options={QUALITY_LABELS}
|
||||
hint="Качество печати: влияет на расход тонера и время прогрева."
|
||||
value={QUALITIES[file.qualityIndex]?.label ?? QUALITY_LABELS[1] ?? QUALITY_LABELS[0]}
|
||||
onchange={(v) => props.onUpdate?.(file.id, { qualityIndex: QUALITY_LABELS.indexOf(v) })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{:else}
|
||||
<!-- ═══ Image / PDF: полные настройки ═══ -->
|
||||
<div class="duo-group">
|
||||
<div class="duo-row">
|
||||
<GearOption value={pagesText(file)} onclick={() => props.onPageSelect?.(file)} />
|
||||
@ -116,7 +164,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 3. Ползунки — ниже -->
|
||||
<div class="slider-options">
|
||||
<SliderOption
|
||||
label="Качество"
|
||||
@ -133,8 +180,9 @@
|
||||
onchange={(v) => props.onUpdate?.(file.id, { dpi: v })}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- 4. Количество — в конце -->
|
||||
<!-- Количество копий — для всех типов -->
|
||||
<div class="copies-row">
|
||||
<label class="option-title compact">Кол-во:</label>
|
||||
<svelte:self
|
||||
@ -147,6 +195,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- FormatPicker только для image/pdf -->
|
||||
{#if !isOffice(file)}
|
||||
<FormatPicker
|
||||
bind:open={formatOpen}
|
||||
options={FORMAT_OPTIONS}
|
||||
@ -154,6 +204,7 @@
|
||||
onselect={(v) => props.onUpdate?.(file.id, { format: v })}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
{:else if as === 'upload-zone'}
|
||||
@ -227,4 +278,31 @@
|
||||
.price-summary { display: flex; justify-content: space-between; align-items: baseline; width: 100%; }
|
||||
.summary-itogo { font-size: 30px; font-weight: 700; color: #8b93a1; }
|
||||
.summary-price { font-size: 38px; font-weight: 800; color: #fff; }
|
||||
|
||||
/* ── Бейдж типа файла (DOC, XLS, ODT…) ── */
|
||||
.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;
|
||||
}
|
||||
|
||||
/* ── Подсказка для офисных файлов ── */
|
||||
.office-hint {
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
background: rgba(251, 191, 36, 0.08);
|
||||
border: 1px solid rgba(251, 191, 36, 0.2);
|
||||
color: #d4a94e;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
</style>
|
||||
|
||||
@ -1,25 +1,30 @@
|
||||
// lib/pages/print/store.svelte.js
|
||||
|
||||
import { onDestroy, tick } from 'svelte';
|
||||
import { getPricePerPage } from '$lib/common/utils/pricing.util.js';
|
||||
import { detectFileType, pagesLabel as _pagesLabel } from '$lib/common/utils/file.util.js';
|
||||
import { loadPdfDocument, renderPageToImage } from '$lib/common/services/pdf.service.js';
|
||||
|
||||
/**
|
||||
* @typedef {{ id: number, file: File, previewUrl: string | null, fileType: 'image' | 'pdf' | 'other', expanded: boolean, format: 'A4' | 'A5', colorMode: 'bw' | 'color', qualityIndex: number, copies: number, totalPages: number, selectedPages: Set<number>, pdfDoc: any }} FileEntry
|
||||
* @typedef {{
|
||||
* id: number, file: File, previewUrl: string | null,
|
||||
* fileType: 'image' | 'pdf' | 'office' | 'other',
|
||||
* expanded: boolean, format: string, colorMode: string,
|
||||
* qualityIndex: number, copies: number, sides: string,
|
||||
* dpi: string, totalPages: number,
|
||||
* selectedPages: Set<number>, pdfDoc: any
|
||||
* }} FileEntry
|
||||
*/
|
||||
|
||||
export function createPrintStore() {
|
||||
let files = $state(/** @type {FileEntry[]} */ ([]));
|
||||
let activeFile = $state(/** @type {FileEntry | null} */ (null));
|
||||
let viewMode = $state(/** @type {'gallery' | 'preview'} */ ('gallery'));
|
||||
let showPayment = $state(false);
|
||||
let isPrinting = $state(false);
|
||||
|
||||
let galleryThumbnails = $state([]);
|
||||
let galleryLoading = $state(false);
|
||||
let previewPagesCache = $state({});
|
||||
let isPreviewRendering = $state(false);
|
||||
|
||||
let uid = 0;
|
||||
|
||||
const totalPrice = $derived(
|
||||
@ -57,27 +62,38 @@ export function createPrintStore() {
|
||||
async function addFiles(fileList) {
|
||||
if (!fileList || fileList.length === 0) return;
|
||||
const newFiles = [];
|
||||
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const file = fileList[i];
|
||||
const fType = detectFileType(file);
|
||||
const isOffice = fType === 'office';
|
||||
|
||||
newFiles.push({
|
||||
id: ++uid,
|
||||
file,
|
||||
previewUrl: URL.createObjectURL(file),
|
||||
// Для офисных файлов превью не создаём
|
||||
previewUrl: isOffice ? null : URL.createObjectURL(file),
|
||||
fileType: fType,
|
||||
expanded: false,
|
||||
format: 'A4',
|
||||
format: 'Авто',
|
||||
colorMode: 'bw',
|
||||
qualityIndex: 1,
|
||||
copies: 1,
|
||||
totalPages: fType === 'image' ? 1 : 0,
|
||||
selectedPages: fType === 'image' ? new Set([1]) : new Set(),
|
||||
sides: 'Односторонняя',
|
||||
dpi: 'Авто',
|
||||
// Для офисных файлов: 1 «страница» для расчёта цены,
|
||||
// реальное кол-во определит CUPS
|
||||
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);
|
||||
// office и image — ничего дополнительно не загружаем
|
||||
}
|
||||
}
|
||||
|
||||
@ -123,6 +139,7 @@ export function createPrintStore() {
|
||||
previewPagesCache = {};
|
||||
galleryThumbnails = [];
|
||||
await tick();
|
||||
|
||||
if (entry.fileType === 'pdf') {
|
||||
const pdf = await ensurePdfLoaded(entry);
|
||||
if (pdf && entry.totalPages > 0) {
|
||||
@ -181,20 +198,35 @@ export function createPrintStore() {
|
||||
async function submitPrint() {
|
||||
if (files.length === 0 || isPrinting) return;
|
||||
isPrinting = true;
|
||||
|
||||
const formData = new FormData();
|
||||
for (const f of files) {
|
||||
formData.append('files', f.file, f.file.name);
|
||||
|
||||
// Для офисных файлов всегда отправляем все страницы —
|
||||
// CUPS сам разберётся
|
||||
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: f.selectedPages ? Array.from(f.selectedPages).sort((a, b) => a - b).join(',') : 'all',
|
||||
pages: pagesValue,
|
||||
copies: f.copies,
|
||||
colorMode: f.colorMode,
|
||||
format: f.format
|
||||
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();
|
||||
@ -223,7 +255,6 @@ export function createPrintStore() {
|
||||
get galleryLoading() { return galleryLoading; },
|
||||
get previewPagesCache() { return previewPagesCache; },
|
||||
get isPreviewRendering() { return isPreviewRendering; },
|
||||
|
||||
addFiles,
|
||||
removeFile,
|
||||
toggleExpand,
|
||||
|
||||
Reference in New Issue
Block a user