mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-22 04:25:32 +00:00
Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c04cd35a1b | ||
|
|
e9c267bc19 | ||
|
|
c6d75ea118 | ||
|
|
f8a7a3ba01 | ||
|
|
ec1cdf9855 | ||
|
|
b6a85dcb13 | ||
|
|
db60bf5ee8 | ||
|
|
393efcfd65 | ||
|
|
f01c889806 | ||
|
|
fea6ccdcad | ||
|
|
a547636e5e | ||
|
|
ef039e092a | ||
|
|
89fbbd8ba6 | ||
|
|
e81ac3799b | ||
|
|
b1cb8a8365 | ||
|
|
423e63b3d0 | ||
|
|
bd67bbea29 | ||
|
|
031d565d0e | ||
|
|
657dd5365f | ||
|
|
2e515ae4f8 | ||
|
|
1a2ab96ddc | ||
|
|
ad6ea30d0d | ||
|
|
df30b75c61 | ||
|
|
0fc148d755 | ||
|
|
a5aa92519b | ||
|
|
6cffa8cb91 | ||
|
|
908a4d6217 | ||
|
|
4da1f36403 | ||
|
|
06a6c2887c | ||
|
|
5fae2c240f | ||
|
|
f3ee22c548 | ||
|
|
0d2625e4ac | ||
|
|
1ac12b9fa4 | ||
|
|
7af74a9746 | ||
|
|
f482fd6c3c | ||
|
|
084a3b1cb8 | ||
|
|
a1a2eb5b36 | ||
|
|
fb4e644df7 | ||
|
|
1356da49ae | ||
|
|
ef1a0f0166 | ||
|
|
da5d1780d9 | ||
|
|
a127ecd35d | ||
|
|
068fc4b8bc | ||
|
|
e7a4367540 | ||
|
|
9f57da5193 | ||
|
|
c091766a86 | ||
|
|
ffe042e5ba | ||
|
|
7f10b918ae | ||
|
|
c944aaedd3 | ||
|
|
45dac15aef | ||
|
|
d6c18ac04d | ||
|
|
3921311901 | ||
|
|
3dc86ba484 |
No files matched your search
@@ -227,12 +227,6 @@
|
||||
</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(34)
|
||||
expect(setSpy).toHaveBeenCalledTimes(33)
|
||||
expect(setSpy).toHaveBeenCalledWith(SETTINGS_KEYS.SIDEBAR_HIDDEN_ITEMS, [
|
||||
HideableSidebarItemID.Workflows,
|
||||
])
|
||||
|
||||
@@ -163,7 +163,6 @@ 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),
|
||||
@@ -343,7 +342,6 @@ 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
|
||||
),
|
||||
@@ -609,10 +607,6 @@ 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
|
||||
|
||||
@@ -361,8 +361,9 @@
|
||||
</a>
|
||||
</li>
|
||||
}
|
||||
<li class="nav-item mt-2 position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation) && !settingsService.organizingSidebarItems()" tourAnchor="tour.outro">
|
||||
<a class="text-muted small d-flex align-items-center flex-wrap text-decoration-none nav-anchor" [class.opacity-50]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation)" [class.pe-5]="settingsService.organizingSidebarItems() && !slimSidebarEnabled && !slimSidebarAnimating()"
|
||||
<li class="nav-item mt-2 position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation) && !settingsService.organizingSidebarItems()"
|
||||
[class.d-md-block]="slimSidebarEnabled && settingsService.unseenReleasesSince()" tourAnchor="tour.outro">
|
||||
<a class="text-muted small d-flex align-items-center flex-wrap text-decoration-none nav-anchor" [class.d-md-none]="slimSidebarEnabled && settingsService.unseenReleasesSince()" [class.opacity-50]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation)" [class.pe-5]="settingsService.organizingSidebarItems() && !slimSidebarEnabled && !slimSidebarAnimating()"
|
||||
target="_blank" rel="noopener noreferrer" href="https://docs.paperless-ngx.com" ngbPopover="Documentation"
|
||||
i18n-ngbPopover [disablePopover]="!slimSidebarPopoversEnabled" placement="end" container="body"
|
||||
triggers="mouseenter:mouseleave" popoverClass="popover-slim">
|
||||
@@ -371,23 +372,35 @@
|
||||
@if (settingsService.organizingSidebarItems()) {
|
||||
<pngx-input-switch class="position-absolute top-50 end-0 translate-middle-y me-1" [class.d-none]="slimSidebarEnabled || slimSidebarAnimating()" [compact]="true" title="Documentation" i18n-title [ngModel]="!settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation)" (ngModelChange)="toggleSidebarItem(HideableSidebarItemID.Documentation, $event)"></pngx-input-switch>
|
||||
}
|
||||
@if (slimSidebarEnabled && settingsService.unseenReleasesSince()) {
|
||||
<button type="button" class="btn btn-link border-0 w-100 text-muted small d-none d-md-flex align-items-center nav-anchor position-relative" (click)="showReleaseNotes()"
|
||||
aria-label="See what's new in this version" i18n-aria-label
|
||||
ngbPopover="What's new" i18n-ngbPopover placement="end" container="body"
|
||||
triggers="mouseenter:mouseleave" popoverClass="popover-slim">
|
||||
<pngx-bs-icon class="d-flex" name="info-circle"></pngx-bs-icon>
|
||||
<div class="position-absolute top-0 start-50 ms-1 p-1 bg-success rounded-circle"></div>
|
||||
</button>
|
||||
}
|
||||
</li>
|
||||
<li class="nav-item" [class.visually-hidden]="slimSidebarEnabled">
|
||||
<div class="text-muted small d-flex align-items-center flex-wrap nav-label">
|
||||
<div class="me-2">
|
||||
<a class="text-muted text-decoration-none" target="_blank" rel="noopener noreferrer"
|
||||
href="https://github.com/paperless-ngx/paperless-ngx" ngbPopover="GitHub" i18n-ngbPopover
|
||||
[disablePopover]="!slimSidebarPopoversEnabled" placement="end" container="body"
|
||||
triggers="mouseenter:mouseleave" popoverClass="popover-slim">
|
||||
<button type="button" class="bg-transparent border-0 p-0 text-muted" (click)="showReleaseNotes()" title="See what's new in this version" i18n-title>
|
||||
{{ versionString }}
|
||||
</a>
|
||||
</button>
|
||||
@if (settingsService.unseenReleasesSince()) {
|
||||
<div class="btn-group ms-2 align-baseline">
|
||||
<button type="button" class="btn btn-whats-new rounded-start-pill smaller py-1 px-2 fw-bold lh-sm" (click)="showReleaseNotes()"
|
||||
title="See what's new in this version" i18n-title i18n>New</button>
|
||||
<button type="button" class="btn btn-whats-new rounded-end-pill smaller py-1 px-1 lh-sm d-flex align-items-center" (click)="dismissReleaseNotes()"
|
||||
title="Dismiss" i18n-title aria-label="Dismiss" i18n-aria-label>
|
||||
<pngx-bs-icon name="x" class="d-flex" width="1em" height="1em"></pngx-bs-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@if (!settingsService.updateCheckingIsSet || appRemoteVersion()) {
|
||||
<div class="version-check d-flex align-items-center">
|
||||
<ng-template #updateAvailablePopContent>
|
||||
<span class="small">Paperless-ngx {{ appRemoteVersion().version }} <ng-container i18n>is
|
||||
available.</ng-container><br /><ng-container i18n>Click to view.</ng-container></span>
|
||||
</ng-template>
|
||||
<ng-template #updateCheckingNotEnabledPopContent>
|
||||
<p class="small mb-2">
|
||||
<ng-container i18n>Paperless-ngx can automatically check for updates</ng-container>
|
||||
@@ -404,15 +417,13 @@
|
||||
</ng-template>
|
||||
@if (settingsService.updateCheckingIsSet) {
|
||||
@if (appRemoteVersion().update_available) {
|
||||
<a class="small text-decoration-none" target="_blank" rel="noopener noreferrer"
|
||||
href="https://github.com/paperless-ngx/paperless-ngx/releases"
|
||||
[ngbPopover]="updateAvailablePopContent" popoverClass="shadow" triggers="mouseenter:mouseleave"
|
||||
container="body">
|
||||
<button type="button" class="bg-transparent border-0 p-0 small text-primary" (click)="showAvailableReleaseNotes()"
|
||||
title="Paperless-ngx {{ appRemoteVersion().version }} is available" i18n-title>
|
||||
<pngx-bs-icon width="1.2em" height="1.2em" name="info-circle" class="me-1"></pngx-bs-icon>
|
||||
@if (appRemoteVersion()?.update_available) {
|
||||
<ng-container i18n>Update available</ng-container>
|
||||
}
|
||||
</a>
|
||||
</button>
|
||||
}
|
||||
} @else {
|
||||
<a *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.UISettings }" class="small text-decoration-none" routerLink="/settings" fragment="update-checking" aria-label="Configure update checking" i18n-aria-label
|
||||
|
||||
@@ -700,3 +700,15 @@ main {
|
||||
.smaller {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
// From active / hover of sidebar nav links
|
||||
.btn-whats-new {
|
||||
--bs-btn-color: var(--bs-primary);
|
||||
--bs-btn-bg: color-mix(in srgb, var(--bs-primary) 13%, transparent);
|
||||
--bs-btn-border-width: 0;
|
||||
--bs-btn-font-weight: 600;
|
||||
--bs-btn-hover-color: var(--bs-primary);
|
||||
--bs-btn-hover-bg: color-mix(in srgb, var(--bs-primary) 20%, transparent);
|
||||
--bs-btn-active-color: var(--bs-primary);
|
||||
--bs-btn-active-bg: color-mix(in srgb, var(--bs-primary) 20%, transparent);
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import { environment } from 'src/environments/environment'
|
||||
import { ProfileEditDialogComponent } from '../common/profile-edit-dialog/profile-edit-dialog.component'
|
||||
import { UploadStatusTrayComponent } from '../common/upload-status-tray/upload-status-tray.component'
|
||||
import { DocumentDetailComponent } from '../document-detail/document-detail.component'
|
||||
import { ReleaseNotesDialogComponent } from '../common/release-notes-dialog/release-notes-dialog.component'
|
||||
import { AppFrameComponent } from './app-frame.component'
|
||||
import { GlobalSearchComponent } from './global-search/global-search.component'
|
||||
|
||||
@@ -695,6 +696,131 @@ describe('AppFrameComponent', () => {
|
||||
expect(maybeRefreshSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should show new release pill and mark releases seen on click', () => {
|
||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
||||
settingsService.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, '3.4.2')
|
||||
fixture.detectChanges()
|
||||
|
||||
const pill = fixture.debugElement
|
||||
.queryAll(By.css('button'))
|
||||
.find((b) => b.nativeElement.textContent.trim() === 'New')
|
||||
expect(pill).toBeTruthy()
|
||||
|
||||
pill.nativeElement.click()
|
||||
const req = httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}ui_settings/`
|
||||
)
|
||||
expect(req.request.body.settings.whats_new.last_seen_version).toEqual(
|
||||
'3.5.1'
|
||||
)
|
||||
req.flush({ success: true })
|
||||
fixture.detectChanges()
|
||||
|
||||
expect(
|
||||
fixture.debugElement
|
||||
.queryAll(By.css('button'))
|
||||
.find((b) => b.nativeElement.textContent.trim() === 'New')
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should dismiss new release pill without opening release notes', () => {
|
||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
||||
settingsService.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, '3.4.2')
|
||||
fixture.detectChanges()
|
||||
const modalSpy = jest.spyOn(modalService, 'open')
|
||||
|
||||
fixture.debugElement
|
||||
.query(By.css('button[aria-label="Dismiss"]'))
|
||||
.nativeElement.click()
|
||||
const req = httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}ui_settings/`
|
||||
)
|
||||
expect(req.request.body.settings.whats_new.last_seen_version).toEqual(
|
||||
'3.5.1'
|
||||
)
|
||||
req.flush({ success: true })
|
||||
fixture.detectChanges()
|
||||
|
||||
expect(modalSpy).not.toHaveBeenCalled()
|
||||
expect(
|
||||
fixture.debugElement.query(By.css('button[aria-label="Dismiss"]'))
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('should open current release notes from the version without marking seen', () => {
|
||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
||||
settingsService.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, '3.5.1')
|
||||
fixture.detectChanges()
|
||||
const modalSpy = jest.spyOn(modalService, 'open')
|
||||
|
||||
const versionButton = fixture.debugElement
|
||||
.queryAll(By.css('button'))
|
||||
.find((b) => b.nativeElement.textContent.includes('3.5.1'))
|
||||
versionButton.nativeElement.click()
|
||||
|
||||
expect(modalSpy).toHaveBeenCalledWith(
|
||||
ReleaseNotesDialogComponent,
|
||||
expect.anything()
|
||||
)
|
||||
httpTestingController.expectNone(`${environment.apiBaseUrl}ui_settings/`)
|
||||
})
|
||||
|
||||
it('should open available release notes from update available', () => {
|
||||
jest
|
||||
.spyOn(remoteVersionService, 'checkForUpdates')
|
||||
.mockReturnValue(of({ version: '3.6.0', update_available: true }))
|
||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
||||
settingsService.set(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED, true)
|
||||
component.ngOnInit()
|
||||
fixture.detectChanges()
|
||||
const modalSpy = jest.spyOn(modalService, 'open')
|
||||
const saveSpy = jest.spyOn(settingsService, 'markReleasesSeen')
|
||||
|
||||
const updateButton = fixture.debugElement
|
||||
.queryAll(By.css('button'))
|
||||
.find((b) => b.nativeElement.textContent.includes('Update available'))
|
||||
expect(updateButton.nativeElement.title).toEqual(
|
||||
'Paperless-ngx 3.6.0 is available'
|
||||
)
|
||||
updateButton.nativeElement.click()
|
||||
|
||||
const dialog = modalSpy.mock.results[0].value
|
||||
.componentInstance as ReleaseNotesDialogComponent
|
||||
expect(dialog.since()).toEqual('3.5.1')
|
||||
expect(dialog.until()).toEqual('3.6.0')
|
||||
expect(saveSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should save update checking chosen in the release notes dialog', () => {
|
||||
const setUpdateCheckingSpy = jest
|
||||
.spyOn(component, 'setUpdateChecking')
|
||||
.mockImplementation(() => {})
|
||||
const modalSpy = jest.spyOn(modalService, 'open')
|
||||
component.showReleaseNotes()
|
||||
|
||||
const dialog = modalSpy.mock.results[0].value
|
||||
.componentInstance as ReleaseNotesDialogComponent
|
||||
dialog.updateCheckingChosen.emit(true)
|
||||
expect(setUpdateCheckingSpy).toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it('should show new release dot instead of documentation in slim sidebar', () => {
|
||||
settingsService.set(SETTINGS_KEYS.SLIM_SIDEBAR, true)
|
||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
||||
settingsService.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, '3.4.2')
|
||||
fixture.detectChanges()
|
||||
|
||||
const whatsNew = fixture.debugElement.query(
|
||||
By.css('button[aria-label="See what\'s new in this version"]')
|
||||
).nativeElement
|
||||
const docs = fixture.debugElement.query(
|
||||
By.css('a[href="https://docs.paperless-ngx.com"].nav-anchor')
|
||||
).nativeElement
|
||||
expect(docs.classList).toContain('d-md-none')
|
||||
// both share one li so the tour anchor points at whichever is shown
|
||||
expect(whatsNew.closest('li')).toBe(docs.closest('li'))
|
||||
})
|
||||
|
||||
it('should show tasks badge for needs-attention tasks', () => {
|
||||
jest
|
||||
.spyOn(tasksService, 'needsAttentionTasksCount', 'get')
|
||||
|
||||
@@ -68,6 +68,7 @@ import { SwitchComponent } from '../common/input/switch/switch.component'
|
||||
import { BrandMarkComponent } from '../common/logo/brand-mark/brand-mark.component'
|
||||
import { LogoComponent } from '../common/logo/logo.component'
|
||||
import { ProfileEditDialogComponent } from '../common/profile-edit-dialog/profile-edit-dialog.component'
|
||||
import { ReleaseNotesDialogComponent } from '../common/release-notes-dialog/release-notes-dialog.component'
|
||||
import { UploadStatusTrayComponent } from '../common/upload-status-tray/upload-status-tray.component'
|
||||
import { DocumentDetailComponent } from '../document-detail/document-detail.component'
|
||||
import { ComponentWithPermissions } from '../with-permissions/with-permissions.component'
|
||||
@@ -551,6 +552,44 @@ export class AppFrameComponent
|
||||
})
|
||||
}
|
||||
|
||||
private openReleaseNotes(
|
||||
since: string | null,
|
||||
until: string | null = null
|
||||
): void {
|
||||
const modal = this.modalService.open(ReleaseNotesDialogComponent, {
|
||||
size: 'lg',
|
||||
scrollable: true,
|
||||
})
|
||||
modal.componentInstance.load(since, until)
|
||||
modal.componentInstance.updateCheckingChosen.subscribe((enable: boolean) =>
|
||||
this.setUpdateChecking(enable)
|
||||
)
|
||||
}
|
||||
|
||||
showReleaseNotes() {
|
||||
const since = this.settingsService.unseenReleasesSince()
|
||||
this.openReleaseNotes(since)
|
||||
if (since) {
|
||||
this.dismissReleaseNotes()
|
||||
}
|
||||
}
|
||||
|
||||
/** Mark the running version's release notes seen, hiding "New" */
|
||||
dismissReleaseNotes() {
|
||||
this.settingsService
|
||||
.markReleasesSeen()
|
||||
.pipe(first())
|
||||
.subscribe({ error: () => {} })
|
||||
}
|
||||
|
||||
/** Notes for releases newer than the running version, not yet installed */
|
||||
showAvailableReleaseNotes() {
|
||||
this.openReleaseNotes(
|
||||
this.settingsService.get(SETTINGS_KEYS.VERSION),
|
||||
this.appRemoteVersion()?.version
|
||||
)
|
||||
}
|
||||
|
||||
setUpdateChecking(enable: boolean) {
|
||||
this.settingsService.set(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED, enable)
|
||||
this.settingsService
|
||||
|
||||
@@ -87,6 +87,7 @@ import folderFill from 'bootstrap-icons/icons/folder-fill.svg'
|
||||
import folder from 'bootstrap-icons/icons/folder.svg'
|
||||
import funnel from 'bootstrap-icons/icons/funnel.svg'
|
||||
import gear from 'bootstrap-icons/icons/gear.svg'
|
||||
import github from 'bootstrap-icons/icons/github.svg'
|
||||
import globe2 from 'bootstrap-icons/icons/globe2.svg'
|
||||
import google from 'bootstrap-icons/icons/google.svg'
|
||||
import grid from 'bootstrap-icons/icons/grid.svg'
|
||||
@@ -249,6 +250,7 @@ export const icons: Record<string, string> = {
|
||||
folderFill,
|
||||
funnel,
|
||||
gear,
|
||||
github,
|
||||
globe2,
|
||||
google,
|
||||
grid,
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
import { provideHttpClient } from '@angular/common/http'
|
||||
import { provideHttpClientTesting } from '@angular/common/http/testing'
|
||||
import { Component } from '@angular/core'
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
||||
import { FormControl, ReactiveFormsModule } from '@angular/forms'
|
||||
import { NumberComponent } from './number/number.component'
|
||||
import { TextComponent } from './text/text.component'
|
||||
import { TextAreaComponent } from './textarea/textarea.component'
|
||||
import { UrlComponent } from './url/url.component'
|
||||
|
||||
@Component({
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
TextComponent,
|
||||
NumberComponent,
|
||||
TextAreaComponent,
|
||||
UrlComponent,
|
||||
],
|
||||
template: `
|
||||
<pngx-input-text [formControl]="control" />
|
||||
<pngx-input-number [formControl]="control" [showAdd]="false" />
|
||||
<pngx-input-textarea [formControl]="control" />
|
||||
<pngx-input-url [formControl]="control" />
|
||||
`,
|
||||
})
|
||||
class InputEventsHostComponent {
|
||||
control = new FormControl<string | number | null>(null)
|
||||
}
|
||||
|
||||
describe.each([
|
||||
['text', 'pngx-input-text input', 'Edited text', 'Edited text'],
|
||||
['number', 'pngx-input-number input', '42', 42],
|
||||
['textarea', 'pngx-input-textarea textarea', 'Edited\ntext', 'Edited\ntext'],
|
||||
['url', 'pngx-input-url input', 'https://example.com', 'https://example.com'],
|
||||
])(
|
||||
'%s input events',
|
||||
(_type, selector: string, text: string, value: string | number) => {
|
||||
let fixture: ComponentFixture<InputEventsHostComponent>
|
||||
let control: FormControl<string | number | null>
|
||||
let input: HTMLInputElement | HTMLTextAreaElement
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [InputEventsHostComponent],
|
||||
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||
})
|
||||
fixture = TestBed.createComponent(InputEventsHostComponent)
|
||||
control = fixture.componentInstance.control
|
||||
})
|
||||
|
||||
async function render() {
|
||||
fixture.detectChanges()
|
||||
await fixture.whenStable()
|
||||
input = fixture.nativeElement.querySelector(selector)
|
||||
}
|
||||
|
||||
it('updates the form while typing and marks it touched only on blur', async () => {
|
||||
await render()
|
||||
const changed = jest.fn()
|
||||
control.valueChanges.subscribe(changed)
|
||||
input.value = text
|
||||
input.dispatchEvent(new Event('input'))
|
||||
expect(control.value).toBe(value)
|
||||
expect(control.dirty).toBe(true)
|
||||
expect(control.touched).toBe(false)
|
||||
|
||||
input.dispatchEvent(new Event('change'))
|
||||
input.dispatchEvent(new Event('blur'))
|
||||
expect(control.touched).toBe(true)
|
||||
expect(changed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('honors an explicit updateOn blur strategy', async () => {
|
||||
control = new FormControl<string | number | null>(null, {
|
||||
updateOn: 'blur',
|
||||
})
|
||||
fixture.componentInstance.control = control
|
||||
await render()
|
||||
input.value = text
|
||||
input.dispatchEvent(new Event('input'))
|
||||
expect(control.value).toBeNull()
|
||||
expect(control.pristine).toBe(true)
|
||||
|
||||
input.dispatchEvent(new Event('blur'))
|
||||
expect(control.value).toBe(value)
|
||||
expect(control.dirty).toBe(true)
|
||||
expect(control.touched).toBe(true)
|
||||
})
|
||||
}
|
||||
)
|
||||
@@ -12,7 +12,7 @@
|
||||
</div>
|
||||
<div class="position-relative" [class.col-md-9]="horizontal">
|
||||
<div class="input-group" [class.is-invalid]="error">
|
||||
<input #inputField type="number" class="form-control" [step]="step" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (ngModelChange)="onChange($event)" (blur)="onTouched()" [class.is-invalid]="error" [disabled]="disabled">
|
||||
<input #inputField type="number" class="form-control" [step]="step" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (change)="onChange(value)" [class.is-invalid]="error" [disabled]="disabled">
|
||||
@if (showAdd) {
|
||||
<button class="btn btn-outline-secondary" type="button" id="button-addon1" (click)="nextAsn()" [disabled]="disabled">+1</button>
|
||||
}
|
||||
|
||||
@@ -17,21 +17,16 @@
|
||||
[searchFn]="searchFn"
|
||||
addTagText="Add tag"
|
||||
i18n-addTagText
|
||||
[keyDownFn]="onKeyDown"
|
||||
(add)="onAdd($event)"
|
||||
(change)="onChange(value)">
|
||||
|
||||
<ng-template ng-label-tmp let-item="item">
|
||||
@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>
|
||||
}
|
||||
<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>
|
||||
</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,21 +7,6 @@
|
||||
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;
|
||||
|
||||
@@ -278,59 +278,4 @@ 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,13 +21,7 @@ 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'
|
||||
@@ -56,7 +50,6 @@ 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() {
|
||||
@@ -138,33 +131,6 @@ 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)
|
||||
@@ -173,26 +139,6 @@ 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
|
||||
|
||||
@@ -289,17 +235,18 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
|
||||
}
|
||||
|
||||
getParentChain(id: number): Tag[] {
|
||||
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]))
|
||||
// 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 this.tagsByIdCache
|
||||
return chain
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
}
|
||||
</div>
|
||||
<div class="position-relative" [class.col-md-9]="horizontal">
|
||||
<input #inputField type="text" class="form-control" [class.is-invalid]="error" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (ngModelChange)="onChange($event)" (blur)="onTouched()" [disabled]="disabled" [autocomplete]="autocomplete" [placeholder]="placeholder">
|
||||
<input #inputField type="text" class="form-control" [class.is-invalid]="error" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (change)="onChange(value)" [disabled]="disabled" [autocomplete]="autocomplete" [placeholder]="placeholder">
|
||||
@if (hint) {
|
||||
<small class="form-text text-muted" [innerHTML]="hint"></small>
|
||||
}
|
||||
|
||||
@@ -18,8 +18,7 @@
|
||||
[class.font-monospace]="monospace"
|
||||
[(ngModel)]="value"
|
||||
[ngModelOptions]="{standalone: true}"
|
||||
(ngModelChange)="onChange($event)"
|
||||
(blur)="onTouched()"
|
||||
(change)="onChange(value)"
|
||||
[disabled]="disabled"
|
||||
[placeholder]="placeholder"
|
||||
rows="4">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</div>
|
||||
<div [class.col-md-9]="horizontal">
|
||||
<div class="input-group" [class.is-invalid]="error">
|
||||
<input #inputField type="url" class="form-control" [class.is-invalid]="error" placeholder="https://" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (ngModelChange)="onChange($event)" (blur)="onTouched()" [disabled]="disabled">
|
||||
<input #inputField type="url" class="form-control" [class.is-invalid]="error" placeholder="https://" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (change)="onChange(value)" [disabled]="disabled">
|
||||
<a class="btn btn-outline-secondary rounded-end" title="Open link" i18n-title [href]="value" target="_blank">
|
||||
<pngx-bs-icon width="1.2em" height="1.2em" name="box-arrow-up-right"></pngx-bs-icon>
|
||||
</a>
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
<div class="modal-header">
|
||||
<div>
|
||||
@if (until()) {
|
||||
<h4 class="modal-title" i18n>Paperless-ngx {{ until() }} is available</h4>
|
||||
<p class="text-muted small mb-0" i18n>You are running {{ version }}</p>
|
||||
} @else {
|
||||
<h4 class="modal-title" i18n>What's new in Paperless-ngx</h4>
|
||||
@if (since()) {
|
||||
<p class="text-muted small mb-0" i18n>Updated from {{ since() }} to {{ version }}</p>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div class="d-flex align-items-center gap-3 ms-auto">
|
||||
<div class="btn-group btn-group-sm" role="group">
|
||||
<a tabindex="-1" class="btn btn-dark border-dark-subtle d-flex align-items-center" [href]="repoUrl" target="_blank" rel="noopener noreferrer"
|
||||
title="Star Paperless-ngx on GitHub" i18n-title>
|
||||
<pngx-bs-icon name="github" class="me-1 d-flex" width="12" height="12"></pngx-bs-icon><span class="small" i18n>Star</span>
|
||||
</a>
|
||||
@if (stars() !== null) {
|
||||
<a tabindex="-1" class="btn btn-dark border-dark-subtle d-flex align-items-center" [href]="repoUrl + '/stargazers'" target="_blank" rel="noopener noreferrer"
|
||||
title="Stargazers" i18n-title>
|
||||
<span class="small">{{ stars() | number }}</span>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
<button type="button" class="btn-close m-0" aria-label="Close" i18n-aria-label (click)="close()"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@if (!updateCheckingEnabled()) {
|
||||
@if (!updateCheckingIsSet() && canChangeUpdateChecking) {
|
||||
<p class="mb-2" i18n>Paperless-ngx can automatically check for updates and show release notes here, fetched from GitHub.</p>
|
||||
<div class="btn-group btn-group-sm">
|
||||
<button type="button" class="btn btn-outline-primary" (click)="setUpdateChecking(true)" i18n>Enable</button>
|
||||
<button type="button" class="btn btn-outline-secondary" (click)="setUpdateChecking(false)" i18n>Disable</button>
|
||||
</div>
|
||||
} @else {
|
||||
<p class="mb-0" i18n>Release notes are fetched from GitHub when update checking is enabled.</p>
|
||||
<ng-container *ngTemplateOutlet="githubLink"></ng-container>
|
||||
}
|
||||
} @else if (loading()) {
|
||||
<div class="d-flex align-items-center gap-2 text-muted">
|
||||
<output class="spinner-border spinner-border-sm"></output>
|
||||
<ng-container i18n>Loading release notes...</ng-container>
|
||||
</div>
|
||||
} @else if (!releases()?.length) {
|
||||
<p class="mb-0" i18n>Release notes could not be loaded.</p>
|
||||
<ng-container *ngTemplateOutlet="githubLink"></ng-container>
|
||||
} @else {
|
||||
@for (release of releases(); track release.version) {
|
||||
<section class="release-notes" [class.border-top]="!$first" [class.pt-3]="!$first" [class.mt-3]="!$first">
|
||||
<div class="d-flex align-items-baseline gap-2 mb-2">
|
||||
<h5 class="mb-0">{{ release.version }}</h5>
|
||||
<a class="d-flex flex-row align-items-center text-secondary btn-link" [href]="release.html_url" target="_blank" rel="noopener noreferrer"
|
||||
title="View on GitHub" i18n-title>
|
||||
@if (release.published_at) {
|
||||
<span class="text-muted small me-2">{{ release.published_at | customDate }}</span>
|
||||
}
|
||||
<pngx-bs-icon name="box-arrow-up-right" class="mt-n1" width=".7rem"></pngx-bs-icon>
|
||||
</a>
|
||||
</div>
|
||||
<div class="release-notes-body" [innerHTML]="release.body_html"></div>
|
||||
</section>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div class="modal-footer justify-content-between">
|
||||
<div class="d-flex flex-wrap gap-3 small">
|
||||
<a class="link-secondary text-decoration-none d-flex align-items-center" [href]="releasesUrl" target="_blank" rel="noopener noreferrer">
|
||||
<pngx-bs-icon name="clock-history" class="me-1"></pngx-bs-icon><ng-container i18n>All releases</ng-container>
|
||||
</a>
|
||||
<a class="link-secondary text-decoration-none d-flex align-items-center" [href]="discussionsUrl" target="_blank" rel="noopener noreferrer">
|
||||
<pngx-bs-icon name="chat-left-text" class="me-1"></pngx-bs-icon><ng-container i18n>Need support? Ask in Discussions</ng-container>
|
||||
</a>
|
||||
</div>
|
||||
<div class="d-flex gap-3">
|
||||
<button type="button" class="btn btn-outline-secondary" (click)="close()" i18n>Close</button>
|
||||
@if (until()) {
|
||||
<a class="btn btn-primary d-flex align-items-center" [href]="updatingDocsUrl" target="_blank" rel="noopener noreferrer">
|
||||
<ng-container i18n>How to update</ng-container>
|
||||
<pngx-bs-icon name="box-arrow-up-right" class="ms-2" width=".8rem"></pngx-bs-icon>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ng-template #githubLink>
|
||||
<a class="small" [href]="releaseUrl" target="_blank" rel="noopener noreferrer">
|
||||
<ng-container i18n>View on GitHub</ng-container>
|
||||
<pngx-bs-icon name="box-arrow-up-right" class="ms-1"></pngx-bs-icon>
|
||||
</a>
|
||||
</ng-template>
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
// Styles for GitHub-rendered release notes (body_html)
|
||||
:host ::ng-deep .release-notes-body {
|
||||
// Repeats the version heading
|
||||
> h2:first-child {
|
||||
display: none;
|
||||
}
|
||||
|
||||
// Section labels e.g. "Bug Fixes"
|
||||
> h3 {
|
||||
color: var(--bs-secondary-color);
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 0.375rem;
|
||||
}
|
||||
|
||||
ul {
|
||||
padding-left: 1.25rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
li {
|
||||
margin-bottom: 0.25rem;
|
||||
|
||||
&::marker {
|
||||
color: var(--bs-secondary-color);
|
||||
}
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
a.user-mention {
|
||||
color: var(--bs-secondary-color);
|
||||
}
|
||||
|
||||
details {
|
||||
margin-bottom: 0.75rem;
|
||||
|
||||
> summary {
|
||||
color: var(--bs-secondary-color);
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
margin-bottom: 0.375rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the link underline off code, where it hides underscores
|
||||
// e.g. PAPERLESS_ALLOWED_HOSTS
|
||||
a code {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
// GitHub alerts, e.g. > [!NOTE]
|
||||
.markdown-alert {
|
||||
background-color: color-mix(in srgb, var(--bs-primary) 8%, transparent);
|
||||
border-left: 0.25rem solid var(--bs-primary);
|
||||
border-radius: var(--bs-border-radius);
|
||||
padding: 0.75rem 1rem;
|
||||
margin-bottom: 1rem;
|
||||
|
||||
> :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.markdown-alert-title {
|
||||
color: var(--bs-primary);
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
import { DatePipe } from '@angular/common'
|
||||
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
|
||||
import {
|
||||
HttpTestingController,
|
||||
provideHttpClientTesting,
|
||||
} from '@angular/common/http/testing'
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
||||
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
|
||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
||||
import { PermissionsService } from 'src/app/services/permissions.service'
|
||||
import { SettingsService } from 'src/app/services/settings.service'
|
||||
import { environment } from 'src/environments/environment'
|
||||
import {
|
||||
prepareReleaseHtml,
|
||||
ReleaseNotesDialogComponent,
|
||||
} from './release-notes-dialog.component'
|
||||
|
||||
describe('ReleaseNotesDialogComponent', () => {
|
||||
let component: ReleaseNotesDialogComponent
|
||||
let fixture: ComponentFixture<ReleaseNotesDialogComponent>
|
||||
let httpTestingController: HttpTestingController
|
||||
let settingsService: SettingsService
|
||||
|
||||
function create(updateCheckingEnabled?: boolean, canChangeSettings = true) {
|
||||
settingsService = TestBed.inject(SettingsService)
|
||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
||||
if (updateCheckingEnabled !== undefined) {
|
||||
settingsService.set(
|
||||
SETTINGS_KEYS.UPDATE_CHECKING_ENABLED,
|
||||
updateCheckingEnabled
|
||||
)
|
||||
}
|
||||
jest
|
||||
.spyOn(TestBed.inject(PermissionsService), 'currentUserCan')
|
||||
.mockReturnValue(canChangeSettings)
|
||||
fixture = TestBed.createComponent(ReleaseNotesDialogComponent)
|
||||
component = fixture.componentInstance
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ReleaseNotesDialogComponent],
|
||||
providers: [
|
||||
DatePipe,
|
||||
NgbActiveModal,
|
||||
provideHttpClient(withInterceptorsFromDi()),
|
||||
provideHttpClientTesting(),
|
||||
],
|
||||
})
|
||||
httpTestingController = TestBed.inject(HttpTestingController)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify()
|
||||
})
|
||||
|
||||
it('should load and render release notes since a version', () => {
|
||||
create(true)
|
||||
component.load('3.4.2')
|
||||
const req = httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}release_notes/?since=3.4.2`
|
||||
)
|
||||
req.flush({
|
||||
version: '3.5.1',
|
||||
releases: [
|
||||
{
|
||||
version: '3.5.1',
|
||||
name: 'Paperless-ngx v3.5.1',
|
||||
body_html:
|
||||
'<h2>paperless-ngx 3.5.1</h2><h3>Bug Fixes</h3><ul><li>Fix: a thing</li></ul>' +
|
||||
'<h3>All App Changes</h3><details><summary>1 change</summary><ul><li>Fix: a thing</li></ul></details>',
|
||||
html_url: '',
|
||||
published_at: '2026-11-18T05:22:01Z',
|
||||
},
|
||||
],
|
||||
})
|
||||
fixture.detectChanges()
|
||||
|
||||
const text = fixture.nativeElement.textContent
|
||||
expect(text).toContain('Updated from 3.4.2 to 3.5.1')
|
||||
expect(text).toContain('Bug Fixes')
|
||||
expect(
|
||||
fixture.nativeElement.querySelector('.modal-footer a.btn-primary')
|
||||
).toBeNull()
|
||||
expect(
|
||||
fixture.nativeElement.querySelector('.release-notes-body details summary')
|
||||
.textContent
|
||||
).toEqual('1 change')
|
||||
})
|
||||
|
||||
it('should load release notes for an available update', () => {
|
||||
create(true)
|
||||
component.load('3.5.1', '3.6.0')
|
||||
httpTestingController
|
||||
.expectOne(
|
||||
`${environment.apiBaseUrl}release_notes/?since=3.5.1&until=3.6.0`
|
||||
)
|
||||
.flush({ version: '3.5.1', releases: [] })
|
||||
fixture.detectChanges()
|
||||
|
||||
const text = fixture.nativeElement.textContent
|
||||
expect(text).toContain('Paperless-ngx 3.6.0 is available')
|
||||
expect(text).toContain('You are running 3.5.1')
|
||||
expect(component.releaseUrl).toEqual(
|
||||
'https://github.com/paperless-ngx/paperless-ngx/releases/tag/v3.6.0'
|
||||
)
|
||||
expect(
|
||||
fixture.nativeElement
|
||||
.querySelector('.modal-footer a.btn-primary')
|
||||
.getAttribute('href')
|
||||
).toEqual('https://docs.paperless-ngx.com/administration/#updating')
|
||||
})
|
||||
|
||||
it('should open release note links safely and drop svg icons', () => {
|
||||
const html = prepareReleaseHtml(
|
||||
'<div class="markdown-alert"><p class="markdown-alert-title"><svg><path d="M0"></path></svg>Note</p></div>' +
|
||||
'<p><a href="https://github.com/paperless-ngx/paperless-ngx/pull/1" data-hovercard-type="pull_request">#1</a></p>'
|
||||
)
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html')
|
||||
expect(doc.querySelector('svg')).toBeNull()
|
||||
expect(doc.querySelector('.markdown-alert-title').textContent).toEqual(
|
||||
'Note'
|
||||
)
|
||||
const link = doc.querySelector('a')
|
||||
expect(link.getAttribute('target')).toEqual('_blank')
|
||||
expect(link.getAttribute('rel')).toEqual('noopener noreferrer nofollow')
|
||||
expect(link.hasAttribute('data-hovercard-type')).toBe(false)
|
||||
})
|
||||
|
||||
it('should show a message if release notes could not be loaded', () => {
|
||||
create(true)
|
||||
component.load(null)
|
||||
httpTestingController
|
||||
.expectOne(`${environment.apiBaseUrl}release_notes/`)
|
||||
.flush('error', { status: 500, statusText: 'error' })
|
||||
fixture.detectChanges()
|
||||
|
||||
expect(fixture.nativeElement.textContent).toContain(
|
||||
'Release notes could not be loaded'
|
||||
)
|
||||
})
|
||||
|
||||
it('should not fetch release notes if update checking is disabled', () => {
|
||||
create(false)
|
||||
component.load('3.4.2')
|
||||
fixture.detectChanges()
|
||||
|
||||
httpTestingController.expectNone(`${environment.apiBaseUrl}release_notes/`)
|
||||
expect(fixture.nativeElement.textContent).toContain(
|
||||
'when update checking is enabled'
|
||||
)
|
||||
expect(component.releaseUrl).toEqual(
|
||||
'https://github.com/paperless-ngx/paperless-ngx/releases/tag/v3.5.1'
|
||||
)
|
||||
})
|
||||
|
||||
it('should offer to enable update checking if never chosen', () => {
|
||||
create()
|
||||
const chosen = jest.fn()
|
||||
component.updateCheckingChosen.subscribe(chosen)
|
||||
component.load('3.4.2')
|
||||
fixture.detectChanges()
|
||||
|
||||
const enable = Array.from(
|
||||
fixture.nativeElement.querySelectorAll('.modal-body button')
|
||||
).find((b: HTMLButtonElement) => b.textContent.trim() === 'Enable') as
|
||||
HTMLButtonElement | undefined
|
||||
expect(enable).toBeTruthy()
|
||||
httpTestingController.expectNone(`${environment.apiBaseUrl}release_notes/`)
|
||||
|
||||
enable.click()
|
||||
expect(chosen).toHaveBeenCalledWith(true)
|
||||
httpTestingController
|
||||
.expectOne(`${environment.apiBaseUrl}release_notes/?since=3.4.2`)
|
||||
.flush({ version: '3.5.1', releases: [] })
|
||||
})
|
||||
|
||||
it('should show the disabled message after choosing disable', () => {
|
||||
create()
|
||||
const chosen = jest.fn()
|
||||
component.updateCheckingChosen.subscribe(chosen)
|
||||
component.load(null)
|
||||
component.setUpdateChecking(false)
|
||||
fixture.detectChanges()
|
||||
|
||||
expect(chosen).toHaveBeenCalledWith(false)
|
||||
httpTestingController.expectNone(`${environment.apiBaseUrl}release_notes/`)
|
||||
expect(fixture.nativeElement.textContent).toContain(
|
||||
'when update checking is enabled'
|
||||
)
|
||||
})
|
||||
|
||||
it('should not offer to enable update checking without permission', () => {
|
||||
create(undefined, false)
|
||||
component.load(null)
|
||||
fixture.detectChanges()
|
||||
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Enable')
|
||||
expect(fixture.nativeElement.textContent).toContain(
|
||||
'when update checking is enabled'
|
||||
)
|
||||
})
|
||||
|
||||
it('should support close', () => {
|
||||
create(false)
|
||||
const closeSpy = jest.spyOn(component.activeModal, 'close')
|
||||
component.close()
|
||||
expect(closeSpy).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
import { DecimalPipe, NgTemplateOutlet } from '@angular/common'
|
||||
import { Component, inject, output, signal } from '@angular/core'
|
||||
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
|
||||
import { first } from 'rxjs'
|
||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
||||
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
||||
import {
|
||||
PermissionAction,
|
||||
PermissionsService,
|
||||
PermissionType,
|
||||
} from 'src/app/services/permissions.service'
|
||||
import {
|
||||
AppRelease,
|
||||
RemoteVersionService,
|
||||
} from 'src/app/services/rest/remote-version.service'
|
||||
import { SettingsService } from 'src/app/services/settings.service'
|
||||
|
||||
const REPO_URL = 'https://github.com/paperless-ngx/paperless-ngx'
|
||||
const RELEASES_URL = `${REPO_URL}/releases`
|
||||
const DISCUSSIONS_URL = `${REPO_URL}/discussions/new/choose`
|
||||
const UPDATING_DOCS_URL =
|
||||
'https://docs.paperless-ngx.com/administration/#updating'
|
||||
|
||||
/**
|
||||
* Tweak GitHub release HTML: open links in a new tab, add no referrer etc,
|
||||
* drop inline svgs and GH `data-*` attributes. Angular sanitizes all of this anyway.
|
||||
*/
|
||||
export function prepareReleaseHtml(html: string): string {
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html')
|
||||
doc.querySelectorAll('svg').forEach((svg) => svg.remove())
|
||||
doc.body.querySelectorAll('*').forEach((el) => {
|
||||
for (const attr of Array.from(el.attributes)) {
|
||||
if (attr.name.startsWith('data-')) el.removeAttribute(attr.name)
|
||||
}
|
||||
})
|
||||
doc.querySelectorAll('a').forEach((a) => {
|
||||
a.setAttribute('target', '_blank')
|
||||
a.setAttribute('rel', 'noopener noreferrer nofollow')
|
||||
})
|
||||
return doc.body.innerHTML
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'pngx-release-notes-dialog',
|
||||
templateUrl: './release-notes-dialog.component.html',
|
||||
styleUrls: ['./release-notes-dialog.component.scss'],
|
||||
imports: [
|
||||
BootstrapIconComponent,
|
||||
CustomDatePipe,
|
||||
NgTemplateOutlet,
|
||||
DecimalPipe,
|
||||
],
|
||||
})
|
||||
export class ReleaseNotesDialogComponent {
|
||||
readonly activeModal = inject(NgbActiveModal)
|
||||
private readonly remoteVersionService = inject(RemoteVersionService)
|
||||
private readonly settingsService = inject(SettingsService)
|
||||
private readonly permissionsService = inject(PermissionsService)
|
||||
|
||||
readonly since = signal<string | null>(null)
|
||||
readonly until = signal<string | null>(null)
|
||||
readonly releases = signal<AppRelease[] | null>(null)
|
||||
readonly stars = signal<number | null>(null)
|
||||
readonly loading = signal(false)
|
||||
|
||||
readonly version: string = this.settingsService.get(SETTINGS_KEYS.VERSION)
|
||||
readonly updateCheckingEnabled = signal<boolean>(
|
||||
this.settingsService.get(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED)
|
||||
)
|
||||
readonly updateCheckingIsSet = signal(
|
||||
this.settingsService.updateCheckingIsSet
|
||||
)
|
||||
readonly canChangeUpdateChecking = this.permissionsService.currentUserCan(
|
||||
PermissionAction.Change,
|
||||
PermissionType.UISettings
|
||||
)
|
||||
|
||||
readonly updateCheckingChosen = output<boolean>()
|
||||
|
||||
readonly repoUrl = REPO_URL
|
||||
readonly releasesUrl = RELEASES_URL
|
||||
readonly discussionsUrl = DISCUSSIONS_URL
|
||||
readonly updatingDocsUrl = UPDATING_DOCS_URL
|
||||
|
||||
get releaseUrl(): string {
|
||||
const version = this.until() ?? this.version
|
||||
return version ? `${RELEASES_URL}/tag/v${version}` : RELEASES_URL
|
||||
}
|
||||
|
||||
/**
|
||||
* Load notes for releases after `since` up to `until` (default: the
|
||||
* running version), or just the `until` version's notes if `since` is null.
|
||||
*/
|
||||
load(since: string | null, until: string | null = null): void {
|
||||
this.since.set(since)
|
||||
this.until.set(until)
|
||||
if (!this.updateCheckingEnabled()) return
|
||||
this.loading.set(true)
|
||||
this.remoteVersionService
|
||||
.getReleaseNotes(since ?? undefined, until ?? undefined)
|
||||
.pipe(first())
|
||||
.subscribe({
|
||||
next: (notes) => {
|
||||
this.releases.set(
|
||||
notes.releases.map((release) => ({
|
||||
...release,
|
||||
body_html: prepareReleaseHtml(release.body_html),
|
||||
}))
|
||||
)
|
||||
this.stars.set(notes.stars ?? null)
|
||||
this.loading.set(false)
|
||||
},
|
||||
error: () => {
|
||||
this.releases.set([])
|
||||
this.loading.set(false)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
setUpdateChecking(enable: boolean): void {
|
||||
this.updateCheckingIsSet.set(true)
|
||||
this.updateCheckingEnabled.set(enable)
|
||||
this.updateCheckingChosen.emit(enable)
|
||||
if (enable) this.load(this.since(), this.until())
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.activeModal.close()
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,13 @@
|
||||
@if (tag()) {
|
||||
@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>
|
||||
}
|
||||
@if (showParents() && tag().parent) {
|
||||
<pngx-tag [tagID]="tag().parent" [clickable]="clickable()" [linkTitle]="linkTitle()"></pngx-tag>
|
||||
>
|
||||
}
|
||||
@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,46 +11,3 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ 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 = {
|
||||
@@ -70,88 +69,4 @@ 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,27 +1,11 @@
|
||||
import {
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
signal,
|
||||
} from '@angular/core'
|
||||
import { Component, effect, inject, input, model } 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',
|
||||
@@ -29,9 +13,8 @@ const COLLAPSE_BELOW_EM = 1.5
|
||||
styleUrls: ['./tag.component.scss'],
|
||||
})
|
||||
export class TagComponent {
|
||||
private readonly permissionsService = inject(PermissionsService)
|
||||
private readonly tagService = inject(TagService)
|
||||
private readonly settingsService = inject(SettingsService)
|
||||
private permissionsService = inject(PermissionsService)
|
||||
private tagService = inject(TagService)
|
||||
|
||||
readonly tag = model<Tag>(null)
|
||||
readonly tagID = input<number>(undefined)
|
||||
@@ -40,101 +23,27 @@ export class TagComponent {
|
||||
transform: (value: boolean | string) =>
|
||||
value === '' || value === true || value === 'true',
|
||||
})
|
||||
|
||||
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(' › ')
|
||||
)
|
||||
readonly showParents = input(false)
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const tagID = this.tagID()
|
||||
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]))
|
||||
if (tagID) {
|
||||
if (
|
||||
this.permissionsService.currentUserCan(
|
||||
PermissionAction.View,
|
||||
PermissionType.Tag
|
||||
)
|
||||
)
|
||||
})
|
||||
) {
|
||||
this.tagService.getCached(tagID).subscribe((tag) => {
|
||||
this.tag.set(tag)
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -76,8 +76,8 @@
|
||||
}
|
||||
}
|
||||
@case (DisplayField.TAGS) {
|
||||
@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>
|
||||
@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>
|
||||
}
|
||||
}
|
||||
@case (DisplayField.DOCUMENT_TYPE) {
|
||||
|
||||
-2
@@ -38,7 +38,6 @@ 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'
|
||||
@@ -76,7 +75,6 @@ import { WidgetFrameComponent } from '../widget-frame/widget-frame.component'
|
||||
DocumentTypeNamePipe,
|
||||
StoragePathNamePipe,
|
||||
AsyncPipe,
|
||||
CollapseTagsPipe,
|
||||
DocumentTitlePipe,
|
||||
CustomDatePipe,
|
||||
NgClass,
|
||||
|
||||
@@ -390,12 +390,14 @@ describe('DocumentDetailComponent', () => {
|
||||
expect(component.documentForm.get('title').value).toEqual('Foo Bar')
|
||||
})
|
||||
|
||||
it('should update the title form value without waiting for debounce or blur', () => {
|
||||
it('should update title before doc change if was not updated via debounce', () => {
|
||||
jest.useFakeTimers()
|
||||
initNormally()
|
||||
const input = component.titleInput.inputField.nativeElement
|
||||
input.value = 'Foo Bar'
|
||||
input.dispatchEvent(new Event('input'))
|
||||
component.titleInput.value = 'Foo Bar'
|
||||
component.titleInput.inputField.nativeElement.dispatchEvent(
|
||||
new Event('change')
|
||||
)
|
||||
jest.advanceTimersByTime(1000)
|
||||
expect(component.documentForm.get('title').value).toEqual('Foo Bar')
|
||||
})
|
||||
|
||||
|
||||
+2
-2
@@ -36,8 +36,8 @@
|
||||
{{document().title | documentTitle}}
|
||||
}
|
||||
@if (displayFields().includes(DisplayField.TAGS)) {
|
||||
@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>
|
||||
@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>
|
||||
}
|
||||
}
|
||||
} @else {
|
||||
|
||||
-2
@@ -20,7 +20,6 @@ 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'
|
||||
@@ -46,7 +45,6 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading
|
||||
TagComponent,
|
||||
CustomFieldDisplayComponent,
|
||||
AsyncPipe,
|
||||
CollapseTagsPipe,
|
||||
NgOptimizedImage,
|
||||
UsernamePipe,
|
||||
CorrespondentNamePipe,
|
||||
|
||||
+4
-5
@@ -19,12 +19,11 @@
|
||||
}
|
||||
|
||||
@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">
|
||||
@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>
|
||||
<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>
|
||||
}
|
||||
@if (getMoreTags(visibleTagIDs); as moreTags) {
|
||||
@if (moreTags) {
|
||||
<div>
|
||||
<span class="badge text-dark">+ {{moreTags}}</span>
|
||||
</div>
|
||||
|
||||
+1
-2
@@ -103,8 +103,7 @@ a {
|
||||
line-height: 1;
|
||||
|
||||
&.tags-no-wrap {
|
||||
// split-pill parents clip to a stub instead (see TagComponent)
|
||||
::ng-deep .badge:not(.split-parent) {
|
||||
::ng-deep .badge {
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
white-space: nowrap;
|
||||
|
||||
+2
-33
@@ -4,9 +4,6 @@ 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'
|
||||
|
||||
@@ -100,36 +97,8 @@ 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.getMoreTags(component.document().tags)).toEqual(3)
|
||||
expect(component.moreTags).toEqual(3)
|
||||
|
||||
fixture.componentRef.setInput('document', {
|
||||
...component.document(),
|
||||
@@ -137,7 +106,7 @@ describe('DocumentCardSmallComponent', () => {
|
||||
})
|
||||
fixture.detectChanges()
|
||||
|
||||
expect(component.getMoreTags(component.document().tags)).toBeNull()
|
||||
expect(component.moreTags).toBeNull()
|
||||
expect(fixture.nativeElement.textContent).not.toContain('+ 3')
|
||||
})
|
||||
|
||||
|
||||
+14
-12
@@ -20,7 +20,6 @@ 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'
|
||||
@@ -46,7 +45,6 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading
|
||||
TagComponent,
|
||||
CustomFieldDisplayComponent,
|
||||
AsyncPipe,
|
||||
CollapseTagsPipe,
|
||||
NgOptimizedImage,
|
||||
UsernamePipe,
|
||||
CorrespondentNamePipe,
|
||||
@@ -92,13 +90,12 @@ export class DocumentCardSmallComponent
|
||||
@Output()
|
||||
clickStoragePath = new EventEmitter<number>()
|
||||
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
@ViewChild('popupPreview') popupPreview: PreviewPopupComponent
|
||||
@@ -119,9 +116,14 @@ export class DocumentCardSmallComponent
|
||||
return this.documentService.getDownloadUrl(this.document().id)
|
||||
}
|
||||
|
||||
getTagIDs(tagIDs: number[]): number[] {
|
||||
const limit = this.tagLimit
|
||||
return tagIDs?.length > limit ? tagIDs.slice(0, limit - 1) : tagIDs
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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 | 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>
|
||||
@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>
|
||||
}
|
||||
}
|
||||
</td>
|
||||
|
||||
@@ -39,7 +39,6 @@ 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'
|
||||
@@ -97,7 +96,6 @@ import { SaveViewConfigDialogComponent } from './save-view-config-dialog/save-vi
|
||||
StoragePathNamePipe,
|
||||
BootstrapIconComponent,
|
||||
AsyncPipe,
|
||||
CollapseTagsPipe,
|
||||
FormsModule,
|
||||
ReactiveFormsModule,
|
||||
NgTemplateOutlet,
|
||||
|
||||
@@ -75,6 +75,7 @@ export const SETTINGS_KEYS = {
|
||||
UPDATE_CHECKING_ENABLED: 'general-settings:update-checking:enabled',
|
||||
UPDATE_CHECKING_BACKEND_SETTING:
|
||||
'general-settings:update-checking:backend-setting',
|
||||
WHATS_NEW_LAST_SEEN_VERSION: 'general-settings:whats-new:last-seen-version',
|
||||
SAVED_VIEWS_WARN_ON_UNSAVED_CHANGE:
|
||||
'general-settings:saved-views:warn-on-unsaved-change',
|
||||
DASHBOARD_VIEWS_VISIBLE_IDS:
|
||||
@@ -94,7 +95,6 @@ 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:
|
||||
@@ -224,6 +224,11 @@ export const SETTINGS: UiSetting[] = [
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
key: SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION,
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
{
|
||||
key: SETTINGS_KEYS.SAVED_VIEWS_WARN_ON_UNSAVED_CHANGE,
|
||||
type: 'boolean',
|
||||
@@ -306,11 +311,6 @@ 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',
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
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])
|
||||
})
|
||||
})
|
||||
@@ -1,47 +0,0 @@
|
||||
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))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -40,4 +40,28 @@ describe('RemoteVersionService', () => {
|
||||
)
|
||||
expect(req.request.method).toEqual('GET')
|
||||
})
|
||||
|
||||
it('should call release notes endpoint without since', () => {
|
||||
subscription = service.getReleaseNotes().subscribe()
|
||||
const req = httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}release_notes/`
|
||||
)
|
||||
expect(req.request.method).toEqual('GET')
|
||||
expect(req.request.params.has('since')).toBe(false)
|
||||
})
|
||||
|
||||
it('should pass since to release notes endpoint', () => {
|
||||
subscription = service.getReleaseNotes('3.4.2').subscribe()
|
||||
const req = httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}release_notes/?since=3.4.2`
|
||||
)
|
||||
expect(req.request.method).toEqual('GET')
|
||||
})
|
||||
|
||||
it('should pass until to release notes endpoint', () => {
|
||||
subscription = service.getReleaseNotes('3.5.1', '3.6.0').subscribe()
|
||||
httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}release_notes/?since=3.5.1&until=3.6.0`
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { HttpClient } from '@angular/common/http'
|
||||
import { HttpClient, HttpParams } from '@angular/common/http'
|
||||
import { Injectable, inject } from '@angular/core'
|
||||
import { Observable } from 'rxjs'
|
||||
import { environment } from 'src/environments/environment'
|
||||
@@ -8,6 +8,20 @@ export interface AppRemoteVersion {
|
||||
update_available: boolean
|
||||
}
|
||||
|
||||
export interface AppRelease {
|
||||
version: string
|
||||
name: string
|
||||
body_html: string
|
||||
html_url: string
|
||||
published_at: string
|
||||
}
|
||||
|
||||
export interface AppReleaseNotes {
|
||||
version: string
|
||||
releases: AppRelease[]
|
||||
stars: number | null
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
@@ -19,4 +33,21 @@ export class RemoteVersionService {
|
||||
`${environment.apiBaseUrl}remote_version/`
|
||||
)
|
||||
}
|
||||
|
||||
public getReleaseNotes(
|
||||
since?: string,
|
||||
until?: string
|
||||
): Observable<AppReleaseNotes> {
|
||||
let params = new HttpParams()
|
||||
if (since) {
|
||||
params = params.set('since', since)
|
||||
}
|
||||
if (until) {
|
||||
params = params.set('until', until)
|
||||
}
|
||||
return this.http.get<AppReleaseNotes>(
|
||||
`${environment.apiBaseUrl}release_notes/`,
|
||||
{ params }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -398,6 +398,60 @@ describe('SettingsService', () => {
|
||||
expect(req.request.method).toEqual('POST')
|
||||
})
|
||||
|
||||
it('seeds last seen version on first load', () => {
|
||||
const settings = {
|
||||
...ui_settings,
|
||||
user: { ...ui_settings.user, is_superuser: true },
|
||||
settings: {
|
||||
...ui_settings.settings,
|
||||
documentListSize: 50,
|
||||
update_checking: { enabled: false, backend_setting: 'default' },
|
||||
},
|
||||
}
|
||||
settings.settings['version'] = '3.5.1'
|
||||
httpTestingController
|
||||
.expectOne(`${environment.apiBaseUrl}ui_settings/`)
|
||||
.flush(settings)
|
||||
|
||||
const req = httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}ui_settings/`
|
||||
)
|
||||
expect(req.request.method).toEqual('POST')
|
||||
expect(req.request.body.settings.whats_new.last_seen_version).toEqual(
|
||||
'3.5.1'
|
||||
)
|
||||
expect(settingsService.unseenReleasesSince()).toBeNull()
|
||||
})
|
||||
|
||||
it('reports unseen releases and marks them seen', () => {
|
||||
const settings = {
|
||||
...ui_settings,
|
||||
user: { ...ui_settings.user, is_superuser: true },
|
||||
settings: {
|
||||
...ui_settings.settings,
|
||||
documentListSize: 50,
|
||||
update_checking: { enabled: false, backend_setting: 'default' },
|
||||
},
|
||||
}
|
||||
settings.settings['version'] = '3.5.1'
|
||||
settings.settings['whats_new'] = { last_seen_version: '3.4.2' }
|
||||
httpTestingController
|
||||
.expectOne(`${environment.apiBaseUrl}ui_settings/`)
|
||||
.flush(settings)
|
||||
httpTestingController.expectNone(`${environment.apiBaseUrl}ui_settings/`)
|
||||
|
||||
expect(settingsService.unseenReleasesSince()).toEqual('3.4.2')
|
||||
|
||||
subscription = settingsService.markReleasesSeen().subscribe()
|
||||
const req = httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}ui_settings/`
|
||||
)
|
||||
expect(req.request.body.settings.whats_new.last_seen_version).toEqual(
|
||||
'3.5.1'
|
||||
)
|
||||
expect(settingsService.unseenReleasesSince()).toBeNull()
|
||||
})
|
||||
|
||||
it('updates settings on complete tour', () => {
|
||||
let req = httpTestingController.expectOne(
|
||||
`${environment.apiBaseUrl}ui_settings/`
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
hexToHsl,
|
||||
} from 'src/app/utils/color'
|
||||
import { DEFAULT_APP_TITLE, environment } from 'src/environments/environment'
|
||||
import { compareVersions } from 'src/app/utils/version'
|
||||
import { DEFAULT_DISPLAY_FIELDS, DisplayField } from '../data/document'
|
||||
import { RemoteOCRModeConfig } from '../data/paperless-config'
|
||||
import { SavedView } from '../data/saved-view'
|
||||
@@ -327,6 +328,18 @@ export class SettingsService {
|
||||
SETTINGS_KEYS.SIDEBAR_HIDDEN_ITEMS
|
||||
)
|
||||
|
||||
/**
|
||||
* The last version the user saw release notes for, if the running
|
||||
* version is newer, or null.
|
||||
*/
|
||||
readonly unseenReleasesSince = computed<string | null>(() => {
|
||||
this.settingsVersion()
|
||||
const currentVersion = this.get(SETTINGS_KEYS.VERSION)
|
||||
const lastSeen = this.get(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION)
|
||||
if (!currentVersion || !lastSeen) return null
|
||||
return compareVersions(currentVersion, lastSeen) > 0 ? lastSeen : null
|
||||
})
|
||||
|
||||
readonly allDisplayFields = signal<Array<{ id: DisplayField; name: string }>>(
|
||||
DEFAULT_DISPLAY_FIELDS
|
||||
)
|
||||
@@ -384,6 +397,7 @@ export class SettingsService {
|
||||
uisettings.permissions,
|
||||
this.currentUser()
|
||||
)
|
||||
this.maybeSeedLastSeenVersion()
|
||||
|
||||
this.initializeDisplayFields()
|
||||
})
|
||||
@@ -713,6 +727,34 @@ export class SettingsService {
|
||||
return this.settingIsSet(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED)
|
||||
}
|
||||
|
||||
/**
|
||||
* Record the baseline version for "what's new" tracking.
|
||||
*/
|
||||
private maybeSeedLastSeenVersion() {
|
||||
const currentVersion = this.get(SETTINGS_KEYS.VERSION)
|
||||
if (
|
||||
!currentVersion ||
|
||||
this.get(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION) ||
|
||||
!this.permissionsService.currentUserCan(
|
||||
PermissionAction.Change,
|
||||
PermissionType.UISettings
|
||||
)
|
||||
)
|
||||
return
|
||||
this.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, currentVersion)
|
||||
this.storeSettings()
|
||||
.pipe(first())
|
||||
.subscribe({ error: () => {} })
|
||||
}
|
||||
|
||||
public markReleasesSeen(): Observable<any> {
|
||||
this.set(
|
||||
SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION,
|
||||
this.get(SETTINGS_KEYS.VERSION)
|
||||
)
|
||||
return this.storeSettings()
|
||||
}
|
||||
|
||||
/**
|
||||
* Offering remote OCR as a choice only makes sense when an engine
|
||||
* is configured but is not already handling every document.
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
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])
|
||||
})
|
||||
})
|
||||
@@ -1,43 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { compareVersions } from './version'
|
||||
|
||||
describe('compareVersions', () => {
|
||||
it('should compare versions numerically', () => {
|
||||
expect(compareVersions('3.5.1', '3.5.0')).toBeGreaterThan(0)
|
||||
expect(compareVersions('3.10.0', '3.9.9')).toBeGreaterThan(0)
|
||||
expect(compareVersions('3.4.2', '3.5.0')).toBeLessThan(0)
|
||||
expect(compareVersions('3.5.0', '3.5.0')).toEqual(0)
|
||||
expect(compareVersions('3.5', '3.5.0')).toEqual(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Compare two X.Y.Z version strings numerically.
|
||||
* Returns a positive number if a > b, negative if a < b, 0 if equal.
|
||||
*/
|
||||
export function compareVersions(a: string, b: string): number {
|
||||
const partsA = a.split('.').map((p) => Number.parseInt(p, 10) || 0)
|
||||
const partsB = b.split('.').map((p) => Number.parseInt(p, 10) || 0)
|
||||
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
|
||||
const diff = (partsA[i] ?? 0) - (partsB[i] ?? 0)
|
||||
if (diff !== 0) return diff
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -13,6 +13,9 @@ $form-file-button-hover-bg: var(--pngx-bg-alt);
|
||||
@include meta.load-css("print");
|
||||
|
||||
// re-created bootstrap styles
|
||||
.mt-n1 {
|
||||
margin-top: -0.25rem;
|
||||
}
|
||||
.mt-n2 {
|
||||
margin-top: -0.5rem;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from django.core.cache import cache
|
||||
from pytest_httpx import HTTPXMock
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from paperless import version
|
||||
|
||||
REPO_URL = "https://api.github.com/repos/paperless-ngx/paperless-ngx"
|
||||
RELEASES_URL = f"{REPO_URL}/releases?per_page=10&page=1"
|
||||
|
||||
|
||||
def _page_url(page: int) -> str:
|
||||
return f"{REPO_URL}/releases?per_page=10&page={page}"
|
||||
|
||||
|
||||
def _tag_url(version_str: str) -> str:
|
||||
return f"{REPO_URL}/releases/tags/v{version_str}"
|
||||
|
||||
|
||||
def _release(tag: str, **kwargs) -> dict:
|
||||
return {
|
||||
"tag_name": tag,
|
||||
"name": f"Paperless-ngx {tag}",
|
||||
"body_html": f"<h2>paperless-ngx {tag}</h2>",
|
||||
"html_url": f"https://github.com/paperless-ngx/paperless-ngx/releases/tag/{tag}",
|
||||
"published_at": "2026-11-17T03:36:20Z",
|
||||
"draft": False,
|
||||
"prerelease": False,
|
||||
**kwargs,
|
||||
}
|
||||
|
||||
|
||||
def _bump(minor: int = 0, patch: int = 0) -> str:
|
||||
major, cur_minor, cur_patch = version.__version__
|
||||
return f"{major}.{cur_minor + minor}.{cur_patch + patch}"
|
||||
|
||||
|
||||
CURRENT = version.__full_version_str__
|
||||
PREVIOUS = f"{version.__version__[0]}.{version.__version__[1] - 1}.0"
|
||||
OLDER = f"{version.__version__[0]}.{version.__version__[1] - 2}.0"
|
||||
|
||||
|
||||
class TestApiReleaseNotes:
|
||||
ENDPOINT = "/api/release_notes/"
|
||||
|
||||
def setup_method(self) -> None:
|
||||
cache.clear()
|
||||
|
||||
@pytest.fixture
|
||||
def releases(self, httpx_mock: HTTPXMock) -> HTTPXMock:
|
||||
httpx_mock.add_response(
|
||||
url=RELEASES_URL,
|
||||
match_headers={"Accept": "application/vnd.github.html+json"},
|
||||
json=[
|
||||
_release(f"v{_bump(patch=1)}"),
|
||||
_release(f"v{_bump(minor=1)}-beta.1", prerelease=True),
|
||||
_release(f"v{CURRENT}"),
|
||||
_release(f"v{PREVIOUS}"),
|
||||
_release(f"ngx-{OLDER}"),
|
||||
],
|
||||
)
|
||||
return httpx_mock
|
||||
|
||||
@pytest.fixture
|
||||
def current_release(self, httpx_mock: HTTPXMock) -> HTTPXMock:
|
||||
httpx_mock.add_response(
|
||||
url=_tag_url(CURRENT),
|
||||
match_headers={"Accept": "application/vnd.github.html+json"},
|
||||
json=_release(f"v{CURRENT}"),
|
||||
)
|
||||
return httpx_mock
|
||||
|
||||
@pytest.fixture
|
||||
def stars(self, httpx_mock: HTTPXMock) -> HTTPXMock:
|
||||
httpx_mock.add_response(url=REPO_URL, json={"stargazers_count": 1234})
|
||||
return httpx_mock
|
||||
|
||||
@pytest.mark.usefixtures("stars")
|
||||
def test_since_returns_newer_up_to_current(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
releases: HTTPXMock,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- GitHub releases older, equal to, and newer than the running version
|
||||
WHEN:
|
||||
- Release notes are requested since an older version
|
||||
THEN:
|
||||
- Only releases after `since` up to the running version are returned,
|
||||
newest first, excluding prereleases and the `since` release itself
|
||||
"""
|
||||
response = rest_api_client.get(self.ENDPOINT, {"since": OLDER})
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["version"] == CURRENT
|
||||
assert [r["version"] for r in response.data["releases"]] == [
|
||||
CURRENT,
|
||||
PREVIOUS,
|
||||
]
|
||||
assert response.data["releases"][0]["html_url"].endswith(f"v{CURRENT}")
|
||||
assert (
|
||||
response.data["releases"][0]["body_html"]
|
||||
== f"<h2>paperless-ngx v{CURRENT}</h2>"
|
||||
)
|
||||
|
||||
@pytest.mark.usefixtures("stars")
|
||||
def test_without_since_fetches_current_only(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
current_release: HTTPXMock,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A GitHub release for the running version
|
||||
WHEN:
|
||||
- Release notes are requested without `since`
|
||||
THEN:
|
||||
- Only that release is fetched, by tag, and returned
|
||||
"""
|
||||
response = rest_api_client.get(self.ENDPOINT)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert [r["version"] for r in response.data["releases"]] == [CURRENT]
|
||||
assert len(current_release.get_requests(url=_tag_url(CURRENT))) == 1
|
||||
|
||||
@pytest.mark.usefixtures("stars")
|
||||
def test_since_pages_back_to_since(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
httpx_mock: HTTPXMock,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- More releases since `since` than fit on one page
|
||||
WHEN:
|
||||
- Release notes are requested since that version
|
||||
THEN:
|
||||
- GitHub is paged until `since` is reached and all releases are returned
|
||||
"""
|
||||
major, minor, _ = version.__version__
|
||||
page_one = [f"{major}.{minor - 1}.{patch}" for patch in range(10, 0, -1)]
|
||||
httpx_mock.add_response(
|
||||
url=_page_url(1),
|
||||
json=[_release(f"v{v}") for v in page_one],
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
url=_page_url(2),
|
||||
json=[_release(f"v{PREVIOUS}"), _release(f"v{OLDER}")],
|
||||
)
|
||||
|
||||
response = rest_api_client.get(self.ENDPOINT, {"since": OLDER})
|
||||
|
||||
assert [r["version"] for r in response.data["releases"]] == [
|
||||
*page_one,
|
||||
PREVIOUS,
|
||||
]
|
||||
|
||||
@pytest.mark.usefixtures("stars")
|
||||
def test_since_paging_is_capped(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
httpx_mock: HTTPXMock,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Full pages of releases that never reach `since`
|
||||
WHEN:
|
||||
- Release notes are requested since a very old version
|
||||
THEN:
|
||||
- Paging stops after the page cap
|
||||
"""
|
||||
major, minor, _ = version.__version__
|
||||
for page in range(1, 4):
|
||||
httpx_mock.add_response(
|
||||
url=_page_url(page),
|
||||
json=[
|
||||
_release(f"v{major}.{minor}.{page * 100 + patch}")
|
||||
for patch in range(10)
|
||||
],
|
||||
)
|
||||
|
||||
rest_api_client.get(self.ENDPOINT, {"since": "0.1.0"})
|
||||
|
||||
assert len(httpx_mock.get_requests()) == 4 # 3 pages + stars
|
||||
|
||||
@pytest.mark.usefixtures("stars")
|
||||
@pytest.mark.usefixtures("current_release")
|
||||
def test_releases_are_cached(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
releases: HTTPXMock,
|
||||
) -> None:
|
||||
for _ in range(2):
|
||||
rest_api_client.get(self.ENDPOINT, {"since": OLDER})
|
||||
rest_api_client.get(self.ENDPOINT)
|
||||
|
||||
assert len(releases.get_requests(url=RELEASES_URL)) == 1
|
||||
assert len(releases.get_requests(url=_tag_url(CURRENT))) == 1
|
||||
assert len(releases.get_requests(url=REPO_URL)) == 1
|
||||
|
||||
@pytest.mark.usefixtures("stars")
|
||||
def test_new_running_version_refetches_releases(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
releases: HTTPXMock,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- GitHub releases cached for the running version
|
||||
WHEN:
|
||||
- The running version changes (i.e. paperless was upgraded)
|
||||
THEN:
|
||||
- The cached releases are not reused and GitHub is queried again
|
||||
"""
|
||||
upgraded = _bump(patch=1)
|
||||
releases.add_response(url=RELEASES_URL, json=[_release(f"v{upgraded}")])
|
||||
|
||||
rest_api_client.get(self.ENDPOINT, {"since": OLDER})
|
||||
with mock.patch.object(version, "__full_version_str__", upgraded):
|
||||
response = rest_api_client.get(self.ENDPOINT, {"since": CURRENT})
|
||||
|
||||
assert len(releases.get_requests(url=RELEASES_URL)) == 2
|
||||
assert [r["version"] for r in response.data["releases"]] == [upgraded]
|
||||
|
||||
@pytest.mark.usefixtures("stars")
|
||||
def test_until_returns_newer_releases(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
releases: HTTPXMock,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A GitHub release newer than the running version
|
||||
WHEN:
|
||||
- Release notes are requested from the running version until the newer one
|
||||
THEN:
|
||||
- Only the newer release is returned, excluding prereleases
|
||||
"""
|
||||
response = rest_api_client.get(
|
||||
self.ENDPOINT,
|
||||
{"since": CURRENT, "until": _bump(minor=1)},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert [r["version"] for r in response.data["releases"]] == [
|
||||
_bump(patch=1),
|
||||
]
|
||||
|
||||
@pytest.mark.parametrize("param", ["since", "until"])
|
||||
def test_invalid_version(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
param: str,
|
||||
) -> None:
|
||||
response = rest_api_client.get(self.ENDPOINT, {param: "not-a-version"})
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mock_kwargs",
|
||||
[
|
||||
pytest.param({"status_code": 503}, id="http-error"),
|
||||
pytest.param(
|
||||
{
|
||||
"content": b'{ "blah":',
|
||||
"headers": {"Content-Type": "application/json"},
|
||||
},
|
||||
id="bad-json",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_github_failure_returns_empty_and_is_not_cached(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
httpx_mock: HTTPXMock,
|
||||
mock_kwargs: dict,
|
||||
) -> None:
|
||||
httpx_mock.add_response(url=_tag_url(CURRENT), **mock_kwargs)
|
||||
httpx_mock.add_response(url=_tag_url(CURRENT), json=_release(f"v{CURRENT}"))
|
||||
httpx_mock.add_response(
|
||||
url=REPO_URL,
|
||||
json={"stargazers_count": 1234},
|
||||
is_reusable=True,
|
||||
)
|
||||
|
||||
response = rest_api_client.get(self.ENDPOINT)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["releases"] == []
|
||||
|
||||
response = rest_api_client.get(self.ENDPOINT)
|
||||
assert [r["version"] for r in response.data["releases"]] == [CURRENT]
|
||||
|
||||
@pytest.mark.usefixtures("current_release", "stars")
|
||||
def test_stars_are_returned_and_cached(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
httpx_mock: HTTPXMock,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The GitHub repository reports a star count
|
||||
WHEN:
|
||||
- Release notes are requested twice
|
||||
THEN:
|
||||
- The star count is included and GitHub is only asked once
|
||||
"""
|
||||
response = rest_api_client.get(self.ENDPOINT)
|
||||
assert response.data["stars"] == 1234
|
||||
|
||||
response = rest_api_client.get(self.ENDPOINT)
|
||||
assert response.data["stars"] == 1234
|
||||
assert len(httpx_mock.get_requests(url=REPO_URL)) == 1
|
||||
|
||||
@pytest.mark.usefixtures("current_release")
|
||||
def test_stars_failure_returns_none_and_is_not_cached(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
httpx_mock: HTTPXMock,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The GitHub repository request fails, then succeeds
|
||||
WHEN:
|
||||
- Release notes are requested twice
|
||||
THEN:
|
||||
- Stars are null at first, then fetched again rather than cached
|
||||
"""
|
||||
httpx_mock.add_response(url=REPO_URL, status_code=503)
|
||||
httpx_mock.add_response(url=REPO_URL, json={"stargazers_count": 1234})
|
||||
|
||||
response = rest_api_client.get(self.ENDPOINT)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["stars"] is None
|
||||
assert len(response.data["releases"]) == 1
|
||||
|
||||
response = rest_api_client.get(self.ENDPOINT)
|
||||
assert response.data["stars"] == 1234
|
||||
@@ -4314,6 +4314,139 @@ class UiSettingsView(GenericAPIView[Any]):
|
||||
)
|
||||
|
||||
|
||||
GITHUB_CACHE_KEY = "github_data:%s"
|
||||
GITHUB_RELEASES_CACHE_TIMEOUT = 60 * 60 * 12
|
||||
GITHUB_REQUEST_TIMEOUT = 5
|
||||
|
||||
|
||||
GITHUB_RELEASES_URL = (
|
||||
"https://api.github.com/repos/paperless-ngx/paperless-ngx/releases"
|
||||
)
|
||||
GITHUB_RELEASES_PER_PAGE = 10
|
||||
# Caps how far back a range can walk, e.g. for a bad `since`
|
||||
GITHUB_RELEASES_MAX_PAGES = 3
|
||||
|
||||
|
||||
def _fetch_github_releases_json(url: str, params: dict | None = None) -> Any | None:
|
||||
try:
|
||||
resp = httpx.get(
|
||||
url,
|
||||
params=params,
|
||||
# GitHub renders release bodies as HTML
|
||||
headers={"Accept": "application/vnd.github.html+json"},
|
||||
timeout=GITHUB_REQUEST_TIMEOUT,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
except ValueError as e:
|
||||
logger.debug(f"An error occurred parsing GitHub releases json: {e}")
|
||||
except httpx.HTTPError as e:
|
||||
logger.debug(f"An error occurred fetching GitHub releases: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _parse_github_release(release: dict[str, Any]) -> dict[str, Any] | None:
|
||||
if release.get("draft") or release.get("prerelease"):
|
||||
return None
|
||||
try:
|
||||
# Some early tags used ngx-x.y.z
|
||||
release_version = packaging_version.parse(
|
||||
release["tag_name"].removeprefix("ngx-"),
|
||||
)
|
||||
except packaging_version.InvalidVersion:
|
||||
return None
|
||||
return {
|
||||
"version": str(release_version),
|
||||
"name": release.get("name") or release["tag_name"],
|
||||
"body_html": release.get("body_html") or "",
|
||||
"html_url": release["html_url"],
|
||||
"published_at": release.get("published_at"),
|
||||
}
|
||||
|
||||
|
||||
def get_github_release(version_str: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
Fetch a single pngx release from GitHub by version.
|
||||
"""
|
||||
cache_key = GITHUB_CACHE_KEY % f"release:{version_str}"
|
||||
release = cache.get(cache_key)
|
||||
if release is not None:
|
||||
return release
|
||||
data = _fetch_github_releases_json(f"{GITHUB_RELEASES_URL}/tags/v{version_str}")
|
||||
if data is None:
|
||||
return None
|
||||
try:
|
||||
release = _parse_github_release(data)
|
||||
except (KeyError, TypeError, AttributeError) as e:
|
||||
logger.debug(f"An error occurred parsing GitHub release json: {e}")
|
||||
return None
|
||||
if release is not None:
|
||||
cache.set(cache_key, release, GITHUB_RELEASES_CACHE_TIMEOUT)
|
||||
return release
|
||||
|
||||
|
||||
def get_github_releases(
|
||||
since: packaging_version.Version,
|
||||
until: packaging_version.Version,
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""
|
||||
Fetch pngx releases from GitHub after `since` up to and including `until`,
|
||||
newest first.
|
||||
"""
|
||||
# Keyed on the range so an upgrade (pill) or a newly detected release
|
||||
# (update available) changes `until` and gets a fresh fetch
|
||||
cache_key = GITHUB_CACHE_KEY % f"releases:{since}:{until}"
|
||||
releases = cache.get(cache_key)
|
||||
if releases is not None:
|
||||
return releases
|
||||
releases = []
|
||||
# Releases are listed newest first, so stop paging once we reach `since`
|
||||
for page in range(1, GITHUB_RELEASES_MAX_PAGES + 1):
|
||||
data = _fetch_github_releases_json(
|
||||
GITHUB_RELEASES_URL,
|
||||
params={"per_page": GITHUB_RELEASES_PER_PAGE, "page": page},
|
||||
)
|
||||
if data is None:
|
||||
return None
|
||||
try:
|
||||
batch = [r for r in map(_parse_github_release, data) if r is not None]
|
||||
except (KeyError, TypeError, AttributeError) as e:
|
||||
logger.debug(f"An error occurred parsing GitHub releases json: {e}")
|
||||
return None
|
||||
releases.extend(batch)
|
||||
if len(data) < GITHUB_RELEASES_PER_PAGE or any(
|
||||
packaging_version.parse(r["version"]) <= since for r in batch
|
||||
):
|
||||
break
|
||||
releases = [
|
||||
r for r in releases if since < packaging_version.parse(r["version"]) <= until
|
||||
]
|
||||
cache.set(cache_key, releases, GITHUB_RELEASES_CACHE_TIMEOUT)
|
||||
return releases
|
||||
|
||||
|
||||
def get_github_stars() -> int | None:
|
||||
"""
|
||||
Fetch the number of stars for the Paperless-NGX repository from GitHub.
|
||||
"""
|
||||
count = cache.get(GITHUB_CACHE_KEY % "stars")
|
||||
if count is not None:
|
||||
return count
|
||||
try:
|
||||
resp = httpx.get(
|
||||
"https://api.github.com/repos/paperless-ngx/paperless-ngx",
|
||||
headers={"Accept": "application/vnd.github+json"},
|
||||
timeout=GITHUB_REQUEST_TIMEOUT,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
count = resp.json()["stargazers_count"]
|
||||
except Exception as e:
|
||||
logger.debug(f"An error occurred fetching GitHub stars: {e}")
|
||||
return None
|
||||
cache.set(GITHUB_CACHE_KEY % "stars", count, 60 * 60)
|
||||
return count
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description="Get the current version of the Paperless-NGX server",
|
||||
@@ -4361,6 +4494,61 @@ class RemoteVersionView(GenericAPIView[Any]):
|
||||
)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description=(
|
||||
"Get release notes from GitHub for releases newer than `since`, "
|
||||
"up to and including `until` (default: the running version). "
|
||||
"Without `since`, only the `until` version's notes are returned."
|
||||
),
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="since",
|
||||
type=OpenApiTypes.STR,
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=False,
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="until",
|
||||
type=OpenApiTypes.STR,
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=False,
|
||||
),
|
||||
],
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
},
|
||||
),
|
||||
)
|
||||
class ReleaseNotesView(GenericAPIView[Any]):
|
||||
def get(self, request, format=None):
|
||||
current_version = packaging_version.parse(version.__full_version_str__)
|
||||
since = until = None
|
||||
try:
|
||||
if since_param := request.query_params.get("since"):
|
||||
since = packaging_version.parse(since_param)
|
||||
if until_param := request.query_params.get("until"):
|
||||
until = packaging_version.parse(until_param)
|
||||
except packaging_version.InvalidVersion:
|
||||
return HttpResponseBadRequest("Invalid version")
|
||||
# Newer releases can be requested e.g. for "update available"
|
||||
until = until or current_version
|
||||
|
||||
if since is None:
|
||||
release = get_github_release(str(until))
|
||||
releases = [release] if release else []
|
||||
else:
|
||||
releases = get_github_releases(since, until) or []
|
||||
|
||||
return Response(
|
||||
{
|
||||
"version": version.__full_version_str__,
|
||||
"releases": releases,
|
||||
"stars": get_github_stars(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class _TasksViewSetSchema(AutoSchema):
|
||||
_UNPAGINATED_ACTIONS = frozenset({"summary", "active", "status_counts"})
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ from documents.views import LogViewSet
|
||||
from documents.views import MergeDocumentsAsVersionsView
|
||||
from documents.views import MergeDocumentsView
|
||||
from documents.views import PostDocumentView
|
||||
from documents.views import ReleaseNotesView
|
||||
from documents.views import RemoteVersionView
|
||||
from documents.views import RemovePasswordDocumentsView
|
||||
from documents.views import ReprocessDocumentsView
|
||||
@@ -219,6 +220,11 @@ urlpatterns = [
|
||||
RemoteVersionView.as_view(),
|
||||
name="remoteversion",
|
||||
),
|
||||
re_path(
|
||||
"^release_notes/",
|
||||
ReleaseNotesView.as_view(),
|
||||
name="release_notes",
|
||||
),
|
||||
re_path(
|
||||
"^ui_settings/",
|
||||
UiSettingsView.as_view(),
|
||||
|
||||
Reference in new issue
Block a user