TSX rewrite and query strings initial set up

This commit is contained in:
Reece
2025-05-21 21:47:44 +01:00
parent 5f7a4e1664
commit 41c82b15da
22 changed files with 1228 additions and 610 deletions
+44
View File
@@ -0,0 +1,44 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { Button, Stack, Text, Group } from '@mantine/core';
const DeepLinks: React.FC = () => {
const commonLinks = [
{
name: "Split PDF Pages 1-5",
url: "/?tool=split&splitMode=byPages&pages=1-5&view=viewer",
description: "Split a PDF and extract pages 1-5"
},
{
name: "Compress PDF (High)",
url: "/?tool=compress&level=9&grayscale=true&view=viewer",
description: "Compress a PDF with high compression level"
},
{
name: "Merge PDFs",
url: "/?tool=merge&view=fileManager",
description: "Combine multiple PDF files into one"
}
];
return (
<Stack>
<Text fw={500}>Common PDF Operations</Text>
{commonLinks.map((link, index) => (
<Group key={index}>
<Button
component={Link}
to={link.url}
variant="subtle"
size="sm"
>
{link.name}
</Button>
<Text size="sm" color="dimmed">{link.description}</Text>
</Group>
))}
</Stack>
);
};
export default DeepLinks;
@@ -1,25 +1,34 @@
import React, { useState, useEffect } from "react";
import { Card, Group, Text, Stack, Image, Badge, Button, Box, Flex } from "@mantine/core";
import { Dropzone, MIME_TYPES } from "@mantine/dropzone";
import { GlobalWorkerOptions, getDocument, version as pdfjsVersion } from "pdfjs-dist";
GlobalWorkerOptions.workerSrc = `${process.env.PUBLIC_URL}/pdf.worker.js`;
import { GlobalWorkerOptions, getDocument } from "pdfjs-dist";
function getFileDate(file) {
GlobalWorkerOptions.workerSrc =
(import.meta as any).env?.PUBLIC_URL
? `${(import.meta as any).env.PUBLIC_URL}/pdf.worker.js`
: "/pdf.worker.js";
export interface FileWithUrl extends File {
url?: string;
file?: File;
}
function getFileDate(file: File): string {
if (file.lastModified) {
return new Date(file.lastModified).toLocaleString();
}
return "Unknown";
}
function getFileSize(file) {
function getFileSize(file: File): string {
if (!file.size) return "Unknown";
if (file.size < 1024) return `${file.size} B`;
if (file.size < 1024 * 1024) return `${(file.size / 1024).toFixed(1)} KB`;
return `${(file.size / (1024 * 1024)).toFixed(2)} MB`;
}
function usePdfThumbnail(file) {
const [thumb, setThumb] = useState(null);
function usePdfThumbnail(file: File | undefined | null): string | null {
const [thumb, setThumb] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
@@ -34,8 +43,10 @@ function usePdfThumbnail(file) {
canvas.width = viewport.width;
canvas.height = viewport.height;
const context = canvas.getContext("2d");
await page.render({ canvasContext: context, viewport }).promise;
if (!cancelled) setThumb(canvas.toDataURL());
if (context) {
await page.render({ canvasContext: context, viewport }).promise;
if (!cancelled) setThumb(canvas.toDataURL());
}
} catch {
if (!cancelled) setThumb(null);
}
@@ -47,7 +58,13 @@ function usePdfThumbnail(file) {
return thumb;
}
function FileCard({ file, onRemove, onDoubleClick }) {
interface FileCardProps {
file: File;
onRemove: () => void;
onDoubleClick?: () => void;
}
function FileCard({ file, onRemove, onDoubleClick }: FileCardProps) {
const thumb = usePdfThumbnail(file);
return (
@@ -59,7 +76,7 @@ function FileCard({ file, onRemove, onDoubleClick }) {
style={{ width: 225, minWidth: 180, maxWidth: 260, cursor: onDoubleClick ? "pointer" : undefined }}
onDoubleClick={onDoubleClick}
>
<Stack spacing={6} align="center">
<Stack gap={6} align="center">
<Box
style={{
border: "2px solid #e0e0e0",
@@ -76,13 +93,13 @@ function FileCard({ file, onRemove, onDoubleClick }) {
{thumb ? (
<Image src={thumb} alt="PDF thumbnail" height={110} width={80} fit="contain" radius="sm" />
) : (
<Image src="/images/pdf-placeholder.svg" alt="PDF" height={60} width={60} fit="contain" radius="sm" withPlaceholder />
<Image src="/images/pdf-placeholder.svg" alt="PDF" height={60} width={60} fit="contain" radius="sm" />
)}
</Box>
<Text weight={500} size="sm" lineClamp={1} align="center">
<Text fw={500} size="sm" lineClamp={1} ta="center">
{file.name}
</Text>
<Group spacing="xs" position="center">
<Group gap="xs" justify="center">
<Badge color="gray" variant="light" size="sm">
{getFileSize(file)}
</Badge>
@@ -104,12 +121,26 @@ function FileCard({ file, onRemove, onDoubleClick }) {
);
}
export default function FileManager({ files = [], setFiles, allowMultiple = true, setPdfFile, setCurrentView }) {
const handleDrop = (uploadedFiles) => {
interface FileManagerProps {
files: FileWithUrl[];
setFiles: React.Dispatch<React.SetStateAction<FileWithUrl[]>>;
allowMultiple?: boolean;
setPdfFile?: (fileObj: { file: File; url: string }) => void;
setCurrentView?: (view: string) => void;
}
const FileManager: React.FC<FileManagerProps> = ({
files = [],
setFiles,
allowMultiple = true,
setPdfFile,
setCurrentView,
}) => {
const handleDrop = (uploadedFiles: File[]) => {
setFiles((prevFiles) => (allowMultiple ? [...prevFiles, ...uploadedFiles] : uploadedFiles));
};
const handleRemoveFile = (index) => {
const handleRemoveFile = (index: number) => {
setFiles((prevFiles) => prevFiles.filter((_, i) => i !== index));
};
@@ -131,14 +162,14 @@ export default function FileManager({ files = [], setFiles, allowMultiple = true
justifyContent: "center",
}}
>
<Group position="center" spacing="xl" style={{ pointerEvents: "none" }}>
<Group justify="center" gap="xl" style={{ pointerEvents: "none" }}>
<Text size="md">
Drag PDF files here or click to select
</Text>
</Group>
</Dropzone>
{files.length === 0 ? (
<Text c="dimmed" align="center">
<Text c="dimmed" ta="center">
No files uploaded yet.
</Text>
) : (
@@ -155,11 +186,12 @@ export default function FileManager({ files = [], setFiles, allowMultiple = true
file={file}
onRemove={() => handleRemoveFile(idx)}
onDoubleClick={() => {
const fileObj = file.file || file; // handle wrapped or raw File
setPdfFile && setPdfFile({
file: fileObj,
url: URL.createObjectURL(fileObj),
});
const fileObj = (file as FileWithUrl).file || file;
setPdfFile &&
setPdfFile({
file: fileObj,
url: URL.createObjectURL(fileObj),
});
setCurrentView && setCurrentView("viewer");
}}
/>
@@ -169,4 +201,6 @@ export default function FileManager({ files = [], setFiles, allowMultiple = true
)}
</div>
);
}
};
export default FileManager;
-9
View File
@@ -1,9 +0,0 @@
import React from "react";
export default function PageEditor({ pdfFile }) {
return (
<div className="w-full h-full flex items-center justify-center">
<p className="text-gray-500">Page Editor is under construction.</p>
</div>
);
}
+196
View File
@@ -0,0 +1,196 @@
import React, { useState } from "react";
import {
Paper, Button, Group, Text, Stack, Center, Checkbox, ScrollArea, Box, Tooltip, ActionIcon, Notification
} from "@mantine/core";
import UndoIcon from "@mui/icons-material/Undo";
import RedoIcon from "@mui/icons-material/Redo";
import AddIcon from "@mui/icons-material/Add";
import ContentCutIcon from "@mui/icons-material/ContentCut";
import DownloadIcon from "@mui/icons-material/Download";
import RotateLeftIcon from "@mui/icons-material/RotateLeft";
import RotateRightIcon from "@mui/icons-material/RotateRight";
import DeleteIcon from "@mui/icons-material/Delete";
import ArrowBackIosNewIcon from "@mui/icons-material/ArrowBackIosNew";
import ArrowForwardIosIcon from "@mui/icons-material/ArrowForwardIos";
export interface PageEditorProps {
file: { file: File; url: string } | null;
setFile?: (file: { file: File; url: string } | null) => void;
downloadUrl?: string | null;
setDownloadUrl?: (url: string | null) => void;
}
const DUMMY_PAGE_COUNT = 8; // Replace with real page count from PDF
const PageEditor: React.FC<PageEditorProps> = ({
file,
setFile,
downloadUrl,
setDownloadUrl,
}) => {
const [selectedPages, setSelectedPages] = useState<number[]>([]);
const [status, setStatus] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [undoStack, setUndoStack] = useState<number[][]>([]);
const [redoStack, setRedoStack] = useState<number[][]>([]);
// Dummy page thumbnails
const pages = Array.from({ length: DUMMY_PAGE_COUNT }, (_, i) => i + 1);
const selectAll = () => setSelectedPages(pages);
const deselectAll = () => setSelectedPages([]);
const togglePage = (page: number) =>
setSelectedPages((prev) =>
prev.includes(page) ? prev.filter((p) => p !== page) : [...prev, page]
);
// Undo/redo logic for selection
const handleUndo = () => {
if (undoStack.length > 0) {
setRedoStack([selectedPages, ...redoStack]);
setSelectedPages(undoStack[0]);
setUndoStack(undoStack.slice(1));
}
};
const handleRedo = () => {
if (redoStack.length > 0) {
setUndoStack([selectedPages, ...undoStack]);
setSelectedPages(redoStack[0]);
setRedoStack(redoStack.slice(1));
}
};
// Example action handlers (replace with real API calls)
const handleRotateLeft = () => setStatus("Rotated left: " + selectedPages.join(", "));
const handleRotateRight = () => setStatus("Rotated right: " + selectedPages.join(", "));
const handleDelete = () => setStatus("Deleted: " + selectedPages.join(", "));
const handleMoveLeft = () => setStatus("Moved left: " + selectedPages.join(", "));
const handleMoveRight = () => setStatus("Moved right: " + selectedPages.join(", "));
const handleSplit = () => setStatus("Split at: " + selectedPages.join(", "));
const handleInsertPageBreak = () => setStatus("Inserted page break at: " + selectedPages.join(", "));
const handleAddFile = () => setStatus("Add file not implemented in demo");
if (!file) {
return (
<Paper shadow="xs" radius="md" p="md">
<Center>
<Text color="dimmed">No PDF loaded. Please upload a PDF to edit.</Text>
</Center>
</Paper>
);
}
return (
<Paper shadow="xs" radius="md" p="md">
<Group align="flex-start" gap="lg">
{/* Sidebar */}
<Stack w={180} gap="xs">
<Text fw={600} size="lg">PDF Multitool</Text>
<Button onClick={selectAll} fullWidth variant="light">Select All</Button>
<Button onClick={deselectAll} fullWidth variant="light">Deselect All</Button>
<Button onClick={handleUndo} leftSection={<UndoIcon fontSize="small" />} fullWidth disabled={undoStack.length === 0}>Undo</Button>
<Button onClick={handleRedo} leftSection={<RedoIcon fontSize="small" />} fullWidth disabled={redoStack.length === 0}>Redo</Button>
<Button onClick={handleAddFile} leftSection={<AddIcon fontSize="small" />} fullWidth>Add File</Button>
<Button onClick={handleInsertPageBreak} leftSection={<ContentCutIcon fontSize="small" />} fullWidth>Insert Page Break</Button>
<Button onClick={handleSplit} leftSection={<ContentCutIcon fontSize="small" />} fullWidth>Split</Button>
<Button
component="a"
href={downloadUrl || "#"}
download="edited.pdf"
leftSection={<DownloadIcon fontSize="small" />}
fullWidth
color="green"
variant="light"
disabled={!downloadUrl}
>
Download All
</Button>
<Button
component="a"
href={downloadUrl || "#"}
download="selected.pdf"
leftSection={<DownloadIcon fontSize="small" />}
fullWidth
color="blue"
variant="light"
disabled={!downloadUrl || selectedPages.length === 0}
>
Download Selected
</Button>
<Button
color="red"
variant="light"
onClick={() => setFile && setFile(null)}
fullWidth
>
Close PDF
</Button>
</Stack>
{/* Main multitool area */}
<Box style={{ flex: 1 }}>
<Group mb="sm">
<Tooltip label="Rotate Left">
<ActionIcon onClick={handleRotateLeft} disabled={selectedPages.length === 0} color="blue" variant="light">
<RotateLeftIcon />
</ActionIcon>
</Tooltip>
<Tooltip label="Rotate Right">
<ActionIcon onClick={handleRotateRight} disabled={selectedPages.length === 0} color="blue" variant="light">
<RotateRightIcon />
</ActionIcon>
</Tooltip>
<Tooltip label="Delete">
<ActionIcon onClick={handleDelete} disabled={selectedPages.length === 0} color="red" variant="light">
<DeleteIcon />
</ActionIcon>
</Tooltip>
<Tooltip label="Move Left">
<ActionIcon onClick={handleMoveLeft} disabled={selectedPages.length === 0} color="gray" variant="light">
<ArrowBackIosNewIcon />
</ActionIcon>
</Tooltip>
<Tooltip label="Move Right">
<ActionIcon onClick={handleMoveRight} disabled={selectedPages.length === 0} color="gray" variant="light">
<ArrowForwardIosIcon />
</ActionIcon>
</Tooltip>
</Group>
<ScrollArea h={350}>
<Group>
{pages.map((page) => (
<Stack key={page} align="center" gap={2}>
<Checkbox
checked={selectedPages.includes(page)}
onChange={() => togglePage(page)}
label={`Page ${page}`}
/>
<Box
w={60}
h={80}
bg={selectedPages.includes(page) ? "blue.1" : "gray.1"}
style={{ border: "1px solid #ccc", borderRadius: 4 }}
>
{/* Replace with real thumbnail */}
<Center h="100%">
<Text size="xs" color="dimmed">
{page}
</Text>
</Center>
</Box>
</Stack>
))}
</Group>
</ScrollArea>
</Box>
</Group>
{status && (
<Notification color="blue" mt="md" onClose={() => setStatus(null)}>
{status}
</Notification>
)}
</Paper>
);
};
export default PageEditor;
+76
View File
@@ -0,0 +1,76 @@
import React, { useState } from "react";
import { Box, Text, Stack, Button, TextInput } from "@mantine/core";
type Tool = {
icon: React.ReactNode;
name: string;
};
type ToolRegistry = {
[id: string]: Tool;
};
interface ToolPickerProps {
selectedToolKey: string;
onSelect: (id: string) => void;
toolRegistry: ToolRegistry;
}
const ToolPicker: React.FC<ToolPickerProps> = ({ selectedToolKey, onSelect, toolRegistry }) => {
const [search, setSearch] = useState("");
const filteredTools = Object.entries(toolRegistry).filter(([_, { name }]) =>
name.toLowerCase().includes(search.toLowerCase())
);
return (
<Box
style={{
width: 220,
background: "#f8f9fa",
borderRight: "1px solid #e9ecef",
minHeight: "100vh",
padding: 16,
position: "fixed",
left: 0,
top: 0,
bottom: 0,
zIndex: 100,
overflowY: "auto",
}}
>
<Text size="lg" fw={500} mb="md">
Tools
</Text>
<TextInput
placeholder="Search tools..."
value={search}
onChange={(e) => setSearch(e.currentTarget.value)}
mb="md"
autoComplete="off"
/>
<Stack gap="sm">
{filteredTools.length === 0 ? (
<Text c="dimmed" size="sm">
No tools found
</Text>
) : (
filteredTools.map(([id, { icon, name }]) => (
<Button
key={id}
variant={selectedToolKey === id ? "filled" : "subtle"}
onClick={() => onSelect(id)}
fullWidth
size="md"
radius="md"
>
{name}
</Button>
))
)}
</Stack>
</Box>
);
};
export default ToolPicker;
@@ -1,13 +1,18 @@
import React, { useEffect, useState } from "react";
import { Paper, Stack, Text, ScrollArea, Loader, Center, Button, Group } from "@mantine/core";
import { getDocument, GlobalWorkerOptions, version as pdfjsVersion } from "pdfjs-dist";
import { getDocument, GlobalWorkerOptions } from "pdfjs-dist";
GlobalWorkerOptions.workerSrc = `${process.env.PUBLIC_URL}/pdf.worker.js`;
export default function Viewer({ pdfFile, setPdfFile }) {
const [numPages, setNumPages] = useState(0);
const [pageImages, setPageImages] = useState([]);
const [loading, setLoading] = useState(false);
export interface ViewerProps {
pdfFile: { file: File; url: string } | null;
setPdfFile: (file: { file: File; url: string } | null) => void;
}
const Viewer: React.FC<ViewerProps> = ({ pdfFile, setPdfFile }) => {
const [numPages, setNumPages] = useState<number>(0);
const [pageImages, setPageImages] = useState<string[]>([]);
const [loading, setLoading] = useState<boolean>(false);
useEffect(() => {
let cancelled = false;
@@ -21,7 +26,7 @@ export default function Viewer({ pdfFile, setPdfFile }) {
try {
const pdf = await getDocument(pdfFile.url).promise;
setNumPages(pdf.numPages);
const images = [];
const images: string[] = [];
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 1.2 });
@@ -29,8 +34,10 @@ export default function Viewer({ pdfFile, setPdfFile }) {
canvas.width = viewport.width;
canvas.height = viewport.height;
const ctx = canvas.getContext("2d");
await page.render({ canvasContext: ctx, viewport }).promise;
images.push(canvas.toDataURL());
if (ctx) {
await page.render({ canvasContext: ctx, viewport }).promise;
images.push(canvas.toDataURL());
}
}
if (!cancelled) setPageImages(images);
} catch {
@@ -59,7 +66,7 @@ export default function Viewer({ pdfFile, setPdfFile }) {
accept="application/pdf"
hidden
onChange={(e) => {
const file = e.target.files[0];
const file = e.target.files?.[0];
if (file && file.type === "application/pdf") {
const fileUrl = URL.createObjectURL(file);
setPdfFile({ file, url: fileUrl });
@@ -75,7 +82,7 @@ export default function Viewer({ pdfFile, setPdfFile }) {
</Center>
) : (
<ScrollArea style={{ flex: 1, height: "100%" }}>
<Stack spacing="xl" align="center">
<Stack gap="xl" align="center">
{pageImages.length === 0 && (
<Text color="dimmed">No pages to display.</Text>
)}
@@ -97,7 +104,7 @@ export default function Viewer({ pdfFile, setPdfFile }) {
</ScrollArea>
)}
{pdfFile && (
<Group position="right" mt="md">
<Group justify="flex-end" mt="md">
<Button
variant="light"
color="red"
@@ -109,4 +116,6 @@ export default function Viewer({ pdfFile, setPdfFile }) {
)}
</Paper>
);
}
};
export default Viewer;