From 94ee54e4a6807762dc3484e181f9a8fa7af5354f Mon Sep 17 00:00:00 2001 From: shamoon <4887959+shamoon@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:49:24 -0800 Subject: [PATCH] Enhancement: nested tag 'split' display (#14843) --- .../admin/settings/settings.component.html | 6 + .../admin/settings/settings.component.spec.ts | 2 +- .../admin/settings/settings.component.ts | 6 + .../common/input/tags/tags.component.html | 17 ++- .../common/input/tags/tags.component.scss | 15 +++ .../common/input/tags/tags.component.spec.ts | 55 ++++++++ .../common/input/tags/tags.component.ts | 77 +++++++++-- .../components/common/tag/tag.component.html | 23 ++-- .../components/common/tag/tag.component.scss | 43 +++++++ .../common/tag/tag.component.spec.ts | 85 ++++++++++++ .../components/common/tag/tag.component.ts | 121 +++++++++++++++--- .../saved-view-widget.component.html | 4 +- .../saved-view-widget.component.ts | 2 + .../document-card-large.component.html | 4 +- .../document-card-large.component.ts | 2 + .../document-card-small.component.html | 9 +- .../document-card-small.component.scss | 3 +- .../document-card-small.component.spec.ts | 35 ++++- .../document-card-small.component.ts | 26 ++-- .../document-list.component.html | 4 +- .../document-list/document-list.component.ts | 2 + src-ui/src/app/data/ui-settings.ts | 6 + .../src/app/pipes/collapse-tags.pipe.spec.ts | 67 ++++++++++ src-ui/src/app/pipes/collapse-tags.pipe.ts | 47 +++++++ src-ui/src/app/utils/collapse-tags.spec.ts | 47 +++++++ src-ui/src/app/utils/collapse-tags.ts | 43 +++++++ 26 files changed, 681 insertions(+), 70 deletions(-) create mode 100644 src-ui/src/app/pipes/collapse-tags.pipe.spec.ts create mode 100644 src-ui/src/app/pipes/collapse-tags.pipe.ts create mode 100644 src-ui/src/app/utils/collapse-tags.spec.ts create mode 100644 src-ui/src/app/utils/collapse-tags.ts diff --git a/src-ui/src/app/components/admin/settings/settings.component.html b/src-ui/src/app/components/admin/settings/settings.component.html index c314f1afcc..6903f74068 100644 --- a/src-ui/src/app/components/admin/settings/settings.component.html +++ b/src-ui/src/app/components/admin/settings/settings.component.html @@ -227,6 +227,12 @@ +
+
+ +
+
+
Document editing
diff --git a/src-ui/src/app/components/admin/settings/settings.component.spec.ts b/src-ui/src/app/components/admin/settings/settings.component.spec.ts index 645b97f10a..66f2a04621 100644 --- a/src-ui/src/app/components/admin/settings/settings.component.spec.ts +++ b/src-ui/src/app/components/admin/settings/settings.component.spec.ts @@ -305,7 +305,7 @@ describe('SettingsComponent', () => { expect(toastErrorSpy).toHaveBeenCalled() expect(storeSpy).toHaveBeenCalled() expect(appearanceSettingsSpy).not.toHaveBeenCalled() - expect(setSpy).toHaveBeenCalledTimes(33) + expect(setSpy).toHaveBeenCalledTimes(34) expect(setSpy).toHaveBeenCalledWith(SETTINGS_KEYS.SIDEBAR_HIDDEN_ITEMS, [ HideableSidebarItemID.Workflows, ]) diff --git a/src-ui/src/app/components/admin/settings/settings.component.ts b/src-ui/src/app/components/admin/settings/settings.component.ts index 3f65e2cb50..1fd6d1ac9b 100644 --- a/src-ui/src/app/components/admin/settings/settings.component.ts +++ b/src-ui/src/app/components/admin/settings/settings.component.ts @@ -163,6 +163,7 @@ export class SettingsComponent bulkEditConfirmationDialogs: new FormControl(null), bulkEditApplyOnClose: new FormControl(null), documentListItemPerPage: new FormControl(null), + tagsShowHierarchy: new FormControl(null), slimSidebarEnabled: new FormControl(null), sidebarHiddenItems: new FormControl([]), darkModeUseSystem: new FormControl(null), @@ -342,6 +343,7 @@ export class SettingsComponent bulkEditApplyOnClose: this.settings.get( SETTINGS_KEYS.BULK_EDIT_APPLY_ON_CLOSE ), + tagsShowHierarchy: this.settings.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY), documentListItemPerPage: this.settings.get( SETTINGS_KEYS.DOCUMENT_LIST_SIZE ), @@ -607,6 +609,10 @@ export class SettingsComponent SETTINGS_KEYS.DEFAULT_PERMS_EDIT_GROUPS, this.settingsForm.value.defaultPermsEditGroups ) + this.settings.set( + SETTINGS_KEYS.TAGS_SHOW_HIERARCHY, + this.settingsForm.value.tagsShowHierarchy + ) this.settings.set( SETTINGS_KEYS.DOCUMENT_EDITING_REMOVE_INBOX_TAGS, this.settingsForm.value.documentEditingRemoveInboxTags diff --git a/src-ui/src/app/components/common/input/tags/tags.component.html b/src-ui/src/app/components/common/input/tags/tags.component.html index 4254b0dca7..1227bb35a6 100644 --- a/src-ui/src/app/components/common/input/tags/tags.component.html +++ b/src-ui/src/app/components/common/input/tags/tags.component.html @@ -17,16 +17,21 @@ [searchFn]="searchFn" addTagText="Add tag" i18n-addTagText + [keyDownFn]="onKeyDown" (add)="onAdd($event)" (change)="onChange(value)"> - + @if (isImplied(item.id)) { + + } @else { + + }
diff --git a/src-ui/src/app/components/common/input/tags/tags.component.scss b/src-ui/src/app/components/common/input/tags/tags.component.scss index 94da626994..80c8d8890a 100644 --- a/src-ui/src/app/components/common/input/tags/tags.component.scss +++ b/src-ui/src/app/components/common/input/tags/tags.component.scss @@ -7,6 +7,21 @@ font-size: 1rem; } +// ancestors of another selected tag render inside that tag's badge +::ng-deep .paperless-input-tags .ng-value:has(> .implied-tag) { + display: none !important; +} + +// let a long (nowrap) split badge shrink to the field instead of widening it +ng-select, +::ng-deep .paperless-input-tags .ng-value-container { + min-width: 0 !important; +} + +::ng-deep .paperless-input-tags .ng-value { + max-width: 100%; +} + .paperless-input-select.disabled { .input-group { cursor: not-allowed; diff --git a/src-ui/src/app/components/common/input/tags/tags.component.spec.ts b/src-ui/src/app/components/common/input/tags/tags.component.spec.ts index 184a6284a8..738a2413b0 100644 --- a/src-ui/src/app/components/common/input/tags/tags.component.spec.ts +++ b/src-ui/src/app/components/common/input/tags/tags.component.spec.ts @@ -278,4 +278,59 @@ describe('TagsComponent', () => { component.tags = [lone] expect(component.getParentChain(5)).toEqual([]) }) + + describe('hierarchy', () => { + const root: Tag = { id: 1, name: 'root' } + const mid: Tag = { id: 2, name: 'mid', parent: 1 } + const leaf: Tag = { id: 3, name: 'leaf', parent: 2 } + const other: Tag = { id: 4, name: 'other' } + + beforeEach(() => { + component.tags = [root, mid, leaf, other] + component.value = [3, 2, 1, 4] + }) + + it('should treat ancestors of another selected tag as implied', () => { + expect([1, 2, 3, 4].map((id) => component.isImplied(id))).toEqual([ + true, + true, + false, + false, + ]) + component.preserveHierarchy = false + expect(component.isImplied(1)).toBe(false) + }) + + it('should remove a whole badge, keeping ancestors other tags still need', () => { + component.removeBadge(3) + expect(component.value).toEqual([4]) + + const sibling: Tag = { id: 5, name: 'sibling', parent: 1 } + component.tags = [root, mid, leaf, other, sibling] + component.value = [3, 2, 1, 5, 4] + component.removeBadge(3) + expect(component.value).toEqual([1, 5, 4]) + }) + + it('should remove only the tag itself from a badge when hierarchy is not shown', () => { + component.preserveHierarchy = false + component.removeBadge(3) + expect(component.value).toEqual([2, 1, 4]) + }) + + it('should remove the last visible tag on backspace, not a hidden ancestor', () => { + const backspace = new KeyboardEvent('keydown', { key: 'Backspace' }) + expect(component.onKeyDown(backspace)).toBe(false) + expect(component.value).toEqual([3, 2, 1]) + expect(component.onKeyDown(backspace)).toBe(false) + expect(component.value).toEqual([2, 1]) + + // nothing hidden: leave it to ng-select + component.value = [4] + expect(component.onKeyDown(backspace)).toBe(true) + expect( + component.onKeyDown(new KeyboardEvent('keydown', { key: 'a' })) + ).toBe(true) + }) + }) }) diff --git a/src-ui/src/app/components/common/input/tags/tags.component.ts b/src-ui/src/app/components/common/input/tags/tags.component.ts index b0db1f3d3a..710334fd7d 100644 --- a/src-ui/src/app/components/common/input/tags/tags.component.ts +++ b/src-ui/src/app/components/common/input/tags/tags.component.ts @@ -21,7 +21,13 @@ import { NgSelectComponent, NgSelectModule } from '@ng-select/ng-select' import { first, firstValueFrom, tap } from 'rxjs' import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component' import { Tag } from 'src/app/data/tag' +import { SETTINGS_KEYS } from 'src/app/data/ui-settings' import { TagService } from 'src/app/services/rest/tag.service' +import { SettingsService } from 'src/app/services/settings.service' +import { + collapseImpliedAncestors, + getTagAncestors, +} from 'src/app/utils/collapse-tags' import { matchesSearchText } from 'src/app/utils/text-search' import { EditDialogMode } from '../../edit-dialog/edit-dialog.component' import { TagEditDialogComponent } from '../../edit-dialog/tag-edit-dialog/tag-edit-dialog.component' @@ -50,6 +56,7 @@ import { TagComponent } from '../../tag/tag.component' export class TagsComponent implements OnInit, ControlValueAccessor { private tagService = inject(TagService) private modalService = inject(NgbModal) + private readonly settingsService = inject(SettingsService) private readonly changeDetector = inject(ChangeDetectorRef) constructor() { @@ -131,6 +138,33 @@ export class TagsComponent implements OnInit, ControlValueAccessor { term ) + /** + * Selected tags that are ancestors of another selected tag which are shown + * as segments of their descendant's badge. + */ + isImplied(id: number): boolean { + if (!this.showsHierarchy || !this.tags || !this.value) return false + return !collapseImpliedAncestors(this.value, this.tagsById).includes(id) + } + + private get showsHierarchy(): boolean { + return ( + this.preserveHierarchy && + !!this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY) + ) + } + + /** + * Remove the last visible tag (in case its actually a hidden ancestor) + */ + readonly onKeyDown = (event: KeyboardEvent): boolean => { + if (event.key !== 'Backspace' || this.select?.searchTerm) return true + const visible = this.value?.filter((id) => !this.isImplied(id)) ?? [] + if (visible.length === (this.value?.length ?? 0)) return true + this.removeTag(visible.at(-1)) + return false + } + getTag(id: number) { if (this.tags) { return this.tags.find((tag) => tag.id == id) @@ -139,6 +173,26 @@ export class TagsComponent implements OnInit, ControlValueAccessor { } } + /** + * Remove a whole badge i.e. the tag plus any ancestors that no other selected + * tag still needs. + */ + removeBadge(tagID: number) { + if (this.disabled) return + if (!this.showsHierarchy) return this.removeTag(tagID) + + const ancestors = new Set(this.getParentChain(tagID).map((t) => t.id)) + const needed = new Set( + this.value + .filter((id) => id !== tagID && !ancestors.has(id)) + .flatMap((id) => this.getParentChain(id).map((t) => t.id)) + ) + this.value = this.value.filter( + (id) => id !== tagID && (!ancestors.has(id) || needed.has(id)) + ) + this.onChange(this.value) + } + removeTag(tagID: number) { if (this.disabled) return @@ -235,18 +289,17 @@ export class TagsComponent implements OnInit, ControlValueAccessor { } getParentChain(id: number): Tag[] { - // Returns ancestors from root → immediate parent for a tag id - const chain: Tag[] = [] - let current = this.getTag(id) - const guard = new Set() - while (current?.parent) { - if (guard.has(current.parent)) break - guard.add(current.parent) - const parent = this.getTag(current.parent) - if (!parent) break - chain.unshift(parent) - current = parent + return getTagAncestors(id, this.tagsById) + } + + private tagsByIdSource: Tag[] + private tagsByIdCache: Map + + private get tagsById(): Map { + if (this.tagsByIdSource !== this.tags) { + this.tagsByIdSource = this.tags + this.tagsByIdCache = new Map(this.tags?.map((t) => [t.id, t])) } - return chain + return this.tagsByIdCache } } diff --git a/src-ui/src/app/components/common/tag/tag.component.html b/src-ui/src/app/components/common/tag/tag.component.html index a7f2de44ce..38a58a6541 100644 --- a/src-ui/src/app/components/common/tag/tag.component.html +++ b/src-ui/src/app/components/common/tag/tag.component.html @@ -1,13 +1,18 @@ @if (tag()) { - @if (showParents() && tag().parent) { - -  >  - } - @if (!clickable()) { - {{tag().name}} - } - @if (clickable()) { - {{tag().name}} + @if (ancestorSegments.length) { + + @for (ancestor of ancestorSegments; track ancestor.id; let first = $first) { + {{ancestor.name}} + } + {{tag().name}} + + } @else { + @if (!clickable()) { + {{tag().name}} + } + @if (clickable()) { + {{tag().name}} + } } } @else if (loading) { diff --git a/src-ui/src/app/components/common/tag/tag.component.scss b/src-ui/src/app/components/common/tag/tag.component.scss index 5dc28b65f2..03166d25c5 100644 --- a/src-ui/src/app/components/common/tag/tag.component.scss +++ b/src-ui/src/app/components/common/tag/tag.component.scss @@ -11,3 +11,46 @@ a, span { opacity: .5; font-style: italic; } + +.split-parent, +.split-child { + overflow: hidden; + white-space: nowrap; + transition: color .2s ease; +} + +.split-parent { + min-width: 1.5em; + max-width: 10em; + padding-inline: .4em; + text-overflow: clip; + + &:nth-last-child(2) { flex-shrink: 1e12; } + &:nth-last-child(3) { flex-shrink: 1e18; } + &:nth-last-child(4) { flex-shrink: 1e24; } + &:nth-last-child(5) { flex-shrink: 1e30; } + + &.collapsed { + color: transparent !important; + } +} + +.split-child { + flex-shrink: 1e6; + min-width: 2em; + max-width: 20em; // nowrap, so very long names would otherwise widen e.g. table columns + text-overflow: ellipsis; +} + +// Hovered segment gets priority, other parents can shrink to a sliver +.split-pill { + > .split-parent.focused, + > .split-child.focused { + flex-shrink: 1; + text-overflow: ellipsis; + } + + &:has(> .focused) > .split-parent:not(.focused) { + min-width: 0; + } +} diff --git a/src-ui/src/app/components/common/tag/tag.component.spec.ts b/src-ui/src/app/components/common/tag/tag.component.spec.ts index 06d79d96ab..e7ce719702 100644 --- a/src-ui/src/app/components/common/tag/tag.component.spec.ts +++ b/src-ui/src/app/components/common/tag/tag.component.spec.ts @@ -6,6 +6,7 @@ import { of } from 'rxjs' import { Tag } from 'src/app/data/tag' import { PermissionsService } from 'src/app/services/permissions.service' import { TagService } from 'src/app/services/rest/tag.service' +import { SettingsService } from 'src/app/services/settings.service' import { TagComponent } from './tag.component' const tag: Tag = { @@ -69,4 +70,88 @@ describe('TagComponent', () => { expect(getCachedSpy).toHaveBeenCalledWith(1) expect(component.tag()).toEqual(tag) }) + describe('split badge', () => { + const root: Tag = { id: 1, name: 'Root', color: '#000000' } + const mid: Tag = { id: 2, name: 'Mid', color: '#111111', parent: 1 } + const leaf: Tag = { id: 3, name: 'Leaf', color: '#222222', parent: 2 } + + const segments = (): HTMLElement[] => + fixture.debugElement + .queryAll(By.css('.split-pill > .badge')) + .map((d) => d.nativeElement) + + beforeEach(() => { + jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true) + jest.spyOn(tagService, 'getCached').mockReturnValue(of(leaf)) + jest + .spyOn(tagService, 'listAll') + .mockReturnValue( + of({ count: 3, all: [1, 2, 3], results: [root, mid, leaf] }) + ) + fixture.componentRef.setInput('tagID', 3) + fixture.componentRef.setInput('split', true) + fixture.detectChanges() + }) + + it('should render ancestors as segments with the full path as title', () => { + expect(segments().map((s) => s.textContent.trim())).toEqual([ + 'Root', + 'Mid', + 'Leaf', + ]) + expect( + fixture.debugElement.query(By.css('.split-pill')).nativeElement.title + ).toEqual('Root › Mid › Leaf') + }) + + it('should render a plain badge when the setting is off', () => { + jest.spyOn(TestBed.inject(SettingsService), 'get').mockReturnValue(false) + fixture.componentRef.setInput('split', false) + fixture.detectChanges() + fixture.componentRef.setInput('split', true) + fixture.detectChanges() + expect(fixture.debugElement.query(By.css('.split-pill'))).toBeNull() + expect(component.ancestorSegments).toEqual([]) + }) + + it('should emit the ancestor id when an ancestor segment is clicked', () => { + const emitSpy = jest.spyOn(component.parentClick, 'emit') + const event = new MouseEvent('click', { bubbles: true }) + const stopSpy = jest.spyOn(event, 'stopImmediatePropagation') + segments()[1].dispatchEvent(event) + expect(emitSpy).toHaveBeenCalledWith(2) + expect(stopSpy).toHaveBeenCalled() + }) + + it('should focus the hovered segment and animate width changes', () => { + const [rootSeg, midSeg, leafSeg] = segments() + const pill = rootSeg.parentElement + // before / after widths per segment, as measured by setFocus + const widths = new Map([ + [rootSeg, [20, 4]], + [midSeg, [20, 60]], + [leafSeg, [40, 40]], + ]) + const animate = jest.fn() + for (const [seg, [before, after]] of widths) { + seg.getAnimations = jest.fn(() => []) + seg.animate = animate + jest + .spyOn(seg, 'getBoundingClientRect') + .mockReturnValueOnce({ width: before } as DOMRect) + .mockReturnValueOnce({ width: after } as DOMRect) + } + + midSeg.dispatchEvent(new MouseEvent('mouseenter')) + expect(midSeg.classList).toContain('focused') + expect(rootSeg.classList).not.toContain('focused') + // only the segments whose width changed are animated + expect(animate).toHaveBeenCalledTimes(2) + + pill.dispatchEvent(new MouseEvent('mouseleave')) + expect(segments().some((s) => s.classList.contains('focused'))).toBe( + false + ) + }) + }) }) diff --git a/src-ui/src/app/components/common/tag/tag.component.ts b/src-ui/src/app/components/common/tag/tag.component.ts index 0cb17ad8e0..5f6d0d9267 100644 --- a/src-ui/src/app/components/common/tag/tag.component.ts +++ b/src-ui/src/app/components/common/tag/tag.component.ts @@ -1,11 +1,27 @@ -import { Component, effect, inject, input, model } from '@angular/core' +import { + Component, + computed, + effect, + inject, + input, + model, + output, + signal, +} from '@angular/core' import { Tag } from 'src/app/data/tag' +import { SETTINGS_KEYS } from 'src/app/data/ui-settings' import { PermissionAction, PermissionsService, PermissionType, } from 'src/app/services/permissions.service' import { TagService } from 'src/app/services/rest/tag.service' +import { SettingsService } from 'src/app/services/settings.service' +import { getTagAncestors } from 'src/app/utils/collapse-tags' + +const FOCUS_ANIMATION_MS = 200 +// matches the .split-parent min-width in tag.component.scss +const COLLAPSE_BELOW_EM = 1.5 @Component({ selector: 'pngx-tag', @@ -13,8 +29,9 @@ import { TagService } from 'src/app/services/rest/tag.service' styleUrls: ['./tag.component.scss'], }) export class TagComponent { - private permissionsService = inject(PermissionsService) - private tagService = inject(TagService) + private readonly permissionsService = inject(PermissionsService) + private readonly tagService = inject(TagService) + private readonly settingsService = inject(SettingsService) readonly tag = model(null) readonly tagID = input(undefined) @@ -23,27 +40,101 @@ export class TagComponent { transform: (value: boolean | string) => value === '' || value === true || value === 'true', }) - readonly showParents = input(false) + + readonly split = input(false) + + readonly parentClick = output() + + private readonly ancestors = signal([]) + + public get ancestorSegments(): Tag[] { + return this.split() && + this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY) + ? this.ancestors() + : [] + } + + public readonly path = computed(() => + [...this.ancestors(), this.tag()] + .filter(Boolean) + .map((t) => t.name) + .join(' › ') + ) constructor() { effect(() => { const tagID = this.tagID() - if (tagID) { - if ( - this.permissionsService.currentUserCan( - PermissionAction.View, - PermissionType.Tag - ) - ) { - this.tagService.getCached(tagID).subscribe((tag) => { - this.tag.set(tag) - }) - } + if (tagID && this.canViewTags) { + this.tagService.getCached(tagID).subscribe((tag) => { + this.tag.set(tag) + }) } }) + + // ancestors for split badges, from either tagID or a passed-in tag + effect(() => { + const id = this.tagID() || this.tag()?.id + if (!this.split() || !id || !this.canViewTags) { + this.ancestors.set([]) + return + } + this.tagService.listAll().subscribe((tags) => { + this.ancestors.set( + getTagAncestors( + id, + new Map(tags.results.map((t) => [t.id, t])) + ) + ) + }) + }) + } + + private get canViewTags(): boolean { + return this.permissionsService.currentUserCan( + PermissionAction.View, + PermissionType.Tag + ) } public get loading(): boolean { return this.tagService.loading } + + /** + * Gives the hovered segment priority (.focused class, see scss) + * and animates each from old width to new + */ + setFocus(segment: HTMLElement, focused: HTMLElement | null) { + const segments = Array.from(segment.children) as HTMLElement[] + const before = segments.map((s) => s.getBoundingClientRect().width) + for (const segment of segments) { + segment.getAnimations().forEach((a) => a.cancel()) + segment.classList.toggle('focused', segment === focused) + } + const after = segments.map((s) => s.getBoundingClientRect().width) + + segments.forEach((segment, i) => { + const em = Number.parseFloat(getComputedStyle(segment).fontSize) + segment.classList.toggle( + 'collapsed', + !!focused && + segment.classList.contains('split-parent') && + after[i] < COLLAPSE_BELOW_EM * em + ) + if (Math.abs(after[i] - before[i]) < 0.5) return + segment.animate( + [ + { flex: `0 0 ${before[i]}px`, minWidth: 0 }, + { flex: `0 0 ${after[i]}px`, minWidth: 0 }, + ], + { duration: FOCUS_ANIMATION_MS, easing: 'ease' } + ) + }) + } + + onParentClick(event: MouseEvent, id: number) { + event.preventDefault() + event.stopImmediatePropagation() + this.parentClick.emit(id) + } } diff --git a/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html b/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html index 823e4f2aff..4f94cfee47 100644 --- a/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html +++ b/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html @@ -76,8 +76,8 @@ } } @case (DisplayField.TAGS) { - @for (tagID of doc.tags; track tagID) { - + @for (tagID of doc.tags | collapseTags | async; track tagID) { + } } @case (DisplayField.DOCUMENT_TYPE) { diff --git a/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.ts b/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.ts index 5daf99fb22..4e5e2d3bd0 100644 --- a/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.ts +++ b/src-ui/src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.ts @@ -38,6 +38,7 @@ import { } from 'src/app/data/filter-rule-type' import { SavedView } from 'src/app/data/saved-view' import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive' +import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe' import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe' import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe' import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe' @@ -75,6 +76,7 @@ import { WidgetFrameComponent } from '../widget-frame/widget-frame.component' DocumentTypeNamePipe, StoragePathNamePipe, AsyncPipe, + CollapseTagsPipe, DocumentTitlePipe, CustomDatePipe, NgClass, diff --git a/src-ui/src/app/components/document-list/document-card-large/document-card-large.component.html b/src-ui/src/app/components/document-list/document-card-large/document-card-large.component.html index 19a1e816bf..6f6067a932 100644 --- a/src-ui/src/app/components/document-list/document-card-large/document-card-large.component.html +++ b/src-ui/src/app/components/document-list/document-card-large/document-card-large.component.html @@ -36,8 +36,8 @@ {{document().title | documentTitle}} } @if (displayFields().includes(DisplayField.TAGS)) { - @for (tagID of document().tags; track tagID) { - + @for (tagID of document().tags | collapseTags | async; track tagID) { + } } } @else { diff --git a/src-ui/src/app/components/document-list/document-card-large/document-card-large.component.ts b/src-ui/src/app/components/document-list/document-card-large/document-card-large.component.ts index 293b3ddd2f..98a5d286e4 100644 --- a/src-ui/src/app/components/document-list/document-card-large/document-card-large.component.ts +++ b/src-ui/src/app/components/document-list/document-card-large/document-card-large.component.ts @@ -20,6 +20,7 @@ import { Document, } from 'src/app/data/document' import { SETTINGS_KEYS } from 'src/app/data/ui-settings' +import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe' import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe' import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe' import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe' @@ -45,6 +46,7 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading TagComponent, CustomFieldDisplayComponent, AsyncPipe, + CollapseTagsPipe, NgOptimizedImage, UsernamePipe, CorrespondentNamePipe, diff --git a/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.html b/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.html index 8c05d95d74..1b77c34ecf 100644 --- a/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.html +++ b/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.html @@ -19,11 +19,12 @@ } @if (document() && displayFields().includes(DisplayField.TAGS)) { -
- @for (tagID of tagIDs; track tagID) { - + @let visibleTagIDs = document().tags | collapseTags | async; +
+ @for (tagID of getTagIDs(visibleTagIDs); track tagID) { + } - @if (moreTags) { + @if (getMoreTags(visibleTagIDs); as moreTags) {
+ {{moreTags}}
diff --git a/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.scss b/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.scss index d098b126bc..0aa525fa31 100644 --- a/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.scss +++ b/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.scss @@ -103,7 +103,8 @@ a { line-height: 1; &.tags-no-wrap { - ::ng-deep .badge { + // split-pill parents clip to a stub instead (see TagComponent) + ::ng-deep .badge:not(.split-parent) { display: inline-block; max-width: 100%; white-space: nowrap; diff --git a/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.spec.ts b/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.spec.ts index 2b5b3245d4..c28037ab7f 100644 --- a/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.spec.ts +++ b/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.spec.ts @@ -4,6 +4,9 @@ import { provideHttpClientTesting } from '@angular/common/http/testing' import { ComponentFixture, TestBed } from '@angular/core/testing' import { By } from '@angular/platform-browser' import { RouterTestingModule } from '@angular/router/testing' +import { of } from 'rxjs' +import { PermissionsService } from 'src/app/services/permissions.service' +import { TagService } from 'src/app/services/rest/tag.service' import { TagComponent } from '../../common/tag/tag.component' import { DocumentCardSmallComponent } from './document-card-small.component' @@ -97,8 +100,36 @@ describe('DocumentCardSmallComponent', () => { ).toHaveLength(6) }) + it('should hide parent tags implied by a child and count pills for the hidden tag counter', () => { + jest + .spyOn(TestBed.inject(PermissionsService), 'currentUserCan') + .mockReturnValue(true) + jest.spyOn(TestBed.inject(TagService), 'listAll').mockReturnValue( + of({ + count: 8, + all: [1, 2, 3, 4, 5, 6, 7, 8], + results: [ + { id: 1, name: 'Parent' }, + { id: 2, name: 'Child', parent: 1 }, + ...[3, 4, 5, 6, 7, 8].map((id) => ({ id, name: `Tag ${id}` })), + ], + }) + ) + fixture.componentRef.setInput('document', { + ...component.document(), + tags: [1, 2, 3, 4, 5, 6, 7, 8], + }) + fixture.detectChanges() + + const tags = fixture.debugElement.queryAll(By.directive(TagComponent)) + expect(tags.map((t) => t.componentInstance.tagID())).toEqual([ + 2, 3, 4, 5, 6, + ]) + expect(fixture.nativeElement.textContent).toContain('+ 2') + }) + it('should clear hidden tag counter when tag count falls below the limit', () => { - expect(component.moreTags).toEqual(3) + expect(component.getMoreTags(component.document().tags)).toEqual(3) fixture.componentRef.setInput('document', { ...component.document(), @@ -106,7 +137,7 @@ describe('DocumentCardSmallComponent', () => { }) fixture.detectChanges() - expect(component.moreTags).toBeNull() + expect(component.getMoreTags(component.document().tags)).toBeNull() expect(fixture.nativeElement.textContent).not.toContain('+ 3') }) diff --git a/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.ts b/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.ts index 784b47ce08..6b9e5f0972 100644 --- a/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.ts +++ b/src-ui/src/app/components/document-list/document-card-small/document-card-small.component.ts @@ -20,6 +20,7 @@ import { Document, } from 'src/app/data/document' import { SETTINGS_KEYS } from 'src/app/data/ui-settings' +import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe' import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe' import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe' import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe' @@ -45,6 +46,7 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading TagComponent, CustomFieldDisplayComponent, AsyncPipe, + CollapseTagsPipe, NgOptimizedImage, UsernamePipe, CorrespondentNamePipe, @@ -90,12 +92,13 @@ export class DocumentCardSmallComponent @Output() clickStoragePath = new EventEmitter() - get moreTags(): number { - const document = this.document() - const limit = document?.notes.length > 0 ? 6 : 7 - return document?.tags.length > limit - ? document.tags.length - (limit - 1) - : null + private get tagLimit(): number { + return this.document()?.notes.length > 0 ? 6 : 7 + } + + getMoreTags(tagIDs: number[]): number { + const limit = this.tagLimit + return tagIDs?.length > limit ? tagIDs.length - (limit - 1) : null } @ViewChild('popupPreview') popupPreview: PreviewPopupComponent @@ -116,14 +119,9 @@ export class DocumentCardSmallComponent return this.documentService.getDownloadUrl(this.document().id) } - get tagIDs() { - const document = this.document() - const limit = document.notes.length > 0 ? 6 : 7 - if (document.tags.length > limit) { - return document.tags.slice(0, limit - 1) - } else { - return document.tags - } + getTagIDs(tagIDs: number[]): number[] { + const limit = this.tagLimit + return tagIDs?.length > limit ? tagIDs.slice(0, limit - 1) : tagIDs } mouseLeaveCard() { diff --git a/src-ui/src/app/components/document-list/document-list.component.html b/src-ui/src/app/components/document-list/document-list.component.html index 71c384300c..3f6e2e56bd 100644 --- a/src-ui/src/app/components/document-list/document-list.component.html +++ b/src-ui/src/app/components/document-list/document-list.component.html @@ -335,8 +335,8 @@ {{d.title | documentTitle}} } @if (activeDisplayFields.includes(DisplayField.TAGS)) { - @for (tagID of d.tags; track tagID) { - + @for (tagID of d.tags | collapseTags | async; track tagID) { + } } diff --git a/src-ui/src/app/components/document-list/document-list.component.ts b/src-ui/src/app/components/document-list/document-list.component.ts index b182b40af2..146e3dda88 100644 --- a/src-ui/src/app/components/document-list/document-list.component.ts +++ b/src-ui/src/app/components/document-list/document-list.component.ts @@ -39,6 +39,7 @@ import { SortableDirective, SortEvent, } from 'src/app/directives/sortable.directive' +import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe' import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe' import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe' import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe' @@ -96,6 +97,7 @@ import { SaveViewConfigDialogComponent } from './save-view-config-dialog/save-vi StoragePathNamePipe, BootstrapIconComponent, AsyncPipe, + CollapseTagsPipe, FormsModule, ReactiveFormsModule, NgTemplateOutlet, diff --git a/src-ui/src/app/data/ui-settings.ts b/src-ui/src/app/data/ui-settings.ts index 7542f10918..58049f3717 100644 --- a/src-ui/src/app/data/ui-settings.ts +++ b/src-ui/src/app/data/ui-settings.ts @@ -95,6 +95,7 @@ export const SETTINGS_KEYS = { DEFAULT_PERMS_VIEW_GROUPS: 'general-settings:permissions:default-view-groups', DEFAULT_PERMS_EDIT_USERS: 'general-settings:permissions:default-edit-users', DEFAULT_PERMS_EDIT_GROUPS: 'general-settings:permissions:default-edit-groups', + TAGS_SHOW_HIERARCHY: 'general-settings:tags:show-hierarchy', DOCUMENT_EDITING_REMOVE_INBOX_TAGS: 'general-settings:document-editing:remove-inbox-tags', DOCUMENT_EDITING_OVERLAY_THUMBNAIL: @@ -311,6 +312,11 @@ export const SETTINGS: UiSetting[] = [ type: 'string', default: '', }, + { + key: SETTINGS_KEYS.TAGS_SHOW_HIERARCHY, + type: 'boolean', + default: true, + }, { key: SETTINGS_KEYS.DOCUMENT_EDITING_REMOVE_INBOX_TAGS, type: 'boolean', diff --git a/src-ui/src/app/pipes/collapse-tags.pipe.spec.ts b/src-ui/src/app/pipes/collapse-tags.pipe.spec.ts new file mode 100644 index 0000000000..d9f3b23220 --- /dev/null +++ b/src-ui/src/app/pipes/collapse-tags.pipe.spec.ts @@ -0,0 +1,67 @@ +import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http' +import { provideHttpClientTesting } from '@angular/common/http/testing' +import { TestBed } from '@angular/core/testing' +import { firstValueFrom, of, throwError } from 'rxjs' +import { Tag } from '../data/tag' +import { PermissionsService } from '../services/permissions.service' +import { TagService } from '../services/rest/tag.service' +import { SettingsService } from '../services/settings.service' +import { CollapseTagsPipe } from './collapse-tags.pipe' + +const tags: Tag[] = [ + { id: 1, name: 'Parent' }, + { id: 2, name: 'Child', parent: 1 }, + { id: 3, name: 'Other' }, +] + +describe('CollapseTagsPipe', () => { + let pipe: CollapseTagsPipe + let tagService: TagService + let settingsService: SettingsService + let permissionsService: PermissionsService + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + CollapseTagsPipe, + provideHttpClient(withInterceptorsFromDi()), + provideHttpClientTesting(), + ], + }) + pipe = TestBed.inject(CollapseTagsPipe) + tagService = TestBed.inject(TagService) + settingsService = TestBed.inject(SettingsService) + permissionsService = TestBed.inject(PermissionsService) + jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true) + jest.spyOn(settingsService, 'get').mockReturnValue(true) + jest + .spyOn(tagService, 'listAll') + .mockReturnValue(of({ count: 3, all: [1, 2, 3], results: tags })) + }) + + it('should drop parents implied by a selected child', async () => { + expect(await firstValueFrom(pipe.transform([1, 2, 3]))).toEqual([2, 3]) + }) + + it('should pass ids through when hierarchy display is off or not permitted', async () => { + jest.spyOn(settingsService, 'get').mockReturnValue(false) + expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual([1, 2]) + + jest.spyOn(settingsService, 'get').mockReturnValue(true) + jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(false) + expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual([1, 2]) + expect(tagService.listAll).not.toHaveBeenCalled() + }) + + it('should handle empty input', async () => { + expect(await firstValueFrom(pipe.transform(null))).toEqual([]) + expect(await firstValueFrom(pipe.transform([]))).toEqual([]) + }) + + it('should fall back to the original ids if tags fail to load', async () => { + jest + .spyOn(tagService, 'listAll') + .mockReturnValue(throwError(() => new Error('failed'))) + expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual([1, 2]) + }) +}) diff --git a/src-ui/src/app/pipes/collapse-tags.pipe.ts b/src-ui/src/app/pipes/collapse-tags.pipe.ts new file mode 100644 index 0000000000..5ba98766d3 --- /dev/null +++ b/src-ui/src/app/pipes/collapse-tags.pipe.ts @@ -0,0 +1,47 @@ +import { inject, Pipe, PipeTransform } from '@angular/core' +import { catchError, map, Observable, of } from 'rxjs' +import { Tag } from '../data/tag' +import { SETTINGS_KEYS } from '../data/ui-settings' +import { + PermissionAction, + PermissionsService, + PermissionType, +} from '../services/permissions.service' +import { TagService } from '../services/rest/tag.service' +import { SettingsService } from '../services/settings.service' +import { collapseImpliedAncestors } from '../utils/collapse-tags' + +/** + * Drops tag IDs whose descendant is also in the list for when the child's + * Tag badge already shows its parent. + */ +@Pipe({ + name: 'collapseTags', +}) +export class CollapseTagsPipe implements PipeTransform { + private readonly permissionsService = inject(PermissionsService) + private readonly tagService = inject(TagService) + private readonly settingsService = inject(SettingsService) + + transform(ids: number[]): Observable { + if ( + !ids?.length || + !this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY) || + !this.permissionsService.currentUserCan( + PermissionAction.View, + PermissionType.Tag + ) + ) { + return of(ids ?? []) + } + return this.tagService.listAll().pipe( + map((tags) => + collapseImpliedAncestors( + ids, + new Map(tags.results.map((t) => [t.id, t])) + ) + ), + catchError(() => of(ids)) + ) + } +} diff --git a/src-ui/src/app/utils/collapse-tags.spec.ts b/src-ui/src/app/utils/collapse-tags.spec.ts new file mode 100644 index 0000000000..f63ed36dfd --- /dev/null +++ b/src-ui/src/app/utils/collapse-tags.spec.ts @@ -0,0 +1,47 @@ +import { Tag } from '../data/tag' +import { collapseImpliedAncestors, getTagAncestors } from './collapse-tags' + +const tags: Tag[] = [ + { id: 1, name: 'Finance' }, + { id: 2, name: 'Account', parent: 1 }, + { id: 3, name: 'Mortgage', parent: 2 }, + { id: 4, name: 'Taxes', parent: 1 }, + { id: 5, name: 'Inbox' }, +] +const tagsById = new Map(tags.map((t) => [t.id, t])) + +describe('collapseImpliedAncestors', () => { + it('drops ancestors that are implied by a descendant in the list', () => { + expect(collapseImpliedAncestors([1, 2, 3, 4, 5], tagsById)).toEqual([ + 3, 4, 5, + ]) + }) + + it('keeps a parent with none of its children present', () => { + expect(collapseImpliedAncestors([1, 5], tagsById)).toEqual([1, 5]) + }) + + it('keeps unknown (private) ids and handles empty input', () => { + expect(collapseImpliedAncestors([99, 2], tagsById)).toEqual([99, 2]) + expect(collapseImpliedAncestors([], tagsById)).toEqual([]) + expect(collapseImpliedAncestors(null, tagsById)).toEqual([]) + }) +}) + +describe('getTagAncestors', () => { + it('returns ancestors root first', () => { + expect(getTagAncestors(3, tagsById).map((t) => t.id)).toEqual([1, 2]) + expect(getTagAncestors(5, tagsById)).toEqual([]) + }) + + it('stops at a parent that is not visible or forms a cycle', () => { + const hidden = new Map([[6, { id: 6, name: 'x', parent: 99 }]]) + expect(getTagAncestors(6, hidden)).toEqual([]) + + const cyclic = new Map([ + [7, { id: 7, name: 'a', parent: 8 }], + [8, { id: 8, name: 'b', parent: 7 }], + ]) + expect(getTagAncestors(7, cyclic).map((t) => t.id)).toEqual([7, 8]) + }) +}) diff --git a/src-ui/src/app/utils/collapse-tags.ts b/src-ui/src/app/utils/collapse-tags.ts new file mode 100644 index 0000000000..72f31646fb --- /dev/null +++ b/src-ui/src/app/utils/collapse-tags.ts @@ -0,0 +1,43 @@ +import { Tag } from '../data/tag' + +/** + * Collapses implied ancestor tags from a list of tag IDs such that if a tag's + * ancestor is also present in the list, the ancestor is removed. For example + * [Finance, Account, Mortgage] -> [Mortgage] + */ +export function collapseImpliedAncestors( + ids: number[], + tagsById: Map +): number[] { + if (!ids?.length) return ids ?? [] + const present = new Set(ids) + const implied = new Set() + for (const id of ids) { + const seen = new Set() + let parentId = tagsById.get(id)?.parent + while (parentId && !seen.has(parentId)) { + seen.add(parentId) + if (present.has(parentId)) implied.add(parentId) + parentId = tagsById.get(parentId)?.parent + } + } + return ids.filter((id) => !implied.has(id)) +} + +/** + * Returns an array of ancestor tags for the given tag ID, starting from the + * root and ending with the immediate parent. + */ +export function getTagAncestors(id: number, tagsById: Map): Tag[] { + const chain: Tag[] = [] + const seen = new Set() + let parentId = tagsById.get(id)?.parent + while (parentId && !seen.has(parentId)) { + seen.add(parentId) + const parent = tagsById.get(parentId) + if (!parent) break + chain.unshift(parent) + parentId = parent.parent + } + return chain +}