Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): add document searchable content view and edit (#230)

Joshua Anderson38aa1ea7f1fd
diff --git a/apps/papra-client/src/modules/demo/demo-api-mock.ts b/apps/papra-client/src/modules/demo/demo-api-mock.ts
index 0954bdd8..a6c691db 100644
--- a/apps/papra-client/src/modules/demo/demo-api-mock.ts
+++ b/apps/papra-client/src/modules/demo/demo-api-mock.ts
@@ -120,6 +120,7 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
originalName: file.name,
originalSize: file.size,
mimeType: file.type,
+ content: '',
createdAt: new Date(),
updatedAt: new Date(),
tags: [],
diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.ts
index 7f5ac45b..b73cdc1f 100644
--- a/apps/papra-client/src/modules/documents/documents.services.ts
+++ b/apps/papra-client/src/modules/documents/documents.services.ts
@@ -208,3 +208,27 @@ export async function deleteTrashDocument({ documentId, organizationId }: { docu
path: `/api/organizations/${organizationId}/documents/trash/${documentId}`,
});
}
+
+export async function updateDocument({
+ documentId,
+ organizationId,
+ content,
+}: {
+ documentId: string;
+ organizationId: string;
+ content: string;
+}) {
+ const { document } = await apiClient<{ document: Document }>({
+ method: 'PATCH',
+ path: `/api/organizations/${organizationId}/documents/${documentId}`,
+ body: { content },
+ });
+
+ return {
+ document: {
+ ...document,
+ createdAt: new Date(document.createdAt),
+ updatedAt: document.updatedAt ? new Date(document.updatedAt) : undefined,
+ },
+ };
+}
diff --git a/apps/papra-client/src/modules/documents/documents.types.ts b/apps/papra-client/src/modules/documents/documents.types.ts
index 0d9f6e14..023e93ce 100644
--- a/apps/papra-client/src/modules/documents/documents.types.ts
+++ b/apps/papra-client/src/modules/documents/documents.types.ts
@@ -11,5 +11,6 @@ export type Document = {
isDeleted?: boolean;
deletedAt?: Date;
deletedBy?: string;
+ content: string;
tags: Tag[];
};
diff --git a/apps/papra-client/src/modules/documents/pages/document.page.tsx b/apps/papra-client/src/modules/documents/pages/document.page.tsx
index 7c0aaf31..ef5cd81a 100644
--- a/apps/papra-client/src/modules/documents/pages/document.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/document.page.tsx
@@ -2,20 +2,26 @@ import { useConfig } from '@/modules/config/config.provider';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { timeAgo } from '@/modules/shared/date/time-ago';
import { downloadFile } from '@/modules/shared/files/download';
+import { queryClient } from '@/modules/shared/query/query-client';
import { DocumentTagPicker } from '@/modules/tags/components/tag-picker.component';
import { CreateTagModal } from '@/modules/tags/pages/tags.page';
import { addTagToDocument, removeTagFromDocument } from '@/modules/tags/tags.services';
import { Alert } from '@/modules/ui/components/alert';
import { Button } from '@/modules/ui/components/button';
import { Separator } from '@/modules/ui/components/separator';
-import { formatBytes } from '@corentinth/chisels';
+import { createToast } from '@/modules/ui/components/sonner';
+import { Tabs, TabsContent, TabsIndicator, TabsList, TabsTrigger } from '@/modules/ui/components/tabs';
+import { TextArea } from '@/modules/ui/components/textarea';
+import { TextFieldRoot } from '@/modules/ui/components/textfield';
+import { formatBytes, safely } from '@corentinth/chisels';
import { useNavigate, useParams } from '@solidjs/router';
import { createQueries } from '@tanstack/solid-query';
import { type Component, For, type JSX, Show, Suspense } from 'solid-js';
+import { createSignal } from 'solid-js';
import { DocumentPreview } from '../components/document-preview.component';
import { getDaysBeforePermanentDeletion } from '../document.models';
import { useDeleteDocument, useRestoreDocument } from '../documents.composables';
-import { fetchDocument, fetchDocumentFile } from '../documents.services';
+import { fetchDocument, fetchDocumentFile, updateDocument } from '../documents.services';
import '@pdfslick/solid/dist/pdf_viewer.css';
type KeyValueItem = {
@@ -85,6 +91,44 @@ export const DocumentPage: Component = () => {
const getDataUrl = () => queries[1].data ? URL.createObjectURL(queries[1].data) : undefined;
+ const [isEditing, setIsEditing] = createSignal(false);
+ const [editedContent, setEditedContent] = createSignal('');
+ const [isSaving, setIsSaving] = createSignal(false);
+
+ const handleEdit = () => {
+ setEditedContent(queries[0].data?.document.content ?? '');
+ setIsEditing(true);
+ };
+
+ const handleCancel = () => {
+ setIsEditing(false);
+ setEditedContent('');
+ };
+
+ const handleSave = async () => {
+ if (!queries[0].data?.document) {
+ return;
+ }
+
+ setIsSaving(true);
+ const [, error] = await safely(updateDocument({
+ documentId: queries[0].data.document.id,
+ organizationId: params.organizationId,
+ content: editedContent(),
+ }));
+ setIsSaving(false);
+ setIsEditing(false);
+
+ if (error) {
+ createToast({ type: 'error', message: 'Failed to update document content' });
+ return;
+ }
+ createToast({ type: 'success', message: 'Document content updated' });
+ await queryClient.invalidateQueries({
+ queryKey: ['organizations', params.organizationId, 'documents', params.documentId],
+ });
+ };
+
return (
<div class="p-6 flex gap-6 h-full flex-col md:flex-row max-w-7xl mx-auto">
<Suspense>
@@ -185,41 +229,88 @@ export const DocumentPage: Component = () => {
</Alert>
)}
- <Separator class="my-6" />
-
- <KeyValues data={[
- {
- label: 'ID',
- value: getDocument().id,
- icon: 'i-tabler-id',
- },
- {
- label: 'Name',
- value: getDocument().name,
- icon: 'i-tabler-file-text',
- },
- {
- label: 'Type',
- value: getDocument().mimeType,
- icon: 'i-tabler-file-unknown',
- },
- {
- label: 'Size',
- value: formatBytes({ bytes: getDocument().originalSize, base: 1000 }),
- icon: 'i-tabler-weight',
- },
- {
- label: 'Created At',
- value: timeAgo({ date: getDocument().createdAt }),
- icon: 'i-tabler-calendar',
- },
- {
- label: 'Updated At',
- value: getDocument().updatedAt ? timeAgo({ date: getDocument().updatedAt! }) : <span class="text-muted-foreground">Never</span>,
- icon: 'i-tabler-calendar',
- },
- ]}
- />
+ <Separator class="my-3" />
+
+ <Tabs defaultValue="info" class="w-full">
+ <TabsList class="w-full h-8">
+ <TabsTrigger value="info">Info</TabsTrigger>
+ <TabsTrigger value="content">Content</TabsTrigger>
+ <TabsIndicator />
+ </TabsList>
+
+ <TabsContent value="info">
+ <KeyValues data={[
+ {
+ label: 'ID',
+ value: getDocument().id,
+ icon: 'i-tabler-id',
+ },
+ {
+ label: 'Name',
+ value: getDocument().name,
+ icon: 'i-tabler-file-text',
+ },
+ {
+ label: 'Type',
+ value: getDocument().mimeType,
+ icon: 'i-tabler-file-unknown',
+ },
+ {
+ label: 'Size',
+ value: formatBytes({ bytes: getDocument().originalSize, base: 1000 }),
+ icon: 'i-tabler-weight',
+ },
+ {
+ label: 'Created At',
+ value: timeAgo({ date: getDocument().createdAt }),
+ icon: 'i-tabler-calendar',
+ },
+ {
+ label: 'Updated At',
+ value: getDocument().updatedAt ? timeAgo({ date: getDocument().updatedAt! }) : <span class="text-muted-foreground">Never</span>,
+ icon: 'i-tabler-calendar',
+ },
+ ]}
+ />
+ </TabsContent>
+ <TabsContent value="content">
+ <Show
+ when={isEditing()}
+ fallback={(
+ <div class="flex flex-col gap-2">
+ <div class="whitespace-pre-wrap font-mono text-sm bg-muted p-4 rounded-md max-h-[400px] overflow-auto">
+ {queries[0].data?.document.content}
+ </div>
+ <div class="flex justify-end">
+ <Button variant="outline" onClick={handleEdit}>
+ <div class="i-tabler-edit size-4 mr-2" />
+ Edit
+ </Button>
+ </div>
+ </div>
+ )}
+ >
+ <div class="flex flex-col gap-2">
+ <TextFieldRoot>
+ <TextArea
+ value={editedContent()}
+ onInput={e => setEditedContent(e.currentTarget.value)}
+ class="font-mono min-h-[200px]"
+ />
+ </TextFieldRoot>
+ <div class="flex justify-end gap-2">
+ <Button variant="outline" onClick={handleCancel} disabled={isSaving()}>
+ Cancel
+ </Button>
+ <Button onClick={handleSave} disabled={isSaving()}>
+ {isSaving() ? 'Saving...' : 'Save'}
+ </Button>
+ </div>
+ </div>
+ </Show>
+ </TabsContent>
+ </Tabs>
+
</div>
</div>
)}
diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.ts
index 550874fe..b580cd6f 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.ts
@@ -29,6 +29,7 @@ export function createDocumentsRepository({ db }: { db: Database }) {
getOrganizationStats,
getOrganizationDocumentBySha256Hash,
getAllOrganizationTrashDocumentIds,
+ updateDocument,
},
{ db },
);
@@ -324,3 +325,28 @@ async function getAllOrganizationTrashDocumentIds({ organizationId, db }: { orga
documentIds: documents.map(document => document.id),
};
}
+
+async function updateDocument({ documentId, organizationId, name, content, db }: { documentId: string; organizationId: string; name?: string; content?: string; db: Database }) {
+ const updateData: Partial<{ name: string; content: string }> = {};
+
+ if (name !== undefined) {
+ updateData.name = name;
+ }
+
+ if (content !== undefined) {
+ updateData.content = content;
+ }
+
+ const [document] = await db
+ .update(documentsTable)
+ .set(updateData)
+ .where(
+ and(
+ eq(documentsTable.id, documentId),
+ eq(documentsTable.organizationId, organizationId),
+ ),
+ )
+ .returning();
+
+ return { document };
+}
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index 14e6c7ab..0650db13 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -7,7 +7,7 @@ import { createOrganizationsRepository } from '../organizations/organizations.re
import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';
import { createPlansRepository } from '../plans/plans.repository';
import { createError } from '../shared/errors/errors';
-import { validateFormData, validateParams, validateQuery } from '../shared/validation/validation';
+import { validateFormData, validateJsonBody, validateParams, validateQuery } from '../shared/validation/validation';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';
import { createTagsRepository } from '../tags/tags.repository';
@@ -30,6 +30,7 @@ export function registerDocumentsPrivateRoutes(context: RouteDefinitionContext)
setupDeleteAllTrashDocumentsRoute(context);
setupDeleteDocumentRoute(context);
setupGetDocumentFileRoute(context);
+ setupUpdateDocumentRoute(context);
}
function setupCreateDocumentRoute({ app, config, db, trackingServices }: RouteDefinitionContext) {
@@ -423,3 +424,38 @@ function setupDeleteAllTrashDocumentsRoute({ app, config, db }: RouteDefinitionC
},
);
}
+
+function setupUpdateDocumentRoute({ app, db }: RouteDefinitionContext) {
+ app.patch(
+ '/api/organizations/:organizationId/documents/:documentId',
+ validateParams(z.object({
+ organizationId: organizationIdSchema,
+ documentId: documentIdSchema,
+ })),
+ validateJsonBody(z.object({
+ name: z.string().min(1).optional(),
+ content: z.string().min(1).optional(),
+ }).refine(data => data.name !== undefined || data.content !== undefined, {
+ message: 'At least one of \'name\' or \'content\' must be provided',
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId, documentId } = context.req.valid('param');
+ const updateData = context.req.valid('json');
+
+ const documentsRepository = createDocumentsRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+ await ensureDocumentExists({ documentId, organizationId, documentsRepository });
+
+ const { document } = await documentsRepository.updateDocument({
+ documentId,
+ organizationId,
+ ...updateData,
+ });
+
+ return context.json({ document });
+ },
+ );
+}