@shivantra/react-web-camera 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Shivantra Solutions Private Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,270 @@
1
+ # WebCamera React Component πŸ“Έ
2
+
3
+ A lightweight and flexible React component for capturing images from the user’s camera (front or back) with support for `jpeg`, `png`, and `webp` formats. Built with modern React (`hooks` + `forwardRef`) and works on both desktop and mobile browsers.
4
+
5
+ ## πŸ“‘ Table of Contents
6
+
7
+ - [Why?](#why-)
8
+ - [Our Solution](#our-solution-)
9
+ - [Features](#features-)
10
+ - [Installation](#installation-)
11
+ - [Usage](#usage-)
12
+ - [Basic Example](#basic-example)
13
+ - [Vite.js Example](#vitejs-example)
14
+ - [Next.js Example (App Router)](#nextjs-example-app-router)
15
+ - [PWA Example](#pwa-example)
16
+ - [Props](#props-%EF%B8%8F)
17
+ - [Ref Methods](#ref-methods-)
18
+ - [Notes](#notes-%EF%B8%8F)
19
+ - [License](#license-)
20
+ - [Contact](#contact-)
21
+
22
+ ---
23
+
24
+ ## Why? ❓
25
+
26
+ Capturing multiple images from a webcam is a common need in modern web apps, especially Progressive Web Apps (PWAs).
27
+ Existing solutions are often:
28
+
29
+ - Single-shot only (cannot capture multiple images)
30
+ - Bloated or heavy
31
+ - Hard to customize UI or styling
32
+ - Not fully compatible with PWAs or mobile browsers
33
+
34
+ **Problem with `<input type="file" capture>` on mobile:**
35
+ When you use a file input like:
36
+
37
+ ```html
38
+ <input type="file" accept="image/*" capture="environment" />
39
+ ```
40
+
41
+ on phones, it only allows **a single photo capture**. After you take one photo, the camera closes, and to capture another, the user must reopen the camera again.
42
+ This creates a poor user experience for apps needing **multi-photo sessions** (for example: KYC verification, delivery apps, or documentation workflows).
43
+
44
+ ---
45
+
46
+ ## Our Solution πŸ’‘
47
+
48
+ `react-web-camera` provides a headless, platform-independent React component that gives you full control over your UI. It handles the complex logic of accessing the webcam, capturing multiple images, and managing state, while you focus on styling and user experience.
49
+
50
+ This makes it:
51
+
52
+ - **Lightweight** – minimal overhead for fast, responsive apps
53
+ - **Flexible** – integrate seamlessly with your design system
54
+ - **Multi-Image Ready** – capture and manage multiple photos in a single session
55
+
56
+ ---
57
+
58
+ ## Features ✨
59
+
60
+ - **πŸ“· Front & Back Camera Support** – Easily capture images from both cameras.
61
+ - **πŸ–Ό Multiple Image Formats** – Export images as jpeg, png, or webp.
62
+ - **⚑ Adjustable Capture Quality** – Control image quality with a range of 0.1–1.0.
63
+ - **πŸ”„ Camera Switching** – Seamlessly switch between front (user) and back (environment) cameras.
64
+ - **πŸ“Έ Multi-Image Capture** – Click and manage multiple pictures within a session on both web and mobile.
65
+ - **🎯 Camera Ready on Mount** – Access the camera instantly when the component loads.
66
+ - **πŸ›  Full Programmatic Control** – Use ref methods like capture(), switch(), and getMode().
67
+ - **🎨 Custom Styling** – Style the container and video element to match your design system.
68
+
69
+ ---
70
+
71
+ ## Installation πŸ“¦
72
+
73
+ ```bash
74
+ # If using npm
75
+ npm install @shivantra/react-web-camera
76
+
77
+ # Or with yarn
78
+ yarn add @shivantra/react-web-camera
79
+
80
+ # Or with pnpm
81
+ pnpm add @shivantra/react-web-camera
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Usage πŸ› 
87
+
88
+ - **Basic Example**
89
+
90
+ ```tsx
91
+ import React, { useRef } from "react";
92
+ import { WebCamera, WebCameraHandler } from "@shivantra/react-web-camera";
93
+
94
+ function App() {
95
+ const cameraHandler = useRef<WebCameraHandler>(null);
96
+ const [images, setImages] = useState<string[]>([]);
97
+
98
+ async function handleCapture() {
99
+ const file = await cameraHandler.current?.capture();
100
+ if (file) {
101
+ const base64 = await fileToBase64(file);
102
+ setImages((_images) => [..._images, base64]);
103
+ }
104
+ }
105
+
106
+ function handleSwitch() {
107
+ cameraHandler.current?.switch();
108
+ }
109
+
110
+ return (
111
+ <div>
112
+ <div style={{ display: "flex", gap: 5 }}>
113
+ <button onClick={handleCapture}>Capture</button>
114
+ <button onClick={handleSwitch}>Switch</button>
115
+ </div>
116
+ <div>
117
+ <WebCamera
118
+ style={{ height: 500, width: 360, padding: 10 }}
119
+ videoStyle={{ borderRadius: 5 }}
120
+ captureMode="back"
121
+ ref={cameraHandler}
122
+ />
123
+ </div>
124
+ <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
125
+ {images.map((image, ind) => (
126
+ <img key={ind} src={image} style={{ height: 160, width: 200 }} />
127
+ ))}
128
+ </div>
129
+ </div>
130
+ );
131
+ }
132
+ ```
133
+
134
+ - **Vite.js Example**
135
+
136
+ ```tsx
137
+ import React from "react";
138
+ import ReactDOM from "react-dom/client";
139
+ import { WebCamera } from "@shivantra/react-web-camera";
140
+
141
+ function App() {
142
+ return (
143
+ <div>
144
+ <h1>πŸ“Έ Vite + Webcam</h1>
145
+ <WebCamera
146
+ style={{ width: 320, height: 480, padding: 10 }}
147
+ videoStyle={{ borderRadius: 5 }}
148
+ className="camera-container"
149
+ videoClassName="camera-video"
150
+ captureMode="front"
151
+ captureType="png"
152
+ getFileName={() => `vite-photo-${Date.now()}.jpeg`}
153
+ />
154
+ </div>
155
+ );
156
+ }
157
+
158
+ ReactDOM.createRoot(document.getElementById("root")!).render(<App />);
159
+ ```
160
+
161
+ - **Next.js Example (App Router)**
162
+
163
+ ```tsx
164
+ "use client";
165
+
166
+ import { WebCamera } from "@shivantra/react-web-camera";
167
+
168
+ export default function CameraPage() {
169
+ return (
170
+ <main>
171
+ <h1>πŸ“Έ Next.js Webcam Example</h1>
172
+ <WebCamera
173
+ style={{ width: 320, height: 480, padding: 10 }}
174
+ videoStyle={{ borderRadius: 5 }}
175
+ className="camera-container"
176
+ videoClassName="camera-video"
177
+ captureMode="front"
178
+ getFileName={() => `next-photo-${Date.now()}.jpeg`}
179
+ onError={(err) => console.error(err)}
180
+ />
181
+ </main>
182
+ );
183
+ }
184
+ ```
185
+
186
+ - **PWA Example**
187
+
188
+ ```tsx
189
+ import { WebCamera } from "@shivantra/react-web-camera";
190
+
191
+ export default function PWAApp() {
192
+ return (
193
+ <div>
194
+ <h2>πŸ“± PWA Webcam Ready</h2>
195
+ <WebCamera
196
+ style={{ width: 320, height: 480, padding: 10 }}
197
+ videoStyle={{ borderRadius: 5 }}
198
+ className="camera-container"
199
+ videoClassName="camera-video"
200
+ captureMode="back"
201
+ captureType="jpeg"
202
+ captureQuality={0.8}
203
+ getFileName={() => `pwa-photo-${Date.now()}.jpeg`}
204
+ onError={(err) => console.error(err)}
205
+ />
206
+ </div>
207
+ );
208
+ }
209
+ ```
210
+
211
+ > βœ… Works on mobile browsers and when installed as a PWA (HTTPS required for camera access).
212
+
213
+ ---
214
+
215
+ ## Props βš™οΈ
216
+
217
+ | Prop | Type | Default | Description |
218
+ | ---------------- | ------------------------------- | -------- | ------------------------------------------------ |
219
+ | `className` | `string` | β€” | CSS class for the wrapper `<div>` |
220
+ | `style` | `React.CSSProperties` | β€” | Inline styles for the wrapper `<div>` |
221
+ | `videoClassName` | `string` | β€” | CSS class for the `<video>` element |
222
+ | `videoStyle` | `React.CSSProperties` | β€” | Inline styles for the `<video>` element |
223
+ | `getFileName` | `() => string` | β€” | Optional function to generate captured file name |
224
+ | `captureMode` | `"front"` \| `"back"` | `"back"` | Initial camera mode |
225
+ | `captureType` | `"jpeg"` \| `"png"` \| `"webp"` | `"jpeg"` | Image format for capture |
226
+ | `captureQuality` | `0.1`–`1.0` | `0.8` | Image quality for capture |
227
+ | `onError` | `(err: Error) => void` | β€” | Callback for camera errors |
228
+
229
+ ---
230
+
231
+ ## Ref Methods πŸ–
232
+
233
+ Access these methods via `ref`:
234
+
235
+ | Method | Description |
236
+ | ----------- | -------------------------------------------------------------- |
237
+ | `capture()` | Captures an image from the camera and returns a `File` object. |
238
+ | `switch()` | Switches between front and back cameras. |
239
+ | `getMode()` | Returns current camera mode: `"front"` or `"back"`. |
240
+
241
+ ---
242
+
243
+ ## Notes ⚠️
244
+
245
+ - On mobile devices, some browsers may require HTTPS to access the camera.
246
+ - Ensure the user grants camera permissions; otherwise, the component will throw an error.
247
+ - `videoStyle` and `style` are independent β€” `videoStyle` only affects the video element, `style` affects the container.
248
+
249
+ ---
250
+
251
+ ## License πŸ“„
252
+
253
+ MIT License Β© 2025 Shivantra Solutions Private Limited
254
+
255
+ ---
256
+
257
+ ## Contact πŸ“§
258
+
259
+ For more details about our projects, services, or any general information regarding **react-web-camera**, feel free to reach out to us. We are here to provide support and answer any questions you may have. Below are the best ways to contact our team:
260
+
261
+ **Email:** Send us your inquiries or support requests at [contact@shivantra.com](mailto:contact@shivantra.com).
262
+ **Website:** Visit our official website for more information: [Shivantra](https://shivantra.com).
263
+
264
+ **Follow us on social media for updates:**
265
+
266
+ - **LinkedIn:** [Shivantra](https://www.linkedin.com/company/shivantra)
267
+ - **Instagram:** [@Shivantra](https://www.instagram.com/shivantra/)
268
+ - **Github:** [Shivantra](https://www.github.com/shivantra/)
269
+
270
+ We look forward to assisting you and ensuring your experience with **react-web-camera** is smooth and enjoyable!
@@ -0,0 +1,21 @@
1
+ export type CaptureType = "jpeg" | "png" | "webp";
2
+ export type CaptureQuality = 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1;
3
+ export type CaptureMode = "front" | "back";
4
+ export type FacingMode = "user" | "environment";
5
+ export interface WebCameraProps {
6
+ className?: string;
7
+ style?: React.CSSProperties;
8
+ videoClassName?: string;
9
+ videoStyle?: React.CSSProperties;
10
+ getFileName?: () => string;
11
+ captureMode?: CaptureMode;
12
+ captureType?: CaptureType;
13
+ captureQuality?: CaptureQuality;
14
+ onError?: (err: Error) => void;
15
+ }
16
+ export type WebCameraHandler = {
17
+ capture: () => Promise<File | null>;
18
+ switch: (facingMode?: FacingMode) => Promise<void>;
19
+ getMode: () => CaptureMode;
20
+ };
21
+ export declare const WebCamera: import('react').ForwardRefExoticComponent<WebCameraProps & import('react').RefAttributes<WebCameraHandler>>;
@@ -0,0 +1,2 @@
1
+ export * from './WebCamera';
2
+ export { WebCamera as default } from './WebCamera';
@@ -0,0 +1,22 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("react");var z={exports:{}},x={};/**
2
+ * @license React
3
+ * react-jsx-runtime.production.js
4
+ *
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var Z;function te(){if(Z)return x;Z=1;var b=Symbol.for("react.transitional.element"),h=Symbol.for("react.fragment");function k(g,o,i){var _=null;if(i!==void 0&&(_=""+i),o.key!==void 0&&(_=""+o.key),"key"in o){i={};for(var R in o)R!=="key"&&(i[R]=o[R])}else i=o;return o=i.ref,{$$typeof:b,type:g,key:_,ref:o!==void 0?o:null,props:i}}return x.Fragment=h,x.jsx=k,x.jsxs=k,x}var C={};/**
10
+ * @license React
11
+ * react-jsx-runtime.development.js
12
+ *
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var Q;function ne(){return Q||(Q=1,process.env.NODE_ENV!=="production"&&function(){function b(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===I?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case P:return"Fragment";case W:return"Profiler";case A:return"StrictMode";case t:return"Suspense";case w:return"SuspenseList";case D:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case T:return"Portal";case M:return(e.displayName||"Context")+".Provider";case N:return(e._context.displayName||"Context")+".Consumer";case a:var r=e.render;return e=e.displayName,e||(e=r.displayName||r.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case u:return r=e.displayName||null,r!==null?r:b(e.type)||"Memo";case m:r=e._payload,e=e._init;try{return b(e(r))}catch{}}return null}function h(e){return""+e}function k(e){try{h(e);var r=!1}catch{r=!0}if(r){r=console;var n=r.error,s=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return n.call(r,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",s),h(e)}}function g(e){if(e===P)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===m)return"<...>";try{var r=b(e);return r?"<"+r+">":"<...>"}catch{return"<...>"}}function o(){var e=O.A;return e===null?null:e.getOwner()}function i(){return Error("react-stack-top-frame")}function _(e){if(Y.call(e,"key")){var r=Object.getOwnPropertyDescriptor(e,"key").get;if(r&&r.isReactWarning)return!1}return e.key!==void 0}function R(e,r){function n(){G||(G=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",r))}n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}function f(){var e=b(this.type);return J[e]||(J[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function $(e,r,n,s,p,v,L,U){return n=v.ref,e={$$typeof:y,type:e,key:r,props:v,_owner:p},(n!==void 0?n:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:f}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:L}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function d(e,r,n,s,p,v,L,U){var c=r.children;if(c!==void 0)if(s)if(ee(c)){for(s=0;s<c.length;s++)j(c[s]);Object.freeze&&Object.freeze(c)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else j(c);if(Y.call(r,"key")){c=b(e);var S=Object.keys(r).filter(function(re){return re!=="key"});s=0<S.length?"{key: someKey, "+S.join(": ..., ")+": ...}":"{key: someKey}",B[c+s]||(S=0<S.length?"{"+S.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
+ let props = %s;
19
+ <%s {...props} />
20
+ React keys must be passed directly to JSX without using spread:
21
+ let props = %s;
22
+ <%s key={someKey} {...props} />`,s,c,S,c),B[c+s]=!0)}if(c=null,n!==void 0&&(k(n),c=""+n),_(r)&&(k(r.key),c=""+r.key),"key"in r){n={};for(var V in r)V!=="key"&&(n[V]=r[V])}else n=r;return c&&R(n,typeof e=="function"?e.displayName||e.name||"Unknown":e),$(e,c,v,p,o(),n,L,U)}function j(e){typeof e=="object"&&e!==null&&e.$$typeof===y&&e._store&&(e._store.validated=1)}var E=l,y=Symbol.for("react.transitional.element"),T=Symbol.for("react.portal"),P=Symbol.for("react.fragment"),A=Symbol.for("react.strict_mode"),W=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),M=Symbol.for("react.context"),a=Symbol.for("react.forward_ref"),t=Symbol.for("react.suspense"),w=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),D=Symbol.for("react.activity"),I=Symbol.for("react.client.reference"),O=E.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Y=Object.prototype.hasOwnProperty,ee=Array.isArray,F=console.createTask?console.createTask:function(){return null};E={react_stack_bottom_frame:function(e){return e()}};var G,J={},X=E.react_stack_bottom_frame.bind(E,i)(),H=F(g(i)),B={};C.Fragment=P,C.jsx=function(e,r,n,s,p){var v=1e4>O.recentlyCreatedOwnerStacks++;return d(e,r,n,!1,s,p,v?Error("react-stack-top-frame"):X,v?F(g(e)):H)},C.jsxs=function(e,r,n,s,p){var v=1e4>O.recentlyCreatedOwnerStacks++;return d(e,r,n,!0,s,p,v?Error("react-stack-top-frame"):X,v?F(g(e)):H)}}()),C}process.env.NODE_ENV==="production"?z.exports=te():z.exports=ne();var q=z.exports;const ae={back:"environment",front:"user"},K=l.forwardRef(({className:b,style:h,videoClassName:k,videoStyle:g,getFileName:o,captureMode:i="back",captureType:_="jpeg",captureQuality:R=.8,onError:f},$)=>{const d=l.useRef(null),j=l.useRef(null),[E,y]=l.useState(null),[T,P]=l.useState(ae[i]),[A,W]=l.useState([]),N=l.useCallback(async()=>{const a=d.current,t=j.current;return!a||!t||a.readyState<2?null:new Promise(w=>{const u=t.getContext("2d"),m=a.videoWidth||640,D=a.videoHeight||480;t.width=m,t.height=D,u.drawImage(a,0,0,m,D);const I=`image/${_}`;t.toBlob(async O=>{if(!O)return;const Y=new File([O],(o==null?void 0:o())??`capture-${Date.now()}.${_}`,{type:I,lastModified:Date.now()});w(Y)},I,R)})},[_,R,o]),M=l.useCallback(async()=>{E&&(E.getTracks().forEach(t=>t.stop()),d.current&&(d.current.srcObject=null));const a=T==="user"?"environment":"user";P(a);try{let t;if(A.length>=2){const u=A.find(m=>a==="user"?m.label.toLowerCase().includes("front"):m.label.toLowerCase().includes("back"));t=u?{video:{deviceId:{exact:u.deviceId}}}:{video:{facingMode:{ideal:a}}}}else t={video:{facingMode:{ideal:a}}};const w=await navigator.mediaDevices.getUserMedia(t);d.current&&(d.current.srcObject=w),y(w)}catch(t){f==null||f(t)}},[E,T,A,f]);return l.useImperativeHandle($,()=>({capture:N,switch:M,getMode:()=>T==="environment"?"back":"front"}),[T,N,M]),l.useEffect(()=>{let a;const t=d.current;return(async()=>{try{const u=await navigator.mediaDevices.enumerateDevices();W(u.filter(m=>m.kind==="videoinput")),a=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:T}}}),t&&(t.srcObject=a,t.onloadedmetadata=()=>t==null?void 0:t.play()),y(a)}catch(u){f==null||f(u)}})(),()=>{a==null||a.getTracks().forEach(u=>u.stop()),t&&(t.srcObject=null)}},[T,f]),q.jsxs("div",{className:b,style:h,children:[q.jsx("video",{ref:d,className:k,autoPlay:!0,playsInline:!0,muted:!0,style:{...g,display:"block",objectFit:"cover",height:"100%",width:"100%"},children:"Video stream not available."}),q.jsx("canvas",{ref:j,style:{display:"none"}})]})});exports.WebCamera=K;exports.default=K;
@@ -0,0 +1,387 @@
1
+ import ne, { forwardRef as ae, useRef as Z, useState as V, useCallback as Q, useImperativeHandle as oe, useEffect as se } from "react";
2
+ var q = { exports: {} }, P = {};
3
+ /**
4
+ * @license React
5
+ * react-jsx-runtime.production.js
6
+ *
7
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
8
+ *
9
+ * This source code is licensed under the MIT license found in the
10
+ * LICENSE file in the root directory of this source tree.
11
+ */
12
+ var K;
13
+ function ce() {
14
+ if (K) return P;
15
+ K = 1;
16
+ var v = Symbol.for("react.transitional.element"), g = Symbol.for("react.fragment");
17
+ function T(k, o, i) {
18
+ var b = null;
19
+ if (i !== void 0 && (b = "" + i), o.key !== void 0 && (b = "" + o.key), "key" in o) {
20
+ i = {};
21
+ for (var R in o)
22
+ R !== "key" && (i[R] = o[R]);
23
+ } else i = o;
24
+ return o = i.ref, {
25
+ $$typeof: v,
26
+ type: k,
27
+ key: b,
28
+ ref: o !== void 0 ? o : null,
29
+ props: i
30
+ };
31
+ }
32
+ return P.Fragment = g, P.jsx = T, P.jsxs = T, P;
33
+ }
34
+ var x = {};
35
+ /**
36
+ * @license React
37
+ * react-jsx-runtime.development.js
38
+ *
39
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
40
+ *
41
+ * This source code is licensed under the MIT license found in the
42
+ * LICENSE file in the root directory of this source tree.
43
+ */
44
+ var ee;
45
+ function ie() {
46
+ return ee || (ee = 1, process.env.NODE_ENV !== "production" && function() {
47
+ function v(e) {
48
+ if (e == null) return null;
49
+ if (typeof e == "function")
50
+ return e.$$typeof === M ? null : e.displayName || e.name || null;
51
+ if (typeof e == "string") return e;
52
+ switch (e) {
53
+ case S:
54
+ return "Fragment";
55
+ case $:
56
+ return "Profiler";
57
+ case A:
58
+ return "StrictMode";
59
+ case t:
60
+ return "Suspense";
61
+ case w:
62
+ return "SuspenseList";
63
+ case D:
64
+ return "Activity";
65
+ }
66
+ if (typeof e == "object")
67
+ switch (typeof e.tag == "number" && console.error(
68
+ "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
69
+ ), e.$$typeof) {
70
+ case E:
71
+ return "Portal";
72
+ case N:
73
+ return (e.displayName || "Context") + ".Provider";
74
+ case C:
75
+ return (e._context.displayName || "Context") + ".Consumer";
76
+ case a:
77
+ var r = e.render;
78
+ return e = e.displayName, e || (e = r.displayName || r.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
79
+ case l:
80
+ return r = e.displayName || null, r !== null ? r : v(e.type) || "Memo";
81
+ case d:
82
+ r = e._payload, e = e._init;
83
+ try {
84
+ return v(e(r));
85
+ } catch {
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ function g(e) {
91
+ return "" + e;
92
+ }
93
+ function T(e) {
94
+ try {
95
+ g(e);
96
+ var r = !1;
97
+ } catch {
98
+ r = !0;
99
+ }
100
+ if (r) {
101
+ r = console;
102
+ var n = r.error, s = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
103
+ return n.call(
104
+ r,
105
+ "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
106
+ s
107
+ ), g(e);
108
+ }
109
+ }
110
+ function k(e) {
111
+ if (e === S) return "<>";
112
+ if (typeof e == "object" && e !== null && e.$$typeof === d)
113
+ return "<...>";
114
+ try {
115
+ var r = v(e);
116
+ return r ? "<" + r + ">" : "<...>";
117
+ } catch {
118
+ return "<...>";
119
+ }
120
+ }
121
+ function o() {
122
+ var e = h.A;
123
+ return e === null ? null : e.getOwner();
124
+ }
125
+ function i() {
126
+ return Error("react-stack-top-frame");
127
+ }
128
+ function b(e) {
129
+ if (I.call(e, "key")) {
130
+ var r = Object.getOwnPropertyDescriptor(e, "key").get;
131
+ if (r && r.isReactWarning) return !1;
132
+ }
133
+ return e.key !== void 0;
134
+ }
135
+ function R(e, r) {
136
+ function n() {
137
+ G || (G = !0, console.error(
138
+ "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
139
+ r
140
+ ));
141
+ }
142
+ n.isReactWarning = !0, Object.defineProperty(e, "key", {
143
+ get: n,
144
+ configurable: !0
145
+ });
146
+ }
147
+ function u() {
148
+ var e = v(this.type);
149
+ return J[e] || (J[e] = !0, console.error(
150
+ "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
151
+ )), e = this.props.ref, e !== void 0 ? e : null;
152
+ }
153
+ function Y(e, r, n, s, p, m, L, U) {
154
+ return n = m.ref, e = {
155
+ $$typeof: y,
156
+ type: e,
157
+ key: r,
158
+ props: m,
159
+ _owner: p
160
+ }, (n !== void 0 ? n : null) !== null ? Object.defineProperty(e, "ref", {
161
+ enumerable: !1,
162
+ get: u
163
+ }) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
164
+ configurable: !1,
165
+ enumerable: !1,
166
+ writable: !0,
167
+ value: 0
168
+ }), Object.defineProperty(e, "_debugInfo", {
169
+ configurable: !1,
170
+ enumerable: !1,
171
+ writable: !0,
172
+ value: null
173
+ }), Object.defineProperty(e, "_debugStack", {
174
+ configurable: !1,
175
+ enumerable: !1,
176
+ writable: !0,
177
+ value: L
178
+ }), Object.defineProperty(e, "_debugTask", {
179
+ configurable: !1,
180
+ enumerable: !1,
181
+ writable: !0,
182
+ value: U
183
+ }), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
184
+ }
185
+ function f(e, r, n, s, p, m, L, U) {
186
+ var c = r.children;
187
+ if (c !== void 0)
188
+ if (s)
189
+ if (re(c)) {
190
+ for (s = 0; s < c.length; s++)
191
+ j(c[s]);
192
+ Object.freeze && Object.freeze(c);
193
+ } else
194
+ console.error(
195
+ "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
196
+ );
197
+ else j(c);
198
+ if (I.call(r, "key")) {
199
+ c = v(e);
200
+ var O = Object.keys(r).filter(function(te) {
201
+ return te !== "key";
202
+ });
203
+ s = 0 < O.length ? "{key: someKey, " + O.join(": ..., ") + ": ...}" : "{key: someKey}", B[c + s] || (O = 0 < O.length ? "{" + O.join(": ..., ") + ": ...}" : "{}", console.error(
204
+ `A props object containing a "key" prop is being spread into JSX:
205
+ let props = %s;
206
+ <%s {...props} />
207
+ React keys must be passed directly to JSX without using spread:
208
+ let props = %s;
209
+ <%s key={someKey} {...props} />`,
210
+ s,
211
+ c,
212
+ O,
213
+ c
214
+ ), B[c + s] = !0);
215
+ }
216
+ if (c = null, n !== void 0 && (T(n), c = "" + n), b(r) && (T(r.key), c = "" + r.key), "key" in r) {
217
+ n = {};
218
+ for (var W in r)
219
+ W !== "key" && (n[W] = r[W]);
220
+ } else n = r;
221
+ return c && R(
222
+ n,
223
+ typeof e == "function" ? e.displayName || e.name || "Unknown" : e
224
+ ), Y(
225
+ e,
226
+ c,
227
+ m,
228
+ p,
229
+ o(),
230
+ n,
231
+ L,
232
+ U
233
+ );
234
+ }
235
+ function j(e) {
236
+ typeof e == "object" && e !== null && e.$$typeof === y && e._store && (e._store.validated = 1);
237
+ }
238
+ var _ = ne, y = Symbol.for("react.transitional.element"), E = Symbol.for("react.portal"), S = Symbol.for("react.fragment"), A = Symbol.for("react.strict_mode"), $ = Symbol.for("react.profiler"), C = Symbol.for("react.consumer"), N = Symbol.for("react.context"), a = Symbol.for("react.forward_ref"), t = Symbol.for("react.suspense"), w = Symbol.for("react.suspense_list"), l = Symbol.for("react.memo"), d = Symbol.for("react.lazy"), D = Symbol.for("react.activity"), M = Symbol.for("react.client.reference"), h = _.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, I = Object.prototype.hasOwnProperty, re = Array.isArray, F = console.createTask ? console.createTask : function() {
239
+ return null;
240
+ };
241
+ _ = {
242
+ react_stack_bottom_frame: function(e) {
243
+ return e();
244
+ }
245
+ };
246
+ var G, J = {}, X = _.react_stack_bottom_frame.bind(
247
+ _,
248
+ i
249
+ )(), H = F(k(i)), B = {};
250
+ x.Fragment = S, x.jsx = function(e, r, n, s, p) {
251
+ var m = 1e4 > h.recentlyCreatedOwnerStacks++;
252
+ return f(
253
+ e,
254
+ r,
255
+ n,
256
+ !1,
257
+ s,
258
+ p,
259
+ m ? Error("react-stack-top-frame") : X,
260
+ m ? F(k(e)) : H
261
+ );
262
+ }, x.jsxs = function(e, r, n, s, p) {
263
+ var m = 1e4 > h.recentlyCreatedOwnerStacks++;
264
+ return f(
265
+ e,
266
+ r,
267
+ n,
268
+ !0,
269
+ s,
270
+ p,
271
+ m ? Error("react-stack-top-frame") : X,
272
+ m ? F(k(e)) : H
273
+ );
274
+ };
275
+ }()), x;
276
+ }
277
+ process.env.NODE_ENV === "production" ? q.exports = ce() : q.exports = ie();
278
+ var z = q.exports;
279
+ const le = {
280
+ back: "environment",
281
+ front: "user"
282
+ }, fe = ae(
283
+ ({
284
+ className: v,
285
+ style: g,
286
+ videoClassName: T,
287
+ videoStyle: k,
288
+ getFileName: o,
289
+ captureMode: i = "back",
290
+ captureType: b = "jpeg",
291
+ captureQuality: R = 0.8,
292
+ onError: u
293
+ }, Y) => {
294
+ const f = Z(null), j = Z(null), [_, y] = V(null), [E, S] = V(
295
+ le[i]
296
+ ), [A, $] = V([]), C = Q(async () => {
297
+ const a = f.current, t = j.current;
298
+ return !a || !t || a.readyState < 2 ? null : new Promise((w) => {
299
+ const l = t.getContext("2d"), d = a.videoWidth || 640, D = a.videoHeight || 480;
300
+ t.width = d, t.height = D, l.drawImage(a, 0, 0, d, D);
301
+ const M = `image/${b}`;
302
+ t.toBlob(
303
+ async (h) => {
304
+ if (!h) return;
305
+ const I = new File(
306
+ [h],
307
+ (o == null ? void 0 : o()) ?? `capture-${Date.now()}.${b}`,
308
+ {
309
+ type: M,
310
+ lastModified: Date.now()
311
+ }
312
+ );
313
+ w(I);
314
+ },
315
+ M,
316
+ R
317
+ );
318
+ });
319
+ }, [b, R, o]), N = Q(async () => {
320
+ _ && (_.getTracks().forEach((t) => t.stop()), f.current && (f.current.srcObject = null));
321
+ const a = E === "user" ? "environment" : "user";
322
+ S(a);
323
+ try {
324
+ let t;
325
+ if (A.length >= 2) {
326
+ const l = A.find(
327
+ (d) => a === "user" ? d.label.toLowerCase().includes("front") : d.label.toLowerCase().includes("back")
328
+ );
329
+ t = l ? { video: { deviceId: { exact: l.deviceId } } } : { video: { facingMode: { ideal: a } } };
330
+ } else
331
+ t = { video: { facingMode: { ideal: a } } };
332
+ const w = await navigator.mediaDevices.getUserMedia(t);
333
+ f.current && (f.current.srcObject = w), y(w);
334
+ } catch (t) {
335
+ u == null || u(t);
336
+ }
337
+ }, [_, E, A, u]);
338
+ return oe(
339
+ Y,
340
+ () => ({
341
+ capture: C,
342
+ switch: N,
343
+ getMode: () => E === "environment" ? "back" : "front"
344
+ }),
345
+ [E, C, N]
346
+ ), se(() => {
347
+ let a;
348
+ const t = f.current;
349
+ return (async () => {
350
+ try {
351
+ const l = await navigator.mediaDevices.enumerateDevices();
352
+ $(l.filter((d) => d.kind === "videoinput")), a = await navigator.mediaDevices.getUserMedia({
353
+ video: { facingMode: { ideal: E } }
354
+ }), t && (t.srcObject = a, t.onloadedmetadata = () => t == null ? void 0 : t.play()), y(a);
355
+ } catch (l) {
356
+ u == null || u(l);
357
+ }
358
+ })(), () => {
359
+ a == null || a.getTracks().forEach((l) => l.stop()), t && (t.srcObject = null);
360
+ };
361
+ }, [E, u]), /* @__PURE__ */ z.jsxs("div", { className: v, style: g, children: [
362
+ /* @__PURE__ */ z.jsx(
363
+ "video",
364
+ {
365
+ ref: f,
366
+ className: T,
367
+ autoPlay: !0,
368
+ playsInline: !0,
369
+ muted: !0,
370
+ style: {
371
+ ...k,
372
+ display: "block",
373
+ objectFit: "cover",
374
+ height: "100%",
375
+ width: "100%"
376
+ },
377
+ children: "Video stream not available."
378
+ }
379
+ ),
380
+ /* @__PURE__ */ z.jsx("canvas", { ref: j, style: { display: "none" } })
381
+ ] });
382
+ }
383
+ );
384
+ export {
385
+ fe as WebCamera,
386
+ fe as default
387
+ };
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@shivantra/react-web-camera",
3
+ "version": "1.0.0",
4
+ "description": "Web camera component for React (by Shivantra)",
5
+ "license": "MIT",
6
+ "sideEffects": false,
7
+ "type": "module",
8
+ "main": "./dist/react-web-camera.cjs",
9
+ "module": "./dist/react-web-camera.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/react-web-camera.js",
15
+ "require": "./dist/react-web-camera.cjs"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "keywords": [
25
+ "react",
26
+ "camera",
27
+ "webcam",
28
+ "media-devices",
29
+ "components",
30
+ "shivantra"
31
+ ],
32
+ "scripts": {
33
+ "dev": "vite",
34
+ "build": "vite build",
35
+ "typecheck": "tsc --noEmit",
36
+ "clean": "rimraf dist",
37
+ "prepublishOnly": "npm run clean && npm run build"
38
+ },
39
+ "peerDependencies": {
40
+ "react": ">=17 || >=18",
41
+ "react-dom": ">=17 || >=18"
42
+ },
43
+ "devDependencies": {
44
+ "@types/react": "^18.2.0",
45
+ "@types/react-dom": "^18.2.0",
46
+ "rimraf": "^6.0.0",
47
+ "typescript": "^5.4.0",
48
+ "vite": "^5.0.0",
49
+ "vite-plugin-dts": "^3.7.0"
50
+ },
51
+ "engines": {
52
+ "node": ">=18.0.0"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "repository": {
58
+ "type": "git",
59
+ "url": "git+https://github.com/shivantra/react-web-camera.git"
60
+ },
61
+ "bugs": {
62
+ "url": "https://github.com/shivantra/react-web-camera/issues"
63
+ },
64
+ "author": {
65
+ "name": "Shivantra",
66
+ "email": "contact@shivantra.com",
67
+ "url": "https://shivantra.com"
68
+ }
69
+ }