Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(tags): prevented multiple tags creation/update form submissions (#851)

Corentin Thomasset316a8c2f9c32
diff --git a/.changeset/polite-windows-heal.md b/.changeset/polite-windows-heal.md
new file mode 100644
index 00000000..845e0c2f
--- /dev/null
+++ b/.changeset/polite-windows-heal.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": patch
+---
+
+Added tag creation/update button loading state
diff --git a/.changeset/shy-waves-drive.md b/.changeset/shy-waves-drive.md
new file mode 100644
index 00000000..1d90d1c3
--- /dev/null
+++ b/.changeset/shy-waves-drive.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": patch
+---
+
+Prevented multiple tag creation attempts when clicking the create button quickly.
\ No newline at end of file
diff --git a/apps/papra-client/src/modules/shared/functions/void.test.ts b/apps/papra-client/src/modules/shared/functions/void.test.ts
new file mode 100644
index 00000000..8c9eb583
--- /dev/null
+++ b/apps/papra-client/src/modules/shared/functions/void.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, test } from 'vitest';
+import { makeReturnVoid, makeReturnVoidAsync } from './void';
+
+describe('void', () => {
+ describe('makeReturnVoid', () => {
+ test('given a function, when called, then it returns void and calls the original function with the same arguments', () => {
+ const args: unknown[][] = [];
+
+ const fn = (a: number, b: number) => {
+ args.push([a, b]);
+ return a + b;
+ };
+
+ const voidFn = makeReturnVoid(fn);
+
+ const result = voidFn(2, 3);
+
+ expect(result).toBeUndefined();
+ expect(args).toEqual([[2, 3]]);
+ });
+ });
+
+ describe('makeReturnVoidAsync', () => {
+ test('given an async function, when called, then it returns Promise<void> and calls the original function with the same arguments', async () => {
+ const args: unknown[][] = [];
+
+ const fn = async (a: number, b: number) => {
+ args.push([a, b]);
+ return a + b;
+ };
+
+ const voidFn = makeReturnVoidAsync(fn);
+
+ const result = await voidFn(5, 7);
+
+ expect(result).toBeUndefined();
+ expect(args).toEqual([[5, 7]]);
+ });
+
+ test('given a sync function, when called, then it returns Promise<void> and calls the original function with the same arguments', async () => {
+ const args: unknown[][] = [];
+
+ const fn = (a: number, b: number) => {
+ args.push([a, b]);
+ return a + b;
+ };
+
+ const voidFn = makeReturnVoidAsync(fn);
+
+ const result = await voidFn(10, 15);
+
+ expect(result).toBeUndefined();
+ expect(args).toEqual([[10, 15]]);
+ });
+ });
+});
diff --git a/apps/papra-client/src/modules/shared/functions/void.ts b/apps/papra-client/src/modules/shared/functions/void.ts
new file mode 100644
index 00000000..440c4b6c
--- /dev/null
+++ b/apps/papra-client/src/modules/shared/functions/void.ts
@@ -0,0 +1,11 @@
+export function makeReturnVoid<T extends (...args: any[]) => any>(fn: T): (...funcArgs: Parameters<T>) => void {
+ return (...args: Parameters<T>): void => {
+ fn(...args);
+ };
+}
+
+export function makeReturnVoidAsync<T extends (...args: any[]) => unknown>(fn: T): (...funcArgs: Parameters<T>) => Promise<void> {
+ return async (...args: Parameters<T>): Promise<void> => {
+ await fn(...args);
+ };
+}
diff --git a/apps/papra-client/src/modules/tags/pages/tags.page.tsx b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
index dafeebf9..878c5f4a 100644
--- a/apps/papra-client/src/modules/tags/pages/tags.page.tsx
+++ b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
@@ -4,7 +4,7 @@ import type { Tag as TagType } from '../tags.types';
import { safely } from '@corentinth/chisels';
import { getValues, setValue } from '@modular-forms/solid';
import { A, useParams } from '@solidjs/router';
-import { useQuery } from '@tanstack/solid-query';
+import { useMutation, useQuery } from '@tanstack/solid-query';
import { createSignal, For, Show, Suspense } from 'solid-js';
import * as v from 'valibot';
import { makeDocumentSearchPermalink } from '@/modules/documents/document.models';
@@ -12,6 +12,7 @@ import { RelativeTime } from '@/modules/i18n/components/RelativeTime';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { useConfirmModal } from '@/modules/shared/confirm';
import { createForm } from '@/modules/shared/form/form';
+import { makeReturnVoidAsync } from '@/modules/shared/functions/void';
import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';
import { queryClient } from '@/modules/shared/query/query-client';
import { Button } from '@/modules/ui/components/button';
@@ -46,13 +47,13 @@ const TagColorPicker: Component<{
};
const TagForm: Component<{
- onSubmit: (values: { name: string; color: string; description: string }) => Promise<void>;
+ onSubmit: (values: { name: string; color: string; description: string }) => Promise<unknown> | unknown;
initialValues?: { name?: string; color?: string; description?: string | null };
- submitLabel?: string;
+ submitButton: JSX.Element;
}> = (props) => {
const { t } = useI18n();
const { form, Form, Field } = createForm({
- onSubmit: props.onSubmit,
+ onSubmit: makeReturnVoidAsync(props.onSubmit),
schema: v.object({
name: v.pipe(
v.string(),
@@ -116,16 +117,12 @@ const TagForm: Component<{
</Field>
<div class="flex flex-row-reverse justify-between items-center mt-6">
- <Button type="submit">
- {props.submitLabel ?? t('tags.create')}
- </Button>
+ {props.submitButton}
{getFormValues().name && (
<Tag {...getFormValues()} />
)}
-
</div>
-
</Form>
);
};
@@ -138,34 +135,33 @@ export const CreateTagModal: Component<{
const { t } = useI18n();
const { getErrorMessage } = useI18nApiErrors({ t });
- const onSubmit = async ({ name, color, description }: { name: string; color: string; description: string }) => {
- const [,error] = await safely(createTag({
- name,
- color: color.toLowerCase(),
- description,
+ const createTagMutation = useMutation(() => ({
+ mutationFn: (data: { name: string; color: string; description: string }) => createTag({
+ name: data.name,
+ color: data.color.toLowerCase(),
+ description: data.description,
organizationId: props.organizationId,
- }));
+ }),
+ onSuccess: async (data, variables) => {
+ await queryClient.invalidateQueries({
+ queryKey: ['organizations', props.organizationId],
+ refetchType: 'all',
+ });
- if (error) {
+ createToast({
+ message: t('tags.create.success', { name: variables.name }),
+ type: 'success',
+ });
+
+ setIsModalOpen(false);
+ },
+ onError: (error) => {
createToast({
message: getErrorMessage({ error }),
type: 'error',
});
- return;
- }
-
- await queryClient.invalidateQueries({
- queryKey: ['organizations', props.organizationId],
- refetchType: 'all',
- });
-
- createToast({
- message: t('tags.create.success', { name }),
- type: 'success',
- });
-
- setIsModalOpen(false);
- };
+ },
+ }));
return (
<Dialog open={getIsModalOpen()} onOpenChange={setIsModalOpen}>
@@ -175,7 +171,19 @@ export const CreateTagModal: Component<{
<DialogTitle>{t('tags.create')}</DialogTitle>
</DialogHeader>
- <TagForm onSubmit={onSubmit} initialValues={{ color: '#D8FF75' }} />
+ <TagForm
+ onSubmit={createTagMutation.mutateAsync}
+ initialValues={{ color: '#D8FF75' }}
+ submitButton={(
+ <Button
+ type="submit"
+ isLoading={createTagMutation.isPending}
+ disabled={!getIsModalOpen()} // As the dialog closing animation may still be running
+ >
+ { t('tags.create') }
+ </Button>
+ )}
+ />
</DialogContent>
</Dialog>
);
@@ -188,28 +196,36 @@ const UpdateTagModal: Component<{
}> = (props) => {
const [getIsModalOpen, setIsModalOpen] = createSignal(false);
const { t } = useI18n();
+ const { getErrorMessage } = useI18nApiErrors({ t });
- const onSubmit = async ({ name, color, description }: { name: string; color: string; description: string }) => {
- await updateTag({
- name,
- color: color.toLowerCase(),
- description,
+ const updateTagMutation = useMutation(() => ({
+ mutationFn: (data: { name: string; color: string; description: string }) => updateTag({
+ name: data.name,
+ color: data.color.toLowerCase(),
+ description: data.description,
organizationId: props.organizationId,
tagId: props.tag.id,
- });
-
- await queryClient.invalidateQueries({
- queryKey: ['organizations', props.organizationId],
- refetchType: 'all',
- });
+ }),
+ onSuccess: async (data, variables) => {
+ await queryClient.invalidateQueries({
+ queryKey: ['organizations', props.organizationId],
+ refetchType: 'all',
+ });
- createToast({
- message: t('tags.update.success', { name }),
- type: 'success',
- });
+ createToast({
+ message: t('tags.update.success', { name: variables.name }),
+ type: 'success',
+ });
- setIsModalOpen(false);
- };
+ setIsModalOpen(false);
+ },
+ onError: (error) => {
+ createToast({
+ message: getErrorMessage({ error }),
+ type: 'error',
+ });
+ },
+ }));
return (
<Dialog open={getIsModalOpen()} onOpenChange={setIsModalOpen}>
@@ -219,7 +235,19 @@ const UpdateTagModal: Component<{
<DialogTitle>{t('tags.update')}</DialogTitle>
</DialogHeader>
- <TagForm onSubmit={onSubmit} initialValues={props.tag} submitLabel={t('tags.update')} />
+ <TagForm
+ onSubmit={updateTagMutation.mutate}
+ initialValues={props.tag}
+ submitButton={(
+ <Button
+ type="submit"
+ isLoading={updateTagMutation.isPending}
+ disabled={!getIsModalOpen()} // As the dialog closing animation may still be running
+ >
+ { t('tags.update') }
+ </Button>
+ )}
+ />
</DialogContent>
</Dialog>
);
diff --git a/apps/papra-client/src/modules/ui/components/button.tsx b/apps/papra-client/src/modules/ui/components/button.tsx
index ddca8532..5c6a3903 100644
--- a/apps/papra-client/src/modules/ui/components/button.tsx
+++ b/apps/papra-client/src/modules/ui/components/button.tsx
@@ -47,6 +47,7 @@ export function Button<T extends ValidComponent = 'button'>(props: PolymorphicPr
'size',
'isLoading',
'children',
+ 'disabled',
]);
return (
@@ -58,6 +59,7 @@ export function Button<T extends ValidComponent = 'button'>(props: PolymorphicPr
}),
local.class,
)}
+ disabled={local.isLoading || local.disabled}
{...rest}
>
{local.isLoading && <div class="i-tabler-loader-2 animate-spin mr-2" />}