@@ -22,8 +22,8 @@ export const ChatKit = React.forwardRef<OpenAIChatKit, ChatKitProps>(
2222 const ref = React . useRef < OpenAIChatKit | null > ( null ) ;
2323
2424 React . useLayoutEffect ( ( ) => {
25- if ( ! ref . current ) return ;
2625 const el = ref . current ;
26+ if ( ! el ) return ;
2727
2828 // Fast path: element is already defined
2929 if ( customElements . get ( 'openai-chatkit' ) ) {
@@ -46,45 +46,40 @@ export const ChatKit = React.forwardRef<OpenAIChatKit, ChatKitProps>(
4646 < openai-chatkit
4747 ref = { ( chatKit ) => {
4848 ref . current = chatKit ;
49+
4950 control . setInstance ( chatKit ) ;
51+
5052 if ( typeof forwardedRef === 'function' ) {
5153 forwardedRef ( chatKit ) ;
5254 } else if ( forwardedRef ) {
5355 forwardedRef . current = chatKit ;
5456 }
5557
56- if ( ref . current ) {
57- const abortController = new AbortController ( ) ;
58- const events = {
59- 'chatkit.error' : 'onError' ,
60- 'chatkit.response.end' : 'onResponseEnd' ,
61- 'chatkit.response.start' : 'onResponseStart' ,
62- 'chatkit.log' : 'onLog' ,
63- 'chatkit.thread.change' : 'onThreadChange' ,
64- 'chatkit.thread.load.start' : 'onThreadLoadStart' ,
65- 'chatkit.thread.load.end' : 'onThreadLoadEnd' ,
66- } satisfies {
67- [ K in keyof ChatKitEvents ] : ToEventHandlerKey < K > ;
68- } ;
58+ if ( ! ref . current ) {
59+ return ;
60+ }
61+
62+ const events : {
63+ [ K in keyof ChatKitEvents ] : ToEventHandlerKey < K > ;
64+ } = {
65+ 'chatkit.error' : 'onError' ,
66+ 'chatkit.response.end' : 'onResponseEnd' ,
67+ 'chatkit.response.start' : 'onResponseStart' ,
68+ 'chatkit.log' : 'onLog' ,
69+ 'chatkit.thread.change' : 'onThreadChange' ,
70+ 'chatkit.thread.load.start' : 'onThreadLoadStart' ,
71+ 'chatkit.thread.load.end' : 'onThreadLoadEnd' ,
72+ } ;
6973
70- for ( const eventName of Object . keys (
71- events ,
72- ) as ( keyof ChatKitEvents ) [ ] ) {
73- ref . current . addEventListener (
74- eventName ,
75- ( e ) => {
76- const handler = control . handlers [ events [ eventName ] ] ;
77- if ( typeof handler === 'function' ) {
78- handler ( e . detail as any ) ;
79- }
80- } ,
81- { signal : abortController . signal } ,
82- ) ;
83- }
74+ const eventNames = Object . keys ( events ) as ( keyof ChatKitEvents ) [ ] ;
8475
85- return ( ) => {
86- abortController . abort ( ) ;
87- } ;
76+ for ( const event of eventNames ) {
77+ ref . current . addEventListener ( event , ( e ) => {
78+ const handler = control . handlers [ events [ event ] ] ;
79+ if ( typeof handler === 'function' ) {
80+ handler ( e . detail as any ) ;
81+ }
82+ } ) ;
8883 }
8984 } }
9085 { ...htmlProps }
0 commit comments