Skip to content

feat(PdfReader): simplify code improve performace#821

Merged
ArgoZhang merged 5 commits intomasterfrom
feat-pdf
Dec 13, 2025
Merged

feat(PdfReader): simplify code improve performace#821
ArgoZhang merged 5 commits intomasterfrom
feat-pdf

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Dec 13, 2025

Link issues

fixes #820

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Streamline PdfReader loading logic to handle URL and byte data sources more efficiently and cleanly reset viewer state.

Bug Fixes:

  • Ensure progress bar value is clamped to a maximum of 100% during PDF loading.
  • Reset cached stream length when switching back to URL-based PDFs to avoid stale state.
  • Prevent removal of the main pdfViewer element by clearing its content instead of deleting it.

Enhancements:

  • Remove intermediate Blob/ObjectURL creation in favor of passing raw byte data directly to the PDF loader.
  • Simplify resource cleanup by dropping unused ObjectURL tracking and revocation logic.
  • Improve PDF viewer DOM cleanup behavior when disposing or reloading PDFs.

Copilot AI review requested due to automatic review settings December 13, 2025 08:27
@bb-auto bb-auto Bot added the enhancement New feature or request label Dec 13, 2025
@bb-auto bb-auto Bot added this to the v9.2.0 milestone Dec 13, 2025
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Dec 13, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Refactors the PdfReader to load PDFs directly from URLs or raw data without intermediate object URLs, simplifies disposal and DOM cleanup, and makes minor safety and state-reset adjustments for progress reporting and stream tracking.

Sequence diagram for loading PDFs via URL or raw data

sequenceDiagram
    actor User
    participant BlazorComponent as PdfReaderComponent
    participant JSInterop
    participant PdfModule as PdfReaderJs
    participant PdfJs as PdfJsLibrary

    User->>BlazorComponent: Set Url or Data parameters
    BlazorComponent->>JSInterop: InvokeVoidAsync setUrl(Id, url) or setData(Id, data)
    JSInterop->>PdfModule: setUrl(id, url)
    activate PdfModule
    PdfModule->>PdfModule: pdf = Data.get(id)
    PdfModule->>PdfModule: options = pdf.options
    PdfModule->>PdfModule: options.url = url
    PdfModule->>PdfModule: options.data = null
    PdfModule->>PdfModule: loadPdf(pdf)
    deactivate PdfModule

    JSInterop->>PdfModule: setData(id, data)
    activate PdfModule
    PdfModule->>PdfModule: pdf = Data.get(id)
    PdfModule->>PdfModule: options = pdf.options
    PdfModule->>PdfModule: options.url = null
    PdfModule->>PdfModule: options.data = data
    PdfModule->>PdfModule: loadPdf(pdf)
    deactivate PdfModule

    PdfModule->>PdfJs: getDocument(options)
    activate PdfJs
    PdfJs-->>PdfModule: loadingTask
    PdfJs-->>PdfModule: pdfDocument
    deactivate PdfJs

    PdfModule->>PdfModule: pdf.pdfViewer.setDocument(pdfDocument)
    PdfModule-->>User: PDF rendered without intermediate object URLs
Loading

Sequence diagram for disposing the PdfReader and cleaning DOM

sequenceDiagram
    actor User
    participant BlazorComponent as PdfReaderComponent
    participant JSInterop
    participant PdfModule as PdfReaderJs
    participant Dom as BrowserDom

    User->>BlazorComponent: Dispose PdfReader
    BlazorComponent->>JSInterop: InvokeVoidAsync dispose(id)
    JSInterop->>PdfModule: disposePdf(pdf)
    activate PdfModule

    PdfModule->>PdfModule: el = pdf.el
    PdfModule->>PdfModule: observer = pdf.observer
    PdfModule->>PdfModule: loadingTask = pdf.loadingTask

    alt Has observer
        PdfModule->>PdfModule: observer.disconnect()
    end

    alt Has loadingTask
        PdfModule->>PdfModule: loadingTask.destroy()
    end

    PdfModule->>Dom: query .bb-view-container
    Dom-->>PdfModule: viewContainer

    loop For each child in viewContainer.children
        alt child has class pdfViewer
            PdfModule->>Dom: child.innerHTML = ""
        else
            PdfModule->>Dom: child.remove()
        end
    end

    PdfModule-->>JSInterop: PdfReader disposed without revoking object URLs
    deactivate PdfModule
Loading

Flow diagram for clamping PDF load progress value

flowchart TD
    A[Start progress update] --> B[Compute val = loaded / total * 100]
    B --> C[Clamp value using Math min of val and 100]
    C --> D[Set CSS variable --bb-view-progress-val to clamped value]
    D --> E[Schedule optional progressHandler timeout]
    E --> F[End progress update]
