Compare commits

...
26 changed files with 670 additions and 70 deletions

No files matched your search

@@ -227,6 +227,12 @@
</div>
</div>
<div class="row">
<div class="col">
<pngx-input-check i18n-title title="Show nested tags with their parents" i18n-hint hint="Child tags are shown together with their parent tags, instead of separately." formControlName="tagsShowHierarchy"></pngx-input-check>
</div>
</div>
<h5 class="mt-3" i18n>Document editing</h5>
<div class="row">
<div class="col">
@@ -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,
])
@@ -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<HideableSidebarItemID[]>([]),
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
@@ -17,16 +17,21 @@
[searchFn]="searchFn"
addTagText="Add tag"
i18n-addTagText
[keyDownFn]="onKeyDown"
(add)="onAdd($event)"
(change)="onChange(value)">
<ng-template ng-label-tmp let-item="item">
<button class="tag-wrap btn p-0 d-flex align-items-center" (click)="removeTag(item.id)" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tag" i18n-title>
<pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon>
@if (item.id && tags) {
<pngx-tag style="background-color: none;" [tag]="getTag(item.id)"></pngx-tag>
}
</button>
@if (isImplied(item.id)) {
<span class="implied-tag"></span>
} @else {
<button class="tag-wrap btn p-0 d-flex align-items-center mw-100" (click)="removeBadge(item.id)" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tag" i18n-title>
<pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon>
@if (item.id && tags) {
<pngx-tag class="mw-100 overflow-hidden" [tag]="getTag(item.id)" [split]="preserveHierarchy" (click)="removeTag(item.id); $event.stopPropagation()" (parentClick)="removeTag($event)"></pngx-tag>
}
</button>
}
</ng-template>
<ng-template ng-option-tmp let-item="item" let-index="index" let-search="searchTerm">
<div class="tag-option-row d-flex align-items-center" [class.w-auto]="!getTag(item.id)?.parent">
@@ -7,6 +7,11 @@
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;
}
.paperless-input-select.disabled {
.input-group {
cursor: not-allowed;
@@ -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)
})
})
})
@@ -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<number>()
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<number, Tag>
private get tagsById(): Map<number, Tag> {
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
}
}
@@ -1,13 +1,18 @@
@if (tag()) {
@if (showParents() && tag().parent) {
<pngx-tag [tagID]="tag().parent" [clickable]="clickable()" [linkTitle]="linkTitle()"></pngx-tag>
&nbsp;&gt;&nbsp;
}
@if (!clickable()) {
<span class="badge" [style.background]="tag().color" [style.color]="tag().text_color">{{tag().name}}</span>
}
@if (clickable()) {
<a [title]="linkTitle()" class="badge" [style.background]="tag().color" [style.color]="tag().text_color">{{tag().name}}</a>
@if (ancestorSegments.length) {
<span #pill class="split-pill d-inline-flex mw-100" [title]="path()" (mouseleave)="setFocus(pill, null)">
@for (ancestor of ancestorSegments; track ancestor.id; let first = $first) {
<span #segment class="badge split-parent" [class.rounded-end-0]="first" [class.rounded-0]="!first" [style.background]="ancestor.color" [style.color]="ancestor.text_color" (mouseenter)="setFocus(pill, segment)" (click)="onParentClick($event, ancestor.id)">{{ancestor.name}}</span>
}
<span #leaf class="badge rounded-start-0 split-child" [style.background]="tag().color" [style.color]="tag().text_color" (mouseenter)="setFocus(pill, leaf)">{{tag().name}}</span>
</span>
} @else {
@if (!clickable()) {
<span class="badge" [style.background]="tag().color" [style.color]="tag().text_color">{{tag().name}}</span>
}
@if (clickable()) {
<a [title]="linkTitle()" class="badge" [style.background]="tag().color" [style.color]="tag().text_color">{{tag().name}}</a>
}
}
} @else if (loading) {
<span class="placeholder-glow">
@@ -11,3 +11,45 @@ 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;
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;
}
}
@@ -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<HTMLElement, number[]>([
[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
)
})
})
})
@@ -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<Tag>(null)
readonly tagID = input<number>(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<number>()
private readonly ancestors = signal<Tag[]>([])
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<number, Tag>(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)
}
}
@@ -76,8 +76,8 @@
}
}
@case (DisplayField.TAGS) {
@for (tagID of doc.tags; track tagID) {
<pngx-tag [tagID]="tagID" class="ms-1 fs-6" (click)="clickTag(tagID, $event)" [clickable]="true" linkTitle="Filter by tag" i18n-title></pngx-tag>
@for (tagID of doc.tags | collapseTags | async; track tagID) {
<pngx-tag [tagID]="tagID" [split]="true" class="ms-1 fs-6" (click)="clickTag(tagID, $event)" (parentClick)="clickTag($event)" [clickable]="true" linkTitle="Filter by tag" i18n-title></pngx-tag>
}
}
@case (DisplayField.DOCUMENT_TYPE) {
@@ -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,
@@ -36,8 +36,8 @@
{{document().title | documentTitle}}
}
@if (displayFields().includes(DisplayField.TAGS)) {
@for (tagID of document().tags; track tagID) {
<pngx-tag [tagID]="tagID" linkTitle="Filter by tag" i18n-linkTitle class="ms-1" (click)="clickTag.emit(tagID);$event.stopPropagation()" [clickable]="clickTag.observers.length"></pngx-tag>
@for (tagID of document().tags | collapseTags | async; track tagID) {
<pngx-tag [tagID]="tagID" [split]="true" linkTitle="Filter by tag" i18n-linkTitle class="ms-1" (click)="clickTag.emit(tagID);$event.stopPropagation()" (parentClick)="clickTag.emit($event)" [clickable]="clickTag.observers.length"></pngx-tag>
}
}
} @else {
@@ -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,
@@ -19,11 +19,12 @@
}
@if (document() && displayFields().includes(DisplayField.TAGS)) {
<div class="tags d-flex flex-column text-end position-absolute me-1 fs-6" [class.tags-no-wrap]="document().tags.length > 3">
@for (tagID of tagIDs; track tagID) {
<pngx-tag [tagID]="tagID" (click)="clickTag.emit(tagID);$event.stopPropagation()" [clickable]="true" linkTitle="Toggle tag filter" i18n-linkTitle></pngx-tag>
@let visibleTagIDs = document().tags | collapseTags | async;
<div class="tags d-flex flex-column text-end position-absolute me-1 fs-6" [class.tags-no-wrap]="visibleTagIDs?.length > 3">
@for (tagID of getTagIDs(visibleTagIDs); track tagID) {
<pngx-tag [tagID]="tagID" [split]="true" (click)="clickTag.emit(tagID);$event.stopPropagation()" (parentClick)="clickTag.emit($event)" [clickable]="true" linkTitle="Toggle tag filter" i18n-linkTitle></pngx-tag>
}
@if (moreTags) {
@if (getMoreTags(visibleTagIDs); as moreTags) {
<div>
<span class="badge text-dark">+ {{moreTags}}</span>
</div>
@@ -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;
@@ -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')
})
@@ -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<number>()
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() {
@@ -335,8 +335,8 @@
<a routerLink="/documents/{{d.id}}" title="Edit document" i18n-title style="overflow-wrap: anywhere;">{{d.title | documentTitle}}</a>
}
@if (activeDisplayFields.includes(DisplayField.TAGS)) {
@for (tagID of d.tags; track tagID) {
<pngx-tag [tagID]="tagID" class="ms-1 fs-6" clickable="true" linkTitle="Filter by tag" i18n-linkTitle (click)="clickTag(tagID);$event.stopPropagation()"></pngx-tag>
@for (tagID of d.tags | collapseTags | async; track tagID) {
<pngx-tag [tagID]="tagID" [split]="true" class="ms-1 fs-6" clickable="true" linkTitle="Filter by tag" i18n-linkTitle (click)="clickTag(tagID);$event.stopPropagation()" (parentClick)="clickTag($event)"></pngx-tag>
}
}
</td>
@@ -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,
+6
View File
@@ -94,6 +94,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:
@@ -305,6 +306,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',
@@ -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])
})
})
@@ -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<number[]> {
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<number, Tag>(tags.results.map((t) => [t.id, t]))
)
),
catchError(() => of(ids))
)
}
}
@@ -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<number, Tag>([[6, { id: 6, name: 'x', parent: 99 }]])
expect(getTagAncestors(6, hidden)).toEqual([])
const cyclic = new Map<number, Tag>([
[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])
})
})
+43
View File
@@ -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, Tag>
): number[] {
if (!ids?.length) return ids ?? []
const present = new Set(ids)
const implied = new Set<number>()
for (const id of ids) {
const seen = new Set<number>()
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<number, Tag>): Tag[] {
const chain: Tag[] = []
const seen = new Set<number>()
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
}