-
Notifications
You must be signed in to change notification settings - Fork 10
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
base: main
Are you sure you want to change the base?
Conversation
Run & review this pull request in StackBlitz Codeflow. |
✅ Deploy Preview for zxing-wasm ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
77ebf16
to
0ebc7e6
Compare
96fa914
to
98c8523
Compare
75fef5b
to
86e8373
Compare
|
b3da337
to
b560e97
Compare
d070518
to
fc0124a
Compare
`validateITFCheckSum`, `tryCode39ExtendedMode` and `validateCode39CheckSum` are deprecated in [later commits](https://github.com/zxing-cpp/zxing-cpp/commits/master/?since=2024-01-26).
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. |
72ca424
to
ecb7cad
Compare
WalkthroughThe 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
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
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 as PR comments)
Additionally, you can add 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.
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
andZXingWriterOptions
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
andZXingWriterOptions
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-caseLength 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 3Length 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
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 toreact-jsx
, which aligns with React applications and supports the new JSX transform.
7-7
: Enhance type safety withnoUncheckedIndexedAccess
.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
: Addlang
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 forUTF-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
withid="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 thedist
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
andwriterOptions.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 ofzxingEnum.value
.The non-null assertion operator assumes that
zxingEnum.value
will always correspond to a valid entry in thetextModes
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 ofzxingEnum.value
.The non-null assertion operator assumes that
zxingEnum.value
will always correspond to a valid entry in thebinarizers
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 ofzxingEnum.value
.The non-null assertion operator assumes that
zxingEnum.value
will always correspond to a valid entry in theeanAddOnSymbols
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 thatzxingEnum.value
is always a valid index incontentTypes
. 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 forcontentTypes
.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 withsatisfies
looks good.The use of
satisfies ResolvedWriterOptions
enhances type safety fordefaultWriterOptions
.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 inzxingEnumToCharacterSet
.The use of the non-null assertion operator (
!
) assumes thatzxingEnum.value
will always be a valid index incharacterSets
. 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 specifyreact
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 changingdefaultReaderOptions
type.The type change from
Required<ReaderOptions>
toReaderOptions
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 inuseEffect
.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 inuseEffect
.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! TheResolvedWriterOptions
type enhances type safety.Defining
ResolvedWriterOptions
asRequired<WriterOptions>
ensures all properties are present, improving type safety and consistency.
75-87
: LGTM! TheresolveWriterOptions
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 towriterOptionsToZXingWriterOptions
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 ofvanillaExtractPlugin
.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 ofprocess.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
, andzustand
enhance the project's capabilities.
97-97
: LGTM: Renaming ofcopy:wasm
script.The renaming of the
copy:wasm
script tocopy
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
andonRepaint
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
andNEGATIVE_DEBOUNCE
are clearly defined with appropriate documentation.
28-29
: Symbols for state keys are well-implemented.The use of
scanSymbol
andcloseSymbol
as unique keys for internal state properties is appropriate.
34-79
: InterfaceVideoScannerOptions
is well-structured.The interface provides a comprehensive set of configuration options with clear documentation.
84-92
: InterfaceVideoScannerState
is well-defined.The interface effectively combines resolved options with internal state properties.
109-148
: FunctionresolveVideoScannerOptions
is correctly implemented.The function effectively resolves and merges user-provided options with defaults.
153-172
: InterfaceVideoScanner
is well-defined.The interface provides essential methods for controlling the video scanner.
184-408
: FunctioncreateVideoScanner
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
andcancelAnimationFrame
is properly managed.
419-454
: FunctiongetImageDataFromVideoElement
is well-implemented.The function includes appropriate checks for video readiness and dimensions, with suitable error handling.
465-484
: FunctioncreateCanvas
is well-implemented.The function correctly handles the creation of a canvas element with a fallback mechanism.
494-510
: FunctiongetSignature
is well-implemented.The function efficiently generates a unique signature for a
ReadResult
using a hash.src/stream/userMediaStream.ts (13)
11-11
: ConstantGET_CAPABILITIES_TIMEOUT
is well-defined.The constant is clearly defined with appropriate documentation.
27-31
: TypeInitConstraints
is well-defined.The type provides flexibility for defining initialization constraints.
47-55
: TypesVideoConstraints
andAudioConstraints
are well-defined.The types offer flexibility for specifying constraints for video and audio tracks.
Also applies to: 71-79
131-173
: InterfaceUserMediaStreamOptions
is well-structured.The interface provides comprehensive configuration options with clear documentation.
178-181
: InterfaceUserMediaStreamCapabilities
is well-defined.The interface effectively encapsulates the capabilities of video and audio tracks.
187-192
: InterfaceUserMediaStream
is well-defined.The interface provides essential methods for managing user media streams.
208-243
: FunctionresolveUserMediaStreamOptions
is correctly implemented.The function effectively resolves and merges user-provided options with default values.
252-554
: FunctioncreateUserMediaStream
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
: FunctionstartMediaStream
is well-implemented.The function includes appropriate checks for secure contexts and API support, with suitable error handling.
646-699
: FunctionconstrainMediaStream
is well-implemented.The function effectively applies constraints to video and audio tracks within a media stream.
705-737
: FunctioninspectMediaStream
is well-implemented.The function efficiently retrieves capabilities of video and audio tracks within a media stream.
748-757
: FunctionstopMediaStream
is well-implemented.The function ensures proper termination of all tracks within a media stream.
768-788
: FunctionattachMediaStream
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 |
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.
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?
useEffect(() => { | ||
if (scanning) { | ||
videoScannerRef.current?.start(); | ||
} else { | ||
videoScannerRef.current?.stop(); | ||
} | ||
}, [scanning]); |
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.
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]);
useEffect(() => { | ||
(async () => { | ||
if (streaming) { | ||
const stream = await userMediaStreamRef.current.start(); | ||
setStream(stream); | ||
userMediaStreamRef.current.inspect(); | ||
} else { | ||
await userMediaStreamRef.current.stop(); | ||
setStream(null); | ||
} | ||
})(); | ||
}, [streaming]); |
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.
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", |
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.
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)
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(); | ||
// } | ||
// } | ||
}; |
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.
Optimize canvas operations for performance.
Canvas operations can be performance-intensive. Ensure that the overlay updates are efficient, especially if called frequently.
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; | ||
}); | ||
} |
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.
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.
commit:
|
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.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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
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.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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 (
!
) inzxingEnumToTextMode
ensures that the value is not null or undefined, preventing potential runtime errors.src/bindings/exposedWriterBindings.ts (3)
1-5
: Improve type safety withsatisfies
keyword.The use of
satisfies ResolvedWriterOptions
enhances type safety by ensuring thatdefaultWriterOptions
conforms to the expected structure.
7-9
: Reorganize exports for clarity.The reorganization of exports, including the addition of new types like
ResolvedWriterOptions
andWriteResult
, improves the clarity and usability of the module.
29-42
: Update deprecated type names for clarity.The renaming of
WriterOptions
toEncodeHints
andZXingWriterOptions
toZXingEncodeHints
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
: Dependencyreact
added.The addition of the
react
dependency is essential for integrating React components and hooks, aligning with the PR's objective.
142-142
: Dependencyreact-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
: Dependencyjust-compare
added.The addition of the
just-compare
dependency provides utility functions for deep comparison, which can be useful in various scenarios.
154-154
: Dependencysha1-uint8array
added.The addition of the
sha1-uint8array
dependency provides SHA-1 hashing capabilities, which may be needed for specific functionalities.
155-155
: Dependencytype-fest
added.The addition of the
type-fest
dependency provides additional TypeScript types, enhancing type safety and development experience.
156-156
: Dependencywebrtc-adapter
added.The addition of the
webrtc-adapter
dependency provides WebRTC compatibility across different browsers, which is useful for media handling.
157-157
: Dependencyzustand
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.
Summary by CodeRabbit
New Features
StreamBarcodeDetector
React component for real-time barcode detection via video streaming.useUserMediaStream
).useHeadlessVideoScanner
anduseVideoScanner
).Enhancements
Bug Fixes
Documentation
Chores