@capgo/capacitor-flash
Version:
Switch the Flashlight / Torch of your device.
100 lines (94 loc) • 3.1 kB
JavaScript
;
var core = require('@capacitor/core');
const CapacitorFlash = core.registerPlugin('CapacitorFlash', {
web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapacitorFlashWeb()),
});
class CapacitorFlashWeb extends core.WebPlugin {
constructor() {
super(...arguments);
this.stream = null;
this.track = null;
this.torchOn = false;
}
async isAvailable() {
var _a, _b;
try {
if (!((_a = navigator.mediaDevices) === null || _a === void 0 ? void 0 : _a.getUserMedia)) {
return { value: false };
}
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' },
});
const track = stream.getVideoTracks()[0];
const capabilities = (_b = track.getCapabilities) === null || _b === void 0 ? void 0 : _b.call(track);
const hasTorch = (capabilities === null || capabilities === void 0 ? void 0 : capabilities.torch) === true;
// Stop the test stream
track.stop();
return { value: hasTorch };
}
catch (_c) {
return { value: false };
}
}
async switchOn(_options) {
var _a;
try {
// If we already have a stream with torch on, just return
if (this.stream && this.torchOn) {
return;
}
// Get camera stream if we don't have one
if (!this.stream) {
this.stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' },
});
this.track = this.stream.getVideoTracks()[0];
}
// Apply torch constraint
await ((_a = this.track) === null || _a === void 0 ? void 0 : _a.applyConstraints({
advanced: [{ torch: true }],
}));
this.torchOn = true;
}
catch (e) {
throw new Error(`Failed to switch on torch: ${e}`);
}
}
async switchOff() {
try {
if (this.track) {
// Turn off torch by stopping the track
this.track.stop();
this.track = null;
}
if (this.stream) {
this.stream = null;
}
this.torchOn = false;
}
catch (e) {
throw new Error(`Failed to switch off torch: ${e}`);
}
}
async isSwitchedOn() {
return { value: this.torchOn };
}
async toggle() {
if (this.torchOn) {
await this.switchOff();
}
else {
await this.switchOn({});
}
return { value: this.torchOn };
}
async getPluginVersion() {
return { version: 'web' };
}
}
var web = /*#__PURE__*/Object.freeze({
__proto__: null,
CapacitorFlashWeb: CapacitorFlashWeb
});
exports.CapacitorFlash = CapacitorFlash;
//# sourceMappingURL=plugin.cjs.js.map