adds ci/cd

This commit is contained in:
2026-07-22 21:28:50 +02:00
parent 0f7bb4b6eb
commit 44ca534cfa
13 changed files with 2040 additions and 185 deletions
@@ -1,11 +1,20 @@
<script lang="ts">
import AttachmentPreview from '$lib/components/AttachmentPreview.svelte';
import Button from '$lib/components/ui/button.svelte';
import SubDocumentEditor from '$lib/components/SubDocumentEditor.svelte';
import {
mergeProcessedZipArchive,
buildArchiveExport,
createSubDocument,
dissolveSubDocument,
moveAttachmentIntoSubDocument,
moveSubDocument,
type AttachmentLocation,
type ExportMode,
type ProcessedZipArchive,
type SubDocument,
type ZipAttachment
} from '$lib/zip-processing';
import { cn } from '$lib/utils';
type Props = {
archive: ProcessedZipArchive;
@@ -15,34 +24,276 @@
let { archive, thumbnailWidth = 200, onArchiveChange = () => {} }: Props = $props();
let attachments = $state<ZipAttachment[]>([]);
const ATTACHMENT_MIME = 'application/x-juri-merger-attachment';
let archiveName = $state('');
let looseAttachments = $state<ZipAttachment[]>([]);
let subDocuments = $state<SubDocument[]>([]);
let selectionMode = $state(false);
let selectedPaths = $state<Set<string>>(new Set());
let dragIndex = $state<number | null>(null);
let dropIndex = $state<number | null>(null);
let blockDragIndex = $state<number | null>(null);
let blockDropIndex = $state<number | null>(null);
let downloadMode = $state<ExportMode>('single');
let isMerging = $state(false);
let mergeError = $state<string | null>(null);
$effect(() => {
archiveName = archive.name;
looseAttachments = archive.attachments.map((attachment) => ({ ...attachment }));
subDocuments = archive.subDocuments.map((subDocument) => ({
...subDocument,
attachments: subDocument.attachments.map((attachment) => ({ ...attachment }))
}));
});
const toArrayBuffer = (bytes: Uint8Array) => {
const copy = new Uint8Array(bytes.byteLength);
copy.set(bytes);
return copy.buffer;
};
$effect(() => {
archiveName = archive.name;
attachments = archive.attachments.map((attachment) => ({ ...attachment }));
});
const normalizeFileName = (name: string) =>
name.toLowerCase().endsWith('.pdf') ? name : `${name}.pdf`;
const emitArchiveChange = () => {
onArchiveChange({
...archive,
name: archiveName,
attachments: attachments.map((attachment) => ({ ...attachment }))
});
const downloadPdfBytes = (bytes: Uint8Array, fileName: string) => {
const pdfBlob = new Blob([toArrayBuffer(bytes)], { type: 'application/pdf' });
const objectUrl = URL.createObjectURL(pdfBlob);
const downloadLink = document.createElement('a');
downloadLink.href = objectUrl;
downloadLink.download = normalizeFileName(fileName);
downloadLink.rel = 'noopener';
downloadLink.click();
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
};
const downloadMergedPdf = async () => {
if (attachments.length === 0 || isMerging) {
const composedArchive = (): ProcessedZipArchive => ({
...archive,
name: archiveName,
attachments: looseAttachments,
subDocuments
});
const emitArchiveChange = (nextArchive: ProcessedZipArchive) => {
archiveName = nextArchive.name;
looseAttachments = nextArchive.attachments;
subDocuments = nextArchive.subDocuments;
onArchiveChange(nextArchive);
};
const commit = () => {
onArchiveChange(composedArchive());
};
const hasSubDocuments = $derived(subDocuments.length > 0);
const toggleSelection = (path: string) => {
const next = new Set(selectedPaths);
if (next.has(path)) {
next.delete(path);
} else {
next.add(path);
}
selectedPaths = next;
};
const toggleSelectionMode = () => {
selectionMode = !selectionMode;
selectedPaths = new Set();
};
const exitSelectionMode = () => {
selectionMode = false;
selectedPaths = new Set();
};
const handleWindowKeydown = (event: KeyboardEvent) => {
if (event.key === 'Escape' && selectionMode) {
exitSelectionMode();
}
};
const createSubDocumentFromSelection = () => {
if (selectedPaths.size === 0) {
return;
}
const selectedAttachments = looseAttachments.filter((attachment) =>
selectedPaths.has(attachment.path)
);
const remainingAttachments = looseAttachments.filter(
(attachment) => !selectedPaths.has(attachment.path)
);
if (selectedAttachments.length === 0) {
return;
}
const subDocumentNumber = subDocuments.length + 1;
const nextSubDocument = createSubDocument(
`Teildokument ${subDocumentNumber}`,
selectedAttachments
);
looseAttachments = remainingAttachments;
subDocuments = [...subDocuments, nextSubDocument];
selectedPaths = new Set();
commit();
};
const dissolveSubDocumentBlock = (subDocumentId: string) => {
const nextArchive = dissolveSubDocument(composedArchive(), subDocumentId);
emitArchiveChange(nextArchive);
};
const handleSubDocumentChange = (next: SubDocument) => {
subDocuments = subDocuments.map((subDocument) =>
subDocument.id === next.id ? next : subDocument
);
commit();
};
const handleAttachmentMove = (source: AttachmentLocation, target: AttachmentLocation) => {
const nextArchive = moveAttachmentIntoSubDocument(composedArchive(), source, target);
emitArchiveChange(nextArchive);
};
const handleBlockDragStart = (blockIndex: number, _event: DragEvent) => {
blockDragIndex = blockIndex;
blockDropIndex = blockIndex;
};
const handleBlockDragOver = (blockIndex: number, _event: DragEvent) => {
blockDropIndex = blockIndex;
};
const handleBlockDrop = (blockIndex: number, _event: DragEvent) => {
if (blockDragIndex === null) {
return;
}
const fromIndex = blockDragIndex;
const nextArchive = moveSubDocument(composedArchive(), fromIndex, blockIndex);
emitArchiveChange(nextArchive);
blockDragIndex = null;
blockDropIndex = null;
};
const handleBlockDragEnd = () => {
blockDragIndex = null;
blockDropIndex = null;
};
const moveLooseAttachment = (fromIndex: number, toIndex: number) => {
if (
fromIndex === toIndex ||
fromIndex < 0 ||
toIndex < 0 ||
fromIndex >= looseAttachments.length ||
toIndex >= looseAttachments.length
) {
return;
}
const nextAttachments = [...looseAttachments];
const [movedAttachment] = nextAttachments.splice(fromIndex, 1);
nextAttachments.splice(toIndex, 0, movedAttachment);
looseAttachments = nextAttachments;
commit();
};
const handleLooseDragStart = (index: number, event: DragEvent) => {
if (selectionMode) {
event.preventDefault();
return;
}
dragIndex = index;
dropIndex = index;
const source: AttachmentLocation = { kind: 'loose', index };
if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData(ATTACHMENT_MIME, JSON.stringify(source));
event.dataTransfer.setData('text/plain', String(index));
}
};
const parseAttachmentPayload = (event: DragEvent): AttachmentLocation | null => {
const raw = event.dataTransfer?.getData(ATTACHMENT_MIME);
if (!raw) {
return null;
}
try {
const parsed = JSON.parse(raw) as AttachmentLocation;
if (parsed.kind === 'loose' || parsed.kind === 'subDocument') {
return parsed;
}
return null;
} catch {
return null;
}
};
const handleLooseDragOver = (index: number, event: DragEvent) => {
if (event.dataTransfer?.types.includes(ATTACHMENT_MIME)) {
event.preventDefault();
dropIndex = index;
}
};
const handleLooseDrop = (index: number, event: DragEvent) => {
const source = parseAttachmentPayload(event);
if (!source) {
return;
}
event.preventDefault();
if (source.kind === 'loose') {
moveLooseAttachment(source.index, index);
} else {
const nextArchive = moveAttachmentIntoSubDocument(composedArchive(), source, {
kind: 'loose',
index
});
emitArchiveChange(nextArchive);
}
dragIndex = null;
dropIndex = null;
};
const handleLooseDragEnd = () => {
dragIndex = null;
dropIndex = null;
};
const downloadArchive = async () => {
if (looseAttachments.length === 0 && subDocuments.length === 0) {
return;
}
if (isMerging) {
return;
}
@@ -50,85 +301,22 @@
mergeError = null;
try {
const mergedBytes = await mergeProcessedZipArchive({
...archive,
name: archiveName,
attachments: attachments.map((attachment) => ({ ...attachment }))
});
const exportUnits = await buildArchiveExport(composedArchive(), downloadMode);
const pdfBlob = new Blob([toArrayBuffer(mergedBytes)], { type: 'application/pdf' });
const objectUrl = URL.createObjectURL(pdfBlob);
const downloadLink = document.createElement('a');
downloadLink.href = objectUrl;
downloadLink.download = archiveName.toLowerCase().endsWith('.pdf')
? archiveName
: `${archiveName}.pdf`;
downloadLink.rel = 'noopener';
downloadLink.click();
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
for (const unit of exportUnits) {
downloadPdfBytes(unit.bytes, unit.name);
}
} catch (error) {
console.error(`Failed to merge archive ${archive.name}`, error);
console.error(`Failed to export archive ${archive.name}`, error);
mergeError = 'PDF konnte nicht erstellt werden.';
} finally {
isMerging = false;
}
};
const moveAttachment = (fromIndex: number, toIndex: number) => {
if (
fromIndex === toIndex ||
fromIndex < 0 ||
toIndex < 0 ||
fromIndex >= attachments.length ||
toIndex >= attachments.length
) {
return;
}
const nextAttachments = [...attachments];
const [movedAttachment] = nextAttachments.splice(fromIndex, 1);
nextAttachments.splice(toIndex, 0, movedAttachment);
attachments = nextAttachments;
emitArchiveChange();
};
const handleDragStart = (index: number, event: DragEvent) => {
dragIndex = index;
dropIndex = index;
if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData('text/plain', String(index));
}
};
const handleDragOver = (index: number, event: DragEvent) => {
event.preventDefault();
dropIndex = index;
};
const handleDrop = (index: number, event: DragEvent) => {
event.preventDefault();
const dataTransferIndex = Number(event.dataTransfer?.getData('text/plain'));
const fromIndex = Number.isFinite(dataTransferIndex) ? dataTransferIndex : dragIndex;
if (fromIndex === null) {
return;
}
moveAttachment(fromIndex, index);
dragIndex = null;
dropIndex = null;
};
const handleDragEnd = () => {
dragIndex = null;
dropIndex = null;
};
</script>
<svelte:window onkeydown={handleWindowKeydown} />
<section
class="flex flex-col gap-4 rounded-2xl border border-primary-100 bg-white px-4 py-4 shadow-sm"
>
@@ -140,25 +328,70 @@
class="w-full max-w-xl rounded-md border border-primary-200 bg-white px-3 py-2 text-[16px] font-bold text-primary-900 outline-none transition focus:border-primary-400 focus:ring-2 focus:ring-primary-200"
type="text"
value={archiveName}
draggable="false"
oninput={(event) => {
archiveName = (event.currentTarget as HTMLInputElement).value;
emitArchiveChange();
commit();
}}
/>
</label>
<p class="mt-1 text-[13px] text-primary">
{attachments.length} relevante Datei{attachments.length === 1 ? '' : 'en'}
{looseAttachments.length} lose Datei{looseAttachments.length === 1 ? '' : 'en'}
{#if hasSubDocuments}
· {subDocuments.length} Teildokument{subDocuments.length === 1 ? '' : 'e'}
{/if}
</p>
</div>
<Button
class="bg-primary"
type="button"
disabled={attachments.length === 0 || isMerging}
onclick={downloadMergedPdf}
>
{isMerging ? 'PDF wird erstellt' : 'PDF herunterladen'}
</Button>
<div class="flex flex-wrap items-center gap-2">
<Button
type="button"
variant={selectionMode ? 'secondary' : 'bordered'}
onclick={toggleSelectionMode}
>
{selectionMode ? 'Fertig' : 'Auswählen'}
</Button>
{#if hasSubDocuments}
<div
class="inline-flex items-center rounded-[16px] border border-primary-200 bg-white p-0.5"
role="radiogroup"
aria-label="Export-Modus"
>
{#each [{ value: 'single', label: 'Eine PDF' }, { value: 'separate', label: 'Getrennt' }] as option (option.value)}
<label
class={cn(
'cursor-pointer rounded-[14px] px-3 py-1 text-[13px] font-semibold transition',
downloadMode === option.value
? 'bg-primary text-primary-foreground'
: 'text-primary-700 hover:bg-primary-50'
)}
>
<input
class="sr-only"
type="radio"
name={`download-mode-${archive.name}`}
value={option.value}
checked={downloadMode === option.value}
onchange={() => {
downloadMode = option.value as ExportMode;
}}
/>
{option.label}
</label>
{/each}
</div>
{/if}
<Button
class="bg-primary"
type="button"
disabled={(looseAttachments.length === 0 && subDocuments.length === 0) || isMerging}
onclick={downloadArchive}
>
{isMerging ? 'PDF wird erstellt' : 'PDF herunterladen'}
</Button>
</div>
</header>
{#if mergeError}
@@ -167,38 +400,103 @@
</div>
{/if}
<ul class="flex gap-3 overflow-x-auto pb-1">
{#each attachments as attachment, index (attachment.path)}
<li
class={`flex flex-col shrink-0 items-stretch gap-2 rounded-xl border text-primary bg-accent p-2 ${
dropIndex === index ? 'border-primary-400 ring-1 ring-primary-200' : 'border-primary-100'
} ${dragIndex === index ? 'opacity-60' : ''}`}
style={`width: ${thumbnailWidth}px;`}
draggable="true"
ondragstart={(event) => handleDragStart(index, event)}
ondragover={(event) => handleDragOver(index, event)}
ondrop={(event) => handleDrop(index, event)}
ondragend={handleDragEnd}
>
<div class="flex min-w-0 flex-1 flex-row gap-2 py-1 items-baseline">
<button
class="w-fit cursor-grab rounded-md border border-primary-200 bg-white px-2 py-1 text-sm font-semibold leading-none text-primary-700 active:cursor-grabbing"
draggable="false"
type="button"
aria-label="Datei verschieben"
>
::
</button>
{#if selectionMode && selectedPaths.size > 0}
<div
class="flex flex-wrap items-center gap-3 rounded-xl border border-primary-200 bg-primary-50 px-4 py-2 text-[13px] font-medium text-primary-900"
>
<span>{selectedPaths.size} Datei{selectedPaths.size === 1 ? '' : 'en'} ausgewählt</span>
<Button type="button" onclick={createSubDocumentFromSelection}>Teildokument erstellen</Button>
</div>
{/if}
<div
class="truncate text-[13px] font-medium leading-tight text-primary-900"
title={attachment.name}
>
{attachment.name}
<ul class="flex gap-3 overflow-x-auto pb-1">
{#each looseAttachments as attachment, index (attachment.path)}
<li
class={cn(
'flex flex-col shrink-0 items-stretch gap-2 rounded-xl border bg-accent p-2 text-primary transition',
dropIndex === index ? 'border-primary-400 ring-1 ring-primary-200' : 'border-primary-100',
dragIndex === index ? 'opacity-60' : '',
selectedPaths.has(attachment.path) ? 'border-primary-500 ring-2 ring-primary-300' : ''
)}
style={`width: ${thumbnailWidth}px;`}
draggable={selectionMode ? 'false' : 'true'}
ondragstart={(event) => handleLooseDragStart(index, event)}
ondragover={(event) => handleLooseDragOver(index, event)}
ondrop={(event) => handleLooseDrop(index, event)}
ondragend={handleLooseDragEnd}
>
{#if selectionMode}
<label class="flex cursor-pointer flex-col gap-2">
<div class="flex items-center gap-2 px-1 text-[13px] font-medium text-primary-900">
<input
class="h-4 w-4 accent-primary-700"
type="checkbox"
checked={selectedPaths.has(attachment.path)}
onchange={() => toggleSelection(attachment.path)}
/>
<span class="truncate"
>{selectedPaths.has(attachment.path) ? 'Ausgewählt' : 'Auswählen'}</span
>
</div>
<div
class="truncate text-[13px] font-medium leading-tight text-primary-900"
title={attachment.name}
>
{attachment.name}
</div>
<AttachmentPreview {attachment} />
</label>
{:else}
<div class="flex min-w-0 flex-1 flex-row items-baseline gap-2 py-1">
<button
class="w-fit cursor-grab rounded-md border border-primary-200 bg-white px-2 py-1 text-sm font-semibold leading-none text-primary-700 active:cursor-grabbing"
draggable="false"
type="button"
aria-label="Datei verschieben"
>
::
</button>
<div
class="truncate text-[13px] font-medium leading-tight text-primary-900"
title={attachment.name}
>
{attachment.name}
</div>
</div>
</div>
<AttachmentPreview {attachment} />
<AttachmentPreview {attachment} />
{/if}
</li>
{/each}
</ul>
{#if looseAttachments.length === 0 && subDocuments.length === 0}
<div
class="rounded-md border border-dashed border-primary-200 bg-primary-50 px-4 py-4 text-[13px] text-primary-700"
>
Keine Dateien in diesem Archiv. Lade ein anderes ZIP, um weiterzuarbeiten.
</div>
{/if}
{#if hasSubDocuments}
<div class="flex flex-col gap-3">
{#each subDocuments as subDocument, blockIndex (subDocument.id)}
<SubDocumentEditor
{subDocument}
{blockIndex}
{thumbnailWidth}
isBlockDragSource={blockDragIndex === blockIndex}
isBlockDropTarget={blockDropIndex === blockIndex && blockDragIndex !== blockIndex}
onSubDocumentChange={handleSubDocumentChange}
onRemove={() => dissolveSubDocumentBlock(subDocument.id)}
onAttachmentMove={handleAttachmentMove}
onBlockDragStart={handleBlockDragStart}
onBlockDragOver={handleBlockDragOver}
onBlockDrop={handleBlockDrop}
onBlockDragEnd={handleBlockDragEnd}
/>
{/each}
</div>
{/if}
</section>
+286
View File
@@ -0,0 +1,286 @@
<script lang="ts">
import AttachmentPreview from '$lib/components/AttachmentPreview.svelte';
import type { AttachmentLocation, SubDocument, ZipAttachment } from '$lib/zip-processing';
import { cn } from '$lib/utils';
type Props = {
subDocument: SubDocument;
blockIndex: number;
thumbnailWidth: number;
isBlockDragSource?: boolean;
isBlockDropTarget?: boolean;
onSubDocumentChange?: (next: SubDocument) => void;
onRemove?: () => void;
onAttachmentMove?: (source: AttachmentLocation, target: AttachmentLocation) => void;
onBlockDragStart?: (blockIndex: number, event: DragEvent) => void;
onBlockDragOver?: (blockIndex: number, event: DragEvent) => void;
onBlockDrop?: (blockIndex: number, event: DragEvent) => void;
onBlockDragEnd?: () => void;
};
let {
subDocument,
blockIndex,
thumbnailWidth = 200,
isBlockDragSource = false,
isBlockDropTarget = false,
onSubDocumentChange = () => {},
onRemove = () => {},
onAttachmentMove = () => {},
onBlockDragStart = () => {},
onBlockDragOver = () => {},
onBlockDrop = () => {},
onBlockDragEnd = () => {}
}: Props = $props();
let subDocumentName = $state('');
let dragIndex = $state<number | null>(null);
let dropIndex = $state<number | null>(null);
$effect(() => {
subDocumentName = subDocument.name;
});
const emitChange = (overrides: Partial<SubDocument> = {}) => {
onSubDocumentChange({
...subDocument,
name: subDocumentName,
attachments: subDocument.attachments.map((attachment) => ({ ...attachment })),
...overrides
});
};
const ATTACHMENT_MIME = 'application/x-juri-merger-attachment';
const BLOCK_MIME = 'application/x-juri-merger-block';
const parseAttachmentPayload = (event: DragEvent): AttachmentLocation | null => {
const raw = event.dataTransfer?.getData(ATTACHMENT_MIME);
if (!raw) {
return null;
}
try {
const parsed = JSON.parse(raw) as AttachmentLocation;
if (parsed.kind === 'loose' || parsed.kind === 'subDocument') {
return parsed;
}
return null;
} catch {
return null;
}
};
const handleCardDragStart = (index: number, event: DragEvent) => {
dragIndex = index;
dropIndex = index;
const source: AttachmentLocation = {
kind: 'subDocument',
id: subDocument.id,
index
};
if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData(ATTACHMENT_MIME, JSON.stringify(source));
// keep a text/plain fallback so the drag is not silently cancelled
event.dataTransfer.setData('text/plain', String(index));
}
};
const handleCardDragOver = (index: number, event: DragEvent) => {
if (event.dataTransfer?.types.includes(ATTACHMENT_MIME)) {
event.preventDefault();
dropIndex = index;
}
};
const handleCardDrop = (index: number, event: DragEvent) => {
const source = parseAttachmentPayload(event);
if (!source) {
return;
}
event.preventDefault();
const target: AttachmentLocation = {
kind: 'subDocument',
id: subDocument.id,
index
};
onAttachmentMove(source, target);
dragIndex = null;
dropIndex = null;
};
const handleCardDragEnd = () => {
dragIndex = null;
dropIndex = null;
};
const handleNameInput = (event: Event) => {
subDocumentName = (event.currentTarget as HTMLInputElement).value;
emitChange();
};
const handleHeaderDragStart = (event: DragEvent) => {
// do not start a block drag when the user grabbed the remove button or name input
if (event.defaultPrevented) {
return;
}
if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData(BLOCK_MIME, String(blockIndex));
event.dataTransfer.setData('text/plain', String(blockIndex));
}
onBlockDragStart(blockIndex, event);
};
const handleHeaderDragOver = (event: DragEvent) => {
if (event.dataTransfer?.types.includes(BLOCK_MIME)) {
event.preventDefault();
onBlockDragOver(blockIndex, event);
}
};
const handleHeaderDrop = (event: DragEvent) => {
const raw = event.dataTransfer?.getData(BLOCK_MIME);
if (raw === undefined || raw === '') {
return;
}
event.preventDefault();
onBlockDrop(blockIndex, event);
};
const attachments: ZipAttachment[] = $derived(subDocument.attachments);
</script>
<section
class={cn(
'flex flex-col gap-3 rounded-xl border bg-primary-50/40 px-3 py-3 transition',
isBlockDropTarget ? 'border-primary-400 ring-1 ring-primary-200' : 'border-primary-100',
isBlockDragSource ? 'opacity-60' : ''
)}
>
<header class="flex flex-wrap items-center gap-2 text-primary">
<button
class="w-fit cursor-grab rounded-md border border-primary-200 bg-white px-2 py-1 text-sm font-semibold leading-none text-primary-700 active:cursor-grabbing"
draggable="true"
type="button"
aria-label="Teildokument verschieben"
ondragstart={handleHeaderDragStart}
ondragover={handleHeaderDragOver}
ondrop={handleHeaderDrop}
ondragend={onBlockDragEnd}
>
::
</button>
<label class="block min-w-0 flex-1">
<span class="sr-only">Teildokumentname</span>
<input
class="w-full max-w-md rounded-md border border-primary-200 bg-white px-3 py-1.5 text-[15px] font-semibold text-primary-900 outline-none transition focus:border-primary-400 focus:ring-2 focus:ring-primary-200"
type="text"
value={subDocumentName}
oninput={handleNameInput}
draggable="false"
/>
</label>
<span class="text-[13px] text-primary-700">
{attachments.length} Datei{attachments.length === 1 ? '' : 'en'}
</span>
<button
class="rounded-md border border-primary-200 bg-white px-2 py-1 text-[13px] font-medium text-primary-700 transition hover:border-red-300 hover:bg-red-50 hover:text-red-700"
type="button"
onclick={onRemove}
draggable="false"
ondragstart={(event) => event.preventDefault()}
>
Auflösen
</button>
</header>
{#if attachments.length === 0}
<ul
class="flex items-center justify-center rounded-md border border-dashed border-primary-200 bg-white/60 px-4 py-6 text-[13px] text-primary-600"
ondragover={(event) => {
if (event.dataTransfer?.types.includes(ATTACHMENT_MIME)) {
event.preventDefault();
}
}}
ondrop={(event) => {
const source = parseAttachmentPayload(event);
if (!source) {
return;
}
event.preventDefault();
const target: AttachmentLocation = {
kind: 'subDocument',
id: subDocument.id,
index: 0
};
onAttachmentMove(source, target);
dragIndex = null;
dropIndex = null;
}}
>
<li class="w-full text-center">
Dieses Teildokument ist leer. Ziehe Dateien hierher, um sie hinzuzufügen.
</li>
</ul>
{:else}
<ul class="flex gap-3 overflow-x-auto pb-1">
{#each attachments as attachment, index (attachment.path)}
<li
class={cn(
'flex flex-col shrink-0 items-stretch gap-2 rounded-xl border bg-accent p-2 text-primary',
dropIndex === index
? 'border-primary-400 ring-1 ring-primary-200'
: 'border-primary-100',
dragIndex === index ? 'opacity-60' : ''
)}
style={`width: ${thumbnailWidth}px;`}
draggable="true"
ondragstart={(event) => handleCardDragStart(index, event)}
ondragover={(event) => handleCardDragOver(index, event)}
ondrop={(event) => handleCardDrop(index, event)}
ondragend={handleCardDragEnd}
>
<div class="flex min-w-0 flex-1 flex-row items-baseline gap-2 py-1">
<button
class="w-fit cursor-grab rounded-md border border-primary-200 bg-white px-2 py-1 text-sm font-semibold leading-none text-primary-700 active:cursor-grabbing"
draggable="false"
type="button"
aria-label="Datei verschieben"
>
::
</button>
<div
class="truncate text-[13px] font-medium leading-tight text-primary-900"
title={attachment.name}
>
{attachment.name}
</div>
</div>
<AttachmentPreview {attachment} />
</li>
{/each}
</ul>
{/if}
</section>
+336 -6
View File
@@ -12,11 +12,33 @@ export type ZipAttachment = {
data: Uint8Array;
};
export type ProcessedZipArchive = {
export type SubDocument = {
id: string;
name: string;
attachments: ZipAttachment[];
};
export type ProcessedZipArchive = {
name: string;
attachments: ZipAttachment[];
subDocuments: SubDocument[];
};
export type ExportMode = 'single' | 'separate';
export type ExportUnit = {
name: string;
bytes: Uint8Array;
};
/**
* Drag source/target descriptors shared between the archive editor and the
* sub-document editor so HTML5 `dataTransfer` payloads stay consistent.
*/
export type AttachmentLocation =
| { kind: 'loose'; index: number }
| { kind: 'subDocument'; id: string; index: number };
const IMAGE_EXTENSIONS = new Set([
'.avif',
'.bmp',
@@ -172,7 +194,8 @@ const extractZipEntries = async (archiveBytes: Uint8Array): Promise<ProcessedZip
if (orderedAttachments.length > 0) {
archives.push({
name: archiveName,
attachments: orderedAttachments
attachments: orderedAttachments,
subDocuments: []
});
}
@@ -283,16 +306,323 @@ const mergeAttachmentIntoPdf = async (mergedPdf: PDFDocument, attachment: ZipAtt
}
};
export const mergeProcessedZipArchive = async (archive: ProcessedZipArchive) => {
if (archive.attachments.length === 0) {
throw new Error('Cannot create a PDF from an empty archive.');
export const mergeAttachments = async (attachments: ZipAttachment[]): Promise<Uint8Array> => {
if (attachments.length === 0) {
throw new Error('Cannot create a PDF from an empty attachment list.');
}
const mergedPdf = await PDFDocument.create();
for (const attachment of archive.attachments) {
for (const attachment of attachments) {
await mergeAttachmentIntoPdf(mergedPdf, attachment);
}
return mergedPdf.save();
};
export const mergeProcessedZipArchive = async (archive: ProcessedZipArchive) => {
if (archive.attachments.length === 0 && archive.subDocuments.length === 0) {
throw new Error('Cannot create a PDF from an empty archive.');
}
return mergeAttachments(flattenArchiveForMerge(archive));
};
/**
* Flatten the archive into a single ordered attachment list, preserving
* sub-document order first and appending loose attachments at the end.
*/
export const flattenArchiveForMerge = (archive: ProcessedZipArchive): ZipAttachment[] => {
const ordered: ZipAttachment[] = [];
for (const subDocument of archive.subDocuments) {
ordered.push(...subDocument.attachments);
}
ordered.push(...archive.attachments);
return ordered;
};
/**
* Create a new sub-document with a stable id from a list of attachments.
*/
export const createSubDocument = (name: string, attachments: ZipAttachment[]): SubDocument => ({
id: crypto.randomUUID(),
name,
attachments: attachments.map((attachment) => ({ ...attachment }))
});
/**
* Reorder sub-documents inside an archive. Matches the semantics of a single
* `splice(fromIndex, 1)` -> `splice(toIndex, 0, moved)` move.
*/
export const moveSubDocument = (
archive: ProcessedZipArchive,
fromIndex: number,
toIndex: number
): ProcessedZipArchive => {
if (
fromIndex === toIndex ||
fromIndex < 0 ||
toIndex < 0 ||
fromIndex >= archive.subDocuments.length ||
toIndex >= archive.subDocuments.length
) {
return archive;
}
const nextSubDocuments = [...archive.subDocuments];
const [movedSubDocument] = nextSubDocuments.splice(fromIndex, 1);
nextSubDocuments.splice(toIndex, 0, movedSubDocument);
return { ...archive, subDocuments: nextSubDocuments };
};
const removeAt = <T>(list: T[], index: number): T | null => {
if (index < 0 || index >= list.length) {
return null;
}
const [item] = list.splice(index, 1);
return item ?? null;
};
const insertAt = <T>(list: T[], index: number, item: T) => {
const clampedIndex = Math.max(0, Math.min(index, list.length));
list.splice(clampedIndex, 0, item);
};
/**
* Reorder an attachment within its current location (loose list or a single
* sub-document's attachment list). Used by the per-list drag handlers.
*/
export const moveAttachmentInPlace = (
archive: ProcessedZipArchive,
location: AttachmentLocation,
toIndex: number
): ProcessedZipArchive => {
if (location.kind === 'loose') {
const nextAttachments = [...archive.attachments];
const moved = removeAt(nextAttachments, location.index);
if (!moved) {
return archive;
}
insertAt(nextAttachments, toIndex, moved);
return { ...archive, attachments: nextAttachments };
}
let changed = false;
const nextSubDocuments = archive.subDocuments.map((subDocument) => {
if (subDocument.id !== location.id) {
return subDocument;
}
const nextAttachments = [...subDocument.attachments];
const moved = removeAt(nextAttachments, location.index);
if (!moved) {
return subDocument;
}
insertAt(nextAttachments, toIndex, moved);
changed = true;
return { ...subDocument, attachments: nextAttachments };
});
return changed ? { ...archive, subDocuments: nextSubDocuments } : archive;
};
/**
* Move an attachment from a source location to a target location. Either side
* may be the loose list or any sub-document. The attachment moves (not copies),
* so the total attachment count is invariant. When source and target point to
* the same list, this degenerates to an in-place reorder (explicitly delegated
* to `moveAttachmentInPlace` so the indices are normalized correctly).
*/
export const moveAttachmentIntoSubDocument = (
archive: ProcessedZipArchive,
source: AttachmentLocation,
target: AttachmentLocation
): ProcessedZipArchive => {
const sameList =
source.kind === 'loose' && target.kind === 'loose'
? true
: source.kind === 'subDocument' && target.kind === 'subDocument'
? source.id === target.id
: false;
if (sameList) {
return moveAttachmentInPlace(archive, source, target.index);
}
const nextSubDocuments = archive.subDocuments.map((subDocument) => ({
...subDocument,
attachments: [...subDocument.attachments]
}));
const looseAttachments = [...archive.attachments];
const removeFromList = (location: AttachmentLocation): ZipAttachment | null => {
if (location.kind === 'loose') {
return removeAt(looseAttachments, location.index);
}
const target_ = nextSubDocuments.find((item) => item.id === location.id);
return target_ ? removeAt(target_.attachments, location.index) : null;
};
const insertIntoList = (attachment: ZipAttachment, location: AttachmentLocation) => {
if (location.kind === 'loose') {
insertAt(looseAttachments, location.index, attachment);
return;
}
const target_ = nextSubDocuments.find((item) => item.id === location.id);
if (!target_) {
// fall back to loose list end if the referenced sub-document vanished
looseAttachments.push(attachment);
return;
}
insertAt(target_.attachments, location.index, attachment);
};
const movedAttachment = removeFromList(source);
if (!movedAttachment) {
return archive;
}
insertIntoList(movedAttachment, target);
return {
...archive,
attachments: looseAttachments,
subDocuments: nextSubDocuments
};
};
/**
* Remove a single attachment from a sub-document and return it to the end of
* the loose list. Useful as a targeted "move back to loose" action.
*/
export const removeAttachmentFromSubDocument = (
archive: ProcessedZipArchive,
subDocumentId: string,
attachmentIndex: number
): ProcessedZipArchive => {
const nextSubDocuments = archive.subDocuments.map((subDocument) => ({
...subDocument,
attachments: [...subDocument.attachments]
}));
const nextLooseAttachments = [...archive.attachments];
const target_ = nextSubDocuments.find((item) => item.id === subDocumentId);
if (!target_) {
return archive;
}
const moved = removeAt(target_.attachments, attachmentIndex);
if (!moved) {
return archive;
}
nextLooseAttachments.push(moved);
return {
...archive,
attachments: nextLooseAttachments,
subDocuments: nextSubDocuments
};
};
/**
* Remove an entire sub-document and return its attachments to the end of the
* loose list. The sub-document ids of the remaining sub-documents are
* preserved.
*/
export const dissolveSubDocument = (
archive: ProcessedZipArchive,
subDocumentId: string
): ProcessedZipArchive => {
const dissolved = archive.subDocuments.find((item) => item.id === subDocumentId);
if (!dissolved) {
return archive;
}
return {
...archive,
attachments: [...archive.attachments, ...dissolved.attachments],
subDocuments: archive.subDocuments.filter((item) => item.id !== subDocumentId)
};
};
const stripPdfExtension = (name: string) =>
name.toLowerCase().endsWith('.pdf') ? name.slice(0, -'.pdf'.length) : name;
/**
* Build one or more PDF export units from the archive.
*
* - `mode: 'single'` mirrors today's behaviour: one merged PDF covering
* sub-documents first, then loose attachments, named after the archive.
* - `mode: 'separate'` produces one PDF per sub-document (named
* `{archiveName} - {subDocumentName}.pdf`) plus a single merged PDF for any
* loose attachments (named after the archive). Empty groups are skipped.
*/
export const buildArchiveExport = async (
archive: ProcessedZipArchive,
mode: ExportMode
): Promise<ExportUnit[]> => {
if (mode === 'single') {
const attachments = flattenArchiveForMerge(archive);
if (attachments.length === 0) {
throw new Error('Cannot create a PDF from an empty archive.');
}
return [
{
name: stripPdfExtension(archive.name),
bytes: await mergeAttachments(attachments)
}
];
}
const separateUnits: ExportUnit[] = [];
for (const subDocument of archive.subDocuments) {
if (subDocument.attachments.length === 0) {
continue;
}
separateUnits.push({
name: `${stripPdfExtension(archive.name)} - ${stripPdfExtension(subDocument.name)}`,
bytes: await mergeAttachments(subDocument.attachments)
});
}
if (archive.attachments.length > 0) {
separateUnits.push({
name: stripPdfExtension(archive.name),
bytes: await mergeAttachments(archive.attachments)
});
}
if (separateUnits.length === 0) {
throw new Error('Cannot create a PDF from an empty archive.');
}
return separateUnits;
};