forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslots.tsx
More file actions
184 lines (164 loc) · 5.45 KB
/
Copy pathslots.tsx
File metadata and controls
184 lines (164 loc) · 5.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import React, { useRef } from "react";
import { twMerge } from "tailwind-merge";
/** Existing union (unchanged) */
export type SlotValue<C extends React.ComponentType<any>> =
| C
| string
| Partial<React.ComponentProps<C>>;
/**
* Shallow equality comparison for objects.
*/
export function shallowEqual<T extends Record<string, unknown>>(
obj1: T,
obj2: T,
): boolean {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
for (const key of keys1) {
if (obj1[key] !== obj2[key]) return false;
}
return true;
}
/**
* Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
* class instances, and other exotic objects that happen to have typeof "object".
*/
function isPlainObject(obj: unknown): obj is Record<string, unknown> {
return (
obj !== null &&
typeof obj === "object" &&
Object.prototype.toString.call(obj) === "[object Object]"
);
}
/**
* Returns the same reference as long as the value is shallowly equal to the
* previous render's value.
*
* - Identical references bail out immediately (O(1)).
* - Plain objects ({}) are shallow-compared key-by-key.
* - Arrays, Dates, class instances, functions, and primitives are compared by
* reference only — shallowEqual is never called on non-plain objects, which
* avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
*
* Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
* equality check isn't defeated by a new object reference on every render.
*/
export function useShallowStableRef<T>(value: T): T {
const ref = useRef(value);
// 1. Identical reference — bail early, no comparison needed.
if (ref.current === value) return ref.current;
// 2. Both are plain objects — shallow-compare to detect structural equality.
if (isPlainObject(ref.current) && isPlainObject(value)) {
if (shallowEqual(ref.current, value)) return ref.current;
}
// 3. Different values (or non-comparable types) — update the ref.
ref.current = value;
return ref.current;
}
/** Utility: concrete React elements for every slot */
type SlotElements<S> = { [K in keyof S]: React.ReactElement };
export type WithSlots<
S extends Record<string, React.ComponentType<any>>,
Rest = {},
> = {
/** Per‑slot overrides */
[K in keyof S]?: SlotValue<S[K]>;
} & {
children?: (props: SlotElements<S> & Rest) => React.ReactNode;
} & Omit<Rest, "children">;
/**
* Check if a value is a React component type (function, class, forwardRef, memo, etc.)
*/
export function isReactComponentType(
value: unknown,
): value is React.ComponentType<any> {
if (typeof value === "function") {
return true;
}
// forwardRef, memo, lazy have $$typeof but are not valid elements
if (
value &&
typeof value === "object" &&
"$$typeof" in value &&
!React.isValidElement(value)
) {
return true;
}
return false;
}
/**
* Internal function to render a slot value as a React element (non-memoized).
*/
function renderSlotElement(
slot: SlotValue<React.ComponentType<any>> | undefined,
DefaultComponent: React.ComponentType<any>,
props: Record<string, unknown>,
): React.ReactElement {
if (typeof slot === "string") {
// When slot is a string, treat it as a className and merge with existing className
const existingClassName = props.className as string | undefined;
return React.createElement(DefaultComponent, {
...props,
className: twMerge(existingClassName, slot),
});
}
// Check if slot is a React component type (function, forwardRef, memo, etc.)
if (isReactComponentType(slot)) {
return React.createElement(slot, props);
}
// If slot is a plain object (not a React element), treat it as props override
if (slot && typeof slot === "object" && !React.isValidElement(slot)) {
return React.createElement(DefaultComponent, {
...props,
...slot,
});
}
return React.createElement(DefaultComponent, props);
}
/**
* Internal memoized wrapper component for renderSlot.
* Uses forwardRef to support ref forwarding.
*/
const MemoizedSlotWrapper = React.memo(
React.forwardRef<unknown, any>(function MemoizedSlotWrapper(props, ref) {
const { $slot, $component, ...rest } = props;
const propsWithRef: Record<string, unknown> =
ref !== null ? { ...rest, ref } : rest;
return renderSlotElement($slot, $component, propsWithRef);
}),
(prev: any, next: any) => {
// Compare slot and component references
if (prev.$slot !== next.$slot) return false;
if (prev.$component !== next.$component) return false;
// Shallow compare remaining props (ref is handled separately by React)
const { $slot: _ps, $component: _pc, ...prevRest } = prev;
const { $slot: _ns, $component: _nc, ...nextRest } = next;
return shallowEqual(
prevRest as Record<string, unknown>,
nextRest as Record<string, unknown>,
);
},
);
/**
* Renders a slot value as a memoized React element.
* Automatically prevents unnecessary re-renders using shallow prop comparison.
* Supports ref forwarding.
*
* @example
* renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })
*/
export function renderSlot<
C extends React.ComponentType<any>,
P = React.ComponentProps<C>,
>(
slot: SlotValue<C> | undefined,
DefaultComponent: C,
props: P,
): React.ReactElement {
return React.createElement(MemoizedSlotWrapper, {
...props,
$slot: slot,
$component: DefaultComponent,
} as any);
}