87 lines
2.5 KiB
TypeScript
87 lines
2.5 KiB
TypeScript
import type { PdfFile } from '../pdf/pdfTypes';
|
|
import type { MergeMode, MergeQueueItem } from './mergeTypes';
|
|
|
|
export function createMergeQueueItemId(): string {
|
|
return `merge_${Math.random().toString(36).slice(2)}`;
|
|
}
|
|
|
|
export function moveMergeQueueItem(
|
|
items: MergeQueueItem[],
|
|
itemId: string,
|
|
direction: 'up' | 'down'
|
|
): MergeQueueItem[] {
|
|
const index = items.findIndex((item) => item.id === itemId);
|
|
if (index < 0) return items;
|
|
|
|
const targetIndex = direction === 'up' ? index - 1 : index + 1;
|
|
if (targetIndex < 0 || targetIndex >= items.length) return items;
|
|
|
|
const next = [...items];
|
|
const [item] = next.splice(index, 1);
|
|
next.splice(targetIndex, 0, item);
|
|
return next;
|
|
}
|
|
|
|
export function getReadyMergeQueuePdfs(items: MergeQueueItem[]): PdfFile[] {
|
|
return items
|
|
.filter((item) => item.status === 'ready' && item.pdf)
|
|
.map((item) => item.pdf as PdfFile);
|
|
}
|
|
|
|
export function canMergeQueue(items: MergeQueueItem[]): boolean {
|
|
return (
|
|
items.length > 0 &&
|
|
items.every((item) => item.status === 'ready' && item.pdf !== null)
|
|
);
|
|
}
|
|
|
|
export function hasMergeQueueErrors(items: MergeQueueItem[]): boolean {
|
|
return items.some((item) => item.status === 'error');
|
|
}
|
|
|
|
export function isMergeQueueLoading(items: MergeQueueItem[]): boolean {
|
|
return items.some((item) => item.status === 'loading');
|
|
}
|
|
|
|
export function clampMergeInsertAt(value: string, pageCount: number): number {
|
|
const parsed = Number.parseInt(value, 10);
|
|
if (!Number.isFinite(parsed)) return pageCount;
|
|
|
|
return Math.min(Math.max(parsed - 1, 0), pageCount);
|
|
}
|
|
|
|
export function defaultMergeInsertPosition(pageCount: number): string {
|
|
return String(pageCount + 1);
|
|
}
|
|
|
|
export function createMergedPdfName(
|
|
currentPdfName: string | null,
|
|
incomingPdfNames: string[],
|
|
mode: MergeMode
|
|
): string {
|
|
const incomingBaseNames = incomingPdfNames.map(stripPdfExtension);
|
|
|
|
if (incomingBaseNames.length === 0) {
|
|
return currentPdfName ?? 'merged.pdf';
|
|
}
|
|
|
|
if (
|
|
incomingBaseNames.length === 1 &&
|
|
(!currentPdfName || mode === 'overwrite')
|
|
) {
|
|
return `${incomingBaseNames[0]}_merged.pdf`;
|
|
}
|
|
|
|
if (currentPdfName && mode !== 'overwrite') {
|
|
const currentBaseName = stripPdfExtension(currentPdfName);
|
|
return `${currentBaseName}_plus_${incomingBaseNames.length}_pdfs.pdf`;
|
|
}
|
|
|
|
return `merged_${incomingBaseNames.length}_pdfs.pdf`;
|
|
}
|
|
|
|
function stripPdfExtension(filename: string): string {
|
|
const base = filename.replace(/\.pdf$/i, '').trim();
|
|
return base || 'document';
|
|
}
|