Skip to content
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

feat: add react hooks and components #61

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

feat: add react hooks and components #61

wants to merge 1 commit into from

Conversation

Sec-ant
Copy link
Owner

@Sec-ant Sec-ant commented Jan 3, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a StreamBarcodeDetector React component for real-time barcode detection via video streaming.
    • Added a new hook for managing user media streams (useUserMediaStream).
    • Implemented hooks for headless video scanning (useHeadlessVideoScanner and useVideoScanner).
  • Enhancements

    • Improved TypeScript support with new type definitions for media handling and compatibility.
    • Updated project configurations to enhance module handling and documentation generation.
    • Enhanced Vite configuration with new plugins and optimized chunk management for output files.
  • Bug Fixes

    • Minor improvements to error handling and type safety across various modules and functions.
  • Documentation

    • Expanded README and type definitions for better clarity on usage and functionality.
  • Chores

    • Refined build configurations for better dependency management and output optimization.

Copy link

stackblitz bot commented Jan 3, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

netlify bot commented Jan 3, 2024

Deploy Preview for zxing-wasm ready!

Name Link
🔨 Latest commit c0bb843
🔍 Latest deploy log https://app.netlify.com/sites/zxing-wasm/deploys/65e3f9cc79f34300084cd5d2
😎 Deploy Preview https://deploy-preview-61--zxing-wasm.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@Sec-ant Sec-ant force-pushed the react branch 6 times, most recently from 77ebf16 to 0ebc7e6 Compare January 6, 2024 16:30
@Sec-ant Sec-ant force-pushed the react branch 2 times, most recently from 96fa914 to 98c8523 Compare January 18, 2024 11:10
@Sec-ant Sec-ant force-pushed the main branch 5 times, most recently from 75fef5b to 86e8373 Compare January 30, 2024 02:51
Copy link

changeset-bot bot commented Jan 30, 2024

⚠️ No Changeset found

