@theforce/react
Version:
React library for TheForce hand tracking
94 lines (91 loc) • 3.1 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
HandTrackerProvider: () => HandTrackerProvider,
useHandTracker: () => useHandTracker
});
module.exports = __toCommonJS(src_exports);
// src/hand-tracker-provider.tsx
var import_react = require("react");
var import_core = require("@theforce/core");
var import_jsx_runtime = require("react/jsx-runtime");
var HandTrackerContext = (0, import_react.createContext)(null);
var HandTrackerProvider = ({
children,
config,
debug
}) => {
const [handLandmarks, setHandLandmarks] = (0, import_react.useState)([]);
const [isTracking, setIsTracking] = (0, import_react.useState)(false);
const trackerRef = (0, import_react.useRef)(null);
const initialize = (0, import_react.useCallback)(
async (customConfig) => {
if (isTracking)
return;
while (!window.Hands) {
console.log("Waiting for MediaPipe Hands to load...");
await new Promise((resolve) => setTimeout(resolve, 100));
}
const finalConfig = { ...config, ...customConfig, debug };
trackerRef.current = new import_core.HandTracker(finalConfig);
trackerRef.current.onResults((results) => {
setHandLandmarks(results.multiHandLandmarks || []);
});
await trackerRef.current.start();
setIsTracking(true);
},
[config, isTracking, debug]
);
const stop = (0, import_react.useCallback)(async () => {
if (!trackerRef.current || !isTracking)
return;
await trackerRef.current.stop();
trackerRef.current = null;
setIsTracking(false);
setHandLandmarks([]);
}, [isTracking]);
(0, import_react.useEffect)(() => {
return () => {
if (trackerRef.current) {
trackerRef.current.stop();
}
};
}, []);
const value = {
handLandmarks,
initialize,
stop,
isTracking
};
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HandTrackerContext.Provider, { value, children });
};
var useHandTracker = () => {
const context = (0, import_react.useContext)(HandTrackerContext);
if (!context) {
throw new Error("useHandTracker must be used within a HandTrackerProvider");
}
return context;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
HandTrackerProvider,
useHandTracker
});