Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(documents): improved UX of the document content update (#468)

Corentin Thomasset14c3587de07a
diff --git a/.changeset/rich-parents-flash.md b/.changeset/rich-parents-flash.md
new file mode 100644
index 00000000..36f30093
--- /dev/null
+++ b/.changeset/rich-parents-flash.md
@@ -0,0 +1,5 @@
+---
+"@papra/app-client": patch
+---
+
+Prevent infinit loading in search modal when an error occure
diff --git a/.changeset/sweet-cougars-bathe.md b/.changeset/sweet-cougars-bathe.md
new file mode 100644
index 00000000..cf7e5810
--- /dev/null
+++ b/.changeset/sweet-cougars-bathe.md
@@ -0,0 +1,5 @@
+---
+"@papra/app-client": patch
+---
+
+Improved the UX of the document content edition panel
diff --git a/.changeset/young-laws-wish.md b/.changeset/young-laws-wish.md
new file mode 100644
index 00000000..6922cf4a
--- /dev/null
+++ b/.changeset/young-laws-wish.md
@@ -0,0 +1,5 @@
+---
+"@papra/app-client": patch
+---
+
+Added content edition support in demo mode
diff --git a/apps/papra-client/src/locales/de.yml b/apps/papra-client/src/locales/de.yml
index ed2672ad..c198cd5a 100644
--- a/apps/papra-client/src/locales/de.yml
+++ b/apps/papra-client/src/locales/de.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Abbrechen
documents.actions.save: Speichern
documents.actions.saving: Speichern...
documents.content.alert: Der Inhalt des Dokuments wird beim Hochladen automatisch aus dem Dokument extrahiert. Er wird nur für Such- und Indexierungszwecke verwendet.
+documents.content.empty-placeholder: Dieses Dokument hat keinen extrahierten Inhalt, Sie können ihn manuell hier eintragen.
documents.info.id: ID
documents.info.name: Name
documents.info.type: Typ
diff --git a/apps/papra-client/src/locales/en.yml b/apps/papra-client/src/locales/en.yml
index ca759528..5ee046ce 100644
--- a/apps/papra-client/src/locales/en.yml
+++ b/apps/papra-client/src/locales/en.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Cancel
documents.actions.save: Save
documents.actions.saving: Saving...
documents.content.alert: The content of the document is automatically extracted from the document on upload. It is only used for search and indexing purposes.
+documents.content.empty-placeholder: This document has no extracted content, you can set it manually here.
documents.info.id: ID
documents.info.name: Name
documents.info.type: Type
diff --git a/apps/papra-client/src/locales/es.yml b/apps/papra-client/src/locales/es.yml
index 32531b07..ea738579 100644
--- a/apps/papra-client/src/locales/es.yml
+++ b/apps/papra-client/src/locales/es.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Cancelar
documents.actions.save: Guardar
documents.actions.saving: Guardando...
documents.content.alert: El contenido del documento se extrae automáticamente al subirlo. Solo se utiliza para búsqueda e indexación.
+documents.content.empty-placeholder: Este documento no tiene contenido extraído, puedes introducirlo manualmente aquí.
documents.info.id: ID
documents.info.name: Nombre
documents.info.type: Tipo
diff --git a/apps/papra-client/src/locales/fr.yml b/apps/papra-client/src/locales/fr.yml
index 1d044b5e..1a4d75d2 100644
--- a/apps/papra-client/src/locales/fr.yml
+++ b/apps/papra-client/src/locales/fr.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Annuler
documents.actions.save: Enregistrer
documents.actions.saving: Enregistrement...
documents.content.alert: Le contenu du document est automatiquement extrait du document lors de l'import. Il est uniquement utilisé pour la recherche et l'indexation.
+documents.content.empty-placeholder: Ce document n'a pas de contenu extrait, vous pouvez le définir manuellement ici.
documents.info.id: ID
documents.info.name: Nom
documents.info.type: Type
diff --git a/apps/papra-client/src/locales/it.yml b/apps/papra-client/src/locales/it.yml
index 6460730e..3d274778 100644
--- a/apps/papra-client/src/locales/it.yml
+++ b/apps/papra-client/src/locales/it.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Annulla
documents.actions.save: Salva
documents.actions.saving: Salvataggio in corso...
documents.content.alert: Il contenuto del documento è estratto automaticamente al caricamento. È usato solo per la ricerca e l'indicizzazione.
+documents.content.empty-placeholder: Questo documento non ha contenuto estratto, puoi inserirlo manualmente qui.
documents.info.id: ID
documents.info.name: Nome
documents.info.type: Tipo
diff --git a/apps/papra-client/src/locales/pl.yml b/apps/papra-client/src/locales/pl.yml
index baec55f0..ec1aa9a5 100644
--- a/apps/papra-client/src/locales/pl.yml
+++ b/apps/papra-client/src/locales/pl.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Anuluj
documents.actions.save: Zapisz
documents.actions.saving: Zapisywanie...
documents.content.alert: Zawartość dokumentu jest automatycznie wyodrębniana z dokumentu podczas przesyłania. Jest używana tylko do wyszukiwania i indeksowania.
+documents.content.empty-placeholder: Ten dokument nie ma wyodrębnionej zawartości, możesz ją ustawić ręcznie tutaj.
documents.info.id: ID
documents.info.name: Nazwa
documents.info.type: Typ
diff --git a/apps/papra-client/src/locales/pt-BR.yml b/apps/papra-client/src/locales/pt-BR.yml
index a3b9fdae..ca04e65c 100644
--- a/apps/papra-client/src/locales/pt-BR.yml
+++ b/apps/papra-client/src/locales/pt-BR.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Cancelar
documents.actions.save: Salvar
documents.actions.saving: Salvando...
documents.content.alert: O conteúdo do documento é extraído automaticamente durante o envio e será utilizado apenas para fins de busca e indexação.
+documents.content.empty-placeholder: Este documento não tem conteúdo extraído, você pode inserir manualmente aqui.
documents.info.id: ID
documents.info.name: Nome
documents.info.type: Tipo
diff --git a/apps/papra-client/src/locales/pt.yml b/apps/papra-client/src/locales/pt.yml
index 247948c7..02172636 100644
--- a/apps/papra-client/src/locales/pt.yml
+++ b/apps/papra-client/src/locales/pt.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Cancelar
documents.actions.save: Guardar
documents.actions.saving: A guardar...
documents.content.alert: O conteúdo do documento é automaticamente extraído do documento no carregamento. É usado apenas para fins de pesquisa e indexação.
+documents.content.empty-placeholder: Este documento não tem conteúdo extraído, pode inserir manualmente aqui.
documents.info.id: ID
documents.info.name: Nome
documents.info.type: Tipo
diff --git a/apps/papra-client/src/locales/ro.yml b/apps/papra-client/src/locales/ro.yml
index c8b77e67..dabc7e8f 100644
--- a/apps/papra-client/src/locales/ro.yml
+++ b/apps/papra-client/src/locales/ro.yml
@@ -228,6 +228,7 @@ documents.actions.cancel: Anulează
documents.actions.save: Salvează
documents.actions.saving: Se salvează...
documents.content.alert: Conținutul documentului este extras automat din document la încarcare. Este folosit doar pentru căutare și indexare.
+documents.content.empty-placeholder: Acest document nu are conținut extra, poți introduce manual aici.
documents.info.id: ID
documents.info.name: Nume
documents.info.type: Tip
diff --git a/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx b/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
index 972281b0..20f00366 100644
--- a/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
+++ b/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
@@ -1,5 +1,6 @@
import type { Accessor, ParentComponent } from 'solid-js';
import type { Document } from '../documents/documents.types';
+import { safely } from '@corentinth/chisels';
import { useNavigate, useParams } from '@solidjs/router';
import { debounce } from 'lodash-es';
import { createContext, createEffect, createSignal, For, on, onCleanup, onMount, Show, useContext } from 'solid-js';
@@ -54,7 +55,10 @@ export const CommandPaletteProvider: ParentComponent = (props) => {
const { setColorMode } = useThemeStore();
const searchDocs = debounce(async ({ searchQuery }: { searchQuery: string }) => {
- const { documents } = await searchDocuments({ searchQuery, organizationId: params.organizationId, pageIndex: 0, pageSize: 5 });
+ const [result] = await safely(searchDocuments({ searchQuery, organizationId: params.organizationId, pageIndex: 0, pageSize: 5 }));
+
+ const { documents = [] } = result ?? {};
+
setMatchingDocuments(documents);
setIsLoading(false);
}, 300);
diff --git a/apps/papra-client/src/modules/demo/demo-api-mock.models.ts b/apps/papra-client/src/modules/demo/demo-api-mock.models.ts
index acf424cb..efe9ef86 100644
--- a/apps/papra-client/src/modules/demo/demo-api-mock.models.ts
+++ b/apps/papra-client/src/modules/demo/demo-api-mock.models.ts
@@ -15,7 +15,7 @@ export function defineHandler<Path extends string>({
handler,
}: {
path: Path;
- method: 'GET' | 'POST' | 'PUT' | 'DELETE';
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
handler: <R extends ResponseType = 'json'>(params: { params: ExtractRouteParams<Path> } & HttpClientOptions<R>) => any;
}) {
return {
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 be992541..f774a446 100644
--- a/apps/papra-client/src/modules/demo/demo-api-mock.ts
+++ b/apps/papra-client/src/modules/demo/demo-api-mock.ts
@@ -1,4 +1,5 @@
import type { ApiKey } from '../api-keys/api-keys.types';
+import type { Document } from '../documents/documents.types';
import type { Webhook } from '../webhooks/webhooks.types';
import { get } from 'lodash-es';
import { FetchError } from 'ofetch';
@@ -203,7 +204,11 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
const searchQuery = rawSearchQuery.trim().toLowerCase();
- const filteredDocuments = documents.filter(document => document?.name.toLowerCase().includes(searchQuery) && !document?.deletedAt);
+ const matchQuery = (document: Document) =>
+ !document?.deletedAt
+ && [document?.name, document?.content].filter(Boolean).some(content => content.toLowerCase().includes(searchQuery));
+
+ const filteredDocuments = documents.filter(matchQuery);
return {
documents: filteredDocuments.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize),
@@ -733,6 +738,29 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
return { webhook };
},
}),
+
+ ...defineHandler({
+ path: '/api/organizations/:organizationId/documents/:documentId',
+ method: 'PATCH',
+ handler: async ({ params: { organizationId, documentId }, body }) => {
+ const document = await documentStorage.getItem(`${organizationId}:${documentId}`);
+
+ assert(document, { status: 404 });
+
+ const { name, content } = body as { name?: string; content?: string };
+
+ const newDocument = {
+ ...document,
+ ...(name !== undefined && { name }),
+ ...(content !== undefined && { content }),
+ updatedAt: new Date(),
+ };
+
+ await documentStorage.setItem(`${organizationId}:${documentId}`, newDocument);
+
+ return { document: newDocument };
+ },
+ }),
};
export const router = createRouter({ routes: inMemoryApiMock, strictTrailingSlash: false });
diff --git a/apps/papra-client/src/modules/documents/components/document-content-edition-panel.component.tsx b/apps/papra-client/src/modules/documents/components/document-content-edition-panel.component.tsx
new file mode 100644
index 00000000..2cd31ffb
--- /dev/null
+++ b/apps/papra-client/src/modules/documents/components/document-content-edition-panel.component.tsx
@@ -0,0 +1,95 @@
+import type { Component } from 'solid-js';
+import { useMutation, useQueryClient } from '@tanstack/solid-query';
+import { createSignal, Show } from 'solid-js';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { cn } from '@/modules/shared/style/cn';
+import { Alert, AlertDescription } from '@/modules/ui/components/alert';
+import { Button } from '@/modules/ui/components/button';
+import { createToast } from '@/modules/ui/components/sonner';
+import { TextArea } from '@/modules/ui/components/textarea';
+import { TextFieldRoot } from '@/modules/ui/components/textfield';
+import { updateDocument } from '../documents.services';
+
+export const DocumentContentEditionPanel: Component<{
+ documentId: string;
+ organizationId: string;
+ content: string;
+}> = (props) => {
+ const { t } = useI18n();
+ const queryClient = useQueryClient();
+
+ const [isEditing, setIsEditing] = createSignal(false);
+ const [getContent, setContent] = createSignal(props.content);
+
+ const updateMutation = useMutation(() => ({
+ mutationFn: ({ content }: { content: string }) => updateDocument({
+ documentId: props.documentId,
+ organizationId: props.organizationId,
+ content,
+ }),
+ onSuccess: () => {
+ createToast({ type: 'success', message: 'Document content updated' });
+ setIsEditing(false);
+ queryClient.invalidateQueries({
+ queryKey: ['organizations', props.organizationId, 'documents', props.documentId],
+ });
+ },
+ onError: () => {
+ createToast({ type: 'error', message: 'Failed to update document content' });
+ },
+ }));
+
+ const handleEdit = () => {
+ setIsEditing(true);
+ };
+
+ const handleCancel = () => {
+ setIsEditing(false);
+ setContent(props.content);
+ };
+
+ const handleSave = () => {
+ updateMutation.mutate({ content: getContent() });
+ };
+
+ return (
+ <div class="flex flex-col gap-2">
+ <TextFieldRoot>
+ <TextArea
+ value={getContent()}
+ onInput={e => setContent(e.currentTarget.value)}
+ class={cn('font-mono placeholder:italic max-h-500px', { 'bg-muted text-muted-foreground': !isEditing() })}
+ readonly={!isEditing()}
+ placeholder={t('documents.content.empty-placeholder')}
+ rows={2}
+ autoResize
+ />
+ </TextFieldRoot>
+ <div class="flex justify-end gap-2">
+ <Show
+ when={isEditing()}
+ fallback={(
+ <Button variant="outline" onClick={handleEdit}>
+ <div class="i-tabler-edit size-4 mr-2" />
+ {t('documents.actions.edit')}
+ </Button>
+ )}
+ >
+ <Button variant="outline" onClick={handleCancel} disabled={updateMutation.isPending}>
+ {t('documents.actions.cancel')}
+ </Button>
+ <Button onClick={handleSave} isLoading={updateMutation.isPending}>
+ {updateMutation.isPending ? t('documents.actions.saving') : t('documents.actions.save')}
+ </Button>
+ </Show>
+ </div>
+
+ <Alert variant="muted" class="my-4 flex items-center gap-2">
+ <div class="i-tabler-info-circle size-8 flex-shrink-0" />
+ <AlertDescription>
+ {t('documents.content.alert')}
+ </AlertDescription>
+ </Alert>
+ </div>
+ );
+};
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 7409e654..c71836a0 100644
--- a/apps/papra-client/src/modules/documents/pages/document.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/document.page.tsx
@@ -1,6 +1,6 @@
import type { Component, JSX } from 'solid-js';
import type { DocumentActivity } from '../documents.types';
-import { formatBytes, safely } from '@corentinth/chisels';
+import { formatBytes } from '@corentinth/chisels';
import { A, useNavigate, useParams, useSearchParams } from '@solidjs/router';
import { createQueries, useInfiniteQuery } from '@tanstack/solid-query';
import { createEffect, createSignal, For, Match, Show, Suspense, Switch } from 'solid-js';
@@ -8,24 +8,20 @@ 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 { cn } from '@/modules/shared/style/cn';
import { DocumentTagPicker } from '@/modules/tags/components/tag-picker.component';
import { TagLink } from '@/modules/tags/components/tag.component';
import { CreateTagModal } from '@/modules/tags/pages/tags.page';
import { addTagToDocument, removeTagFromDocument } from '@/modules/tags/tags.services';
-import { Alert, AlertDescription } from '@/modules/ui/components/alert';
+import { Alert } from '@/modules/ui/components/alert';
import { Button } from '@/modules/ui/components/button';
import { Separator } from '@/modules/ui/components/separator';
-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 { DocumentContentEditionPanel } from '../components/document-content-edition-panel.component';
import { DocumentPreview } from '../components/document-preview.component';
import { useRenameDocumentDialog } from '../components/rename-document-button.component';
import { getDaysBeforePermanentDeletion, getDocumentActivityIcon } from '../document.models';
import { useDeleteDocument, useRestoreDocument } from '../documents.composables';
-import { fetchDocument, fetchDocumentActivities, fetchDocumentFile, updateDocument } from '../documents.services';
+import { fetchDocument, fetchDocumentActivities, fetchDocumentFile } from '../documents.services';
import '@pdfslick/solid/dist/pdf_viewer.css';
type KeyValueItem = {
@@ -61,7 +57,7 @@ const ActivityItem: Component<{ activity: DocumentActivity }> = (props) => {
return (
<div class="border-b py-3 flex items-center gap-2">
<div>
- <div class={cn(getDocumentActivityIcon({ event: props.activity.event }), 'size-6 text-muted-foreground')} />
+ <div class={`${getDocumentActivityIcon({ event: props.activity.event })} size-6 text-muted-foreground`} />
</div>
<div>
<Switch fallback={<span class="text-sm">{t(`activity.document.${props.activity.event}`)}</span>}>
@@ -184,44 +180,6 @@ 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>
@@ -391,48 +349,13 @@ export const DocumentPage: Component = () => {
]}
/>
</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" />
- {t('documents.actions.edit')}
- </Button>
- </div>
-
- <Alert variant="muted" class="my-4 flex items-center gap-2">
- <div class="i-tabler-info-circle size-8 flex-shrink-0" />
- <AlertDescription>
- {t('documents.content.alert')}
- </AlertDescription>
- </Alert>
- </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()}>
- {t('documents.actions.cancel')}
- </Button>
- <Button onClick={handleSave} disabled={isSaving()}>
- {isSaving() ? t('documents.actions.saving') : t('documents.actions.save')}
- </Button>
- </div>
- </div>
- </Show>
+ <DocumentContentEditionPanel
+ documentId={getDocument().id}
+ organizationId={params.organizationId}
+ content={getDocument().content}
+ />
</TabsContent>
<TabsContent value="activity">
<Show when={activityQuery.data?.pages}>
diff --git a/apps/papra-client/src/modules/i18n/locales.types.ts b/apps/papra-client/src/modules/i18n/locales.types.ts
index 0c392255..39099247 100644
--- a/apps/papra-client/src/modules/i18n/locales.types.ts
+++ b/apps/papra-client/src/modules/i18n/locales.types.ts
@@ -204,6 +204,7 @@ export type LocaleKeys =
| 'documents.actions.save'
| 'documents.actions.saving'
| 'documents.content.alert'
+ | 'documents.content.empty-placeholder'
| 'documents.info.id'
| 'documents.info.name'
| 'documents.info.type'
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index 8df37172..bad5ef86 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -468,7 +468,7 @@ function setupUpdateDocumentRoute({ app, db }: RouteDefinitionContext) {
})),
validateJsonBody(z.object({
name: z.string().min(1).max(255).optional(),
- content: z.string().min(1).optional(),
+ content: z.string().optional(),
}).refine(data => data.name !== undefined || data.content !== undefined, {
message: 'At least one of \'name\' or \'content\' must be provided',
})),