Latest commit: 6bfe105

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@Sec-ant Sec-ant force-pushed the react branch 6 times, most recently from b3da337 to b560e97 Compare February 2, 2024 02:56
@Sec-ant Sec-ant force-pushed the react branch 2 times, most recently from d070518 to fc0124a Compare February 19, 2024 12:01
Sec-ant referenced this pull request Feb 21, 2024
`validateITFCheckSum`, `tryCode39ExtendedMode` and `validateCode39CheckSum`
are deprecated in [later commits](https://github.com/zxing-cpp/zxing-cpp/commits/master/?since=2024-01-26).
@Sec-ant Sec-ant changed the title feat: add react hooks feat: add react hooks and components Feb 26, 2024
Copy link

codesandbox-ci bot commented Feb 26, 2024

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Copy link

coderabbitai bot commented Aug 21, 2024

Walkthrough

The recent changes enhance the structure and functionality of a barcode scanning application built with React. Key updates include the introduction of new modules for video scanning, compatibility improvements for media handling across browsers, and refined TypeScript definitions. The overall organization of components, hooks, and utility functions has been optimized for better usability and modularity, making it easier for developers to implement barcode detection features and manage media streams.

Changes

Files Change Summary
README.md, src/bindings/*, src/react/components/*, src/react/hooks/*, src/stream/*, src/writer/* Various formatting improvements, including comment clarifications, non-null assertions, and restructured export statements.
biome.json, package.json, tsconfig.*.json, vite.config.ts Enhanced configurations for formatting, dependencies, TypeScript settings, and module handling.
index.html, main.tsx, src/index.css.ts, src/react/index.ts Updates to HTML structure, entry points for React components, and CSS styling definitions for better layout and flexibility.
src/scanner/videoScanner.ts, src/stream/userMediaStream.ts, src/stream/shimGetUserMedia.ts Introduction of new functionalities for video scanning and user media management, ensuring better compatibility and usability.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant VideoScanner
    participant MediaStream

    User->>App: Start scanning
    App->>VideoScanner: Initialize video stream
    VideoScanner->>MediaStream: Create user media stream
    MediaStream-->>VideoScanner: Stream ready
    VideoScanner->>VideoScanner: Process video for scanning
    VideoScanner-->>User: Display scan results
Loading

🐰 In the land where code does hop,
A barcode scan, with a flip and a bop!
New hooks and streams, a joyful delight,
With colors and styles, oh what a sight!
So let’s cheer for the changes, oh what a scene,
A rabbit's dream where all code is clean! 🐇✨


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?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

Outside diff range, codebase verification and nitpick comments (2)
src/bindings/exposedWriterBindings.ts (1)

31-36: Deprecated types are still in use.

The deprecated types WriterOptions and ZXingWriterOptions are still being used in several parts of the codebase. Please update these references to the new type names.

  • src/core.ts
  • src/writer/index.ts
  • src/full/index.ts
  • src/bindings/writerOptions.ts
  • src/bindings/exposedWriterBindings.ts
Analysis chain

Deprecation notices are clear and helpful.

The deprecation comments for WriterOptions and ZXingWriterOptions provide clear guidance on the new naming conventions.

Verify that all references to these types in the codebase have been updated to the new names.

Run the following script to verify the usage of deprecated types:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that deprecated types are not used in the codebase.

# Test: Search for occurrences of deprecated types. Expect: No results.
rg --type typescript 'WriterOptions|ZXingWriterOptions' --ignore-case

Length of output: 106


Script:

#!/bin/bash
# Description: Verify that deprecated types are not used in the codebase.

# Test: Search for occurrences of deprecated types in TypeScript files. Expect: No results.
rg 'WriterOptions|ZXingWriterOptions' --glob '*.ts' --ignore-case -A 3

Length of output: 7048

src/react/hooks/useVideoScanner.ts (1)

81-108: Consider removing or documenting commented-out code.

The commented-out code for drawing strokes might be useful for debugging or future features. Consider removing it or adding comments to explain its purpose.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4e8bb86 and 68520bd.

Files selected for processing (47)
  • README.md (1 hunks)
  • biome.json (1 hunks)
  • copy-files-from-to.json (1 hunks)
  • index.html (1 hunks)
  • main.tsx (1 hunks)
  • package.json (4 hunks)
  • scripts/build-iife.ts (2 hunks)
  • scripts/vite-plugin-emscripten-bun.ts (1 hunks)
  • src/bindings/barcodeFormat.ts (2 hunks)
  • src/bindings/binarizer.ts (1 hunks)
  • src/bindings/characterSet.ts (1 hunks)
  • src/bindings/contentType.ts (1 hunks)
  • src/bindings/eanAddOnSymbol.ts (1 hunks)
  • src/bindings/exposedReaderBindings.ts (1 hunks)
  • src/bindings/exposedWriterBindings.ts (1 hunks)
  • src/bindings/index.ts (1 hunks)
  • src/bindings/position.ts (1 hunks)
  • src/bindings/readResult.ts (3 hunks)
  • src/bindings/readerOptions.ts (7 hunks)
  • src/bindings/textMode.ts (1 hunks)
  • src/bindings/writeResult.ts (2 hunks)
  • src/bindings/writerOptions.ts (2 hunks)
  • src/core.ts (7 hunks)
  • src/index.css.ts (1 hunks)
  • src/react/components/StreamBarcodeDetector.tsx (1 hunks)
  • src/react/components/index.ts (1 hunks)
  • src/react/hooks/index.ts (1 hunks)
  • src/react/hooks/useHeadlessVideoScanner.ts (1 hunks)
  • src/react/hooks/useUserMediaStream.ts (1 hunks)
  • src/react/hooks/useVideoScanner.ts (1 hunks)
  • src/react/index.ts (1 hunks)
  • src/reader/index.ts (1 hunks)
  • src/scanner/index.ts (1 hunks)
  • src/scanner/videoScanner.ts (1 hunks)
  • src/stream/compatibility.d.ts (1 hunks)
  • src/stream/index.ts (1 hunks)
  • src/stream/media-track-shims.d.ts (1 hunks)
  • src/stream/shimGetUserMedia.ts (1 hunks)
  • src/stream/userMediaStream.ts (1 hunks)
  • src/stream/webrtc-adapter.d.ts (1 hunks)
  • src/writer/index.ts (2 hunks)
  • tsconfig.base.json (1 hunks)
  • tsconfig.json (1 hunks)
  • tsconfig.node.json (1 hunks)
  • tsconfig.production.json (1 hunks)
  • typedoc.json (1 hunks)
  • vite.config.ts (3 hunks)
Files skipped from review due to trivial changes (12)
  • README.md
  • src/bindings/barcodeFormat.ts
  • src/bindings/position.ts
  • src/bindings/readResult.ts
  • src/bindings/writeResult.ts
  • src/react/components/index.ts
  • src/react/hooks/index.ts
  • src/react/index.ts
  • src/scanner/index.ts
  • src/stream/index.ts
  • src/writer/index.ts
  • tsconfig.production.json
Additional context used
Biome
vite.config.ts

[error] 28-28: This property value named chunkFileNames is later overwritten by an object member with the same name.

Overwritten with this value.

If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.
Unsafe fix: Remove this property value named chunkFileNames

(lint/suspicious/noDuplicateObjectKeys)

Additional comments not posted (84)
tsconfig.node.json (1)

3-8: Verify the impact of module and module resolution changes.

The removal of "module": "ESNext" and "moduleResolution": "Bundler" may affect module imports and resolution. Ensure that the default settings align with the project's requirements.

Run the following script to check for any potential issues related to module imports and resolution:

src/stream/compatibility.d.ts (1)

1-11: LGTM! Compatibility declarations are well-defined.

The types and interfaces for media compatibility are correctly declared and align with common patterns.

typedoc.json (1)

6-11: LGTM! Documentation entry points and sorting are well-configured.

The new entry points expand the documentation scope, and the sortEntryPoints setting allows for a custom order, enhancing documentation organization.

tsconfig.json (3)

4-4: Update JSX rendering strategy.

The jsx option is set to react-jsx, which aligns with React applications and supports the new JSX transform.


7-7: Enhance type safety with noUncheckedIndexedAccess.

The addition of noUncheckedIndexedAccess improves type safety by ensuring that indexed access types are checked.


9-9: Expand included files for TypeScript compilation.

The inclusion of ./main.ts and ./main.tsx expands the scope of TypeScript compilation, indicating new or updated functionality.

index.html (6)

2-2: Add lang attribute for accessibility and SEO.

The lang attribute is set to "en", which improves accessibility and search engine optimization.


4-4: Specify character encoding with meta tag.

The meta tag for UTF-8 character encoding ensures proper text rendering.


5-5: Add favicon link for visual identity.

The link tag for a favicon enhances the application's visual identity.


7-7: Update document title for branding.

The title change to "ZXing WASM React" reflects the application's branding and purpose.


10-10: Add root div for React component mounting.

The div with id="root" is a common practice for mounting React components.


11-11: Update script source to TypeScript with JSX support.

The script source is updated to main.tsx, indicating the use of TypeScript with JSX, essential for React applications.

copy-files-from-to.json (1)

16-17: Include TypeScript declaration files in the distribution.

The new entry ensures that media-track-shims.d.ts is copied to the dist directory, making type definitions available to consumers.

tsconfig.base.json (1)

4-5: LGTM! The TypeScript configuration changes enhance compatibility and module resolution.

Setting "module": "ESNext" and "moduleResolution": "Bundler" aligns with modern JavaScript development practices, improving compatibility and optimizing module resolution.

src/index.css.ts (1)

1-22: LGTM! The use of vanilla-extract for styling is well-structured and modular.

The styles are defined using the style function, promoting modularity and reusability with class composition.

src/bindings/index.ts (1)

10-14: LGTM! The export additions enhance module accessibility.

Including readerOptions.js and writerOptions.js in the exports makes their functionalities available for import, improving the module's interface.

src/bindings/textMode.ts (1)

21-21: Verify the validity of zxingEnum.value.

The non-null assertion operator assumes that zxingEnum.value will always correspond to a valid entry in the textModes array. Ensure that this assumption holds true in all cases.

Run the following script to verify the usage and potential values of zxingEnum.value:

src/bindings/binarizer.ts (1)

26-26: Verify the validity of zxingEnum.value.

The non-null assertion operator assumes that zxingEnum.value will always correspond to a valid entry in the binarizers array. Ensure that this assumption holds true in all cases.

Run the following script to verify the usage and potential values of zxingEnum.value:

src/bindings/eanAddOnSymbol.ts (1)

23-23: Verify the validity of zxingEnum.value.

The non-null assertion operator assumes that zxingEnum.value will always correspond to a valid entry in the eanAddOnSymbols array. Ensure that this assumption holds true in all cases.

Run the following script to verify the usage and potential values of zxingEnum.value:

src/bindings/contentType.ts (1)

28-28: Ensure index validity before using non-null assertion.

The use of the non-null assertion operator (!) assumes that zxingEnum.value is always a valid index in contentTypes. This could lead to runtime errors if the index is out of bounds.

Consider adding a check to ensure that zxingEnum.value is within the valid range of indices for contentTypes.

biome.json (1)

37-42: Configuration for React components looks good.

The addition of a specific formatter configuration for the "react/components" directory is well-structured.

Ensure that the new configuration does not conflict with existing settings and verify its impact on the code formatting.

Run the following script to verify the impact of the new configuration:

src/bindings/exposedWriterBindings.ts (1)

7-9: Type validation with satisfies looks good.

The use of satisfies ResolvedWriterOptions enhances type safety for defaultWriterOptions.

Ensure that the changes do not introduce any type mismatches in the codebase.

src/stream/webrtc-adapter.d.ts (1)

1-30: Type declarations for WebRTC adapter shims look good.

The type declarations are well-structured and provide clarity for internal usage of WebRTC adapter shims.

src/bindings/characterSet.ts (1)

56-56: Verify the non-null assertion in zxingEnumToCharacterSet.

The use of the non-null assertion operator (!) assumes that zxingEnum.value will always be a valid index in characterSets. Ensure that this assumption holds true in all use cases.

main.tsx (1)

1-45: React component setup for barcode detection looks good.

The component is well-structured, and the use of React hooks for managing constraints and handling events is appropriate.

scripts/build-iife.ts (4)

4-4: Import looks good.

The emscriptenBun import is correctly added and used in the plugins array.


9-11: Verify the impact of limiting entries to three.

The .slice(0, 3) method limits the entries processed to the first three. Ensure that this change aligns with the intended build process and does not omit necessary entries.


25-31: External dependency handling is appropriate.

The rollupOptions now specify react as an external dependency, ensuring it is not bundled. This is a good practice for libraries that rely on React.


37-37: Plugin integration looks good.

The emscriptenBun plugin is correctly added to the plugins array, which should enhance the build process.

src/reader/index.ts (1)

54-54: Export addition is beneficial.

Adding ZXingReaderModule to the exports enhances the module's interface, allowing for better type integration across the codebase.

src/bindings/exposedReaderBindings.ts (3)

7-10: Verify the impact of changing defaultReaderOptions type.

The type change from Required<ReaderOptions> to ReaderOptions may affect type constraints. Ensure that this aligns with the intended usage and does not introduce type safety issues.


14-41: Expanded exports enhance module interface.

The addition of new types to the exports broadens the module's interface, facilitating more comprehensive type checking and integration.


48-61: Deprecation notices provide clear guidance.

The updated deprecation annotations clearly indicate the renaming of types, aiding developers in transitioning to the new type names.

src/stream/shimGetUserMedia.ts (1)

1-50: LGTM! The shim implementation is well-structured.

The use of webrtc-adapter to handle browser-specific differences is appropriate, and the code ensures that the shim is applied only once.

scripts/vite-plugin-emscripten-bun.ts (1)

1-68: LGTM! The plugin effectively adds Bun runtime support.

The use of Babel to transform Emscripten-generated code is appropriate, and the modifications correctly add support for the Bun runtime.

src/react/hooks/useHeadlessVideoScanner.ts (1)

68-92: Ensure all dependencies are listed in useEffect.

Make sure all variables used within useEffect are included in the dependency array. This ensures that the effect runs correctly when any of these variables change.

Double-check that all dependencies are included in the dependency array. If any are missing, add them to ensure the effect runs as expected.

src/react/hooks/useUserMediaStream.ts (1)

74-94: Ensure all dependencies are listed in useEffect.

Make sure all variables used within useEffect are included in the dependency array. This ensures that the effect runs correctly when any of these variables change.

Double-check that all dependencies are included in the dependency array. If any are missing, add them to ensure the effect runs as expected.

src/bindings/writerOptions.ts (3)

64-64: LGTM! The ResolvedWriterOptions type enhances type safety.

Defining ResolvedWriterOptions as Required<WriterOptions> ensures all properties are present, improving type safety and consistency.


75-87: LGTM! The resolveWriterOptions function is well-implemented.

The function effectively merges user-defined options with default options, ensuring all properties are filled. This enhances flexibility in options handling.


88-98: LGTM! The update to writerOptionsToZXingWriterOptions aligns with the new type structure.

The function now operates with ResolvedWriterOptions, ensuring it works with resolved options and maintains consistency.

vite.config.ts (3)

1-1: LGTM: Addition of vanillaExtractPlugin.

The addition of the vanillaExtractPlugin for CSS-in-JS styling looks good.

Also applies to: 79-79


26-26: LGTM: External dependencies and manual chunking.

The changes to mark react as external and the enhanced manual chunking logic are well-implemented.

Also applies to: 30-72


90-90: LGTM: Addition of process.env.NODE_ENV.

Setting process.env.NODE_ENV to "production" is a good practice for production builds.

package.json (3)

36-63: LGTM: Addition of new export paths.

The new export paths for modules like scanner, stream, and React components enhance module resolution and compatibility.


Line range hint 132-157: LGTM: Addition of new dependencies.

The added dependencies like @types/react, react, and zustand enhance the project's capabilities.


97-97: LGTM: Renaming of copy:wasm script.

The renaming of the copy:wasm script to copy is acceptable and may simplify the build process.

src/react/components/StreamBarcodeDetector.tsx (4)

1-18: LGTM: Imports and interface definition.

The imports and interface for StreamBarcodeDetectorProps are well-structured and comprehensive.


20-130: LGTM: Component implementation.

The StreamBarcodeDetector component is efficiently implemented, leveraging hooks and memoization for optimal performance.


167-182: LGTM: useEffect and return statement.

The useEffect hook and the JSX layout are well-implemented, ensuring proper management of video element references.


186-186: LGTM: Default export.

The default export of the StreamBarcodeDetector component is appropriate.

src/react/hooks/useVideoScanner.ts (4)

11-15: Ensure proper handling of optional callbacks.

The onScanUpdate and onRepaint callbacks are optional, but their usage is correctly guarded with optional chaining. Ensure that these callbacks are always provided when necessary.


18-23: LGTM!

The scannerVideoRefCallback is correctly implemented and memoized.


124-145: LGTM! Consider performance implications.

The handleFrameUpdate function is correctly implemented. However, ensure that frequent canvas updates do not impact performance.


161-167: LGTM!

The videoRefCallback is correctly implemented and memoized.

src/core.ts (4)

Line range hint 73-94: LGTM!

The getZXingModuleWithFactory function is correctly implemented with caching using a WeakMap.


Line range hint 176-187: LGTM! Verify memory management.

The readBarcodesFromImageFileWithFactory function is correctly implemented. Ensure that memory allocation and deallocation are correctly handled.


Line range hint 204-220: LGTM! Verify memory management.

The readBarcodesFromImageDataWithFactory function is correctly implemented. Ensure that memory allocation and deallocation are correctly handled.


237-243: LGTM!

The writeBarcodeToImageFileWithFactory function is correctly implemented and handles writer options appropriately.

src/bindings/readerOptions.ts (3)

240-281: LGTM!

The resolveReaderOptions function is correctly implemented and resolves default values appropriately.


216-216: LGTM!

The ResolvedReaderOptions type alias is correctly defined and improves code maintainability.


Line range hint 283-300: LGTM!

The readerOptionsToZXingReaderOptions function is correctly implemented and uses the appropriate conversions.

src/scanner/videoScanner.ts (10)

18-23: Constants are well-defined.

The constants SCAN_THROTTLE and NEGATIVE_DEBOUNCE are clearly defined with appropriate documentation.


28-29: Symbols for state keys are well-implemented.

The use of scanSymbol and closeSymbol as unique keys for internal state properties is appropriate.


34-79: Interface VideoScannerOptions is well-structured.

The interface provides a comprehensive set of configuration options with clear documentation.


84-92: Interface VideoScannerState is well-defined.

The interface effectively combines resolved options with internal state properties.


109-148: Function resolveVideoScannerOptions is correctly implemented.

The function effectively resolves and merges user-provided options with defaults.


153-172: Interface VideoScanner is well-defined.

The interface provides essential methods for controlling the video scanner.


184-408: Function createVideoScanner is comprehensive and well-structured.

The function effectively initializes a video scanner with control methods and state management using Zustand.

However, ensure that error handling for external calls like requestAnimationFrame and cancelAnimationFrame is properly managed.


419-454: Function getImageDataFromVideoElement is well-implemented.

The function includes appropriate checks for video readiness and dimensions, with suitable error handling.


465-484: Function createCanvas is well-implemented.

The function correctly handles the creation of a canvas element with a fallback mechanism.


494-510: Function getSignature is well-implemented.

The function efficiently generates a unique signature for a ReadResult using a hash.

src/stream/userMediaStream.ts (13)

11-11: Constant GET_CAPABILITIES_TIMEOUT is well-defined.

The constant is clearly defined with appropriate documentation.


27-31: Type InitConstraints is well-defined.

The type provides flexibility for defining initialization constraints.


47-55: Types VideoConstraints and AudioConstraints are well-defined.

The types offer flexibility for specifying constraints for video and audio tracks.

Also applies to: 71-79


131-173: Interface UserMediaStreamOptions is well-structured.

The interface provides comprehensive configuration options with clear documentation.


178-181: Interface UserMediaStreamCapabilities is well-defined.

The interface effectively encapsulates the capabilities of video and audio tracks.


187-192: Interface UserMediaStream is well-defined.

The interface provides essential methods for managing user media streams.


208-243: Function resolveUserMediaStreamOptions is correctly implemented.

The function effectively resolves and merges user-provided options with default values.


252-554: Function createUserMediaStream is comprehensive and well-structured.

The function effectively creates a user media stream with control methods and state management using Zustand.

However, ensure that error handling for external calls like getUserMedia is properly managed.


573-627: Function startMediaStream is well-implemented.

The function includes appropriate checks for secure contexts and API support, with suitable error handling.


646-699: Function constrainMediaStream is well-implemented.

The function effectively applies constraints to video and audio tracks within a media stream.


705-737: Function inspectMediaStream is well-implemented.

The function efficiently retrieves capabilities of video and audio tracks within a media stream.


748-757: Function stopMediaStream is well-implemented.

The function ensures proper termination of all tracks within a media stream.


768-788: Function attachMediaStream is well-implemented.

The function correctly handles attaching a media stream to an HTMLVideoElement, considering browser compatibility.

@@ -0,0 +1,61 @@
// TODO: complete constraints and capabilities
Copy link

Choose a reason for hiding this comment

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

Reminder: Complete constraints and capabilities.

The TODO comment indicates that the constraints and capabilities are incomplete. Ensure that all necessary properties are defined.

Would you like me to help complete these definitions or open a GitHub issue to track this task?

Comment on lines +33 to +39
useEffect(() => {
if (scanning) {
videoScannerRef.current?.start();
} else {
videoScannerRef.current?.stop();
}
}, [scanning]);
Copy link

Choose a reason for hiding this comment

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

Ensure proper cleanup in useEffect.

The useEffect hook should handle cleanup to prevent potential memory leaks. Consider adding a cleanup function to stop the scanner when the component unmounts or when scanning changes.

useEffect(() => {
  if (scanning) {
    videoScannerRef.current?.start();
  } else {
    videoScannerRef.current?.stop();
  }
  return () => {
    videoScannerRef.current?.stop();
  };
}, [scanning]);

Comment on lines +51 to +62
useEffect(() => {
(async () => {
if (streaming) {
const stream = await userMediaStreamRef.current.start();
setStream(stream);
userMediaStreamRef.current.inspect();
} else {
await userMediaStreamRef.current.stop();
setStream(null);
}
})();
}, [streaming]);
Copy link

Choose a reason for hiding this comment

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

Ensure proper cleanup in useEffect.

The useEffect hook should handle cleanup to prevent potential memory leaks. Consider adding a cleanup function to stop the stream when the component unmounts or when streaming changes.

useEffect(() => {
  (async () => {
    if (streaming) {
      const stream = await userMediaStreamRef.current.start();
      setStream(stream);
      userMediaStreamRef.current.inspect();
    } else {
      await userMediaStreamRef.current.stop();
      setStream(null);
    }
  })();
  return () => {
    userMediaStreamRef.current.stop();
    setStream(null);
  };
}, [streaming]);

},
formats: ["es"],
fileName: (_, entryName) => `${entryName}.js`,
},
outDir: "dist/es",
rollupOptions: {
external: ["react"],
output: {
chunkFileNames: "[name]-[hash].js",
Copy link

Choose a reason for hiding this comment

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

Remove duplicate chunkFileNames property.

The chunkFileNames property is defined twice in the output object, which can lead to unexpected behavior. Remove the duplicate definition.

Use this diff to fix the issue:

        chunkFileNames: "[name]-[hash].js",

Also applies to: 74-74

Tools
Biome

[error] 28-28: This property value named chunkFileNames is later overwritten by an object member with the same name.

Overwritten with this value.

If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.
Unsafe fix: Remove this property value named chunkFileNames

(lint/suspicious/noDuplicateObjectKeys)

Comment on lines +27 to +109
const handleOverlayUpdate = useCallback(
(() => {
let context: CanvasRenderingContext2D | undefined = undefined;
return (readResults: ReadResult[]) => {
// check canvas ready state
if (
overlayCanvasElementRef.current === null ||
videoElementRef.current === null
) {
return;
}
// update canvas dimension
const { videoWidth, videoHeight } = videoElementRef.current;
if (context === undefined) {
context = overlayCanvasElementRef.current.getContext("2d")!;
}
if (context.canvas.width !== videoWidth) {
context.canvas.width = videoWidth;
}
if (context.canvas.height !== videoHeight) {
context.canvas.height = videoHeight;
}
// draw overlay
context.clearRect(0, 0, videoWidth, videoHeight);
context.beginPath();

context.moveTo(0, 0);
context.lineTo(videoWidth, 0);
context.lineTo(videoWidth, videoHeight);
context.lineTo(0, videoHeight);
context.closePath();

for (const readResult of readResults) {
if (readResult.isValid) {
context.moveTo(
readResult.position.topLeft.x,
readResult.position.topLeft.y,
);
context.lineTo(
readResult.position.bottomLeft.x,
readResult.position.bottomLeft.y,
);
context.lineTo(
readResult.position.bottomRight.x,
readResult.position.bottomRight.y,
);
context.lineTo(
readResult.position.topRight.x,
readResult.position.topRight.y,
);
context.closePath();
}
}

context.fillStyle = "rgba(0, 0, 0, 0.8)";
context.fill();
// context.clearRect(0, 0, videoWidth, videoHeight);
// for (const readResult of readResults) {
// if (readResult.isValid) {
// context.strokeStyle = "#f00";
// context.lineWidth = 1;
// context.beginPath();
// context.moveTo(
// readResult.position.topLeft.x,
// readResult.position.topLeft.y,
// );
// context.lineTo(
// readResult.position.topRight.x,
// readResult.position.topRight.y,
// );
// context.lineTo(
// readResult.position.bottomRight.x,
// readResult.position.bottomRight.y,
// );
// context.lineTo(
// readResult.position.bottomLeft.x,
// readResult.position.bottomLeft.y,
// );
// context.closePath();
// context.stroke();
// }
// }
};
Copy link

Choose a reason for hiding this comment

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

Optimize canvas operations for performance.

Canvas operations can be performance-intensive. Ensure that the overlay updates are efficient, especially if called frequently.

Comment on lines +804 to +834
export async function getCapabilities(
track: MediaStreamTrack,
timeout = GET_CAPABILITIES_TIMEOUT,
): Promise<MediaTrackCapabilities> {
return new Promise((resolve) => {
// timeout, return empty capabilities
let timeoutId: number | undefined = setTimeout(() => {
resolve({});
timeoutId = undefined;
return;
}, timeout);

// not supported, return empty capabilities
if (!track.getCapabilities) {
clearTimeout(timeoutId);
resolve({});
timeoutId = undefined;
return;
}

// poll to check capabilities
let capabilities: MediaTrackCapabilities = {};
while (Object.keys(capabilities).length === 0 && timeoutId !== undefined) {
capabilities = track.getCapabilities();
}
clearTimeout(timeoutId);
resolve(capabilities);
timeoutId = undefined;
return;
});
}
Copy link

Choose a reason for hiding this comment

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

Consider improving the polling logic in getCapabilities.

The current implementation uses a while loop for polling, which may not be efficient. Consider using an event-driven approach or a more efficient polling mechanism.

Copy link

pkg-pr-new bot commented Aug 21, 2024

commit: 6bfe105

pnpm add https://pkg.pr.new/zxing-wasm@61

Open in Stackblitz

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 68520bd and 5aa8b8e.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (47)
  • README.md (1 hunks)
  • biome.json (1 hunks)
  • copy-files-from-to.json (1 hunks)
  • index.html (1 hunks)
  • main.tsx (1 hunks)
  • package.json (5 hunks)
  • scripts/build-iife.ts (2 hunks)
  • scripts/vite-plugin-emscripten-bun.ts (1 hunks)
  • src/bindings/barcodeFormat.ts (2 hunks)
  • src/bindings/binarizer.ts (1 hunks)
  • src/bindings/characterSet.ts (1 hunks)
  • src/bindings/contentType.ts (1 hunks)
  • src/bindings/eanAddOnSymbol.ts (1 hunks)
  • src/bindings/exposedReaderBindings.ts (1 hunks)
  • src/bindings/exposedWriterBindings.ts (1 hunks)
  • src/bindings/index.ts (1 hunks)
  • src/bindings/position.ts (1 hunks)
  • src/bindings/readResult.ts (3 hunks)
  • src/bindings/readerOptions.ts (7 hunks)
  • src/bindings/textMode.ts (1 hunks)
  • src/bindings/writeResult.ts (2 hunks)
  • src/bindings/writerOptions.ts (2 hunks)
  • src/core.ts (7 hunks)
  • src/index.css.ts (1 hunks)
  • src/react/components/StreamBarcodeDetector.tsx (1 hunks)
  • src/react/components/index.ts (1 hunks)
  • src/react/hooks/index.ts (1 hunks)
  • src/react/hooks/useHeadlessVideoScanner.ts (1 hunks)
  • src/react/hooks/useUserMediaStream.ts (1 hunks)
  • src/react/hooks/useVideoScanner.ts (1 hunks)
  • src/react/index.ts (1 hunks)
  • src/reader/index.ts (1 hunks)
  • src/scanner/index.ts (1 hunks)
  • src/scanner/videoScanner.ts (1 hunks)
  • src/stream/compatibility.d.ts (1 hunks)
  • src/stream/index.ts (1 hunks)
  • src/stream/media-track-shims.d.ts (1 hunks)
  • src/stream/shimGetUserMedia.ts (1 hunks)
  • src/stream/userMediaStream.ts (1 hunks)
  • src/stream/webrtc-adapter.d.ts (1 hunks)
  • src/writer/index.ts (2 hunks)
  • tsconfig.base.json (1 hunks)
  • tsconfig.json (1 hunks)
  • tsconfig.node.json (1 hunks)
  • tsconfig.production.json (1 hunks)
  • typedoc.json (1 hunks)
  • vite.config.ts (3 hunks)
Files skipped from review due to trivial changes (11)
  • README.md
  • src/bindings/index.ts
  • src/bindings/readResult.ts
  • src/core.ts
  • src/react/hooks/index.ts
  • src/scanner/index.ts
  • src/stream/compatibility.d.ts
  • src/stream/index.ts
  • src/writer/index.ts
  • tsconfig.base.json
  • tsconfig.production.json
Files skipped from review as they are similar to previous changes (36)
  • biome.json
  • copy-files-from-to.json
  • index.html
  • main.tsx
  • package.json
  • scripts/build-iife.ts
  • scripts/vite-plugin-emscripten-bun.ts
  • src/bindings/barcodeFormat.ts
  • src/bindings/binarizer.ts
  • src/bindings/characterSet.ts
  • src/bindings/contentType.ts
  • src/bindings/eanAddOnSymbol.ts
  • src/bindings/exposedReaderBindings.ts
  • src/bindings/exposedWriterBindings.ts
  • src/bindings/position.ts
  • src/bindings/readerOptions.ts
  • src/bindings/textMode.ts
  • src/bindings/writeResult.ts
  • src/bindings/writerOptions.ts
  • src/index.css.ts
  • src/react/components/StreamBarcodeDetector.tsx
  • src/react/components/index.ts
  • src/react/hooks/useHeadlessVideoScanner.ts
  • src/react/hooks/useUserMediaStream.ts
  • src/react/hooks/useVideoScanner.ts
  • src/react/index.ts
  • src/reader/index.ts
  • src/scanner/videoScanner.ts
  • src/stream/media-track-shims.d.ts
  • src/stream/shimGetUserMedia.ts
  • src/stream/userMediaStream.ts
  • src/stream/webrtc-adapter.d.ts
  • tsconfig.json
  • tsconfig.node.json
  • typedoc.json
  • vite.config.ts

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5aa8b8e and 6bfe105.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (47)
  • README.md (1 hunks)
  • biome.json (1 hunks)
  • copy-files-from-to.json (1 hunks)
  • index.html (1 hunks)
  • main.tsx (1 hunks)
  • package.json (3 hunks)
  • scripts/build-iife.ts (2 hunks)
  • scripts/vite-plugin-emscripten-bun.ts (1 hunks)
  • src/bindings/barcodeFormat.ts (2 hunks)
  • src/bindings/binarizer.ts (1 hunks)
  • src/bindings/characterSet.ts (1 hunks)
  • src/bindings/contentType.ts (1 hunks)
  • src/bindings/eanAddOnSymbol.ts (1 hunks)
  • src/bindings/exposedReaderBindings.ts (1 hunks)
  • src/bindings/exposedWriterBindings.ts (1 hunks)
  • src/bindings/index.ts (1 hunks)
  • src/bindings/position.ts (1 hunks)
  • src/bindings/readResult.ts (3 hunks)
  • src/bindings/readerOptions.ts (7 hunks)
  • src/bindings/textMode.ts (1 hunks)
  • src/bindings/writeResult.ts (2 hunks)
  • src/bindings/writerOptions.ts (2 hunks)
  • src/core.ts (7 hunks)
  • src/index.css.ts (1 hunks)
  • src/react/components/StreamBarcodeDetector.tsx (1 hunks)
  • src/react/components/index.ts (1 hunks)
  • src/react/hooks/index.ts (1 hunks)
  • src/react/hooks/useHeadlessVideoScanner.ts (1 hunks)
  • src/react/hooks/useUserMediaStream.ts (1 hunks)
  • src/react/hooks/useVideoScanner.ts (1 hunks)
  • src/react/index.ts (1 hunks)
  • src/reader/index.ts (1 hunks)
  • src/scanner/index.ts (1 hunks)
  • src/scanner/videoScanner.ts (1 hunks)
  • src/stream/compatibility.d.ts (1 hunks)
  • src/stream/index.ts (1 hunks)
  • src/stream/media-track-shims.d.ts (1 hunks)
  • src/stream/shimGetUserMedia.ts (1 hunks)
  • src/stream/userMediaStream.ts (1 hunks)
  • src/stream/webrtc-adapter.d.ts (1 hunks)
  • src/writer/index.ts (2 hunks)
  • tsconfig.base.json (1 hunks)
  • tsconfig.json (1 hunks)
  • tsconfig.node.json (1 hunks)
  • tsconfig.production.json (1 hunks)
  • typedoc.json (1 hunks)
  • vite.config.ts (3 hunks)
Files skipped from review due to trivial changes (12)
  • README.md
  • src/bindings/barcodeFormat.ts
  • src/bindings/index.ts
  • src/bindings/readResult.ts
  • src/bindings/writeResult.ts
  • src/react/hooks/index.ts
  • src/reader/index.ts
  • src/scanner/index.ts
  • src/stream/compatibility.d.ts
  • src/stream/index.ts
  • src/writer/index.ts
  • tsconfig.production.json
Files skipped from review as they are similar to previous changes (31)
  • biome.json
  • copy-files-from-to.json
  • index.html
  • main.tsx
  • scripts/build-iife.ts
  • scripts/vite-plugin-emscripten-bun.ts
  • src/bindings/binarizer.ts
  • src/bindings/characterSet.ts
  • src/bindings/contentType.ts
  • src/bindings/eanAddOnSymbol.ts
  • src/bindings/exposedReaderBindings.ts
  • src/bindings/position.ts
  • src/bindings/readerOptions.ts
  • src/bindings/writerOptions.ts
  • src/core.ts
  • src/index.css.ts
  • src/react/components/StreamBarcodeDetector.tsx
  • src/react/components/index.ts
  • src/react/hooks/useHeadlessVideoScanner.ts
  • src/react/hooks/useUserMediaStream.ts
  • src/react/hooks/useVideoScanner.ts
  • src/react/index.ts
  • src/scanner/videoScanner.ts
  • src/stream/media-track-shims.d.ts
  • src/stream/shimGetUserMedia.ts
  • src/stream/userMediaStream.ts
  • src/stream/webrtc-adapter.d.ts
  • tsconfig.json
  • tsconfig.node.json
  • typedoc.json
  • vite.config.ts
Additional comments not posted (20)
tsconfig.base.json (1)

4-5: Modernize module system and resolution strategy.

The addition of "module": "ESNext" and "moduleResolution": "Bundler" is a good move towards leveraging modern JavaScript features and optimizing module resolution for bundlers.

src/bindings/textMode.ts (1)

21-21: Ensure non-null value with assertion operator.

The use of the non-null assertion operator (!) in zxingEnumToTextMode ensures that the value is not null or undefined, preventing potential runtime errors.

src/bindings/exposedWriterBindings.ts (3)

1-5: Improve type safety with satisfies keyword.

The use of satisfies ResolvedWriterOptions enhances type safety by ensuring that defaultWriterOptions conforms to the expected structure.


7-9: Reorganize exports for clarity.

The reorganization of exports, including the addition of new types like ResolvedWriterOptions and WriteResult, improves the clarity and usability of the module.


29-42: Update deprecated type names for clarity.

The renaming of WriterOptions to EncodeHints and ZXingWriterOptions to ZXingEncodeHints provides clearer naming conventions, enhancing code readability.

package.json (15)

36-40: Export path ./scanner added.

The addition of the ./scanner export path improves modularity and provides a clear entry point for scanner-related functionalities.


41-45: Export path ./stream added.

The addition of the ./stream export path improves modularity and provides a clear entry point for stream-related functionalities.


46-48: Export path ./media-track-shims added.

The addition of the ./media-track-shims export path provides TypeScript definitions, enhancing type safety and development experience.


49-53: Export path ./react added.

The addition of the ./react export path supports the integration of React components, aligning with the PR's objective to add React hooks and components.


54-58: Export path ./react/components added.

The addition of the ./react/components export path supports the modularization of React components, enhancing the project's structure.


59-63: Export path ./react/hooks added.

The addition of the ./react/hooks export path supports the modularization of React hooks, enhancing the project's structure and usability.


132-132: Dependency @types/react added.

The addition of the @types/react dependency provides TypeScript definitions for React, enhancing type safety and development experience.


133-133: Dependency @types/react-dom added.

The addition of the @types/react-dom dependency provides TypeScript definitions for React DOM, enhancing type safety and development experience.


141-141: Dependency react added.

The addition of the react dependency is essential for integrating React components and hooks, aligning with the PR's objective.


142-142: Dependency react-dom added.

The addition of the react-dom dependency is essential for rendering React components in the DOM, aligning with the PR's objective.


153-153: Dependency just-compare added.

The addition of the just-compare dependency provides utility functions for deep comparison, which can be useful in various scenarios.


154-154: Dependency sha1-uint8array added.

The addition of the sha1-uint8array dependency provides SHA-1 hashing capabilities, which may be needed for specific functionalities.


155-155: Dependency type-fest added.

The addition of the type-fest dependency provides additional TypeScript types, enhancing type safety and development experience.


156-156: Dependency webrtc-adapter added.

The addition of the webrtc-adapter dependency provides WebRTC compatibility across different browsers, which is useful for media handling.


157-157: Dependency zustand added.

The addition of the zustand dependency provides a small, fast, and scalable state management solution, which can enhance the application's state management capabilities.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant