Compare commits

..
23 changed files with 437 additions and 54 deletions

No files matched your search

@@ -67,6 +67,7 @@ import exclamationCircleFill from 'bootstrap-icons/icons/exclamation-circle-fill
import exclamationTriangleFill from 'bootstrap-icons/icons/exclamation-triangle-fill.svg'
import exclamationTriangle from 'bootstrap-icons/icons/exclamation-triangle.svg'
import eye from 'bootstrap-icons/icons/eye.svg'
import eyeSlash from 'bootstrap-icons/icons/eye-slash.svg'
import fileEarmarkArrowUp from 'bootstrap-icons/icons/file-earmark-arrow-up.svg'
import fileEarmarkCheck from 'bootstrap-icons/icons/file-earmark-check.svg'
import fileEarmarkDiff from 'bootstrap-icons/icons/file-earmark-diff.svg'
@@ -230,6 +231,7 @@ export const icons: Record<string, string> = {
exclamationTriangle,
exclamationTriangleFill,
eye,
eyeSlash,
fileEarmark,
fileEarmarkArrowUp,
fileEarmarkCheck,
@@ -0,0 +1,4 @@
<span class="badge text-bg-secondary d-inline-flex align-items-center gap-1" title="Tags you don't have access to" i18n-title>
<pngx-bs-icon name="eye-slash" width=".8em" height=".8em"></pngx-bs-icon>
<ng-container i18n>{{count()}} hidden</ng-container>
</span>
@@ -0,0 +1,19 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { HiddenTagsBadgeComponent } from './hidden-tags-badge.component'
describe('HiddenTagsBadgeComponent', () => {
let fixture: ComponentFixture<HiddenTagsBadgeComponent>
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HiddenTagsBadgeComponent],
})
fixture = TestBed.createComponent(HiddenTagsBadgeComponent)
fixture.componentRef.setInput('count', 3)
fixture.detectChanges()
})
it('should show the hidden tag count', () => {
expect(fixture.nativeElement.textContent).toContain('3 hidden')
})
})
@@ -0,0 +1,15 @@
import { ChangeDetectionStrategy, Component, input } from '@angular/core'
import { BootstrapIconComponent } from '../bootstrap-icon/bootstrap-icon.component'
/**
* A badge indicating the number of hidden tags.
*/
@Component({
selector: 'pngx-hidden-tags-badge',
templateUrl: './hidden-tags-badge.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [BootstrapIconComponent],
})
export class HiddenTagsBadgeComponent {
readonly count = input.required<number>()
}
@@ -7,7 +7,7 @@
}
<div class="position-relative" [class.col-md-9]="horizontal">
<div class="input-group flex-nowrap">
<ng-select #tagSelect name="tags" [items]="tags" bindLabel="name" bindValue="id" [(ngModel)]="value" [ngModelOptions]="{standalone: true}"
<ng-select #tagSelect name="tags" [items]="tags" bindLabel="name" bindValue="id" [ngModel]="value" (ngModelChange)="onModelChange($event)" [ngModelOptions]="{standalone: true}"
[disabled]="disabled"
[multiple]="multiple"
[closeOnSelect]="false"
@@ -24,11 +24,20 @@
<ng-template ng-label-tmp let-item="item">
@if (isImplied(item.id)) {
<span class="implied-tag"></span>
} @else if (isHidden(item.id)) {
@if (item.id === hiddenTagIds[0]) {
<button class="tag-wrap hidden-tags btn p-0 d-flex align-items-center mw-100" (click)="removeHiddenTags()" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tags you don't have access to" i18n-title>
<pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon>
<pngx-hidden-tags-badge class="d-flex" [count]="hiddenTagIds.length"></pngx-hidden-tags-badge>
</button>
} @else {
<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>
<pngx-tag class="mw-100 overflow-hidden d-flex" [tag]="getTag(item.id)" [split]="preserveHierarchy" (click)="removeTag(item.id); $event.stopPropagation()" (parentClick)="removeTag($event)"></pngx-tag>
}
</button>
}
@@ -12,6 +12,15 @@
display: none !important;
}
// hidden tags bundle always sits after the visible tags
::ng-deep .paperless-input-tags .ng-value:has(> .hidden-tags) {
order: 1;
}
::ng-deep .paperless-input-tags .ng-value-container .ng-input {
order: 2;
}
// let a long (nowrap) split badge shrink to the field instead of widening it
ng-select,
::ng-deep .paperless-input-tags .ng-value-container {
@@ -333,4 +333,87 @@ describe('TagsComponent', () => {
).toBe(true)
})
})
describe('hidden tags', () => {
// 98, 99 are not in the tags list i.e. the user cannot view them
beforeEach(() => {
component.tags = tags
component.value = [1, 98, 2, 99]
fixture.detectChanges()
})
it('should collapse hidden tags into a single badge', async () => {
await fixture.whenStable()
fixture.detectChanges()
expect(component.hiddenTagIds).toEqual([98, 99])
expect(component.isHidden(1)).toBe(false)
const badges = fixture.nativeElement.querySelectorAll('.ng-value')
const visible = Array.from(badges).filter(
(b: HTMLElement) => !b.querySelector('.implied-tag')
) as HTMLElement[]
expect(visible).toHaveLength(3)
expect(visible[1].textContent).toContain('2 hidden')
})
it('should only recompute hidden tags when the value or tags change', () => {
const first = component.hiddenTagIds
expect(component.hiddenTagIds).toBe(first)
component.value = [1, 99]
expect(component.hiddenTagIds).toEqual([99])
component.tags = [...tags, { id: 99, name: 'now visible' }]
expect(component.hiddenTagIds).toEqual([])
})
it('should not treat tags as hidden before tags load', () => {
;(component as any).tagsLoaded = false
expect(component.hiddenTagIds).toEqual([])
})
it('should not treat a hidden ancestor of a visible tag as hidden', () => {
component.tags = [{ id: 3, name: 'child', parent: 98 }]
component.value = [3, 98]
expect(component.hiddenTagIds).toEqual([])
})
it('should keep hidden tags when ng-select changes the selection', () => {
component.onModelChange([])
expect(component.value).toEqual([98, 99])
component.onModelChange([1, 10])
expect(component.value).toEqual([1, 10, 98, 99])
})
it('should skip hidden tags on backspace', () => {
const backspace = new KeyboardEvent('keydown', { key: 'Backspace' })
expect(component.onKeyDown(backspace)).toBe(false)
expect(component.value).toEqual([1, 98, 99])
expect(component.onKeyDown(backspace)).toBe(false)
expect(component.onKeyDown(backspace)).toBe(false)
expect(component.value).toEqual([98, 99])
})
it('should remove all hidden tags after confirmation', () => {
let propagated: number[]
component.registerOnChange((value: number[]) => (propagated = value))
let activeInstances: NgbModalRef[]
modalService.activeInstances.subscribe((v) => (activeInstances = v))
component.removeHiddenTags()
expect(modalService.hasOpenModals()).toBeTruthy()
expect(component.value).toEqual([1, 98, 2, 99])
activeInstances[0].componentInstance.confirmClicked.emit()
expect(component.value).toEqual([1, 2])
expect(propagated).toEqual([1, 2])
})
it('should not remove hidden tags when disabled or none exist', () => {
component.disabled = true
component.removeHiddenTags()
expect(modalService.hasOpenModals()).toBeFalsy()
component.disabled = false
component.value = [1]
component.removeHiddenTags()
expect(modalService.hasOpenModals()).toBeFalsy()
})
})
})
@@ -24,11 +24,10 @@ 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 { getTagAncestors, partitionTags } from 'src/app/utils/tag-display'
import { matchesSearchText } from 'src/app/utils/text-search'
import { ConfirmDialogComponent } from '../../confirm-dialog/confirm-dialog.component'
import { HiddenTagsBadgeComponent } from '../../hidden-tags-badge/hidden-tags-badge.component'
import { EditDialogMode } from '../../edit-dialog/edit-dialog.component'
import { TagEditDialogComponent } from '../../edit-dialog/tag-edit-dialog/tag-edit-dialog.component'
import { TagComponent } from '../../tag/tag.component'
@@ -51,6 +50,7 @@ import { TagComponent } from '../../tag/tag.component'
ReactiveFormsModule,
RouterModule,
BootstrapIconComponent,
HiddenTagsBadgeComponent,
],
})
export class TagsComponent implements OnInit, ControlValueAccessor {
@@ -85,6 +85,7 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
ngOnInit(): void {
this.tagService.listAll().subscribe((result) => {
this.tags = result.results
this.tagsLoaded = true
this.changeDetector.markForCheck()
})
}
@@ -128,6 +129,8 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
tags: Tag[] = []
private tagsLoaded = false
public createTagRef: (name) => void
public searchFn = (term: string, tag: Tag): boolean =>
@@ -143,8 +146,7 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
* 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)
return !!this.value?.includes(id) && !this.display.shown.has(id)
}
private get showsHierarchy(): boolean {
@@ -154,17 +156,103 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
)
}
isHidden(id: number): boolean {
return this.display.hiddenSet.has(id)
}
/**
* Remove the last visible tag (in case its actually a hidden ancestor)
* Tags that are hidden from the current user.
*/
get hiddenTagIds(): number[] {
return this.display.hidden
}
private displayCache: {
value: number[]
tagsById: Map<number, Tag>
showsHierarchy: boolean
tagsLoaded: boolean
shown: Set<number>
hidden: number[]
hiddenSet: Set<number>
}
/**
* Partition of the current value, recomputed only when the value, tags or
* hierarchy setting change.
*/
private get display() {
const tagsById = this.tagsById
const showsHierarchy = this.showsHierarchy
const cached = this.displayCache
if (
cached?.value === this.value &&
cached.tagsById === tagsById &&
cached.showsHierarchy === showsHierarchy &&
cached.tagsLoaded === this.tagsLoaded
) {
return cached
}
const { visible, hidden } = partitionTags(
this.value,
tagsById,
showsHierarchy
)
const hiddenIds = this.tagsLoaded ? hidden : []
this.displayCache = {
value: this.value,
tagsById,
showsHierarchy,
tagsLoaded: this.tagsLoaded,
shown: new Set([...visible, ...hidden]),
hidden: hiddenIds,
hiddenSet: new Set(hiddenIds),
}
return this.displayCache
}
/**
* Remove the last visible tag (in case its actually a hidden ancestor or a
* tag the user cannot view)
*/
readonly onKeyDown = (event: KeyboardEvent): boolean => {
if (event.key !== 'Backspace' || this.select?.searchTerm) return true
const visible = this.value?.filter((id) => !this.isImplied(id)) ?? []
const visible =
this.value?.filter((id) => !this.isImplied(id) && !this.isHidden(id)) ??
[]
if (visible.length === (this.value?.length ?? 0)) return true
this.removeTag(visible.at(-1))
if (visible.length) this.removeTag(visible.at(-1))
return false
}
/**
* Changes from ng-select itself (e.g. clear all) never drop hidden tags,
* those are only removed via their own badge.
*/
onModelChange(newValue: number[]) {
const kept = this.hiddenTagIds.filter((id) => !newValue?.includes(id))
this.value = [...(newValue ?? []), ...kept]
}
removeHiddenTags() {
if (this.disabled) return
const hidden = new Set(this.hiddenTagIds)
if (!hidden.size) return
const modal = this.modalService.open(ConfirmDialogComponent, {
backdrop: 'static',
})
modal.componentInstance.title = $localize`Remove hidden tags`
modal.componentInstance.messageBold = $localize`Remove ${hidden.size} tag(s) you don't have access to?`
modal.componentInstance.message = $localize`You will not be able to add them back.`
modal.componentInstance.btnClass = 'btn-danger'
modal.componentInstance.btnCaption = $localize`Remove`
modal.componentInstance.confirmClicked.pipe(first()).subscribe(() => {
modal.close()
this.value = this.value.filter((id) => !hidden.has(id))
this.onChange(this.value)
})
}
getTag(id: number) {
if (this.tags) {
return this.tags.find((tag) => tag.id == id)
@@ -17,7 +17,7 @@ import {
} 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'
import { getTagAncestors } from 'src/app/utils/tag-display'
const FOCUS_ANIMATION_MS = 200
// matches the .split-parent min-width in tag.component.scss
@@ -76,9 +76,13 @@
}
}
@case (DisplayField.TAGS) {
@for (tagID of doc.tags | collapseTags | async; track tagID) {
@let tags = doc.tags | displayTags | async;
@for (tagID of tags?.visible; 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>
}
@if (tags?.hidden.length) {
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1 fs-6"></pngx-hidden-tags-badge>
}
}
@case (DisplayField.DOCUMENT_TYPE) {
@if (doc.document_type) {
@@ -1,3 +1,4 @@
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
import { AsyncPipe, NgClass, NgStyle } from '@angular/common'
import {
Component,
@@ -38,7 +39,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 { DisplayTagsPipe } from 'src/app/pipes/display-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'
@@ -76,7 +77,8 @@ import { WidgetFrameComponent } from '../widget-frame/widget-frame.component'
DocumentTypeNamePipe,
StoragePathNamePipe,
AsyncPipe,
CollapseTagsPipe,
DisplayTagsPipe,
HiddenTagsBadgeComponent,
DocumentTitlePipe,
CustomDatePipe,
NgClass,
@@ -36,9 +36,13 @@
{{document().title | documentTitle}}
}
@if (displayFields().includes(DisplayField.TAGS)) {
@for (tagID of document().tags | collapseTags | async; track tagID) {
@let tags = document().tags | displayTags | async;
@for (tagID of tags?.visible; 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>
}
@if (tags?.hidden.length) {
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1"></pngx-hidden-tags-badge>
}
}
} @else {
<div class="placeholder bg-secondary w-75 mb-3">&nbsp;</div>
@@ -1,3 +1,4 @@
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
import { AsyncPipe, NgOptimizedImage } from '@angular/common'
import {
AfterViewInit,
@@ -20,7 +21,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 { DisplayTagsPipe } from 'src/app/pipes/display-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'
@@ -46,7 +47,8 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading
TagComponent,
CustomFieldDisplayComponent,
AsyncPipe,
CollapseTagsPipe,
DisplayTagsPipe,
HiddenTagsBadgeComponent,
NgOptimizedImage,
UsernamePipe,
CorrespondentNamePipe,
@@ -19,8 +19,10 @@
}
@if (document() && displayFields().includes(DisplayField.TAGS)) {
@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">
@let tags = document().tags | displayTags | async;
@let visibleTagIDs = tags?.visible;
@let showHidden = showHiddenTags(tags);
<div class="tags d-flex flex-column text-end position-absolute me-1 fs-6" [class.tags-no-wrap]="(visibleTagIDs?.length ?? 0) + (showHidden ? 1 : 0) > 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>
}
@@ -29,6 +31,9 @@
<span class="badge text-dark">+ {{moreTags}}</span>
</div>
}
@if (showHidden) {
<pngx-hidden-tags-badge [count]="tags.hidden.length"></pngx-hidden-tags-badge>
}
</div>
}
</div>
@@ -42,6 +42,19 @@ describe('DocumentCardSmallComponent', () => {
],
}).compileComponents()
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: [1, 2, 3, 4, 5, 6, 7, 8].map((id) => ({
id,
name: `Tag ${id}`,
})),
})
)
fixture = TestBed.createComponent(DocumentCardSmallComponent)
component = fixture.componentInstance
fixture.componentRef.setInput('document', Object.assign({}, doc))
@@ -148,4 +161,33 @@ describe('DocumentCardSmallComponent', () => {
component.mouseLeaveCard()
expect(component.popupPreview.close).toHaveBeenCalled()
})
it('should show hidden tags last, only when visible tags leave a slot free', () => {
fixture.componentRef.setInput('document', {
...component.document(),
tags: [1, 2, 3, 98, 99],
})
fixture.detectChanges()
const tagsEl = () => fixture.nativeElement.querySelector('.tags')
expect(tagsEl().lastElementChild.textContent).toContain('2 hidden')
// 6 visible tags fill the limit (document has notes)
fixture.componentRef.setInput('document', {
...component.document(),
tags: [1, 2, 3, 4, 5, 6, 98, 99],
})
fixture.detectChanges()
expect(tagsEl().textContent).not.toContain('hidden')
expect(
fixture.debugElement.queryAll(By.directive(TagComponent))
).toHaveLength(6)
fixture.componentRef.setInput('document', {
...component.document(),
tags: [1, 2, 3, 4, 5, 6, 7, 98],
})
fixture.detectChanges()
expect(tagsEl().textContent).toContain('+ 2')
expect(tagsEl().textContent).not.toContain('hidden')
})
})
@@ -1,3 +1,5 @@
import { TagPartition } from 'src/app/utils/tag-display'
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
import { AsyncPipe, NgOptimizedImage } from '@angular/common'
import {
AfterViewInit,
@@ -20,7 +22,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 { DisplayTagsPipe } from 'src/app/pipes/display-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'
@@ -46,7 +48,8 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading
TagComponent,
CustomFieldDisplayComponent,
AsyncPipe,
CollapseTagsPipe,
DisplayTagsPipe,
HiddenTagsBadgeComponent,
NgOptimizedImage,
UsernamePipe,
CorrespondentNamePipe,
@@ -96,6 +99,13 @@ export class DocumentCardSmallComponent
return this.document()?.notes.length > 0 ? 6 : 7
}
/**
* The hidden tags badge only fills a slot the visible tags leave free.
*/
showHiddenTags(tags: TagPartition): boolean {
return tags?.hidden.length > 0 && tags.visible.length < this.tagLimit
}
getMoreTags(tagIDs: number[]): number {
const limit = this.tagLimit
return tagIDs?.length > limit ? tagIDs.length - (limit - 1) : null
@@ -335,9 +335,13 @@
<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 | collapseTags | async; track tagID) {
@let tags = d.tags | displayTags | async;
@for (tagID of tags?.visible; 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>
}
@if (tags?.hidden.length) {
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1 fs-6"></pngx-hidden-tags-badge>
}
}
</td>
}
@@ -1,3 +1,4 @@
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
import { AsyncPipe, NgClass, NgTemplateOutlet } from '@angular/common'
import {
Component,
@@ -39,7 +40,7 @@ import {
SortableDirective,
SortEvent,
} from 'src/app/directives/sortable.directive'
import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe'
import { DisplayTagsPipe } from 'src/app/pipes/display-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'
@@ -97,7 +98,8 @@ import { SaveViewConfigDialogComponent } from './save-view-config-dialog/save-vi
StoragePathNamePipe,
BootstrapIconComponent,
AsyncPipe,
CollapseTagsPipe,
DisplayTagsPipe,
HiddenTagsBadgeComponent,
FormsModule,
ReactiveFormsModule,
NgTemplateOutlet,
@@ -6,7 +6,7 @@ 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'
import { DisplayTagsPipe } from './display-tags.pipe'
const tags: Tag[] = [
{ id: 1, name: 'Parent' },
@@ -14,8 +14,8 @@ const tags: Tag[] = [
{ id: 3, name: 'Other' },
]
describe('CollapseTagsPipe', () => {
let pipe: CollapseTagsPipe
describe('DisplayTagsPipe', () => {
let pipe: DisplayTagsPipe
let tagService: TagService
let settingsService: SettingsService
let permissionsService: PermissionsService
@@ -23,12 +23,12 @@ describe('CollapseTagsPipe', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
CollapseTagsPipe,
DisplayTagsPipe,
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
],
})
pipe = TestBed.inject(CollapseTagsPipe)
pipe = TestBed.inject(DisplayTagsPipe)
tagService = TestBed.inject(TagService)
settingsService = TestBed.inject(SettingsService)
permissionsService = TestBed.inject(PermissionsService)
@@ -39,29 +39,43 @@ describe('CollapseTagsPipe', () => {
.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 split visible and hidden tags, collapsing implied parents', async () => {
expect(await firstValueFrom(pipe.transform([1, 2, 98, 3]))).toEqual({
visible: [2, 3],
hidden: [98],
})
})
it('should pass ids through when hierarchy display is off or not permitted', async () => {
it('should not collapse parents when hierarchy display is off', async () => {
jest.spyOn(settingsService, 'get').mockReturnValue(false)
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual([1, 2])
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
visible: [1, 2],
hidden: [],
})
})
jest.spyOn(settingsService, 'get').mockReturnValue(true)
it('should hide all tags without tag view permission', async () => {
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(false)
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual([1, 2])
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
visible: [],
hidden: [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([])
const empty = { visible: [], hidden: [] }
expect(await firstValueFrom(pipe.transform(null))).toEqual(empty)
expect(await firstValueFrom(pipe.transform([]))).toEqual(empty)
})
it('should fall back to the original ids if tags fail to load', async () => {
it('should show 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])
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
visible: [1, 2],
hidden: [],
})
})
})
@@ -9,39 +9,39 @@ import {
} from '../services/permissions.service'
import { TagService } from '../services/rest/tag.service'
import { SettingsService } from '../services/settings.service'
import { collapseImpliedAncestors } from '../utils/collapse-tags'
import { partitionTags, TagPartition } from '../utils/tag-display'
/**
* Drops tag IDs whose descendant is also in the list for when the child's
* Tag badge already shows its parent.
* Splits a document's tag IDs into regular ones vs those the
* current user cannot view, see partitionTags.
*/
@Pipe({
name: 'collapseTags',
name: 'displayTags',
})
export class CollapseTagsPipe implements PipeTransform {
export class DisplayTagsPipe implements PipeTransform {
private readonly permissionsService = inject(PermissionsService)
private readonly tagService = inject(TagService)
private readonly settingsService = inject(SettingsService)
transform(ids: number[]): Observable<number[]> {
transform(ids: number[]): Observable<TagPartition> {
if (!ids?.length) return of({ visible: [], hidden: [] })
if (
!ids?.length ||
!this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY) ||
!this.permissionsService.currentUserCan(
PermissionAction.View,
PermissionType.Tag
)
) {
return of(ids ?? [])
return of({ visible: [], hidden: ids })
}
return this.tagService.listAll().pipe(
map((tags) =>
collapseImpliedAncestors(
partitionTags(
ids,
new Map<number, Tag>(tags.results.map((t) => [t.id, t]))
new Map<number, Tag>(tags.results.map((t) => [t.id, t])),
!!this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY)
)
),
catchError(() => of(ids))
catchError(() => of({ visible: ids, hidden: [] }))
)
}
}
@@ -1,5 +1,9 @@
import { Tag } from '../data/tag'
import { collapseImpliedAncestors, getTagAncestors } from './collapse-tags'
import {
collapseImpliedAncestors,
getTagAncestors,
partitionTags,
} from './tag-display'
const tags: Tag[] = [
{ id: 1, name: 'Finance' },
@@ -45,3 +49,33 @@ describe('getTagAncestors', () => {
expect(getTagAncestors(7, cyclic).map((t) => t.id)).toEqual([7, 8])
})
})
describe('partitionTags', () => {
it('splits ids into visible and hidden, keeping order', () => {
expect(partitionTags([5, 98, 4, 99], tagsById, true)).toEqual({
visible: [5, 4],
hidden: [98, 99],
})
expect(partitionTags(null, tagsById, true)).toEqual({
visible: [],
hidden: [],
})
})
it('drops implied ancestors only when showing hierarchy', () => {
expect(partitionTags([1, 2, 3], tagsById, true).visible).toEqual([3])
expect(partitionTags([1, 2, 3], tagsById, false).visible).toEqual([1, 2, 3])
})
it('drops a hidden ancestor of a visible tag only when showing hierarchy', () => {
const withHiddenParent = new Map(tagsById)
withHiddenParent.set(6, { id: 6, name: 'Child', parent: 98 })
expect(partitionTags([6, 98, 99], withHiddenParent, true)).toEqual({
visible: [6],
hidden: [99],
})
expect(partitionTags([6, 98, 99], withHiddenParent, false).hidden).toEqual([
98, 99,
])
})
})
@@ -41,3 +41,27 @@ export function getTagAncestors(id: number, tagsById: Map<number, Tag>): Tag[] {
}
return chain
}
export interface TagPartition {
visible: number[]
hidden: number[]
}
/**
* Splits a document's tag IDs for display. Tags missing from tagsById are hidden
* from the current user and when showing hierarchy, ancestors of a child are dropped
* since the descendant badge will show them.
*/
export function partitionTags(
ids: number[],
tagsById: Map<number, Tag>,
showHierarchy: boolean
): TagPartition {
const shown = showHierarchy
? collapseImpliedAncestors(ids, tagsById)
: (ids ?? [])
return {
visible: shown.filter((id) => tagsById.has(id)),
hidden: shown.filter((id) => !tagsById.has(id)),
}
}
+8 -1
View File
@@ -415,10 +415,17 @@ th[pngxSortable] {
.ng-select.ng-select-multiple .ng-select-container .ng-value-container .ng-value {
background-color: transparent;
border-color: transparent;
// split ng-select's 5px bottom margin so values stay vertically centered
margin-block: 2.5px;
}
.ng-select.ng-select-multiple .ng-select-container .ng-value-container {
padding-top: 1px;
padding-top: 0;
}
// undo bootstrap's .btn .badge nudge
.tag-wrap .badge {
top: 0;
}
}