Loading

File-Level Changes

Change Details Files
Load PDFs directly from URL or raw byte data instead of using temporary Blob object URLs.
  • In setUrl, ensure any previously set data source is cleared by setting options.data to null before loading a new URL.
  • In setData, stop creating a Blob and object URL from the byte array and instead assign the raw data to options.data while clearing options.url.
  • Remove helper functions that created Blob-based object URLs from base64 or byte arrays, as they are no longer used.
src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js
Simplify and harden loading progress handling and PDF viewer disposal/cleanup.
  • Clamp the computed progress percentage using Math.min before applying it to the CSS variable to avoid values over 100%.
  • Simplify disposePdf by removing object URL revocation logic now that object URLs are no longer used.
  • Adjust DOM cleanup so the .pdfViewer element is kept but its inner HTML is cleared, while other child nodes are removed.
src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js
Reset internal stream tracking state when initializing with a URL after first render.
  • On first render when initializing with Url, reset _lastStreamHash to an empty string and _lastStreamLength to 0 before calling the JS setUrl helper.
src/components/BootstrapBlazor.PdfReader/PdfReader.razor.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#820 Simplify the PdfReader implementation code (especially around loading PDFs from URL/data and cleanup).
#820 Improve PdfReader performance and resource handling (progress calculation, memory/DOM handling, and stream state tracking).

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@ArgoZhang ArgoZhang merged commit f0e73cc into master Dec 13, 2025
6 of 7 checks passed
@ArgoZhang ArgoZhang deleted the feat-pdf branch December 13, 2025 08:27
Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • In setData, there’s a minor typo (options.data = data;;) that should be cleaned up to a single semicolon.
  • In loadPdf, consider guarding against total being zero or undefined before computing loaded / total * 100 to avoid NaN progress values when total length is not known.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `setData`, there’s a minor typo (`options.data = data;;`) that should be cleaned up to a single semicolon.
- In `loadPdf`, consider guarding against `total` being zero or undefined before computing `loaded / total * 100` to avoid `NaN` progress values when total length is not known.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR simplifies code and improves performance in the PdfReader component by eliminating unnecessary object URL creation/revocation when handling PDF data. The changes allow pdf.js to process byte arrays directly, reducing memory overhead and improving efficiency.

Key Changes:

  • Removed intermediate object URL creation when handling PDF byte data, passing data directly to pdf.js
  • Refactored disposal logic to clear pdfViewer content instead of removing the element entirely
  • Simplified progress bar value calculation using Math.min
  • Added proper state reset for _lastStreamLength when switching between URL and stream modes

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
PdfReader.razor.js Removed object URL helper functions, modified setData to pass byte arrays directly to pdf.js, simplified progress calculation, and improved disposal logic
PdfReader.razor.cs Added _lastStreamLength reset when URL changes to ensure proper state management
BootstrapBlazor.PdfReader.csproj Bumped version from 10.0.14 to 10.0.15
Comments suppressed due to low confidence (11)

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.cs:211

  • Equality checks on floating point values can yield unexpected results.
        if (_currentRotation != CurrentRotation)

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:206

  • Unused variable title.
    const title = el.querySelector('.bb-view-pdf-dialog-title');

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:207

  • Unused variable author.
    const author = el.querySelector('.bb-view-pdf-dialog-author');

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:208

  • Unused variable subject.
    const subject = el.querySelector('.bb-view-pdf-dialog-subject');

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:209

  • Unused variable keywords.
    const keywords = el.querySelector('.bb-view-pdf-dialog-keywords');

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:213

  • Unused variable modified.
    const modified = el.querySelector('.bb-view-pdf-dialog-modified');

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:233

  • Unused variable webview.
    const webview = el.querySelector('.bb-view-pdf-dialog-webview');

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:596

  • Unused variable scaleEl.
    const scaleEl = el.querySelector(".bb-view-scale-input");

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:697

  • The initial value of v is unused, since it is always overwritten.
    let v = 100;

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:516

  • Avoid automated semicolon insertion (95% of all statements in the enclosing function have an explicit semicolon).
    })

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:620

  • Avoid automated semicolon insertion (91% of all statements in the enclosing function have an explicit semicolon).
    delete el.widths

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

options.url = objectUrl;
options.data = null;
options.url = null;
options.data = data;;
Copy link

Copilot AI Dec 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is an extra semicolon at the end of this line. Remove one of the semicolons.

Suggested change
options.data = data;;
options.data = data;

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(PdfReader): simplify code improve performace

2 participants