@coxwave/tap-kit 2.0.1 → 2.0.3

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/dist/react.js CHANGED
@@ -1,3 +1,378 @@
1
- 'use strict';var B=require('react'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var B__default=/*#__PURE__*/_interopDefault(B);var R={"tap-kit:ready":"onReady","tap-kit:error":"onError"},k=Object.keys(R);var X=B__default.default.forwardRef(function({control:t,containerId:i,...s},a){let o=B.useRef(null);B.useImperativeHandle(a,()=>o.current,[]),B.useEffect(()=>{let d=o.current;if(d)return t.setInstance(d),()=>{t.setInstance(null);}},[t.setInstance]),B.useEffect(()=>{let d=o.current;if(!d)return;let l=[];for(let c of k){let p=R[c],_=t.handlers[p];if(_){let f=m=>{let T=m;p==="onError"&&T.detail?.error?_(T.detail.error):p==="onReady"&&_();};d.addEventListener(c,f),l.push({event:c,handler:f});}}return ()=>{for(let{event:c,handler:p}of l)d.removeEventListener(c,p);}},[t]);let{options:r}=t;return jsxRuntime.jsx("tap-kit",{ref:o,"api-key":r.apiKey,"user-id":r.userId,"course-id":r.courseId,"clip-id":r.clipId,"clip-play-head":r.clipPlayHead,language:r.language,"button-id":r.buttonId,"container-id":i,mode:r.mode,debug:r.debug,"tap-url":r.tapUrl,"api-url":r.apiUrl,environment:r.environment,...s})});var W=typeof __DEFAULT_CDN_LOADER_URL__<"u"?__DEFAULT_CDN_LOADER_URL__:"https://files.edutap.ai/tap-sdk/loader.js",Y=4e3,h=500;function Z(){return window?.__TAP_KIT_LOADER_URL__?window.__TAP_KIT_LOADER_URL__:W}function j(){return typeof window<"u"&&!!window.__TAP_KIT_CORE_URL__}function ee(){return window.__TAP_KIT_CORE_URL__||""}function N(n,t,i){let s=Date.now(),a=()=>{if(window.TapKit&&window.TapKitLoaded===true){window.__TAP_KIT_LOADER_LOADED__=true,window.__TAP_KIT_LOADER_LOADING__=void 0,n();return}if(Date.now()-s>i){window.__TAP_KIT_LOADER_LOADING__=void 0,t(new Error(`TapKit loader timeout: SDK not available after ${i}ms`));return}typeof requestIdleCallback<"u"?requestIdleCallback(a,{timeout:h}):setTimeout(a,h);};return a}function H(n=Y){if(window.__TAP_KIT_LOADER_LOADED__&&window.TapKit)return Promise.resolve();if(window.__TAP_KIT_LOADER_LOADING__)return window.__TAP_KIT_LOADER_LOADING__;let t=new Promise((i,s)=>{if(typeof document>"u"){s(new Error("TapKit requires browser environment (document is undefined)"));return}if(j()){if(window.TapKit&&window.TapKitLoaded===true){window.__TAP_KIT_LOADER_LOADED__=true,window.__TAP_KIT_LOADER_LOADING__=void 0,i();return}let d=ee(),l=document.createElement("script");l.src=d,l.async=true,l.onload=()=>{window.TapKit?(window.TapKitLoaded=true,window.__TAP_KIT_LOADER_LOADED__=true,window.__TAP_KIT_LOADER_LOADING__=void 0,i()):(window.__TAP_KIT_LOADER_LOADING__=void 0,s(new Error("TapKit not available after loading local core")));},l.onerror=()=>{window.__TAP_KIT_LOADER_LOADING__=void 0,s(new Error(`Failed to load local TapKit core: ${d}`));},document.head.appendChild(l);return}let a=Z(),o=document.createElement("script");o.src=a,o.async=true,o.onload=()=>{N(i,s,n)();},o.onerror=()=>{window.__TAP_KIT_LOADER_LOADING__=void 0,s(new Error(`Failed to load TapKit CDN loader: ${a}`));};let r=document.querySelector(`script[src="${a}"]`);r?(r.addEventListener("load",()=>{N(i,s,n)();}),r.addEventListener("error",()=>s(new Error(`Failed to load TapKit CDN loader: ${a}`)))):document.head.appendChild(o);});return window.__TAP_KIT_LOADER_LOADING__=t,t}function ne(n){let{onReady:t,onError:i,onTimelineSeek:s,onAlarmFadeIn:a,...o}=n;return o}function te(n){return {onReady:n.onReady,onError:n.onError,onTimelineSeek:n.onTimelineSeek,onAlarmFadeIn:n.onAlarmFadeIn}}function re(n,t){let i=[];return t.onTimelineSeek&&i.push(n.events.onTimelineSeek(t.onTimelineSeek)),t.onAlarmFadeIn&&i.push(n.events.onAlarmFadeIn(t.onAlarmFadeIn)),i}function ie(n){let{onReady:t,onError:i,apiKey:s,userId:a,courseId:o,clipId:r,clipPlayHead:d,language:l,buttonId:c,mode:p="floating",debug:_,tapUrl:f,apiUrl:m,environment:T}=n,u=B.useRef(null),I=B.useRef(null),[E,O]=B.useState(false),[x,M]=B.useState(null),K=B.useRef(true),F=B.useCallback(e=>{I.current=e;},[]),b=B.useCallback(e=>{u.current=e;},[]);B.useEffect(()=>{K.current=true;let e=null;async function D(){try{if(await H(),await customElements.whenDefined("tap-kit"),!K.current||!I.current)return;if(!window.createTapKit)throw new Error("createTapKit not available after loading CDN");if(e=window.createTapKit({apiKey:s,userId:a,courseId:o,clipId:r,clipPlayHead:d,language:l,buttonId:c,mode:p,debug:_,tapUrl:f,apiUrl:m,environment:T}),I.current.appendChild(e),u.current=e,await e.ready,!K.current)return;O(!0),t&&t();}catch(w){let P=w instanceof Error?w:new Error(String(w));K.current&&(M(P),i&&i(P));}}return D(),()=>{K.current=false,e&&(e.remove(),u.current=null),O(false);}},[s,t,i]),B.useEffect(()=>{let e=u.current;!e||!E||(a!==void 0&&(e.userId=a),o!==void 0&&(e.courseId=o),r!==void 0&&(e.clipId=r),d!==void 0&&(e.clipPlayHead=d),l!==void 0&&(e.language=l),c!==void 0&&(e.buttonId=c),p!==void 0&&(e.mode=p),_!==void 0&&(e.debug=_),f!==void 0&&(e.tapUrl=f),m!==void 0&&(e.apiUrl=m),T!==void 0&&(e.environment=T));},[E,a,o,r,d,l,c,p,_,f,m,T]);let C=B.useMemo(()=>ne(n),[n]),L=B.useMemo(()=>te(n),[n]);B.useEffect(()=>{let e=u.current;if(!e||!E)return;let D=re(e,L);return ()=>{for(let w of D)w();}},[E,L]);let G=B.useMemo(()=>({setInstance:b,options:C,handlers:L}),[b,C,L]),V=B.useCallback(()=>{u.current&&u.current.show();},[]),$=B.useCallback(()=>{u.current&&u.current.hide();},[]),q=B.useCallback(e=>{u.current&&u.current.setCourse(e);},[]);return {element:u.current,ref:u,elementRef:F,control:G,isReady:E,error:x,show:V,hide:$,setCourse:q}}
2
- exports.TapKit=X;exports.useTapKit=ie;//# sourceMappingURL=react.js.map
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+ var jsxRuntime = require('react/jsx-runtime');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
+
8
+ var React__default = /*#__PURE__*/_interopDefault(React);
9
+
10
+ // src/react/TapKit.tsx
11
+
12
+ // src/react/types.ts
13
+ var EVENT_HANDLER_MAP = {
14
+ "tap-kit:ready": "onReady",
15
+ "tap-kit:error": "onError"
16
+ };
17
+ var EVENT_NAMES = Object.keys(
18
+ EVENT_HANDLER_MAP
19
+ );
20
+ var TapKit = React__default.default.forwardRef(
21
+ function TapKit2({ control, ...htmlProps }, forwardedRef) {
22
+ const elementRef = React.useRef(null);
23
+ React.useImperativeHandle(
24
+ forwardedRef,
25
+ () => elementRef.current,
26
+ []
27
+ );
28
+ const setElementRef = React.useCallback(
29
+ (element) => {
30
+ elementRef.current = element;
31
+ if (element && control.options.apiKey) {
32
+ element.apiKey = control.options.apiKey;
33
+ }
34
+ control.setInstance(element);
35
+ },
36
+ [control.setInstance, control.options.apiKey]
37
+ );
38
+ const handlersRef = React.useRef(control.handlers);
39
+ handlersRef.current = control.handlers;
40
+ React.useEffect(() => {
41
+ const element = elementRef.current;
42
+ if (!element) return;
43
+ const listeners = [];
44
+ for (const eventName of EVENT_NAMES) {
45
+ const handlerKey = EVENT_HANDLER_MAP[eventName];
46
+ const listener = (e) => {
47
+ const handler = handlersRef.current[handlerKey];
48
+ if (!handler) return;
49
+ const customEvent = e;
50
+ if (handlerKey === "onError" && customEvent.detail?.error) {
51
+ handler(customEvent.detail.error);
52
+ } else if (handlerKey === "onReady") {
53
+ handler();
54
+ }
55
+ };
56
+ element.addEventListener(eventName, listener);
57
+ listeners.push({ event: eventName, handler: listener });
58
+ }
59
+ return () => {
60
+ for (const { event, handler } of listeners) {
61
+ element.removeEventListener(event, handler);
62
+ }
63
+ };
64
+ }, []);
65
+ const { options, isCdnLoaded } = control;
66
+ if (!isCdnLoaded) {
67
+ return null;
68
+ }
69
+ return /* @__PURE__ */ jsxRuntime.jsx(
70
+ "tap-kit",
71
+ {
72
+ ref: setElementRef,
73
+ "user-id": options.userId,
74
+ "course-id": options.courseId,
75
+ "clip-id": options.clipId,
76
+ "clip-play-head": options.clipPlayHead,
77
+ language: options.language,
78
+ "button-id": options.buttonId,
79
+ mode: options.mode,
80
+ debug: options.debug,
81
+ "tap-url": options.tapUrl,
82
+ "api-url": options.apiUrl,
83
+ environment: options.environment,
84
+ ...htmlProps
85
+ }
86
+ );
87
+ }
88
+ );
89
+
90
+ // src/loader.ts
91
+ var DEFAULT_CDN_LOADER_URL = typeof __DEFAULT_CDN_LOADER_URL__ !== "undefined" ? __DEFAULT_CDN_LOADER_URL__ : "https://files.edutap.ai/tap-sdk/loader.js";
92
+ var DEFAULT_TIMEOUT_MS = 4e3;
93
+ var IDLE_CALLBACK_TIMEOUT_MS = 500;
94
+ function getLoaderURL() {
95
+ return window?.__TAP_KIT_LOADER_URL__ ? window.__TAP_KIT_LOADER_URL__ : DEFAULT_CDN_LOADER_URL;
96
+ }
97
+ function isLocalCoreMode() {
98
+ return typeof window !== "undefined" && !!window.__TAP_KIT_CORE_URL__;
99
+ }
100
+ function getLocalCoreURL() {
101
+ return window.__TAP_KIT_CORE_URL__ || "";
102
+ }
103
+ function createSDKChecker(resolve, reject, timeoutMs) {
104
+ const startTime = Date.now();
105
+ const checkSDK = () => {
106
+ if (window.TapKit && window.TapKitLoaded === true) {
107
+ window.__TAP_KIT_LOADER_LOADED__ = true;
108
+ window.__TAP_KIT_LOADER_LOADING__ = void 0;
109
+ resolve();
110
+ return;
111
+ }
112
+ const elapsed = Date.now() - startTime;
113
+ if (elapsed > timeoutMs) {
114
+ window.__TAP_KIT_LOADER_LOADING__ = void 0;
115
+ reject(
116
+ new Error(
117
+ `TapKit loader timeout: SDK not available after ${timeoutMs}ms`
118
+ )
119
+ );
120
+ return;
121
+ }
122
+ if (typeof requestIdleCallback !== "undefined") {
123
+ requestIdleCallback(checkSDK, { timeout: IDLE_CALLBACK_TIMEOUT_MS });
124
+ } else {
125
+ setTimeout(checkSDK, IDLE_CALLBACK_TIMEOUT_MS);
126
+ }
127
+ };
128
+ return checkSDK;
129
+ }
130
+ function loadCDNLoader(timeoutMs = DEFAULT_TIMEOUT_MS) {
131
+ if (window.__TAP_KIT_LOADER_LOADED__ && window.TapKit) {
132
+ return Promise.resolve();
133
+ }
134
+ if (window.__TAP_KIT_LOADER_LOADING__) {
135
+ return window.__TAP_KIT_LOADER_LOADING__;
136
+ }
137
+ const loadingPromise = new Promise((resolve, reject) => {
138
+ if (typeof document === "undefined") {
139
+ reject(
140
+ new Error(
141
+ "TapKit requires browser environment (document is undefined)"
142
+ )
143
+ );
144
+ return;
145
+ }
146
+ if (isLocalCoreMode()) {
147
+ if (window.TapKit && window.TapKitLoaded === true) {
148
+ window.__TAP_KIT_LOADER_LOADED__ = true;
149
+ window.__TAP_KIT_LOADER_LOADING__ = void 0;
150
+ resolve();
151
+ return;
152
+ }
153
+ const coreURL = getLocalCoreURL();
154
+ const script2 = document.createElement("script");
155
+ script2.src = coreURL;
156
+ script2.async = true;
157
+ script2.onload = () => {
158
+ if (window.TapKit) {
159
+ window.TapKitLoaded = true;
160
+ window.__TAP_KIT_LOADER_LOADED__ = true;
161
+ window.__TAP_KIT_LOADER_LOADING__ = void 0;
162
+ resolve();
163
+ } else {
164
+ window.__TAP_KIT_LOADER_LOADING__ = void 0;
165
+ reject(new Error("TapKit not available after loading local core"));
166
+ }
167
+ };
168
+ script2.onerror = () => {
169
+ window.__TAP_KIT_LOADER_LOADING__ = void 0;
170
+ reject(new Error(`Failed to load local TapKit core: ${coreURL}`));
171
+ };
172
+ document.head.appendChild(script2);
173
+ return;
174
+ }
175
+ const loaderURL = getLoaderURL();
176
+ const script = document.createElement("script");
177
+ script.src = loaderURL;
178
+ script.async = true;
179
+ script.onload = () => {
180
+ const checkSDK = createSDKChecker(resolve, reject, timeoutMs);
181
+ checkSDK();
182
+ };
183
+ script.onerror = () => {
184
+ window.__TAP_KIT_LOADER_LOADING__ = void 0;
185
+ reject(new Error(`Failed to load TapKit CDN loader: ${loaderURL}`));
186
+ };
187
+ const existingScript = document.querySelector(`script[src="${loaderURL}"]`);
188
+ if (existingScript) {
189
+ existingScript.addEventListener("load", () => {
190
+ const checkSDK = createSDKChecker(resolve, reject, timeoutMs);
191
+ checkSDK();
192
+ });
193
+ existingScript.addEventListener(
194
+ "error",
195
+ () => reject(new Error(`Failed to load TapKit CDN loader: ${loaderURL}`))
196
+ );
197
+ } else {
198
+ document.head.appendChild(script);
199
+ }
200
+ });
201
+ window.__TAP_KIT_LOADER_LOADING__ = loadingPromise;
202
+ return loadingPromise;
203
+ }
204
+
205
+ // src/react/useTapKit.ts
206
+ function extractHandlers(options) {
207
+ return {
208
+ onReady: options.onReady,
209
+ onError: options.onError,
210
+ onTimelineSeek: options.onTimelineSeek,
211
+ onAlarmFadeIn: options.onAlarmFadeIn
212
+ };
213
+ }
214
+ function useTapKit(options) {
215
+ const elementRef = React.useRef(null);
216
+ const [isCdnLoaded, setIsCdnLoaded] = React.useState(false);
217
+ const [isReady, setIsReady] = React.useState(false);
218
+ const [error, setError] = React.useState(null);
219
+ const handlersRef = React.useRef(extractHandlers(options));
220
+ handlersRef.current = extractHandlers(options);
221
+ React.useEffect(() => {
222
+ loadCDNLoader().then(() => {
223
+ setIsCdnLoaded(true);
224
+ }).catch((err) => {
225
+ const loadError = err instanceof Error ? err : new Error("Failed to load TapKit CDN");
226
+ setError(loadError);
227
+ handlersRef.current.onError?.(loadError);
228
+ });
229
+ }, []);
230
+ const setInstance = React.useCallback((instance) => {
231
+ elementRef.current = instance;
232
+ if (!instance) {
233
+ setIsReady(false);
234
+ return;
235
+ }
236
+ const handleReady = () => {
237
+ setIsReady(true);
238
+ handlersRef.current.onReady?.();
239
+ };
240
+ const handleError = (e) => {
241
+ const customEvent = e;
242
+ const err = customEvent.detail?.error ?? new Error("Unknown error");
243
+ setError(err);
244
+ handlersRef.current.onError?.(err);
245
+ };
246
+ instance.addEventListener("tap-kit:ready", handleReady);
247
+ instance.addEventListener("tap-kit:error", handleError);
248
+ if (instance.isInitialized) {
249
+ setIsReady(true);
250
+ }
251
+ const setupEventHandlers = () => {
252
+ if (instance.events && typeof instance.events.onTimelineSeek === "function") {
253
+ if (handlersRef.current.onTimelineSeek) {
254
+ instance.events.onTimelineSeek(handlersRef.current.onTimelineSeek);
255
+ }
256
+ if (handlersRef.current.onAlarmFadeIn) {
257
+ instance.events.onAlarmFadeIn(handlersRef.current.onAlarmFadeIn);
258
+ }
259
+ }
260
+ };
261
+ if (instance.ready && typeof instance.ready.then === "function") {
262
+ instance.ready.then(setupEventHandlers).catch(() => {
263
+ });
264
+ } else if (instance.isInitialized) {
265
+ setupEventHandlers();
266
+ } else {
267
+ instance.addEventListener("tap-kit:ready", setupEventHandlers, {
268
+ once: true
269
+ });
270
+ }
271
+ }, []);
272
+ const configOptions = React.useMemo(
273
+ () => ({
274
+ apiKey: options.apiKey,
275
+ userId: options.userId,
276
+ courseId: options.courseId,
277
+ clipId: options.clipId,
278
+ clipPlayHead: options.clipPlayHead,
279
+ language: options.language,
280
+ buttonId: options.buttonId,
281
+ mode: options.mode,
282
+ debug: options.debug,
283
+ tapUrl: options.tapUrl,
284
+ apiUrl: options.apiUrl,
285
+ environment: options.environment
286
+ }),
287
+ [
288
+ options.apiKey,
289
+ options.userId,
290
+ options.courseId,
291
+ options.clipId,
292
+ options.clipPlayHead,
293
+ options.language,
294
+ options.buttonId,
295
+ options.mode,
296
+ options.debug,
297
+ options.tapUrl,
298
+ options.apiUrl,
299
+ options.environment
300
+ ]
301
+ );
302
+ const handlers = React.useMemo(
303
+ () => ({
304
+ onReady: handlersRef.current.onReady,
305
+ onError: handlersRef.current.onError,
306
+ onTimelineSeek: handlersRef.current.onTimelineSeek,
307
+ onAlarmFadeIn: handlersRef.current.onAlarmFadeIn
308
+ }),
309
+ // Empty deps - handlers are accessed via ref which is always up-to-date
310
+ []
311
+ );
312
+ const control = React.useMemo(
313
+ () => ({
314
+ setInstance,
315
+ options: configOptions,
316
+ handlers,
317
+ isCdnLoaded
318
+ }),
319
+ [setInstance, configOptions, handlers, isCdnLoaded]
320
+ );
321
+ const show = React.useCallback(() => {
322
+ if (!elementRef.current) {
323
+ console.warn("[useTapKit] Cannot show: element not mounted");
324
+ return;
325
+ }
326
+ elementRef.current.show();
327
+ }, []);
328
+ const hide = React.useCallback(() => {
329
+ if (!elementRef.current) {
330
+ console.warn("[useTapKit] Cannot hide: element not mounted");
331
+ return;
332
+ }
333
+ elementRef.current.hide();
334
+ }, []);
335
+ const setCourse = React.useCallback(
336
+ (course) => {
337
+ if (!elementRef.current) {
338
+ console.warn("[useTapKit] Cannot setCourse: element not mounted");
339
+ return;
340
+ }
341
+ elementRef.current.setCourse(course);
342
+ },
343
+ []
344
+ );
345
+ const video = React.useMemo(
346
+ () => ({
347
+ bind: (adapter, clipId) => {
348
+ if (!elementRef.current) {
349
+ console.warn("[useTapKit] Cannot bind video: element not mounted");
350
+ return;
351
+ }
352
+ if (!elementRef.current.video) {
353
+ console.warn("[useTapKit] Cannot bind video: video controller not available");
354
+ return;
355
+ }
356
+ elementRef.current.video.bind(adapter, clipId);
357
+ },
358
+ unbind: () => {
359
+ elementRef.current?.video?.unbind();
360
+ }
361
+ }),
362
+ []
363
+ );
364
+ return {
365
+ control,
366
+ isReady,
367
+ error,
368
+ show,
369
+ hide,
370
+ setCourse,
371
+ video
372
+ };
373
+ }
374
+
375
+ exports.TapKit = TapKit;
376
+ exports.useTapKit = useTapKit;
377
+ //# sourceMappingURL=react.js.map
3
378
  //# sourceMappingURL=react.js.map
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react/types.ts","../src/react/TapKit.tsx","../src/loader.ts","../src/react/useTapKit.ts"],"names":["EVENT_HANDLER_MAP","EVENT_NAMES","TapKit","React","control","containerId","htmlProps","forwardedRef","elementRef","useRef","useImperativeHandle","useEffect","element","listeners","eventName","handlerKey","handler","listener","e","customEvent","event","options","jsx","DEFAULT_CDN_LOADER_URL","DEFAULT_TIMEOUT_MS","IDLE_CALLBACK_TIMEOUT_MS","getLoaderURL","isLocalCoreMode","getLocalCoreURL","createSDKChecker","resolve","reject","timeoutMs","startTime","checkSDK","loadCDNLoader","loadingPromise","coreURL","script","loaderURL","existingScript","extractConfig","onReady","onError","onTimelineSeek","onAlarmFadeIn","config","extractHandlers","createEventBindings","handlers","unsubscribers","useTapKit","apiKey","userId","courseId","clipId","clipPlayHead","language","buttonId","mode","debug","tapUrl","apiUrl","environment","containerRef","isReady","setIsReady","useState","error","setError","isMountedRef","setContainerRef","useCallback","node","setInstance","instance","init","err","configOptions","useMemo","unsubscribe","show","hide","setCourse","course"],"mappings":"4LAkFO,IAAMA,CAAAA,CAAoB,CAC/B,eAAA,CAAiB,UACjB,eAAA,CAAiB,SACnB,CAAA,CAOaC,CAAAA,CAAc,MAAA,CAAO,IAAA,CAChCD,CACF,CAAA,CCYO,IAAME,CAAAA,CAASC,kBAAAA,CAAM,UAAA,CAC1B,SAAgB,CAAE,OAAA,CAAAC,CAAAA,CAAS,WAAA,CAAAC,CAAAA,CAAa,GAAGC,CAAU,CAAA,CAAGC,CAAAA,CAAc,CACpE,IAAMC,CAAAA,CAAaC,QAAAA,CAA6B,IAAI,CAAA,CAGpDC,qBAAAA,CACEH,CAAAA,CACA,IAAMC,CAAAA,CAAW,OAAA,CACjB,EACF,CAAA,CAGAG,WAAAA,CAAU,IAAM,CACd,IAAMC,CAAAA,CAAUJ,CAAAA,CAAW,OAAA,CAC3B,GAAKI,CAAAA,CAEL,OAAAR,CAAAA,CAAQ,YAAYQ,CAAO,CAAA,CAEpB,IAAM,CACXR,CAAAA,CAAQ,WAAA,CAAY,IAAI,EAC1B,CACF,CAAA,CA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+B,CAAAA,IAAe9B,CAAAA,CACxB8B,CAAAA,GAEJ,CACF,CAAA,CAAG,CAACf,EAAShB,CAAQ,CAAC,CAAA,CAGtB,IAAM7C,CAAAA,CAAU2E,SAAAA,CACd,KAAO,CACL,WAAA,CAAAL,CAAAA,CACA,OAAA,CAASI,CAAAA,CACT,QAAA,CAAA7B,CACF,CAAA,CAAA,CACA,CAACyB,EAAaI,CAAAA,CAAe7B,CAAQ,CACvC,CAAA,CAGMgC,CAAAA,CAAOT,aAAAA,CAAY,IAAM,CACxBhE,CAAAA,CAAW,OAAA,EAIhBA,CAAAA,CAAW,OAAA,CAAQ,IAAA,GACrB,CAAA,CAAG,EAAE,CAAA,CAEC0E,CAAAA,CAAOV,aAAAA,CAAY,IAAM,CACxBhE,CAAAA,CAAW,OAAA,EAIhBA,CAAAA,CAAW,OAAA,CAAQ,IAAA,GACrB,CAAA,CAAG,EAAE,CAAA,CAEC2E,CAAAA,CAAYX,cACfY,CAAAA,EAKK,CACC5E,CAAAA,CAAW,OAAA,EAIhBA,CAAAA,CAAW,OAAA,CAAQ,SAAA,CAAU4E,CAAM,EACrC,CAAA,CACA,EACF,CAAA,CAEA,OAAO,CACL,OAAA,CAAS5E,EAAW,OAAA,CACpB,GAAA,CAAKA,CAAAA,CACL,UAAA,CAAY+D,CAAAA,CACZ,OAAA,CAAAnE,CAAAA,CACA,OAAA,CAAA6D,CAAAA,CACA,KAAA,CAAAG,CAAAA,CACA,IAAA,CAAAa,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CACF,CACF","file":"react.js","sourcesContent":["/**\n * React-specific type definitions for TapKit\n *\n * Defines event handler types and control patterns for React integration.\n */\n\nimport type { TapKitElement } from \"@coxwave/tap-kit-types\";\n\n/**\n * Event handler type definitions for TapKit Web Component\n *\n * Maps CustomEvent types to React callback signatures.\n */\nexport interface TapKitEventHandlers {\n /**\n * Called when TapKit SDK is ready\n * @example onReady={() => console.log('TapKit ready!')}\n */\n onReady?: () => void;\n\n /**\n * Called when initialization or runtime error occurs\n * @example onError={(error) => console.error('TapKit error:', error)}\n */\n onError?: (error: Error) => void;\n\n /**\n * Called when timeline seek event occurs\n * @example onTimelineSeek={(clipPlayHead, clipId) => console.log('Seek:', clipPlayHead)}\n */\n onTimelineSeek?: (clipPlayHead: number, clipId: string) => void;\n\n /**\n * Called when alarm fade-in occurs\n * @example onAlarmFadeIn={(messageInfo) => console.log('Alarm:', messageInfo)}\n */\n onAlarmFadeIn?: (messageInfo: unknown) => void;\n}\n\n/**\n * Control object pattern for managing TapKit instance\n *\n * Separates instance management (setInstance) from configuration (options)\n * and event handling (handlers). Inspired by ChatKit's control pattern.\n *\n * @example\n * ```tsx\n * const tapkit = useTapKit({ apiKey: 'key', onReady: () => {} });\n * <TapKit control={tapkit.control} />\n * ```\n */\nexport interface TapKitControl<T> {\n /**\n * Set the TapKit element instance reference\n *\n * Called by TapKit component to register the element instance.\n * Enables imperative control via useTapKit methods.\n */\n setInstance: (instance: TapKitElement | null) => void;\n\n /**\n * Configuration options (non-function values)\n *\n * All options except event handlers.\n */\n options: T;\n\n /**\n * Event handler callbacks (function values)\n *\n * Separated from options for easier event listener management.\n */\n handlers: TapKitEventHandlers;\n}\n\n/**\n * Map of TapKit event names to their handler keys\n *\n * Used for automatic event listener binding in TapKit component.\n *\n * @internal\n */\nexport const EVENT_HANDLER_MAP = {\n \"tap-kit:ready\": \"onReady\",\n \"tap-kit:error\": \"onError\",\n} as const;\n\n/**\n * List of TapKit event names\n *\n * @internal\n */\nexport const EVENT_NAMES = Object.keys(\n EVENT_HANDLER_MAP,\n) as (keyof typeof EVENT_HANDLER_MAP)[];\n","/**\n * TapKit React Component\n *\n * Declarative React wrapper for <tap-kit> Web Component.\n * Use this with useTapKit hook for a clean separation of control and rendering.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { TapKit, useTapKit } from '@coxwave/tap-kit/react';\n *\n * function MyApp() {\n * const tapkit = useTapKit({\n * apiKey: 'your-key',\n * userId: 'user-123',\n * courseId: 'course-456',\n * clipId: 'clip-789',\n * onReady: () => console.log('TapKit ready!'),\n * onError: (error) => console.error('Error:', error),\n * });\n *\n * return (\n * <div>\n * <button onClick={tapkit.show} disabled={!tapkit.isReady}>\n * Show Chat\n * </button>\n * <TapKit control={tapkit.control} style={{ height: '600px' }} />\n * </div>\n * );\n * }\n * ```\n *\n * **Note for Next.js App Router users:**\n * Make sure to add 'use client' at the top of your component file.\n *\n * @see https://edutap-ai-docs.vercel.app/docs/guides/react\n */\n\nimport type { TapKitElement } from \"@coxwave/tap-kit-types\";\nimport React, { useEffect, useImperativeHandle, useRef } from \"react\";\nimport type { TapKitControl } from \"./types\";\nimport { EVENT_HANDLER_MAP, EVENT_NAMES } from \"./types\";\n\n/**\n * Props for TapKit React component\n */\nexport interface TapKitProps\n extends Omit<\n React.HTMLAttributes<TapKitElement>,\n \"children\" | \"dangerouslySetInnerHTML\"\n > {\n /**\n * Control object from useTapKit hook\n *\n * Provides instance management, configuration, and event handlers.\n */\n control: TapKitControl<any>;\n\n /**\n * Custom container element ID (optional)\n *\n * If provided, TapKit will use this element as container.\n */\n containerId?: string;\n}\n\n// Augment JSX namespace to support <tap-kit> custom element\ndeclare global {\n namespace JSX {\n interface IntrinsicElements {\n \"tap-kit\": React.DetailedHTMLProps<\n React.HTMLAttributes<TapKitElement>,\n TapKitElement\n > & {\n \"api-key\"?: string;\n \"user-id\"?: string;\n \"course-id\"?: string;\n \"clip-id\"?: string;\n \"clip-play-head\"?: number;\n language?: \"ko\" | \"en\";\n \"button-id\"?: string;\n \"container-id\"?: string;\n mode?: \"inline\" | \"floating\" | \"sidebar\";\n debug?: boolean;\n \"tap-url\"?: string;\n \"api-url\"?: string;\n environment?: \"dev\" | \"prod\" | \"staging\" | \"demo\";\n };\n }\n }\n}\n\n/**\n * TapKit React Component\n *\n * Renders <tap-kit> Web Component with React integration.\n * Automatically manages instance lifecycle and event listeners.\n *\n * **Ref Access**: The forwarded ref provides direct access to the TapKitElement:\n * ```tsx\n * const tapkitRef = useRef<TapKitElement>(null);\n * <TapKit ref={tapkitRef} control={...} />\n * // tapkitRef.current?.show()\n * ```\n */\nexport const TapKit = React.forwardRef<TapKitElement, TapKitProps>(\n function TapKit({ control, containerId, ...htmlProps }, forwardedRef) {\n const elementRef = useRef<TapKitElement | null>(null);\n\n // Forward TapKitElement to parent\n useImperativeHandle(\n forwardedRef,\n () => elementRef.current as TapKitElement,\n [],\n );\n\n // Register element instance with control\n useEffect(() => {\n const element = elementRef.current;\n if (!element) return;\n\n control.setInstance(element);\n\n return () => {\n control.setInstance(null);\n };\n }, [control.setInstance]);\n\n // Register event listeners\n useEffect(() => {\n const element = elementRef.current;\n if (!element) return;\n\n const listeners: Array<{\n event: string;\n handler: EventListener;\n }> = [];\n\n // Bind CustomEvent listeners (tap-kit:ready, tap-kit:error)\n for (const eventName of EVENT_NAMES) {\n const handlerKey =\n EVENT_HANDLER_MAP[eventName as keyof typeof EVENT_HANDLER_MAP];\n const handler = control.handlers[handlerKey];\n\n if (handler) {\n const listener = (e: Event) => {\n const customEvent = e as CustomEvent;\n if (handlerKey === \"onError\" && customEvent.detail?.error) {\n // onError receives error directly\n // biome-ignore lint/suspicious/noExplicitAny: Handler type is validated at runtime\n (handler as any)(customEvent.detail.error);\n } else if (handlerKey === \"onReady\") {\n // onReady receives no arguments\n // biome-ignore lint/suspicious/noExplicitAny: Handler type is validated at runtime\n (handler as any)();\n }\n };\n\n element.addEventListener(eventName, listener);\n listeners.push({ event: eventName, handler: listener });\n }\n }\n\n return () => {\n // Cleanup all event listeners\n for (const { event, handler } of listeners) {\n element.removeEventListener(event, handler);\n }\n };\n }, [control]);\n\n const { options } = control;\n\n // Render <tap-kit> Web Component directly\n return (\n <tap-kit\n ref={elementRef}\n api-key={options.apiKey}\n user-id={options.userId}\n course-id={options.courseId}\n clip-id={options.clipId}\n clip-play-head={options.clipPlayHead}\n language={options.language}\n button-id={options.buttonId}\n container-id={containerId}\n mode={options.mode}\n debug={options.debug}\n tap-url={options.tapUrl}\n api-url={options.apiUrl}\n environment={options.environment}\n {...htmlProps}\n />\n );\n },\n);\n","/**\n * CDN loader for TapKit\n * Dynamically loads the TapKit SDK from CDN\n *\n * For local testing, you can override the loader URL:\n * window.__TAP_KIT_LOADER_URL__ = '/tap-kit-core/loader.js';\n *\n * For local development (bypass loader, load IIFE directly):\n * window.__TAP_KIT_CORE_URL__ = '/packages/tap-kit-core/dist/index.global.js';\n */\n\n// Build-time constant injected by tsup define\ndeclare const __DEFAULT_CDN_LOADER_URL__: string;\n\nconst DEFAULT_CDN_LOADER_URL =\n typeof __DEFAULT_CDN_LOADER_URL__ !== \"undefined\"\n ? __DEFAULT_CDN_LOADER_URL__\n : \"https://files.edutap.ai/tap-sdk/loader.js\";\nconst DEFAULT_TIMEOUT_MS = 4000; // 4 seconds total timeout\nconst IDLE_CALLBACK_TIMEOUT_MS = 500; // 500ms for requestIdleCallback\n\n/**\n * Get the loader URL from window override or default CDN\n */\nfunction getLoaderURL(): string {\n return window?.__TAP_KIT_LOADER_URL__\n ? window.__TAP_KIT_LOADER_URL__\n : DEFAULT_CDN_LOADER_URL;\n}\n\n/**\n * Check if local core mode is enabled\n * When __TAP_KIT_CORE_URL__ is set, directly load the IIFE bundle\n * This bypasses the loader.js and loads tap-kit-core directly\n */\nfunction isLocalCoreMode(): boolean {\n return typeof window !== \"undefined\" && !!window.__TAP_KIT_CORE_URL__;\n}\n\n/**\n * Get the local core URL\n */\nfunction getLocalCoreURL(): string {\n return window.__TAP_KIT_CORE_URL__ || \"\";\n}\n\n/**\n * Creates a SDK checker function with timeout and retry logic\n * Uses requestIdleCallback to avoid blocking browser rendering\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n * @param timeoutMs - Maximum time to wait for SDK to load (milliseconds)\n * @returns Checker function to be called repeatedly\n */\nfunction createSDKChecker(\n resolve: (value: void | PromiseLike<void>) => void,\n reject: (reason?: unknown) => void,\n timeoutMs: number,\n): () => void {\n const startTime = Date.now();\n\n const checkSDK = (): void => {\n // Check if real TapKit is loaded (not just stub)\n // Stub has TapKitLoaded flag set to true by loader.js after real SDK loads\n if (window.TapKit && window.TapKitLoaded === true) {\n window.__TAP_KIT_LOADER_LOADED__ = true;\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n resolve();\n return;\n }\n\n const elapsed = Date.now() - startTime;\n\n // Check if exceeded timeout\n if (elapsed > timeoutMs) {\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n reject(\n new Error(\n `TapKit loader timeout: SDK not available after ${timeoutMs}ms`,\n ),\n );\n return;\n }\n\n // Use requestIdleCallback for better performance\n // Falls back to setTimeout if not available\n if (typeof requestIdleCallback !== \"undefined\") {\n requestIdleCallback(checkSDK, { timeout: IDLE_CALLBACK_TIMEOUT_MS });\n } else {\n setTimeout(checkSDK, IDLE_CALLBACK_TIMEOUT_MS);\n }\n };\n\n return checkSDK;\n}\n\n/**\n * Loads the CDN loader script\n * The loader will then fetch versions.json and load the appropriate SDK version\n *\n * If __TAP_KIT_CORE_URL__ is set, bypasses loader and loads IIFE directly\n *\n * @param timeoutMs - Maximum time to wait for SDK to load (default: 4000ms)\n * @returns Promise that resolves when SDK is loaded\n * @throws {Error} If loader fails to load or times out\n */\nexport function loadCDNLoader(\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n): Promise<void> {\n // If already loaded, return immediately\n if (window.__TAP_KIT_LOADER_LOADED__ && window.TapKit) {\n return Promise.resolve();\n }\n\n // If currently loading, return the existing promise\n if (window.__TAP_KIT_LOADER_LOADING__) {\n return window.__TAP_KIT_LOADER_LOADING__;\n }\n\n // Create loading promise\n const loadingPromise = new Promise<void>((resolve, reject) => {\n if (typeof document === \"undefined\") {\n reject(\n new Error(\n \"TapKit requires browser environment (document is undefined)\",\n ),\n );\n return;\n }\n\n // Local core mode: Load IIFE directly\n if (isLocalCoreMode()) {\n // Check if TapKit is already loaded (from other pages in playground)\n if (window.TapKit && window.TapKitLoaded === true) {\n window.__TAP_KIT_LOADER_LOADED__ = true;\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n resolve();\n return;\n }\n\n const coreURL = getLocalCoreURL();\n\n const script = document.createElement(\"script\");\n script.src = coreURL;\n script.async = true;\n\n script.onload = () => {\n // IIFE directly sets window.TapKit\n // Set the loaded flag manually since we bypass loader.js\n if (window.TapKit) {\n window.TapKitLoaded = true;\n window.__TAP_KIT_LOADER_LOADED__ = true;\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n resolve();\n } else {\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n reject(new Error(\"TapKit not available after loading local core\"));\n }\n };\n\n script.onerror = () => {\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n reject(new Error(`Failed to load local TapKit core: ${coreURL}`));\n };\n\n document.head.appendChild(script);\n return;\n }\n\n // CDN mode: Load loader.js\n const loaderURL = getLoaderURL();\n const script = document.createElement(\"script\");\n script.src = loaderURL;\n script.async = true;\n\n script.onload = () => {\n // The loader script will load the actual SDK\n // We need to wait a bit for the loader to fetch and load the SDK\n const checkSDK = createSDKChecker(resolve, reject, timeoutMs);\n checkSDK();\n };\n\n script.onerror = () => {\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n reject(new Error(`Failed to load TapKit CDN loader: ${loaderURL}`));\n };\n\n // Check if script already exists\n const existingScript = document.querySelector(`script[src=\"${loaderURL}\"]`);\n\n if (existingScript) {\n // Script already added but not yet loaded\n existingScript.addEventListener(\"load\", () => {\n const checkSDK = createSDKChecker(resolve, reject, timeoutMs);\n checkSDK();\n });\n existingScript.addEventListener(\"error\", () =>\n reject(new Error(`Failed to load TapKit CDN loader: ${loaderURL}`)),\n );\n } else {\n document.head.appendChild(script);\n }\n });\n\n window.__TAP_KIT_LOADER_LOADING__ = loadingPromise;\n return loadingPromise;\n}\n","/**\n * useTapKit Hook - Advanced imperative control of TapKit Web Component\n *\n * This hook provides direct access to the TapKitElement instance and full\n * control over its lifecycle. Use this when you need:\n * - Direct element manipulation\n * - Custom rendering logic\n * - Imperative control over Web Component behavior\n *\n * For most use cases, prefer the `<TapKit />` component which provides a\n * simpler declarative API.\n *\n * @param options - TapKit configuration\n * @returns Object with element reference, state, and control methods\n *\n * @example Advanced control with custom rendering\n * ```tsx\n * 'use client';\n *\n * import { useTapKit } from '@coxwave/tap-kit/react';\n *\n * function MyComponent() {\n * const { element, elementRef, show, hide, isReady, error } = useTapKit({\n * apiKey: 'your-key',\n * userId: 'user-123',\n * courseId: 'course-456',\n * clipId: 'clip-789',\n * });\n *\n * // Direct element access for advanced operations\n * useEffect(() => {\n * if (element) {\n * // Direct manipulation of TapKitElement\n * console.log('Element mounted:', element);\n * }\n * }, [element]);\n *\n * return (\n * <div>\n * <button onClick={show} disabled={!isReady}>Show Chat</button>\n * <button onClick={hide}>Hide Chat</button>\n * {error && <p>Error: {error.message}</p>}\n * <div ref={elementRef} /> // Container for Web Component\n * </div>\n * );\n * }\n * ```\n *\n * @see TapKit - Use this component for simpler declarative API\n */\n\nimport type { TapKitConfig, TapKitElement } from \"@coxwave/tap-kit-types\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { loadCDNLoader } from \"../loader\";\nimport type { TapKitControl, TapKitEventHandlers } from \"./types\";\n\nexport interface UseTapKitOptions extends TapKitConfig, TapKitEventHandlers {\n /** User ID */\n userId?: string;\n /** Course ID */\n courseId?: string;\n /** Clip ID */\n clipId?: string;\n /** Clip playhead position */\n clipPlayHead?: number;\n /** Language */\n language?: \"ko\" | \"en\";\n /** Custom button element ID */\n buttonId?: string;\n /** Display mode */\n mode?: \"inline\" | \"floating\" | \"sidebar\";\n /** Debug mode */\n debug?: boolean;\n /** TAP Frontend URL */\n tapUrl?: string;\n /** API Backend URL */\n apiUrl?: string;\n /** Environment */\n environment?: \"dev\" | \"prod\" | \"staging\" | \"demo\";\n}\n\n/**\n * Configuration options type (non-function values)\n */\ntype TapKitOptions = Omit<UseTapKitOptions, keyof TapKitEventHandlers>;\n\n/**\n * Extract configuration from options (pure function)\n */\nfunction extractConfig(options: UseTapKitOptions): TapKitOptions {\n const { onReady, onError, onTimelineSeek, onAlarmFadeIn, ...config } =\n options;\n return config;\n}\n\n/**\n * Extract event handlers from options (pure function)\n */\nfunction extractHandlers(options: UseTapKitOptions): TapKitEventHandlers {\n return {\n onReady: options.onReady,\n onError: options.onError,\n onTimelineSeek: options.onTimelineSeek,\n onAlarmFadeIn: options.onAlarmFadeIn,\n };\n}\n\n/**\n * Create event bindings for TapKitElement (pure function)\n */\nfunction createEventBindings(\n element: TapKitElement,\n handlers: TapKitEventHandlers,\n): Array<() => void> {\n const unsubscribers: Array<() => void> = [];\n\n if (handlers.onTimelineSeek) {\n unsubscribers.push(element.events.onTimelineSeek(handlers.onTimelineSeek));\n }\n\n if (handlers.onAlarmFadeIn) {\n unsubscribers.push(element.events.onAlarmFadeIn(handlers.onAlarmFadeIn));\n }\n\n return unsubscribers;\n}\n\nexport interface UseTapKitReturn {\n /** Web Component element reference */\n element: TapKitElement | null;\n /** Ref object for direct element access */\n ref: React.RefObject<TapKitElement | null>;\n /** Container ref to attach element */\n elementRef: React.RefCallback<HTMLDivElement>;\n /** Control object for TapKit component */\n control: TapKitControl<TapKitOptions>;\n /** Whether TapKit is ready */\n isReady: boolean;\n /** Error during initialization */\n error: Error | null;\n /** Show chat interface */\n show: () => void;\n /** Hide chat interface */\n hide: () => void;\n /** Set course information */\n setCourse: (course: {\n courseId: string;\n clipId: string;\n userId?: string;\n clipPlayHead?: number;\n }) => void;\n}\n\n/**\n * Hook for managing TapKit Web Component\n *\n * Automatically loads CDN, creates Web Component, and provides control methods.\n *\n * @param options - TapKit configuration with event handlers\n * @returns Methods to control TapKit instance and control object\n */\nexport function useTapKit(options: UseTapKitOptions): UseTapKitReturn {\n const {\n // Event handlers (used in init effect)\n onReady,\n onError,\n // Configuration\n apiKey,\n userId,\n courseId,\n clipId,\n clipPlayHead,\n language,\n buttonId,\n mode = \"floating\",\n debug,\n tapUrl,\n apiUrl,\n environment,\n } = options;\n\n const elementRef = useRef<TapKitElement | null>(null);\n const containerRef = useRef<HTMLDivElement | null>(null);\n const [isReady, setIsReady] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const isMountedRef = useRef(true);\n\n // Ref callback to attach container\n const setContainerRef = useCallback((node: HTMLDivElement | null) => {\n containerRef.current = node;\n }, []);\n\n // Set instance callback for control pattern\n const setInstance = useCallback((instance: TapKitElement | null) => {\n elementRef.current = instance;\n }, []);\n\n // Initialize Web Component\n // biome-ignore lint/correctness/useExhaustiveDependencies: We intentionally only re-initialize when apiKey changes. Other props are updated dynamically via the second useEffect.\n useEffect(() => {\n isMountedRef.current = true;\n let element: TapKitElement | null = null;\n\n async function init() {\n try {\n // Load CDN\n await loadCDNLoader();\n\n // Wait for custom element definition\n await customElements.whenDefined(\"tap-kit\");\n\n if (!isMountedRef.current || !containerRef.current) return;\n\n // Create Web Component\n if (!window.createTapKit) {\n throw new Error(\"createTapKit not available after loading CDN\");\n }\n\n element = window.createTapKit({\n apiKey,\n userId,\n courseId,\n clipId,\n clipPlayHead,\n language,\n buttonId,\n mode,\n debug,\n tapUrl,\n apiUrl,\n environment,\n });\n\n containerRef.current.appendChild(element);\n elementRef.current = element;\n\n // Wait for ready\n await element.ready;\n\n if (!isMountedRef.current) return;\n setIsReady(true);\n\n // Call onReady handler if provided\n if (onReady) {\n onReady();\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n console.error(\"[useTapKit] Initialization failed:\", error);\n if (isMountedRef.current) {\n setError(error);\n // Call onError handler if provided\n if (onError) {\n onError(error);\n }\n }\n }\n }\n\n init();\n\n return () => {\n isMountedRef.current = false;\n if (element) {\n element.remove();\n elementRef.current = null;\n }\n setIsReady(false);\n };\n }, [apiKey, onReady, onError]); // Re-initialize on apiKey or handlers change\n\n // Update properties when options change\n useEffect(() => {\n const element = elementRef.current;\n if (!element || !isReady) return;\n\n if (userId !== undefined) element.userId = userId;\n if (courseId !== undefined) element.courseId = courseId;\n if (clipId !== undefined) element.clipId = clipId;\n if (clipPlayHead !== undefined) element.clipPlayHead = clipPlayHead;\n if (language !== undefined) element.language = language;\n if (buttonId !== undefined) element.buttonId = buttonId;\n if (mode !== undefined) element.mode = mode;\n if (debug !== undefined) element.debug = debug;\n if (tapUrl !== undefined) element.tapUrl = tapUrl;\n if (apiUrl !== undefined) element.apiUrl = apiUrl;\n if (environment !== undefined) element.environment = environment;\n }, [\n isReady,\n userId,\n courseId,\n clipId,\n clipPlayHead,\n language,\n buttonId,\n mode,\n debug,\n tapUrl,\n apiUrl,\n environment,\n ]);\n\n // Separate configuration options from event handlers (memoized)\n const configOptions = useMemo(() => extractConfig(options), [options]);\n\n const handlers = useMemo(() => extractHandlers(options), [options]);\n\n // Register event listeners for EventManager callbacks\n useEffect(() => {\n const element = elementRef.current;\n if (!element || !isReady) return;\n\n const unsubscribers = createEventBindings(element, handlers);\n\n return () => {\n for (const unsubscribe of unsubscribers) {\n unsubscribe();\n }\n };\n }, [isReady, handlers]);\n\n // Create control object\n const control = useMemo<TapKitControl<TapKitOptions>>(\n () => ({\n setInstance,\n options: configOptions,\n handlers,\n }),\n [setInstance, configOptions, handlers],\n );\n\n // Methods\n const show = useCallback(() => {\n if (!elementRef.current) {\n console.warn(\"[useTapKit] Cannot show: element not mounted\");\n return;\n }\n elementRef.current.show();\n }, []);\n\n const hide = useCallback(() => {\n if (!elementRef.current) {\n console.warn(\"[useTapKit] Cannot hide: element not mounted\");\n return;\n }\n elementRef.current.hide();\n }, []);\n\n const setCourse = useCallback(\n (course: {\n courseId: string;\n clipId: string;\n userId?: string;\n clipPlayHead?: number;\n }) => {\n if (!elementRef.current) {\n console.warn(\"[useTapKit] Cannot setCourse: element not mounted\");\n return;\n }\n elementRef.current.setCourse(course);\n },\n [],\n );\n\n return {\n element: elementRef.current,\n ref: elementRef,\n elementRef: setContainerRef,\n control,\n isReady,\n error,\n show,\n hide,\n setCourse,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/react/types.ts","../src/react/TapKit.tsx","../src/loader.ts","../src/react/useTapKit.ts"],"names":["React","TapKit","useRef","useImperativeHandle","useCallback","useEffect","jsx","script","useState","useMemo"],"mappings":";;;;;;;;;;;;AAyFO,IAAM,iBAAA,GAAoB;AAAA,EAC/B,eAAA,EAAiB,SAAA;AAAA,EACjB,eAAA,EAAiB;AACnB,CAAA;AAOO,IAAM,cAAc,MAAA,CAAO,IAAA;AAAA,EAChC;AACF,CAAA;ACEO,IAAM,SAASA,sBAAA,CAAM,UAAA;AAAA,EAC1B,SAASC,OAAAA,CAAO,EAAE,SAAS,GAAG,SAAA,IAAa,YAAA,EAAc;AACvD,IAAA,MAAM,UAAA,GAAaC,aAA6B,IAAI,CAAA;AAGpD,IAAAC,yBAAA;AAAA,MACE,YAAA;AAAA,MACA,MAAM,UAAA,CAAW,OAAA;AAAA,MACjB;AAAC,KACH;AAGA,IAAA,MAAM,aAAA,GAAgBC,iBAAA;AAAA,MACpB,CAAC,OAAA,KAAkC;AACjC,QAAA,UAAA,CAAW,OAAA,GAAU,OAAA;AAIrB,QAAA,IAAI,OAAA,IAAW,OAAA,CAAQ,OAAA,CAAQ,MAAA,EAAQ;AACrC,UAAA,OAAA,CAAQ,MAAA,GAAS,QAAQ,OAAA,CAAQ,MAAA;AAAA,QACnC;AAEA,QAAA,OAAA,CAAQ,YAAY,OAAO,CAAA;AAAA,MAC7B,CAAA;AAAA,MACA,CAAC,OAAA,CAAQ,WAAA,EAAa,OAAA,CAAQ,QAAQ,MAAM;AAAA,KAC9C;AAIA,IAAA,MAAM,WAAA,GAAcF,YAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA;AAC3C,IAAA,WAAA,CAAY,UAAU,OAAA,CAAQ,QAAA;AAG9B,IAAAG,eAAA,CAAU,MAAM;AACd,MAAA,MAAM,UAAU,UAAA,CAAW,OAAA;AAC3B,MAAA,IAAI,CAAC,OAAA,EAAS;AAEd,MAAA,MAAM,YAGD,EAAC;AAGN,MAAA,KAAA,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AAEA,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,IAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;AACF","file":"react.js","sourcesContent":["/**\n * React-specific type definitions for TapKit\n *\n * Defines event handler types and control patterns for React integration.\n */\n\nimport type { TapKitElement } from \"@coxwave/tap-kit-types\";\n\n/**\n * Event handler type definitions for TapKit Web Component\n *\n * Maps CustomEvent types to React callback signatures.\n */\nexport interface TapKitEventHandlers {\n /**\n * Called when TapKit SDK is ready\n * @example onReady={() => console.log('TapKit ready!')}\n */\n onReady?: () => void;\n\n /**\n * Called when initialization or runtime error occurs\n * @example onError={(error) => console.error('TapKit error:', error)}\n */\n onError?: (error: Error) => void;\n\n /**\n * Called when timeline seek event occurs\n * @example onTimelineSeek={(clipPlayHead, clipId) => console.log('Seek:', clipPlayHead)}\n */\n onTimelineSeek?: (clipPlayHead: number, clipId: string) => void;\n\n /**\n * Called when alarm fade-in occurs\n * @example onAlarmFadeIn={(messageInfo) => console.log('Alarm:', messageInfo)}\n */\n onAlarmFadeIn?: (messageInfo: unknown) => void;\n}\n\n/**\n * Control object pattern for managing TapKit instance\n *\n * Separates instance management (setInstance) from configuration (options)\n * and event handling (handlers). Inspired by ChatKit's control pattern.\n *\n * @example\n * ```tsx\n * const tapkit = useTapKit({ apiKey: 'key', onReady: () => {} });\n * <TapKit control={tapkit.control} />\n * ```\n */\nexport interface TapKitControl<T> {\n /**\n * Set the TapKit element instance reference\n *\n * Called by TapKit component to register the element instance.\n * Enables imperative control via useTapKit methods.\n */\n setInstance: (instance: TapKitElement | null) => void;\n\n /**\n * Configuration options (non-function values)\n *\n * All options except event handlers.\n */\n options: T;\n\n /**\n * Event handler callbacks (function values)\n *\n * Separated from options for easier event listener management.\n */\n handlers: TapKitEventHandlers;\n\n /**\n * Whether CDN is loaded and Web Component is available\n *\n * @internal Used by TapKit component to delay rendering\n */\n isCdnLoaded: boolean;\n}\n\n/**\n * Map of TapKit event names to their handler keys\n *\n * Used for automatic event listener binding in TapKit component.\n *\n * @internal\n */\nexport const EVENT_HANDLER_MAP = {\n \"tap-kit:ready\": \"onReady\",\n \"tap-kit:error\": \"onError\",\n} as const;\n\n/**\n * List of TapKit event names\n *\n * @internal\n */\nexport const EVENT_NAMES = Object.keys(\n EVENT_HANDLER_MAP,\n) as (keyof typeof EVENT_HANDLER_MAP)[];\n","/**\n * TapKit React Component\n *\n * Declarative React wrapper for <tap-kit> Web Component.\n * Use this with useTapKit hook for a clean separation of control and rendering.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { TapKit, useTapKit } from '@coxwave/tap-kit/react';\n *\n * function MyApp() {\n * const tapkit = useTapKit({\n * apiKey: 'your-key',\n * userId: 'user-123',\n * courseId: 'course-456',\n * clipId: 'clip-789',\n * onReady: () => console.log('TapKit ready!'),\n * onError: (error) => console.error('Error:', error),\n * });\n *\n * return (\n * <div>\n * <button onClick={tapkit.show} disabled={!tapkit.isReady}>\n * Show Chat\n * </button>\n * <TapKit control={tapkit.control} style={{ height: '600px' }} />\n * </div>\n * );\n * }\n * ```\n *\n * **Note for Next.js App Router users:**\n * Make sure to add 'use client' at the top of your component file.\n *\n * @see https://edutap-ai-docs.vercel.app/docs/guides/react\n */\n\nimport type { TapKitElement } from \"@coxwave/tap-kit-types\";\nimport React, {\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n} from \"react\";\nimport type { TapKitControl } from \"./types\";\nimport { EVENT_HANDLER_MAP, EVENT_NAMES } from \"./types\";\n\n/**\n * Props for TapKit React component\n */\nexport interface TapKitProps\n extends Omit<\n React.HTMLAttributes<TapKitElement>,\n \"children\" | \"dangerouslySetInnerHTML\"\n > {\n /**\n * Control object from useTapKit hook\n *\n * Provides instance management, configuration, and event handlers.\n */\n control: TapKitControl<any>;\n}\n\n// Augment JSX namespace to support <tap-kit> custom element\ndeclare global {\n namespace JSX {\n interface IntrinsicElements {\n \"tap-kit\": React.DetailedHTMLProps<\n React.HTMLAttributes<TapKitElement>,\n TapKitElement\n > & {\n \"api-key\"?: string;\n \"user-id\"?: string;\n \"course-id\"?: string;\n \"clip-id\"?: string;\n \"clip-play-head\"?: number;\n language?: \"ko\" | \"en\";\n \"button-id\"?: string;\n mode?: \"inline\" | \"floating\" | \"sidebar\";\n debug?: boolean;\n \"tap-url\"?: string;\n \"api-url\"?: string;\n environment?: \"dev\" | \"prod\" | \"staging\" | \"demo\";\n };\n }\n }\n}\n\n/**\n * TapKit React Component\n *\n * Renders <tap-kit> Web Component with React integration.\n * Automatically manages instance lifecycle and event listeners.\n *\n * **Ref Access**: The forwarded ref provides direct access to the TapKitElement:\n * ```tsx\n * const tapkitRef = useRef<TapKitElement>(null);\n * <TapKit ref={tapkitRef} control={...} />\n * // tapkitRef.current?.show()\n * ```\n */\nexport const TapKit = React.forwardRef<TapKitElement, TapKitProps>(\n function TapKit({ control, ...htmlProps }, forwardedRef) {\n const elementRef = useRef<TapKitElement | null>(null);\n\n // Forward TapKitElement to parent\n useImperativeHandle(\n forwardedRef,\n () => elementRef.current as TapKitElement,\n [],\n );\n\n // Callback ref to register element when mounted\n const setElementRef = useCallback(\n (element: TapKitElement | null) => {\n elementRef.current = element;\n\n // Set apiKey as property (not attribute) - required for LitElement\n // apiKey has { attribute: false } so it won't work via HTML attribute\n if (element && control.options.apiKey) {\n element.apiKey = control.options.apiKey;\n }\n\n control.setInstance(element);\n },\n [control.setInstance, control.options.apiKey],\n );\n\n // Store handlers in ref to avoid effect re-runs on handler reference changes\n // Handlers are stable via useMemo in useTapKit, but use ref for extra safety\n const handlersRef = useRef(control.handlers);\n handlersRef.current = control.handlers;\n\n // Register event listeners (only once per element mount)\n useEffect(() => {\n const element = elementRef.current;\n if (!element) return;\n\n const listeners: Array<{\n event: string;\n handler: EventListener;\n }> = [];\n\n // Bind CustomEvent listeners (tap-kit:ready, tap-kit:error)\n for (const eventName of EVENT_NAMES) {\n const handlerKey =\n EVENT_HANDLER_MAP[eventName as keyof typeof EVENT_HANDLER_MAP];\n\n // Use closure over handlersRef to always get latest handler\n const listener = (e: Event) => {\n const handler = handlersRef.current[handlerKey];\n if (!handler) return;\n\n const customEvent = e as CustomEvent;\n if (handlerKey === \"onError\" && customEvent.detail?.error) {\n // onError receives error directly\n // biome-ignore lint/suspicious/noExplicitAny: Handler type is validated at runtime\n (handler as any)(customEvent.detail.error);\n } else if (handlerKey === \"onReady\") {\n // onReady receives no arguments\n // biome-ignore lint/suspicious/noExplicitAny: Handler type is validated at runtime\n (handler as any)();\n }\n };\n\n element.addEventListener(eventName, listener);\n listeners.push({ event: eventName, handler: listener });\n }\n\n return () => {\n // Cleanup all event listeners\n for (const { event, handler } of listeners) {\n element.removeEventListener(event, handler);\n }\n };\n }, []); // Empty deps - listeners use ref for handlers\n\n const { options, isCdnLoaded } = control;\n\n // Wait for CDN to load before rendering Web Component\n // Without this, <tap-kit> is just an HTMLUnknownElement without methods\n if (!isCdnLoaded) {\n return null;\n }\n\n // Render <tap-kit> Web Component directly\n // Note: apiKey is set via ref callback (property-only in LitElement)\n return (\n <tap-kit\n ref={setElementRef}\n user-id={options.userId}\n course-id={options.courseId}\n clip-id={options.clipId}\n clip-play-head={options.clipPlayHead}\n language={options.language}\n button-id={options.buttonId}\n mode={options.mode}\n debug={options.debug}\n tap-url={options.tapUrl}\n api-url={options.apiUrl}\n environment={options.environment}\n {...htmlProps}\n />\n );\n },\n);\n","/**\n * CDN loader for TapKit\n * Dynamically loads the TapKit SDK from CDN\n *\n * For local testing, you can override the loader URL:\n * window.__TAP_KIT_LOADER_URL__ = '/tap-kit-core/loader.js';\n *\n * For local development (bypass loader, load IIFE directly):\n * window.__TAP_KIT_CORE_URL__ = '/packages/tap-kit-core/dist/index.global.js';\n */\n\n// Build-time constant injected by tsup define\ndeclare const __DEFAULT_CDN_LOADER_URL__: string;\n\nconst DEFAULT_CDN_LOADER_URL =\n typeof __DEFAULT_CDN_LOADER_URL__ !== \"undefined\"\n ? __DEFAULT_CDN_LOADER_URL__\n : \"https://files.edutap.ai/tap-sdk/loader.js\";\nconst DEFAULT_TIMEOUT_MS = 4000; // 4 seconds total timeout\nconst IDLE_CALLBACK_TIMEOUT_MS = 500; // 500ms for requestIdleCallback\n\n/**\n * Get the loader URL from window override or default CDN\n */\nfunction getLoaderURL(): string {\n return window?.__TAP_KIT_LOADER_URL__\n ? window.__TAP_KIT_LOADER_URL__\n : DEFAULT_CDN_LOADER_URL;\n}\n\n/**\n * Check if local core mode is enabled\n * When __TAP_KIT_CORE_URL__ is set, directly load the IIFE bundle\n * This bypasses the loader.js and loads tap-kit-core directly\n */\nfunction isLocalCoreMode(): boolean {\n return typeof window !== \"undefined\" && !!window.__TAP_KIT_CORE_URL__;\n}\n\n/**\n * Get the local core URL\n */\nfunction getLocalCoreURL(): string {\n return window.__TAP_KIT_CORE_URL__ || \"\";\n}\n\n/**\n * Creates a SDK checker function with timeout and retry logic\n * Uses requestIdleCallback to avoid blocking browser rendering\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n * @param timeoutMs - Maximum time to wait for SDK to load (milliseconds)\n * @returns Checker function to be called repeatedly\n */\nfunction createSDKChecker(\n resolve: (value: void | PromiseLike<void>) => void,\n reject: (reason?: unknown) => void,\n timeoutMs: number,\n): () => void {\n const startTime = Date.now();\n\n const checkSDK = (): void => {\n // Check if real TapKit is loaded (not just stub)\n // Stub has TapKitLoaded flag set to true by loader.js after real SDK loads\n if (window.TapKit && window.TapKitLoaded === true) {\n window.__TAP_KIT_LOADER_LOADED__ = true;\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n resolve();\n return;\n }\n\n const elapsed = Date.now() - startTime;\n\n // Check if exceeded timeout\n if (elapsed > timeoutMs) {\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n reject(\n new Error(\n `TapKit loader timeout: SDK not available after ${timeoutMs}ms`,\n ),\n );\n return;\n }\n\n // Use requestIdleCallback for better performance\n // Falls back to setTimeout if not available\n if (typeof requestIdleCallback !== \"undefined\") {\n requestIdleCallback(checkSDK, { timeout: IDLE_CALLBACK_TIMEOUT_MS });\n } else {\n setTimeout(checkSDK, IDLE_CALLBACK_TIMEOUT_MS);\n }\n };\n\n return checkSDK;\n}\n\n/**\n * Loads the CDN loader script\n * The loader will then fetch versions.json and load the appropriate SDK version\n *\n * If __TAP_KIT_CORE_URL__ is set, bypasses loader and loads IIFE directly\n *\n * @param timeoutMs - Maximum time to wait for SDK to load (default: 4000ms)\n * @returns Promise that resolves when SDK is loaded\n * @throws {Error} If loader fails to load or times out\n */\nexport function loadCDNLoader(\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n): Promise<void> {\n // If already loaded, return immediately\n if (window.__TAP_KIT_LOADER_LOADED__ && window.TapKit) {\n return Promise.resolve();\n }\n\n // If currently loading, return the existing promise\n if (window.__TAP_KIT_LOADER_LOADING__) {\n return window.__TAP_KIT_LOADER_LOADING__;\n }\n\n // Create loading promise\n const loadingPromise = new Promise<void>((resolve, reject) => {\n if (typeof document === \"undefined\") {\n reject(\n new Error(\n \"TapKit requires browser environment (document is undefined)\",\n ),\n );\n return;\n }\n\n // Local core mode: Load IIFE directly\n if (isLocalCoreMode()) {\n // Check if TapKit is already loaded (from other pages in playground)\n if (window.TapKit && window.TapKitLoaded === true) {\n window.__TAP_KIT_LOADER_LOADED__ = true;\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n resolve();\n return;\n }\n\n const coreURL = getLocalCoreURL();\n\n const script = document.createElement(\"script\");\n script.src = coreURL;\n script.async = true;\n\n script.onload = () => {\n // IIFE directly sets window.TapKit\n // Set the loaded flag manually since we bypass loader.js\n if (window.TapKit) {\n window.TapKitLoaded = true;\n window.__TAP_KIT_LOADER_LOADED__ = true;\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n resolve();\n } else {\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n reject(new Error(\"TapKit not available after loading local core\"));\n }\n };\n\n script.onerror = () => {\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n reject(new Error(`Failed to load local TapKit core: ${coreURL}`));\n };\n\n document.head.appendChild(script);\n return;\n }\n\n // CDN mode: Load loader.js\n const loaderURL = getLoaderURL();\n const script = document.createElement(\"script\");\n script.src = loaderURL;\n script.async = true;\n\n script.onload = () => {\n // The loader script will load the actual SDK\n // We need to wait a bit for the loader to fetch and load the SDK\n const checkSDK = createSDKChecker(resolve, reject, timeoutMs);\n checkSDK();\n };\n\n script.onerror = () => {\n window.__TAP_KIT_LOADER_LOADING__ = undefined;\n reject(new Error(`Failed to load TapKit CDN loader: ${loaderURL}`));\n };\n\n // Check if script already exists\n const existingScript = document.querySelector(`script[src=\"${loaderURL}\"]`);\n\n if (existingScript) {\n // Script already added but not yet loaded\n existingScript.addEventListener(\"load\", () => {\n const checkSDK = createSDKChecker(resolve, reject, timeoutMs);\n checkSDK();\n });\n existingScript.addEventListener(\"error\", () =>\n reject(new Error(`Failed to load TapKit CDN loader: ${loaderURL}`)),\n );\n } else {\n document.head.appendChild(script);\n }\n });\n\n window.__TAP_KIT_LOADER_LOADING__ = loadingPromise;\n return loadingPromise;\n}\n","/**\n * useTapKit Hook - ChatKit-style control for TapKit Web Component\n *\n * This hook provides a control object to manage TapKit through the\n * <TapKit /> component. Inspired by OpenAI's ChatKit pattern.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { TapKit, useTapKit } from '@coxwave/tap-kit/react';\n *\n * function MyApp() {\n * const tapkit = useTapKit({\n * apiKey: 'your-key',\n * userId: 'user-123',\n * courseId: 'course-456',\n * clipId: 'clip-789',\n * onReady: () => console.log('Ready!'),\n * onError: (error) => console.error(error),\n * });\n *\n * return (\n * <div>\n * <button onClick={tapkit.show} disabled={!tapkit.isReady}>\n * Ask AI Tutor\n * </button>\n * <TapKit control={tapkit.control} />\n * </div>\n * );\n * }\n * ```\n */\n\nimport type { TapKitElement } from \"@coxwave/tap-kit-types\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { loadCDNLoader } from \"../loader\";\nimport type { TapKitControl, TapKitEventHandlers } from \"./types\";\n\nexport interface UseTapKitOptions extends TapKitEventHandlers {\n /** API Key (required) */\n apiKey: string;\n /** User ID */\n userId?: string;\n /** Course ID */\n courseId?: string;\n /** Clip ID */\n clipId?: string;\n /** Clip playhead position */\n clipPlayHead?: number;\n /** Language */\n language?: \"ko\" | \"en\";\n /** Custom button element ID */\n buttonId?: string;\n /** Display mode */\n mode?: \"inline\" | \"floating\" | \"sidebar\";\n /** Debug mode */\n debug?: boolean;\n /** TAP Frontend URL */\n tapUrl?: string;\n /** API Backend URL */\n apiUrl?: string;\n /** Environment */\n environment?: \"dev\" | \"prod\" | \"staging\" | \"demo\";\n}\n\n/**\n * Configuration options type (non-function values)\n */\nexport type TapKitOptions = Omit<UseTapKitOptions, keyof TapKitEventHandlers>;\n\n/**\n * Extract event handlers from options (pure function)\n */\nfunction extractHandlers(options: UseTapKitOptions): TapKitEventHandlers {\n return {\n onReady: options.onReady,\n onError: options.onError,\n onTimelineSeek: options.onTimelineSeek,\n onAlarmFadeIn: options.onAlarmFadeIn,\n };\n}\n\nexport interface UseTapKitReturn {\n /** Control object for <TapKit /> component */\n control: TapKitControl<TapKitOptions>;\n /** Whether TapKit is ready */\n isReady: boolean;\n /** Error during initialization */\n error: Error | null;\n /** Show chat interface */\n show: () => void;\n /** Hide chat interface */\n hide: () => void;\n /** Set course information */\n setCourse: (course: {\n courseId: string;\n clipId: string;\n userId?: string;\n clipPlayHead?: number;\n }) => void;\n /** Video adapter control */\n video: {\n /** Bind video player for timeline synchronization */\n bind: (\n adapter: {\n getCurrentTime: () => number;\n setCurrentTime: (time: number) => void;\n },\n clipId: string,\n ) => void;\n /** Unbind current video player */\n unbind: () => void;\n };\n}\n\n/**\n * Hook for managing TapKit Web Component (ChatKit Pattern)\n *\n * Returns a control object to pass to <TapKit /> component.\n * The component handles rendering, this hook handles state and methods.\n */\nexport function useTapKit(options: UseTapKitOptions): UseTapKitReturn {\n // Element ref - set by <TapKit /> component via control.setInstance\n const elementRef = useRef<TapKitElement | null>(null);\n\n // State\n const [isCdnLoaded, setIsCdnLoaded] = useState(false);\n const [isReady, setIsReady] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Store handlers in refs to avoid stale closures\n const handlersRef = useRef(extractHandlers(options));\n handlersRef.current = extractHandlers(options);\n\n // Load CDN on mount (defines <tap-kit> Web Component)\n useEffect(() => {\n loadCDNLoader()\n .then(() => {\n setIsCdnLoaded(true);\n })\n .catch((err) => {\n const loadError =\n err instanceof Error ? err : new Error(\"Failed to load TapKit CDN\");\n setError(loadError);\n handlersRef.current.onError?.(loadError);\n });\n }, []);\n\n // Set instance callback - called by <TapKit /> component\n const setInstance = useCallback((instance: TapKitElement | null) => {\n elementRef.current = instance;\n\n if (!instance) {\n setIsReady(false);\n return;\n }\n\n // Listen for ready event\n const handleReady = () => {\n setIsReady(true);\n handlersRef.current.onReady?.();\n };\n\n const handleError = (e: Event) => {\n const customEvent = e as CustomEvent<{ error: Error }>;\n const err = customEvent.detail?.error ?? new Error(\"Unknown error\");\n setError(err);\n handlersRef.current.onError?.(err);\n };\n\n instance.addEventListener(\"tap-kit:ready\", handleReady);\n instance.addEventListener(\"tap-kit:error\", handleError);\n\n // Check if already ready\n if (instance.isInitialized) {\n setIsReady(true);\n }\n\n // Setup EventManager callbacks when ready\n const setupEventHandlers = () => {\n if (\n instance.events &&\n typeof instance.events.onTimelineSeek === \"function\"\n ) {\n if (handlersRef.current.onTimelineSeek) {\n instance.events.onTimelineSeek(handlersRef.current.onTimelineSeek);\n }\n if (handlersRef.current.onAlarmFadeIn) {\n instance.events.onAlarmFadeIn(handlersRef.current.onAlarmFadeIn);\n }\n }\n };\n\n // Check if ready property exists (may not be available immediately)\n if (instance.ready && typeof instance.ready.then === \"function\") {\n instance.ready.then(setupEventHandlers).catch(() => {\n // Ignore - error already handled by tap-kit:error event\n });\n } else if (instance.isInitialized) {\n // Already initialized, setup handlers immediately\n setupEventHandlers();\n } else {\n // Fallback: wait for ready event then setup handlers\n instance.addEventListener(\"tap-kit:ready\", setupEventHandlers, {\n once: true,\n });\n }\n }, []);\n\n // Memoize config options using individual values to prevent infinite re-renders\n // (options object is recreated on every render, so we must depend on primitives)\n const configOptions = useMemo(\n () => ({\n apiKey: options.apiKey,\n userId: options.userId,\n courseId: options.courseId,\n clipId: options.clipId,\n clipPlayHead: options.clipPlayHead,\n language: options.language,\n buttonId: options.buttonId,\n mode: options.mode,\n debug: options.debug,\n tapUrl: options.tapUrl,\n apiUrl: options.apiUrl,\n environment: options.environment,\n }),\n [\n options.apiKey,\n options.userId,\n options.courseId,\n options.clipId,\n options.clipPlayHead,\n options.language,\n options.buttonId,\n options.mode,\n options.debug,\n options.tapUrl,\n options.apiUrl,\n options.environment,\n ],\n );\n\n // Store handlers in stable ref (already done above with handlersRef)\n // Use ref-based handlers for control to maintain stability\n const handlers = useMemo(\n () => ({\n onReady: handlersRef.current.onReady,\n onError: handlersRef.current.onError,\n onTimelineSeek: handlersRef.current.onTimelineSeek,\n onAlarmFadeIn: handlersRef.current.onAlarmFadeIn,\n }),\n // Empty deps - handlers are accessed via ref which is always up-to-date\n [],\n );\n\n // Create control object\n const control = useMemo<TapKitControl<TapKitOptions>>(\n () => ({\n setInstance,\n options: configOptions,\n handlers,\n isCdnLoaded,\n }),\n [setInstance, configOptions, handlers, isCdnLoaded],\n );\n\n // Methods\n const show = useCallback(() => {\n if (!elementRef.current) {\n console.warn(\"[useTapKit] Cannot show: element not mounted\");\n return;\n }\n elementRef.current.show();\n }, []);\n\n const hide = useCallback(() => {\n if (!elementRef.current) {\n console.warn(\"[useTapKit] Cannot hide: element not mounted\");\n return;\n }\n elementRef.current.hide();\n }, []);\n\n const setCourse = useCallback(\n (course: {\n courseId: string;\n clipId: string;\n userId?: string;\n clipPlayHead?: number;\n }) => {\n if (!elementRef.current) {\n console.warn(\"[useTapKit] Cannot setCourse: element not mounted\");\n return;\n }\n elementRef.current.setCourse(course);\n },\n [],\n );\n\n // Video adapter control\n const video = useMemo(\n () => ({\n bind: (\n adapter: {\n getCurrentTime: () => number;\n setCurrentTime: (time: number) => void;\n },\n clipId: string,\n ) => {\n if (!elementRef.current) {\n console.warn(\"[useTapKit] Cannot bind video: element not mounted\");\n return;\n }\n if (!elementRef.current.video) {\n console.warn(\"[useTapKit] Cannot bind video: video controller not available\");\n return;\n }\n elementRef.current.video.bind(adapter, clipId);\n },\n unbind: () => {\n elementRef.current?.video?.unbind();\n },\n }),\n [],\n );\n\n return {\n control,\n isReady,\n error,\n show,\n hide,\n setCourse,\n video,\n };\n}\n"]}