Compare commits

..

39 Commits

Author SHA1 Message Date
Trenton H
2cae31db7f Wrong Redis URL 2026-01-30 12:20:40 -08:00
Trenton H
38df71b71a Missing ijson 2026-01-29 10:39:11 -08:00
Trenton H
7bae6b7f6d Fixes the merge conflicts I missed 2026-01-29 10:35:10 -08:00
Trenton H
1c99e55069 Initial version hacked up by Opus 2026-01-29 10:06:02 -08:00
Trenton H
b44eea6508 The websocket included script 2026-01-29 09:39:52 -08:00
Trenton H
b8af971652 Merge remote-tracking branch 'origin/dev' into feature-migrator-application 2026-01-29 09:28:24 -08:00
shamoon
e1655045ca Ready
[ci skip]
2026-01-23 22:04:58 -08:00
shamoon
1a638d8cc0 drop, migrate, then import 2026-01-23 22:04:44 -08:00
shamoon
b21ff75a30 Run importer 2026-01-23 21:50:01 -08:00
shamoon
58f1a186d4 2.20.6 2026-01-23 21:38:02 -08:00
shamoon
2a1c06c047 Merge branch 'feature/migrator' of https://github.com/paperless-ngx/paperless-ngx into feature/migrator 2026-01-23 21:33:27 -08:00
shamoon
770dc02833 Add root URL redirect to migration home 2026-01-23 21:31:51 -08:00
shamoon
af9d75dfcf Fix static files again 2026-01-23 21:31:34 -08:00
shamoon
7b23cdc0c1 Opacify complete steps 2026-01-23 15:44:07 -08:00
shamoon
09892809f9 Tweak instructions 2026-01-23 15:37:53 -08:00
shamoon
94c6108006 Nice, upload button 2026-01-23 15:29:19 -08:00
shamoon
33c5d5bab0 Update migration_home.html
[ci skip]
2026-01-23 08:54:00 -08:00
shamoon
9beb508f1d Auto-step after transform
[ci skip]
2026-01-23 08:40:37 -08:00
shamoon
a290fcfe6f Sick, run transform as subprocess 2026-01-23 08:39:57 -08:00
shamoon
0846fe9845 Script deps 2026-01-23 08:33:12 -08:00
shamoon
910d16374b Stumpylog's current version of the transform script
[ci skip]

Co-Authored-By: Trenton H <797416+stumpylog@users.noreply.github.com>
2026-01-23 08:22:34 -08:00
shamoon
35d77b144d Small startup detection thing 2026-01-23 08:11:34 -08:00
shamoon
5987e35101 Dummy console thing
[ci skip]
2026-01-22 23:28:26 -08:00
shamoon
96259ce441 Export instructions 2026-01-22 23:27:30 -08:00
shamoon
283afb265d Update settings.py
[ci skip]
2026-01-22 23:12:47 -08:00
shamoon
67564dd573 more light mode shit 2026-01-22 23:12:47 -08:00
shamoon
046d65c2ba Just light mode
[ci skip]
2026-01-22 22:59:27 -08:00
shamoon
8761816635 Update urls.py 2026-01-22 22:55:30 -08:00
shamoon
a1cdc45f1a one-time code 2026-01-22 22:39:11 -08:00
shamoon
190e42e722 Oh nice, reuse existing 2026-01-22 22:14:09 -08:00
shamoon
75c6ffe01f fix export dir
[ci skip]
2026-01-22 22:09:59 -08:00
shamoon
2964b4b256 Update migration_home.html
[ci skip]
2026-01-22 22:07:12 -08:00
shamoon
f52f9dd325 Basic login styling 2026-01-22 21:59:13 -08:00
shamoon
5827a0ec25 Disable unusable buttons 2026-01-22 21:59:12 -08:00
shamoon
990ef05d99 Some prettiness 2026-01-22 21:59:12 -08:00
shamoon
9f48b8e6e1 Some styling 2026-01-22 21:40:08 -08:00
shamoon
42689070b3 Still support conf 2026-01-22 21:40:08 -08:00
shamoon
09f3cfdb93 Start in migrator 2026-01-22 21:40:07 -08:00
shamoon
84f408fa43 save this, it does work 2026-01-22 21:40:07 -08:00
297 changed files with 9012 additions and 30947 deletions

View File

@@ -64,6 +64,8 @@ ARG RUNTIME_PACKAGES="\
libmagic1 \
media-types \
zlib1g \
# Barcode splitter
libzbar0 \
poppler-utils \
htop \
sudo"

View File

@@ -91,12 +91,12 @@ Additional tasks are available for common maintenance operations:
## Committing from the Host Machine
The DevContainer automatically installs Git pre-commit hooks during setup. However, these hooks are configured for use inside the container.
The DevContainer automatically installs pre-commit hooks during setup. However, these hooks are configured for use inside the container.
If you want to commit changes from your host machine (outside the DevContainer), you need to set up prek on your host. This installs it as a standalone tool.
If you want to commit changes from your host machine (outside the DevContainer), you need to set up pre-commit on your host. This installs it as a standalone tool.
```bash
uv tool install prek && prek install
uv tool install pre-commit && pre-commit install
```
After this, you can commit either from inside the DevContainer or from your host machine.

View File

