react-webcam
Advanced tools
Comparing version 1.1.1 to 2.0.0
@@ -10,3 +10,3 @@ (function webpackUniversalModuleDefinition(root, factory) { | ||
root["Webcam"] = factory(root["PropTypes"], root["React"]); | ||
})(this, function(__WEBPACK_EXTERNAL_MODULE_0__, __WEBPACK_EXTERNAL_MODULE_1__) { | ||
})(window, function(__WEBPACK_EXTERNAL_MODULE_prop_types__, __WEBPACK_EXTERNAL_MODULE_react__) { | ||
return /******/ (function(modules) { // webpackBootstrap | ||
@@ -47,16 +47,33 @@ /******/ // The module cache | ||
/******/ | ||
/******/ // identity function for calling harmony imports with the correct context | ||
/******/ __webpack_require__.i = function(value) { return value; }; | ||
/******/ | ||
/******/ // define getter function for harmony exports | ||
/******/ __webpack_require__.d = function(exports, name, getter) { | ||
/******/ if(!__webpack_require__.o(exports, name)) { | ||
/******/ Object.defineProperty(exports, name, { | ||
/******/ configurable: false, | ||
/******/ enumerable: true, | ||
/******/ get: getter | ||
/******/ }); | ||
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); | ||
/******/ } | ||
/******/ }; | ||
/******/ | ||
/******/ // define __esModule on exports | ||
/******/ __webpack_require__.r = function(exports) { | ||
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { | ||
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); | ||
/******/ } | ||
/******/ Object.defineProperty(exports, '__esModule', { value: true }); | ||
/******/ }; | ||
/******/ | ||
/******/ // create a fake namespace object | ||
/******/ // mode & 1: value is a module id, require it | ||
/******/ // mode & 2: merge all properties of value into the ns | ||
/******/ // mode & 4: return value when already ns object | ||
/******/ // mode & 8|1: behave like require | ||
/******/ __webpack_require__.t = function(value, mode) { | ||
/******/ if(mode & 1) value = __webpack_require__(value); | ||
/******/ if(mode & 8) return value; | ||
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; | ||
/******/ var ns = Object.create(null); | ||
/******/ __webpack_require__.r(ns); | ||
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); | ||
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); | ||
/******/ return ns; | ||
/******/ }; | ||
/******/ | ||
/******/ // getDefaultExport function for compatibility with non-harmony modules | ||
@@ -77,347 +94,43 @@ /******/ __webpack_require__.n = function(module) { | ||
/******/ | ||
/******/ | ||
/******/ // Load entry module and return exports | ||
/******/ return __webpack_require__(__webpack_require__.s = 2); | ||
/******/ return __webpack_require__(__webpack_require__.s = "./src/react-webcam.js"); | ||
/******/ }) | ||
/************************************************************************/ | ||
/******/ ([ | ||
/* 0 */ | ||
/***/ (function(module, exports) { | ||
/******/ ({ | ||
module.exports = __WEBPACK_EXTERNAL_MODULE_0__; | ||
/***/ "./src/react-webcam.js": | ||
/*!*****************************!*\ | ||
!*** ./src/react-webcam.js ***! | ||
\*****************************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
eval("var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) {\n if (true) {\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(/*! react */ \"react\"), __webpack_require__(/*! prop-types */ \"prop-types\")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else { var mod; }\n})(this, function (_exports, _react, _propTypes) {\n \"use strict\";\n\n Object.defineProperty(_exports, \"__esModule\", {\n value: true\n });\n _exports[\"default\"] = void 0;\n _react = _interopRequireWildcard(_react);\n _propTypes = _interopRequireDefault(_propTypes);\n\n function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj[\"default\"] = obj; return newObj; } }\n\n function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\n function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }\n\n function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\n function _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\n function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\n function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\n function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\n function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\n function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\n function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n function _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\n function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\n function hasGetUserMedia() {\n return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);\n }\n\n var constrainStringType = _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].string, _propTypes[\"default\"].arrayOf(_propTypes[\"default\"].string), _propTypes[\"default\"].shape({\n exact: _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].string, _propTypes[\"default\"].arrayOf(_propTypes[\"default\"].string)])\n }), _propTypes[\"default\"].shape({\n ideal: _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].string, _propTypes[\"default\"].arrayOf(_propTypes[\"default\"].string)])\n })]);\n\n var constrainBooleanType = _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].shape({\n exact: _propTypes[\"default\"].bool\n }), _propTypes[\"default\"].shape({\n ideal: _propTypes[\"default\"].bool\n })]);\n\n var constrainLongType = _propTypes[\"default\"].oneOfType([_propTypes[\"default\"].number, _propTypes[\"default\"].shape({\n exact: _propTypes[\"default\"].number,\n ideal: _propTypes[\"default\"].number,\n min: _propTypes[\"default\"].number,\n max: _propTypes[\"default\"].number\n })]);\n\n var constrainDoubleType = constrainLongType;\n\n var audioConstraintType = _propTypes[\"default\"].shape({\n deviceId: constrainStringType,\n groupId: constrainStringType,\n autoGainControl: constrainBooleanType,\n channelCount: constrainLongType,\n latency: constrainDoubleType,\n noiseSuppression: constrainBooleanType,\n sampleRate: constrainLongType,\n sampleSize: constrainLongType,\n volume: constrainDoubleType\n });\n\n var videoConstraintType = _propTypes[\"default\"].shape({\n deviceId: constrainStringType,\n groupId: constrainStringType,\n aspectRatio: constrainDoubleType,\n facingMode: constrainStringType,\n frameRate: constrainDoubleType,\n height: constrainLongType,\n width: constrainLongType\n });\n\n var propTypes = {\n audio: _propTypes[\"default\"].bool,\n onUserMedia: _propTypes[\"default\"].func,\n onUserMediaError: _propTypes[\"default\"].func,\n screenshotFormat: _propTypes[\"default\"].oneOf(['image/webp', 'image/png', 'image/jpeg']),\n screenshotQuality: _propTypes[\"default\"].number,\n minScreenshotWidth: _propTypes[\"default\"].number,\n minScreenshotHeight: _propTypes[\"default\"].number,\n audioConstraints: audioConstraintType,\n videoConstraints: videoConstraintType,\n imageSmoothing: _propTypes[\"default\"].bool\n };\n\n var Webcam =\n /*#__PURE__*/\n function (_Component) {\n _inherits(Webcam, _Component);\n\n function Webcam() {\n var _this;\n\n _classCallCheck(this, Webcam);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(Webcam).call(this));\n _this.state = {\n hasUserMedia: false\n };\n return _this;\n }\n\n _createClass(Webcam, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n if (!hasGetUserMedia()) return;\n var state = this.state;\n Webcam.mountedInstances.push(this);\n\n if (!state.hasUserMedia && !Webcam.userMediaRequested) {\n this.requestUserMedia();\n }\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate(nextProps) {\n var props = this.props;\n\n if (JSON.stringify(nextProps.audioConstraints) !== JSON.stringify(props.audioConstraints) || JSON.stringify(nextProps.videoConstraints) !== JSON.stringify(props.videoConstraints)) {\n this.requestUserMedia();\n }\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n var state = this.state;\n var index = Webcam.mountedInstances.indexOf(this);\n Webcam.mountedInstances.splice(index, 1);\n Webcam.userMediaRequested = false;\n\n if (Webcam.mountedInstances.length === 0 && state.hasUserMedia) {\n if (this.stream.getVideoTracks && this.stream.getAudioTracks) {\n this.stream.getVideoTracks().map(function (track) {\n return track.stop();\n });\n this.stream.getAudioTracks().map(function (track) {\n return track.stop();\n });\n } else {\n this.stream.stop();\n }\n\n window.URL.revokeObjectURL(state.src);\n }\n }\n }, {\n key: \"getScreenshot\",\n value: function getScreenshot() {\n var state = this.state,\n props = this.props;\n if (!state.hasUserMedia) return null;\n var canvas = this.getCanvas();\n return canvas && canvas.toDataURL(props.screenshotFormat, props.screenshotQuality);\n }\n }, {\n key: \"getCanvas\",\n value: function getCanvas() {\n var state = this.state,\n props = this.props;\n if (!state.hasUserMedia || !this.video.videoHeight) return null;\n\n if (!this.ctx) {\n var _canvas = document.createElement('canvas');\n\n var aspectRatio = this.video.videoWidth / this.video.videoHeight;\n var canvasWidth = props.minScreenshotWidth || this.video.clientWidth;\n var canvasHeight = canvasWidth / aspectRatio;\n\n if (props.minScreenshotHeight && canvasHeight < props.minScreenshotHeight) {\n canvasHeight = props.minScreenshotHeight;\n canvasWidth = canvasHeight * aspectRatio;\n }\n\n _canvas.width = canvasWidth;\n _canvas.height = canvasHeight;\n this.canvas = _canvas;\n this.ctx = _canvas.getContext('2d');\n }\n\n var ctx = this.ctx,\n canvas = this.canvas;\n ctx.imageSmoothingEnabled = props.imageSmoothing;\n ctx.drawImage(this.video, 0, 0, canvas.width, canvas.height);\n return canvas;\n }\n }, {\n key: \"requestUserMedia\",\n value: function requestUserMedia() {\n var props = this.props;\n navigator.getUserMedia = navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;\n\n var sourceSelected = function sourceSelected(audioConstraints, videoConstraints) {\n var constraints = {\n video: typeof videoConstraints !== 'undefined' ? videoConstraints : true\n };\n\n if (props.audio) {\n constraints.audio = typeof audioConstraints !== 'undefined' ? audioConstraints : true;\n }\n\n navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {\n Webcam.mountedInstances.forEach(function (instance) {\n return instance.handleUserMedia(null, stream);\n });\n })[\"catch\"](function (e) {\n Webcam.mountedInstances.forEach(function (instance) {\n return instance.handleUserMedia(e);\n });\n });\n };\n\n if ('mediaDevices' in navigator) {\n sourceSelected(props.audioConstraints, props.videoConstraints);\n } else {\n var optionalSource = function optionalSource(id) {\n return {\n optional: [{\n sourceId: id\n }]\n };\n };\n\n var constraintToSourceId = function constraintToSourceId(constraint) {\n var _ref = constraint || {},\n deviceId = _ref.deviceId;\n\n if (typeof deviceId === 'string') {\n return deviceId;\n }\n\n if (Array.isArray(deviceId) && deviceId.length > 0) {\n return deviceId[0];\n }\n\n if (_typeof(deviceId) === 'object' && deviceId.ideal) {\n return deviceId.ideal;\n }\n\n return null;\n };\n\n MediaStreamTrack.getSources(function (sources) {\n var audioSource = null;\n var videoSource = null;\n sources.forEach(function (source) {\n if (source.kind === 'audio') {\n audioSource = source.id;\n } else if (source.kind === 'video') {\n videoSource = source.id;\n }\n });\n var audioSourceId = constraintToSourceId(props.audioConstraints);\n\n if (audioSourceId) {\n audioSource = audioSourceId;\n }\n\n var videoSourceId = constraintToSourceId(props.videoConstraints);\n\n if (videoSourceId) {\n videoSource = videoSourceId;\n }\n\n sourceSelected(optionalSource(audioSource), optionalSource(videoSource));\n });\n }\n\n Webcam.userMediaRequested = true;\n }\n }, {\n key: \"handleUserMedia\",\n value: function handleUserMedia(err, stream) {\n var props = this.props;\n\n if (err) {\n this.setState({\n hasUserMedia: false\n });\n props.onUserMediaError(err);\n return;\n }\n\n this.stream = stream;\n\n try {\n this.video.srcObject = stream;\n this.setState({\n hasUserMedia: true\n });\n } catch (error) {\n this.setState({\n hasUserMedia: true,\n src: window.URL.createObjectURL(stream)\n });\n }\n\n props.onUserMedia();\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this2 = this;\n\n var state = this.state,\n props = this.props;\n var passThroughProps = Object.entries(props).reduce(function (result, _ref2) {\n var _ref3 = _slicedToArray(_ref2, 2),\n key = _ref3[0],\n value = _ref3[1];\n\n if (Object.prototype.hasOwnProperty.call(propTypes, key)) {\n return result;\n }\n\n return _objectSpread({}, result, _defineProperty({}, key, value));\n }, {});\n return _react[\"default\"].createElement(\"video\", _extends({\n autoPlay: true,\n src: state.src,\n muted: props.audio,\n playsInline: true,\n ref: function ref(_ref4) {\n _this2.video = _ref4;\n }\n }, passThroughProps));\n }\n }]);\n\n return Webcam;\n }(_react.Component);\n\n _exports[\"default\"] = Webcam;\n Webcam.defaultProps = {\n audio: true,\n imageSmoothing: true,\n onUserMedia: function onUserMedia() {},\n onUserMediaError: function onUserMediaError() {},\n screenshotFormat: 'image/webp',\n screenshotQuality: 0.92\n };\n Webcam.propTypes = propTypes;\n Webcam.mountedInstances = [];\n Webcam.userMediaRequested = false;\n module.exports = exports.default;\n});\n\n//# sourceURL=webpack://Webcam/./src/react-webcam.js?"); | ||
/***/ }), | ||
/* 1 */ | ||
/***/ "prop-types": | ||
/*!*********************************************************************************************************!*\ | ||
!*** external {"root":"PropTypes","commonjs2":"prop-types","commonjs":"prop-types","amd":"prop-types"} ***! | ||
\*********************************************************************************************************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports) { | ||
module.exports = __WEBPACK_EXTERNAL_MODULE_1__; | ||
eval("module.exports = __WEBPACK_EXTERNAL_MODULE_prop_types__;\n\n//# sourceURL=webpack://Webcam/external_%7B%22root%22:%22PropTypes%22,%22commonjs2%22:%22prop-types%22,%22commonjs%22:%22prop-types%22,%22amd%22:%22prop-types%22%7D?"); | ||
/***/ }), | ||
/* 2 */ | ||
/***/ (function(module, exports, __webpack_require__) { | ||
"use strict"; | ||
/***/ "react": | ||
/*!**************************************************************************************!*\ | ||
!*** external {"root":"React","commonjs2":"react","commonjs":"react","amd":"react"} ***! | ||
\**************************************************************************************/ | ||
/*! no static exports found */ | ||
/***/ (function(module, exports) { | ||
eval("module.exports = __WEBPACK_EXTERNAL_MODULE_react__;\n\n//# sourceURL=webpack://Webcam/external_%7B%22root%22:%22React%22,%22commonjs2%22:%22react%22,%22commonjs%22:%22react%22,%22amd%22:%22react%22%7D?"); | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
/***/ }) | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; | ||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
var _react = __webpack_require__(1); | ||
var _react2 = _interopRequireDefault(_react); | ||
var _propTypes = __webpack_require__(0); | ||
var _propTypes2 = _interopRequireDefault(_propTypes); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | ||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } | ||
function hasGetUserMedia() { | ||
return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); | ||
} | ||
var constrainStringType = _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.arrayOf(_propTypes2.default.string), _propTypes2.default.shape({ | ||
exact: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.arrayOf(_propTypes2.default.string)]) | ||
}), _propTypes2.default.shape({ | ||
ideal: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.arrayOf(_propTypes2.default.string)]) | ||
})]); | ||
var constrainBooleanType = _propTypes2.default.oneOfType([_propTypes2.default.shape({ | ||
exact: _propTypes2.default.bool | ||
}), _propTypes2.default.shape({ | ||
ideal: _propTypes2.default.bool | ||
})]); | ||
var constrainLongType = _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.shape({ | ||
exact: _propTypes2.default.number, | ||
ideal: _propTypes2.default.number, | ||
min: _propTypes2.default.number, | ||
max: _propTypes2.default.number | ||
})]); | ||
var constrainDoubleType = constrainLongType; | ||
var audioConstraintType = _propTypes2.default.shape({ | ||
deviceId: constrainStringType, | ||
groupId: constrainStringType, | ||
autoGainControl: constrainBooleanType, | ||
channelCount: constrainLongType, | ||
latency: constrainDoubleType, | ||
noiseSuppression: constrainBooleanType, | ||
sampleRate: constrainLongType, | ||
sampleSize: constrainLongType, | ||
volume: constrainDoubleType | ||
}); | ||
var videoConstraintType = _propTypes2.default.shape({ | ||
deviceId: constrainStringType, | ||
groupId: constrainStringType, | ||
aspectRatio: constrainDoubleType, | ||
facingMode: constrainStringType, | ||
frameRate: constrainDoubleType, | ||
height: constrainLongType, | ||
width: constrainLongType | ||
}); | ||
var Webcam = function (_Component) { | ||
_inherits(Webcam, _Component); | ||
function Webcam() { | ||
_classCallCheck(this, Webcam); | ||
var _this = _possibleConstructorReturn(this, (Webcam.__proto__ || Object.getPrototypeOf(Webcam)).call(this)); | ||
_this.state = { | ||
hasUserMedia: false | ||
}; | ||
return _this; | ||
} | ||
_createClass(Webcam, [{ | ||
key: 'componentDidMount', | ||
value: function componentDidMount() { | ||
if (!hasGetUserMedia()) return; | ||
Webcam.mountedInstances.push(this); | ||
if (!this.state.hasUserMedia && !Webcam.userMediaRequested) { | ||
this.requestUserMedia(); | ||
} | ||
} | ||
}, { | ||
key: 'componentDidUpdate', | ||
value: function componentDidUpdate(nextProps) { | ||
if (JSON.stringify(nextProps.audioConstraints) !== JSON.stringify(this.props.audioConstraints) || JSON.stringify(nextProps.videoConstraints) !== JSON.stringify(this.props.videoConstraints)) { | ||
this.requestUserMedia(); | ||
} | ||
} | ||
}, { | ||
key: 'componentWillUnmount', | ||
value: function componentWillUnmount() { | ||
var index = Webcam.mountedInstances.indexOf(this); | ||
Webcam.mountedInstances.splice(index, 1); | ||
Webcam.userMediaRequested = false; | ||
if (Webcam.mountedInstances.length === 0 && this.state.hasUserMedia) { | ||
if (this.stream.getVideoTracks && this.stream.getAudioTracks) { | ||
this.stream.getVideoTracks().map(function (track) { | ||
return track.stop(); | ||
}); | ||
this.stream.getAudioTracks().map(function (track) { | ||
return track.stop(); | ||
}); | ||
} else { | ||
this.stream.stop(); | ||
} | ||
window.URL.revokeObjectURL(this.state.src); | ||
} | ||
} | ||
}, { | ||
key: 'getScreenshot', | ||
value: function getScreenshot() { | ||
if (!this.state.hasUserMedia) return null; | ||
var canvas = this.getCanvas(); | ||
return canvas && canvas.toDataURL(this.props.screenshotFormat, this.props.screenshotQuality); | ||
} | ||
}, { | ||
key: 'getCanvas', | ||
value: function getCanvas() { | ||
if (!this.state.hasUserMedia || !this.video.videoHeight) return null; | ||
if (!this.ctx) { | ||
var _canvas = document.createElement('canvas'); | ||
var aspectRatio = this.video.videoWidth / this.video.videoHeight; | ||
var canvasWidth = this.props.minScreenshotWidth || this.video.clientWidth; | ||
var canvasHeight = canvasWidth / aspectRatio; | ||
if (this.props.minScreenshotHeight && canvasHeight < this.props.minScreenshotHeight) { | ||
canvasHeight = this.props.minScreenshotHeight; | ||
canvasWidth = canvasHeight * aspectRatio; | ||
} | ||
_canvas.width = canvasWidth; | ||
_canvas.height = canvasHeight; | ||
this.canvas = _canvas; | ||
this.ctx = _canvas.getContext('2d'); | ||
} | ||
var ctx = this.ctx, | ||
canvas = this.canvas; | ||
ctx.imageSmoothingEnabled = this.props.imageSmoothing; | ||
ctx.drawImage(this.video, 0, 0, canvas.width, canvas.height); | ||
return canvas; | ||
} | ||
}, { | ||
key: 'requestUserMedia', | ||
value: function requestUserMedia() { | ||
var _this2 = this; | ||
navigator.getUserMedia = navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; | ||
var sourceSelected = function sourceSelected(audioConstraints, videoConstraints) { | ||
var constraints = { | ||
video: videoConstraints || true | ||
}; | ||
if (_this2.props.audio) { | ||
constraints.audio = audioConstraints || true; | ||
} | ||
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { | ||
Webcam.mountedInstances.forEach(function (instance) { | ||
return instance.handleUserMedia(null, stream); | ||
}); | ||
}).catch(function (e) { | ||
Webcam.mountedInstances.forEach(function (instance) { | ||
return instance.handleUserMedia(e); | ||
}); | ||
}); | ||
}; | ||
if ('mediaDevices' in navigator) { | ||
sourceSelected(this.props.audioConstraints, this.props.videoConstraints); | ||
} else { | ||
var optionalSource = function optionalSource(id) { | ||
return { optional: [{ sourceId: id }] }; | ||
}; | ||
var constraintToSourceId = function constraintToSourceId(constraint) { | ||
var deviceId = (constraint || {}).deviceId; | ||
if (typeof deviceId === 'string') { | ||
return deviceId; | ||
} else if (Array.isArray(deviceId) && deviceId.length > 0) { | ||
return deviceId[0]; | ||
} else if ((typeof deviceId === 'undefined' ? 'undefined' : _typeof(deviceId)) === 'object' && deviceId.ideal) { | ||
return deviceId.ideal; | ||
} | ||
return null; | ||
}; | ||
MediaStreamTrack.getSources(function (sources) { | ||
var audioSource = null; | ||
var videoSource = null; | ||
sources.forEach(function (source) { | ||
if (source.kind === 'audio') { | ||
audioSource = source.id; | ||
} else if (source.kind === 'video') { | ||
videoSource = source.id; | ||
} | ||
}); | ||
var audioSourceId = constraintToSourceId(_this2.props.audioConstraints); | ||
if (audioSourceId) { | ||
audioSource = audioSourceId; | ||
} | ||
var videoSourceId = constraintToSourceId(_this2.props.videoConstraints); | ||
if (videoSourceId) { | ||
videoSource = videoSourceId; | ||
} | ||
sourceSelected(optionalSource(audioSource), optionalSource(videoSource)); | ||
}); | ||
} | ||
Webcam.userMediaRequested = true; | ||
} | ||
}, { | ||
key: 'handleUserMedia', | ||
value: function handleUserMedia(err, stream) { | ||
if (err) { | ||
this.setState({ hasUserMedia: false }); | ||
this.props.onUserMediaError(err); | ||
return; | ||
} | ||
this.stream = stream; | ||
try { | ||
this.video.srcObject = stream; | ||
this.setState({ hasUserMedia: true }); | ||
} catch (error) { | ||
this.setState({ | ||
hasUserMedia: true, | ||
src: window.URL.createObjectURL(stream) | ||
}); | ||
} | ||
this.props.onUserMedia(); | ||
} | ||
}, { | ||
key: 'render', | ||
value: function render() { | ||
var _this3 = this; | ||
return _react2.default.createElement('video', { | ||
autoPlay: true, | ||
width: this.props.width, | ||
height: this.props.height, | ||
src: this.state.src, | ||
muted: this.props.audio, | ||
className: this.props.className, | ||
playsInline: true, | ||
style: this.props.style, | ||
ref: function ref(_ref) { | ||
_this3.video = _ref; | ||
} | ||
}); | ||
} | ||
}]); | ||
return Webcam; | ||
}(_react.Component); | ||
Webcam.defaultProps = { | ||
audio: true, | ||
className: '', | ||
height: 480, | ||
imageSmoothing: true, | ||
onUserMedia: function onUserMedia() {}, | ||
onUserMediaError: function onUserMediaError() {}, | ||
screenshotFormat: 'image/webp', | ||
width: 640, | ||
screenshotQuality: 0.92 | ||
}; | ||
Webcam.propTypes = { | ||
audio: _propTypes2.default.bool, | ||
onUserMedia: _propTypes2.default.func, | ||
onUserMediaError: _propTypes2.default.func, | ||
height: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]), | ||
width: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]), | ||
screenshotFormat: _propTypes2.default.oneOf(['image/webp', 'image/png', 'image/jpeg']), | ||
style: _propTypes2.default.object, | ||
className: _propTypes2.default.string, | ||
screenshotQuality: _propTypes2.default.number, | ||
minScreenshotWidth: _propTypes2.default.number, | ||
minScreenshotHeight: _propTypes2.default.number, | ||
audioConstraints: audioConstraintType, | ||
videoConstraints: videoConstraintType, | ||
imageSmoothing: _propTypes2.default.bool | ||
}; | ||
Webcam.mountedInstances = []; | ||
Webcam.userMediaRequested = false; | ||
exports.default = Webcam; | ||
module.exports = exports['default']; | ||
/***/ }) | ||
/******/ ]); | ||
/******/ }); | ||
}); |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("prop-types"),require("react")):"function"==typeof define&&define.amd?define(["prop-types","react"],t):"object"==typeof exports?exports.Webcam=t(require("prop-types"),require("react")):e.Webcam=t(e.PropTypes,e.React)}(this,function(e,t){return function(e){function t(i){if(n[i])return n[i].exports;var r=n[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,i){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:i})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=2)}([function(t,n){t.exports=e},function(e,n){e.exports=t},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia)}Object.defineProperty(t,"__esModule",{value:!0});var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},d=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}(),c=n(1),f=i(c),l=n(0),p=i(l),h=p.default.oneOfType([p.default.string,p.default.arrayOf(p.default.string),p.default.shape({exact:p.default.oneOfType([p.default.string,p.default.arrayOf(p.default.string)])}),p.default.shape({ideal:p.default.oneOfType([p.default.string,p.default.arrayOf(p.default.string)])})]),m=p.default.oneOfType([p.default.shape({exact:p.default.bool}),p.default.shape({ideal:p.default.bool})]),g=p.default.oneOfType([p.default.number,p.default.shape({exact:p.default.number,ideal:p.default.number,min:p.default.number,max:p.default.number})]),v=g,y=p.default.shape({deviceId:h,groupId:h,autoGainControl:m,channelCount:g,latency:v,noiseSuppression:m,sampleRate:g,sampleSize:g,volume:v}),b=p.default.shape({deviceId:h,groupId:h,aspectRatio:v,facingMode:h,frameRate:v,height:g,width:g}),M=function(e){function t(){r(this,t);var e=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return e.state={hasUserMedia:!1},e}return o(t,e),d(t,[{key:"componentDidMount",value:function(){s()&&(t.mountedInstances.push(this),this.state.hasUserMedia||t.userMediaRequested||this.requestUserMedia())}},{key:"componentDidUpdate",value:function(e){JSON.stringify(e.audioConstraints)===JSON.stringify(this.props.audioConstraints)&&JSON.stringify(e.videoConstraints)===JSON.stringify(this.props.videoConstraints)||this.requestUserMedia()}},{key:"componentWillUnmount",value:function(){var e=t.mountedInstances.indexOf(this);t.mountedInstances.splice(e,1),t.userMediaRequested=!1,0===t.mountedInstances.length&&this.state.hasUserMedia&&(this.stream.getVideoTracks&&this.stream.getAudioTracks?(this.stream.getVideoTracks().map(function(e){return e.stop()}),this.stream.getAudioTracks().map(function(e){return e.stop()})):this.stream.stop(),window.URL.revokeObjectURL(this.state.src))}},{key:"getScreenshot",value:function(){if(!this.state.hasUserMedia)return null;var e=this.getCanvas();return e&&e.toDataURL(this.props.screenshotFormat,this.props.screenshotQuality)}},{key:"getCanvas",value:function(){if(!this.state.hasUserMedia||!this.video.videoHeight)return null;if(!this.ctx){var e=document.createElement("canvas"),t=this.video.videoWidth/this.video.videoHeight,n=this.props.minScreenshotWidth||this.video.clientWidth,i=n/t;this.props.minScreenshotHeight&&i<this.props.minScreenshotHeight&&(i=this.props.minScreenshotHeight,n=i*t),e.width=n,e.height=i,this.canvas=e,this.ctx=e.getContext("2d")}var r=this.ctx,a=this.canvas;return r.imageSmoothingEnabled=this.props.imageSmoothing,r.drawImage(this.video,0,0,a.width,a.height),a}},{key:"requestUserMedia",value:function(){var e=this;navigator.getUserMedia=navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var n=function(n,i){var r={video:i||!0};e.props.audio&&(r.audio=n||!0),navigator.mediaDevices.getUserMedia(r).then(function(e){t.mountedInstances.forEach(function(t){return t.handleUserMedia(null,e)})}).catch(function(e){t.mountedInstances.forEach(function(t){return t.handleUserMedia(e)})})};if("mediaDevices"in navigator)n(this.props.audioConstraints,this.props.videoConstraints);else{var i=function(e){return{optional:[{sourceId:e}]}},r=function(e){var t=(e||{}).deviceId;return"string"==typeof t?t:Array.isArray(t)&&t.length>0?t[0]:"object"===(void 0===t?"undefined":u(t))&&t.ideal?t.ideal:null};MediaStreamTrack.getSources(function(t){var a=null,o=null;t.forEach(function(e){"audio"===e.kind?a=e.id:"video"===e.kind&&(o=e.id)});var s=r(e.props.audioConstraints);s&&(a=s);var u=r(e.props.videoConstraints);u&&(o=u),n(i(a),i(o))})}t.userMediaRequested=!0}},{key:"handleUserMedia",value:function(e,t){if(e)return this.setState({hasUserMedia:!1}),void this.props.onUserMediaError(e);this.stream=t;try{this.video.srcObject=t,this.setState({hasUserMedia:!0})}catch(e){this.setState({hasUserMedia:!0,src:window.URL.createObjectURL(t)})}this.props.onUserMedia()}},{key:"render",value:function(){var e=this;return f.default.createElement("video",{autoPlay:!0,width:this.props.width,height:this.props.height,src:this.state.src,muted:this.props.audio,className:this.props.className,playsInline:!0,style:this.props.style,ref:function(t){e.video=t}})}}]),t}(c.Component);M.defaultProps={audio:!0,className:"",height:480,imageSmoothing:!0,onUserMedia:function(){},onUserMediaError:function(){},screenshotFormat:"image/webp",width:640,screenshotQuality:.92},M.propTypes={audio:p.default.bool,onUserMedia:p.default.func,onUserMediaError:p.default.func,height:p.default.oneOfType([p.default.number,p.default.string]),width:p.default.oneOfType([p.default.number,p.default.string]),screenshotFormat:p.default.oneOf(["image/webp","image/png","image/jpeg"]),style:p.default.object,className:p.default.string,screenshotQuality:p.default.number,minScreenshotWidth:p.default.number,minScreenshotHeight:p.default.number,audioConstraints:y,videoConstraints:b,imageSmoothing:p.default.bool},M.mountedInstances=[],M.userMediaRequested=!1,t.default=M,e.exports=t.default}])}); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("prop-types")):"function"==typeof define&&define.amd?define(["react","prop-types"],t):"object"==typeof exports?exports.Webcam=t(require("react"),require("prop-types")):e.Webcam=t(e.React,e.PropTypes)}(window,function(e,t){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){var n,o,i;o=[t,r(1),r(2)],void 0===(i="function"==typeof(n=function(r,n,o){"use strict";function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=[],n=!0,o=!1,i=void 0;try{for(var a,u=e[Symbol.iterator]();!(n=(a=u.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){o=!0,i=e}finally{try{n||null==u.return||u.return()}finally{if(o)throw i}}return r}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function s(e){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function c(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function d(e,t){return!t||"object"!==s(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function l(e,t){return(l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0,n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){var n=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,r):{};n.get||n.set?Object.defineProperty(t,r,n):t[r]=e[r]}return t.default=e,t}(n);var p,h=(p=o,o=p&&p.__esModule?p:{default:p}).default.oneOfType([o.default.string,o.default.arrayOf(o.default.string),o.default.shape({exact:o.default.oneOfType([o.default.string,o.default.arrayOf(o.default.string)])}),o.default.shape({ideal:o.default.oneOfType([o.default.string,o.default.arrayOf(o.default.string)])})]),v=o.default.oneOfType([o.default.shape({exact:o.default.bool}),o.default.shape({ideal:o.default.bool})]),y=o.default.oneOfType([o.default.number,o.default.shape({exact:o.default.number,ideal:o.default.number,min:o.default.number,max:o.default.number})]),m=y,g=o.default.shape({deviceId:h,groupId:h,autoGainControl:v,channelCount:y,latency:m,noiseSuppression:v,sampleRate:y,sampleSize:y,volume:m}),b=o.default.shape({deviceId:h,groupId:h,aspectRatio:m,facingMode:h,frameRate:m,height:y,width:y}),O={audio:o.default.bool,onUserMedia:o.default.func,onUserMediaError:o.default.func,screenshotFormat:o.default.oneOf(["image/webp","image/png","image/jpeg"]),screenshotQuality:o.default.number,minScreenshotWidth:o.default.number,minScreenshotHeight:o.default.number,audioConstraints:g,videoConstraints:b,imageSmoothing:o.default.bool},M=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=d(this,f(t).call(this))).state={hasUserMedia:!1},e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&l(e,t)}(t,e),r=t,(o=[{key:"componentDidMount",value:function(){if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia){var e=this.state;t.mountedInstances.push(this),e.hasUserMedia||t.userMediaRequested||this.requestUserMedia()}}},{key:"componentDidUpdate",value:function(e){var t=this.props;JSON.stringify(e.audioConstraints)===JSON.stringify(t.audioConstraints)&&JSON.stringify(e.videoConstraints)===JSON.stringify(t.videoConstraints)||this.requestUserMedia()}},{key:"componentWillUnmount",value:function(){var e=this.state,r=t.mountedInstances.indexOf(this);t.mountedInstances.splice(r,1),t.userMediaRequested=!1,0===t.mountedInstances.length&&e.hasUserMedia&&(this.stream.getVideoTracks&&this.stream.getAudioTracks?(this.stream.getVideoTracks().map(function(e){return e.stop()}),this.stream.getAudioTracks().map(function(e){return e.stop()})):this.stream.stop(),window.URL.revokeObjectURL(e.src))}},{key:"getScreenshot",value:function(){var e=this.state,t=this.props;if(!e.hasUserMedia)return null;var r=this.getCanvas();return r&&r.toDataURL(t.screenshotFormat,t.screenshotQuality)}},{key:"getCanvas",value:function(){var e=this.state,t=this.props;if(!e.hasUserMedia||!this.video.videoHeight)return null;if(!this.ctx){var r=document.createElement("canvas"),n=this.video.videoWidth/this.video.videoHeight,o=t.minScreenshotWidth||this.video.clientWidth,i=o/n;t.minScreenshotHeight&&i<t.minScreenshotHeight&&(i=t.minScreenshotHeight,o=i*n),r.width=o,r.height=i,this.canvas=r,this.ctx=r.getContext("2d")}var a=this.ctx,u=this.canvas;return a.imageSmoothingEnabled=t.imageSmoothing,a.drawImage(this.video,0,0,u.width,u.height),u}},{key:"requestUserMedia",value:function(){var e=this.props;navigator.getUserMedia=navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var r=function(r,n){var o={video:void 0===n||n};e.audio&&(o.audio=void 0===r||r),navigator.mediaDevices.getUserMedia(o).then(function(e){t.mountedInstances.forEach(function(t){return t.handleUserMedia(null,e)})}).catch(function(e){t.mountedInstances.forEach(function(t){return t.handleUserMedia(e)})})};if("mediaDevices"in navigator)r(e.audioConstraints,e.videoConstraints);else{var n=function(e){return{optional:[{sourceId:e}]}},o=function(e){var t=e||{},r=t.deviceId;return"string"==typeof r?r:Array.isArray(r)&&r.length>0?r[0]:"object"===s(r)&&r.ideal?r.ideal:null};MediaStreamTrack.getSources(function(t){var i=null,a=null;t.forEach(function(e){"audio"===e.kind?i=e.id:"video"===e.kind&&(a=e.id)});var u=o(e.audioConstraints);u&&(i=u);var s=o(e.videoConstraints);s&&(a=s),r(n(i),n(a))})}t.userMediaRequested=!0}},{key:"handleUserMedia",value:function(e,t){var r=this.props;if(e)return this.setState({hasUserMedia:!1}),void r.onUserMediaError(e);this.stream=t;try{this.video.srcObject=t,this.setState({hasUserMedia:!0})}catch(e){this.setState({hasUserMedia:!0,src:window.URL.createObjectURL(t)})}r.onUserMedia()}},{key:"render",value:function(){var e=this,t=this.state,r=this.props,o=Object.entries(r).reduce(function(e,t){var r=u(t,2),n=r[0],o=r[1];return Object.prototype.hasOwnProperty.call(O,n)?e:function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){a(e,t,r[t])})}return e}({},e,a({},n,o))},{});return n.default.createElement("video",i({autoPlay:!0,src:t.src,muted:r.audio,playsInline:!0,ref:function(t){e.video=t}},o))}}])&&c(r.prototype,o),p&&c(r,p),t;var r,o,p}(n.Component);r.default=M,M.defaultProps={audio:!0,imageSmoothing:!0,onUserMedia:function(){},onUserMediaError:function(){},screenshotFormat:"image/webp",screenshotQuality:.92},M.propTypes=O,M.mountedInstances=[],M.userMediaRequested=!1,e.exports=t.default})?n.apply(t,o):n)||(e.exports=i)},function(t,r){t.exports=e},function(e,r){e.exports=t}])}); |
@@ -1,4 +0,185 @@ | ||
import { configure } from 'enzyme'; | ||
import Adapter from 'enzyme-adapter-react-16'; | ||
// For a detailed explanation regarding each configuration property, visit: | ||
// https://jestjs.io/docs/en/configuration.html | ||
configure({ adapter: new Adapter() }); | ||
module.exports = { | ||
// All imported modules in your tests should be mocked automatically | ||
// automock: false, | ||
// Stop running tests after `n` failures | ||
// bail: 0, | ||
// Respect "browser" field in package.json when resolving modules | ||
// browser: false, | ||
// The directory where Jest should store its cached dependency information | ||
// cacheDirectory: "/private/var/folders/jz/22xcp9mn67d2y_6s98mzxmx00000gn/T/jest_dx", | ||
// Automatically clear mock calls and instances between every test | ||
clearMocks: true, | ||
// Indicates whether the coverage information should be collected while executing the test | ||
// collectCoverage: false, | ||
// An array of glob patterns indicating a set of files for which coverage information should be collected | ||
// collectCoverageFrom: null, | ||
// The directory where Jest should output its coverage files | ||
coverageDirectory: "coverage", | ||
// An array of regexp pattern strings used to skip coverage collection | ||
// coveragePathIgnorePatterns: [ | ||
// "/node_modules/" | ||
// ], | ||
// A list of reporter names that Jest uses when writing coverage reports | ||
// coverageReporters: [ | ||
// "json", | ||
// "text", | ||
// "lcov", | ||
// "clover" | ||
// ], | ||
// An object that configures minimum threshold enforcement for coverage results | ||
// coverageThreshold: null, | ||
// A path to a custom dependency extractor | ||
// dependencyExtractor: null, | ||
// Make calling deprecated APIs throw helpful error messages | ||
// errorOnDeprecated: false, | ||
// Force coverage collection from ignored files using an array of glob patterns | ||
// forceCoverageMatch: [], | ||
// A path to a module which exports an async function that is triggered once before all test suites | ||
// globalSetup: null, | ||
// A path to a module which exports an async function that is triggered once after all test suites | ||
// globalTeardown: null, | ||
// A set of global variables that need to be available in all test environments | ||
// globals: {}, | ||
// An array of directory names to be searched recursively up from the requiring module's location | ||
// moduleDirectories: [ | ||
// "node_modules" | ||
// ], | ||
// An array of file extensions your modules use | ||
// moduleFileExtensions: [ | ||
// "js", | ||
// "json", | ||
// "jsx", | ||
// "ts", | ||
// "tsx", | ||
// "node" | ||
// ], | ||
// A map from regular expressions to module names that allow to stub out resources with a single module | ||
// moduleNameMapper: {}, | ||
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader | ||
// modulePathIgnorePatterns: [], | ||
// Activates notifications for test results | ||
// notify: false, | ||
// An enum that specifies notification mode. Requires { notify: true } | ||
// notifyMode: "failure-change", | ||
// A preset that is used as a base for Jest's configuration | ||
// preset: null, | ||
// Run tests from one or more projects | ||
// projects: null, | ||
// Use this configuration option to add custom reporters to Jest | ||
// reporters: undefined, | ||
// Automatically reset mock state between every test | ||
// resetMocks: false, | ||
// Reset the module registry before running each individual test | ||
// resetModules: false, | ||
// A path to a custom resolver | ||
// resolver: null, | ||
// Automatically restore mock state between every test | ||
// restoreMocks: false, | ||
// The root directory that Jest should scan for tests and modules within | ||
// rootDir: null, | ||
// A list of paths to directories that Jest should use to search for files in | ||
// roots: [ | ||
// "<rootDir>" | ||
// ], | ||
// Allows you to use a custom runner instead of Jest's default test runner | ||
// runner: "jest-runner", | ||
// The paths to modules that run some code to configure or set up the testing environment before each test | ||
// setupFiles: [], | ||
// A list of paths to modules that run some code to configure or set up the testing framework before each test | ||
// setupFilesAfterEnv: [], | ||
// A list of paths to snapshot serializer modules Jest should use for snapshot testing | ||
// snapshotSerializers: [], | ||
// The test environment that will be used for testing | ||
// testEnvironment: "jest-environment-jsdom", | ||
// Options that will be passed to the testEnvironment | ||
// testEnvironmentOptions: {}, | ||
// Adds a location field to test results | ||
// testLocationInResults: false, | ||
// The glob patterns Jest uses to detect test files | ||
// testMatch: [ | ||
// "**/__tests__/**/*.[jt]s?(x)", | ||
// "**/?(*.)+(spec|test).[tj]s?(x)" | ||
// ], | ||
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped | ||
// testPathIgnorePatterns: [ | ||
// "/node_modules/" | ||
// ], | ||
// The regexp pattern or array of patterns that Jest uses to detect test files | ||
// testRegex: [], | ||
// This option allows the use of a custom results processor | ||
// testResultsProcessor: null, | ||
// This option allows use of a custom test runner | ||
// testRunner: "jasmine2", | ||
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href | ||
// testURL: "http://localhost", | ||
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" | ||
// timers: "real", | ||
// A map from regular expressions to paths to transformers | ||
// transform: null, | ||
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation | ||
// transformIgnorePatterns: [ | ||
// "/node_modules/" | ||
// ], | ||
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them | ||
// unmockedModulePathPatterns: undefined, | ||
// Indicates whether each individual test should be reported during the run | ||
// verbose: null, | ||
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode | ||
// watchPathIgnorePatterns: [], | ||
// Whether to use watchman for file crawling | ||
// watchman: true, | ||
}; |
{ | ||
"name": "react-webcam", | ||
"version": "1.1.1", | ||
"version": "2.0.0", | ||
"description": "React webcam component", | ||
"main": "dist/react-webcam.js", | ||
"scripts": { | ||
"prepublish": "npm run build:umd", | ||
"build": "webpack src/react-webcam.js dist/react-webcam.js", | ||
"build:umd": "npm run build && NODE_ENV=production webpack src/react-webcam.js dist/react-webcam.min.js", | ||
"lint": "eslint src" | ||
"prepublish": "npm run build:production", | ||
"build": "NODE_ENV=development webpack-cli src/react-webcam.js", | ||
"build:production": "npm run build && NODE_ENV=production webpack-cli src/react-webcam.js", | ||
"lint": "eslint src", | ||
"test": "jest" | ||
}, | ||
@@ -32,22 +33,25 @@ "repository": { | ||
"devDependencies": { | ||
"babel-core": "^6.25.0", | ||
"babel-eslint": "^7.2.3", | ||
"babel-loader": "^7.1.1", | ||
"babel-plugin-add-module-exports": "^0.2.1", | ||
"@babel/core": "^7.4.5", | ||
"@babel/preset-env": "^7.4.5", | ||
"@babel/preset-react": "^7.0.0", | ||
"babel-eslint": "^10.0.1", | ||
"babel-loader": "^8.0.6", | ||
"babel-plugin-add-module-exports": "^1.0.2", | ||
"babel-plugin-transform-class-properties": "^6.24.1", | ||
"babel-plugin-transform-react-jsx": "^6.24.1", | ||
"babel-preset-env": "^1.6.0", | ||
"babel-preset-react": "^6.24.1", | ||
"eslint": "^3.19.0", | ||
"eslint-config-airbnb": "^15.0.2", | ||
"eslint-plugin-import": "^2.7.0", | ||
"eslint-plugin-jsx-a11y": "^5.1.1", | ||
"eslint-plugin-react": "^7.1.0", | ||
"eslint": "^5.16.0", | ||
"eslint-config-airbnb": "^17.1.0", | ||
"eslint-plugin-import": "^2.17.3", | ||
"eslint-plugin-jest": "^22.6.4", | ||
"eslint-plugin-jsx-a11y": "^6.2.1", | ||
"eslint-plugin-react": "^7.13.0", | ||
"jest": "^24.8.0", | ||
"react": "^16.3.1", | ||
"react-dom": "^16.3.1", | ||
"webpack": "^2.5.1" | ||
"react-test-renderer": "^16.8.6", | ||
"webpack": "^4.32.2", | ||
"webpack-cli": "^3.3.2" | ||
}, | ||
"dependencies": { | ||
"prop-types": "^15.5.8" | ||
"prop-types": "^15.7.2" | ||
} | ||
} |
# react-webcam | ||
[![npm](https://img.shields.io/npm/dw/react-webcam.svg)](https://www.npmjs.com/package/react-webcam) | ||
[![Build Status][build-badge]][build] | ||
![downloads][downloads-badge] | ||
@@ -37,17 +38,15 @@ <img src="Logotype primary.png" width="70%" height="70%" /> | ||
The props here are specific to this component but one can pass any prop to the underlying video tag eg `className` or `style` | ||
| prop | type | default | notes | | ||
| ----------------- | -------- | ------------ | --------------------------------------------------------------------------------------- | | ||
| className | string | '' | CSS class of video element | | ||
| audio | boolean | true | enable/disable audio | | ||
| height | number | 480 | height of video element | | ||
| width | number | 640 | width of video element | | ||
| audioConstraints | object | | MediaStreamConstraint(s) for the audio | | ||
| imageSmoothing | boolean | true | pixel smoothing of the screenshot taken å| | ||
| minScreenshotHeight | number | | min height of screenshot | | ||
| minScreenshotWidth | number | | min width of screenshot | | ||
| minScreenshotHeight | number | | min height of screenshot | | ||
| style | object | | style prop passed to video element | | ||
| screenshotFormat | string | 'image/webp' | format of screenshot | | ||
| imageSmoothing | boolean | true | pixel smoothing of the screenshot taken | | ||
| onUserMedia | function | noop | callback for when component receives a media stream | | ||
| onUserMediaError | function | noop | callback for when component can't receive a media stream with MediaStreamError param | | ||
| screenshotFormat | string | 'image/webp' | format of screenshot | | ||
| screenshotQuality | number | 0.92 | quality of screenshot(0 to 1) | | ||
| audioConstraints | object | | MediaStreamConstraint(s) for the audio | | ||
| videoConstraints | object | | MediaStreamConstraints(s) for the video | | ||
@@ -80,6 +79,6 @@ | ||
audio={false} | ||
height={350} | ||
height={720} | ||
ref={this.setRef} | ||
screenshotFormat="image/jpeg" | ||
width={350} | ||
width={1280} | ||
videoConstraints={videoConstraints} | ||
@@ -126,5 +125,5 @@ /> | ||
## Using in iframes | ||
## Using within an iframe | ||
The Webcam component will fail to load when used inside cross-origin iframes in newer version of Chrome (> 64). In order to overcome this security restriction a special `allow` attribute needs to be added to the iframe tag specifying `microphone` and `camera` as the required permissions like in the below example: | ||
The Webcam component will fail to load when used inside a cross-origin iframe in newer version of Chrome (> 64). In order to overcome this security restriction a special `allow` attribute needs to be added to the iframe tag specifying `microphone` and `camera` as the required permissions like in the below example: | ||
@@ -139,4 +138,4 @@ ``` | ||
## Credits | ||
Many thanks to @cezary for his work on this component. | ||
[build-badge]: https://img.shields.io/travis/com/mozmorris/react-webcam.svg?style=flat-square | ||
[build]: https://travis-ci.com/mozmorris/react-webcam | ||
[downloads-badge]: https://img.shields.io/npm/dw/react-webcam.svg?style=flat-square |
@@ -1,26 +0,3 @@ | ||
"use strict"; | ||
var webpack = require("webpack"); | ||
var plugins = [ | ||
new webpack.EnvironmentPlugin({ | ||
NODE_ENV: "development", | ||
}), | ||
]; | ||
if (process.env.NODE_ENV === "production") { | ||
plugins.push( | ||
new webpack.optimize.UglifyJsPlugin({ | ||
compressor: { | ||
screw_ie8: true, | ||
}, | ||
sourceMap: true, | ||
}), | ||
new webpack.LoaderOptionsPlugin({ | ||
minimize: true, | ||
}), | ||
); | ||
} | ||
module.exports = { | ||
mode: process.env.NODE_ENV, | ||
externals: [ | ||
@@ -32,3 +9,3 @@ { | ||
commonjs: "react", | ||
amd: "react", | ||
amd: "react" | ||
}, | ||
@@ -39,3 +16,3 @@ "react-dom": { | ||
commonjs: "react-dom", | ||
amd: "react-dom", | ||
amd: "react-dom" | ||
}, | ||
@@ -46,5 +23,5 @@ "prop-types": { | ||
commonjs: "prop-types", | ||
amd: "prop-types", | ||
}, | ||
}, | ||
amd: "prop-types" | ||
} | ||
} | ||
], | ||
@@ -55,11 +32,14 @@ module: { | ||
test: /\.js$/, | ||
use: "babel-loader", | ||
}, | ||
], | ||
use: "babel-loader" | ||
} | ||
] | ||
}, | ||
output: { | ||
library: "Webcam", | ||
libraryTarget: "umd", | ||
}, | ||
plugins: plugins, | ||
libraryTarget: 'umd', | ||
filename: | ||
process.env.NODE_ENV === "production" | ||
? "react-webcam.min.js" | ||
: "react-webcam.js" | ||
} | ||
}; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
114434
19
347
138
4
Updatedprop-types@^15.7.2