Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(tags): better picker (#867)

Corentin Thomassetfaebe9359478
diff --git a/apps/papra-client/src/modules/documents/components/documents-list.component.tsx b/apps/papra-client/src/modules/documents/components/documents-list.component.tsx
index 59053047..0c450046 100644
--- a/apps/papra-client/src/modules/documents/components/documents-list.component.tsx
+++ b/apps/papra-client/src/modules/documents/components/documents-list.component.tsx
@@ -14,7 +14,7 @@ import { For, Match, Show, Switch } from 'solid-js';
import { RelativeTime } from '@/modules/i18n/components/RelativeTime';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { cn } from '@/modules/shared/style/cn';
-import { TagLink } from '@/modules/tags/components/tag.component';
+import { DocumentTagsList } from '@/modules/tags/components/tag-list.component';
import { Button } from '@/modules/ui/components/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/modules/ui/components/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/modules/ui/components/table';
@@ -64,11 +64,14 @@ export const tagsColumn: ColumnDef<Document> = {
},
accessorKey: 'tags',
cell: data => (
- <div class="text-muted-foreground hidden sm:flex flex-wrap gap-1">
- <For each={data.getValue<Tag[]>()}>
- {tag => <TagLink {...tag} class="text-xs" />}
- </For>
- </div>
+ <DocumentTagsList
+ tags={data.getValue<Tag[]>()}
+ tagClass="text-xs text-muted-foreground"
+ triggerClass="size-6"
+ documentId={data.row.original.id}
+ organizationId={data.row.original.organizationId}
+ asLink
+ />
),
};
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 370fe1c4..b4b34e4d 100644
--- a/apps/papra-client/src/modules/documents/pages/document.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/document.page.tsx
@@ -8,10 +8,8 @@ import { useConfig } from '@/modules/config/config.provider';
import { RelativeTime } from '@/modules/i18n/components/RelativeTime';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { downloadFile } from '@/modules/shared/files/download';
-import { DocumentTagPicker } from '@/modules/tags/components/tag-picker.component';
+import { DocumentTagsList } from '@/modules/tags/components/tag-list.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 } from '@/modules/ui/components/alert';
import { Button } from '@/modules/ui/components/button';
import { Separator } from '@/modules/ui/components/separator';
@@ -234,39 +232,14 @@ export const DocumentPage: Component = () => {
</Button>
)}
</div>
+ <Separator class="my-3" />
- <div class="flex gap-2 sm:items-center sm:flex-row flex-col">
- <div class="flex-1">
- <DocumentTagPicker
- organizationId={params.organizationId}
- tagIds={getDocument().tags.map(tag => tag.id)}
- onTagAdded={async ({ tag }) => {
- await addTagToDocument({
- documentId: params.documentId,
- organizationId: params.organizationId,
- tagId: tag.id,
- });
- }}
-
- onTagRemoved={async ({ tag }) => {
- await removeTagFromDocument({
- documentId: params.documentId,
- organizationId: params.organizationId,
- tagId: tag.id,
- });
- }}
- />
- </div>
-
- <CreateTagModal organizationId={params.organizationId}>
- {params => (
- <Button variant="outline" {...params}>
- <div class="i-tabler-plus size-4 mr-2" />
- {t('tagging-rules.form.tags.add-tag')}
- </Button>
- )}
- </CreateTagModal>
- </div>
+ <DocumentTagsList
+ documentId={params.documentId}
+ organizationId={params.organizationId}
+ tags={getDocument().tags}
+ asLink
+ />
{getDocument().isDeleted && (
<Alert variant="destructive" class="mt-6">
diff --git a/apps/papra-client/src/modules/shared/utils/array.test.ts b/apps/papra-client/src/modules/shared/utils/array.test.ts
index 93a28e23..069653cd 100644
--- a/apps/papra-client/src/modules/shared/utils/array.test.ts
+++ b/apps/papra-client/src/modules/shared/utils/array.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest';
-import { castArray } from './array';
+import { castArray, toArrayIf } from './array';
describe('array', () => {
describe('castArray', () => {
@@ -18,4 +18,24 @@ describe('array', () => {
expect(castArray(objArray)).toEqual(objArray);
});
});
+
+ describe('toArrayIf', () => {
+ test('simple helper to conditionally add stuff to an array', () => {
+ const array = [
+ ...toArrayIf(true, 'a'),
+ ...toArrayIf(false, 'b'),
+ ...toArrayIf(true, 'c'),
+ ];
+
+ expect(array).toEqual(['a', 'c']);
+ });
+
+ test('returns an empty array when condition is false', () => {
+ expect(toArrayIf(false, 42)).toEqual([]);
+ });
+
+ test('returns an array with the value when condition is true', () => {
+ expect(toArrayIf(true, 42)).toEqual([42]);
+ });
+ });
});
diff --git a/apps/papra-client/src/modules/shared/utils/array.ts b/apps/papra-client/src/modules/shared/utils/array.ts
index 1b267d15..da6978e8 100644
--- a/apps/papra-client/src/modules/shared/utils/array.ts
+++ b/apps/papra-client/src/modules/shared/utils/array.ts
@@ -1,3 +1,29 @@
export function castArray<T>(value: T | T[]): T[] {
return Array.isArray(value) ? value : [value];
}
+
+/**
+ * Returns an array containing the value if the condition is true, otherwise returns an empty array.
+ * @example
+ * ```ts
+ * const array = [
+ * ...toArrayIf(true, 'a'),
+ * ...toArrayIf(false, 'b'),
+ * ...toArrayIf(true, 'c'),
+ * ];
+ *
+ * console.log(array); // Output: ['a', 'c']
+ * ```
+ * Instead of writing:
+ * ```ts
+ * const array = [
+ * ...(true ? ['a'] : []),
+ * ...(false ? ['b'] : []),
+ * ...(true ? ['c'] : []),
+ * ];
+ * console.log(array); // Output: ['a', 'c']
+ * ```
+ */
+export function toArrayIf<C extends boolean, T>(condition: C, value: T): C extends true ? T[] : [] {
+ return (condition ? [value] : []) as C extends true ? T[] : [];
+}
diff --git a/apps/papra-client/src/modules/tags/components/tag-list.component.tsx b/apps/papra-client/src/modules/tags/components/tag-list.component.tsx
new file mode 100644
index 00000000..87c88486
--- /dev/null
+++ b/apps/papra-client/src/modules/tags/components/tag-list.component.tsx
@@ -0,0 +1,256 @@
+import type { PopoverTriggerProps } from '@kobalte/core/popover';
+import type { Component, ComponentProps } from 'solid-js';
+import type { Tag } from '../tags.types';
+import { useQuery } from '@tanstack/solid-query';
+import { createEffect, createSignal, For, splitProps } from 'solid-js';
+import { queryClient } from '@/modules/shared/query/query-client';
+import { cn } from '@/modules/shared/style/cn';
+import { Button } from '@/modules/ui/components/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/modules/ui/components/popover';
+import { TextField, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { CreateTagModal } from '../pages/tags.page';
+import { addTagToDocument, fetchTags, removeTagFromDocument } from '../tags.services';
+import { TagPickerList } from './tag-picker-list.component';
+import { Tag as TagComponent, TagLink } from './tag.component';
+import { useTagPicker } from './use-tag-picker.hook';
+
+export const TagPickerFilter: Component<{
+ value: string;
+ onInput: (value: string) => void;
+ placeholder?: string;
+ isOpen?: boolean;
+}> = (props) => {
+ let ref: HTMLInputElement | undefined;
+
+ createEffect(() => {
+ if (props.isOpen && ref) {
+ // Small delay to ensure the popover is fully open
+ setTimeout(() => ref?.focus(), 10);
+ }
+ });
+
+ return (
+ <TextFieldRoot>
+ <TextField
+ class="focus-visible:ring-0 rounded-none border-t-none border-x-none"
+ placeholder={props.placeholder ?? 'Filter tags...'}
+ value={props.value}
+ onInput={e => props.onInput(e.currentTarget.value)}
+ ref={ref}
+ autofocus
+ />
+ </TextFieldRoot>
+ );
+};
+
+const TagPicker: Component<{
+ selectedTags?: Tag[];
+ onChange?: (tags: Tag[]) => void;
+ organizationId: string;
+ isOpen?: boolean;
+}> = (props) => {
+ const [getIsTagCreationModalOpen, setIsTagCreationModalOpen] = createSignal(false);
+ const tagsQuery = useQuery(() => ({
+ queryKey: ['organizations', props.organizationId, 'tags'],
+ queryFn: () => fetchTags({ organizationId: props.organizationId }),
+ }));
+
+ const {
+ setFilterQuery,
+ filterQuery,
+ resetHighlight,
+ getTagsListItems,
+ highlighted,
+ highlightNext,
+ highlightPrevious,
+ getListItems,
+ getNormalizedFilterQuery,
+ } = useTagPicker({
+ getAvailableTags: () => tagsQuery.data?.tags ?? [],
+ getSelectedTagIds: () => props.selectedTags?.map(tag => tag.id) ?? [],
+ });
+
+ // Reset filter and highlight when popover opens
+ createEffect(() => {
+ if (props.isOpen) {
+ setFilterQuery('');
+ resetHighlight();
+ }
+ });
+
+ const setTagSelection = ({ tagId, setSelection }: { tagId: string; setSelection: (previous: boolean) => boolean }) => {
+ const updatedTagItems = getTagsListItems()
+ .map(tagItem => ({
+ ...tagItem,
+ isSelected: tagItem.tag.id === tagId ? setSelection(tagItem.isSelected) : tagItem.isSelected,
+ }));
+
+ return updatedTagItems.filter(tag => tag.isSelected).map(({ tag }) => tag);
+ };
+
+ const handleToggle = (tagId: string, selected: boolean | ((old: boolean) => boolean)) => {
+ const updatedTags = setTagSelection({ tagId, setSelection: typeof selected === 'function' ? selected : () => selected });
+
+ props.onChange?.(updatedTags);
+ };
+
+ const handleTagCreated = (args: { tag: Tag }) => {
+ const updatedTags = setTagSelection({ tagId: args.tag.id, setSelection: () => true });
+ props.onChange?.(updatedTags);
+ };
+
+ const handleKeyDown = (e: KeyboardEvent) => {
+ const currentHighlight = highlighted();
+ const { key } = e;
+ const isEnterOrSpace = key === 'Enter' || key === ' ';
+
+ if (key === 'ArrowDown') {
+ e.preventDefault();
+ highlightNext();
+ return;
+ }
+
+ if (key === 'ArrowUp') {
+ e.preventDefault();
+ highlightPrevious();
+ return;
+ }
+
+ if (isEnterOrSpace && currentHighlight.action === 'create-new-tag') {
+ e.preventDefault();
+ setIsTagCreationModalOpen(true);
+ return;
+ }
+
+ if (isEnterOrSpace && currentHighlight.tagId) {
+ e.preventDefault();
+ handleToggle(currentHighlight.tagId, selected => !selected);
+ return;
+ }
+
+ if (key === 'Escape') {
+ // No preventDefault to allow closing the popover
+ resetHighlight();
+ }
+ };
+
+ return (
+ <div onKeyDown={handleKeyDown}>
+ <TagPickerFilter
+ value={filterQuery()}
+ onInput={(value) => {
+ setFilterQuery(value);
+ resetHighlight();
+ }}
+ isOpen={props.isOpen}
+ />
+
+ <TagPickerList
+ listItems={getListItems()}
+ highlighted={highlighted()}
+ onToggle={handleToggle}
+ onCreateNewTag={() => setIsTagCreationModalOpen(true)}
+ />
+
+ <CreateTagModal
+ open={getIsTagCreationModalOpen()}
+ onOpenChange={setIsTagCreationModalOpen}
+ initialName={getNormalizedFilterQuery()}
+ onTagCreated={handleTagCreated}
+ organizationId={props.organizationId}
+ />
+ </div>
+ );
+};
+
+export const TagList: Component<{
+ tags: Tag[];
+ onChange?: (tags: Tag[]) => void;
+ asLink?: boolean;
+ tagClass?: string;
+ triggerClass?: string;
+ organizationId: string;
+}> = (props) => {
+ const TagItem = (props.asLink ?? true) ? TagLink : TagComponent;
+ let containerRef: HTMLDivElement | undefined;
+ const [isOpen, setIsOpen] = createSignal(false);
+
+ const handleTagsChange = (tags: Tag[]) => {
+ props.onChange?.(tags);
+ };
+
+ return (
+ <div ref={containerRef} class="flex flex-wrap items-center gap-1">
+ <For each={props.tags}>
+ {tag => (
+ <TagItem {...tag} class={props.tagClass} />
+ )}
+ </For>
+
+ <Popover anchorRef={() => containerRef} open={isOpen()} onOpenChange={setIsOpen}>
+ <PopoverTrigger
+ as={(triggerProps: PopoverTriggerProps) => (
+ <Button variant="outline" size="icon" {...triggerProps} class={cn('size-7 text-muted-foreground/30 hover:text-muted-foreground rounded-lg', props.triggerClass)}>
+ <div class="i-tabler-plus size-4" />
+ </Button>
+ )}
+ />
+ <PopoverContent class="p-0">
+ <TagPicker
+ selectedTags={props.tags}
+ onChange={handleTagsChange}
+ organizationId={props.organizationId}
+ isOpen={isOpen()}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ );
+};
+
+export const DocumentTagsList: Component<{
+ tags: Tag[];
+ documentId: string;
+ organizationId: string;
+} & Pick<ComponentProps<typeof TagList>, 'tagClass' | 'asLink' | 'triggerClass'>> = (props) => {
+ const [getDocumentsTags, setDocumentsTags] = createSignal<Tag[]>(props.tags);
+ const [rest] = splitProps(props, ['tagClass', 'asLink', 'triggerClass']);
+
+ const onTagsChange = async (tags: Tag[]) => {
+ const currentTags = getDocumentsTags();
+ const addedTags = tags.filter(tag => !currentTags.find(t => t.id === tag.id));
+ const removedTags = currentTags.filter(tag => !tags.find(t => t.id === tag.id));
+
+ // Optimistic update
+ setDocumentsTags(tags);
+
+ await Promise.all(
+ addedTags.map(tag => addTagToDocument({
+ documentId: props.documentId,
+ organizationId: props.organizationId,
+ tagId: tag.id,
+ })),
+ );
+
+ await Promise.all(
+ removedTags.map(tag => removeTagFromDocument({
+ documentId: props.documentId,
+ organizationId: props.organizationId,
+ tagId: tag.id,
+ })),
+ );
+
+ await queryClient.invalidateQueries({
+ queryKey: ['organizations', props.organizationId, 'documents', props.documentId, 'tags'],
+ });
+ };
+
+ return (
+ <TagList
+ tags={getDocumentsTags()}
+ organizationId={props.organizationId}
+ onChange={onTagsChange}
+ {...rest}
+ />
+ );
+};
diff --git a/apps/papra-client/src/modules/tags/components/tag-picker-item.component.tsx b/apps/papra-client/src/modules/tags/components/tag-picker-item.component.tsx
new file mode 100644
index 00000000..1da51936
--- /dev/null
+++ b/apps/papra-client/src/modules/tags/components/tag-picker-item.component.tsx
@@ -0,0 +1,98 @@
+import type { Component, ComponentProps, ParentComponent } from 'solid-js';
+import type { Tag } from '../tags.types';
+import { splitProps } from 'solid-js';
+import { cn } from '@/modules/shared/style/cn';
+import { Checkbox, CheckboxControl } from '@/modules/ui/components/checkbox';
+
+export type TagPickerItemProps = {
+ selected: boolean;
+ highlighted: boolean;
+} & ComponentProps<'li'>;
+
+export const TagPickerItem: ParentComponent<TagPickerItemProps> = (props) => {
+ const [local, rest] = splitProps(props, ['children', 'selected', 'highlighted']);
+
+ return (
+ <li
+ class="px-1 cursor-pointer group"
+ role="option"
+ aria-selected={local.selected}
+ {...rest}
+ >
+ <div class={cn(
+ 'flex items-center gap-2 rounded-md cursor-pointer transition-colors',
+ local.highlighted ? 'bg-accent' : 'group-hover:bg-accent/50',
+ )}
+ >
+ {local.children}
+ </div>
+ </li>
+ );
+};
+
+export type TagPickerItemTagProps = {
+ tag: Tag;
+ selected: boolean;
+ highlighted: boolean;
+ onToggle: (selected: boolean) => void;
+};
+
+export const TagPickerItemTag: Component<TagPickerItemTagProps> = (props) => {
+ const handleRowClick = () => props.onToggle(!props.selected);
+ const handleCheckboxChange = (checked: boolean) => props.onToggle(checked);
+
+ const handleCheckboxAreaClick = (e: MouseEvent) => {
+ e.stopPropagation();
+ props.onToggle(!props.selected);
+ };
+
+ return (
+ <TagPickerItem
+ selected={props.selected}
+ highlighted={props.highlighted}
+ onClick={handleRowClick}
+ >
+ <div
+ class="flex items-center justify-center h-full pl-2 py-2"
+ onClick={handleCheckboxAreaClick}
+ >
+ <Checkbox
+ checked={props.selected}
+ onChange={handleCheckboxChange}
+ onClick={e => e.stopPropagation()}
+ >
+ <CheckboxControl class="border-transparent group-hover:border-border data-[checked]:(border-primary group-hover:border-primary)" />
+ </Checkbox>
+ </div>
+
+ <div class="flex items-center gap-2 min-w-0">
+ <span
+ class="size-2 rounded-full flex-shrink-0"
+ style={{ 'background-color': props.tag.color }}
+ />
+ <span class="text-sm truncate">{props.tag.name}</span>
+ </div>
+ </TagPickerItem>
+ );
+};
+
+export const TagPickerItemCreateNewTag: Component<{
+ highlighted: boolean;
+ onClick: () => void;
+ name?: string;
+}> = (props) => {
+ return (
+ <TagPickerItem
+ selected={false}
+ highlighted={props.highlighted}
+ onClick={props.onClick}
+ >
+ <div class="flex items-center gap-2 pl-2 py-2 text-muted-foreground">
+ <div class="i-tabler-plus size-4" />
+ <span class="text-sm">
+ {props.name ? `Create new tag "${props.name}"` : 'Create new tag'}
+ </span>
+ </div>
+ </TagPickerItem>
+ );
+};
diff --git a/apps/papra-client/src/modules/tags/components/tag-picker-list.component.tsx b/apps/papra-client/src/modules/tags/components/tag-picker-list.component.tsx
new file mode 100644
index 00000000..ea4cbd5e
--- /dev/null
+++ b/apps/papra-client/src/modules/tags/components/tag-picker-list.component.tsx
@@ -0,0 +1,51 @@
+import type { Component } from 'solid-js';
+import type { HighlightedItem, TagPickerListItem } from './use-tag-picker.hook';
+import { For, Match, Switch } from 'solid-js';
+import { TagPickerItemCreateNewTag, TagPickerItemTag } from './tag-picker-item.component';
+
+export type TagPickerListProps = {
+ listItems: TagPickerListItem[];
+ highlighted: HighlightedItem;
+ onToggle: (tagId: string, selected: boolean) => void;
+ onCreateNewTag?: () => void;
+};
+
+export const TagPickerList: Component<TagPickerListProps> = (props) => {
+ return (
+ <ul role="listbox" class="py-1">
+ <For each={props.listItems}>
+ {baseItem => (
+ <Switch>
+ <Match when={baseItem.type === 'tag' ? baseItem : null}>
+ {getTagItem => (
+ <TagPickerItemTag
+ tag={getTagItem().tag}
+ selected={getTagItem().isSelected}
+ highlighted={props.highlighted.tagId === getTagItem().tag.id}
+ onToggle={selected => props.onToggle(getTagItem().tag.id, selected)}
+ />
+ )}
+ </Match>
+
+ <Match when={baseItem.type === 'create-new-tag-button' ? baseItem : null}>
+ {getCreateTagItem => (
+ <TagPickerItemCreateNewTag
+ highlighted={props.highlighted.action === 'create-new-tag'}
+ onClick={() => props.onCreateNewTag?.()}
+ name={getCreateTagItem().name}
+ />
+ )}
+ </Match>
+
+ <Match when={baseItem.type === 'initially-selected-separator' ? baseItem : null}>
+ <li role="separator">
+ <hr class="my-1 border-t border-border/50" />
+ </li>
+ </Match>
+ </Switch>
+ )}
+ </For>
+
+ </ul>
+ );
+};
diff --git a/apps/papra-client/src/modules/tags/components/use-tag-picker.hook.ts b/apps/papra-client/src/modules/tags/components/use-tag-picker.hook.ts
new file mode 100644
index 00000000..1510fb61
--- /dev/null
+++ b/apps/papra-client/src/modules/tags/components/use-tag-picker.hook.ts
@@ -0,0 +1,157 @@
+import type { Tag } from '../tags.types';
+import { createMemo, createSignal } from 'solid-js';
+import { toArrayIf } from '@/modules/shared/utils/array';
+
+export type UseTagPickerOptions = {
+ getAvailableTags: () => Tag[];
+ getSelectedTagIds: () => string[];
+};
+
+export type HighlightedItem
+ = | { tagId: string; action?: never }
+ | { tagId?: never; action: 'create-new-tag' }
+ | { tagId?: never; action?: never }; // represents no highlight
+
+export type TagPickerListItemTag = {
+ type: 'tag';
+ tag: Tag;
+ isSelected: boolean;
+};
+
+export type TagPickerListItem = TagPickerListItemTag | {
+ type: 'create-new-tag-button';
+ name?: string;
+} | {
+ type: 'initially-selected-separator';
+};
+
+export function useTagPicker(options: UseTagPickerOptions) {
+ const [filterQuery, setFilterQuery] = createSignal('');
+ const [highlighted, setHighlighted] = createSignal<HighlightedItem>({});
+
+ const initiallySelectedTagIds = options.getSelectedTagIds?.() ?? [];
+
+ const getNormalizedFilterQuery = createMemo(() => filterQuery().trim().toLowerCase());
+
+ const getTagsListItems = createMemo<TagPickerListItemTag[]>(() =>
+ options.getAvailableTags()
+ .toSorted((a, b) => a.name.localeCompare(b.name))
+ .map(tag => ({
+ type: 'tag' as const,
+ tag,
+ isSelected: options.getSelectedTagIds().includes(tag.id),
+ isInitiallySelected: initiallySelectedTagIds.includes(tag.id),
+ })),
+ );
+
+ const getFilteredTagListItems = createMemo(() => getTagsListItems().filter(({ tag }) => tag.name.toLowerCase().includes(getNormalizedFilterQuery())));
+
+ const isExactMatch = createMemo(() => getFilteredTagListItems().some(({ tag }) => tag.name.toLowerCase() === getNormalizedFilterQuery()));
+
+ const shouldShowCreateOption = createMemo(() => {
+ if (options.getAvailableTags().length === 0) {
+ return true;
+ }
+ return getNormalizedFilterQuery().length > 0 && !isExactMatch();
+ });
+
+ const getListItems = createMemo<TagPickerListItem[]>(() => {
+ const tagListItems = getFilteredTagListItems();
+ const initiallySelectedTagsItems = tagListItems.filter(item => initiallySelectedTagIds.includes(item.tag.id));
+ const nonInitiallySelectedTagsItems = tagListItems.filter(item => !initiallySelectedTagIds.includes(item.tag.id));
+
+ const showSeparator = initiallySelectedTagsItems.length > 0 && nonInitiallySelectedTagsItems.length > 0;
+
+ return [
+ ...initiallySelectedTagsItems,
+ ...(toArrayIf(showSeparator, { type: 'initially-selected-separator' as const })),
+ ...nonInitiallySelectedTagsItems,
+ ...(toArrayIf(shouldShowCreateOption(), { type: 'create-new-tag-button', name: getNormalizedFilterQuery() } as const)),
+ ];
+ });
+
+ const getHighlightableItems = createMemo(() => getListItems().filter(item => item.type === 'tag' || item.type === 'create-new-tag-button'));
+
+ const highlightItem = (item: TagPickerListItem) => {
+ if (item.type === 'tag') {
+ setHighlighted({ tagId: item.tag.id });
+ } else if (item.type === 'create-new-tag-button') {
+ setHighlighted({ action: 'create-new-tag' });
+ }
+ };
+
+ const getCurrentHighlightIndex = () => {
+ const current = highlighted();
+ const highlightableItems = getHighlightableItems();
+
+ return highlightableItems.findIndex((item) => {
+ if (current.tagId && item.type === 'tag') {
+ return item.tag.id === current.tagId;
+ }
+ if (current.action === 'create-new-tag' && item.type === 'create-new-tag-button') {
+ return true;
+ }
+ return false;
+ });
+ };
+
+ const highlightNext = () => {
+ const highlightableItems = getHighlightableItems();
+ const itemsCount = highlightableItems.length;
+ if (itemsCount === 0) {
+ return;
+ }
+
+ const currentIndex = getCurrentHighlightIndex();
+
+ // No highlight - go to first item
+ if (currentIndex === -1) {
+ const firstItem = highlightableItems[0];
+ highlightItem(firstItem);
+ return;
+ }
+
+ // Go to next item or wrap to first
+ const nextIndex = (currentIndex + 1) % itemsCount;
+ const nextItem = highlightableItems[nextIndex];
+ highlightItem(nextItem);
+ };
+
+ const highlightPrevious = () => {
+ const highlightableItems = getHighlightableItems();
+ const itemsCount = highlightableItems.length;
+ if (itemsCount === 0) {
+ return;
+ }
+
+ const currentIndex = getCurrentHighlightIndex();
+
+ // No highlight - go to last item
+ if (currentIndex === -1) {
+ const lastItem = highlightableItems[itemsCount - 1];
+ highlightItem(lastItem);
+ return;
+ }
+
+ // Go to previous item or wrap to last
+ const previousIndex = (currentIndex - 1 + itemsCount) % itemsCount;
+ const previousItem = highlightableItems[previousIndex];
+ highlightItem(previousItem);
+ };
+
+ const resetHighlight = () => {
+ setHighlighted({});
+ };
+
+ return {
+ getListItems,
+ filterQuery,
+ setFilterQuery,
+ getNormalizedFilterQuery,
+ getTagsListItems,
+ highlighted,
+ highlightNext,
+ highlightPrevious,
+ resetHighlight,
+ };
+}
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 878c5f4a..bfc8080a 100644
--- a/apps/papra-client/src/modules/tags/pages/tags.page.tsx
+++ b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
@@ -1,5 +1,5 @@
import type { DialogTriggerProps } from '@kobalte/core/dialog';
-import type { Component, JSX } from 'solid-js';
+import type { Component, JSX, ValidComponent } from 'solid-js';
import type { Tag as TagType } from '../tags.types';
import { safely } from '@corentinth/chisels';
import { getValues, setValue } from '@modular-forms/solid';
@@ -23,7 +23,7 @@ import { createToast } from '@/modules/ui/components/sonner';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/modules/ui/components/table';
import { TextArea } from '@/modules/ui/components/textarea';
import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
-import { Tag, TagLink } from '../components/tag.component';
+import { Tag as TagComponent, TagLink } from '../components/tag.component';
import { createTag, deleteTag, fetchTags, updateTag } from '../tags.services';
// To keep, useful for generating swatches
@@ -120,7 +120,7 @@ const TagForm: Component<{
{props.submitButton}
{getFormValues().name && (
- <Tag {...getFormValues()} />
+ <TagComponent {...getFormValues()} />
)}
</div>
</Form>
@@ -128,13 +128,26 @@ const TagForm: Component<{
};
export const CreateTagModal: Component<{
- children: (props: DialogTriggerProps) => JSX.Element;
+ children?: <T extends ValidComponent | HTMLElement>(props: DialogTriggerProps<T>) => JSX.Element;
organizationId: string;
+ onTagCreated?: (args: { tag: TagType }) => void | Promise<void>;
+ initialName?: string;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
}> = (props) => {
- const [getIsModalOpen, setIsModalOpen] = createSignal(false);
+ const [getInternalIsModalOpen, setInternalIsModalOpen] = createSignal(false);
const { t } = useI18n();
const { getErrorMessage } = useI18nApiErrors({ t });
+ // Use controlled state if provided, otherwise use internal state
+ const getIsModalOpen = () => props.open ?? getInternalIsModalOpen();
+ const setIsModalOpen = (value: boolean) => {
+ props.onOpenChange?.(value);
+ if (props.open === undefined) {
+ setInternalIsModalOpen(value);
+ }
+ };
+
const createTagMutation = useMutation(() => ({
mutationFn: (data: { name: string; color: string; description: string }) => createTag({
name: data.name,
@@ -142,9 +155,9 @@ export const CreateTagModal: Component<{
description: data.description,
organizationId: props.organizationId,
}),
- onSuccess: async (data, variables) => {
+ onSuccess: async ({ tag }, variables) => {
await queryClient.invalidateQueries({
- queryKey: ['organizations', props.organizationId],
+ queryKey: ['organizations', props.organizationId, 'tags'],
refetchType: 'all',
});
@@ -154,6 +167,7 @@ export const CreateTagModal: Component<{
});
setIsModalOpen(false);
+ props.onTagCreated?.({ tag });
},
onError: (error) => {
createToast({
@@ -165,7 +179,7 @@ export const CreateTagModal: Component<{
return (
<Dialog open={getIsModalOpen()} onOpenChange={setIsModalOpen}>
- <DialogTrigger as={props.children} />
+ {props.children && <DialogTrigger as={props.children} /> }
<DialogContent>
<DialogHeader>
<DialogTitle>{t('tags.create')}</DialogTitle>
@@ -173,7 +187,7 @@ export const CreateTagModal: Component<{
<TagForm
onSubmit={createTagMutation.mutateAsync}
- initialValues={{ color: '#D8FF75' }}
+ initialValues={{ color: '#D8FF75', name: props.initialName }}
submitButton={(
<Button
type="submit"
diff --git a/apps/papra-client/src/modules/ui/components/color-swatch-picker.tsx b/apps/papra-client/src/modules/ui/components/color-swatch-picker.tsx
index f49a56f4..56568dc2 100644
--- a/apps/papra-client/src/modules/ui/components/color-swatch-picker.tsx
+++ b/apps/papra-client/src/modules/ui/components/color-swatch-picker.tsx
@@ -174,7 +174,7 @@ export function ColorSwatchPicker(props: ColorSwatchPickerProps) {
>
<div class="i-tabler-plus size-4" style={{ color: getIsNotInSwatch(local.value) ? getContrastTextColor(local.value ?? '') : undefined }} />
</PopoverTrigger>
- <PopoverContent>
+ <PopoverContent closable>
<p class="text-sm font-medium mb-4">{t('color-picker.select-a-color')}</p>
<ColorPicker color={local.value ?? ''} onChange={local?.onChange} />
diff --git a/apps/papra-client/src/modules/ui/components/combobox.tsx b/apps/papra-client/src/modules/ui/components/combobox.tsx
index ecef69b5..9dfa783a 100644
--- a/apps/papra-client/src/modules/ui/components/combobox.tsx
+++ b/apps/papra-client/src/modules/ui/components/combobox.tsx
@@ -91,10 +91,11 @@ export function ComboboxTrigger<T extends ValidComponent = 'button'>(props: Poly
type comboboxContentProps<T extends ValidComponent = 'div'>
= ComboboxContentProps<T> & {
class?: string;
+ footer?: JSX.Element;
};
export function ComboboxContent<T extends ValidComponent = 'div'>(props: PolymorphicProps<T, comboboxContentProps<T>>) {
- const [local, rest] = splitProps(props as comboboxContentProps, ['class']);
+ const [local, rest] = splitProps(props as comboboxContentProps, ['class', 'footer']);
return (
<ComboboxPrimitive.Portal>
@@ -106,6 +107,7 @@ export function ComboboxContent<T extends ValidComponent = 'div'>(props: Polymor
{...rest}
>
<ComboboxPrimitive.Listbox class="p-1" />
+ {local.footer}
</ComboboxPrimitive.Content>
</ComboboxPrimitive.Portal>
);
@@ -126,7 +128,7 @@ export function ComboboxItem<T extends ValidComponent = 'li'>(props: Polymorphic
return (
<ComboboxPrimitive.Item
class={cn(
- 'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none data-[disabled]:(pointer-events-none opacity-50) data-[highlighted]:(bg-accent text-accent-foreground)',
+ 'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none data-[disabled]:(pointer-events-none opacity-50) hover:bg-accent transition-colors ',
local.class,
)}
{...rest}
diff --git a/apps/papra-client/src/modules/ui/components/popover.tsx b/apps/papra-client/src/modules/ui/components/popover.tsx
index f147e165..34e6c1ef 100644
--- a/apps/papra-client/src/modules/ui/components/popover.tsx
+++ b/apps/papra-client/src/modules/ui/components/popover.tsx
@@ -27,6 +27,7 @@ export function Popover(props: PopoverRootProps) {
type popoverContentProps<T extends ValidComponent = 'div'> = ParentProps<
PopoverContentProps<T> & {
class?: string;
+ closable?: boolean;
}
>;
@@ -34,6 +35,7 @@ export function PopoverContent<T extends ValidComponent = 'div'>(props: Polymorp
const [local, rest] = splitProps(props as popoverContentProps, [
'class',
'children',
+ 'closable',
]);
return (
@@ -46,23 +48,25 @@ export function PopoverContent<T extends ValidComponent = 'div'>(props: Polymorp
{...rest}
>
{local.children}
- <PopoverPrimitive.CloseButton class="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:(outline-none ring-1.5 ring-ring ring-offset-2) disabled:pointer-events-none bg-inherit transition-property-[opacity,box-shadow]">
- <svg
- xmlns="http://www.w3.org/2000/svg"
- viewBox="0 0 24 24"
- class="h-4 w-4"
- >
- <path
- fill="none"
- stroke="currentColor"
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M18 6L6 18M6 6l12 12"
- />
- <title>Close</title>
- </svg>
- </PopoverPrimitive.CloseButton>
+ {local.closable && (
+ <PopoverPrimitive.CloseButton class="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:(outline-none ring-1.5 ring-ring ring-offset-2) disabled:pointer-events-none bg-inherit transition-property-[opacity,box-shadow]">
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ class="h-4 w-4"
+ >
+ <path
+ fill="none"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M18 6L6 18M6 6l12 12"
+ />
+ <title>Close</title>
+ </svg>
+ </PopoverPrimitive.CloseButton>
+ )}
</PopoverPrimitive.Content>
</PopoverPrimitive.Portal>
);