@@ -3,11 +3,10 @@
"dockerComposeFile": "docker-compose.devcontainer.sqlite-tika.yml",
"service": "paperless-development",
"workspaceFolder": "/usr/src/paperless/paperless-ngx",
"forwardPorts": [4200, 8000],
"containerEnv": {
"UV_CACHE_DIR": "/usr/src/paperless/paperless-ngx/.uv-cache"
},
"postCreateCommand": "/bin/bash -c 'rm -rf .venv/.* && uv sync --group dev && uv run prek install'",
"postCreateCommand": "/bin/bash -c 'rm -rf .venv/.* && uv sync --group dev && uv run pre-commit install'",
"customizations": {
"vscode": {
"extensions": [

View File

@@ -33,7 +33,7 @@
"label": "Start: Frontend Angular",
"description": "Start the Frontend Angular Dev Server",
"type": "shell",
"command": "pnpm exec ng serve --host 0.0.0.0",
"command": "pnpm start",
"isBackground": true,
"options": {
"cwd": "${workspaceFolder}/src-ui"
@@ -116,9 +116,9 @@
},
{
"label": "Maintenance: Build Documentation",
"description": "Build the documentation with Zensical",
"description": "Build the documentation with MkDocs",
"type": "shell",
"command": "uv run zensical build && uv run zensical serve",
"command": "uv run mkdocs build --config-file mkdocs.yml && uv run mkdocs serve",
"group": "none",
"presentation": {
"echo": true,

View File

@@ -28,4 +28,3 @@
./resources
# Other stuff
**/*.drawio.png
.mypy_baseline

View File

@@ -37,6 +37,6 @@ NOTE: PRs that do not address the following will not be merged, please do not sk
- [ ] If applicable, I have included testing coverage for new code in this PR, for [backend](https://docs.paperless-ngx.com/development/#testing) and / or [front-end](https://docs.paperless-ngx.com/development/#testing-and-code-style) changes.
- [ ] If applicable, I have tested my code for breaking changes & regressions on both mobile & desktop devices, using the latest version of major browsers.
- [ ] If applicable, I have checked that all tests pass, see [documentation](https://docs.paperless-ngx.com/development/#back-end-development).
- [ ] I have run all Git `pre-commit` hooks, see [documentation](https://docs.paperless-ngx.com/development/#code-formatting-with-pre-commit-hooks).
- [ ] I have run all `pre-commit` hooks, see [documentation](https://docs.paperless-ngx.com/development/#code-formatting-with-pre-commit-hooks).
- [ ] I have made corresponding changes to the documentation as needed.
- [ ] In the description of the PR above I have disclosed the use of AI tools in the coding of this PR.

View File

@@ -46,8 +46,8 @@ updates:
patterns:
- "*pytest*"
- "ruff"
- "zensical"
- "prek*"
- "mkdocs-material"
- "pre-commit*"
# Django & DRF Ecosystem
django-ecosystem:
patterns:
@@ -69,6 +69,7 @@ updates:
patterns:
- "ocrmypdf"
- "pdf2image"
- "pyzbar"
- "zxing-cpp"
- "tika-client"
- "gotenberg-client"

View File

@@ -22,16 +22,13 @@ on:
concurrency:
group: backend-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions: {}
env:
DEFAULT_UV_VERSION: "0.10.x"
DEFAULT_UV_VERSION: "0.9.x"
NLTK_DATA: "/usr/share/nltk_data"
jobs:
test:
name: "Python ${{ matrix.python-version }}"
runs-on: ubuntu-24.04
permissions:
contents: read
strategy:
matrix:
python-version: ['3.10', '3.11', '3.12']
@@ -58,7 +55,7 @@ jobs:
run: |
sudo apt-get update -qq
sudo apt-get install -qq --no-install-recommends \
unpaper tesseract-ocr imagemagick ghostscript poppler-utils
unpaper tesseract-ocr imagemagick ghostscript libzbar0 poppler-utils
- name: Configure ImageMagick
run: |
sudo cp docker/rootfs/etc/ImageMagick-6/paperless-policy.xml /etc/ImageMagick-6/policy.xml
@@ -102,54 +99,3 @@ jobs:
run: |
docker compose --file docker/compose/docker-compose.ci-test.yml logs
docker compose --file docker/compose/docker-compose.ci-test.yml down
typing:
name: Check project typing
runs-on: ubuntu-24.04
permissions:
contents: read
env:
DEFAULT_PYTHON: "3.12"
steps:
- name: Checkout
uses: actions/checkout@v6.0.1
- name: Set up Python
id: setup-python
uses: actions/setup-python@v6.2.0
with:
python-version: "${{ env.DEFAULT_PYTHON }}"
- name: Install uv
uses: astral-sh/setup-uv@v7.2.1
with:
version: ${{ env.DEFAULT_UV_VERSION }}
enable-cache: true
python-version: ${{ steps.setup-python.outputs.python-version }}
- name: Install Python dependencies
run: |
uv sync \
--python ${{ steps.setup-python.outputs.python-version }} \
--group testing \
--group typing \
--frozen
- name: List installed Python dependencies
run: |
uv pip list
- name: Check typing (pyrefly)
run: |
uv run pyrefly \
check \
src/
- name: Cache Mypy
uses: actions/cache@v5.0.3
with:
path: .mypy_cache
# Keyed by OS, Python version, and dependency hashes
key: ${{ runner.os }}-mypy-py${{ env.DEFAULT_PYTHON }}-${{ hashFiles('pyproject.toml', 'uv.lock') }}
restore-keys: |
${{ runner.os }}-mypy-py${{ env.DEFAULT_PYTHON }}-
${{ runner.os }}-mypy-
- name: Check typing (mypy)
run: |
uv run mypy \
--show-error-codes \
--warn-unused-configs \
src/ | uv run mypy-baseline filter

View File

@@ -15,7 +15,6 @@ on:
concurrency:
group: docker-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions: {}
env:
REGISTRY: ghcr.io
jobs:
@@ -107,7 +106,7 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.12.0
- name: Login to GitHub Container Registry
uses: docker/login-action@v3.7.0
uses: docker/login-action@v3.6.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -181,20 +180,20 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.12.0
- name: Login to GitHub Container Registry
uses: docker/login-action@v3.7.0
uses: docker/login-action@v3.6.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to Docker Hub
if: needs.build-arch.outputs.push-external == 'true'
uses: docker/login-action@v3.7.0
uses: docker/login-action@v3.6.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to Quay.io
if: needs.build-arch.outputs.push-external == 'true'
uses: docker/login-action@v3.7.0
uses: docker/login-action@v3.6.0
with:
registry: quay.io
username: ${{ secrets.QUAY_USERNAME }}

View File

@@ -6,33 +6,25 @@ on:
- dev
paths:
- 'docs/**'
- 'zensical.toml'
- 'pyproject.toml'
- 'uv.lock'
- 'mkdocs.yml'
- '.github/workflows/ci-docs.yml'
pull_request:
paths:
- 'docs/**'
- 'zensical.toml'
- 'pyproject.toml'
- 'uv.lock'
- 'mkdocs.yml'
- '.github/workflows/ci-docs.yml'
workflow_dispatch:
concurrency:
group: docs-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions: {}
env:
DEFAULT_UV_VERSION: "0.10.x"
DEFAULT_PYTHON_VERSION: "3.12"
DEFAULT_UV_VERSION: "0.9.x"
DEFAULT_PYTHON_VERSION: "3.11"
jobs:
build:
name: Build Documentation
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- uses: actions/configure-pages@v5
- name: Checkout
uses: actions/checkout@v6
- name: Set up Python
@@ -55,27 +47,42 @@ jobs:
--python ${{ steps.setup-python.outputs.python-version }} \
--dev \
--frozen \
zensical build --clean
- name: Upload GitHub Pages artifact
uses: actions/upload-pages-artifact@v4
mkdocs build --config-file ./mkdocs.yml
- name: Upload artifact
uses: actions/upload-artifact@v6
with:
path: site
name: github-pages-${{ github.run_id }}-${{ github.run_attempt }}
name: documentation
path: site/
retention-days: 7
deploy:
name: Deploy Documentation
needs: build
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
permissions:
contents: read
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy GitHub Pages
uses: actions/deploy-pages@v4
id: deployment
- name: Checkout
uses: actions/checkout@v6
- name: Set up Python
id: setup-python
uses: actions/setup-python@v6
with:
artifact_name: github-pages-${{ github.run_id }}-${{ github.run_attempt }}
python-version: ${{ env.DEFAULT_PYTHON_VERSION }}
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
version: ${{ env.DEFAULT_UV_VERSION }}
enable-cache: true
python-version: ${{ env.DEFAULT_PYTHON_VERSION }}
- name: Install Python dependencies
run: |
uv sync --python ${{ steps.setup-python.outputs.python-version }} --dev --frozen
- name: Deploy documentation
run: |
echo "docs.paperless-ngx.com" > "${{ github.workspace }}/docs/CNAME"
git config --global user.name "${{ github.actor }}"
git config --global user.email "${{ github.actor }}@users.noreply.github.com"
uv run \
--python ${{ steps.setup-python.outputs.python-version }} \
--dev \
--frozen \
mkdocs gh-deploy --force --no-history

View File

@@ -16,13 +16,10 @@ on:
concurrency:
group: frontend-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions: {}
jobs:
install-dependencies:
name: Install Dependencies
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -50,8 +47,6 @@ jobs:
name: Lint
needs: install-dependencies
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -80,8 +75,6 @@ jobs:
name: "Unit Tests (${{ matrix.shard-index }}/${{ matrix.shard-count }})"
needs: install-dependencies
runs-on: ubuntu-24.04
permissions:
contents: read
strategy:
fail-fast: false
matrix:
@@ -128,9 +121,7 @@ jobs:
name: "E2E Tests (${{ matrix.shard-index }}/${{ matrix.shard-count }})"
needs: install-dependencies
runs-on: ubuntu-24.04
permissions:
contents: read
container: mcr.microsoft.com/playwright:v1.58.2-noble
container: mcr.microsoft.com/playwright:v1.57.0-noble
env:
PLAYWRIGHT_BROWSERS_PATH: /ms-playwright
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
@@ -170,8 +161,6 @@ jobs:
name: Bundle Analysis
needs: [unit-tests, e2e-tests]
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v6

View File

@@ -9,19 +9,16 @@ on:
concurrency:
group: lint-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions: {}
jobs:
lint:
name: Linting via prek
runs-on: ubuntu-slim
permissions:
contents: read
pre-commit:
name: Pre-commit Checks
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6.0.2
uses: actions/checkout@v6
- name: Install Python
uses: actions/setup-python@v6.2.0
uses: actions/setup-python@v6
with:
python-version: "3.14"
- name: Run prek
uses: j178/prek-action@v1.1.1
python-version: "3.11"
- name: Run pre-commit
uses: pre-commit/action@v3.0.1

View File

@@ -7,21 +7,16 @@ on:
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
permissions: {}
env:
DEFAULT_UV_VERSION: "0.10.x"
DEFAULT_PYTHON_VERSION: "3.12"
DEFAULT_UV_VERSION: "0.9.x"
DEFAULT_PYTHON_VERSION: "3.11"
jobs:
wait-for-docker:
name: Wait for Docker Build
runs-on: ubuntu-24.04
permissions:
# lewagon/wait-on-check-action reads workflow check runs
actions: read
contents: read
steps:
- name: Wait for Docker build
uses: lewagon/wait-on-check-action@v1.5.0
uses: lewagon/wait-on-check-action@v1.4.1
with:
ref: ${{ github.sha }}
check-name: 'Build Docker Image'
@@ -31,8 +26,6 @@ jobs:
name: Build Release
needs: wait-for-docker
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -77,7 +70,7 @@ jobs:
--python ${{ steps.setup-python.outputs.python-version }} \
--dev \
--frozen \
zensical build --clean
mkdocs build --config-file ./mkdocs.yml
# ---- Prepare Release ----
- name: Generate requirements file
run: |
@@ -134,10 +127,6 @@ jobs:
name: Publish Release
needs: build-release
runs-on: ubuntu-24.04
permissions:
# release-drafter reads PRs to build the changelog and creates/publishes the release
contents: write
pull-requests: read
outputs:
prerelease: ${{ steps.get-version.outputs.prerelease }}
changelog: ${{ steps.create-release.outputs.body }}
@@ -166,7 +155,6 @@ jobs:
version: ${{ steps.get-version.outputs.version }}
prerelease: ${{ steps.get-version.outputs.prerelease }}
publish: true
commitish: main
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload release archive
@@ -185,11 +173,6 @@ jobs:
needs: publish-release
if: needs.publish-release.outputs.prerelease == 'false'
runs-on: ubuntu-24.04
permissions:
# git push of the changelog branch requires contents: write
# github.rest.pulls.create() and github.rest.issues.addLabels() require pull-requests: write
contents: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -227,7 +210,7 @@ jobs:
uv run \
--python ${{ steps.setup-python.outputs.python-version }} \
--dev \
prek run --files changelog.md || true
pre-commit run --files changelog.md || true
git config --global user.name "github-actions"
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"

View File

@@ -12,7 +12,6 @@ on:
concurrency:
group: registry-tags-cleanup
cancel-in-progress: false
permissions: {}
jobs:
cleanup-images:
name: Cleanup Image Tags for ${{ matrix.primary-name }}

View File

@@ -18,7 +18,6 @@ on:
branches: [dev]
schedule:
- cron: '28 13 * * 5'
permissions: {}
jobs:
analyze:
name: Analyze

View File

@@ -6,16 +6,11 @@ on:
push:
paths: ['src/locale/**', 'src-ui/messages.xlf', 'src-ui/src/locale/**']
branches: [dev]
permissions: {}
jobs:
synchronize-with-crowdin:
name: Crowdin Sync
if: github.repository_owner == 'paperless-ngx'
runs-on: ubuntu-24.04
permissions:
# Crowdin action pushes translation branches and creates/updates PRs via GITHUB_TOKEN
contents: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v6

View File

@@ -2,15 +2,13 @@ name: PR Bot
on:
pull_request_target:
types: [opened]
permissions: {}
permissions:
contents: read
pull-requests: write
jobs:
pr-bot:
name: Automated PR Bot
runs-on: ubuntu-latest
permissions:
# labeler reads file paths; all steps add labels or post comments on PRs
contents: read
pull-requests: write
steps:
- name: Label PR by file path or branch name
# see .github/labeler.yml for the labeler config

View File

@@ -7,14 +7,13 @@ on:
branches:
- main
- dev
permissions: {}
permissions:
contents: read
jobs:
pr_opened_or_reopened:
name: pr_opened_or_reopened
runs-on: ubuntu-24.04
permissions:
# release-drafter reads its config file from the repo
contents: read
# write permission is required for autolabeler
pull-requests: write
if: github.event_name == 'pull_request_target' && (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.pull_request.user.login != 'dependabot'

View File

@@ -3,7 +3,10 @@ on:
schedule:
- cron: '0 3 * * *'
workflow_dispatch:
permissions: {}
permissions:
issues: write
pull-requests: write
discussions: write
concurrency:
group: lock
jobs:
@@ -11,9 +14,6 @@ jobs:
name: 'Stale'
if: github.repository_owner == 'paperless-ngx'
runs-on: ubuntu-24.04
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v10
with:
@@ -36,10 +36,6 @@ jobs:
name: 'Lock Old Threads'
if: github.repository_owner == 'paperless-ngx'
runs-on: ubuntu-24.04
permissions:
issues: write
pull-requests: write
discussions: write
steps:
- uses: dessant/lock-threads@v6
with:
@@ -60,8 +56,6 @@ jobs:
name: 'Close Answered Discussions'
if: github.repository_owner == 'paperless-ngx'
runs-on: ubuntu-24.04
permissions:
discussions: write
steps:
- uses: actions/github-script@v8
with:
@@ -119,8 +113,6 @@ jobs:
name: 'Close Outdated Discussions'
if: github.repository_owner == 'paperless-ngx'
runs-on: ubuntu-24.04
permissions:
discussions: write
steps:
- uses: actions/github-script@v8
with:
@@ -213,8 +205,6 @@ jobs:
name: 'Close Unsupported Feature Requests'
if: github.repository_owner == 'paperless-ngx'
runs-on: ubuntu-24.04
permissions:
discussions: write
steps:
- uses: actions/github-script@v8
with:

View File

@@ -3,7 +3,6 @@ on:
push:
branches:
- dev
permissions: {}
jobs:
generate-translate-strings:
name: Generate Translation Strings

2
.gitignore vendored
View File

@@ -54,7 +54,7 @@ junit.xml
# Django stuff:
*.log
# Zensical documentation
# MkDocs documentation
site/
# PyBuilder

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,6 @@
# This file configures pre-commit hooks.
# See https://pre-commit.com/ for general information
# See https://pre-commit.com/hooks.html for a listing of possible hooks
# We actually run via https://github.com/j178/prek which is compatible
repos:
# General hooks
- repo: https://github.com/pre-commit/pre-commit-hooks
@@ -50,12 +49,12 @@ repos:
- 'prettier-plugin-organize-imports@4.1.0'
# Python hooks
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.0
rev: v0.14.14
hooks:
- id: ruff-check
- id: ruff-format
- repo: https://github.com/tox-dev/pyproject-fmt
rev: "v2.12.1"
rev: "v2.11.1"
hooks:
- id: pyproject-fmt
# Dockerfile hooks

File diff suppressed because one or more lines are too long

View File

@@ -30,7 +30,7 @@ RUN set -eux \
# Purpose: Installs s6-overlay and rootfs
# Comments:
# - Don't leave anything extra in here either
FROM ghcr.io/astral-sh/uv:0.10.0-python3.12-trixie-slim AS s6-overlay-base
FROM ghcr.io/astral-sh/uv:0.9.26-python3.12-trixie-slim AS s6-overlay-base
WORKDIR /usr/src/s6
@@ -154,6 +154,8 @@ ARG RUNTIME_PACKAGES="\
libmagic1 \
media-types \
zlib1g \
# Barcode splitter
libzbar0 \
poppler-utils"
# Install basic runtime packages.

View File

@@ -4,7 +4,7 @@
# correct networking for the tests
services:
gotenberg:
image: docker.io/gotenberg/gotenberg:8.26
image: docker.io/gotenberg/gotenberg:8.25
hostname: gotenberg
container_name: gotenberg
network_mode: host
@@ -35,7 +35,7 @@ services:
- "3143:3143" # IMAP
restart: unless-stopped
nginx:
image: docker.io/nginx:1.29.5-alpine
image: docker.io/nginx:1.29-alpine
hostname: nginx
container_name: nginx
ports:

View File

@@ -72,7 +72,7 @@ services:
PAPERLESS_TIKA_GOTENBERG_ENDPOINT: http://gotenberg:3000
PAPERLESS_TIKA_ENDPOINT: http://tika:9998
gotenberg:
image: docker.io/gotenberg/gotenberg:8.26
image: docker.io/gotenberg/gotenberg:8.25
restart: unless-stopped
# The gotenberg chromium route is used to convert .eml files. We do not
# want to allow external content like tracking pixels or even javascript.

View File

@@ -66,7 +66,7 @@ services:
PAPERLESS_TIKA_GOTENBERG_ENDPOINT: http://gotenberg:3000
PAPERLESS_TIKA_ENDPOINT: http://tika:9998
gotenberg:
image: docker.io/gotenberg/gotenberg:8.26
image: docker.io/gotenberg/gotenberg:8.25
restart: unless-stopped
# The gotenberg chromium route is used to convert .eml files. We do not
# want to allow external content like tracking pixels or even javascript.

View File

@@ -55,7 +55,7 @@ services:
PAPERLESS_TIKA_GOTENBERG_ENDPOINT: http://gotenberg:3000
PAPERLESS_TIKA_ENDPOINT: http://tika:9998
gotenberg:
image: docker.io/gotenberg/gotenberg:8.26
image: docker.io/gotenberg/gotenberg:8.25
restart: unless-stopped
# The gotenberg chromium route is used to convert .eml files. We do not
# want to allow external content like tracking pixels or even javascript.

View File

@@ -7,11 +7,6 @@ cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py management_command "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py management_command "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py management_command "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py management_command "$@"
fi

View File

@@ -8,6 +8,11 @@ echo "${log_prefix} Apply database migrations..."
cd "${PAPERLESS_SRC_DIR}"
if [[ "${PAPERLESS_MIGRATION_MODE:-0}" == "1" ]]; then
echo "${log_prefix} Migration mode enabled, skipping migrations."
exit 0
fi
# The whole migrate, with flock, needs to run as the right user
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
exec s6-setlock -n "${data_dir}/migration_lock" python3 manage.py migrate --skip-checks --no-input

View File

@@ -9,7 +9,15 @@ echo "${log_prefix} Running Django checks"
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py check
if [[ "${PAPERLESS_MIGRATION_MODE:-0}" == "1" ]]; then
python3 manage_migration.py check
else
python3 manage.py check
fi
else
s6-setuidgid paperless python3 manage.py check
if [[ "${PAPERLESS_MIGRATION_MODE:-0}" == "1" ]]; then
s6-setuidgid paperless python3 manage_migration.py check
else
s6-setuidgid paperless python3 manage.py check
fi
fi

View File

@@ -13,8 +13,14 @@ if [[ -n "${PAPERLESS_FORCE_SCRIPT_NAME}" ]]; then
export GRANIAN_URL_PATH_PREFIX=${PAPERLESS_FORCE_SCRIPT_NAME}
fi
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
exec granian --interface asginl --ws --loop uvloop "paperless.asgi:application"
if [[ "${PAPERLESS_MIGRATION_MODE:-0}" == "1" ]]; then
app_module="paperless.migration_asgi:application"
else
exec s6-setuidgid paperless granian --interface asginl --ws --loop uvloop "paperless.asgi:application"
app_module="paperless.asgi:application"
fi
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
exec granian --interface asginl --ws --loop uvloop "${app_module}"
else
exec s6-setuidgid paperless granian --interface asginl --ws --loop uvloop "${app_module}"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py convert_mariadb_uuid "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py convert_mariadb_uuid "$@"
python3 manage.py convert_mariadb_uuid "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py convert_mariadb_uuid "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py convert_mariadb_uuid "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py createsuperuser "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py createsuperuser "$@"
python3 manage.py createsuperuser "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py createsuperuser "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py createsuperuser "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_archiver "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_archiver "$@"
python3 manage.py document_archiver "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_archiver "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_archiver "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_create_classifier "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_create_classifier "$@"
python3 manage.py document_create_classifier "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_create_classifier "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_create_classifier "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_exporter "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_exporter "$@"
python3 manage.py document_exporter "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_exporter "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_exporter "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_fuzzy_match "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_fuzzy_match "$@"
python3 manage.py document_fuzzy_match "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_fuzzy_match "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_fuzzy_match "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_importer "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_importer "$@"
python3 manage.py document_importer "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_importer "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_importer "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_index "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_index "$@"
python3 manage.py document_index "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_index "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_index "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_renamer "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_renamer "$@"
python3 manage.py document_renamer "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_renamer "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_renamer "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_retagger "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_retagger "$@"
python3 manage.py document_retagger "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_retagger "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_retagger "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_sanity_checker "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_sanity_checker "$@"
python3 manage.py document_sanity_checker "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_sanity_checker "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_sanity_checker "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py document_thumbnails "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py document_thumbnails "$@"
python3 manage.py document_thumbnails "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py document_thumbnails "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py document_thumbnails "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py mail_fetcher "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py mail_fetcher "$@"
python3 manage.py mail_fetcher "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py mail_fetcher "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py mail_fetcher "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py manage_superuser "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py manage_superuser "$@"
python3 manage.py manage_superuser "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py manage_superuser "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py manage_superuser "$@"
fi

View File

@@ -6,12 +6,7 @@ set -e
cd "${PAPERLESS_SRC_DIR}"
if [[ -n "${USER_IS_NON_ROOT}" ]]; then
python3 manage.py prune_audit_logs "$@"
elif [[ $(id -u) == 0 ]]; then
s6-setuidgid paperless python3 manage.py prune_audit_logs "$@"
python3 manage.py prune_audit_logs "$@"
elif [[ $(id -un) == "paperless" ]]; then
python3 manage.py prune_audit_logs "$@"
else
echo "Unknown user."
exit 1
s6-setuidgid paperless python3 manage.py prune_audit_logs "$@"
fi

View File

@@ -774,6 +774,7 @@ At this time, the library utilized for detection of barcodes supports the follow
- QR Code
- SQ Code
You may check for updates on the [zbar library homepage](https://github.com/mchehab/zbar).
For usage in Paperless, the type of barcode does not matter, only the contents of it.
For how to enable barcode usage, see [the configuration](configuration.md#barcodes).
@@ -804,27 +805,6 @@ See the relevant settings [`PAPERLESS_CONSUMER_ENABLE_TAG_BARCODE`](configuratio
and [`PAPERLESS_CONSUMER_TAG_BARCODE_MAPPING`](configuration.md#PAPERLESS_CONSUMER_TAG_BARCODE_MAPPING)
for more information.
#### Splitting on Tag Barcodes
By default, tag barcodes only assign tags to documents without splitting them. However,
you can enable document splitting on tag barcodes by setting
[`PAPERLESS_CONSUMER_TAG_BARCODE_SPLIT`](configuration.md#PAPERLESS_CONSUMER_TAG_BARCODE_SPLIT)
to `true`.
When enabled, documents will be split at pages containing tag barcodes, similar to how
ASN barcodes work. Key features:
- The page with the tag barcode is **retained** in the resulting document
- **Each split document extracts its own tags** - only tags on pages within that document are assigned
- Multiple tag barcodes can trigger multiple splits in the same document
- Works seamlessly with ASN barcodes - each split document gets its own ASN and tags
This is useful for batch scanning where you place tag barcode pages between different
documents to both separate and categorize them in a single operation.
**Example:** A 6-page scan with TAG:invoice on page 3 and TAG:receipt on page 5 will create
three documents: pages 1-2 (no tags), pages 3-4 (tagged "invoice"), and pages 5-6 (tagged "receipt").
## Automatic collation of double-sided documents {#collate}
!!! note

View File

@@ -1,4 +1,4 @@
# REST API
# The REST API
Paperless-ngx now ships with a fully-documented REST API and a browsable
web interface to explore it. The API browsable interface is available at

View File

@@ -1,31 +1,13 @@
:root>* {
--paperless-green: #17541f;
--paperless-green-accent: #2b8a38;
--md-primary-fg-color: var(--paperless-green);
--md-primary-fg-color--dark: var(--paperless-green);
--md-primary-fg-color--light: var(--paperless-green-accent);
--md-accent-fg-color: var(--paperless-green-accent);
:root > * {
--md-primary-fg-color: #17541f;
--md-primary-fg-color--dark: #17541f;
--md-primary-fg-color--light: #17541f;
--md-accent-fg-color: #2b8a38;
--md-typeset-a-color: #21652a;
}
.md-header,
.md-tabs {
background-color: var(--paperless-green);
color: #fff;
}
.md-tabs__link {
color: rgba(255, 255, 255, 0.82);
}
.md-tabs__link:hover,
.md-tabs__link--active {
color: #fff;
}
[data-md-color-scheme="slate"] {
--md-hue: 222;
--md-default-bg-color: hsla(var(--md-hue), 15%, 10%, 1);
}
@media (min-width: 768px) {
@@ -87,8 +69,8 @@ h4 code {
}
/* Hide config vars from sidebar, toc and move the border on mobile case their hidden */
.md-nav.md-nav--secondary .md-nav__item:has(> .md-nav__link[href*="PAPERLESS_"]),
.md-nav.md-nav--secondary .md-nav__item:has(> .md-nav__link[href*="USERMAP_"]) {
.md-nav.md-nav--secondary .md-nav__item .md-nav__link[href*="PAPERLESS_"],
.md-nav.md-nav--secondary .md-nav__item .md-nav__link[href*="USERMAP_"] {
display: none;
}
@@ -101,3 +83,18 @@ h4 code {
border-top: .05rem solid var(--md-default-fg-color--lightest);
}
}
/* Show search shortcut key */
[data-md-toggle="search"]:not(:checked) ~ .md-header .md-search__form::after {
position: absolute;
top: .3rem;
right: .3rem;
display: block;
padding: .1rem .4rem;
color: var(--md-default-fg-color--lighter);
font-weight: bold;
font-size: .8rem;
border: .05rem solid var(--md-default-fg-color--lighter);
border-radius: .1rem;
content: "/";
}

View File

@@ -1,24 +1,5 @@
# Changelog
## paperless-ngx 2.20.6
### Bug Fixes
- Fix: extract all ids for nested tags [@shamoon](https://github.com/shamoon) ([#11888](https://github.com/paperless-ngx/paperless-ngx/pull/11888))
- Fixhancement: change date calculation for 'this year' to include future documents [@shamoon](https://github.com/shamoon) ([#11884](https://github.com/paperless-ngx/paperless-ngx/pull/11884))
- Fix: Running management scripts under rootless could fail [@stumpylog](https://github.com/stumpylog) ([#11870](https://github.com/paperless-ngx/paperless-ngx/pull/11870))
- Fix: use correct field id for overrides [@shamoon](https://github.com/shamoon) ([#11869](https://github.com/paperless-ngx/paperless-ngx/pull/11869))
### All App Changes
<details>
<summary>3 changes</summary>
- Fix: extract all ids for nested tags [@shamoon](https://github.com/shamoon) ([#11888](https://github.com/paperless-ngx/paperless-ngx/pull/11888))
- Fixhancement: change date calculation for 'this year' to include future documents [@shamoon](https://github.com/shamoon) ([#11884](https://github.com/paperless-ngx/paperless-ngx/pull/11884))
- Fix: use correct field id for overrides [@shamoon](https://github.com/shamoon) ([#11869](https://github.com/paperless-ngx/paperless-ngx/pull/11869))
</details>
## paperless-ngx 2.20.5
### Bug Fixes

View File

@@ -1222,6 +1222,14 @@ using Python's `re.match()`, which anchors at the start of the filename.
The default ignores are `[.stfolder, .stversions, .localized, @eaDir, .Spotlight-V100, .Trashes, __MACOSX]` and cannot be overridden.
#### [`PAPERLESS_CONSUMER_BARCODE_SCANNER=<string>`](#PAPERLESS_CONSUMER_BARCODE_SCANNER) {#PAPERLESS_CONSUMER_BARCODE_SCANNER}
: Sets the barcode scanner used for barcode functionality.
Currently, "PYZBAR" (the default) or "ZXING" might be selected.
If you have problems that your Barcodes/QR-Codes are not detected
(especially with bad scan quality and/or small codes), try the other one.
#### [`PAPERLESS_PRE_CONSUME_SCRIPT=<filename>`](#PAPERLESS_PRE_CONSUME_SCRIPT) {#PAPERLESS_PRE_CONSUME_SCRIPT}
: After some initial validation, Paperless can trigger an arbitrary
@@ -1549,20 +1557,6 @@ assigns or creates tags if a properly formatted barcode is detected.
Please refer to the Python regex documentation for more information.
#### [`PAPERLESS_CONSUMER_TAG_BARCODE_SPLIT=<bool>`](#PAPERLESS_CONSUMER_TAG_BARCODE_SPLIT) {#PAPERLESS_CONSUMER_TAG_BARCODE_SPLIT}
: Enables splitting of documents on tag barcodes, similar to how ASN barcodes work.
When enabled, documents will be split into separate PDFs at pages containing
tag barcodes that match the configured `PAPERLESS_CONSUMER_TAG_BARCODE_MAPPING`
patterns. The page with the tag barcode will be retained in the new document.
Each split document will have the detected tags assigned to it.
This only has an effect if `PAPERLESS_CONSUMER_ENABLE_TAG_BARCODE` is also enabled.
Defaults to false.
## Audit Trail
#### [`PAPERLESS_AUDIT_LOG_ENABLED=<bool>`](#PAPERLESS_AUDIT_LOG_ENABLED) {#PAPERLESS_AUDIT_LOG_ENABLED}

View File

@@ -81,7 +81,7 @@ first-time setup.
5. Install pre-commit hooks:
```bash
$ uv run prek install
$ uv run pre-commit install
```
6. Apply migrations and create a superuser (also can be done via the web UI) for your development instance:
@@ -217,7 +217,7 @@ commit. See [above](#code-formatting-with-pre-commit-hooks) for installation ins
command such as
```bash
$ git ls-files -- '*.ts' | xargs prek run prettier --files
$ git ls-files -- '*.ts' | xargs pre-commit run prettier --files
```
Front end testing uses Jest and Playwright. Unit tests and e2e tests,
@@ -338,13 +338,13 @@ LANGUAGES = [
## Building the documentation
The documentation is built using Zensical, see their [documentation](https://zensical.org/docs/).
The documentation is built using material-mkdocs, see their [documentation](https://squidfunk.github.io/mkdocs-material/reference/).
If you want to build the documentation locally, this is how you do it:
1. Build the documentation
```bash
$ uv run zensical build
$ uv run mkdocs build --config-file mkdocs.yml
```
_alternatively..._
@@ -355,7 +355,7 @@ If you want to build the documentation locally, this is how you do it:
something.
```bash
$ uv run zensical serve
$ uv run mkdocs serve
```
## Building the Docker image
@@ -481,147 +481,3 @@ To get started:
5. The project is ready for debugging, start either run the fullstack debug or individual debug
processes. Yo spin up the project without debugging run the task **Project Start: Run all Services**
## Developing Date Parser Plugins
Paperless-ngx uses a plugin system for date parsing, allowing you to extend or replace the default date parsing behavior. Plugins are discovered using [Python entry points](https://setuptools.pypa.io/en/latest/userguide/entry_point.html).
### Creating a Date Parser Plugin
To create a custom date parser plugin, you need to:
1. Create a class that inherits from `DateParserPluginBase`
2. Implement the required abstract method
3. Register your plugin via an entry point
#### 1. Implementing the Parser Class
Your parser must extend `documents.plugins.date_parsing.DateParserPluginBase` and implement the `parse` method:
```python
from collections.abc import Iterator
import datetime
from documents.plugins.date_parsing import DateParserPluginBase
class MyDateParserPlugin(DateParserPluginBase):
"""
Custom date parser implementation.
"""
def parse(self, filename: str, content: str) -> Iterator[datetime.datetime]:
"""
Parse dates from the document's filename and content.
Args:
filename: The original filename of the document
content: The extracted text content of the document
Yields:
datetime.datetime: Valid datetime objects found in the document
"""
# Your parsing logic here
# Use self.config to access configuration settings
# Example: parse dates from filename first
if self.config.filename_date_order:
# Your filename parsing logic
yield some_datetime
# Then parse dates from content
# Your content parsing logic
yield another_datetime
```
#### 2. Configuration and Helper Methods
Your parser instance is initialized with a `DateParserConfig` object accessible via `self.config`. This provides:
- `languages: list[str]` - List of language codes for date parsing
- `timezone_str: str` - Timezone string for date localization
- `ignore_dates: set[datetime.date]` - Dates that should be filtered out
- `reference_time: datetime.datetime` - Current time for filtering future dates
- `filename_date_order: str | None` - Date order preference for filenames (e.g., "DMY", "MDY")
- `content_date_order: str` - Date order preference for content
The base class provides two helper methods you can use:
```python
def _parse_string(
self,
date_string: str,
date_order: str,
) -> datetime.datetime | None:
"""
Parse a single date string using dateparser with configured settings.
"""
def _filter_date(
self,
date: datetime.datetime | None,
) -> datetime.datetime | None:
"""
Validate a parsed datetime against configured rules.
Filters out dates before 1900, future dates, and ignored dates.
"""
```
#### 3. Resource Management (Optional)
If your plugin needs to acquire or release resources (database connections, API clients, etc.), override the context manager methods. Paperless-ngx will always use plugins as context managers, ensuring resources can be released even in the event of errors.
#### 4. Registering Your Plugin
Register your plugin using a setuptools entry point in your package's `pyproject.toml`:
```toml
[project.entry-points."paperless_ngx.date_parsers"]
my_parser = "my_package.parsers:MyDateParserPlugin"
```
The entry point name (e.g., `"my_parser"`) is used for sorting when multiple plugins are found. Paperless-ngx will use the first plugin alphabetically by name if multiple plugins are discovered.
### Plugin Discovery
Paperless-ngx automatically discovers and loads date parser plugins at runtime. The discovery process:
1. Queries the `paperless_ngx.date_parsers` entry point group
2. Validates that each plugin is a subclass of `DateParserPluginBase`
3. Sorts valid plugins alphabetically by entry point name
4. Uses the first valid plugin, or falls back to the default `RegexDateParserPlugin` if none are found
If multiple plugins are installed, a warning is logged indicating which plugin was selected.
### Example: Simple Date Parser
Here's a minimal example that only looks for ISO 8601 dates:
```python
import datetime
import re
from collections.abc import Iterator
from documents.plugins.date_parsing.base import DateParserPluginBase
class ISODateParserPlugin(DateParserPluginBase):
"""
Parser that only matches ISO 8601 formatted dates (YYYY-MM-DD).
"""
ISO_REGEX = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
def parse(self, filename: str, content: str) -> Iterator[datetime.datetime]:
# Combine filename and content for searching
text = f"{filename} {content}"
for match in self.ISO_REGEX.finditer(text):
date_string = match.group(1)
# Use helper method to parse with configured timezone
date = self._parse_string(date_string, "YMD")
# Use helper method to validate the date
filtered_date = self._filter_date(date)
if filtered_date is not None:
yield filtered_date
```

View File

@@ -1,7 +1,3 @@
---
title: FAQs
---
# Frequently Asked Questions
## _What's the general plan for Paperless-ngx?_
@@ -67,10 +63,8 @@ elsewhere. Here are a couple notes about that.
Paperless also supports various Office documents (.docx, .doc, odt,
.ppt, .pptx, .odp, .xls, .xlsx, .ods).
Paperless-ngx determines the type of a file by inspecting its content
rather than its file extensions. However, files processed via the
consumption directory will be rejected if they have a file extension that
not supported by any of the available parsers.
Paperless-ngx determines the type of a file by inspecting its content.
The file extensions do not matter.
## _Will paperless-ngx run on Raspberry Pi?_

View File

@@ -1,7 +1,3 @@
---
title: Home
---
<div class="grid-left" markdown>
![image](assets/logo_full_black.svg#only-light){.index-logo}
![image](assets/logo_full_white.svg#only-dark){.index-logo}

View File

@@ -23,28 +23,3 @@ separating the directory ignore from the file ignore.
Document and thumbnail encryption is no longer supported. This was previously deprecated in [paperless-ng 0.9.3](https://github.com/paperless-ngx/paperless-ngx/blob/dev/docs/changelog.md#paperless-ng-093)
Users must decrypt their document using the `decrypt_documents` command before upgrading.
## Barcode Scanner Changes
Support for [pyzbar](https://github.com/NaturalHistoryMuseum/pyzbar) has been removed. The underlying libzbar library has
seen no updates in 16 years and is largely unmaintained, and the pyzbar Python wrapper last saw a release in March 2022. In
practice, pyzbar struggled with barcode detection reliability, particularly on skewed, low-contrast, or partially
obscured barcodes. [zxing-cpp](https://github.com/zxing-cpp/zxing-cpp) is actively maintained, significantly more
reliable at finding barcodes, and now ships pre-built wheels for both x86_64 and arm64, removing the need to build the library.
The `CONSUMER_BARCODE_SCANNER` setting has been removed. zxing-cpp is now the only backend.
### Summary
| Old Setting | New Setting | Notes |
| -------------------------- | ----------- | --------------------------------- |
| `CONSUMER_BARCODE_SCANNER` | _Removed_ | zxing-cpp is now the only backend |
### Action Required
- If you were already using `CONSUMER_BARCODE_SCANNER=ZXING`, simply remove the setting.
- If you had `CONSUMER_BARCODE_SCANNER=PYZBAR` or were using the default, no functional changes are needed beyond
removing the setting. zxing-cpp supports all the same barcode formats and you should see improved detection
reliability.
- The `libzbar0` / `libzbar-dev` system packages are no longer required and can be removed from any custom Docker
images or host installations.

View File

@@ -1,8 +1,4 @@
---
title: Setup
---
# Installation
## Installation
You can go multiple routes to setup and run Paperless:
@@ -207,12 +203,13 @@ are released, dependency support is confirmed, etc.
- `libpq-dev` for PostgreSQL
- `libmagic-dev` for mime type detection
- `mariadb-client` for MariaDB compile time
- `libzbar0` for barcode detection
- `poppler-utils` for barcode detection
Use this list for your preferred package management:
```
python3 python3-pip python3-dev imagemagick fonts-liberation gnupg libpq-dev default-libmysqlclient-dev pkg-config libmagic-dev poppler-utils
python3 python3-pip python3-dev imagemagick fonts-liberation gnupg libpq-dev default-libmysqlclient-dev pkg-config libmagic-dev libzbar0 poppler-utils
```
These dependencies are required for OCRmyPDF, which is used for text

View File

@@ -1,8 +1,4 @@
---
title: Basic Usage
---
# Usage
# Usage Overview
Paperless-ngx is an application that manages your personal documents. With
the (optional) help of a document scanner (see [the scanners wiki](https://github.com/paperless-ngx/paperless-ngx/wiki/Scanner-&-Software-Recommendations)), Paperless-ngx transforms your unwieldy
@@ -566,8 +562,8 @@ you may want to adjust these settings to prevent abuse.
#### Workflow placeholders
Titles and webhook payloads can be generated by workflows using [Jinja templates](https://jinja.palletsprojects.com/en/3.1.x/templates/).
This allows for complex logic to be used, including [logical structures](https://jinja.palletsprojects.com/en/3.1.x/templates/#list-of-control-structures)
Titles can be assigned by workflows using [Jinja templates](https://jinja.palletsprojects.com/en/3.1.x/templates/).
This allows for complex logic to be used to generate the title, including [logical structures](https://jinja.palletsprojects.com/en/3.1.x/templates/#list-of-control-structures)
and [filters](https://jinja.palletsprojects.com/en/3.1.x/templates/#id11).
The template is provided as a string.
@@ -590,7 +586,7 @@ applied. You can use the following placeholders in the template with any trigger
- `{{added_time}}`: added time in HH:MM format
- `{{original_filename}}`: original file name without extension
- `{{filename}}`: current file name without extension
- `{{doc_title}}`: current document title (cannot be used in title assignment)
- `{{doc_title}}`: current document title
The following placeholders are only available for "added" or "updated" triggers

87
mkdocs.yml Normal file
View File

@@ -0,0 +1,87 @@
site_name: Paperless-ngx
theme:
name: material
logo: assets/logo.svg
font:
text: Roboto
code: Roboto Mono
palette:
# Palette toggle for automatic mode
- media: "(prefers-color-scheme)"
toggle:
icon: material/brightness-auto
name: Switch to light mode
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
toggle:
icon: material/brightness-4
name: Switch to system preference
features:
- navigation.tabs
- navigation.top
- toc.integrate
- content.code.annotate
icon:
repo: fontawesome/brands/github
favicon: assets/favicon.png
repo_url: https://github.com/paperless-ngx/paperless-ngx
repo_name: paperless-ngx/paperless-ngx
edit_uri: blob/main/docs/
extra_css:
- assets/extra.css
markdown_extensions:
- attr_list
- md_in_html
- def_list
- admonition
- tables
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.superfences
- pymdownx.inlinehilite
- pymdownx.snippets
- pymdownx.tilde
- footnotes
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- pymdownx.emoji:
emoji_index: !!python/name:material.extensions.emoji.twemoji
emoji_generator: !!python/name:material.extensions.emoji.to_svg
strict: true
nav:
- index.md
- setup.md
- 'Basic Usage': usage.md
- configuration.md
- administration.md
- advanced_usage.md
- 'REST API': api.md
- development.md
- 'FAQs': faq.md
- troubleshooting.md
- 'Migration to v3': migration.md
- changelog.md
copyright: Copyright &copy; 2016 - 2026 Daniel Quinn, Jonas Winkler, and the Paperless-ngx team
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/paperless-ngx/paperless-ngx
- icon: fontawesome/brands/docker
link: https://hub.docker.com/r/paperlessngx/paperless-ngx
- icon: material/chat
link: https://matrix.to/#/#paperless:matrix.org
plugins:
- search
- glightbox:
skip_classes:
- no-lightbox

View File

@@ -33,8 +33,6 @@
"**/coverage.json": true
},
"python.defaultInterpreterPath": ".venv/bin/python3",
"python.analysis.inlayHints.pytestParameters": true,
"python.testing.pytestEnabled": true,
},
"extensions": {
"recommendations": ["ms-python.python", "charliermarsh.ruff", "editorconfig.editorconfig"],

View File

@@ -66,7 +66,6 @@
#PAPERLESS_CONSUMER_BARCODE_DPI=300
#PAPERLESS_CONSUMER_ENABLE_TAG_BARCODE=false
#PAPERLESS_CONSUMER_TAG_BARCODE_MAPPING={"TAG:(.*)": "\\g<1>"}
#PAPERLESS_CONSUMER_TAG_BARCODE_SPLIT=false
#PAPERLESS_CONSUMER_ENABLE_COLLATE_DOUBLE_SIDED=false
#PAPERLESS_CONSUMER_COLLATE_DOUBLE_SIDED_SUBDIR_NAME=double-sided
#PAPERLESS_CONSUMER_COLLATE_DOUBLE_SIDED_TIFF_SUPPORT=false

View File

@@ -1,6 +1,6 @@
[project]
name = "paperless-ngx"
version = "2.20.6"
version = "2.20.5"
description = "A community-supported supercharged document management system: scan, index and archive all your physical documents"
readme = "README.md"
requires-python = ">=3.10"
@@ -27,9 +27,9 @@ dependencies = [
# WARNING: django does not use semver.
# Only patch versions are guaranteed to not introduce breaking changes.
"django~=5.2.10",
"django-allauth[mfa,socialaccount]~=65.14.0",
"django-allauth[mfa,socialaccount]~=65.13.1",
"django-auditlog~=3.4.1",
"django-cachalot~=2.9.0",
"django-cachalot~=2.8.0",
"django-celery-results~=2.6.0",
"django-compression-middleware~=0.5.0",
"django-cors-headers~=4.9.0",
@@ -42,13 +42,15 @@ dependencies = [
"djangorestframework~=3.16",
"djangorestframework-guardian~=0.4.0",
"drf-spectacular~=0.28",
"drf-spectacular-sidecar~=2026.1.1",
"drf-spectacular-sidecar~=2025.10.1",
"drf-writable-nested~=0.7.1",
"faiss-cpu>=1.10",
"filelock~=3.20.0",
"flower~=2.0.1",
"gotenberg-client~=0.13.1",
"httpx-oauth~=0.16",
"ijson",
"ijson~=3.3",
"imap-tools~=1.11.0",
"jinja2~=3.1.5",
"langdetect~=1.0.9",
@@ -68,19 +70,21 @@ dependencies = [
"python-gnupg~=0.5.4",
"python-ipware~=3.0.0",
"python-magic~=0.4.27",
"pyzbar~=0.1.9",
"rapidfuzz~=3.14.0",
"redis[hiredis]~=5.2.1",
"regex>=2025.9.18",
"rich~=14.1.0",
"scikit-learn~=1.7.0",
"sentence-transformers>=4.1",
"setproctitle~=1.3.4",
"tika-client~=0.10.0",
"torch~=2.10.0",
"torch~=2.9.1",
"tqdm~=4.67.1",
"watchfiles>=1.1.1",
"whitenoise~=6.11",
"whoosh-reloaded>=2.7.5",
"zxing-cpp~=3.0.0",
"zxing-cpp~=2.3.0",
]
optional-dependencies.mariadb = [
@@ -93,7 +97,7 @@ optional-dependencies.postgres = [
"psycopg-pool==3.3",
]
optional-dependencies.webserver = [
"granian[uvloop]~=2.7.0",
"granian[uvloop]~=2.6.0",
]
[dependency-groups]
@@ -105,7 +109,8 @@ dev = [
]
docs = [
"zensical>=0.0.21",
"mkdocs-glightbox~=0.5.1",
"mkdocs-material~=9.7.0",
]
testing = [
@@ -125,8 +130,9 @@ testing = [
]
lint = [
"prek~=0.3.0",
"ruff~=0.15.0",
"pre-commit~=4.5.1",
"pre-commit-uv~=4.2.0",
"ruff~=0.14.0",
]
typing = [
@@ -135,12 +141,8 @@ typing = [
"django-stubs[compatible-mypy]",
"djangorestframework-stubs[compatible-mypy]",
"lxml-stubs",
"microsoft-python-type-stubs @ git+https://github.com/microsoft/python-type-stubs.git",
"mypy",
"mypy-baseline",
"pyrefly",
"types-bleach",
"types-channels",
"types-colorama",
"types-dateparser",
"types-markdown",
@@ -160,22 +162,26 @@ environments = [
"sys_platform == 'linux'",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
# Markers are chosen to select these almost exclusively when building the Docker image
psycopg-c = [
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.0/psycopg_c-3.3.0-cp312-cp312-linux_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64' and python_version == '3.12'" },
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.0/psycopg_c-3.3.0-cp312-cp312-linux_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64' and python_version == '3.12'" },
]
zxing-cpp = [
{ url = "https://github.com/paperless-ngx/builder/releases/download/zxing-2.3.0/zxing_cpp-2.3.0-cp312-cp312-linux_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64' and python_version == '3.12'" },
{ url = "https://github.com/paperless-ngx/builder/releases/download/zxing-2.3.0/zxing_cpp-2.3.0-cp312-cp312-linux_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64' and python_version == '3.12'" },
]
torch = [
{ index = "pytorch-cpu" },
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.ruff]
target-version = "py310"
line-length = 88
@@ -303,20 +309,12 @@ markers = [
"gotenberg: Tests requiring Gotenberg service",
"tika: Tests requiring Tika service",
"greenmail: Tests requiring Greenmail service",
"date_parsing: Tests which cover date parsing from content or filename",
]
[tool.pytest_env]
PAPERLESS_DISABLE_DBHANDLER = "true"
PAPERLESS_CACHE_BACKEND = "django.core.cache.backends.locmem.LocMemCache"
[tool.coverage.report]
exclude_also = [
"if settings.AUDIT_LOG_ENABLED:",
"if AUDIT_LOG_ENABLED:",
"if TYPE_CHECKING:",
]
[tool.coverage.run]
source = [
"src/",
@@ -328,6 +326,13 @@ omit = [
"paperless/auth.py",
]
[tool.coverage.report]
exclude_also = [
"if settings.AUDIT_LOG_ENABLED:",
"if AUDIT_LOG_ENABLED:",
"if TYPE_CHECKING:",
]
[tool.mypy]
mypy_path = "src"
plugins = [
@@ -341,15 +346,5 @@ disallow_untyped_defs = true
warn_redundant_casts = true
warn_unused_ignores = true
[tool.pyrefly]
search-path = [ "src" ]
baseline = ".pyrefly-baseline.json"
python-platform = "linux"
[tool.django-stubs]
django_settings_module = "paperless.settings"
[tool.mypy-baseline]
baseline_path = ".mypy-baseline.txt"
sort_baseline = true
ignore_categories = [ "note" ]

View File

@@ -86,6 +86,7 @@
],
"scripts": [],
"allowedCommonJsDependencies": [
"ng2-pdf-viewer",
"file-saver",
"utif"
],

View File

@@ -72,7 +72,7 @@ test('should show a mobile preview', async ({ page }) => {
await page.setViewportSize({ width: 400, height: 1000 })
await expect(page.getByRole('tab', { name: 'Preview' })).toBeVisible()
await page.getByRole('tab', { name: 'Preview' }).click()
await page.waitForSelector('pngx-pdf-viewer')
await page.waitForSelector('pdf-viewer')
})
test('should show a list of notes', async ({ page }) => {

View File

@@ -180,9 +180,6 @@ test('bulk edit', async ({ page }) => {
await page.locator('pngx-document-card-small').nth(2).click()
await page.getByRole('button', { name: 'Tags' }).click()
await page
.getByRole('textbox', { name: 'Filter tags' })
.fill('TagWithPartial')
await page.getByRole('menuitem', { name: 'TagWithPartial' }).click()
await page.getByRole('button', { name: 'Apply' }).click()

View File

@@ -31,10 +31,6 @@ module.exports = {
moduleNameMapper: {
...esmPreset.moduleNameMapper,
'^src/(.*)': '<rootDir>/src/$1',
'^pdfjs-dist/legacy/build/pdf\\.mjs$':
'<rootDir>/src/test/mocks/pdfjs-legacy-build-pdf.ts',
'^pdfjs-dist/web/pdf_viewer\\.mjs$':
'<rootDir>/src/test/mocks/pdfjs-web-pdf_viewer.ts',
},
workerIdleMemoryLimit: '512MB',
reporters: [

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "paperless-ngx-ui",
"version": "2.20.6",
"version": "2.20.5",
"scripts": {
"preinstall": "npx only-allow pnpm",
"ng": "ng",
@@ -11,55 +11,55 @@
},
"private": true,
"dependencies": {
"@angular/cdk": "^21.1.3",
"@angular/common": "~21.1.3",
"@angular/compiler": "~21.1.3",
"@angular/core": "~21.1.3",
"@angular/forms": "~21.1.3",
"@angular/localize": "~21.1.3",
"@angular/platform-browser": "~21.1.3",
"@angular/platform-browser-dynamic": "~21.1.3",
"@angular/router": "~21.1.3",
"@angular/cdk": "^21.0.6",
"@angular/common": "~21.0.8",
"@angular/compiler": "~21.0.8",
"@angular/core": "~21.0.8",
"@angular/forms": "~21.0.8",
"@angular/localize": "~21.0.8",
"@angular/platform-browser": "~21.0.8",
"@angular/platform-browser-dynamic": "~21.0.8",
"@angular/router": "~21.0.8",
"@ng-bootstrap/ng-bootstrap": "^20.0.0",
"@ng-select/ng-select": "^21.2.0",
"@ng-select/ng-select": "^21.1.4",
"@ngneat/dirty-check-forms": "^3.0.3",
"@popperjs/core": "^2.11.8",
"bootstrap": "^5.3.8",
"file-saver": "^2.0.5",
"mime-names": "^1.0.0",
"ng2-pdf-viewer": "^10.4.0",
"ngx-bootstrap-icons": "^1.9.3",
"ngx-color": "^10.1.0",
"ngx-cookie-service": "^21.1.0",
"ngx-device-detector": "^11.0.0",
"ngx-ui-tour-ng-bootstrap": "^18.0.0",
"pdfjs-dist": "^5.4.624",
"ngx-ui-tour-ng-bootstrap": "^17.0.1",
"rxjs": "^7.8.2",
"tslib": "^2.8.1",
"utif": "^3.1.0",
"uuid": "^13.0.0",
"zone.js": "^0.16.0"
"zone.js": "^0.15.1"
},
"devDependencies": {
"@angular-builders/custom-webpack": "^21.0.3",
"@angular-builders/jest": "^21.0.3",
"@angular-devkit/core": "^21.1.3",
"@angular-devkit/schematics": "^21.1.3",
"@angular-eslint/builder": "21.2.0",
"@angular-eslint/eslint-plugin": "21.2.0",
"@angular-eslint/eslint-plugin-template": "21.2.0",
"@angular-eslint/schematics": "21.2.0",
"@angular-eslint/template-parser": "21.2.0",
"@angular/build": "^21.1.3",
"@angular/cli": "~21.1.3",
"@angular/compiler-cli": "~21.1.3",
"@angular-builders/custom-webpack": "^21.0.0-beta.1",
"@angular-builders/jest": "^21.0.0-beta.1",
"@angular-devkit/core": "^21.0.5",
"@angular-devkit/schematics": "^21.0.5",
"@angular-eslint/builder": "21.1.0",
"@angular-eslint/eslint-plugin": "21.1.0",
"@angular-eslint/eslint-plugin-template": "21.1.0",
"@angular-eslint/schematics": "21.1.0",
"@angular-eslint/template-parser": "21.1.0",
"@angular/build": "^21.0.5",
"@angular/cli": "~21.0.5",
"@angular/compiler-cli": "~21.0.8",
"@codecov/webpack-plugin": "^1.9.1",
"@playwright/test": "^1.58.2",
"@playwright/test": "^1.57.0",
"@types/jest": "^30.0.0",
"@types/node": "^25.2.1",
"@typescript-eslint/eslint-plugin": "^8.54.0",
"@typescript-eslint/parser": "^8.54.0",
"@typescript-eslint/utils": "^8.54.0",
"eslint": "^9.39.2",
"@types/node": "^24.10.1",
"@typescript-eslint/eslint-plugin": "^8.48.1",
"@typescript-eslint/parser": "^8.48.1",
"@typescript-eslint/utils": "^8.48.1",
"eslint": "^9.39.1",
"jest": "30.2.0",
"jest-environment-jsdom": "^30.2.0",
"jest-junit": "^16.0.0",
@@ -68,7 +68,7 @@
"prettier-plugin-organize-imports": "^4.3.0",
"ts-node": "~10.9.1",
"typescript": "^5.9.3",
"webpack": "^5.105.0"
"webpack": "^5.103.0"
},
"packageManager": "pnpm@10.17.1",
"pnpm": {

5642
src-ui/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -100,10 +100,10 @@ const mock = () => {
}
}
Object.defineProperty(globalThis, 'open', { value: jest.fn() })
Object.defineProperty(globalThis, 'localStorage', { value: mock() })
Object.defineProperty(globalThis, 'sessionStorage', { value: mock() })
Object.defineProperty(globalThis, 'getComputedStyle', {
Object.defineProperty(window, 'open', { value: jest.fn() })
Object.defineProperty(window, 'localStorage', { value: mock() })
Object.defineProperty(window, 'sessionStorage', { value: mock() })
Object.defineProperty(window, 'getComputedStyle', {
value: () => ['-webkit-appearance'],
})
Object.defineProperty(navigator, 'clipboard', {
@@ -115,33 +115,13 @@ Object.defineProperty(navigator, 'canShare', { value: () => true })
if (!navigator.share) {
Object.defineProperty(navigator, 'share', { value: jest.fn() })
}
if (!globalThis.URL.createObjectURL) {
Object.defineProperty(globalThis.URL, 'createObjectURL', { value: jest.fn() })
if (!URL.createObjectURL) {
Object.defineProperty(window.URL, 'createObjectURL', { value: jest.fn() })
}
if (!globalThis.URL.revokeObjectURL) {
Object.defineProperty(globalThis.URL, 'revokeObjectURL', { value: jest.fn() })
if (!URL.revokeObjectURL) {
Object.defineProperty(window.URL, 'revokeObjectURL', { value: jest.fn() })
}
class MockResizeObserver {
private readonly callback: ResizeObserverCallback
constructor(callback: ResizeObserverCallback) {
this.callback = callback
}
observe = jest.fn()
unobserve = jest.fn()
disconnect = jest.fn()
trigger = (entries: ResizeObserverEntry[] = []) => {
this.callback(entries, this)
}
}
Object.defineProperty(globalThis, 'ResizeObserver', {
writable: true,
configurable: true,
value: MockResizeObserver,
})
Object.defineProperty(window, 'ResizeObserver', { value: mock() })
if (typeof IntersectionObserver === 'undefined') {
class MockIntersectionObserver {
@@ -156,7 +136,7 @@ if (typeof IntersectionObserver === 'undefined') {
takeRecords = jest.fn()
}
Object.defineProperty(globalThis, 'IntersectionObserver', {
Object.defineProperty(window, 'IntersectionObserver', {
writable: true,
configurable: true,
value: MockIntersectionObserver,

View File

@@ -9,11 +9,7 @@ import {
import { Router, RouterModule } from '@angular/router'
import { NgbModalModule } from '@ng-bootstrap/ng-bootstrap'
import { allIcons, NgxBootstrapIconsModule } from 'ngx-bootstrap-icons'
import {
provideUiTour,
TourNgBootstrap,
TourService,
} from 'ngx-ui-tour-ng-bootstrap'
import { TourNgBootstrapModule, TourService } from 'ngx-ui-tour-ng-bootstrap'
import { Subject } from 'rxjs'
import { routes } from './app-routing.module'
import { AppComponent } from './app.component'
@@ -44,12 +40,12 @@ describe('AppComponent', () => {
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [
TourNgBootstrapModule,
RouterModule.forRoot(routes),
NgbModalModule,
AppComponent,
ToastsComponent,
FileDropComponent,
TourNgBootstrap,
NgxBootstrapIconsModule.pick(allIcons),
],
providers: [
@@ -57,7 +53,6 @@ describe('AppComponent', () => {
DirtySavedViewGuard,
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
provideUiTour(),
],
}).compileComponents()

View File

@@ -1,6 +1,6 @@
import { Component, inject, OnDestroy, OnInit, Renderer2 } from '@angular/core'
import { Router, RouterOutlet } from '@angular/router'
import { TourNgBootstrap, TourService } from 'ngx-ui-tour-ng-bootstrap'
import { TourNgBootstrapModule, TourService } from 'ngx-ui-tour-ng-bootstrap'
import { first, Subscription } from 'rxjs'
import { ToastsComponent } from './components/common/toasts/toasts.component'
import { FileDropComponent } from './components/file-drop/file-drop.component'
@@ -21,7 +21,12 @@ import { WebsocketStatusService } from './services/websocket-status.service'
selector: 'pngx-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
imports: [FileDropComponent, ToastsComponent, TourNgBootstrap, RouterOutlet],
imports: [
FileDropComponent,
ToastsComponent,
TourNgBootstrapModule,
RouterOutlet,
],
})
export class AppComponent implements OnInit, OnDestroy {
private settings = inject(SettingsService)
@@ -162,91 +167,108 @@ export class AppComponent implements OnInit, OnDestroy {
})
}
this.tourService.initialize([
{
anchorId: 'tour.dashboard',
content: $localize`The dashboard can be used to show saved views, such as an 'Inbox'. Views are found under Manage > Saved Views once you have created some.`,
route: '/dashboard',
delayAfterNavigation: 500,
isOptional: false,
},
{
anchorId: 'tour.upload-widget',
content: $localize`Drag-and-drop documents here to start uploading or place them in the consume folder. You can also drag-and-drop documents anywhere on all other pages of the web app. Once you do, Paperless-ngx will start training its machine learning algorithms.`,
route: '/dashboard',
},
{
anchorId: 'tour.documents',
content: $localize`The documents list shows all of your documents and allows for filtering as well as bulk-editing. There are three different view styles: list, small cards and large cards. A list of documents currently opened for editing is shown in the sidebar.`,
route: '/documents?sort=created&reverse=1&page=1',
delayAfterNavigation: 500,
placement: 'bottom',
},
{
anchorId: 'tour.documents-filter-editor',
content: $localize`The filtering tools allow you to quickly find documents using various searches, dates, tags, etc.`,
route: '/documents?sort=created&reverse=1&page=1',
placement: 'bottom',
},
{
anchorId: 'tour.documents-views',
content: $localize`Any combination of filters can be saved as a 'view' which can then be displayed on the dashboard and / or sidebar.`,
route: '/documents?sort=created&reverse=1&page=1',
},
{
anchorId: 'tour.tags',
content: $localize`Tags, correspondents, document types and storage paths can all be managed using these pages. They can also be created from the document edit view.`,
route: '/tags',
backdropConfig: {
offset: 0,
const prevBtnTitle = $localize`Prev`
const nextBtnTitle = $localize`Next`
const endBtnTitle = $localize`End`
this.tourService.initialize(
[
{
anchorId: 'tour.dashboard',
content: $localize`The dashboard can be used to show saved views, such as an 'Inbox'. Views are found under Manage > Saved Views once you have created some.`,
route: '/dashboard',
delayAfterNavigation: 500,
isOptional: false,
},
},
{
anchorId: 'tour.mail',
content: $localize`Manage e-mail accounts and rules for automatically importing documents.`,
route: '/mail',
backdropConfig: {
offset: 0,
{
anchorId: 'tour.upload-widget',
content: $localize`Drag-and-drop documents here to start uploading or place them in the consume folder. You can also drag-and-drop documents anywhere on all other pages of the web app. Once you do, Paperless-ngx will start training its machine learning algorithms.`,
route: '/dashboard',
},
},
{
anchorId: 'tour.workflows',
content: $localize`Workflows give you more control over the document pipeline.`,
route: '/workflows',
backdropConfig: {
offset: 0,
{
anchorId: 'tour.documents',
content: $localize`The documents list shows all of your documents and allows for filtering as well as bulk-editing. There are three different view styles: list, small cards and large cards. A list of documents currently opened for editing is shown in the sidebar.`,
route: '/documents?sort=created&reverse=1&page=1',
delayAfterNavigation: 500,
placement: 'bottom',
},
},
{
anchorId: 'tour.file-tasks',
content: $localize`File Tasks shows you documents that have been consumed, are waiting to be, or may have failed during the process.`,
route: '/tasks',
backdropConfig: {
offset: 0,
{
anchorId: 'tour.documents-filter-editor',
content: $localize`The filtering tools allow you to quickly find documents using various searches, dates, tags, etc.`,
route: '/documents?sort=created&reverse=1&page=1',
placement: 'bottom',
},
},
{
anchorId: 'tour.settings',
content: $localize`Check out the settings for various tweaks to the web app.`,
route: '/settings',
backdropConfig: {
offset: 0,
{
anchorId: 'tour.documents-views',
content: $localize`Any combination of filters can be saved as a 'view' which can then be displayed on the dashboard and / or sidebar.`,
route: '/documents?sort=created&reverse=1&page=1',
},
},
{
anchorId: 'tour.outro',
title: $localize`Thank you! 🙏`,
content:
$localize`There are <em>tons</em> more features and info we didn't cover here, but this should get you started. Check out the documentation or visit the project on GitHub to learn more or to report issues.` +
'<br/><br/>' +
$localize`Lastly, on behalf of every contributor to this community-supported project, thank you for using Paperless-ngx!`,
route: '/dashboard',
isOptional: false,
backdropConfig: {
offset: 0,
{
anchorId: 'tour.tags',
content: $localize`Tags, correspondents, document types and storage paths can all be managed using these pages. They can also be created from the document edit view.`,
route: '/tags',
backdropConfig: {
offset: 0,
},
},
},
])
{
anchorId: 'tour.mail',
content: $localize`Manage e-mail accounts and rules for automatically importing documents.`,
route: '/mail',
backdropConfig: {
offset: 0,
},
},
{
anchorId: 'tour.workflows',
content: $localize`Workflows give you more control over the document pipeline.`,
route: '/workflows',
backdropConfig: {
offset: 0,
},
},
{
anchorId: 'tour.file-tasks',
content: $localize`File Tasks shows you documents that have been consumed, are waiting to be, or may have failed during the process.`,
route: '/tasks',
backdropConfig: {
offset: 0,
},
},
{
anchorId: 'tour.settings',
content: $localize`Check out the settings for various tweaks to the web app.`,
route: '/settings',
backdropConfig: {
offset: 0,
},
},
{
anchorId: 'tour.outro',
title: $localize`Thank you! 🙏`,
content:
$localize`There are <em>tons</em> more features and info we didn't cover here, but this should get you started. Check out the documentation or visit the project on GitHub to learn more or to report issues.` +
'<br/><br/>' +
$localize`Lastly, on behalf of every contributor to this community-supported project, thank you for using Paperless-ngx!`,
route: '/dashboard',
isOptional: false,
backdropConfig: {
offset: 0,
},
},
],
{
enableBackdrop: true,
backdropConfig: {
offset: 10,
},
prevBtnTitle,
nextBtnTitle,
endBtnTitle,
isOptional: true,
useLegacyTitle: true,
}
)
this.tourService.start$.subscribe(() => {
this.renderer.addClass(document.body, 'tour-active')

View File

@@ -222,8 +222,8 @@
</div>
<div class="col">
<select class="form-select" formControlName="pdfViewerDefaultZoom">
<option [ngValue]="PdfZoomScale.PageWidth" i18n>Fit width</option>
<option [ngValue]="PdfZoomScale.PageFit" i18n>Fit page</option>
<option [ngValue]="ZoomSetting.PageWidth" i18n>Fit width</option>
<option [ngValue]="ZoomSetting.PageFit" i18n>Fit page</option>
</select>
<p class="small text-muted mt-1" i18n>Only applies to the Paperless-ngx PDF viewer.</p>
</div>

View File

@@ -16,7 +16,6 @@ import {
} from '@ng-bootstrap/ng-bootstrap'
import { NgSelectModule } from '@ng-select/ng-select'
import { NgxBootstrapIconsModule, allIcons } from 'ngx-bootstrap-icons'
import { provideUiTour } from 'ngx-ui-tour-ng-bootstrap'
import { of, throwError } from 'rxjs'
import { routes } from 'src/app/app-routing.module'
import {
@@ -148,7 +147,6 @@ describe('SettingsComponent', () => {
PermissionsGuard,
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
provideUiTour(),
],
}).compileComponents()

View File

@@ -65,8 +65,8 @@ import { PermissionsUserComponent } from '../../common/input/permissions/permiss
import { SelectComponent } from '../../common/input/select/select.component'
import { PageHeaderComponent } from '../../common/page-header/page-header.component'
import { PdfEditorEditMode } from '../../common/pdf-editor/pdf-editor-edit-mode'
import { PdfZoomScale } from '../../common/pdf-viewer/pdf-viewer.types'
import { SystemStatusDialogComponent } from '../../common/system-status-dialog/system-status-dialog.component'
import { ZoomSetting } from '../../document-detail/zoom-setting'
import { ComponentWithPermissions } from '../../with-permissions/with-permissions.component'
enum SettingsNavIDs {
@@ -196,7 +196,7 @@ export class SettingsComponent
public readonly GlobalSearchType = GlobalSearchType
public readonly PdfZoomScale = PdfZoomScale
public readonly ZoomSetting = ZoomSetting
public readonly PdfEditorEditMode = PdfEditorEditMode

View File

@@ -16,7 +16,6 @@ import { ActivatedRoute, Router } from '@angular/router'
import { RouterTestingModule } from '@angular/router/testing'
import { NgbModal, NgbModalModule, NgbModule } from '@ng-bootstrap/ng-bootstrap'
import { NgxBootstrapIconsModule, allIcons } from 'ngx-bootstrap-icons'
import { provideUiTour } from 'ngx-ui-tour-ng-bootstrap'
import { of, throwError } from 'rxjs'
import { routes } from 'src/app/app-routing.module'
import { SavedView } from 'src/app/data/saved-view'
@@ -158,7 +157,6 @@ describe('AppFrameComponent', () => {
PermissionsGuard,
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
provideUiTour(),
],
}).compileComponents()

View File

@@ -16,7 +16,7 @@ import {
NgbPopoverModule,
} from '@ng-bootstrap/ng-bootstrap'
import { NgxBootstrapIconsModule } from 'ngx-bootstrap-icons'
import { TourNgBootstrap } from 'ngx-ui-tour-ng-bootstrap'
import { TourNgBootstrapModule } from 'ngx-ui-tour-ng-bootstrap'
import { Observable } from 'rxjs'
import { first } from 'rxjs/operators'
import { Document } from 'src/app/data/document'
@@ -69,7 +69,7 @@ import { ToastsDropdownComponent } from './toasts-dropdown/toasts-dropdown.compo
NgbNavModule,
NgxBootstrapIconsModule,
DragDropModule,
TourNgBootstrap,
TourNgBootstrapModule,
],
})
export class AppFrameComponent

View File

@@ -430,24 +430,6 @@
</div>
</div>
}
@case (WorkflowActionType.PasswordRemoval) {
<div class="row">
<div class="col">
<p class="small" i18n>
One password per line. The workflow will try them in order until one succeeds.
</p>
<pngx-input-textarea
i18n-title
title="Passwords"
formControlName="passwords"
rows="4"
[error]="error?.actions?.[i]?.passwords"
hint="Passwords are stored in plain text. Use with caution."
i18n-hint
></pngx-input-textarea>
</div>
</div>
}
}
</div>
</ng-template>

View File

@@ -3,7 +3,6 @@ import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
import { provideHttpClientTesting } from '@angular/common/http/testing'
import { ComponentFixture, TestBed } from '@angular/core/testing'
import {
FormArray,
FormControl,
FormGroup,
FormsModule,
@@ -995,32 +994,4 @@ describe('WorkflowEditDialogComponent', () => {
component.removeSelectedCustomField(3, formGroup)
expect(formGroup.get('assign_custom_fields').value).toEqual([])
})
it('should handle parsing of passwords from array to string and back on save', () => {
const passwordAction: WorkflowAction = {
id: 1,
type: WorkflowActionType.PasswordRemoval,
passwords: ['pass1', 'pass2'],
}
component.object = {
name: 'Workflow with Passwords',
id: 1,
order: 1,
enabled: true,
triggers: [],
actions: [passwordAction],
}
component.ngOnInit()
const formActions = component.objectForm.get('actions') as FormArray
expect(formActions.value[0].passwords).toBe('pass1\npass2')
formActions.at(0).get('passwords').setValue('pass1\npass2\npass3')
component.save()
expect(component.objectForm.get('actions').value[0].passwords).toEqual([
'pass1',
'pass2',
'pass3',
])
})
})

View File

@@ -139,10 +139,6 @@ export const WORKFLOW_ACTION_OPTIONS = [
id: WorkflowActionType.Webhook,
name: $localize`Webhook`,
},
{
id: WorkflowActionType.PasswordRemoval,
name: $localize`Password removal`,
},
]
export enum TriggerFilterType {
@@ -1206,25 +1202,11 @@ export class WorkflowEditDialogComponent
headers: new FormControl(action.webhook?.headers),
include_document: new FormControl(!!action.webhook?.include_document),
}),
passwords: new FormControl(
this.formatPasswords(action.passwords ?? [])
),
}),
{ emitEvent }
)
}
private formatPasswords(passwords: string[] = []): string {
return passwords.join('\n')
}
private parsePasswords(value: string = ''): string[] {
return value
.split(/[\n,]+/)
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
}
private updateAllTriggerActionFields(emitEvent: boolean = false) {
this.triggerFields.clear({ emitEvent: false })
this.object?.triggers.forEach((trigger) => {
@@ -1349,7 +1331,6 @@ export class WorkflowEditDialogComponent
headers: null,
include_document: false,
},
passwords: [],
}
this.object.actions.push(action)
this.createActionField(action)
@@ -1386,7 +1367,6 @@ export class WorkflowEditDialogComponent
if (action.type !== WorkflowActionType.Email) {
action.email = null
}
action.passwords = this.parsePasswords(action.passwords as any)
})
super.save()
}

View File

@@ -34,8 +34,8 @@
</div>
</div>
@if (selectionModel.items) {
<cdk-virtual-scroll-viewport class="items" [itemSize]="FILTERABLE_BUTTON_HEIGHT_PX" #buttonsViewport [style.height.px]="scrollViewportHeight">
<div *cdkVirtualFor="let item of selectionModel.items | filter: filterText:'name'; trackBy: trackByItem; let i = index">
<div class="items" #buttonItems>
@for (item of selectionModel.items | filter: filterText:'name'; track item; let i = $index) {
@if (allowSelectNone || item.id) {
<pngx-toggleable-dropdown-button
[item]="item"
@@ -45,11 +45,12 @@
[count]="getUpdatedDocumentCount(item.id)"
(toggled)="selectionModel.toggle(item.id)"
(exclude)="excludeClicked(item.id)"
(click)="setButtonItemIndex(i - 1)"
[disabled]="disabled">
</pngx-toggleable-dropdown-button>
}
</div>
</cdk-virtual-scroll-viewport>
}
</div>
}
@if (editing) {
@if ((selectionModel.items | filter: filterText:'name').length === 0 && createRef !== undefined) {

View File

@@ -1,4 +1,3 @@
import { ScrollingModule } from '@angular/cdk/scrolling'
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
import { provideHttpClientTesting } from '@angular/common/http/testing'
import {
@@ -65,7 +64,7 @@ describe('FilterableDropdownComponent & FilterableDropdownSelectionModel', () =>
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
],
imports: [NgxBootstrapIconsModule.pick(allIcons), ScrollingModule],
imports: [NgxBootstrapIconsModule.pick(allIcons)],
}).compileComponents()
hotkeyService = TestBed.inject(HotKeyService)
@@ -266,11 +265,18 @@ describe('FilterableDropdownComponent & FilterableDropdownSelectionModel', () =>
expect(document.activeElement).toEqual(
component.listFilterTextInput.nativeElement
)
expect(component.buttonsViewport.getRenderedRange().end).toEqual(3) // all items shown
expect(
Array.from(
(fixture.nativeElement as HTMLDivElement).querySelectorAll('button')
).filter((b) => b.textContent.includes('Tag'))
).toHaveLength(2)
component.filterText = 'Tag2'
fixture.detectChanges()
expect(component.buttonsViewport.getRenderedRange().end).toEqual(1) // filtered
expect(
Array.from(
(fixture.nativeElement as HTMLDivElement).querySelectorAll('button')
).filter((b) => b.textContent.includes('Tag'))
).toHaveLength(1)
component.dropdown.close()
expect(component.filterText).toHaveLength(0)
}))
@@ -325,8 +331,6 @@ describe('FilterableDropdownComponent & FilterableDropdownSelectionModel', () =>
.dispatchEvent(new MouseEvent('click')) // open
fixture.detectChanges()
tick(100)
component.buttonsViewport?.checkViewportSize()
fixture.detectChanges()
const filterInputEl: HTMLInputElement =
component.listFilterTextInput.nativeElement
expect(document.activeElement).toEqual(filterInputEl)
@@ -372,8 +376,6 @@ describe('FilterableDropdownComponent & FilterableDropdownSelectionModel', () =>
.dispatchEvent(new MouseEvent('click')) // open
fixture.detectChanges()
tick(100)
component.buttonsViewport?.checkViewportSize()
fixture.detectChanges()
const filterInputEl: HTMLInputElement =
component.listFilterTextInput.nativeElement
expect(document.activeElement).toEqual(filterInputEl)
@@ -410,8 +412,6 @@ describe('FilterableDropdownComponent & FilterableDropdownSelectionModel', () =>
.dispatchEvent(new MouseEvent('click')) // open
fixture.detectChanges()
tick(100)
component.buttonsViewport?.checkViewportSize()
fixture.detectChanges()
const filterInputEl: HTMLInputElement =
component.listFilterTextInput.nativeElement
expect(document.activeElement).toEqual(filterInputEl)

View File

@@ -1,7 +1,3 @@
import {
CdkVirtualScrollViewport,
ScrollingModule,
} from '@angular/cdk/scrolling'
import { NgClass } from '@angular/common'
import {
Component,
@@ -631,27 +627,18 @@ export class FilterableDropdownSelectionModel {
NgxBootstrapIconsModule,
NgbDropdownModule,
NgClass,
ScrollingModule,
],
})
export class FilterableDropdownComponent
extends LoadingComponentWithPermissions
implements OnInit
{
public readonly FILTERABLE_BUTTON_HEIGHT_PX = 42
private filterPipe = inject(FilterPipe)
private hotkeyService = inject(HotKeyService)
@ViewChild('listFilterTextInput') listFilterTextInput: ElementRef
@ViewChild('dropdown') dropdown: NgbDropdown
@ViewChild('buttonsViewport') buttonsViewport: CdkVirtualScrollViewport
private get renderedButtons(): Array<HTMLButtonElement> {
return Array.from(
this.buttonsViewport.elementRef.nativeElement.querySelectorAll('button')
)
}
@ViewChild('buttonItems') buttonItems: ElementRef
public popperOptions = pngxPopperOptions
@@ -765,14 +752,6 @@ export class FilterableDropdownComponent
private keyboardIndex: number
public get scrollViewportHeight(): number {
const filteredLength = this.filterPipe.transform(
this.items,
this.filterText
).length
return Math.min(filteredLength * this.FILTERABLE_BUTTON_HEIGHT_PX, 400)
}
constructor() {
super()
this.selectionModelChange.subscribe((updatedModel) => {
@@ -797,10 +776,6 @@ export class FilterableDropdownComponent
}
}
public trackByItem(index: number, item: MatchingModel) {
return item?.id ?? index
}
applyClicked() {
if (this.selectionModel.isDirty()) {
this.dropdown.close()
@@ -819,7 +794,6 @@ export class FilterableDropdownComponent
if (open) {
setTimeout(() => {
this.listFilterTextInput?.nativeElement.focus()
this.buttonsViewport?.checkViewportSize()
}, 0)
if (this.editing) {
this.selectionModel.reset()
@@ -887,14 +861,12 @@ export class FilterableDropdownComponent
event.preventDefault()
}
} else if (event.target instanceof HTMLButtonElement) {
this.syncKeyboardIndexFromButton(event.target)
this.focusNextButtonItem()
event.preventDefault()
}
break
case 'ArrowUp':
if (event.target instanceof HTMLButtonElement) {
this.syncKeyboardIndexFromButton(event.target)
if (this.keyboardIndex === 0) {
this.listFilterTextInput.nativeElement.focus()
} else {
@@ -931,18 +903,15 @@ export class FilterableDropdownComponent
if (setFocus) this.setButtonItemFocus()
}
private syncKeyboardIndexFromButton(button: HTMLButtonElement) {
// because of virtual scrolling, re-calculate the index
const idx = this.renderedButtons.indexOf(button)
if (idx >= 0) {
this.keyboardIndex = this.buttonsViewport.getRenderedRange().start + idx
}
setButtonItemFocus() {
this.buttonItems.nativeElement.children[
this.keyboardIndex
]?.children[0].focus()
}
setButtonItemFocus() {
const offset =
this.keyboardIndex - this.buttonsViewport.getRenderedRange().start
this.renderedButtons[offset]?.focus()
setButtonItemIndex(index: number) {
// just track the index in case user uses arrows
this.keyboardIndex = index
}
hideCount(item: ObjectWithPermissions) {

View File

@@ -15,7 +15,7 @@
<span class="h6 mb-0 mt-1 d-block d-md-inline fw-normal ms-md-3 text-truncate" style="line-height: 1.4">{{subTitle}}</span>
}
@if (info) {
<button class="btn btn-sm btn-link text-muted p-0 p-md-2" title="What's this?" i18n-title type="button" [ngbPopover]="infoPopover" [autoClose]="true">
<button class="btn btn-sm btn-link text-muted me-auto p-0 p-md-2" title="What's this?" i18n-title type="button" [ngbPopover]="infoPopover" [autoClose]="true">
<i-bs name="question-circle"></i-bs>
</button>
<ng-template #infoPopover>
@@ -26,9 +26,6 @@
}
</ng-template>
}
@if (loading) {
<output class="spinner-border spinner-border-sm fs-6 fw-normal" aria-hidden="true"><span class="visually-hidden" i18n>Loading...</span></output>
}
</h3>
</div>
<div class="btn-toolbar col col-md-auto gap-2">

View File

@@ -3,14 +3,14 @@ import { Component, Input, inject } from '@angular/core'
import { Title } from '@angular/platform-browser'
import { NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap'
import { NgxBootstrapIconsModule } from 'ngx-bootstrap-icons'
import { TourNgBootstrap } from 'ngx-ui-tour-ng-bootstrap'
import { TourNgBootstrapModule } from 'ngx-ui-tour-ng-bootstrap'
import { environment } from 'src/environments/environment'
@Component({
selector: 'pngx-page-header',
templateUrl: './page-header.component.html',
styleUrls: ['./page-header.component.scss'],
imports: [NgbPopoverModule, NgxBootstrapIconsModule, TourNgBootstrap],
imports: [NgbPopoverModule, NgxBootstrapIconsModule, TourNgBootstrapModule],
})
export class PageHeaderComponent {
private titleService = inject(Title)
@@ -42,9 +42,6 @@ export class PageHeaderComponent {
@Input()
infoLink: string
@Input()
loading: boolean = false
public copyID() {
this.copied = this.clipboard.copy(this.id.toString())
clearTimeout(this.copyTimeout)

View File

@@ -1,4 +1,4 @@
<pngx-pdf-viewer class="visually-hidden" [src]="pdfSrc" [renderMode]="PdfRenderMode.Single" [page]="1" [selectable]="false" (afterLoadComplete)="pdfLoaded($event)"></pngx-pdf-viewer>
<pdf-viewer [src]="pdfSrc" [render-text]="false" zoom="0.4" (after-load-complete)="pdfLoaded($event)"></pdf-viewer>
<div class="modal-header">
<h4 class="modal-title">{{ title }}</h4>
<button type="button" class="btn-close" aria-label="Close" (click)="cancel()"></button>
@@ -59,7 +59,7 @@
<span class="placeholder w-100 h-100"></span>
</div>
}
<pngx-pdf-viewer class="fade" [class.show]="p.loaded" [src]="pdfSrc" [page]="p.page" [rotation]="p.rotate" [renderMode]="PdfRenderMode.Single" (rendered)="p.loaded = true"></pngx-pdf-viewer>
<pdf-viewer class="fade" [class.show]="p.loaded" [src]="pdfSrc" [page]="p.page" [rotation]="p.rotate" [original-size]="false" [show-all]="false" [render-text]="false" (page-rendered)="p.loaded = true"></pdf-viewer>
} @placeholder {
<div class="placeholder-glow w-100 h-100 z-10">
<span class="placeholder w-100 h-100"></span>

View File

@@ -15,13 +15,13 @@
background-color: gray;
height: 240px;
pngx-pdf-viewer {
pdf-viewer {
width: 100%;
height: 100%;
}
}
::ng-deep .pngx-pdf-viewer-container {
::ng-deep .ng2-pdf-viewer-container {
overflow: hidden;
}

View File

@@ -6,16 +6,12 @@ import {
import { Component, inject } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
import { PDFDocumentProxy, PdfViewerModule } from 'ng2-pdf-viewer'
import { NgxBootstrapIconsModule } from 'ngx-bootstrap-icons'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
import { DocumentService } from 'src/app/services/rest/document.service'
import { SettingsService } from 'src/app/services/settings.service'
import { ConfirmDialogComponent } from '../confirm-dialog/confirm-dialog.component'
import { PngxPdfViewerComponent } from '../pdf-viewer/pdf-viewer.component'
import {
PdfRenderMode,
PngxPdfDocumentProxy,
} from '../pdf-viewer/pdf-viewer.types'
import { PdfEditorEditMode } from './pdf-editor-edit-mode'
interface PageOperation {
@@ -33,12 +29,11 @@ interface PageOperation {
imports: [
DragDropModule,
FormsModule,
PdfViewerModule,
NgxBootstrapIconsModule,
PngxPdfViewerComponent,
],
})
export class PDFEditorComponent extends ConfirmDialogComponent {
PdfRenderMode = PdfRenderMode
public PdfEditorEditMode = PdfEditorEditMode
private documentService = inject(DocumentService)
@@ -58,7 +53,7 @@ export class PDFEditorComponent extends ConfirmDialogComponent {
return this.documentService.getPreviewUrl(this.documentID)
}
pdfLoaded(pdf: PngxPdfDocumentProxy) {
pdfLoaded(pdf: PDFDocumentProxy) {
this.totalPages = pdf.numPages
this.pages = Array.from({ length: this.totalPages }, (_, i) => ({
page: i + 1,

View File

@@ -1,3 +0,0 @@
<div #container class="pngx-pdf-viewer-container">
<div #viewer class="pdfViewer"></div>
</div>

View File

@@ -1,153 +0,0 @@
:host {
display: block;
width: 100%;
height: 100%;
position: relative;
}
:host ::ng-deep .pngx-pdf-viewer-container {
position: absolute;
inset: 0;
overflow: auto;
}
:host ::ng-deep .pdfViewer {
--scale-factor: 1;
--page-bg-color: unset;
padding-bottom: 0;
}
:host ::ng-deep .pdfViewer .page {
--user-unit: 1;
--total-scale-factor: calc(var(--scale-factor) * var(--user-unit));
--scale-round-x: 1px;
--scale-round-y: 1px;
direction: ltr;
margin: 0 auto 10px;
border: 0;
position: relative;
overflow: visible;
background-clip: content-box;
background-color: var(--page-bg-color, rgb(255 255 255));
}
:host ::ng-deep .pdfViewer > .page:last-of-type {
margin-bottom: 0;
}
:host ::ng-deep .pdfViewer.singlePageView {
display: inline-block;
}
:host ::ng-deep .pdfViewer.singlePageView .page {
margin: 0;
border: none;
}
:host ::ng-deep .pdfViewer .canvasWrapper {
overflow: hidden;
width: 100%;
height: 100%;
}
:host ::ng-deep .pdfViewer .canvasWrapper canvas {
position: absolute;
top: 0;
left: 0;
margin: 0;
display: block;
width: 100%;
height: 100%;
contain: content;
}
:host ::ng-deep .textLayer {
position: absolute;
text-align: initial;
inset: 0;
overflow: clip;
opacity: 1;
line-height: 1;
text-size-adjust: none;
transform-origin: 0 0;
caret-color: CanvasText;
z-index: 0;
user-select: text;
--min-font-size: 1;
--text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));
--min-font-size-inv: calc(1 / var(--min-font-size));
}
:host ::ng-deep .textLayer.highlighting {
touch-action: none;
}
:host ::ng-deep .textLayer :is(span, br) {
position: absolute;
white-space: pre;
color: transparent;
cursor: text;
transform-origin: 0% 0%;
}
:host ::ng-deep .textLayer > :not(.markedContent),
:host ::ng-deep .textLayer .markedContent span:not(.markedContent) {
z-index: 1;
--font-height: 0;
font-size: calc(var(--text-scale-factor) * var(--font-height));
--scale-x: 1;
--rotate: 0deg;
transform: rotate(var(--rotate)) scaleX(var(--scale-x))
scale(var(--min-font-size-inv));
}
:host ::ng-deep .textLayer .markedContent {
display: contents;
}
:host ::ng-deep .textLayer span[role='img'] {
user-select: none;
cursor: default;
}
:host ::ng-deep .textLayer .highlight {
--highlight-bg-color: rgb(180 0 170 / 0.25);
--highlight-selected-bg-color: rgb(0 100 0 / 0.25);
--highlight-backdrop-filter: none;
--highlight-selected-backdrop-filter: none;
margin: -1px;
padding: 1px;
background-color: var(--highlight-bg-color);
backdrop-filter: var(--highlight-backdrop-filter);
border-radius: 4px;
}
:host ::ng-deep .appended:is(.textLayer .highlight) {
position: initial;
}
:host ::ng-deep .begin:is(.textLayer .highlight) {
border-radius: 4px 0 0 4px;
}
:host ::ng-deep .end:is(.textLayer .highlight) {
border-radius: 0 4px 4px 0;
}
:host ::ng-deep .middle:is(.textLayer .highlight) {
border-radius: 0;
}
:host ::ng-deep .selected:is(.textLayer .highlight) {
background-color: var(--highlight-selected-bg-color);
}
:host ::ng-deep .textLayer ::selection {
background: rgba(30, 100, 255, 0.35);
}
:host ::ng-deep .annotationLayer {
position: absolute;
inset: 0;
pointer-events: none;
}

View File

@@ -1,299 +0,0 @@
import { SimpleChange } from '@angular/core'
import { ComponentFixture, TestBed } from '@angular/core/testing'
import * as pdfjs from 'pdfjs-dist/legacy/build/pdf.mjs'
import { PDFSinglePageViewer, PDFViewer } from 'pdfjs-dist/web/pdf_viewer.mjs'
import { PngxPdfViewerComponent } from './pdf-viewer.component'
import { PdfRenderMode, PdfZoomLevel, PdfZoomScale } from './pdf-viewer.types'
describe('PngxPdfViewerComponent', () => {
let fixture: ComponentFixture<PngxPdfViewerComponent>
let component: PngxPdfViewerComponent
const initComponent = async (src = 'test.pdf') => {
component.src = src
fixture.detectChanges()
await fixture.whenStable()
}
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [PngxPdfViewerComponent],
}).compileComponents()
fixture = TestBed.createComponent(PngxPdfViewerComponent)
component = fixture.componentInstance
})
it('loads a document and emits events', async () => {
const loadSpy = jest.fn()
const renderedSpy = jest.fn()
component.afterLoadComplete.subscribe(loadSpy)
component.rendered.subscribe(renderedSpy)
await initComponent()
expect(pdfjs.GlobalWorkerOptions.workerSrc).toBe(
'/assets/js/pdf.worker.min.mjs'
)
const isVisible = (component as any).findController.onIsPageVisible as
| (() => boolean)
| undefined
expect(isVisible?.()).toBe(true)
expect(loadSpy).toHaveBeenCalledWith(
expect.objectContaining({ numPages: 1 })
)
expect(renderedSpy).toHaveBeenCalled()
expect((component as any).pdfViewer).toBeInstanceOf(PDFViewer)
})
it('initializes single-page viewer and disables text layer', async () => {
component.renderMode = PdfRenderMode.Single
component.selectable = false
await initComponent()
const viewer = (component as any).pdfViewer as PDFSinglePageViewer & {
options: Record<string, unknown>
}
expect(viewer).toBeInstanceOf(PDFSinglePageViewer)
expect(viewer.options.textLayerMode).toBe(0)
})
it('applies zoom, rotation, and page changes', async () => {
await initComponent()
const pageSpy = jest.fn()
component.pageChange.subscribe(pageSpy)
component.zoomScale = PdfZoomScale.PageFit
component.zoom = PdfZoomLevel.Two
component.rotation = 90
component.page = 2
component.ngOnChanges({
zoomScale: new SimpleChange(
PdfZoomScale.PageWidth,
PdfZoomScale.PageFit,
false
),
zoom: new SimpleChange(PdfZoomLevel.One, PdfZoomLevel.Two, false),
rotation: new SimpleChange(undefined, 90, false),
page: new SimpleChange(undefined, 2, false),
})
const viewer = (component as any).pdfViewer as PDFViewer
expect(viewer.pagesRotation).toBe(90)
expect(viewer.currentPageNumber).toBe(2)
expect(pageSpy).toHaveBeenCalledWith(2)
viewer.currentScale = 1
;(component as any).applyScale()
expect(viewer.currentScaleValue).toBe(PdfZoomScale.PageFit)
expect(viewer.currentScale).toBe(2)
const applyScaleSpy = jest.spyOn(component as any, 'applyScale')
component.page = 2
;(component as any).lastViewerPage = 2
;(component as any).applyViewerState()
expect((component as any).lastViewerPage).toBeUndefined()
expect(applyScaleSpy).toHaveBeenCalled()
})
it('dispatches find when search query changes after render', async () => {
await initComponent()
const eventBus = (component as any).eventBus as { dispatch: jest.Mock }
const dispatchSpy = jest.spyOn(eventBus, 'dispatch')
;(component as any).hasRenderedPage = true
component.searchQuery = 'needle'
component.ngOnChanges({
searchQuery: new SimpleChange('', 'needle', false),
})
expect(dispatchSpy).toHaveBeenCalledWith('find', {
query: 'needle',
caseSensitive: false,
highlightAll: true,
phraseSearch: true,
})
component.ngOnChanges({
searchQuery: new SimpleChange('needle', 'needle', false),
})
expect(dispatchSpy).toHaveBeenCalledTimes(1)
})
it('emits error when document load fails', async () => {
const errorSpy = jest.fn()
component.loadError.subscribe(errorSpy)
jest.spyOn(pdfjs, 'getDocument').mockImplementationOnce(() => {
return {
promise: Promise.reject(new Error('boom')),
destroy: jest.fn(),
} as any
})
await initComponent('bad.pdf')
expect(errorSpy).toHaveBeenCalled()
})
it('cleans up resources on destroy', async () => {
await initComponent()
const viewer = (component as any).pdfViewer as { cleanup: jest.Mock }
const loadingTask = (component as any).loadingTask as unknown as {
destroy: jest.Mock
}
const resizeObserver = (component as any).resizeObserver as unknown as {
disconnect: jest.Mock
}
const eventBus = (component as any).eventBus as { off: jest.Mock }
jest.spyOn(viewer, 'cleanup')
jest.spyOn(loadingTask, 'destroy')
jest.spyOn(resizeObserver, 'disconnect')
jest.spyOn(eventBus, 'off')
component.ngOnDestroy()
expect(eventBus.off).toHaveBeenCalledWith(
'pagerendered',
expect.any(Function)
)
expect(eventBus.off).toHaveBeenCalledWith('pagesinit', expect.any(Function))
expect(eventBus.off).toHaveBeenCalledWith(
'pagechanging',
expect.any(Function)
)
expect(resizeObserver.disconnect).toHaveBeenCalled()
expect(loadingTask.destroy).toHaveBeenCalled()
expect(viewer.cleanup).toHaveBeenCalled()
expect((component as any).pdfViewer).toBeUndefined()
})
it('skips work when viewer is missing or has no pages', () => {
const eventBus = (component as any).eventBus as { dispatch: jest.Mock }
const dispatchSpy = jest.spyOn(eventBus, 'dispatch')
;(component as any).dispatchFindIfReady()
expect(dispatchSpy).not.toHaveBeenCalled()
;(component as any).applyViewerState()
;(component as any).applyScale()
const viewer = new PDFViewer({ eventBus: undefined })
viewer.pagesCount = 0
;(component as any).pdfViewer = viewer
viewer.currentScale = 5
;(component as any).applyScale()
expect(viewer.currentScale).toBe(5)
})
it('returns early on src change in ngOnChanges', () => {
const loadSpy = jest.spyOn(component as any, 'loadDocument')
const initSpy = jest.spyOn(component as any, 'initViewer')
const scaleSpy = jest.spyOn(component as any, 'applyViewerState')
const resizeSpy = jest.spyOn(component as any, 'setupResizeObserver')
component.ngOnChanges({
src: new SimpleChange(undefined, 'test.pdf', true),
zoomScale: new SimpleChange(
PdfZoomScale.PageWidth,
PdfZoomScale.PageFit,
false
),
})
expect(loadSpy).toHaveBeenCalled()
expect(resizeSpy).not.toHaveBeenCalled()
expect(initSpy).not.toHaveBeenCalled()
expect(scaleSpy).not.toHaveBeenCalled()
})
it('applies viewer state after view init when already loaded', () => {
const applySpy = jest.spyOn(component as any, 'applyViewerState')
;(component as any).hasLoaded = true
;(component as any).pdf = { numPages: 1 }
fixture.detectChanges()
expect(applySpy).toHaveBeenCalled()
})
it('skips viewer state after view init when no pdf is available', () => {
const applySpy = jest.spyOn(component as any, 'applyViewerState')
;(component as any).hasLoaded = true
fixture.detectChanges()
expect(applySpy).not.toHaveBeenCalled()
})
it('does not reload when already loaded', async () => {
await initComponent()
const getDocumentSpy = jest.spyOn(pdfjs, 'getDocument')
const callCount = getDocumentSpy.mock.calls.length
await (component as any).loadDocument()
expect(getDocumentSpy).toHaveBeenCalledTimes(callCount)
})
it('runs applyScale on resize observer notifications', async () => {
await initComponent()
const applySpy = jest.spyOn(component as any, 'applyScale')
const resizeObserver = (component as any).resizeObserver as {
trigger: () => void
}
resizeObserver.trigger()
expect(applySpy).toHaveBeenCalled()
})
it('skips page work when no pages are available', async () => {
await initComponent()
const viewer = (component as any).pdfViewer as PDFViewer
viewer.pagesCount = 0
const applyScaleSpy = jest.spyOn(component as any, 'applyScale')
component.page = undefined
;(component as any).lastViewerPage = 1
;(component as any).applyViewerState()
expect(applyScaleSpy).not.toHaveBeenCalled()
expect((component as any).lastViewerPage).toBe(1)
})
it('falls back to a default zoom when input is invalid', async () => {
await initComponent()
const viewer = (component as any).pdfViewer as PDFViewer
viewer.currentScale = 3
component.zoom = 'not-a-number' as PdfZoomLevel
;(component as any).applyScale()
expect(viewer.currentScale).toBe(3)
})
it('re-initializes viewer on selectable or render mode changes', async () => {
await initComponent()
const initSpy = jest.spyOn(component as any, 'initViewer')
component.selectable = false
component.renderMode = PdfRenderMode.Single
component.ngOnChanges({
selectable: new SimpleChange(true, false, false),
renderMode: new SimpleChange(
PdfRenderMode.All,
PdfRenderMode.Single,
false
),
})
expect(initSpy).toHaveBeenCalled()
})
})

View File

@@ -1,266 +0,0 @@
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnDestroy,
Output,
SimpleChanges,
ViewChild,
} from '@angular/core'
import {
getDocument,
GlobalWorkerOptions,
PDFDocumentLoadingTask,
PDFDocumentProxy,
} from 'pdfjs-dist/legacy/build/pdf.mjs'
import {
EventBus,
PDFFindController,
PDFLinkService,
PDFSinglePageViewer,
PDFViewer,
} from 'pdfjs-dist/web/pdf_viewer.mjs'
import {
PdfRenderMode,
PdfSource,
PdfZoomLevel,
PdfZoomScale,
PngxPdfDocumentProxy,
} from './pdf-viewer.types'
@Component({
selector: 'pngx-pdf-viewer',
templateUrl: './pdf-viewer.component.html',
styleUrl: './pdf-viewer.component.scss',
})
export class PngxPdfViewerComponent
implements AfterViewInit, OnChanges, OnDestroy
{
@Input() src!: PdfSource
@Input() page?: number
@Output() pageChange = new EventEmitter<number>()
@Input() rotation?: number
@Input() renderMode: PdfRenderMode = PdfRenderMode.All
@Input() selectable = true
@Input() searchQuery = ''
@Input() zoom: PdfZoomLevel = PdfZoomLevel.One
@Input() zoomScale: PdfZoomScale = PdfZoomScale.PageWidth
@Output() afterLoadComplete = new EventEmitter<PngxPdfDocumentProxy>()
@Output() rendered = new EventEmitter<void>()
@Output() loadError = new EventEmitter<unknown>()
@ViewChild('container', { static: true })
private readonly container!: ElementRef<HTMLDivElement>
@ViewChild('viewer', { static: true })
private readonly viewer!: ElementRef<HTMLDivElement>
private hasLoaded = false
private loadingTask?: PDFDocumentLoadingTask
private resizeObserver?: ResizeObserver
private pdf?: PDFDocumentProxy
private pdfViewer?: PDFViewer | PDFSinglePageViewer
private hasRenderedPage = false
private lastFindQuery = ''
private lastViewerPage?: number
private readonly eventBus = new EventBus()
private readonly linkService = new PDFLinkService({ eventBus: this.eventBus })
private readonly findController = new PDFFindController({
eventBus: this.eventBus,
linkService: this.linkService,
updateMatchesCountOnProgress: false,
})
private readonly onPageRendered = () => {
this.hasRenderedPage = true
this.dispatchFindIfReady()
this.rendered.emit()
}
private readonly onPagesInit = () => this.applyScale()
private readonly onPageChanging = (evt: { pageNumber: number }) => {
// Avoid [(page)] two-way binding re-triggers navigation
this.lastViewerPage = evt.pageNumber
this.pageChange.emit(evt.pageNumber)
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['src']) {
this.hasLoaded = false
this.loadDocument()
return
}
if (changes['zoomScale']) {
this.setupResizeObserver()
}
if (changes['selectable'] || changes['renderMode']) {
this.initViewer()
}
if (
changes['page'] ||
changes['zoom'] ||
changes['zoomScale'] ||
changes['rotation']
) {
this.applyViewerState()
}
if (changes['searchQuery']) {
this.dispatchFindIfReady()
}
}
ngAfterViewInit(): void {
this.setupResizeObserver()
this.initViewer()
if (!this.hasLoaded) {
this.loadDocument()
return
}
if (this.pdf) {
this.applyViewerState()
}
}
ngOnDestroy(): void {
this.eventBus.off('pagerendered', this.onPageRendered)
this.eventBus.off('pagesinit', this.onPagesInit)
this.eventBus.off('pagechanging', this.onPageChanging)
this.resizeObserver?.disconnect()
this.loadingTask?.destroy()
this.pdfViewer?.cleanup()
this.pdfViewer = undefined
}
private async loadDocument(): Promise<void> {
if (this.hasLoaded) {
return
}
this.hasLoaded = true
this.hasRenderedPage = false
this.lastFindQuery = ''
this.loadingTask?.destroy()
GlobalWorkerOptions.workerSrc = '/assets/js/pdf.worker.min.mjs'
this.loadingTask = getDocument(this.src)
try {
const pdf = await this.loadingTask.promise
this.pdf = pdf
this.linkService.setDocument(pdf)
this.findController.onIsPageVisible = () => true
this.pdfViewer?.setDocument(pdf)
this.applyViewerState()
this.afterLoadComplete.emit(pdf)
} catch (err) {
this.loadError.emit(err)
}
}
private setupResizeObserver(): void {
this.resizeObserver?.disconnect()
this.resizeObserver = new ResizeObserver(() => {
this.applyScale()
})
this.resizeObserver.observe(this.container.nativeElement)
}
private initViewer(): void {
this.viewer.nativeElement.innerHTML = ''
this.pdfViewer?.cleanup()
this.hasRenderedPage = false
this.lastFindQuery = ''
const textLayerMode = this.selectable === false ? 0 : 1
const options = {
container: this.container.nativeElement,
viewer: this.viewer.nativeElement,
eventBus: this.eventBus,
linkService: this.linkService,
findController: this.findController,
textLayerMode,
removePageBorders: true,
}
this.pdfViewer =
this.renderMode === PdfRenderMode.Single
? new PDFSinglePageViewer(options)
: new PDFViewer(options)
this.linkService.setViewer(this.pdfViewer)
this.eventBus.off('pagerendered', this.onPageRendered)
this.eventBus.off('pagesinit', this.onPagesInit)
this.eventBus.off('pagechanging', this.onPageChanging)
this.eventBus.on('pagerendered', this.onPageRendered)
this.eventBus.on('pagesinit', this.onPagesInit)
this.eventBus.on('pagechanging', this.onPageChanging)
if (this.pdf) {
this.pdfViewer.setDocument(this.pdf)
this.applyViewerState()
}
}
private applyViewerState(): void {
if (!this.pdfViewer) {
return
}
const hasPages = this.pdfViewer.pagesCount > 0
if (typeof this.rotation === 'number' && hasPages) {
this.pdfViewer.pagesRotation = this.rotation
}
if (
typeof this.page === 'number' &&
hasPages &&
this.page !== this.lastViewerPage
) {
this.pdfViewer.currentPageNumber = this.page
}
if (this.page === this.lastViewerPage) {
this.lastViewerPage = undefined
}
if (hasPages) {
this.applyScale()
}
this.dispatchFindIfReady()
}
private applyScale(): void {
if (!this.pdfViewer) {
return
}
if (this.pdfViewer.pagesCount === 0) {
return
}
const zoomFactor = Number(this.zoom) || 1
this.pdfViewer.currentScaleValue = this.zoomScale
if (zoomFactor !== 1) {
this.pdfViewer.currentScale = this.pdfViewer.currentScale * zoomFactor
}
}
private dispatchFindIfReady(): void {
if (!this.hasRenderedPage) {
return
}
const query = this.searchQuery.trim()
if (query === this.lastFindQuery) {
return
}
this.lastFindQuery = query
this.eventBus.dispatch('find', {
query,
caseSensitive: false,
highlightAll: query.length > 0,
phraseSearch: true,
})
}
}

View File

@@ -1,25 +0,0 @@
export type PngxPdfDocumentProxy = {
numPages: number
}
export type PdfSource = string | { url: string; password?: string }
export enum PdfRenderMode {
Single = 'single',
All = 'all',
}
export enum PdfZoomScale {
PageFit = 'page-fit',
PageWidth = 'page-width',
}
export enum PdfZoomLevel {
Quarter = '.25',
Half = '.5',
ThreeQuarters = '.75',
One = '1',
OneAndHalf = '1.5',
Two = '2',
Three = '3',
}

View File

@@ -23,12 +23,14 @@
</div>
}
@if (!requiresPassword) {
<pngx-pdf-viewer
<pdf-viewer
[src]="previewUrl"
[renderMode]="PdfRenderMode.All"
[searchQuery]="documentService.searchQuery"
(loadError)="onError($event)">
</pngx-pdf-viewer>
[original-size]="false"
[show-borders]="false"
[show-all]="true"
(text-layer-rendered)="onPageRendered()"
(error)="onError($event)" #pdfViewer>
</pdf-viewer>
}
}
}

View File

@@ -12,7 +12,6 @@ import { of, throwError } from 'rxjs'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
import { DocumentService } from 'src/app/services/rest/document.service'
import { SettingsService } from 'src/app/services/settings.service'
import { PngxPdfViewerComponent } from '../pdf-viewer/pdf-viewer.component'
import { PreviewPopupComponent } from './preview-popup.component'
const doc = {
@@ -79,7 +78,7 @@ describe('PreviewPopupComponent', () => {
component.popover.open()
fixture.detectChanges()
expect(fixture.debugElement.query(By.css('object'))).toBeNull()
expect(fixture.debugElement.query(By.css('pngx-pdf-viewer'))).not.toBeNull()
expect(fixture.debugElement.query(By.css('pdf-viewer'))).not.toBeNull()
})
it('should show lock icon on password error', () => {
@@ -160,15 +159,23 @@ describe('PreviewPopupComponent', () => {
expect(component.popover.isOpen()).toBeFalsy()
})
it('should pass searchQuery to viewer', () => {
it('should dispatch find event on viewer loaded if searchQuery set', () => {
documentService.searchQuery = 'test'
settingsService.set(SETTINGS_KEYS.USE_NATIVE_PDF_VIEWER, false)
component.popover.open()
jest.advanceTimersByTime(1000)
fixture.detectChanges()
const viewer = fixture.debugElement.query(
By.directive(PngxPdfViewerComponent)
)
expect(viewer).not.toBeNull()
expect(viewer.componentInstance.searchQuery).toBe('test')
// normally setup by pdf-viewer
jest.replaceProperty(component.pdfViewer, 'eventBus', {
dispatch: jest.fn(),
} as any)
const dispatchSpy = jest.spyOn(component.pdfViewer.eventBus, 'dispatch')
component.onPageRendered()
expect(dispatchSpy).toHaveBeenCalledWith('find', {
query: 'test',
caseSensitive: false,
highlightAll: true,
phraseSearch: true,
})
})
})

View File

@@ -1,6 +1,7 @@
import { HttpClient } from '@angular/common/http'
import { Component, inject, Input, OnDestroy, ViewChild } from '@angular/core'
import { NgbPopover, NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap'
import { PdfViewerComponent, PdfViewerModule } from 'ng2-pdf-viewer'
import { NgxBootstrapIconsModule } from 'ngx-bootstrap-icons'
import { first, Subject, takeUntil } from 'rxjs'
import { Document } from 'src/app/data/document'
@@ -9,8 +10,6 @@ import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
import { SafeUrlPipe } from 'src/app/pipes/safeurl.pipe'
import { DocumentService } from 'src/app/services/rest/document.service'
import { SettingsService } from 'src/app/services/settings.service'
import { PngxPdfViewerComponent } from '../pdf-viewer/pdf-viewer.component'
import { PdfRenderMode } from '../pdf-viewer/pdf-viewer.types'
@Component({
selector: 'pngx-preview-popup',
@@ -19,15 +18,14 @@ import { PdfRenderMode } from '../pdf-viewer/pdf-viewer.types'
imports: [
NgbPopoverModule,
DocumentTitlePipe,
PngxPdfViewerComponent,
PdfViewerModule,
SafeUrlPipe,
NgxBootstrapIconsModule,
],
})
export class PreviewPopupComponent implements OnDestroy {
PdfRenderMode = PdfRenderMode
private settingsService = inject(SettingsService)
public readonly documentService = inject(DocumentService)
private documentService = inject(DocumentService)
private http = inject(HttpClient)
private _document: Document
@@ -63,6 +61,8 @@ export class PreviewPopupComponent implements OnDestroy {
@ViewChild('popover') popover: NgbPopover
@ViewChild('pdfViewer') pdfViewer: PdfViewerComponent
mouseOnPreview: boolean = false
popoverClass: string = 'shadow popover-preview'
@@ -114,6 +114,18 @@ export class PreviewPopupComponent implements OnDestroy {
}
}
onPageRendered() {
// Only triggered by the pngx pdf viewer
if (this.documentService.searchQuery) {
this.pdfViewer.eventBus.dispatch('find', {
query: this.documentService.searchQuery,
caseSensitive: false,
highlightAll: true,
phraseSearch: true,
})
}
}
mouseEnterPreview() {
this.mouseOnPreview = true
if (!this.popover.isOpen()) {

View File

@@ -5,12 +5,8 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'
import { By } from '@angular/platform-browser'
import { RouterTestingModule } from '@angular/router/testing'
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap'
import { allIcons, NgxBootstrapIconsModule } from 'ngx-bootstrap-icons'
import {
provideUiTour,
TourNgBootstrap,
TourService,
} from 'ngx-ui-tour-ng-bootstrap'
import { NgxBootstrapIconsModule, allIcons } from 'ngx-bootstrap-icons'
import { TourNgBootstrapModule, TourService } from 'ngx-ui-tour-ng-bootstrap'
import { of, throwError } from 'rxjs'
import { SavedView } from 'src/app/data/saved-view'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
@@ -79,7 +75,7 @@ describe('DashboardComponent', () => {
imports: [
NgbAlertModule,
RouterTestingModule,
TourNgBootstrap,
TourNgBootstrapModule,
DragDropModule,
NgxBootstrapIconsModule.pick(allIcons),
DashboardComponent,
@@ -115,7 +111,6 @@ describe('DashboardComponent', () => {
},
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
provideUiTour(),
],
}).compileComponents()

View File

@@ -8,7 +8,7 @@ import {
import { Component, inject } from '@angular/core'
import { RouterModule } from '@angular/router'
import { NgxBootstrapIconsModule } from 'ngx-bootstrap-icons'
import { TourNgBootstrap, TourService } from 'ngx-ui-tour-ng-bootstrap'
import { TourNgBootstrapModule, TourService } from 'ngx-ui-tour-ng-bootstrap'
import { SavedView } from 'src/app/data/saved-view'
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
import { SavedViewService } from 'src/app/services/rest/saved-view.service'
@@ -36,7 +36,7 @@ import { WelcomeWidgetComponent } from './widgets/welcome-widget/welcome-widget.
WelcomeWidgetComponent,
IfPermissionsDirective,
DragDropModule,
TourNgBootstrap,
TourNgBootstrapModule,
NgxBootstrapIconsModule,
RouterModule,
],

View File

@@ -9,7 +9,6 @@ import {
import { By } from '@angular/platform-browser'
import { RouterTestingModule } from '@angular/router/testing'
import { NgxBootstrapIconsModule, allIcons } from 'ngx-bootstrap-icons'
import { provideUiTour } from 'ngx-ui-tour-ng-bootstrap'
import { routes } from 'src/app/app-routing.module'
import { PermissionsGuard } from 'src/app/guards/permissions.guard'
import { PermissionsService } from 'src/app/services/permissions.service'
@@ -62,7 +61,6 @@ describe('UploadFileWidgetComponent', () => {
},
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
provideUiTour(),
],
}).compileComponents()

Some files were not shown because too many files have changed in this diff Show More