-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add PdfReader component (#8991) #9078
Add PdfReader component (#8991) #9078
Conversation
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughThe changes introduce a new PDF viewer control, Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant BitPdfReader
participant PDFjs
User->>BitPdfReader: Load PDF Document
BitPdfReader->>PDFjs: Initialize PDF.js
PDFjs-->>BitPdfReader: Scripts Loaded
BitPdfReader->>PDFjs: Load PDF Document from URL
PDFjs-->>BitPdfReader: PDF Document Loaded
BitPdfReader->>User: Display PDF Pages
User->>BitPdfReader: Navigate to Next Page
BitPdfReader->>PDFjs: Render Next Page
PDFjs-->>BitPdfReader: Page Rendered
BitPdfReader->>User: Show Next Page
Assessment against linked issues
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Caution
Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.
🛑 Comments failed to post (112)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/murmurhash3.d.ts (1)
1-7: 🛠️ Refactor suggestion
Improve type safety and add documentation.
The type definitions could be more specific and better documented:
- The
any
types are too permissive and should be replaced with more specific types- Missing JSDoc documentation for the class and its members
Apply this diff to improve type safety and add documentation:
+/** + * MurmurHash3 is a non-cryptographic hash function optimized for fast hash computation + * This implementation provides the 64-bit variant of the algorithm + */ export class MurmurHash3_64 { - constructor(seed: any); + /** + * Creates a new instance of MurmurHash3_64 + * @param seed A numeric seed value for the hash + */ + constructor(seed: number); + /** First 32 bits of the 64-bit hash state */ h1: number; + /** Second 32 bits of the 64-bit hash state */ h2: number; - update(input: any): void; + /** + * Updates the hash state with new input + * @param input The input data (string or Uint8Array) + */ + update(input: string | Uint8Array): void; + /** + * Returns the final hash value as a hexadecimal string + * @returns A string containing the hexadecimal representation of the hash + */ hexdigest(): string; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./** * MurmurHash3 is a non-cryptographic hash function optimized for fast hash computation * This implementation provides the 64-bit variant of the algorithm */ export class MurmurHash3_64 { /** * Creates a new instance of MurmurHash3_64 * @param seed A numeric seed value for the hash */ constructor(seed: number); /** First 32 bits of the 64-bit hash state */ h1: number; /** Second 32 bits of the 64-bit hash state */ h2: number; /** * Updates the hash state with new input * @param input The input data (string or Uint8Array) */ update(input: string | Uint8Array): void; /** * Returns the final hash value as a hexadecimal string * @returns A string containing the hexadecimal representation of the hash */ hexdigest(): string; }
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/metadata.d.ts (1)
2-9: 🛠️ Refactor suggestion
Replace 'any' types with more specific types for better type safety.
The current implementation uses
any
type extensively, which bypasses TypeScript's type checking benefits. Consider using more specific types to improve type safety and developer experience.declare class Metadata { - constructor({ parsedData, rawData }: { - parsedData: any; - rawData: any; + constructor({ parsedData, rawData }: { + parsedData: Record<string, unknown>; + rawData: Record<string, unknown>; }); - getRaw(): any; - get(name: any): any; - getAll(): any; - has(name: any): any; + getRaw(): Record<string, unknown>; + get(name: string): unknown; + getAll(): Record<string, unknown>; + has(name: string): boolean; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.constructor({ parsedData, rawData }: { parsedData: Record<string, unknown>; rawData: Record<string, unknown>; }); getRaw(): Record<string, unknown>; get(name: string): unknown; getAll(): Record<string, unknown>; has(name: string): boolean;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/content_disposition.d.ts (1)
7-7: 💡 Codebase verification
⚠️ Potential issueFunction lacks security documentation and implementation details
The
getFilenameFromContentDispositionHeader
function is only defined as a type declaration without any implementation or security documentation. This is concerning because:
- The function is used for extracting filenames from HTTP headers, which is a common attack vector
- There's no documentation about security measures for handling malicious input
- No implementation was found in the codebase that shows security controls
- The type definition lacks return value documentation for error cases
Security considerations that should be documented:
- How invalid or malformed Content-Disposition headers are handled
- Sanitization of extracted filenames to prevent path traversal
- Maximum filename length restrictions
- Handling of special characters and encoding
🔗 Analysis chain
Document security considerations and error handling.
The function should document:
- How it handles potentially malicious filenames
- Path traversal prevention
- Behavior when the header is invalid or missing
Let's check if there are any security measures implemented in the codebase:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for security-related code in PDF reader implementation rg -g '!*.d.ts' -i 'content.?disposition|filename' ./src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/Length of output: 109
Script:
#!/bin/bash # Let's search for the implementation of the content disposition function rg -g '*.ts' -g '!*.d.ts' -g '!*.test.ts' -l "getFilenameFromContentDispositionHeader" ./ # Also search for any PDF-related file handling code rg -g '*.ts' -g '!*.d.ts' "filename.*pdf|pdf.*filename" ./ # Look for any security-related sanitization functions ast-grep --pattern 'function $_(filename: $_) { $$$ }'Length of output: 323
Script:
#!/bin/bash # Let's check the entire PdfReader directory structure and content find ./src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/ -type f -ls # Look for any JavaScript files that might contain the implementation rg -g '*.js' "getFilenameFromContentDispositionHeader" ./src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/ # Check if there's any implementation in the PDF.js source files fd -e js "pdf" ./src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/ --exec cat {}Length of output: 7463
Script:
#!/bin/bash # Let's examine the TypeScript and C# files for any security-related handling cat ./src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReader.ts cat ./src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReaderJsInterop.cs # Let's also check the content of the content_disposition.d.ts file cat ./src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/content_disposition.d.ts # Search for any security-related code in the entire codebase rg -i "sanitize|security|malicious|path.?traversal" ./src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/Length of output: 5896
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReader.razor (2)
8-8: 🛠️ Refactor suggestion
Add loading states and error boundaries for canvas elements.
The canvas elements should display loading indicators while PDF.js renders the content and handle rendering failures gracefully.
-<canvas @key="@($"{Config.Id}-{i+1}")" id="@($"{Config.Id}-{i+1}")" style="@CanvasStyle" class="@CanvasClass" /> +<div class="bit-pdr-page-container"> + <canvas @key="@($"{Config.Id}-{i+1}")" + id="@($"{Config.Id}-{i+1}")" + style="@CanvasStyle" + class="@CanvasClass" + aria-label="PDF page @(i+1)" + role="img" /> + @if (IsPageLoading(i+1)) + { + <div class="bit-pdr-loading">Loading page @(i+1)...</div> + } + @if (HasPageError(i+1)) + { + <div class="bit-pdr-error">Failed to render page @(i+1)</div> + } +</div>Also applies to: 13-13
3-3: 🛠️ Refactor suggestion
Consider adding role and aria-label attributes for accessibility.
The container div should have appropriate ARIA attributes to improve accessibility.
-<div style="@Style" class="bit-pdr @(Horizontal ? "bit-pdr-hor" : "") @Class"> +<div style="@Style" class="bit-pdr @(Horizontal ? "bit-pdr-hor" : "") @Class" role="document" aria-label="PDF document viewer">📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.<div style="@Style" class="bit-pdr @(Horizontal ? "bit-pdr-hor" : "") @Class" role="document" aria-label="PDF document viewer">
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/optional_content_config.d.ts (2)
6-11: 🛠️ Refactor suggestion
Improve type safety for visibility management methods.
The methods for managing visibility use
any
types extensively. Consider creating interfaces for the group and state objects to provide better type checking and IntelliSense support.- isVisible(group: any): any; - setVisibility(id: any, visible?: boolean): void; - setOCGState({ state, preserveRB }: { - state: any; - preserveRB: any; - }): void; + /** + * Checks if a content group is visible + * @param group The optional content group + * @returns Whether the group is visible + */ + isVisible(group: OptionalContentGroup): boolean; + /** + * Sets the visibility of a content group + * @param id The group identifier + * @param visible Optional visibility flag + */ + setVisibility(id: string, visible?: boolean): void; + /** + * Sets the state of optional content groups + * @param params The state configuration + */ + setOCGState({ state, preserveRB }: { + state: Record<string, boolean>; + preserveRB: boolean; + }): void;Consider adding these supporting interfaces:
interface OptionalContentGroup { id: string; name?: string; intent?: string[]; }
12-16: 🛠️ Refactor suggestion
Improve return types for getter methods.
The getter methods return
any
type which doesn't provide type information for consumers. Consider defining specific return types.get hasInitialVisibility(): boolean; - getOrder(): any; - getGroups(): any; - getGroup(id: any): any; + /** + * Gets the order of content groups + * @returns Array of group identifiers in order + */ + getOrder(): string[]; + /** + * Gets all content groups + * @returns Map of group identifiers to groups + */ + getGroups(): Map<string, OptionalContentGroup>; + /** + * Gets a specific content group + * @param id The group identifier + * @returns The content group if found + */ + getGroup(id: string): OptionalContentGroup | undefined; getHash(): string;src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/toolbar.d.ts (2)
13-17: 🛠️ Refactor suggestion
Add type safety and documentation for HighlightToolbar class.
The class needs proper typing and documentation to ensure correct usage.
Consider applying these improvements:
+ /** Toolbar for managing PDF text highlights */ declare class HighlightToolbar { - constructor(uiManager: any); - show(parent: any, boxes: any, isLTR: any): void; + constructor(uiManager: UIManager); + /** Shows the highlight toolbar + * @param parent The parent element to attach the toolbar to + * @param boxes The highlight box coordinates + * @param isLTR Whether the text direction is left-to-right + */ + show(parent: HTMLElement, boxes: HighlightBox[], isLTR: boolean): void; hide(): void; } + interface UIManager { + // Add relevant UI manager properties + } + interface HighlightBox { + x: number; + y: number; + width: number; + height: number; + }Committable suggestion skipped: line range outside the PR's diff.
1-12: 🛠️ Refactor suggestion
Improve type safety and add documentation for EditorToolbar class.
The class definition has several areas that could be improved:
- Replace
any
types with specific interfaces/types to ensure type safety- Add JSDoc comments to document the purpose and parameters of each method
- The
div
getter returningnull
seems suspicious and might indicate incomplete implementationConsider applying these improvements:
+ /** Editor toolbar for managing PDF annotations and edits */ declare class EditorToolbar { - static "__#4@#l10nRemove": null; - static "__#4@#pointerDown"(e: any): void; - constructor(editor: any); + static "__#4@#l10nRemove": null; + static "__#4@#pointerDown"(e: PointerEvent): void; + constructor(editor: PDFEditor); + /** Renders the toolbar and returns its container element */ render(): HTMLDivElement; - get div(): null; + /** Returns the toolbar's container element */ + get div(): HTMLDivElement | null; + /** Hides the toolbar */ hide(): void; + /** Shows the toolbar */ show(): void; - addAltText(altText: any): Promise<void>; - addColorPicker(colorPicker: any): void; + /** Adds alternative text to the selected element + * @param altText The alternative text configuration + */ + addAltText(altText: AltTextConfig): Promise<void>; + /** Adds a color picker to the toolbar + * @param colorPicker The color picker configuration + */ + addColorPicker(colorPicker: ColorPickerConfig): void; + /** Removes the toolbar */ remove(): void; } + interface PDFEditor { + // Add relevant editor properties + } + interface AltTextConfig { + // Add alt text configuration properties + } + interface ColorPickerConfig { + // Add color picker configuration properties + }Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/image_utils.d.ts (3)
17-17: 🛠️ Refactor suggestion
Improve type safety and documentation for grayscale conversion function.
The function parameters should use typed arrays instead of
any
for better type safety.+/** + * Converts grayscale image data to RGBA format + * @param src Source grayscale data + * @param dest Destination buffer for RGBA data + */ -export function grayToRGBA(src: any, dest: any): void; +export function grayToRGBA(src: Uint8Array | Uint8ClampedArray, dest: Uint8ClampedArray): void;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./** * Converts grayscale image data to RGBA format * @param src Source grayscale data * @param dest Destination buffer for RGBA data */ export function grayToRGBA(src: Uint8Array | Uint8ClampedArray, dest: Uint8ClampedArray): void;
13-16: 🛠️ Refactor suggestion
Document parameters and improve type safety for the generic converter.
The function uses a generic
params: any
which makes it difficult to understand the expected input. Consider:
- Adding JSDoc comments to document the expected parameter structure
- Creating a proper interface for the params object
+/** + * Converts image data to RGBA format + * @param params Configuration object containing source data and conversion options + * @returns Object with source and destination positions, or null if conversion fails + */ +interface ConversionParams { + src: Uint8Array | Uint8ClampedArray; + dest: Uint8ClampedArray; + width: number; + height: number; + // Add other relevant parameters +} -export function convertToRGBA(params: any): { +export function convertToRGBA(params: ConversionParams): { srcPos: number; destPos: number; } | null;Committable suggestion skipped: line range outside the PR's diff.
1-12: 🛠️ Refactor suggestion
Strengthen type safety by replacing
any
types with more specific types.The function parameters use
any
type which reduces type safety. Consider using more specific types:export function convertBlackAndWhiteToRGBA({ src, srcPos, dest, width, height, nonBlackColor, inverseDecode, }: { - src: any; + src: Uint8Array | Uint8ClampedArray; srcPos?: number | undefined; - dest: any; + dest: Uint8ClampedArray; - width: any; + width: number; - height: any; + height: number; nonBlackColor?: number | undefined; inverseDecode?: boolean | undefined; }): { srcPos: number; destPos: number; };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.export function convertBlackAndWhiteToRGBA({ src, srcPos, dest, width, height, nonBlackColor, inverseDecode, }: { src: Uint8Array | Uint8ClampedArray; srcPos?: number | undefined; dest: Uint8ClampedArray; width: number; height: number; nonBlackColor?: number | undefined; inverseDecode?: boolean | undefined; }): { srcPos: number; destPos: number; };
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/network_utils.d.ts (1)
1-13:
⚠️ Potential issueImprove type safety by avoiding
any
types.The extensive use of
any
type defeats TypeScript's purpose of providing type safety. This can lead to runtime errors and makes it harder to catch issues during development.Apply this diff to improve type safety:
-declare function createHeaders(isHttp: any, httpHeaders: any): Headers; -declare function createResponseStatusError(status: any, url: any): MissingPDFException | UnexpectedResponseException; -declare function extractFilenameFromHeader(responseHeaders: any): string | null; -declare function validateRangeRequestCapabilities({ responseHeaders, isHttp, rangeChunkSize, disableRange, }: { - responseHeaders: any; - isHttp: any; - rangeChunkSize: any; - disableRange: any; +declare function createHeaders(isHttp: boolean, httpHeaders: Record<string, string>): Headers; +declare function createResponseStatusError(status: number, url: string): MissingPDFException | UnexpectedResponseException; +declare function extractFilenameFromHeader(responseHeaders: Headers): string | null; +declare function validateRangeRequestCapabilities({ responseHeaders, isHttp, rangeChunkSize, disableRange, }: { + responseHeaders: Headers; + isHttp: boolean; + rangeChunkSize: number; + disableRange: boolean; }): { allowRangeRequests: boolean; suggestedLength: undefined; }; -declare function validateResponseStatus(status: any): boolean; +declare function validateResponseStatus(status: number): boolean;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare function createHeaders(isHttp: boolean, httpHeaders: Record<string, string>): Headers; declare function createResponseStatusError(status: number, url: string): MissingPDFException | UnexpectedResponseException; declare function extractFilenameFromHeader(responseHeaders: Headers): string | null; declare function validateRangeRequestCapabilities({ responseHeaders, isHttp, rangeChunkSize, disableRange, }: { responseHeaders: Headers; isHttp: boolean; rangeChunkSize: number; disableRange: boolean; }): { allowRangeRequests: boolean; suggestedLength: undefined; }; declare function validateResponseStatus(status: number): boolean;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/node_utils.d.ts (1)
15-18: 🛠️ Refactor suggestion
Refactor static class to standalone functions with improved types.
The static-only class should be replaced with standalone functions for better maintainability and type safety.
-declare class NodePackages { - static get promise(): any; - static get(name: any): any; -} +declare function getNodePackagePromise(): Promise<unknown>; +declare function getNodePackage(name: string): unknown;Consider adding more specific return types based on the expected package types.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare function getNodePackagePromise(): Promise<unknown>; declare function getNodePackage(name: string): unknown;
🧰 Tools
🪛 Biome
[error] 15-18: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/color_picker.d.ts (3)
10-14: 🛠️ Refactor suggestion
Improve type safety of keyboard event handlers.
The keyboard navigation methods use
any
type for events, which loses type checking benefits.Consider using proper event types:
-_colorSelectFromKeyboard(event: any): void; -_moveToNext(event: any): void; -_moveToPrevious(event: any): void; -_moveToBeginning(event: any): void; -_moveToEnd(event: any): void; +_colorSelectFromKeyboard(event: KeyboardEvent): void; +_moveToNext(event: KeyboardEvent): void; +_moveToPrevious(event: KeyboardEvent): void; +_moveToBeginning(event: KeyboardEvent): void; +_moveToEnd(event: KeyboardEvent): void;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements._colorSelectFromKeyboard(event: KeyboardEvent): void; _moveToNext(event: KeyboardEvent): void; _moveToPrevious(event: KeyboardEvent): void; _moveToBeginning(event: KeyboardEvent): void; _moveToEnd(event: KeyboardEvent): void;
17-17: 🛠️ Refactor suggestion
Add type safety to color parameter.
The
updateColor
method acceptsany
type for the color parameter, which could lead to runtime errors.Consider defining a proper color type:
-updateColor(color: any): void; +type ColorValue = string | { r: number; g: number; b: number; a?: number }; +updateColor(color: ColorValue): void;Committable suggestion skipped: line range outside the PR's diff.
2-3: 🛠️ Refactor suggestion
Improve type safety and clarity of static members.
The static property name
"__#24@#l10nColor"
appears to be a mangled private field name. Additionally, the_keyboardManager
getter lacks a specific return type.Consider this improvement:
-static "__#24@#l10nColor": null; -static get _keyboardManager(): any; +private static readonly l10nColor: null; +static get keyboardManager(): KeyboardManager;Note: You'll need to define or import the
KeyboardManager
type.Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReaderConfig.cs (2)
15-18: 🛠️ Refactor suggestion
Add validation for Scale property
The Scale property should include validation to prevent negative or zero values which could cause rendering issues.
/// <summary> /// The scale in which the pdf document gets rendered on the page. /// </summary> - public double Scale { get; set; } = 1; + private double _scale = 1; + public double Scale + { + get => _scale; + set + { + if (value <= 0) + throw new ArgumentException("Scale must be greater than 0", nameof(value)); + _scale = value; + } + }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./// <summary> /// The scale in which the pdf document gets rendered on the page. /// </summary> private double _scale = 1; public double Scale { get => _scale; set { if (value <= 0) throw new ArgumentException("Scale must be greater than 0", nameof(value)); _scale = value; } }
10-13:
⚠️ Potential issueAdd URL validation and security considerations
The URL property should include validation to:
- Ensure it's not null/empty
- Validate it's a well-formed URL
- Consider restricting to specific schemes (http/https) or domains for security
/// <summary> /// The URL of the pdf file. /// </summary> - public string Url { get; set; } + private string _url; + public string Url + { + get => _url; + set + { + if (string.IsNullOrWhiteSpace(value)) + throw new ArgumentException("URL cannot be null or empty", nameof(value)); + + if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) + throw new ArgumentException("Invalid URL format", nameof(value)); + + if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) + throw new ArgumentException("URL must use HTTP or HTTPS scheme", nameof(value)); + + _url = value; + } + }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./// <summary> /// The URL of the pdf file. /// </summary> private string _url; public string Url { get => _url; set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("URL cannot be null or empty", nameof(value)); if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) throw new ArgumentException("Invalid URL format", nameof(value)); if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) throw new ArgumentException("URL must use HTTP or HTTPS scheme", nameof(value)); _url = value; } }
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/xfa_text.d.ts (1)
3-12: 🛠️ Refactor suggestion
Improve type safety by specifying the XFA object structure.
The
Object
type is too broad and doesn't provide type safety. Consider defining an interface that describes the expected XFA DOM structure.interface XfaNode { name: string; children?: XfaNode[]; value?: string; // Add other relevant XFA node properties } /** * Walk an XFA tree and create an array of text nodes that is compatible * with a regular PDFs TextContent. Currently, only TextItem.str is supported, * all other fields and styles haven't been implemented. * * @param {XfaNode} xfa - An XFA fake DOM object representing the XML Forms Architecture tree. * @returns {TextContent} */ static textContent(xfa: XfaNode): TextContent;🧰 Tools
🪛 Biome
[error] 12-12: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/scripting_utils.d.ts (2)
2-15: 🛠️ Refactor suggestion
Improve type safety by replacing
any
with specific types.The extensive use of
any
type reduces type safety. Consider using more specific types for color components and return values.Examples of type improvements:
// For RGB values (0-255) type RGBComponent = number; type RGBTuple = [RGBComponent, RGBComponent, RGBComponent]; // For CMYK values (0-100) type CMYKComponent = number; type CMYKTuple = [CMYKComponent, CMYKComponent, CMYKComponent, CMYKComponent]; // For method signatures static CMYK_G(color: CMYKTuple): [number]; static RGB_HTML(color: RGBTuple): string;
1-16: 🛠️ Refactor suggestion
Refactor static class into standalone functions for better maintainability.
The current implementation as a static-only class could be improved by converting it to a module with standalone functions, following TypeScript best practices.
Here's a suggested refactoring:
-export class ColorConverters { - static CMYK_G([c, y, m, k]: [any, any, any, any]): (string | number)[]; - static G_CMYK([g]: [any]): (string | number)[]; - // ... other methods -} +// Define specific types for color values +type ColorComponent = number; +type CMYKColor = [ColorComponent, ColorComponent, ColorComponent, ColorComponent]; +type RGBColor = [ColorComponent, ColorComponent, ColorComponent]; +type GrayscaleColor = [ColorComponent]; + +export function cmykToGrayscale([c, m, y, k]: CMYKColor): GrayscaleColor; +export function grayscaleToCMYK([g]: GrayscaleColor): CMYKColor; +export function grayscaleToRGB([g]: GrayscaleColor): RGBColor; +// ... other functionsCommittable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 1-16: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReaderJsInterop.cs (4)
5-8: 🛠️ Refactor suggestion
Add parameter validation and extract JavaScript function names.
The method should validate the
scripts
parameter and use constants for JavaScript function names.+ private const string JS_NAMESPACE = "BitBlazorUI.BitPdfReader"; + public static ValueTask BitPdfReaderInitPdfJs(this IJSRuntime jsRuntime, IEnumerable<string> scripts) { + ArgumentNullException.ThrowIfNull(jsRuntime); + ArgumentNullException.ThrowIfNull(scripts); + - return jsRuntime.InvokeVoidAsync("BitBlazorUI.BitPdfReader.init", scripts); + return jsRuntime.InvokeVoidAsync($"{JS_NAMESPACE}.init", scripts); }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.private const string JS_NAMESPACE = "BitBlazorUI.BitPdfReader"; public static ValueTask BitPdfReaderInitPdfJs(this IJSRuntime jsRuntime, IEnumerable<string> scripts) { ArgumentNullException.ThrowIfNull(jsRuntime); ArgumentNullException.ThrowIfNull(scripts); return jsRuntime.InvokeVoidAsync($"{JS_NAMESPACE}.init", scripts); }
15-18: 🛠️ Refactor suggestion
Add parameter validation for id and pageNumber.
The method should validate both parameters to prevent invalid inputs.
public static ValueTask BitPdfReaderRenderPage(this IJSRuntime jsRuntime, string id, int pageNumber) { + ArgumentNullException.ThrowIfNull(jsRuntime); + ArgumentException.ThrowIfNullOrEmpty(id); + if (pageNumber <= 0) throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number must be positive."); + - return jsRuntime.InvokeVoidAsync("BitBlazorUI.BitPdfReader.renderPage", id, pageNumber); + return jsRuntime.InvokeVoidAsync($"{JS_NAMESPACE}.renderPage", id, pageNumber); }Committable suggestion skipped: line range outside the PR's diff.
10-13: 🛠️ Refactor suggestion
Add parameter validation, error handling, and document the return value.
The method needs proper validation and should handle potential JavaScript exceptions. Additionally, the purpose of the returned integer should be documented.
+ /// <summary> + /// Sets up the PDF document with the specified configuration. + /// </summary> + /// <param name="jsRuntime">The JS runtime instance.</param> + /// <param name="config">The PDF reader configuration.</param> + /// <returns>The total number of pages in the PDF document.</returns> + /// <exception cref="ArgumentNullException">Thrown when jsRuntime or config is null.</exception> public static ValueTask<int> BitPdfReaderSetupPdfDoc(this IJSRuntime jsRuntime, BitPdfReaderConfig config) { - return jsRuntime.InvokeAsync<int>("BitBlazorUI.BitPdfReader.setup", config); + ArgumentNullException.ThrowIfNull(jsRuntime); + ArgumentNullException.ThrowIfNull(config); + + return jsRuntime.InvokeAsync<int>($"{JS_NAMESPACE}.setup", config); }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./// <summary> /// Sets up the PDF document with the specified configuration. /// </summary> /// <param name="jsRuntime">The JS runtime instance.</param> /// <param name="config">The PDF reader configuration.</param> /// <returns>The total number of pages in the PDF document.</returns> /// <exception cref="ArgumentNullException">Thrown when jsRuntime or config is null.</exception> public static ValueTask<int> BitPdfReaderSetupPdfDoc(this IJSRuntime jsRuntime, BitPdfReaderConfig config) { ArgumentNullException.ThrowIfNull(jsRuntime); ArgumentNullException.ThrowIfNull(config); return jsRuntime.InvokeAsync<int>($"{JS_NAMESPACE}.setup", config); }
20-23: 🛠️ Refactor suggestion
Add parameter validation and clarify method purpose.
The method needs validation and its distinct purpose from
BitPdfReaderRenderPage
should be documented.+ /// <summary> + /// Refreshes an existing PDF page with updated configuration settings. + /// </summary> + /// <param name="jsRuntime">The JS runtime instance.</param> + /// <param name="config">The updated PDF reader configuration.</param> + /// <param name="pageNumber">The page number to refresh.</param> public static ValueTask BitPdfReaderRefreshPage(this IJSRuntime jsRuntime, BitPdfReaderConfig config, int pageNumber) { + ArgumentNullException.ThrowIfNull(jsRuntime); + ArgumentNullException.ThrowIfNull(config); + if (pageNumber <= 0) throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number must be positive."); + - return jsRuntime.InvokeVoidAsync("BitBlazorUI.BitPdfReader.refreshPage", config, pageNumber); + return jsRuntime.InvokeVoidAsync($"{JS_NAMESPACE}.refreshPage", config, pageNumber); }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./// <summary> /// Refreshes an existing PDF page with updated configuration settings. /// </summary> /// <param name="jsRuntime">The JS runtime instance.</param> /// <param name="config">The updated PDF reader configuration.</param> /// <param name="pageNumber">The page number to refresh.</param> public static ValueTask BitPdfReaderRefreshPage(this IJSRuntime jsRuntime, BitPdfReaderConfig config, int pageNumber) { ArgumentNullException.ThrowIfNull(jsRuntime); ArgumentNullException.ThrowIfNull(config); if (pageNumber <= 0) throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number must be positive."); return jsRuntime.InvokeVoidAsync($"{JS_NAMESPACE}.refreshPage", config, pageNumber); }
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/alt_text.d.ts (1)
22-29:
⚠️ Potential issueFix inconsistency between data getter and setter types.
The data accessor methods have mismatched types and incomplete parameter definitions:
+ interface AltTextData { + altText: string | null; + decorative: boolean; + guessedText?: string | null; + textWithDisclaimer?: string | null; + cancel?: boolean; + } - set data({ altText, decorative, guessedText, textWithDisclaimer, cancel, }: { - altText: null; - decorative: boolean; - }); - get data(): { - altText: null; - decorative: boolean; - }; + set data(value: AltTextData); + get data(): AltTextData;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.interface AltTextData { altText: string | null; decorative: boolean; guessedText?: string | null; textWithDisclaimer?: string | null; cancel?: boolean; } set data(value: AltTextData); get data(): AltTextData;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/xfa_layer.d.ts (2)
1-11: 🛠️ Refactor suggestion
Strengthen type definitions for better type safety.
The type definition could be improved in several ways:
- Replace
Object
with a more specific type forxfaHtml
- Consider using a string literal type for
intent
to enforce valid valuesConsider applying these changes:
declare type XfaLayerParameters = { viewport: PageViewport; div: HTMLDivElement; - xfaHtml: Object; + xfaHtml: Record<string, unknown>; annotationStorage?: AnnotationStorage | undefined; linkService: IPDFLinkService; /** * - (default value is 'display'). */ - intent?: string | undefined; + intent?: 'display' | 'print' | undefined; };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare type XfaLayerParameters = { viewport: PageViewport; div: HTMLDivElement; xfaHtml: Record<string, unknown>; annotationStorage?: AnnotationStorage | undefined; linkService: IPDFLinkService; /** * - (default value is 'display'). */ intent?: 'display' | 'print' | undefined; };
🧰 Tools
🪛 Biome
[error] 4-4: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
21-44: 🛠️ Refactor suggestion
Convert static-only class to standalone functions with proper typing.
The current implementation has several issues:
- The class contains only static methods, which is an anti-pattern in TypeScript
- Extensive use of
any
types reduces type safety- Some parameters lack proper typing
Consider refactoring to standalone functions with proper typing:
-declare class XfaLayer { - static setupStorage(html: any, id: any, element: any, storage: any, intent: any): void; - static setAttributes({ html, element, storage, intent, linkService }: { - html: any; - element: any; - storage?: null | undefined; - intent: any; - linkService: any; - }): void; - static render(parameters: XfaLayerParameters): { - textDivs: Text[]; - }; - static update(parameters: XfaLayerParameters): void; -} +interface XfaAttributes { + html: HTMLElement; + element: HTMLElement; + storage?: AnnotationStorage | null; + intent: 'display' | 'print'; + linkService: IPDFLinkService; +} + +declare function setupXfaStorage( + html: HTMLElement, + id: string, + element: HTMLElement, + storage: AnnotationStorage, + intent: 'display' | 'print' +): void; + +declare function setXfaAttributes(attributes: XfaAttributes): void; + +declare function renderXfaLayer(parameters: XfaLayerParameters): { + textDivs: Text[]; +}; + +declare function updateXfaLayer(parameters: XfaLayerParameters): void;This refactoring:
- Converts static methods to standalone functions
- Introduces proper typing for parameters
- Creates a dedicated interface for attributes
- Uses string literal types for intent
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 21-44: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/draw_layer.d.ts (3)
14-17: 🛠️ Refactor suggestion
Add proper typing for pageIndex.
The
any
type for pageIndex reduces type safety. Since this represents a page number, it should be typed as a number:constructor({ pageIndex }: { - pageIndex: any; + pageIndex: number; }); - pageIndex: any; + readonly pageIndex: number;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.constructor({ pageIndex }: { pageIndex: number; }); readonly pageIndex: number;
18-37: 🛠️ Refactor suggestion
Add proper typing and documentation for instance methods.
The methods need proper TypeScript types and JSDoc documentation:
+ /** Sets the parent element for the SVG container */ - setParent(parent: any): void; + setParent(parent: HTMLElement): void; + /** + * Creates a highlight overlay on the page + * @param outlines Array of point coordinates defining the highlight area + * @param color CSS color value + * @param opacity Opacity value between 0 and 1 + * @param isPathUpdatable Whether the path can be updated later + * @returns Object containing the highlight ID and clipPath ID + */ - highlight(outlines: any, color: any, opacity: any, isPathUpdatable?: boolean): { - id: number; - clipPathId: string; - }; + highlight( + outlines: Array<{ x: number; y: number }>, + color: string, + opacity: number, + isPathUpdatable?: boolean + ): { + id: number; + clipPathId: string; + }; + /** Updates the visibility of an SVG element */ - show(id: any, visible: any): void; + show(id: number, visible: boolean): void; // Continue with similar improvements for other methods...Consider creating appropriate interfaces for complex parameters and return types.
Committable suggestion skipped: line range outside the PR's diff.
7-13: 🛠️ Refactor suggestion
Improve type safety and use proper TypeScript features.
Several improvements can be made to the static members:
+interface Box { + x?: number; + y?: number; + width?: number; + height?: number; +} + +interface SVGFactory { + create(type: string): SVGElement; + // Add other required methods +} declare class DrawLayer { - static get _svgFactory(): any; + static get _svgFactory(): SVGFactory; - static "__#28@#setBox"(element: any, { x, y, width, height }?: { - x?: number | undefined; - y?: number | undefined; - width?: number | undefined; - height?: number | undefined; - }): void; + private static setBox(element: SVGElement, box?: Box): void;Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/stamp.d.ts (3)
5-20: 🛠️ Refactor suggestion
Improve type safety in static methods
The static methods use
any
types extensively, which reduces type safety. Consider defining proper interfaces for the parameters and return types.Suggested improvements:
interface L10n { // Add localization-related properties } interface UiManager { // Add UI management properties } interface PasteItem { // Add paste-related properties } interface TelemetryData { hasAltText: boolean; hasNoAltText: boolean; } declare class StampEditor extends AnnotationEditor { static initialize(l10n: L10n, uiManager: UiManager): void; static isHandlingMimeForPasting(mime: string): boolean; static paste(item: PasteItem, parent: AnnotationEditor): void; static computeTelemetryFinalData(data: unknown): TelemetryData; // ... rest of the methods }
41-41: 🛠️ Refactor suggestion
Replace Object return type with a specific interface
Using
Object
as a return type provides minimal type safety and was flagged by static analysis.Define an interface for the serialized data:
interface SerializedStampData { // Add properties that represent the serialized stamp type: string; // Add other relevant properties } // Then update the method signature: serialize(isForCopying?: boolean, context?: null): SerializedStampData | null;🧰 Tools
🪛 Biome
[error] 41-41: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
1-4:
⚠️ Potential issueClarify the class purpose in documentation
There's an inconsistency between the class name
StampEditor
and its documentation which describes it as a "Basic text editor" for "FreeTex annotation". This could lead to confusion about the component's actual purpose.Please clarify whether this is intended for:
- Stamp annotations
- Free text annotations
- Both functionalities
If it's for stamps, update the documentation:
-* Basic text editor in order to create a FreeTex annotation. +* Editor component for creating and managing stamp annotations.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./** * Editor component for creating and managing stamp annotations. */ declare class StampEditor extends AnnotationEditor {
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/base_factory.d.ts (5)
52-59:
⚠️ Potential issueFix SVG factory return types and improve type safety
The SVG factory methods incorrectly return void and use
any
types.Apply this diff to fix return types and improve type safety:
declare class BaseSVGFactory { - create(width: any, height: any, skipDimensions?: boolean): void; + create(width: number, height: number, skipDimensions?: boolean): SVGSVGElement; - createElement(type: any): void; + createElement(type: 'svg' | 'path' | 'rect' | 'circle' | 'g'): SVGElement; /** * @ignore */ - _createSVG(type: any): void; + _createSVG(type: 'svg' | 'path' | 'rect' | 'circle' | 'g'): SVGElement; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseSVGFactory { create(width: number, height: number, skipDimensions?: boolean): SVGSVGElement; createElement(type: 'svg' | 'path' | 'rect' | 'circle' | 'g'): SVGElement; /** * @ignore */ _createSVG(type: 'svg' | 'path' | 'rect' | 'circle' | 'g'): SVGElement; }
39-51: 🛠️ Refactor suggestion
Improve type safety for font data factory
The font data factory uses
any
types which reduces type safety.Apply this diff to improve type definitions:
declare class BaseStandardFontDataFactory { constructor({ baseUrl }: { - baseUrl?: null | undefined; + baseUrl?: string | null; }); - baseUrl: any; + baseUrl: string | null; - fetch({ filename }: { - filename: any; - }): Promise<any>; + fetch({ filename }: { filename: string }): Promise<Uint8Array>; /** * @ignore */ - _fetchData(url: any): void; + _fetchData(url: string): Promise<Uint8Array>; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseStandardFontDataFactory { constructor({ baseUrl }: { baseUrl?: string | null; }); baseUrl: string | null; fetch({ filename }: { filename: string }): Promise<Uint8Array>; /** * @ignore */ _fetchData(url: string): Promise<Uint8Array>; }
16-30: 🛠️ Refactor suggestion
Improve type safety for CMap reader factory
The current implementation uses
any
types which reduces type safety and IDE support.Apply this diff to improve type definitions:
declare class BaseCMapReaderFactory { constructor({ baseUrl, isCompressed }: { - baseUrl?: null | undefined; + baseUrl?: string | null; isCompressed?: boolean | undefined; }); - baseUrl: any; + baseUrl: string | null; isCompressed: boolean; - fetch({ name }: { - name: any; - }): Promise<any>; + fetch({ name }: { name: string }): Promise<Uint8Array>; /** * @ignore */ - _fetchData(url: any, compressionType: any): void; + _fetchData(url: string, compressionType: string): Promise<Uint8Array>; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseCMapReaderFactory { constructor({ baseUrl, isCompressed }: { baseUrl?: string | null; isCompressed?: boolean | undefined; }); baseUrl: string | null; isCompressed: boolean; fetch({ name }: { name: string }): Promise<Uint8Array>; /** * @ignore */ _fetchData(url: string, compressionType: string): Promise<Uint8Array>; }
1-15:
⚠️ Potential issueFix return type for canvas creation and improve type safety
The current implementation has several type-related issues:
- The
canvas
property in thecreate()
method's return type is incorrectly typed asvoid
- Extensive use of
any
type reduces type safetyApply this diff to fix the types:
declare class BaseCanvasFactory { constructor({ enableHWA }: { enableHWA?: boolean | undefined; }); - create(width: any, height: any): { - canvas: void; - context: any; + create(width: number, height: number): { + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; }; - reset(canvasAndContext: any, width: any, height: any): void; - destroy(canvasAndContext: any): void; + reset(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }, + width: number, height: number): void; + destroy(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }): void; /** * @ignore */ - _createCanvas(width: any, height: any): void; + _createCanvas(width: number, height: number): HTMLCanvasElement; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseCanvasFactory { constructor({ enableHWA }: { enableHWA?: boolean | undefined; }); create(width: number, height: number): { canvas: HTMLCanvasElement; context: CanvasRenderingContext2D; }; reset(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }, width: number, height: number): void; destroy(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }): void; /** * @ignore */ _createCanvas(width: number, height: number): HTMLCanvasElement; }
🧰 Tools
🪛 Biome
[error] 6-6: void is confusing outside a return type or a type parameter.
Unsafe fix: Use undefined instead.
(lint/suspicious/noConfusingVoidType)
31-38: 🛠️ Refactor suggestion
Add proper type definitions for filter operations
The filter factory lacks proper type definitions for colors and filter maps.
Apply this diff to add proper types:
declare class BaseFilterFactory { - addFilter(maps: any): string; + addFilter(maps: Record<string, number[]>): string; - addHCMFilter(fgColor: any, bgColor: any): string; + addHCMFilter(fgColor: [number, number, number], bgColor: [number, number, number]): string; - addAlphaFilter(map: any): string; + addAlphaFilter(map: number[]): string; - addLuminosityFilter(map: any): string; + addLuminosityFilter(map: number[]): string; - addHighlightHCMFilter(filterName: any, fgColor: any, bgColor: any, newFgColor: any, newBgColor: any): string; + addHighlightHCMFilter( + filterName: string, + fgColor: [number, number, number], + bgColor: [number, number, number], + newFgColor: [number, number, number], + newBgColor: [number, number, number] + ): string; destroy(keepHCM?: boolean): void; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseFilterFactory { addFilter(maps: Record<string, number[]>): string; addHCMFilter(fgColor: [number, number, number], bgColor: [number, number, number]): string; addAlphaFilter(map: number[]): string; addLuminosityFilter(map: number[]): string; addHighlightHCMFilter( filterName: string, fgColor: [number, number, number], bgColor: [number, number, number], newFgColor: [number, number, number], newBgColor: [number, number, number] ): string; destroy(keepHCM?: boolean): void; }
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/message_handler.d.ts (4)
1-2: 🛠️ Refactor suggestion
Consider using more specific types instead of 'any'
The extensive use of
any
type reduces TypeScript's ability to catch type-related errors at compile time. Consider defining more specific types forsourceName
,targetName
, andcomObj
.declare class MessageHandler { - constructor(sourceName: any, targetName: any, comObj: any); + constructor( + sourceName: string, + targetName: string, + comObj: EventTarget | MessagePort + );📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class MessageHandler { constructor( sourceName: string, targetName: string, comObj: EventTarget | MessagePort );
12-13: 🛠️ Refactor suggestion
Add type safety to event handler and 'on' method
The event handler and 'on' method use 'any' types, which could lead to runtime errors.
- _onComObjOnMessage: (event: any) => void; - on(actionName: any, handler: any): void; + _onComObjOnMessage: (event: MessageEvent) => void; + on(actionName: string, handler: (data: unknown) => void): void;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements._onComObjOnMessage: (event: MessageEvent) => void; on(actionName: string, handler: (data: unknown) => void): void;
40-40: 🛠️ Refactor suggestion
Replace Object type with a specific interface
The
queueingStrategy
parameter uses the banned 'Object' type. Define a proper interface for the queuing strategy.- sendWithStream(actionName: string, data: JSON, queueingStrategy: Object, transfers?: any[] | undefined): ReadableStream; + sendWithStream( + actionName: string, + data: JSON, + queueingStrategy: QueuingStrategy<unknown>, + transfers?: ArrayBuffer[] + ): ReadableStream<unknown>;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.sendWithStream( actionName: string, data: JSON, queueingStrategy: QueuingStrategy<unknown>, transfers?: ArrayBuffer[] ): ReadableStream<unknown>;
🧰 Tools
🪛 Biome
[error] 40-40: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
3-11: 🛠️ Refactor suggestion
Enhance type safety and documentation for class properties
Properties lack proper typing and documentation. Consider:
- Adding proper TypeScript types
- Using access modifiers
- Adding JSDoc comments for each property
- sourceName: any; - targetName: any; - comObj: any; - callbackId: number; - streamId: number; - streamSinks: any; - streamControllers: any; - callbackCapabilities: any; - actionHandler: any; + /** Name of the message source */ + private readonly sourceName: string; + /** Name of the message target */ + private readonly targetName: string; + /** Communication object for message passing */ + private readonly comObj: EventTarget | MessagePort; + /** Counter for callback IDs */ + private callbackId: number; + /** Counter for stream IDs */ + private streamId: number; + /** Map of stream sinks */ + private streamSinks: Map<number, WritableStream>; + /** Map of stream controllers */ + private streamControllers: Map<number, ReadableStreamController>; + /** Map of callback capabilities */ + private callbackCapabilities: Map<number, PromiseCapability>; + /** Map of action handlers */ + private actionHandler: Map<string, (data: unknown) => void>;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./** Name of the message source */ private readonly sourceName: string; /** Name of the message target */ private readonly targetName: string; /** Communication object for message passing */ private readonly comObj: EventTarget | MessagePort; /** Counter for callback IDs */ private callbackId: number; /** Counter for stream IDs */ private streamId: number; /** Map of stream sinks */ private streamSinks: Map<number, WritableStream>; /** Map of stream controllers */ private streamControllers: Map<number, ReadableStreamController>; /** Map of callback capabilities */ private callbackCapabilities: Map<number, PromiseCapability>; /** Map of action handlers */ private actionHandler: Map<string, (data: unknown) => void>;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/freetext.d.ts (4)
13-21: 🛠️ Refactor suggestion
Improve type safety by replacing 'any' types with specific interfaces.
Several static methods use the
any
type, which reduces TypeScript's type-checking benefits. Additionally, the private static method naming pattern"__#19@#"
seems unconventional.Consider defining proper interfaces and using them:
interface UIManager { // Define required properties and methods } interface L10n { // Define localization interface } interface DeserializationData { // Define expected data structure } declare class FreeTextEditor extends AnnotationEditor { static initialize(l10n: L10n, uiManager: UIManager): void; static updateDefaultParams(type: string, value: unknown): void; static deserialize(data: DeserializationData, parent: AnnotationEditor, uiManager: UIManager): Promise<AnnotationEditor | null>; // ... other methods }
42-49: 🛠️ Refactor suggestion
Use proper DOM event types for event handlers.
Event handlers should use specific TypeScript event types instead of
any
.Consider this improvement:
- editorDivKeydown(event: any): void; - editorDivFocus(event: any): void; - editorDivBlur(event: any): void; - editorDivInput(event: any): void; + editorDivKeydown(event: KeyboardEvent): void; + editorDivFocus(event: FocusEvent): void; + editorDivBlur(event: FocusEvent): void; + editorDivInput(event: InputEvent): void;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.dblclick(event: MouseEvent): void; editorDivKeydown(event: KeyboardEvent): void; editorDivFocus(event: FocusEvent): void; editorDivBlur(event: FocusEvent): void; editorDivInput(event: InputEvent): void; editorDiv: HTMLDivElement | undefined; overlayDiv: HTMLDivElement | undefined; editorDivPaste(event: any): void;
22-38: 🛠️ Refactor suggestion
Add proper parameter typing for constructor and improve method return types.
The constructor and commit method lack proper type definitions:
- Constructor parameter is typed as
any
commit()
method explicitly returnsundefined
instead ofvoid
Consider this improvement:
- constructor(params: any); + constructor(params: FreeTextEditorParams); /** @inheritdoc */ updateParams(type: any, value: any): void; /** @inheritdoc */ get propertiesToUpdate(): any[][]; /** * Helper to translate the editor with the keyboard when it's empty. * @param {number} x in page units. * @param {number} y in page units. */ _translateEmpty(x: number, y: number): void; - commit(): undefined; + commit(): void;Where
FreeTextEditorParams
is a new interface defining the expected parameters.Committable suggestion skipped: line range outside the PR's diff.
50-53: 🛠️ Refactor suggestion
Address static analysis warning about Object return type.
The
serialize
method uses a broadObject
return type, which was flagged by static analysis.Consider defining a specific interface for the serialized data:
+ interface SerializedFreeTextData { + type: string; + content: string; + position?: { x: number; y: number }; + // Add other relevant properties + } - serialize(isForCopying?: boolean): Object | null; + serialize(isForCopying?: boolean): SerializedFreeTextData | null;Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 51-51: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Extras/PdfReader/BitPdfReaderDemo.razor (1)
29-36: 🛠️ Refactor suggestion
Add null checks and improve accessibility for navigation controls.
The current implementation has potential null reference issues and lacks proper accessibility attributes.
- <BitButton OnClick="() => publicApiPdfReaderRef!.First()">First</BitButton> - <BitButton OnClick="() => publicApiPdfReaderRef!.Prev()">Prev</BitButton> + <BitButton OnClick="() => publicApiPdfReaderRef?.First()" AriaLabel="Go to first page">First</BitButton> + <BitButton OnClick="() => publicApiPdfReaderRef?.Prev()" AriaLabel="Go to previous page">Prev</BitButton> <BitTag Variant="BitVariant.Outline" Text="@($"{publicApiPdfReaderRef?.CurrentPageNumber.ToString()}/{publicApiPdfReaderRef?.NumberOfPages.ToString()}")" Color="BitColor.Info" /> - <BitButton OnClick="() => publicApiPdfReaderRef!.Next()">Next</BitButton> - <BitButton OnClick="() => publicApiPdfReaderRef!.Last()">Last</BitButton> | - <BitButton OnClick="ZoomOut">Zoom -</BitButton> - <BitButton OnClick="ZoomIn">Zoom +</BitButton> + <BitButton OnClick="() => publicApiPdfReaderRef?.Next()" AriaLabel="Go to next page">Next</BitButton> + <BitButton OnClick="() => publicApiPdfReaderRef?.Last()" AriaLabel="Go to last page">Last</BitButton> | + <BitButton OnClick="ZoomOut" AriaLabel="Zoom out">Zoom -</BitButton> + <BitButton OnClick="ZoomIn" AriaLabel="Zoom in">Zoom +</BitButton>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.<BitButton OnClick="() => publicApiPdfReaderRef?.First()" AriaLabel="Go to first page">First</BitButton> <BitButton OnClick="() => publicApiPdfReaderRef?.Prev()" AriaLabel="Go to previous page">Prev</BitButton> <BitTag Variant="BitVariant.Outline" Text="@($"{publicApiPdfReaderRef?.CurrentPageNumber.ToString()}/{publicApiPdfReaderRef?.NumberOfPages.ToString()}")" Color="BitColor.Info" /> <BitButton OnClick="() => publicApiPdfReaderRef?.Next()" AriaLabel="Go to next page">Next</BitButton> <BitButton OnClick="() => publicApiPdfReaderRef?.Last()" AriaLabel="Go to last page">Last</BitButton> | <BitButton OnClick="ZoomOut" AriaLabel="Zoom out">Zoom -</BitButton> <BitButton OnClick="ZoomIn" AriaLabel="Zoom in">Zoom +</BitButton> </div>
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/annotation_storage.d.ts (2)
14-45: 🛠️ Refactor suggestion
Replace broad 'Object' types with specific interfaces.
Using
Object
type reduces type safety. Define specific interfaces for annotation values to improve type checking and code maintainability.Consider defining and using specific types:
interface AnnotationValue { value: unknown; type: string; modified?: boolean; } declare class AnnotationStorage { getValue(key: string, defaultValue: AnnotationValue): AnnotationValue; getRawValue(key: string): AnnotationValue; setValue(key: string, value: AnnotationValue): void; getAll(): Record<string, AnnotationValue> | null; setAll(obj: Record<string, AnnotationValue>): void; // ... other methods }🧰 Tools
🪛 Biome
[error] 14-14: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
[error] 14-14: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
[error] 20-20: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
[error] 31-31: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
[error] 41-41: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
[error] 45-45: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
4-8: 🛠️ Refactor suggestion
Define specific types for callback properties instead of using 'any'.
The callback properties should have explicit function signatures to maintain type safety and improve code maintainability.
Consider defining proper types:
declare class AnnotationStorage { - onSetModified: any; - onResetModified: any; - onAnnotationEditor: any; + onSetModified: () => void; + onResetModified: () => void; + onAnnotationEditor: (params: { action: string; value: unknown }) => void;Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/text_layer.d.ts (1)
19-30:
⚠️ Potential issueReplace generic
Function
type with a specific function signature.Using the generic
Function
type reduces type safety. Define an explicit function signature based on how the callback is used.Apply this change:
- onBefore?: Function | undefined; + onBefore?: (() => void) | undefined;If the callback requires parameters or returns a value, please adjust the signature accordingly based on its usage in the implementation.
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 29-29: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Extras/PdfReader/BitPdfReaderDemo.razor.cs (1)
1-191: 💡 Codebase verification
PDF.js resources are not properly cleaned up.
The implementation lacks proper cleanup of PDF.js resources. The following issues need to be addressed:
- The PDFDocumentProxy instances stored in
_bitPdfReaders
map are never destroyed- No cleanup of render tasks when pages are re-rendered
- Missing disposal of PDF loading tasks
- No cleanup when the component is disposed
Add the following cleanup:
- Implement cleanup in the component:
public static cleanup(id: string) { const config = BitPdfReader._bitPdfReaders.get(id); if (config) { config.pdfDoc?.destroy(); BitPdfReader._bitPdfReaders.delete(id); } }
- Call cleanup when refreshing pages:
public static async refreshPage(config: BitPdfReaderConfig, pageNumber: number) { let oldConfig = BitPdfReader._bitPdfReaders.get(config.id); if (oldConfig) { oldConfig.pdfDoc?.destroy(); // Cleanup old PDF BitPdfReader._bitPdfReaders.set(config.id, Object.assign(oldConfig, config)); } // ... }
- Cancel render tasks when re-rendering pages.
🔗 Analysis chain
Verify PDF.js integration and cleanup.
Please ensure proper cleanup of PDF.js resources when the component is disposed.
Let's search for the actual implementation files to verify the PDF.js integration and cleanup mechanisms.
Let's search for the PDF.js integration and cleanup implementation files.
Let's check the TypeScript implementation to verify the PDF.js cleanup handling.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for dispose/cleanup implementations rg -l "IAsyncDisposable|Dispose|CleanupPdfJs" --type cs # Search for PDF.js initialization rg -l "pdfjsLib|getDocument|PDFDocumentProxy" --type csLength of output: 6658
Script:
#!/bin/bash # Let's search for PDF-related files and implementations fd -e cs -e js -e ts "pdf" -i # Search for PDF-related code in JavaScript files rg "pdfjsLib|getDocument|PDFDocumentProxy" --type js -A 5 -B 5 # Search for BitPdfReader implementation fd "BitPdfReader.razor.cs"Length of output: 336806
Script:
#!/bin/bash # Let's search for PDF.js cleanup and initialization code rg -l "pdfjsLib|getDocument|PDFDocumentProxy|cleanup|dispose|destroy" --type cs src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/ # Let's also check the TypeScript file fd -e ts BitPdfReader src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/Length of output: 285
Script:
#!/bin/bash # Let's examine the TypeScript file for cleanup implementation cat src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReader.tsLength of output: 4368
src/BlazorUI/Bit.BlazorUI.Extras/Components/Chart/BitChart.razor.cs (2)
125-133: 🛠️ Refactor suggestion
Consider optimizing re-render performance and adding error handling.
The current implementation calls
BitChartJsSetupChart
on every re-render, which might be inefficient. Consider adding a check to determine if setup is actually needed.Additionally, the JS interop calls lack error handling which could lead to unhandled exceptions.
Consider applying this pattern:
if (firstRender) { var scripts = new List<string> { "_content/Bit.BlazorUI.Extras/chart.js/chartjs-2.9.4.js" }; // ... script setup ... - await _js.BitChartJsInitChartJs(scripts); - await _js.BitChartJsSetupChart(Config); + try { + await _js.BitChartJsInitChartJs(scripts); + await _js.BitChartJsSetupChart(Config); + await SetupCompletedCallback.InvokeAsync(this); + } + catch (Exception ex) { + // Log error or notify user + throw; + } - await SetupCompletedCallback.InvokeAsync(this); } else { - await _js.BitChartJsSetupChart(Config); + if (ShouldUpdateChart()) // Add method to check if update is needed + { + try { + await _js.BitChartJsSetupChart(Config); + } + catch (Exception ex) { + // Log error or notify user + throw; + } + } }Committable suggestion skipped: line range outside the PR's diff.
145-145: 🛠️ Refactor suggestion
Add error handling to Update method.
The Update method should include error handling to gracefully handle JS interop failures.
Consider applying this pattern:
public Task Update() { - return _js.BitChartJsUpdateChart(Config).AsTask(); + try + { + return _js.BitChartJsUpdateChart(Config).AsTask(); + } + catch (Exception ex) + { + // Log error or notify user + throw; + } }Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/node_stream.d.ts (6)
8-9: 🛠️ Refactor suggestion
Specify types for '_fullRequestReader' and '_rangeRequestReaders'
The properties
_fullRequestReader
and_rangeRequestReaders
useany
types or are not fully specified. For better type safety, specify the exact types of the readers.Apply the following diff:
declare class PDFNodeStream { // ... - _fullRequestReader: PDFNodeStreamFsFullReader | PDFNodeStreamFullReader | null; - _rangeRequestReaders: any[]; + _fullRequestReader: PDFNodeStreamFsFullReader | PDFNodeStreamFullReader | null; + _rangeRequestReaders: Array<PDFNodeStreamFsRangeReader | PDFNodeStreamRangeReader>;This ensures that
_rangeRequestReaders
is an array containing the correct reader types.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements._fullRequestReader: PDFNodeStreamFsFullReader | PDFNodeStreamFullReader | null; _rangeRequestReaders: Array<PDFNodeStreamFsRangeReader | PDFNodeStreamRangeReader>;
17-19: 🛠️ Refactor suggestion
Define '_request' property type in 'PDFNodeStreamFullReader'
The
_request: any;
property inPDFNodeStreamFullReader
lacks a specific type. Specifying its type enhances clarity and assists in proper usage.Please replace
any
with the appropriate type for_request
.declare class PDFNodeStreamFullReader extends BaseFullReader { - _request: any; + _request: RequestType; }Define
RequestType
based on the actual type of_request
.Committable suggestion skipped: line range outside the PR's diff.
24-26: 🛠️ Refactor suggestion
Define '_request' property type in 'PDFNodeStreamRangeReader'
Similar to
PDFNodeStreamFullReader
, the_request: any;
property inPDFNodeStreamRangeReader
should have a specific type.Apply the following diff:
declare class PDFNodeStreamRangeReader extends BaseRangeReader { // ... - _request: any; + _request: RequestType; }Ensure
RequestType
reflects the correct type of_request
.Committable suggestion skipped: line range outside the PR's diff.
2-3: 🛠️ Refactor suggestion
Specify precise types for 'source' parameter and property
The
constructor(source: any)
and thesource: any
property use theany
type. To enhance type safety and readability, it's recommended to replaceany
with a more specific type that reflects the expected structure ofsource
.Apply the following diff to update the type:
declare class PDFNodeStream { - constructor(source: any); - source: any; + constructor(source: PDFSource); + source: PDFSource;Please define the
PDFSource
interface or type alias that accurately represents the expectedsource
object.Committable suggestion skipped: line range outside the PR's diff.
12-12: 🛠️ Refactor suggestion
Replace 'any' types for 'start' and 'end' parameters
In
getRangeReader(start: any, end: any)
, the parametersstart
andend
are typed asany
. To improve type safety, specify these parameters as numbers.Apply the following diff:
getRangeReader(start: any, end: any): PDFNodeStreamFsRangeReader | PDFNodeStreamRangeReader | null; +getRangeReader(start: number, end: number): PDFNodeStreamFsRangeReader | PDFNodeStreamRangeReader | null;
Committable suggestion skipped: line range outside the PR's diff.
27-68: 🛠️ Refactor suggestion
Improve type definitions in 'BaseFullReader' and 'BaseRangeReader' classes
Several properties and methods in
BaseFullReader
andBaseRangeReader
use theany
type or lack explicit return types. Defining specific types enhances maintainability and type checking.Examples:
- Specify the types of
_url
,_readableStream
, and other properties.- Define return types for methods like
read()
andheadersReady
.- If methods return Promises or specific objects, indicate this in the type.
For instance:
declare class BaseFullReader { constructor(stream: any); - _url: any; + _url: string; // ... - read(): any; + read(): Promise<ReadResult>; // ... - get headersReady(): any; + get headersReady(): Promise<void>; }Define
ReadResult
or use the appropriate built-in types.Similarly, update
BaseRangeReader
accordingly.Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/highlight.d.ts (3)
14-16: 🛠️ Refactor suggestion
Replace
any
types with specific types for better type safetySeveral methods use
any
as parameter or return types, which reduces type safety and can lead to runtime errors. Please consider defining specific types or interfaces for these parameters and return values.For example, update method signatures:
- static computeTelemetryFinalData(data: any): { + static computeTelemetryFinalData(data: TelemetryData): { numberOfColors: number; }; - static startHighlighting(parent: any, isLTR: any, { target: textLayer, x, y }: { target: any; x: any; y: any }): void; + static startHighlighting(parent: AnnotationLayer, isLTR: boolean, { target: textLayer, x, y }: { target: HTMLElement; x: number; y: number }): void; - static "__#25@#highlightMove"(parent: any, event: any): void; + static highlightMove(parent: AnnotationLayer, event: MouseEvent): void; - static "__#25@#endHighlight"(parent: any, event: any): void; + static endHighlight(parent: AnnotationLayer, event: MouseEvent): void; - static deserialize(data: any, parent: any, uiManager: any): Promise<AnnotationEditor | null>; + static deserialize(data: SerializedHighlightData, parent: AnnotationLayer, uiManager: UIManager): Promise<AnnotationEditor | null>;Define the necessary interfaces/types such as
TelemetryData
,AnnotationLayer
,UIManager
, andSerializedHighlightData
.Also applies to: 33-37, 38-39, 41-41
22-32:
⚠️ Potential issueAvoid using compiler-generated method names
The methods
__#25@#rotateBbox
,__#25@#highlightMove
, and__#25@#endHighlight
have names that include compiler-generated symbols, which can lead to confusion and maintenance issues. Consider renaming these methods to meaningful and valid identifiers.Apply this diff to rename the methods appropriately:
- static "__#25@#rotateBbox"({ x, y, width, height }: { x: any; y: any; width: any; height: any; }, angle: any): { x: any; y: any; width: any; height: any; }; + static rotateBbox({ x, y, width, height }: { x: number; y: number; width: number; height: number; }, angle: number): { x: number; y: number; width: number; height: number; }; - static "__#25@#highlightMove"(parent: any, event: any): void; + static highlightMove(parent: AnnotationLayer, event: MouseEvent): void; - static "__#25@#endHighlight"(parent: any, event: any): void; + static endHighlight(parent: AnnotationLayer, event: MouseEvent): void;Also applies to: 38-39
73-73:
⚠️ Potential issueAvoid using
Object
as a return type inserialize
methodUsing
Object
as a type is discouraged in TypeScript because it doesn't provide type safety. Please define a specific interface or type for the return value to enhance type safety and maintainability.Apply this diff to specify the return type:
- serialize(isForCopying?: boolean): Object | null; + serialize(isForCopying?: boolean): SerializedHighlightData | null; + interface SerializedHighlightData { + // Define the properties of the serialized highlight data here + }Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 73-73: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/network.d.ts (5)
3-12: 🛠️ Refactor suggestion
Consider specifying explicit types instead of 'any' in 'PDFNetworkStream'
The class
PDFNetworkStream
has several properties and methods typed asany
. Specifying explicit types enhances type safety and code clarity. Please consider replacingany
with more precise types where possible.
37-65: 🛠️ Refactor suggestion
Specify explicit types instead of 'any' in 'PDFNetworkStreamFullRequestReader'
Many properties and method parameters in
PDFNetworkStreamFullRequestReader
are typed asany
. Defining specific types improves code quality and maintainability. Please update the types where possible.
50-50:
⚠️ Potential issueUndefined exception types in '_storedError' property
The
_storedError
property uses the typesMissingPDFException
andUnexpectedResponseException
, which may not be defined or imported. This could lead to type errors. Please ensure these exception types are declared or imported appropriately.
68-85: 🛠️ Refactor suggestion
Consider specifying explicit types instead of 'any' in 'PDFNetworkStreamRangeRequestReader'
The class
PDFNetworkStreamRangeRequestReader
has properties and methods typed asany
. Specifying explicit types enhances type safety and code clarity. Please consider replacingany
with more precise types where possible.
75-75:
⚠️ Potential issueUndefined exception types in '_storedError' property
The
_storedError
property uses the typesMissingPDFException
andUnexpectedResponseException
, which may not be defined or imported. This could lead to type errors. Please ensure these exception types are declared or imported appropriately.src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/ink.d.ts (3)
26-26: 🛠️ Refactor suggestion
Define a specific type for constructor parameters
The constructor parameter
params
is typed asany
. Defining an interface forparams
improves type safety and clarity.Apply this diff to update the constructor signature:
- constructor(params: any); + constructor(params: InkEditorParams);And define the
InkEditorParams
interface:interface InkEditorParams { color?: string; thickness?: number; opacity?: number; // Add other parameters as needed }
27-29: 🛠️ Refactor suggestion
Specify explicit types for properties
The properties
color
,thickness
, andopacity
are currently typed asany
. Specifying precise types enhances type safety and code readability.Apply this diff to specify the types:
- color: any; - thickness: any; - opacity: any; + color: string; // Assuming color is a CSS color string + thickness: number; + opacity: number;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.color: string; // Assuming color is a CSS color string thickness: number; opacity: number;
21-23:
⚠️ Potential issueRemove private methods from the declaration file
Private methods should not be included in declaration files (
.d.ts
) as they are not part of the public API. The methods__#26@#buildPath2D
,__#26@#toPDFCoordinates
, and__#26@#fromPDFCoordinates
appear to be internal and their mangled names indicate they are intended for private use.Apply this diff to remove these methods:
- static "__#26@#buildPath2D"(bezier: Array<Array<number>>): Path2D; - static "__#26@#toPDFCoordinates"(points: any, rect: any, rotation: any): any; - static "__#26@#fromPDFCoordinates"(points: any, rect: any, rotation: any): any;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/interfaces.d.ts (3)
117-117: 🛠️ Refactor suggestion
Avoid using 'Object' as a type for the 'reason' parameter
Consistent with previous comments, replace
Object
with a more specific type to enhance type safety.Apply this change:
- cancel(reason: Object): void; + cancel(reason: unknown): void;Or define a specific interface for
reason
.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.cancel(reason: unknown): void;
🧰 Tools
🪛 Biome
[error] 117-117: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
24-24: 🛠️ Refactor suggestion
Avoid using 'Object' as a type for the 'reason' parameter
Using
Object
as a type is discouraged because it is too broad and does not provide type safety. Consider defining a more specific type or usingunknown
if the exact type is not known.Apply this diff to enhance type safety:
- cancelAllRequests(reason: Object): void; + cancelAllRequests(reason: unknown): void;Or define a specific interface for
reason
.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.cancelAllRequests(reason: unknown): void;
🧰 Tools
🪛 Biome
[error] 24-24: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
57-57: 🛠️ Refactor suggestion
Avoid using 'Object' as a type for the 'reason' parameter
Similar to the previous instance, using
Object
as a type is too generic. Please use a more specific type.Suggested change:
- cancel(reason: Object): void; + cancel(reason: unknown): void;Or define a specific interface for
reason
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 57-57: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReader.ts (5)
16-117: 🛠️ Refactor suggestion
Consider refactoring the class with only static members into a module of functions
The
BitPdfReader
class contains only static methods and properties. It's recommended to use a module or namespace with plain functions instead of a class when no instances are created. This reduces unnecessary complexity and aligns with best practices.🧰 Tools
🪛 Biome
[error] 16-117: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
[error] 30-37: Promise executor functions should not be
async
.(lint/suspicious/noAsyncPromiseExecutor)
70-70:
⚠️ Potential issueAwait the 'setup' method in 'refreshPage'
The
setup
method is asynchronous and should be awaited to ensure it completes before proceeding to render the page.Modify the code to await the
setup
method:- BitPdfReader.setup(config); + await BitPdfReader.setup(config);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.await BitPdfReader.setup(config);
93-99:
⚠️ Potential issueAdd null checks for 'canvas' before accessing its context
If the
canvas
element is not found, callinggetContext('2d')
will result in an error. Ensure thecanvas
is not null before proceeding.Add a null check for
canvas
:let canvas = document.getElementById(config.id) as HTMLCanvasElement; if (!canvas) { canvas = document.getElementById(`${config.id}-${pageNumber}`) as HTMLCanvasElement; } +if (!canvas) { + console.error(`Canvas element with id '${config.id}' or '${config.id}-${pageNumber}' not found.`); + return; +} const context = canvas.getContext('2d')!;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.let canvas = document.getElementById(config.id) as HTMLCanvasElement; if (!canvas) { canvas = document.getElementById(`${config.id}-${pageNumber}`) as HTMLCanvasElement; } if (!canvas) { console.error(`Canvas element with id '${config.id}' or '${config.id}-${pageNumber}' not found.`); return; } const context = canvas.getContext('2d')!; canvas.width = viewport.width;
81-84:
⚠️ Potential issueFix potential off-by-one errors in 'isRendering' array indexing
The
isRendering
array usespageNumber
as an index. Since arrays are zero-based andpageNumber
starts from 1, this could lead to off-by-one errors.Adjust the indexing by subtracting 1 from
pageNumber
:-if (config.isRendering[pageNumber]) return; +if (config.isRendering[pageNumber - 1]) return; ... -if (pageNumber < 1 || pageNumber > config.pdfDoc.numPages) return; +if (pageNumber < 1 || pageNumber > config.pdfDoc.numPages) return; ... -config.isRendering[pageNumber] = true; +config.isRendering[pageNumber - 1] = true; ... -config.isRendering[pageNumber] = false; +config.isRendering[pageNumber - 1] = false;Apply this adjustment wherever
isRendering[pageNumber]
is accessed.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.if (config.isRendering[pageNumber - 1]) return; if (pageNumber < 1 || pageNumber > config.pdfDoc.numPages) return; config.isRendering[pageNumber - 1] = true;
30-37:
⚠️ Potential issueAvoid using 'async' functions as Promise executors
The executor function passed to
new Promise()
should not beasync
. Using anasync
function as a Promise executor can lead to unexpected behavior because exceptions inside the executor are not handled correctly.You can fix this by removing
async
from the executor function:-const promise = new Promise(async (resolve: any, reject: any) => { +const promise = new Promise((resolve: any, reject: any) => { try { - for (let url of notAppenedScripts) await addScript(url); + for (let url of notAppendedScripts) await addScript(url); resolve(); } catch (e: any) { reject(e); } });Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 30-37: Promise executor functions should not be
async
.(lint/suspicious/noAsyncPromiseExecutor)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReader.razor.cs (1)
129-136:
⚠️ Potential issueImplement the "scroll to page" functionality for
RenderAllPages
.When
RenderAllPages
is set totrue
, theGo
method currently lacks the implementation to scroll to the specified page. Implement this functionality to ensure a smooth user experience when navigating to a specific page in the "render all pages" mode.Do you want me to provide a code snippet that demonstrates how to implement the "scroll to page" functionality?
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/annotation_editor_layer.d.ts (9)
2-2:
⚠️ Potential issueDefine a specific type for 'mode' instead of using 'Object'.
Using
Object
as a type is discouraged because it doesn't provide type safety. Please define a specific type or interface that represents the structure ofmode
.For example:
interface ModeOptions { // Define the properties of 'mode' here } mode: ModeOptions;🧰 Tools
🪛 Biome
[error] 2-2: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
73-75:
⚠️ Potential issueSpecify a detailed type for 'params' in 'addCommands' method.
The parameter
params
is currently typed asObject
, which lacks specificity and type safety. Please define a specific type or interface that outlines the expected structure ofparams
.Example:
addCommands(params: CommandParams): void;Define the
CommandParams
interface accordingly:interface CommandParams { // Define the properties of 'params' here }🧰 Tools
🪛 Biome
[error] 75-75: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
137-139:
⚠️ Potential issueDefine a specific type for 'params' in 'pasteEditor' method.
Using
Object
as a type forparams
does not provide clarity on its structure. Please specify a detailed type or interface for better type safety.Example:
pasteEditor(mode: number, params: PasteEditorParams): void;Define the
PasteEditorParams
interface:interface PasteEditorParams { // Define the properties of 'params' here }🧰 Tools
🪛 Biome
[error] 139-139: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
143-145:
⚠️ Potential issueSpecify a detailed type for 'data' in 'deserialize' method.
The
data
parameter is typed asObject
, which is too generic. Please define a specific type or interface that represents the expected structure ofdata
.Example:
deserialize(data: SerializedEditorData): AnnotationEditor | null;Define the
SerializedEditorData
interface:interface SerializedEditorData { // Define the properties of 'data' here }🧰 Tools
🪛 Biome
[error] 145-145: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
149-153:
⚠️ Potential issueReplace '{}' with a specific type for 'data' parameter in 'createAndAddNewEditor' method.
Using
{}
as a type means "any non-nullable value" and lacks type safety. Please provide a specific type or interface fordata
.Example:
createAndAddNewEditor(event: PointerEvent, isCentered: boolean, data?: EditorData): AnnotationEditor;Define the
EditorData
interface:interface EditorData { // Define the optional properties of 'data' here }🧰 Tools
🪛 Biome
[error] 153-153: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
212-214:
⚠️ Potential issueSpecify a precise return type for 'pageDimensions' getter.
Returning
Object
does not convey the structure of the returned dimensions. Please define a specific type or interface for better clarity and type safety.Example:
get pageDimensions(): PageDimensions;Define the
PageDimensions
interface:interface PageDimensions { width: number; height: number; }🧰 Tools
🪛 Biome
[error] 214-214: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
65-65: 🛠️ Refactor suggestion
Avoid using 'any' type for 'isCommitting' in 'addInkEditorIfNeeded' method.
The parameter
isCommitting
is typed asany
, which reduces type safety. Please specify the appropriate type, such asboolean
.Example:
addInkEditorIfNeeded(isCommitting: boolean): void;
98-99: 🛠️ Refactor suggestion
Specify the type for 'editor' parameter in 'attach' and 'detach' methods.
Using
any
for theeditor
parameter does not provide type safety. Please specify the appropriate type, such asAnnotationEditor
.Example:
attach(editor: AnnotationEditor): void; detach(editor: AnnotationEditor): void;
132-132: 🛠️ Refactor suggestion
Define a specific type for 'ac' parameter in 'combinedSignal' method.
The parameter
ac
is typed asany
, which is not type-safe. Please specify the correct type, such asAbortController
.Example:
combinedSignal(ac: AbortController): AbortSignal;src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/annotation_layer.d.ts (4)
13-13:
⚠️ Potential issueAvoid using 'Object' as a type for 'svgFactory'; define a specific type
The type
Object
is too general and doesn't convey the expected shape ofsvgFactory
. Please replace it with a more precise type to enhance type safety.Apply this diff:
- svgFactory: Object; + svgFactory: ISvgFactory;Note: Define the
ISvgFactory
interface that describes the methods and properties ofsvgFactory
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 13-13: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
16-16:
⚠️ Potential issueReplace 'Object' type with a specific interface for 'fieldObjects'
Using
Object
as a type is not recommended. Defining a specific interface forfieldObjects
will improve clarity and maintainability.Apply this diff:
- fieldObjects?: Object | undefined; + fieldObjects?: FieldObjects | undefined;Note: Define the
FieldObjects
interface to represent the structure offieldObjects
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 16-16: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
2-2:
⚠️ Potential issueSpecify explicit types instead of 'Object' for better type safety
Using
Object
as a type is discouraged as it doesn't provide information about the structure of the data. It's better to define a specific interface or type fordata
to improve type checking and code readability.Apply this diff to fix the issue:
- data: Object; + data: AnnotationData;Note: Define the
AnnotationData
interface according to the structure ofdata
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 2-2: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
42-42:
⚠️ Potential issueProvide an explicit type for the index signature values
The index signature
[x: string]: Object[];
usesObject[]
as a type, which is too vague. Specify the exact type of objects within the array to enhance type safety.Apply this diff:
- [x: string]: Object[]; + [x: string]: FieldObject[];Note: Define the
FieldObject
interface to describe the elements within the array.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 42-42: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/canvas.d.ts (1)
9-9: 🛠️ Refactor suggestion
Avoid using
{}
as a type; explicitly define the object shapeUsing
{}
as a type is discouraged because it represents any non-nullable value and lacks specificity. Explicitly define the object shape forpendingClip
to improve type safety and code clarity.Apply this diff to define a specific type:
-pendingClip: {} | {} | null; +pendingClip: PendingClip | null;Where
PendingClip
is defined as:interface PendingClip { // Define the properties of pendingClip here }🧰 Tools
🪛 Biome
[error] 9-9: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 9-9: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/tools.d.ts (3)
398-398: 🛠️ Refactor suggestion
Avoid using 'Object' as a type for 'self'; specify the correct interface
Using
Object
as a type is not recommended as it is too general. Please specify the exact type or interface forself
, or useany
if the type cannot be determined.Apply this diff to enhance type safety:
- exec(self: Object, event: KeyboardEvent): void; + exec(self: any, event: KeyboardEvent): void;Ideally, define an interface representing the structure of
self
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 398-398: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
348-350: 🛠️ Refactor suggestion
Avoid using 'Function' as a type; specify function signatures explicitly
Using
Function
as a type is discouraged because it lacks specificity and type safety. Please provide explicit function types forcmd
,undo
, andpost
.Apply this diff to specify function types:
cmd: Function; undo: Function; post?: Function | undefined;Change to:
+ cmd: () => void; + undo: () => void; + post?: () => void;If these functions have parameters, specify them accordingly.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.cmd: () => void; undo: () => void; post?: () => void;
🧰 Tools
🪛 Biome
[error] 348-348: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 349-349: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 350-350: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
233-233: 🛠️ Refactor suggestion
Avoid using 'Object' as a type; define a specific interface for 'params'
Using
Object
as a type is too broad and does not provide type safety. Please define an interface that specifies the exact shape of theparams
object.Apply this diff to improve type safety:
- addCommands(params: Object): void; + addCommands(params: AddCommandsParams): void; +interface AddCommandsParams { + // Define the properties of params here +}Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 233-233: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/util.d.ts (4)
1-8:
⚠️ Potential issueSpecify correct base classes for exception classes
Several exception classes (
AbortException
,FormatError
,InvalidPDFException
,MissingPDFException
,PasswordException
,UnexpectedResponseException
,UnknownErrorException
) are extending base classes declared asany
. To improve type safety and take advantage of TypeScript's features, these should extend from the built-inError
class or a properly defined base exception class.Apply this diff to update the base classes:
For
AbortException
(lines 1-8):-declare const AbortException_base: any; +declare const AbortException_base: Error;Repeat similar changes for the other exception classes:
FormatError
(lines 182-189)InvalidPDFException
(lines 200-204)MissingPDFException
(lines 210-214)PasswordException
(lines 315-320)UnexpectedResponseException
(lines 368-373)UnknownErrorException
(lines 374-379)Also applies to: 182-189, 200-204, 210-214, 315-320, 368-373, 374-379
163-169: 🛠️ Refactor suggestion
Refactor 'FeatureTest' class containing only static members
The
FeatureTest
class (lines 163-169) contains only static members and no instance members. In TypeScript, it's preferable to use a namespace or module to group related functions instead of a class with only static members. This simplifies the code and avoids unnecessary complexity.Apply this diff to refactor the class into a namespace:
-export class FeatureTest { - static get isLittleEndian(): any; - static get isEvalSupported(): any; - static get isOffscreenCanvasSupported(): any; - static get platform(): any; - static get isCSSRoundSupported(): any; -} +export namespace FeatureTest { + function isLittleEndian(): any; + function isEvalSupported(): any; + function isOffscreenCanvasSupported(): any; + function platform(): any; + function isCSSRoundSupported(): any; +}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.export namespace FeatureTest { function isLittleEndian(): any; function isEvalSupported(): any; function isOffscreenCanvasSupported(): any; function platform(): any; function isCSSRoundSupported(): any; }
🧰 Tools
🪛 Biome
[error] 163-169: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
155-155:
⚠️ Potential issueAvoid using 'Object' as a type
In line 155, the
options
parameter is typed asObject
. It's recommended to avoid usingObject
as a type in TypeScript because it means "any non-nullable value" and doesn't provide type safety. Consider defining a more specific interface or type foroptions
.Apply this diff to improve type safety:
-export function createValidAbsoluteUrl(url: URL | string, baseUrl?: string | URL | undefined, options?: Object | undefined): URL | null; +export function createValidAbsoluteUrl(url: URL | string, baseUrl?: string | URL, options?: Record<string, unknown> | undefined): URL | null;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.export function createValidAbsoluteUrl(url: URL | string, baseUrl?: string | URL, options?: Record<string, unknown> | undefined): URL | null;
🧰 Tools
🪛 Biome
[error] 155-155: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
382-396: 🛠️ Refactor suggestion
Refactor 'Util' class containing only static members
Similarly, the
Util
class (lines 382-396) contains only static methods. Using a class in this case is unnecessary. Consider refactoring it into a namespace or exporting the functions directly.Apply this diff to refactor the class into a namespace:
-export class Util { - static makeHexColor(r: any, g: any, b: any): string; - static scaleMinMax(transform: any, minMax: any): void; - static transform(m1: any, m2: any): any[]; - static applyTransform(p: any, m: any): any[]; - static applyInverseTransform(p: any, m: any): number[]; - static getAxialAlignedBoundingBox(r: any, m: any): number[]; - static inverseTransform(m: any): number[]; - static singularValueDecompose2dScale(m: any): number[]; - static normalizeRect(rect: any): any; - static intersect(rect1: any, rect2: any): number[] | null; - static "__#1@#getExtremumOnCurve"(x0: any, x1: any, x2: any, x3: any, y0: any, y1: any, y2: any, y3: any, t: any, minMax: any): void; - static "__#1@#getExtremum"(x0: any, x1: any, x2: any, x3: any, y0: any, y1: any, y2: any, y3: any, a: any, b: any, c: any, minMax: any): void; - static bezierBoundingBox(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, x3: any, y3: any, minMax: any): any; -} +export namespace Util { + function makeHexColor(r: any, g: any, b: any): string; + function scaleMinMax(transform: any, minMax: any): void; + function transform(m1: any, m2: any): any[]; + function applyTransform(p: any, m: any): any[]; + function applyInverseTransform(p: any, m: any): number[]; + function getAxialAlignedBoundingBox(r: any, m: any): number[]; + function inverseTransform(m: any): any[]; + function singularValueDecompose2dScale(m: any): number[]; + function normalizeRect(rect: any): any; + function intersect(rect1: any, rect2: any): number[] | null; + function "__#1@#getExtremumOnCurve"(x0: any, x1: any, x2: any, x3: any, y0: any, y1: any, y2: any, y3: any, t: any, minMax: any): void; + function "__#1@#getExtremum"(x0: any, x1: any, x2: any, x3: any, y0: any, y1: any, y2: any, y3: any, a: any, b: any, c: any, minMax: any): void; + function bezierBoundingBox(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, x3: any, y3: any, minMax: any): any; +}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.export namespace Util { function makeHexColor(r: any, g: any, b: any): string; function scaleMinMax(transform: any, minMax: any): void; function transform(m1: any, m2: any): any[]; function applyTransform(p: any, m: any): any[]; function applyInverseTransform(p: any, m: any): number[]; function getAxialAlignedBoundingBox(r: any, m: any): number[]; function inverseTransform(m: any): any[]; function singularValueDecompose2dScale(m: any): number[]; function normalizeRect(rect: any): any; function intersect(rect1: any, rect2: any): number[] | null; function "__#1@#getExtremumOnCurve"(x0: any, x1: any, x2: any, x3: any, y0: any, y1: any, y2: any, y3: any, t: any, minMax: any): void; function "__#1@#getExtremum"(x0: any, x1: any, x2: any, x3: any, y0: any, y1: any, y2: any, y3: any, a: any, b: any, c: any, minMax: any): void; function bezierBoundingBox(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, x3: any, y3: any, minMax: any): any; }
🧰 Tools
🪛 Biome
[error] 382-396: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/editor.d.ts (8)
84-84: 🛠️ Refactor suggestion
Define a specific type for 'data' parameter instead of 'Object'
Using
Object
as a type is not recommended because it lacks specificity. Please define an explicit type or interface for thedata
parameter to improve type safety.Apply this diff:
-static deserialize(data: Object, parent: AnnotationEditorLayer, uiManager: AnnotationEditorUIManager): Promise<AnnotationEditor | null>; +static deserialize(data: AnnotationEditorData, parent: AnnotationEditorLayer, uiManager: AnnotationEditorUIManager): Promise<AnnotationEditor | null>;Define the
AnnotationEditorData
interface to represent the structure of thedata
parameter.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 84-84: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
317-317: 🛠️ Refactor suggestion
Avoid returning 'Object'; define a specific return type for 'serializeDeleted'
Returning
Object
does not provide type safety. Please define a specific interface or type that represents the return value ofserializeDeleted
.Apply this diff:
-serializeDeleted(): Object; +serializeDeleted(): SerializedEditorData;Define the
SerializedEditorData
interface to represent the serialized data structure.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 317-317: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
48-48: 🛠️ Refactor suggestion
Avoid using 'Object' as a type; define a specific interface for 'l10n' parameter
Using
Object
as a type is discouraged because it lacks specificity. Define an appropriate interface for thel10n
parameter to enhance type safety.Apply this diff:
-static initialize(l10n: Object, _uiManager: any, options: any): void; +static initialize(l10n: IL10n, _uiManager: any, options: any): void;Define the
IL10n
interface according to the expected structure ofl10n
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 48-48: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
413-413: 🛠️ Refactor suggestion
Define a specific return type for 'telemetryInitialData'
Returning
Object
does not provide type safety. Please define an explicit interface or type fortelemetryInitialData
.Apply this diff:
-get telemetryInitialData(): Object; +get telemetryInitialData(): TelemetryData;Define the
TelemetryData
interface to represent the telemetry data structure.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 413-413: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
132-132: 🛠️ Refactor suggestion
Specify a concrete type for 'params' parameter instead of 'Object'
Using
Object
as a type is discouraged. Please define the expected structure of theparams
parameter with an explicit interface or type.Apply this diff:
-addCommands(params: Object): void; +addCommands(params: CommandParams): void;Define the
CommandParams
interface to represent the shape ofparams
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 132-132: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
418-418: 🛠️ Refactor suggestion
Define a specific return type for 'telemetryFinalData'
Returning
Object
does not provide type safety. Please define an explicit interface or type fortelemetryFinalData
.Apply this diff:
-get telemetryFinalData(): Object | null; +get telemetryFinalData(): TelemetryData | null;Assuming the
TelemetryData
interface is defined.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 418-418: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
432-432: 🛠️ Refactor suggestion
Define a specific type for 'annotation' parameter in 'renderAnnotationElement'
Using
Object
as a parameter type lacks specificity. Please define an explicit interface or type that represents the structure ofannotation
.Apply this diff:
-renderAnnotationElement(annotation: Object): HTMLElement | null; +renderAnnotationElement(annotation: AnnotationData): HTMLElement | null;Define the
AnnotationData
interface according to the expected structure ofannotation
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 432-432: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
328-328: 🛠️ Refactor suggestion
Specify concrete types for 'context' parameter and return type in 'serialize' method
Using
Object
as a type forcontext
and the return type lacks specificity. Please define explicit interfaces or types to enhance type safety.Apply this diff:
-serialize(isForCopying?: boolean | undefined, context?: Object | null | undefined): Object | null; +serialize(isForCopying?: boolean | undefined, context?: SerializationContext | null): SerializedEditorData | null;Define the
SerializationContext
andSerializedEditorData
interfaces according to the expected structures.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 328-328: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
[error] 328-328: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/api.d.ts (2)
28-28: 🛠️ Refactor suggestion
⚠️ Potential issueAvoid using the
Object
type. Use a more specific type instead.The
Object
type is very broad and provides little type safety. It's better to explicitly define the expected properties and their types.Replace the
Object
type with a more specific type that defines the expected properties and their types. For example:- CanvasFactory?: Object | undefined; + CanvasFactory?: { + create(width: number, height: number): HTMLCanvasElement; + reset(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }, width: number, height: number): void; + destroy(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }): void; + } | undefined;Apply this change for all occurrences of the
Object
type in this file.Also applies to: 86-86, 106-106, 204-204, 210-210, 430-430, 811-811, 815-815, 837-837, 887-887, 906-906, 982-982, 1057-1057, 1289-1289, 1293-1293, 1304-1304
🧰 Tools
🪛 Biome
[error] 28-28: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
710-710: 🛠️ Refactor suggestion
⚠️ Potential issueAvoid using the
Function
type. Use a more specific function type instead.The
Function
type accepts any function-like value, which can be a source of bugs. It's better to explicitly define the function signature.Replace the
Function
type with a more specific function type that defines the parameters and return type. For example:- onPassword: Function; + onPassword: (updatePassword: (password: string) => void, reason: PasswordResponses) => void;Apply this change for all occurrences of the
Function
type in this file.Also applies to: 714-714, 718-718, 722-722, 777-777, 784-784, 1454-1454, 1495-1495
🧰 Tools
🪛 Biome
[error] 710-710: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Caution
Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.
🛑 Comments failed to post (97)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/murmurhash3.d.ts (1)
1-7: 🛠️ Refactor suggestion
Enhance type safety and add documentation.
The type declarations could be improved with stronger typing and comprehensive documentation:
+/** + * MurmurHash3_64 implements the 64-bit variant of MurmurHash3, a non-cryptographic hash function + * optimized for performance. NOT suitable for cryptographic purposes. + */ export class MurmurHash3_64 { + /** + * Creates a new MurmurHash3_64 instance + * @param seed The seed value for the hash (typically a number) + */ - constructor(seed: any); + constructor(seed: number); + /** First 32 bits of the 64-bit hash */ h1: number; + /** Second 32 bits of the 64-bit hash */ h2: number; - update(input: any): void; + /** + * Updates the hash with new input + * @param input The input to hash (string, number, or Uint8Array) + */ + update(input: string | number | Uint8Array): void; + /** + * Returns the final hash value as a hexadecimal string + * @returns A string containing the 64-bit hash value in hexadecimal + */ hexdigest(): string; }Note: MurmurHash3 is designed for performance and is NOT cryptographically secure. Ensure it's only used for performance-oriented scenarios like caching or quick lookups, not for security purposes.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./** * MurmurHash3_64 implements the 64-bit variant of MurmurHash3, a non-cryptographic hash function * optimized for performance. NOT suitable for cryptographic purposes. */ export class MurmurHash3_64 { /** * Creates a new MurmurHash3_64 instance * @param seed The seed value for the hash (typically a number) */ constructor(seed: number); /** First 32 bits of the 64-bit hash */ h1: number; /** Second 32 bits of the 64-bit hash */ h2: number; /** * Updates the hash with new input * @param input The input to hash (string, number, or Uint8Array) */ update(input: string | number | Uint8Array): void; /** * Returns the final hash value as a hexadecimal string * @returns A string containing the 64-bit hash value in hexadecimal */ hexdigest(): string; }
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/metadata.d.ts (1)
1-10: 🛠️ Refactor suggestion
Improve type safety by replacing
any
with specific typesThe current implementation uses
any
type extensively, which bypasses TypeScript's type checking benefits. Consider using more specific types to improve type safety and developer experience.+interface PdfMetadataRaw { + Title?: string; + Author?: string; + Subject?: string; + Keywords?: string; + Creator?: string; + Producer?: string; + CreationDate?: string; + ModificationDate?: string; + [key: string]: string | undefined; +} + +interface PdfMetadataParsed { + info: PdfMetadataRaw; + metadata?: any; // XMP metadata if available +} + declare class Metadata { constructor({ parsedData, rawData }: { - parsedData: any; - rawData: any; + parsedData: PdfMetadataParsed; + rawData: PdfMetadataRaw; }); - getRaw(): any; - get(name: any): any; - getAll(): any; - has(name: any): any; + getRaw(): PdfMetadataRaw; + get(name: keyof PdfMetadataRaw): string | undefined; + getAll(): PdfMetadataParsed; + has(name: keyof PdfMetadataRaw): boolean; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.interface PdfMetadataRaw { Title?: string; Author?: string; Subject?: string; Keywords?: string; Creator?: string; Producer?: string; CreationDate?: string; ModificationDate?: string; [key: string]: string | undefined; } interface PdfMetadataParsed { info: PdfMetadataRaw; metadata?: any; // XMP metadata if available } declare class Metadata { constructor({ parsedData, rawData }: { parsedData: PdfMetadataParsed; rawData: PdfMetadataRaw; }); getRaw(): PdfMetadataRaw; get(name: keyof PdfMetadataRaw): string | undefined; getAll(): PdfMetadataParsed; has(name: keyof PdfMetadataRaw): boolean; }
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReader.razor (1)
4-14: 🛠️ Refactor suggestion
Add loading states and accessibility features.
The current implementation lacks:
- Loading states for better user experience
- Fallback content when PDF fails to load
- Accessibility features for canvas elements
@if (RenderAllPages) { + @if (IsLoading) + { + <div class="bit-pdf-reader__loading" role="status"> + <span class="visually-hidden">Loading PDF document...</span> + </div> + } for (int i = 0; i < _numberOfPages; i++) { - <canvas @key="@($"{Config.Id}-{i+1}")" id="@($"{Config.Id}-{i+1}")" style="@CanvasStyle" class="@CanvasClass" /> + <div class="bit-pdf-reader__page" role="region" aria-label="@($"Page {i + 1} of {_numberOfPages}")"> + <canvas + @key="@($"{Config.Id}-{i+1}")" + id="@($"{Config.Id}-{i+1}")" + style="@CanvasStyle" + class="@CanvasClass" + aria-hidden="true" + /> + </div> } } else { - <canvas id="@Config.Id" style="@CanvasStyle" class="@CanvasClass" /> + <div class="bit-pdf-reader__page" role="region" aria-label="@($"Page {CurrentPage} of {_numberOfPages}")"> + <canvas + id="@Config.Id" + style="@CanvasStyle" + class="@CanvasClass" + aria-hidden="true" + /> + </div> } +@if (HasError) +{ + <div class="bit-pdf-reader__error" role="alert"> + <p>Failed to load PDF document. @ErrorMessage</p> + </div> +}Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/optional_content_config.d.ts (2)
6-11: 🛠️ Refactor suggestion
Strengthen type safety by replacing 'any' with specific types.
The visibility management methods use 'any' types extensively, which bypasses TypeScript's type checking benefits.
- isVisible(group: any): any; + isVisible(group: OptionalContentGroup): boolean; - setVisibility(id: any, visible?: boolean): void; + setVisibility(groupId: string, visible?: boolean): void; setOCGState({ state, preserveRB }: { - state: any; - preserveRB: any; + state: Record<string, boolean>; + preserveRB: boolean; }): void;Consider defining an interface for
OptionalContentGroup
:interface OptionalContentGroup { id: string; name: string; visible: boolean; }
12-16: 🛠️ Refactor suggestion
Improve return type specificity for utility methods.
The utility methods return 'any' type, which should be replaced with more specific types.
get hasInitialVisibility(): boolean; - getOrder(): any; + getOrder(): OptionalContentGroup[]; - getGroups(): any; + getGroups(): Map<string, OptionalContentGroup>; - getGroup(id: any): any; + getGroup(id: string): OptionalContentGroup | undefined; getHash(): string;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.get hasInitialVisibility(): boolean; getOrder(): OptionalContentGroup[]; getGroups(): Map<string, OptionalContentGroup>; getGroup(id: string): OptionalContentGroup | undefined; getHash(): string;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/toolbar.d.ts (2)
1-12: 🛠️ Refactor suggestion
Enhance type safety and documentation for EditorToolbar class.
The class definition needs improvements in several areas:
- Replace
any
types with specific interfaces/types- Add TSDoc comments for public methods
- Specify access modifiers
- Use conventional naming for private fields
Consider applying these changes:
+ /** Editor toolbar component for PDF annotations */ declare class EditorToolbar { - static "__#4@#l10nRemove": null; + private static readonly l10nRemove: null; - static "__#4@#pointerDown"(e: any): void; + private static pointerDown(event: PointerEvent): void; + /** Creates a new editor toolbar instance */ - constructor(editor: any); + constructor(editor: PDFEditor); + /** Renders the toolbar and returns the container element */ - render(): HTMLDivElement; + public render(): HTMLDivElement; + /** Gets the toolbar's container element */ - get div(): null; + public get div(): HTMLDivElement | null; + /** Hides the toolbar */ - hide(): void; + public hide(): void; + /** Shows the toolbar */ - show(): void; + public show(): void; + /** Adds alternative text to the current selection */ - addAltText(altText: any): Promise<void>; + public addAltText(altText: string): Promise<void>; + /** Adds a color picker to the toolbar */ - addColorPicker(colorPicker: any): void; + public addColorPicker(colorPicker: ColorPicker): void; + /** Removes the toolbar */ - remove(): void; + public remove(): void; }Committable suggestion skipped: line range outside the PR's diff.
13-17: 🛠️ Refactor suggestion
Improve type safety and documentation for HighlightToolbar class.
The class needs better type definitions and documentation:
- Replace
any
types with specific interfaces/types- Add descriptive parameter names
- Add TSDoc comments
- Specify access modifiers
Consider applying these changes:
+ /** Toolbar for text highlight operations */ declare class HighlightToolbar { + /** Creates a new highlight toolbar instance */ - constructor(uiManager: any); + constructor(uiManager: PDFUIManager); + /** + * Shows the highlight toolbar + * @param containerElement - The parent element to attach the toolbar to + * @param highlightBoxes - The highlight box coordinates + * @param isLeftToRight - Text direction for proper toolbar positioning + */ - show(parent: any, boxes: any, isLTR: any): void; + public show( + containerElement: HTMLElement, + highlightBoxes: HighlightBox[], + isLeftToRight: boolean + ): void; + /** Hides the highlight toolbar */ - hide(): void; + public hide(): void; } + interface HighlightBox { + x: number; + y: number; + width: number; + height: number; + }Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/image_utils.d.ts (1)
1-12: 🛠️ Refactor suggestion
Enhance type safety by replacing
any
with specific types.The current implementation uses
any
type extensively, which bypasses TypeScript's type checking benefits. Consider using more specific types for better type safety and developer experience.export function convertBlackAndWhiteToRGBA({ src, srcPos, dest, width, height, nonBlackColor, inverseDecode, }: { - src: any; - srcPos?: number | undefined; - dest: any; - width: any; - height: any; + src: Uint8Array | Uint8ClampedArray; + srcPos?: number; + dest: Uint8ClampedArray; + width: number; + height: number; nonBlackColor?: number | undefined; inverseDecode?: boolean | undefined; }): { srcPos: number; destPos: number; };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.export function convertBlackAndWhiteToRGBA({ src, srcPos, dest, width, height, nonBlackColor, inverseDecode, }: { src: Uint8Array | Uint8ClampedArray; srcPos?: number; dest: Uint8ClampedArray; width: number; height: number; nonBlackColor?: number | undefined; inverseDecode?: boolean | undefined; }): { srcPos: number; destPos: number; };
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/network_utils.d.ts (3)
13-13: 🛠️ Refactor suggestion
Enhance status validation type safety
The status parameter should be explicitly typed as a number.
-declare function validateResponseStatus(status: any): boolean; +declare function validateResponseStatus(status: number): boolean;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare function validateResponseStatus(status: number): boolean;
1-3: 🛠️ Refactor suggestion
Strengthen type safety for HTTP utility functions
The current type declarations use
any
which defeats TypeScript's type checking benefits. Consider using more specific types:-declare function createHeaders(isHttp: any, httpHeaders: any): Headers; +declare function createHeaders(isHttp: boolean, httpHeaders: Record<string, string>): Headers; -declare function createResponseStatusError(status: any, url: any): MissingPDFException | UnexpectedResponseException; +declare function createResponseStatusError(status: number, url: string): MissingPDFException | UnexpectedResponseException; -declare function extractFilenameFromHeader(responseHeaders: any): string | null; +declare function extractFilenameFromHeader(responseHeaders: Headers | Record<string, string>): string | null;Also, consider adding JSDoc comments to document the purpose and behavior of each function.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare function createHeaders(isHttp: boolean, httpHeaders: Record<string, string>): Headers; declare function createResponseStatusError(status: number, url: string): MissingPDFException | UnexpectedResponseException; declare function extractFilenameFromHeader(responseHeaders: Headers | Record<string, string>): string | null;
4-12: 🛠️ Refactor suggestion
Improve type definitions for range request validation
The current parameter type uses a complex object with all
any
types, which could lead to runtime errors.-declare function validateRangeRequestCapabilities({ responseHeaders, isHttp, rangeChunkSize, disableRange, }: { - responseHeaders: any; - isHttp: any; - rangeChunkSize: any; - disableRange: any; -}): { - allowRangeRequests: boolean; - suggestedLength: undefined; -}; +interface RangeRequestOptions { + responseHeaders: Headers | Record<string, string>; + isHttp: boolean; + rangeChunkSize: number; + disableRange: boolean; +} + +interface RangeRequestCapabilities { + allowRangeRequests: boolean; + suggestedLength: undefined; +} + +declare function validateRangeRequestCapabilities(options: RangeRequestOptions): RangeRequestCapabilities;This improves type safety and makes the code more maintainable.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.interface RangeRequestOptions { responseHeaders: Headers | Record<string, string>; isHttp: boolean; rangeChunkSize: number; disableRange: boolean; } interface RangeRequestCapabilities { allowRangeRequests: boolean; suggestedLength: undefined; } declare function validateRangeRequestCapabilities(options: RangeRequestOptions): RangeRequestCapabilities;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/node_utils.d.ts (1)
15-18: 🛠️ Refactor suggestion
Refactor static class to standalone functions.
Consider converting this static-only class to standalone functions for better modularity and add specific types.
-declare class NodePackages { - static get promise(): any; - static get(name: any): any; -} +declare function getNodePackagePromise(): Promise<void>; +declare function getNodePackage(name: string): unknown;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare function getNodePackagePromise(): Promise<void>; declare function getNodePackage(name: string): unknown;
🧰 Tools
🪛 Biome
[error] 15-18: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/color_picker.d.ts (4)
8-9: 🛠️ Refactor suggestion
Add method documentation and improve type safety.
The public methods lack JSDoc documentation and some parameters use the unsafe
any
type.Consider these improvements:
declare class ColorPicker { + /** Renders the color picker button element */ renderButton(): HTMLButtonElement; + /** Renders the main color selection dropdown */ renderMainDropdown(): HTMLDivElement; hideDropdown(): void; - updateColor(color: any): void; + /** Updates the currently selected color + * @param color The color value in hex format (e.g., #RRGGBB) + */ + updateColor(color: string): void; + /** Cleans up resources used by the color picker */ destroy(): void;Also applies to: 15-15, 17-18
10-14: 🛠️ Refactor suggestion
Improve event typing and method visibility.
The keyboard event handlers use the unsafe
any
type, and the methods use underscore prefix instead of proper TypeScript visibility modifiers.Consider these improvements:
declare class ColorPicker { - _colorSelectFromKeyboard(event: any): void; - _moveToNext(event: any): void; - _moveToPrevious(event: any): void; - _moveToBeginning(event: any): void; - _moveToEnd(event: any): void; - _hideDropdownFromKeyboard(): void; + private colorSelectFromKeyboard(event: KeyboardEvent): void; + private moveToNext(event: KeyboardEvent): void; + private moveToPrevious(event: KeyboardEvent): void; + private moveToBeginning(event: KeyboardEvent): void; + private moveToEnd(event: KeyboardEvent): void; + private hideDropdownFromKeyboard(): void;Also applies to: 16-16
4-7: 🛠️ Refactor suggestion
Strengthen constructor parameter types.
The current type definitions are too permissive and lack proper typing for the
editor
anduiManager
parameters.Consider defining proper interfaces for these parameters:
+interface PdfEditor { + // Add relevant editor properties +} + +interface UiManager { + // Add relevant UI manager properties +} + declare class ColorPicker { constructor({ editor, uiManager }: { - editor?: null | undefined; - uiManager?: null | undefined; + editor?: PdfEditor; + uiManager?: UiManager; });Committable suggestion skipped: line range outside the PR's diff.
1-3: 🛠️ Refactor suggestion
Improve type safety and declaration clarity.
A few suggestions to enhance the type definitions:
- The mangled static property name suggests this is an implementation detail that shouldn't be exposed in the type definitions.
- The
_keyboardManager
getter should have a more specific return type thanany
to provide better type safety.Consider this improvement:
declare class ColorPicker { - static "__#24@#l10nColor": null; - static get _keyboardManager(): any; + static get _keyboardManager(): KeyboardManager;Note: You'll need to either import or declare the
KeyboardManager
type.Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReaderConfig.cs (2)
18-18:
⚠️ Potential issueAdd scale validation.
The Scale property should include validation to ensure it's a positive value, as negative or zero scaling would render the PDF unreadable.
- public double Scale { get; set; } = 1; + private double _scale = 1; + public double Scale + { + get => _scale; + set + { + if (value <= 0) + throw new ArgumentException("Scale must be a positive value"); + _scale = value; + } + }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.private double _scale = 1; public double Scale { get => _scale; set { if (value <= 0) throw new ArgumentException("Scale must be a positive value"); _scale = value; } }
13-13:
⚠️ Potential issueAdd URL validation.
The Url property should include validation to ensure it's not null/empty and is a valid URL format. Consider adding data annotations or implementing validation in the setter.
- public string Url { get; set; } + private string _url; + public string Url + { + get => _url; + set + { + if (string.IsNullOrWhiteSpace(value)) + throw new ArgumentException("URL cannot be null or empty"); + if (!Uri.TryCreate(value, UriKind.Absolute, out _)) + throw new ArgumentException("Invalid URL format"); + _url = value; + } + }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.private string _url; public string Url { get => _url; set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("URL cannot be null or empty"); if (!Uri.TryCreate(value, UriKind.Absolute, out _)) throw new ArgumentException("Invalid URL format"); _url = value; } }
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/xfa_text.d.ts (2)
1-2: 🛠️ Refactor suggestion
Consider converting static-only class to standalone functions.
The class currently only contains static methods, which suggests it's being used as a namespace. Consider restructuring this as a module with standalone functions for better maintainability and adherence to TypeScript best practices.
- declare class XfaText { + declare module XfaText {Committable suggestion skipped: line range outside the PR's diff.
8-12: 🛠️ Refactor suggestion
Improve type safety by defining a specific interface for XFA tree.
Using the broad
Object
type reduces type safety. Consider creating a specific interface that describes the expected structure of the XFA tree.+ interface XfaNode { + name: string; + children?: XfaNode[]; + value?: string; + } - static textContent(xfa: Object): TextContent; + static textContent(xfa: XfaNode): TextContent;Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 12-12: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/scripting_utils.d.ts (1)
1-16: 🛠️ Refactor suggestion
Enhance type safety and consider functional approach.
The color conversion utilities would benefit from several improvements:
- Replace
any
types with specific numeric types for better type safety- Consider converting the static class to standalone functions
- Add JSDoc comments to document the color space conversions
-export class ColorConverters { - static CMYK_G([c, y, m, k]: [any, any, any, any]): (string | number)[]; - static G_CMYK([g]: [any]): (string | number)[]; - // ... other methods -} +/** Converts color values between different color spaces */ +export const ColorConverters = { + /** Convert CMYK to Grayscale + * @param c - Cyan value (0-100) + * @param m - Magenta value (0-100) + * @param y - Yellow value (0-100) + * @param k - Key (Black) value (0-100) + * @returns Grayscale value array + */ + CMYK_G: ([c, m, y, k]: [number, number, number, number]): number[] => { + // Implementation + }, + + /** Convert Grayscale to CMYK + * @param g - Grayscale value (0-255) + * @returns CMYK values as [c, m, y, k] + */ + G_CMYK: ([g]: [number]): number[] => { + // Implementation + }, + // ... other methods with proper typing } as const;Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 1-16: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReaderJsInterop.cs (4)
5-8: 🛠️ Refactor suggestion
Add input validation and error handling.
The initialization method should validate inputs and handle potential JavaScript initialization failures:
- Validate that
scripts
is not null and contains items- Consider wrapping the JS invocation in try-catch for better error handling
public static ValueTask BitPdfReaderInitPdfJs(this IJSRuntime jsRuntime, IEnumerable<string> scripts) { + ArgumentNullException.ThrowIfNull(jsRuntime); + ArgumentNullException.ThrowIfNull(scripts); + + if (!scripts.Any()) + throw new ArgumentException("At least one script path must be provided.", nameof(scripts)); + return jsRuntime.InvokeVoidAsync("BitBlazorUI.BitPdfReader.init", scripts); }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.public static ValueTask BitPdfReaderInitPdfJs(this IJSRuntime jsRuntime, IEnumerable<string> scripts) { ArgumentNullException.ThrowIfNull(jsRuntime); ArgumentNullException.ThrowIfNull(scripts); if (!scripts.Any()) throw new ArgumentException("At least one script path must be provided.", nameof(scripts)); return jsRuntime.InvokeVoidAsync("BitBlazorUI.BitPdfReader.init", scripts); }
15-18: 🛠️ Refactor suggestion
Add parameter validation for render method.
The render method should validate its parameters and handle potential rendering failures:
- Validate id is not null/empty
- Validate pageNumber is positive
public static ValueTask BitPdfReaderRenderPage(this IJSRuntime jsRuntime, string id, int pageNumber) { + ArgumentNullException.ThrowIfNull(jsRuntime); + ArgumentException.ThrowIfNullOrEmpty(id, nameof(id)); + if (pageNumber < 1) + throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number must be positive."); + return jsRuntime.InvokeVoidAsync("BitBlazorUI.BitPdfReader.renderPage", id, pageNumber); }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.public static ValueTask BitPdfReaderRenderPage(this IJSRuntime jsRuntime, string id, int pageNumber) { ArgumentNullException.ThrowIfNull(jsRuntime); ArgumentException.ThrowIfNullOrEmpty(id, nameof(id)); if (pageNumber < 1) throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number must be positive."); return jsRuntime.InvokeVoidAsync("BitBlazorUI.BitPdfReader.renderPage", id, pageNumber); }
20-23: 🛠️ Refactor suggestion
Consider consolidating rendering logic and add validation.
The refresh method appears to duplicate rendering logic. Consider:
- Adding parameter validation
- Potentially consolidating with
renderPage
method if the underlying logic is similar- Adding error handling for refresh failures
public static ValueTask BitPdfReaderRefreshPage(this IJSRuntime jsRuntime, BitPdfReaderConfig config, int pageNumber) { + ArgumentNullException.ThrowIfNull(jsRuntime); + ArgumentNullException.ThrowIfNull(config); + if (pageNumber < 1) + throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number must be positive."); + return jsRuntime.InvokeVoidAsync("BitBlazorUI.BitPdfReader.refreshPage", config, pageNumber); }Committable suggestion skipped: line range outside the PR's diff.
10-13: 🛠️ Refactor suggestion
Enhance error handling and documentation for setup method.
The setup method should:
- Validate the config parameter
- Document that the return value represents the page count
- Handle potential setup failures (invalid PDF, network issues)
+/// <summary> +/// Sets up a PDF document and returns its total page count. +/// </summary> +/// <param name="jsRuntime">The JS runtime instance.</param> +/// <param name="config">The PDF reader configuration.</param> +/// <returns>The total number of pages in the PDF document.</returns> +/// <exception cref="ArgumentNullException">Thrown when parameters are null.</exception> public static ValueTask<int> BitPdfReaderSetupPdfDoc(this IJSRuntime jsRuntime, BitPdfReaderConfig config) { + ArgumentNullException.ThrowIfNull(jsRuntime); + ArgumentNullException.ThrowIfNull(config); + ArgumentException.ThrowIfNullOrEmpty(config.Url, nameof(config.Url)); + return jsRuntime.InvokeAsync<int>("BitBlazorUI.BitPdfReader.setup", config); }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./// <summary> /// Sets up a PDF document and returns its total page count. /// </summary> /// <param name="jsRuntime">The JS runtime instance.</param> /// <param name="config">The PDF reader configuration.</param> /// <returns>The total number of pages in the PDF document.</returns> /// <exception cref="ArgumentNullException">Thrown when parameters are null.</exception> public static ValueTask<int> BitPdfReaderSetupPdfDoc(this IJSRuntime jsRuntime, BitPdfReaderConfig config) { ArgumentNullException.ThrowIfNull(jsRuntime); ArgumentNullException.ThrowIfNull(config); ArgumentException.ThrowIfNullOrEmpty(config.Url, nameof(config.Url)); return jsRuntime.InvokeAsync<int>("BitBlazorUI.BitPdfReader.setup", config); }
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/alt_text.d.ts (5)
10-11:
⚠️ Potential issueImprove type consistency and error handling for guessed text
The guessed text getter and setter have inconsistent types and lack error handling:
- get guessedText(): null; - setGuessedText(guessedText: any): Promise<void>; + get guessedText(): string | null; + /** + * Sets the guessed text content + * @param guessedText The text to set + * @throws {Error} If text processing fails + */ + setGuessedText(guessedText: string | null): Promise<void>;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.get guessedText(): string | null; /** * Sets the guessed text content * @param guessedText The text to set * @throws {Error} If text processing fails */ setGuessedText(guessedText: string | null): Promise<void>;
12-18: 🛠️ Refactor suggestion
Define proper interfaces for serialization
The serialization methods need proper TypeScript interfaces and return types:
+ interface AltTextData { + altText: string | null; + decorative: boolean; + guessedText: string | null; + textWithDisclaimer: string | null; + } + - toggleAltTextBadge(visibility?: boolean): void; + toggleAltTextBadge(visibility?: boolean): boolean; - serialize(isForCopying: any): { - altText: null; - decorative: boolean; - guessedText: null; - textWithDisclaimer: null; - }; + serialize(isForCopying: boolean): AltTextData;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.interface AltTextData { altText: string | null; decorative: boolean; guessedText: string | null; textWithDisclaimer: string | null; } toggleAltTextBadge(visibility?: boolean): boolean; serialize(isForCopying: boolean): AltTextData;
2-4: 🛠️ Refactor suggestion
Improve type safety for static members
The static members lack proper TypeScript types which reduces type safety. Consider:
- Using a more specific type than
any
forl10nPromise
- Using a proper naming convention for the localization button property
- static "__#35@#l10nNewButton": null; - static _l10nPromise: null; - static initialize(l10nPromise: any): void; + static #l10nNewButton: HTMLButtonElement | null; + static _l10nPromise: Promise<L10n> | null; + static initialize(l10nPromise: Promise<L10n>): void;Committable suggestion skipped: line range outside the PR's diff.
5-9: 🛠️ Refactor suggestion
Add proper types and documentation for core methods
The constructor and core methods need proper TypeScript types and documentation:
- constructor(editor: any); - render(): Promise<HTMLButtonElement>; - finish(): void; - isEmpty(): boolean; - hasData(): boolean; + /** + * Creates a new AltText instance + * @param editor The PDF editor instance + */ + constructor(editor: PdfEditor); + /** + * Renders the alt text UI element + * @returns Promise resolving to the rendered button + */ + render(): Promise<HTMLButtonElement>; + /** + * Finalizes the current alt text operation + */ + finish(): void; + /** + * Checks if alt text content is empty + */ + isEmpty(): boolean; + /** + * Checks if alt text data exists + */ + hasData(): boolean;Committable suggestion skipped: line range outside the PR's diff.
22-29:
⚠️ Potential issueAlign data accessor interfaces
The data getter and setter have mismatched interfaces and the cancel parameter appears unused:
+ interface AltTextSetData extends AltTextGetData { + guessedText?: string | null; + textWithDisclaimer?: string | null; + cancel?: boolean; + } + + interface AltTextGetData { + altText: string | null; + decorative: boolean; + } + - set data({ altText, decorative, guessedText, textWithDisclaimer, cancel, }: { - altText: null; - decorative: boolean; - }); - get data(): { - altText: null; - decorative: boolean; - }; + set data(data: AltTextSetData); + get data(): AltTextGetData;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.interface AltTextSetData extends AltTextGetData { guessedText?: string | null; textWithDisclaimer?: string | null; cancel?: boolean; } interface AltTextGetData { altText: string | null; decorative: boolean; } set data(data: AltTextSetData); get data(): AltTextGetData;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/draw_layer.d.ts (3)
14-17: 🛠️ Refactor suggestion
Improve constructor parameter typing.
The constructor parameter uses
any
type forpageIndex
, which reduces type safety.Consider applying this improvement:
constructor({ pageIndex }: { - pageIndex: any; + pageIndex: number; }); - pageIndex: any; + pageIndex: number;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.constructor({ pageIndex }: { pageIndex: number; }); pageIndex: number;
6-13: 🛠️ Refactor suggestion
Improve type safety and method naming.
- The static getter
_svgFactory
returnsany
type, which reduces type safety.- The static method name
"__#28@#setBox"
appears to be a mangled private field, which might cause issues with different JavaScript runtimes.Consider applying these improvements:
declare class DrawLayer { - static get _svgFactory(): any; + static get _svgFactory(): SVGFactory; - static "__#28@#setBox"(element: any, { x, y, width, height }?: { + private static setBox(element: SVGElement, { x, y, width, height }?: { x?: number | undefined; y?: number | undefined; width?: number | undefined; height?: number | undefined; }): void;Committable suggestion skipped: line range outside the PR's diff.
18-37: 🛠️ Refactor suggestion
Add type safety to instance methods.
Most methods use
any
type for parameters, which reduces type safety and IDE support.Consider applying these improvements:
- setParent(parent: any): void; + setParent(parent: HTMLElement): void; - highlight(outlines: any, color: any, opacity: any, isPathUpdatable?: boolean): { + highlight(outlines: SVGPathElement[], color: string, opacity: number, isPathUpdatable?: boolean): { id: number; clipPathId: string; }; - highlightOutline(outlines: any): number; + highlightOutline(outlines: SVGPathElement[]): number; - finalizeLine(id: any, line: any): void; + finalizeLine(id: number, line: SVGPathElement): void; - updateLine(id: any, line: any): void; + updateLine(id: number, line: SVGPathElement): void; - removeFreeHighlight(id: any): void; + removeFreeHighlight(id: number): void; - updatePath(id: any, line: any): void; + updatePath(id: number, line: SVGPathElement): void; - updateBox(id: any, box: any): void; + updateBox(id: number, box: { x: number; y: number; width: number; height: number }): void; - show(id: any, visible: any): void; + show(id: number, visible: boolean): void; - rotate(id: any, angle: any): void; + rotate(id: number, angle: number): void; - changeColor(id: any, color: any): void; + changeColor(id: number, color: string): void; - changeOpacity(id: any, opacity: any): void; + changeOpacity(id: number, opacity: number): void; - addClass(id: any, className: any): void; + addClass(id: number, className: string): void; - removeClass(id: any, className: any): void; + removeClass(id: number, className: string): void; - getSVGRoot(id: any): any; + getSVGRoot(id: number): SVGElement | null; - remove(id: any): void; + remove(id: number): void;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.setParent(parent: HTMLElement): void; highlight(outlines: SVGPathElement[], color: string, opacity: number, isPathUpdatable?: boolean): { id: number; clipPathId: string; }; highlightOutline(outlines: SVGPathElement[]): number; finalizeLine(id: number, line: SVGPathElement): void; updateLine(id: number, line: SVGPathElement): void; removeFreeHighlight(id: number): void; updatePath(id: number, line: SVGPathElement): void; updateBox(id: number, box: { x: number; y: number; width: number; height: number }): void; show(id: number, visible: boolean): void; rotate(id: number, angle: number): void; changeColor(id: number, color: string): void; changeOpacity(id: number, opacity: number): void; addClass(id: number, className: string): void; removeClass(id: number, className: string): void; getSVGRoot(id: number): SVGElement | null; remove(id: number): void; destroy(): void;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/stamp.d.ts (2)
21-44: 🛠️ Refactor suggestion
Define explicit interfaces and improve type safety.
The instance methods need better type definitions and documentation:
+ interface ImageData { + width: number; + height: number; + data: Uint8ClampedArray; + } + + interface CanvasResult { + canvas: HTMLCanvasElement | null; + width: number; + height: number; + imageData: ImageData | null; + } + + interface SerializedStampData { + type: string; + content: string; + position: { x: number; y: number }; + // Add other relevant properties + } constructor(params: any); /** @inheritdoc */ get telemetryFinalData(): { type: string; hasAltText: boolean; }; + /** + * Attempts to guess alt text for the stamp using ML. + * @param imageData Optional image data to analyze + * @param updateAltTextData Whether to update existing alt text + * @returns Promise resolving to the guessed alt text + */ - mlGuessAltText(imageData?: null, updateAltTextData?: boolean): Promise<any>; + mlGuessAltText(imageData?: ImageData | null, updateAltTextData?: boolean): Promise<string>; /** + * Creates a copy of the stamp canvas with optional size constraints. + */ - copyCanvas(maxDataDimension: any, maxPreviewDimension: any, createImageData?: boolean): { - canvas: HTMLCanvasElement | null; - width: any; - height: any; - imageData: { - width: any; - height: any; - data: Uint8ClampedArray; - } | null; - }; + copyCanvas( + maxDataDimension: number, + maxPreviewDimension: number, + createImageData?: boolean + ): CanvasResult; /** + * Returns null as stamps don't support alt text images. + * @returns {null} + */ getImageForAltText(): null; /** + * Serializes the stamp annotation for saving or copying. + * @param isForCopying Whether serialization is for copying + * @param context Optional serialization context + * @returns Serialized stamp data or null if serialization fails + */ - serialize(isForCopying?: boolean, context?: null): Object | null; + serialize(isForCopying?: boolean, context?: null): SerializedStampData | null; /** + * Renders the annotation element. Returns null as rendering is handled elsewhere. + * @param annotation The annotation to render + * @returns {null} + */ - renderAnnotationElement(annotation: any): null; + renderAnnotationElement(annotation: SerializedStampData): null;Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 41-41: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
12-20: 🛠️ Refactor suggestion
Improve type safety by replacing 'any' with specific types.
The static methods could benefit from more specific type definitions:
/** + * Checks if the editor can handle the given MIME type for pasting. + * @param mime The MIME type to check + * @returns {boolean} True if the MIME type can be handled */ - static isHandlingMimeForPasting(mime: any): any; + static isHandlingMimeForPasting(mime: string): boolean; /** + * Handles pasting of content into the editor. + * @param item The paste data + * @param parent The parent element */ - static paste(item: any, parent: any): void; + static paste(item: ClipboardItem, parent: HTMLElement): void; + /** + * Computes telemetry data for annotations. + * @param data The annotation data + * @returns Object containing alt text statistics + */ static computeTelemetryFinalData(data: any): { - hasAltText: any; - hasNoAltText: any; + hasAltText: number; + hasNoAltText: number; }; /** + * Deserializes annotation data into an editor instance. + * @param data The serialized annotation data + * @param parent The parent element + * @param uiManager The UI manager instance + * @returns Promise resolving to an editor instance or null */ - static deserialize(data: any, parent: any, uiManager: any): Promise<AnnotationEditor | null>; + static deserialize( + data: SerializedStampData, + parent: HTMLElement, + uiManager: UIManager + ): Promise<AnnotationEditor | null>;Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/base_factory.d.ts (5)
52-59: 🛠️ Refactor suggestion
Add proper SVG type definitions to BaseSVGFactory.
The class needs specific SVG-related types for better type safety.
Consider applying these type improvements:
declare class BaseSVGFactory { - create(width: any, height: any, skipDimensions?: boolean): void; + create(width: number, height: number, skipDimensions?: boolean): SVGSVGElement; - createElement(type: any): void; + createElement(type: string): SVGElement; /** * @ignore */ - _createSVG(type: any): void; + _createSVG(type: string): SVGElement; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseSVGFactory { create(width: number, height: number, skipDimensions?: boolean): SVGSVGElement; createElement(type: string): SVGElement; /** * @ignore */ _createSVG(type: string): SVGElement; }
16-30: 🛠️ Refactor suggestion
Enhance type definitions in BaseCMapReaderFactory.
The class would benefit from more specific types for better type safety and documentation.
Consider applying these type improvements:
declare class BaseCMapReaderFactory { constructor({ baseUrl, isCompressed }: { - baseUrl?: null | undefined; + baseUrl?: string | null; isCompressed?: boolean | undefined; }); - baseUrl: any; + baseUrl: string | null; isCompressed: boolean; fetch({ name }: { - name: any; + name: string; - }): Promise<any>; + }): Promise<ArrayBuffer>; /** * @ignore */ - _fetchData(url: any, compressionType: any): void; + _fetchData(url: string, compressionType: string): Promise<ArrayBuffer>; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseCMapReaderFactory { constructor({ baseUrl, isCompressed }: { baseUrl?: string | null; isCompressed?: boolean | undefined; }); baseUrl: string | null; isCompressed: boolean; fetch({ name }: { name: string; }): Promise<ArrayBuffer>; /** * @ignore */ _fetchData(url: string, compressionType: string): Promise<ArrayBuffer>; }
39-51: 🛠️ Refactor suggestion
Improve type safety in BaseStandardFontDataFactory.
The class needs proper typing for font data handling.
Consider applying these type improvements:
declare class BaseStandardFontDataFactory { constructor({ baseUrl }: { - baseUrl?: null | undefined; + baseUrl?: string | null; }); - baseUrl: any; + baseUrl: string | null; fetch({ filename }: { - filename: any; + filename: string; - }): Promise<any>; + }): Promise<ArrayBuffer>; /** * @ignore */ - _fetchData(url: any): void; + _fetchData(url: string): Promise<ArrayBuffer>; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseStandardFontDataFactory { constructor({ baseUrl }: { baseUrl?: string | null; }); baseUrl: string | null; fetch({ filename }: { filename: string; }): Promise<ArrayBuffer>; /** * @ignore */ _fetchData(url: string): Promise<ArrayBuffer>; }
31-38: 🛠️ Refactor suggestion
Strengthen type definitions in BaseFilterFactory.
The class needs proper typing for color values and filter maps.
Consider applying these type improvements:
+interface ColorRGB { + r: number; + g: number; + b: number; +} + +interface FilterMap { + brightness?: number; + contrast?: number; + grayscale?: number; + filters?: string[]; +} + declare class BaseFilterFactory { - addFilter(maps: any): string; + addFilter(maps: FilterMap): string; - addHCMFilter(fgColor: any, bgColor: any): string; + addHCMFilter(fgColor: ColorRGB, bgColor: ColorRGB): string; - addAlphaFilter(map: any): string; + addAlphaFilter(map: { alpha: number }): string; - addLuminosityFilter(map: any): string; + addLuminosityFilter(map: { luminosity: number }): string; addHighlightHCMFilter( - filterName: any, - fgColor: any, - bgColor: any, - newFgColor: any, - newBgColor: any + filterName: string, + fgColor: ColorRGB, + bgColor: ColorRGB, + newFgColor: ColorRGB, + newBgColor: ColorRGB ): string; destroy(keepHCM?: boolean): void; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.interface ColorRGB { r: number; g: number; b: number; } interface FilterMap { brightness?: number; contrast?: number; grayscale?: number; filters?: string[]; } declare class BaseFilterFactory { addFilter(maps: FilterMap): string; addHCMFilter(fgColor: ColorRGB, bgColor: ColorRGB): string; addAlphaFilter(map: { alpha: number }): string; addLuminosityFilter(map: { luminosity: number }): string; addHighlightHCMFilter( filterName: string, fgColor: ColorRGB, bgColor: ColorRGB, newFgColor: ColorRGB, newBgColor: ColorRGB ): string; destroy(keepHCM?: boolean): void; }
1-15:
⚠️ Potential issueImprove type safety in BaseCanvasFactory.
The class has several type-related issues that should be addressed:
- The
canvas
property in thecreate()
method return type is incorrectly typed asvoid
- Extensive use of
any
type reduces type safetyConsider applying these type improvements:
declare class BaseCanvasFactory { constructor({ enableHWA }: { enableHWA?: boolean | undefined; }); - create(width: any, height: any): { - canvas: void; + create(width: number, height: number): { + canvas: HTMLCanvasElement; context: any; }; - reset(canvasAndContext: any, width: any, height: any): void; - destroy(canvasAndContext: any): void; + reset(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }, + width: number, height: number): void; + destroy(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }): void; /** * @ignore */ - _createCanvas(width: any, height: any): void; + _createCanvas(width: number, height: number): HTMLCanvasElement; }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.declare class BaseCanvasFactory { constructor({ enableHWA }: { enableHWA?: boolean | undefined; }); create(width: number, height: number): { canvas: HTMLCanvasElement; context: any; }; reset(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }, width: number, height: number): void; destroy(canvasAndContext: { canvas: HTMLCanvasElement, context: CanvasRenderingContext2D }): void; /** * @ignore */ _createCanvas(width: number, height: number): HTMLCanvasElement; }
🧰 Tools
🪛 Biome
[error] 6-6: void is confusing outside a return type or a type parameter.
Unsafe fix: Use undefined instead.
(lint/suspicious/noConfusingVoidType)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/shared/message_handler.d.ts (4)
12-13: 🛠️ Refactor suggestion
Define proper types for event handling.
The event handler and action registration need proper typing.
- _onComObjOnMessage: (event: any) => void; - on(actionName: any, handler: any): void; + private _onComObjOnMessage: (event: MessageEvent) => void; + on(actionName: string, handler: (data: unknown) => void): void;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.private _onComObjOnMessage: (event: MessageEvent) => void; on(actionName: string, handler: (data: unknown) => void): void;
1-5: 🛠️ Refactor suggestion
Improve type safety by replacing 'any' with specific types.
The extensive use of
any
reduces type safety. Consider defining proper types:+interface ComObject { + postMessage(message: unknown, transfers?: ArrayBuffer[]): void; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} declare class MessageHandler { - constructor(sourceName: any, targetName: any, comObj: any); - sourceName: any; - targetName: any; - comObj: any; + constructor(sourceName: string, targetName: string, comObj: ComObject); + sourceName: string; + targetName: string; + readonly comObj: ComObject;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.interface ComObject { postMessage(message: unknown, transfers?: ArrayBuffer[]): void; addEventListener(type: string, listener: EventListener): void; removeEventListener(type: string, listener: EventListener): void; } declare class MessageHandler { constructor(sourceName: string, targetName: string, comObj: ComObject); sourceName: string; targetName: string; readonly comObj: ComObject;
6-11: 🛠️ Refactor suggestion
Define proper types for internal tracking properties.
The properties need proper typing to ensure type safety and improve maintainability.
- callbackId: number; - streamId: number; - streamSinks: any; - streamControllers: any; - callbackCapabilities: any; - actionHandler: any; + private callbackId: number; + private streamId: number; + private streamSinks: Map<number, WritableStreamDefaultWriter>; + private streamControllers: Map<number, ReadableStreamController<unknown>>; + private callbackCapabilities: Map<number, { resolve: (data: unknown) => void; reject: (reason: any) => void; }>; + private actionHandler: Map<string, (data: unknown) => void>;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.private callbackId: number; private streamId: number; private streamSinks: Map<number, WritableStreamDefaultWriter>; private streamControllers: Map<number, ReadableStreamController<unknown>>; private callbackCapabilities: Map<number, { resolve: (data: unknown) => void; reject: (reason: any) => void; }>; private actionHandler: Map<string, (data: unknown) => void>;
14-40: 🛠️ Refactor suggestion
Improve type definitions for message handling methods.
- Replace the broad
Object
type with a properQueuingStrategy
interface- Consider using a more flexible type for the data parameter
+interface QueuingStrategy<T = any> { + highWaterMark?: number; + size?: (chunk: T) => number; +} - send(actionName: string, data: JSON, transfers?: any[] | undefined): void; + send(actionName: string, data: unknown, transfers?: ArrayBuffer[]): void; - sendWithPromise(actionName: string, data: JSON, transfers?: any[] | undefined): Promise<any>; + sendWithPromise<T>(actionName: string, data: unknown, transfers?: ArrayBuffer[]): Promise<T>; sendWithStream( actionName: string, - data: JSON, - queueingStrategy: Object, - transfers?: any[] | undefined + data: unknown, + queueingStrategy: QueuingStrategy, + transfers?: ArrayBuffer[] ): ReadableStream;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./** * Sends a message to the comObj to invoke the action with the supplied data. * @param {string} actionName - Action to call. * @param {JSON} data - JSON data to send. * @param {Array} [transfers] - List of transfers/ArrayBuffers. */ send(actionName: string, data: unknown, transfers?: ArrayBuffer[]): void; /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that the other side will callback with the response. * @param {string} actionName - Action to call. * @param {JSON} data - JSON data to send. * @param {Array} [transfers] - List of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise<T>(actionName: string, data: unknown, transfers?: ArrayBuffer[]): Promise<T>; /** * Sends a message to the comObj to invoke the action with the supplied data. * Expect that the other side will callback to signal 'start_complete'. * @param {string} actionName - Action to call. * @param {JSON} data - JSON data to send. * @param {Object} queueingStrategy - Strategy to signal backpressure based on * internal queue. * @param {Array} [transfers] - List of transfers/ArrayBuffers. * @returns {ReadableStream} ReadableStream to read data in chunks. */ interface QueuingStrategy<T = any> { highWaterMark?: number; size?: (chunk: T) => number; } sendWithStream( actionName: string, data: unknown, queueingStrategy: QueuingStrategy, transfers?: ArrayBuffer[] ): ReadableStream;
🧰 Tools
🪛 Biome
[error] 40-40: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Extras/PdfReader/BitPdfReaderDemo.razor (1)
29-33:
⚠️ Potential issueAdd null checks and loading state handling.
The current implementation uses the null-forgiving operator (!) extensively, which could lead to runtime errors. Consider implementing proper null checks and loading states.
- <BitButton OnClick="() => publicApiPdfReaderRef!.First()">First</BitButton> - <BitButton OnClick="() => publicApiPdfReaderRef!.Prev()">Prev</BitButton> - <BitTag Variant="BitVariant.Outline" Text="@($"{publicApiPdfReaderRef?.CurrentPageNumber.ToString()}/{publicApiPdfReaderRef?.NumberOfPages.ToString()}")" Color="BitColor.Info" /> - <BitButton OnClick="() => publicApiPdfReaderRef!.Next()">Next</BitButton> - <BitButton OnClick="() => publicApiPdfReaderRef!.Last()">Last</BitButton> | + <BitButton Disabled="@(publicApiPdfReaderRef is null)" OnClick="() => publicApiPdfReaderRef?.First()">First</BitButton> + <BitButton Disabled="@(publicApiPdfReaderRef is null)" OnClick="() => publicApiPdfReaderRef?.Prev()">Prev</BitButton> + <BitTag Variant="BitVariant.Outline" Text="@GetPageInfo()" Color="BitColor.Info" /> + <BitButton Disabled="@(publicApiPdfReaderRef is null)" OnClick="() => publicApiPdfReaderRef?.Next()">Next</BitButton> + <BitButton Disabled="@(publicApiPdfReaderRef is null)" OnClick="() => publicApiPdfReaderRef?.Last()">Last</BitButton> |Add this helper method to the code-behind:
private string GetPageInfo() => publicApiPdfReaderRef is null ? "-/-" : $"{publicApiPdfReaderRef.CurrentPageNumber}/{publicApiPdfReaderRef.NumberOfPages}";src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/text_layer.d.ts (2)
19-30:
⚠️ Potential issueReplace generic
Function
type with a specific function signature.The
onBefore
callback should have a more specific type definition to ensure type safety and better IDE support.Apply this change:
- onBefore?: Function | undefined; + onBefore?: (() => void) | undefined;If the callback needs specific parameters or return type, please update the signature accordingly.
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 29-29: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
53-82: 🛠️ Refactor suggestion
Enhance type safety with specific return types.
The methods would benefit from more specific return type annotations instead of using
any
andundefined
.Suggested improvements:
- render(): Promise<any>; + render(): Promise<void>; - update({ viewport, onBefore }: TextLayerUpdateParameters): undefined; + update({ viewport, onBefore }: TextLayerUpdateParameters): void; - cancel(): undefined; + cancel(): void;This would:
- Improve type safety
- Make the API more predictable
- Enhance IDE support and autocompletion
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.constructor({ textContentSource, container, viewport }: TextLayerParameters); /** * Render the textLayer. * @returns {Promise} */ render(): Promise<void>; /** * Update a previously rendered textLayer, if necessary. * @param {TextLayerUpdateParameters} options * @returns {undefined} */ update({ viewport, onBefore }: TextLayerUpdateParameters): void; /** * Cancel rendering of the textLayer. * @returns {undefined} */ cancel(): void; /** * @type {Array<HTMLElement>} HTML elements that correspond to the text items * of the textContent input. * This is output and will initially be set to an empty array. */ get textDivs(): HTMLElement[]; /** * @type {Array<string>} Strings that correspond to the `str` property of * the text items of the textContent input. * This is output and will initially be set to an empty array */ get textContentItemsStr(): string[]; }
src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Extras/PdfReader/BitPdfReaderDemo.razor.cs (1)
131-146: 🛠️ Refactor suggestion
Consider adding maximum scale limit and debouncing.
The zoom functionality could be improved:
- Add a maximum scale limit to prevent performance issues with extremely large scales
- Consider debouncing the refresh operation to prevent rapid consecutive updates
+ private const double MAX_SCALE = 5.0; + private const double MIN_SCALE = 0.25; + private const double SCALE_STEP = 0.25; private async Task ZoomIn() { - scale += 0.25; + if (scale < MAX_SCALE) + { + scale += SCALE_STEP; + } publicApiConfig.Scale = scale; await publicApiPdfReaderRef.Refresh(); } private async Task ZoomOut() { - if (scale > 0.25) + if (scale > MIN_SCALE) { - scale -= 0.25; + scale -= SCALE_STEP; } publicApiConfig.Scale = scale; await publicApiPdfReaderRef.Refresh(); }Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/font_loader.d.ts (3)
32-33: 🛠️ Refactor suggestion
Specify return types for font loading support getters
The getters
isFontLoadingAPISupported
andisSyncFontLoadingSupported
currently returnany
. It would be more precise to define their return type asboolean
.Apply this diff to specify the return types:
- get isFontLoadingAPISupported(): any; + get isFontLoadingAPISupported(): boolean; - get isSyncFontLoadingSupported(): any; + get isSyncFontLoadingSupported(): boolean;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.get isFontLoadingAPISupported(): boolean; get isSyncFontLoadingSupported(): boolean;
2-5:
⚠️ Potential issueCorrect the type annotation for
inspectFont
in the constructorThe
inspectFont
parameter in theFontFaceObject
constructor is currently typed asnull | undefined
, but it should beboolean | undefined
to accurately represent its usage.Apply this diff to fix the type annotation:
constructor(translatedData: any, { disableFontFace, inspectFont }: { disableFontFace?: boolean | undefined; - inspectFont?: null | undefined; + inspectFont?: boolean | undefined; });📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.constructor(translatedData: any, { disableFontFace, inspectFont }: { disableFontFace?: boolean | undefined; inspectFont?: boolean | undefined; });
14-17:
⚠️ Potential issueSpecify the correct type for
styleElement
in the constructorIn the
FontLoader
constructor, thestyleElement
parameter is typed asnull | undefined
. It should beHTMLStyleElement | undefined
to accurately reflect its possible types.Apply this diff to correct the type annotation:
constructor({ ownerDocument, styleElement, }: { ownerDocument?: Document | undefined; - styleElement?: null | undefined; + styleElement?: HTMLStyleElement | undefined; });📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.constructor({ ownerDocument, styleElement, }: { ownerDocument?: Document | undefined; styleElement?: HTMLStyleElement | undefined; });
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/freetext.d.ts (1)
51-51: 🛠️ Refactor suggestion
Avoid using 'Object' as a type; prefer a more specific type.
Using
Object
as a type is discouraged because it is too broad and doesn't provide type safety. It's recommended to useobject
(lowercase) or define a specific interface for the return type.Apply this diff to update the return type:
- serialize(isForCopying?: boolean): Object | null; + serialize(isForCopying?: boolean): object | null;Alternatively, define an interface for the serialized object to enhance type safety.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.serialize(isForCopying?: boolean): object | null;
🧰 Tools
🪛 Biome
[error] 51-51: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/node_stream.d.ts (3)
4-7:
⚠️ Potential issueEnsure 'URL' and 'Headers' types are available in the TypeScript context
The types
URL
andHeaders
are used, but they might not be recognized in some TypeScript configurations. Make sure these types are imported or globally available to prevent type errors.If needed, import the types at the beginning of the file:
import { URL } from 'url'; import { Headers } from 'fetch';Or, if they are globally available in your environment, ensure that the appropriate type definitions are included in your project's TypeScript configuration.
3-13: 🛠️ Refactor suggestion
Specify precise types instead of 'any' for better type safety
Many properties and parameters are currently typed as
any
. Usingany
can undermine the advantages of TypeScript's static type checking. Consider specifying more precise types to enhance code reliability and maintainability.For example:
- constructor(source: any); + constructor(source: PDFSource); - source: any; + source: PDFSource; - getRangeReader(start: any, end: any): PDFNodeStreamFsRangeReader | PDFNodeStreamRangeReader | null; + getRangeReader(start: number, end: number): PDFNodeStreamFsRangeReader | PDFNodeStreamRangeReader | null;Define the
PDFSource
interface to represent the structure of thesource
object.Committable suggestion skipped: line range outside the PR's diff.
28-68: 🛠️ Refactor suggestion
Improve type annotations in base reader classes
The
BaseFullReader
andBaseRangeReader
classes have several properties and methods typed asany
. For stronger type safety and clarity, specify exact types where possible.Examples:
- constructor(stream: any); + constructor(stream: ReadableStream); - _url: any; + _url: string; - read(): any; + read(): Promise<{ value: Uint8Array; done: boolean }>; - cancel(reason: any): void; + cancel(reason: Error): void;Ensure that methods like
read()
and properties like_readableStream
have accurate type annotations reflecting their actual use.Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/transport_stream.d.ts (2)
16-19: 🛠️ Refactor suggestion
Specify parameter types in
_onReceiveData
method.The parameters
begin
andchunk
are typed asany
. Specifying precise types enhances readability and type safety.Apply this diff:
- _onReceiveData({ begin, chunk }: { - begin: any; - chunk: any; - }): void; + _onReceiveData({ begin, chunk }: { + begin: number; + chunk: ArrayBuffer; + }): void;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements._onReceiveData({ begin, chunk }: { begin: number; chunk: ArrayBuffer; }): void;
3-6: 🛠️ Refactor suggestion
Specify explicit types for constructor parameters.
The use of
any
forpdfDataRangeTransport
and the options object reduces type safety. Defining specific types enhances code reliability and maintainability.Apply this diff to specify parameter types:
- constructor(pdfDataRangeTransport: any, { disableRange, disableStream }: { - disableRange?: boolean | undefined; - disableStream?: boolean | undefined; - }); + constructor(pdfDataRangeTransport: PDFDataRangeTransport, { disableRange, disableStream }: { + disableRange?: boolean; + disableStream?: boolean; + });Ensure that
PDFDataRangeTransport
is properly defined or imported.Committable suggestion skipped: line range outside the PR's diff.
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/highlight.d.ts (1)
73-73:
⚠️ Potential issueAvoid using 'Object' as a return type; define a more specific type.
Using
Object
as a return type is discouraged as it doesn't convey the structure of the returned data. Consider defining an explicit interface or type that represents the returned value's shape.Apply this diff to specify a more precise return type:
- serialize(isForCopying?: boolean): Object | null; + serialize(isForCopying?: boolean): SerializedAnnotation | null;Please ensure that
SerializedAnnotation
is defined appropriately to reflect the returned data structure.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 73-73: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/outliner.d.ts (3)
5-8: 🛠️ Refactor suggestion
Specify explicit types instead of 'any' in constructor parameters
Using
any
for the constructor parameters{ x, y }: { x: any; y: any; }
,box: any
,scaleFactor: any
,thickness: any
, andisLTR: any
reduces type safety. Define specific types or interfaces to improve code reliability and maintainability.
62-62:
⚠️ Potential issueReplace
Object
with a specific type for return value ofbox
Returning
Object | null
fromget box()
lacks clarity. Define and use a specific type or interface that represents the structure ofbox
.Apply this change:
- get box(): Object | null; + get box(): BoxType | null;Define the
BoxType
interface:interface BoxType { // Define properties of BoxType here }🧰 Tools
🪛 Biome
[error] 62-62: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
31-31:
⚠️ Potential issueReplace
Object
with a specific interface forboxes
parameterUsing
Object
as a type is discouraged because it provides no type safety. Instead, define an interface for the items in theboxes
array to clarify the expected structure.Apply this change:
- constructor(boxes: Array<Object>, borderWidth?: number, innerMargin?: number, isLTR?: boolean); + interface Box { + // Define the properties of Box here + } + constructor(boxes: Array<Box>, borderWidth?: number, innerMargin?: number, isLTR?: boolean);Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 31-31: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/network.d.ts (4)
3-13: 🛠️ Refactor suggestion
Specify explicit types instead of 'any' in
PDFNetworkStream
classThe
PDFNetworkStream
class usesany
for several properties and method parameters, such as_source
,_manager
, andsource
in the constructor. Defining explicit types enhances type safety and code readability. Please consider specifying precise types based on the expected values.
14-34: 🛠️ Refactor suggestion
Define specific types for properties and parameters in
NetworkManager
The
NetworkManager
class has properties and method parameters typed asany
, includingurl
,httpHeaders
, andwithCredentials
in the constructor, as well as parameters in methods likerequestRange
andrequestFull
. Replacingany
with precise types will improve maintainability and reduce potential runtime errors.
37-65: 🛠️ Refactor suggestion
Use explicit types instead of 'any' in
PDFNetworkStreamFullRequestReader
In the
PDFNetworkStreamFullRequestReader
class, properties like_manager
,_url
, and parameters in the constructor are typed asany
. Specifying accurate types enhances code clarity and leverages TypeScript's type-checking capabilities.
68-85: 🛠️ Refactor suggestion
Avoid using 'any' as types in
PDFNetworkStreamRangeRequestReader
The
PDFNetworkStreamRangeRequestReader
class usesany
for properties_manager
,_url
, and parameters likebegin
andend
. Defining specific types will enhance type safety and help prevent errors during development.src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/ink.d.ts (1)
11-15: 🛠️ Refactor suggestion
Replace 'any' Types with Specific Types for Improved Type Safety
The use of the
any
type reduces type safety and can obscure the intended use of the variables. Specifically:
- Methods:
static initialize(l10n: any, uiManager: any): void;
static updateDefaultParams(type: any, value: any): void;
updateParams(type: any, value: any): void;
- Properties:
color: any;
thickness: any;
opacity: any;
paths: any[];
bezierPath2D: any[];
allRawPaths: any[];
currentPath: any[];
Please specify more precise types for these methods and properties. For example:
- static initialize(l10n: any, uiManager: any): void; + static initialize(l10n: LocalizationService, uiManager: UIManager): void; - static updateDefaultParams(type: any, value: any): void; + static updateDefaultParams(type: string, value: number | string): void; - updateParams(type: any, value: any): void; + updateParams(type: string, value: number | string): void; - color: any; + color: string; - thickness: any; + thickness: number; - opacity: any; + opacity: number; - paths: any[]; + paths: Array<Path2D>; - bezierPath2D: any[]; + bezierPath2D: Array<Path2D>; - allRawPaths: any[]; + allRawPaths: Array<Array<{ x: number; y: number }>>; - currentPath: any[]; + currentPath: Array<{ x: number; y: number }>;Providing specific types enhances type checking and makes the code more self-documenting.
Also applies to: 27-40
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/interfaces.d.ts (2)
7-7: 🛠️ Refactor suggestion
Use
interface
instead ofdeclare class
for interface declarationsThe declarations for
IPDFStream
,IPDFStreamRangeReader
, andIPDFStreamReader
are intended to represent interfaces, as indicated by the@interface
comments. It's more appropriate to use theinterface
keyword in TypeScript for defining interfaces.Apply this diff to update the declarations:
-declare class IPDFStream { +declare interface IPDFStream {-declare class IPDFStreamRangeReader { +declare interface IPDFStreamRangeReader {-declare class IPDFStreamReader { +declare interface IPDFStreamReader {Also applies to: 31-31, 64-64
24-24: 🛠️ Refactor suggestion
Avoid using
Object
as a parameter type; specify a more precise typeUsing
Object
as a type is discouraged because it doesn't provide type safety. Consider defining a more specific type or usingunknown
orany
if the type can vary.Apply this diff to specify a more precise type:
- cancelAllRequests(reason: Object): void; + cancelAllRequests(reason: any): void;- cancel(reason: Object): void; + cancel(reason: any): void;Alternatively, define a specific interface for
reason
to enhance type safety.Also applies to: 57-57, 117-117
🧰 Tools
🪛 Biome
[error] 24-24: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/BitPdfReader.ts (3)
70-70:
⚠️ Potential issueAwait the asynchronous
setup
method to ensure proper initializationThe
setup
method is asynchronous and should be awaited to ensure that the PDF document is fully loaded before proceeding. Not awaiting it might causerenderPage
to execute before setup is complete.Apply this diff to fix the issue:
} else { - BitPdfReader.setup(config); + await BitPdfReader.setup(config); }Committable suggestion skipped: line range outside the PR's diff.
30-37:
⚠️ Potential issueAvoid using
async
functions as Promise executorsUsing an
async
function as a Promise executor is not recommended and can lead to unexpected behavior. It's better to remove theasync
keyword from the executor function and handle asynchronous operations within it.Apply this diff to fix the issue:
-const promise = new Promise(async (resolve: any, reject: any) => { +const promise = new Promise((resolve: any, reject: any) => { try { - for (let url of notAppenedScripts) await addScript(url); + (async () => { + for (let url of notAppenedScripts) await addScript(url); + resolve(); + })(); } catch (e: any) { reject(e); } });📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.const promise = new Promise((resolve: any, reject: any) => { try { (async () => { for (let url of notAppenedScripts) await addScript(url); resolve(); })(); } catch (e: any) { reject(e); } });
🧰 Tools
🪛 Biome
[error] 30-37: Promise executor functions should not be
async
.(lint/suspicious/noAsyncPromiseExecutor)
16-117: 🛠️ Refactor suggestion
Refactor the static-only class into a module with exported functions
The
BitPdfReader
class contains only static members. Refactoring it into a module with exported functions can simplify the code and adhere to best practices by removing unnecessary class structures.Apply this diff to refactor the class into a module:
-namespace BitBlazorUI { - export class BitPdfReader { - private static _initPromise?: Promise<unknown>; - private static _bitPdfReaders = new Map<string, BitPdfReaderConfig>(); +namespace BitBlazorUI { + let _initPromise: Promise<unknown> | undefined; + const _bitPdfReaders = new Map<string, BitPdfReaderConfig>(); - public static async init(scripts: string[]) { + export async function init(scripts: string[]) { // ... rest of the code remains the same, // remove 'static' keywords and adjust references accordingly. } - public static async setup(config: BitPdfReaderConfig) { + export async function setup(config: BitPdfReaderConfig) { // ... rest of the code } - public static async refreshPage(config: BitPdfReaderConfig, pageNumber: number) { + export async function refreshPage(config: BitPdfReaderConfig, pageNumber: number) { // ... rest of the code } - public static async renderPage(id: string, pageNumber: number) { + export async function renderPage(id: string, pageNumber: number) { // ... rest of the code } - } }Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 16-117: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
[error] 30-37: Promise executor functions should not be
async
.(lint/suspicious/noAsyncPromiseExecutor)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/annotation_editor_layer.d.ts (6)
75-75: 🛠️ Refactor suggestion
Define the shape of 'params' instead of using 'Object'.
The
params
parameter in theaddCommands
method should have a specific type to clarify its expected structure.Consider defining an interface for
params
:-addCommands(params: Object): void; +addCommands(params: CommandParams): void; +interface CommandParams { + // Define the properties of CommandParams here +}Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 75-75: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
153-153: 🛠️ Refactor suggestion
Avoid using '{}' as a type; define the exact structure for 'data'.
Using
{}
as a type is too broad. Specify the exact shape ofdata
with a proper type or interface.Update the method signature with a specific type:
-createAndAddNewEditor(event: PointerEvent, isCentered: boolean, data?: {}): AnnotationEditor; +createAndAddNewEditor(event: PointerEvent, isCentered: boolean, data?: EditorData): AnnotationEditor; +interface EditorData { + // Define the properties of EditorData here +}Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 153-153: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
145-145: 🛠️ Refactor suggestion
Replace 'Object' with a specific type for 'data' in 'deserialize' method.
Specifying the exact type for
data
improves code readability and type safety.Define an interface for
data
:-deserialize(data: Object): AnnotationEditor | null; +deserialize(data: AnnotationData): AnnotationEditor | null; +interface AnnotationData { + // Define the properties of AnnotationData here +}Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 145-145: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
139-139: 🛠️ Refactor suggestion
Avoid using 'Object' for 'params'; specify its exact type.
Using
Object
for theparams
parameter inpasteEditor
lacks specificity. Define the expected structure with a proper type.Define a specific type for
params
:-pasteEditor(mode: number, params: Object): void; +pasteEditor(mode: number, params: PasteParams): void; +interface PasteParams { + // Define the properties of PasteParams here +}Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 139-139: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
214-214: 🛠️ Refactor suggestion
Specify the return type of 'pageDimensions' instead of using 'Object'.
Returning a specific type enhances clarity and allows for better type checking.
Define the return type explicitly:
-get pageDimensions(): Object; +get pageDimensions(): PageDimensions; +interface PageDimensions { + width: number; + height: number; +}Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 214-214: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
2-2: 🛠️ Refactor suggestion
Specify a more precise type for 'mode' instead of 'Object'.
Using
Object
as a type is discouraged because it doesn't convey the expected structure. Please replace it with a specific type, such asnumber
or a custom type that accurately representsmode
.Apply this diff to specify the type of
mode
:-mode: Object; +mode: number;Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 2-2: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/annotation_layer.d.ts (6)
170-170:
⚠️ Potential issueProvide the method signature for
_createContainer
The private method
_createContainer
lacks a method signature. Ensure it is defined with appropriate parameters and return type for clarity.Proposed change:
-private _createContainer; +private _createContainer(ignoreBorder: boolean): HTMLElement;Include the method parameters and return type to complete the declaration.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.private _createContainer(ignoreBorder: boolean): HTMLElement;
42-42:
⚠️ Potential issueSpecify a more precise type for the values in
fieldObjects
The value type of the
fieldObjects
dictionary is currentlyObject[]
, which is too generic. Specify a more accurate type for the array elements to enhance type safety.Proposed change:
- [x: string]: Object[]; + [x: string]: AnnotationFieldObject[];Define an
AnnotationFieldObject
interface that represents the items in the array.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 42-42: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
13-13:
⚠️ Potential issueSpecify a more precise type for
svgFactory
instead ofObject
The type
Object
forsvgFactory
is too generic. Please define a more specific type or interface that describes the expected methods and properties ofsvgFactory
.Proposed change:
- svgFactory: Object; + svgFactory: ISVGFactory;Define an
ISVGFactory
interface that outlines the required functionality ofsvgFactory
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 13-13: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
2-2:
⚠️ Potential issueSpecify a more precise type for
data
instead ofObject
Using
Object
as a type is too general and does not provide type safety. It is recommended to define a specific interface or type that reflects the actual structure ofdata
.Proposed change:
- data: Object; + data: AnnotationData;Ensure that you define the
AnnotationData
interface to accurately represent the expected properties ofdata
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 2-2: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
98-102:
⚠️ Potential issueCorrect the JSDoc parameter name in the
update
methodThe JSDoc comment for the
update
method incorrectly names the parameter asviewport
, but it should reflect the actual parameter{ viewport }
used in the method signature.Proposed change:
/** - * @param {AnnotationLayerParameters} viewport + * @param {AnnotationLayerParameters} params + * @param {PageViewport} params.viewport * @memberof AnnotationLayer */This ensures consistency between the JSDoc comment and the method signature.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.* Update the annotation elements on existing annotation layer. * * @param {AnnotationLayerParameters} params * @param {PageViewport} params.viewport * @memberof AnnotationLayer */
16-16:
⚠️ Potential issueSpecify a more precise type for
fieldObjects
instead ofObject
Using
Object
as a type reduces type safety. Consider defining a specific type or interface that accurately represents the structure offieldObjects
.Proposed change:
- fieldObjects?: Object | undefined; + fieldObjects?: FieldObjects | undefined;Create a
FieldObjects
interface to detail the expected structure and properties.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 16-16: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/canvas.d.ts (1)
9-9: 🛠️ Refactor suggestion
Avoid using '{}' as a type and eliminate redundant union types
The property
pendingClip
is declared as{} | {} | null
, which is redundant and lacks specificity. Using{}
as a type means "any non-nullable value" and does not provide meaningful type safety. Consider defining a specific interface or type that accurately represents the structure ofpendingClip
. This will enhance code readability and maintainability.Apply this diff to improve the type definition:
- pendingClip: {} | {} | null; + pendingClip: PendingClipType | null;Where
PendingClipType
is an explicitly defined interface representing the expected structure ofpendingClip
.Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Biome
[error] 9-9: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 9-9: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/display_utils.d.ts (1)
208-208: 🛠️ Refactor suggestion
Avoid using 'Object' as a type.
The
rawDims
getter property in thePageViewport
class is typed asObject
. It's generally recommended to explicitly define the shape of the object instead of using the broadObject
type.-get rawDims(): Object; +get rawDims(): { width: number; height: number };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.get rawDims(): { width: number; height: number };
🧰 Tools
🪛 Biome
[error] 208-208: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/tools.d.ts (4)
233-233: 🛠️ Refactor suggestion
Avoid using 'Object' as a type; prefer specific interfaces.
Using
Object
as a type is discouraged because it represents all non-primitive types and lacks type safety. It's better to define an interface that specifies the exact structure ofparams
.Consider defining an interface for
params
:interface AddCommandsParams { cmd: () => void; undo: () => void; post?: () => void; mustExec: boolean; type: number; overwriteIfSameType: boolean; keepUndo: boolean; } addCommands(params: AddCommandsParams): void;🧰 Tools
🪛 Biome
[error] 233-233: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
348-350: 🛠️ Refactor suggestion
Avoid using 'Function' as a type; define explicit function types.
Using
Function
as a type is discouraged because it accepts any function-like value, which can lead to type safety issues. Instead, specify the exact function signatures.Specify the parameter and return types of the functions:
cmd: () => void; undo: () => void; post?: () => void;So the updated type definition becomes:
add({ cmd, undo, post, mustExec, type, overwriteIfSameType, keepUndo, }: { cmd: () => void; undo: () => void; post?: () => void; mustExec: boolean; type: number; overwriteIfSameType: boolean; keepUndo: boolean; }): void;🧰 Tools
🪛 Biome
[error] 348-348: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 349-349: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 350-350: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
398-398: 🛠️ Refactor suggestion
Avoid using 'Object' as a type for 'self'; prefer a specific interface or type.
Using
Object
as a type reduces type safety because it includes all non-primitive types. Define a specific interface or type that describes the expected properties and methods ofself
.Define an interface for
self
:interface ExecContext { // Define the expected properties and methods of 'self' } exec(self: ExecContext, event: KeyboardEvent): void;Alternatively, if the exact structure is unknown, consider using
unknown
and perform type assertions within the method:exec(self: unknown, event: KeyboardEvent): void;🧰 Tools
🪛 Biome
[error] 398-398: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
276-276:
⚠️ Potential issueReview the return type 'editor is never' in the 'isActive' method.
The return type
editor is never
indicates thateditor
cannot exist, which may not be the intended behavior. This may cause confusion or errors during type checking.If the method is meant to check whether the given editor is active, it should return a boolean value:
-isActive(editor: AnnotationEditor): editor is never; +isActive(editor: AnnotationEditor): boolean;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.isActive(editor: AnnotationEditor): boolean;
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/editor/editor.d.ts (1)
48-48:
⚠️ Potential issueReplace 'Object' type annotations with explicit interfaces
Using
Object
as a type provides minimal type safety. Please define and use explicit interfaces or type aliases that accurately represent the expected structure of the data for parameters and return values.For example, you can define an interface for
l10n
:interface Localization { // Define the properties of the localization object here }Then update the method signature:
- static initialize(l10n: Object, _uiManager: any, options: any): void; + static initialize(l10n: Localization, _uiManager: any, options: any): void;Similarly, replace other occurrences of
Object
with appropriate types.Also applies to: 84-84, 132-132, 317-317, 328-328, 413-413, 418-418, 432-432
🧰 Tools
🪛 Biome
[error] 48-48: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
src/BlazorUI/Bit.BlazorUI.Extras/Components/PdfReader/@types/display/annotation_storage.d.ts (7)
65-65: 🛠️ Refactor suggestion
Specify a more precise type instead of 'any'
The property
editorStats
is typed asany
. Usingany
can lead to loss of type safety. Consider specifying a more precise type to enhance code reliability.If the type of
editorStats
is known, replaceany
with the specific type. Otherwise, consider usingunknown
or defining an appropriate interface.
41-41:
⚠️ Potential issueAvoid using 'Object' as a type; specify a more precise type
The
getAll
method returnsObject | null
. UsingObject
does not provide sufficient type safety. Consider specifying a more precise return type.Apply this diff:
-getAll(): Object | null; +getAll(): Record<string, unknown> | null;This change assumes that
getAll
returns an object with string keys and values of unknown types. Adjust the type as necessary based on the actual data structure.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.getAll(): Record<string, unknown> | null;
🧰 Tools
🪛 Biome
[error] 41-41: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
20-20:
⚠️ Potential issueAvoid using 'Object' as a type; specify a more precise type
The
getRawValue
method returnsObject
. UsingObject
is too general and lacks type safety. Specify a more precise return type or useunknown
if the type is uncertain.Apply this diff:
-getRawValue(key: string): Object; +getRawValue(key: string): unknown;Or define a specific type that represents the returned value.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.getRawValue(key: string): unknown;
🧰 Tools
🪛 Biome
[error] 20-20: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
31-31:
⚠️ Potential issueAvoid using 'Object' as a type; specify a more precise type
The
setValue
method accepts avalue
parameter of typeObject
. UsingObject
is discouraged. Specify a more precise type to enhance type safety.Apply this diff:
-setValue(key: string, value: Object): void; +setValue(key: string, value: unknown): void;Or define an explicit interface representing the structure of
value
.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.setValue(key: string, value: unknown): void;
🧰 Tools
🪛 Biome
[error] 31-31: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
45-45:
⚠️ Potential issueAvoid using 'Object' as a type; specify a more precise type
The
setAll
method accepts anobj
parameter of typeObject
. UsingObject
is too broad. Specify a more precise type to improve type safety.Apply this diff:
-setAll(obj: Object): void; +setAll(obj: Record<string, unknown>): void;Define the structure of
obj
if possible, or use a more appropriate generic type.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.setAll(obj: Record<string, unknown>): void;
🧰 Tools
🪛 Biome
[error] 45-45: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
14-14:
⚠️ Potential issueAvoid using 'Object' as a type; specify a more precise type
The
getValue
method usesObject
as the type fordefaultValue
and its return type. UsingObject
is discouraged because it is too broad and doesn't provide type safety. Consider specifying a more precise type or usingunknown
if the type is not known.Apply this diff to improve type specificity:
-getValue(key: string, defaultValue: Object): Object; +getValue(key: string, defaultValue: unknown): unknown;Alternatively, define an explicit interface or type that represents the expected value.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.getValue(key: string, defaultValue: unknown): unknown;
🧰 Tools
🪛 Biome
[error] 14-14: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
[error] 14-14: Don't use 'Object' as a type.
Prefer explicitly define the object shape. This type means "any non-nullable value", which is slightly better than 'unknown', but it's still a broad type.
(lint/complexity/noBannedTypes)
91-91: 🛠️ Refactor suggestion
Specify a more precise return type instead of 'any'
The
get modifiedIds()
method returnsany
. Providing a specific return type will improve type safety and clarity.If the method returns an object similar to
{ ids: Set<string>; hash: string; }
, specify this as the return type.-get modifiedIds(): any; +get modifiedIds(): { ids: Set<string>; hash: string; };Committable suggestion skipped: line range outside the PR's diff.
…ynk/bitframework into 8991-blazorui-extra-pdfreader
closes #8991
Summary by CodeRabbit
New Features
BitPdfReader
component for rendering PDF documents.BitPdfReader
showcasing various configurations and functionalities.Documentation
BitDataGridColumnBase
,BitDataGridPropertyColumn
, andBitDataGridTemplateColumn
in theBitDataGridDemo
class.BitPdfReader
component.Styles
BitPdfReader.scss
.