@zayne-labs/toolkit-react 0.10.26 → 0.11.0
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.
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import * as react10 from "react";
|
|
1
2
|
import { RefCallback } from "react";
|
|
2
|
-
import { AnyFunction, AnyObject, Prettify, UnionDiscriminator } from "@zayne-labs/toolkit-type-helpers";
|
|
3
|
+
import { AnyFunction, AnyObject, CallbackFn, EmptyObject, Prettify, UnionDiscriminator, UnionToIntersection, UnknownObject } from "@zayne-labs/toolkit-type-helpers";
|
|
3
4
|
|
|
4
5
|
//#region src/utils/composeEventHandlers.d.ts
|
|
5
6
|
declare const composeTwoEventHandlers: (formerHandler: AnyFunction | undefined, latterHandler: AnyFunction | undefined) => (event: unknown) => unknown;
|
|
@@ -19,8 +20,145 @@ declare const setRef: <TRef extends HTMLElement>(ref: PossibleRef<TRef>, node: T
|
|
|
19
20
|
declare const composeRefs: <TRef extends HTMLElement>(...refs: Array<PossibleRef<TRef>>) => RefCallback<TRef>;
|
|
20
21
|
declare const useComposeRefs: <TRef extends HTMLElement>(...refs: Array<PossibleRef<TRef>>) => () => RefCallback<TRef>;
|
|
21
22
|
//#endregion
|
|
23
|
+
//#region src/utils/getSlot/getSlot.d.ts
|
|
24
|
+
type FunctionalComponent<TProps extends UnknownObject = never> = React.FunctionComponent<TProps>;
|
|
25
|
+
/**
|
|
26
|
+
* @description Checks if a react child (within the children array) matches the provided SlotComponent using multiple matching strategies:
|
|
27
|
+
* 1. Matches by slot symbol property
|
|
28
|
+
* 2. Matches by component name
|
|
29
|
+
*/
|
|
30
|
+
declare const matchesSlotComponent: (child: React.ReactNode, SlotComponent: FunctionalComponent) => boolean;
|
|
31
|
+
/**
|
|
32
|
+
* @description Checks if a react child (within the children array) matches any of the provided SlotComponents.
|
|
33
|
+
*/
|
|
34
|
+
declare const matchesAnySlotComponent: (child: React.ReactNode, SlotComponents: FunctionalComponent[]) => boolean;
|
|
35
|
+
type SlotOptions = {
|
|
36
|
+
/**
|
|
37
|
+
* @description The error message to throw when multiple slots are found for a given slot component
|
|
38
|
+
*/
|
|
39
|
+
errorMessage?: string;
|
|
40
|
+
/**
|
|
41
|
+
* @description When true, an AssertionError will be thrown if multiple slots are found for a given slot component
|
|
42
|
+
*/
|
|
43
|
+
throwOnMultipleSlotMatch?: boolean;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* @description Retrieves a single slot element from a collection of React children that matches the provided SlotComponent component.
|
|
47
|
+
*
|
|
48
|
+
* @throws { AssertionError } when throwOnMultipleSlotMatch is true and multiple slots are found
|
|
49
|
+
*/
|
|
50
|
+
declare const getSingleSlot: (children: React.ReactNode, SlotComponent: FunctionalComponent, options?: SlotOptions) => react10.ReactNode;
|
|
51
|
+
type MultipleSlotsOptions = {
|
|
52
|
+
/**
|
|
53
|
+
* @description The error message to throw when multiple slots are found for a given slot component
|
|
54
|
+
* If a string is provided, the same message will be used for all slot components
|
|
55
|
+
* If an array is provided, each string in the array will be used as the errorMessage for the corresponding slot component
|
|
56
|
+
*/
|
|
57
|
+
errorMessage?: string | string[];
|
|
58
|
+
/**
|
|
59
|
+
* @description When true, an AssertionError will be thrown if multiple slots are found for a given slot component
|
|
60
|
+
* If a boolean is provided, the same value will be used for all slot components
|
|
61
|
+
* If an array is provided, each boolean in the array will be used as the throwOnMultipleSlotMatch value for the corresponding slot component
|
|
62
|
+
*/
|
|
63
|
+
throwOnMultipleSlotMatch?: boolean | boolean[];
|
|
64
|
+
};
|
|
65
|
+
type GetMultipleSlotsResult<TSlotComponents extends FunctionalComponent[]> = {
|
|
66
|
+
regularChildren: React.ReactNode[];
|
|
67
|
+
slots: { [Key in keyof TSlotComponents]: ReturnType<TSlotComponents[Key]> };
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* @description The same as getSingleSlot, but for multiple slot components
|
|
71
|
+
*/
|
|
72
|
+
declare const getMultipleSlots: <const TSlotComponents extends FunctionalComponent[]>(children: React.ReactNode, SlotComponents: TSlotComponents, options?: MultipleSlotsOptions) => Prettify<GetMultipleSlotsResult<TSlotComponents>>;
|
|
73
|
+
/**
|
|
74
|
+
* @description Returns all children that are not slot elements (i.e., don't match any of the provided slot components)
|
|
75
|
+
*/
|
|
76
|
+
declare const getRegularChildren: (children: React.ReactNode, SlotComponentOrComponents: FunctionalComponent | FunctionalComponent[]) => react10.ReactNode[];
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/utils/getSlotMap/getSlotMap.d.ts
|
|
79
|
+
type GetSlotName<TSlotComponentProps extends GetSlotComponentProps> = string extends TSlotComponentProps["name"] ? never : "default" extends TSlotComponentProps["name"] ? never : TSlotComponentProps["name"];
|
|
80
|
+
type GetSpecificSlotsType<TSlotComponentProps extends GetSlotComponentProps> = { [TName in keyof TSlotComponentProps as GetSlotName<TSlotComponentProps>]: Extract<TSlotComponentProps["children"], React.ReactNode> };
|
|
81
|
+
/**
|
|
82
|
+
* Maps slot names to their corresponding children types
|
|
83
|
+
*/
|
|
84
|
+
type GetSlotMapResult<TSlotComponentProps extends GetSlotComponentProps> = UnionToIntersection<GetSpecificSlotsType<TSlotComponentProps>> & {
|
|
85
|
+
default: React.ReactNode[];
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Symbol used to identify SlotComponent instances
|
|
89
|
+
*/
|
|
90
|
+
declare const slotComponentSymbol: unique symbol;
|
|
91
|
+
/**
|
|
92
|
+
* @description Creates a map of named slots from React children. Returns an object mapping slot names to their children,
|
|
93
|
+
* with a default slot for unmatched children.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```tsx
|
|
97
|
+
* import { type GetSlotComponentProps, SlotComponent } from "@zayne-labs/toolkit-react/utils"
|
|
98
|
+
*
|
|
99
|
+
* type SlotProps = GetSlotComponentProps<"header" | "footer">;
|
|
100
|
+
*
|
|
101
|
+
* function Parent({ children }: { children: React.ReactNode }) {
|
|
102
|
+
* const slots = getSlotMap<SlotProps>(children);
|
|
103
|
+
*
|
|
104
|
+
* return (
|
|
105
|
+
* <div>
|
|
106
|
+
* <header>{slots.header}</header>
|
|
107
|
+
* <main>{slots.default}</main>
|
|
108
|
+
* <footer>{slots.footer}</footer>
|
|
109
|
+
* </div>
|
|
110
|
+
* );
|
|
111
|
+
* }
|
|
112
|
+
* ```
|
|
113
|
+
*
|
|
114
|
+
* Usage:
|
|
115
|
+
* ```tsx
|
|
116
|
+
* <Parent>
|
|
117
|
+
* <SlotComponent name="header">Header Content</SlotComponent>
|
|
118
|
+
* <div>Random stuff</div>
|
|
119
|
+
* <SlotComponent name="footer">Footer Content</SlotComponent>
|
|
120
|
+
* </Parent>
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
declare const getSlotMap: <TSlotComponentProps extends GetSlotComponentProps>(children: React.ReactNode) => Prettify<GetSlotMapResult<TSlotComponentProps>>;
|
|
124
|
+
/**
|
|
125
|
+
* @description Produce props for the SlotComponent
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```ts
|
|
129
|
+
* // Pattern One (slot or slots have same children type, which is just React.ReactNode by default)
|
|
130
|
+
* type SlotProps = GetSlotComponentProps<"header" | "content" | "footer">;
|
|
131
|
+
*
|
|
132
|
+
* // Pattern Two (some slots can have different children type)
|
|
133
|
+
* type SlotProps = GetSlotComponentProps<"header", React.ReactNode> | GetSlotComponentProps<"header", (renderProp: RenderProp) => React.ReactNode>;
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
type GetSlotComponentProps<TName extends string = string, TChildren extends CallbackFn<never, React.ReactNode> | React.ReactNode = CallbackFn<never, React.ReactNode> | React.ReactNode> = {
|
|
137
|
+
children: TChildren;
|
|
138
|
+
/**
|
|
139
|
+
* Name of the slot where content should be rendered
|
|
140
|
+
*/
|
|
141
|
+
name: TName;
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* @description Creates a slot component
|
|
145
|
+
*/
|
|
146
|
+
declare const createSlotComponent: <TSlotComponentProps extends GetSlotComponentProps>() => {
|
|
147
|
+
(props: TSlotComponentProps): React.ReactNode;
|
|
148
|
+
slotSymbol: typeof slotComponentSymbol;
|
|
149
|
+
};
|
|
150
|
+
type SlotWithNameAndSymbol<TSlotComponentProps extends GetSlotComponentProps = GetSlotComponentProps, TOtherProps extends UnknownObject = EmptyObject> = {
|
|
151
|
+
(props: Pick<TSlotComponentProps, "children"> & TOtherProps): React.ReactNode;
|
|
152
|
+
readonly slotName?: TSlotComponentProps["name"];
|
|
153
|
+
readonly slotSymbol?: symbol;
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* @description Adds a slot symbol and name to a slot component passed in
|
|
157
|
+
*/
|
|
158
|
+
declare const withSlotNameAndSymbol: <TSlotComponentProps extends GetSlotComponentProps, TOtherProps extends UnknownObject = EmptyObject>(name: TSlotComponentProps["name"], SlotComponent?: SlotWithNameAndSymbol<TSlotComponentProps, TOtherProps>) => SlotWithNameAndSymbol<TSlotComponentProps, TOtherProps>;
|
|
159
|
+
//#endregion
|
|
22
160
|
//#region src/utils/mergeProps.d.ts
|
|
23
|
-
type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : "") extends ((param: infer TParam) => void) ? TParam : "";
|
|
161
|
+
type UnionToIntersection$1<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : "") extends ((param: infer TParam) => void) ? TParam : "";
|
|
24
162
|
/**
|
|
25
163
|
* Merges multiple sets of React props.
|
|
26
164
|
*
|
|
@@ -35,7 +173,7 @@ type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) =>
|
|
|
35
173
|
* @param props props to merge.
|
|
36
174
|
* @returns the merged props.
|
|
37
175
|
*/
|
|
38
|
-
declare const mergeProps: <TProps extends Record<never, never>>(...propsObjectArray: Array<TProps | undefined>) => UnionToIntersection<TProps>;
|
|
176
|
+
declare const mergeProps: <TProps extends Record<never, never>>(...propsObjectArray: Array<TProps | undefined>) => UnionToIntersection$1<TProps>;
|
|
39
177
|
//#endregion
|
|
40
178
|
//#region src/utils/mergeTwoProps.d.ts
|
|
41
179
|
declare const mergeTwoProps: <TProps extends Record<never, never>>(formerProps: TProps | undefined, latterProps: TProps | undefined) => TProps;
|
|
@@ -84,5 +222,5 @@ type InferRemainingProps<TElement extends React.ElementType, TProps> = Omit<Infe
|
|
|
84
222
|
type MergedGivenPropsWithAs<TElement extends React.ElementType, TProps> = Prettify<Omit<AsProp<TElement>, keyof TProps> & TProps>;
|
|
85
223
|
type PolymorphicProps<TElement extends React.ElementType, TProps extends AnyObject = NonNullable<unknown>> = MergedGivenPropsWithAs<TElement, TProps> & InferRemainingProps<TElement, TProps>;
|
|
86
224
|
//#endregion
|
|
87
|
-
export { AsProp, CssWithCustomProperties, DefaultRenderErrorMessages, DefaultRenderItemErrorMessages, DiscriminatedRenderItemProps, DiscriminatedRenderProps, ForwardedRefType, InferProps, PolymorphicProps, StateSetter, composeEventHandlers, composeRefs, composeTwoEventHandlers, mergeProps, mergeTwoProps, setRef, useComposeRefs };
|
|
225
|
+
export { AsProp, CssWithCustomProperties, DefaultRenderErrorMessages, DefaultRenderItemErrorMessages, DiscriminatedRenderItemProps, DiscriminatedRenderProps, ForwardedRefType, FunctionalComponent, GetSlotComponentProps, GetSlotMapResult, InferProps, PolymorphicProps, StateSetter, composeEventHandlers, composeRefs, composeTwoEventHandlers, createSlotComponent, getMultipleSlots, getRegularChildren, getSingleSlot, getSlotMap, matchesAnySlotComponent, matchesSlotComponent, mergeProps, mergeTwoProps, setRef, slotComponentSymbol, useComposeRefs, withSlotNameAndSymbol };
|
|
88
226
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/esm/utils/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { useCallback } from "react";
|
|
2
|
-
import {
|
|
1
|
+
import { Fragment, isValidElement, useCallback } from "react";
|
|
2
|
+
import { toArray } from "@zayne-labs/toolkit-core";
|
|
3
|
+
import { AssertionError, isArray, isFunction, isObject } from "@zayne-labs/toolkit-type-helpers";
|
|
3
4
|
|
|
4
5
|
//#region src/utils/composeEventHandlers.ts
|
|
5
6
|
const isSyntheticEvent = (event) => {
|
|
@@ -60,6 +61,168 @@ const useComposeRefs = (...refs) => {
|
|
|
60
61
|
return mergedRef;
|
|
61
62
|
};
|
|
62
63
|
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/utils/getSlot/getSlot.ts
|
|
66
|
+
const isWithSlotSymbol = (component) => {
|
|
67
|
+
return "slotSymbol" in component && Boolean(component.slotSymbol);
|
|
68
|
+
};
|
|
69
|
+
const isWithSlotReference = (component) => {
|
|
70
|
+
return "slotReference" in component && Boolean(component.slotReference);
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* @description Checks if a react child (within the children array) matches the provided SlotComponent using multiple matching strategies:
|
|
74
|
+
* 1. Matches by slot symbol property
|
|
75
|
+
* 2. Matches by component name
|
|
76
|
+
*/
|
|
77
|
+
const matchesSlotComponent = (child, SlotComponent) => {
|
|
78
|
+
if (!isValidElement(child) || !isFunction(child.type)) return false;
|
|
79
|
+
const resolvedChildType = isWithSlotReference(child.type) ? child.type.slotReference : child.type;
|
|
80
|
+
const hasMatchingSlotSymbol = isWithSlotSymbol(resolvedChildType) && isWithSlotSymbol(SlotComponent) && resolvedChildType.slotSymbol === SlotComponent.slotSymbol;
|
|
81
|
+
if (hasMatchingSlotSymbol) return true;
|
|
82
|
+
if (child.type.name === SlotComponent.name) return true;
|
|
83
|
+
return false;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* @description Checks if a react child (within the children array) matches any of the provided SlotComponents.
|
|
87
|
+
*/
|
|
88
|
+
const matchesAnySlotComponent = (child, SlotComponents) => {
|
|
89
|
+
const matchesSlot = SlotComponents.some((SlotComponent) => matchesSlotComponent(child, SlotComponent));
|
|
90
|
+
return matchesSlot;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* @description Counts how many times a given slot component appears in an array of children
|
|
94
|
+
* @internal
|
|
95
|
+
*/
|
|
96
|
+
const calculateSlotOccurrences = (childrenArray, SlotComponent) => {
|
|
97
|
+
let count = 0;
|
|
98
|
+
for (const child of childrenArray) {
|
|
99
|
+
if (!matchesSlotComponent(child, SlotComponent)) continue;
|
|
100
|
+
count += 1;
|
|
101
|
+
}
|
|
102
|
+
return count;
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* @description Retrieves a single slot element from a collection of React children that matches the provided SlotComponent component.
|
|
106
|
+
*
|
|
107
|
+
* @throws { AssertionError } when throwOnMultipleSlotMatch is true and multiple slots are found
|
|
108
|
+
*/
|
|
109
|
+
const getSingleSlot = (children, SlotComponent, options = {}) => {
|
|
110
|
+
const { errorMessage = "Only one instance of the SlotComponent is allowed", throwOnMultipleSlotMatch = false } = options;
|
|
111
|
+
const actualChildren = isValidElement(children) && children.type === Fragment ? children.props.children : children;
|
|
112
|
+
const childrenArray = toArray(actualChildren);
|
|
113
|
+
const shouldThrow = throwOnMultipleSlotMatch && calculateSlotOccurrences(childrenArray, SlotComponent) > 1;
|
|
114
|
+
if (shouldThrow) throw new AssertionError(errorMessage);
|
|
115
|
+
const slotElement = childrenArray.find((child) => matchesSlotComponent(child, SlotComponent));
|
|
116
|
+
return slotElement;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* @description The same as getSingleSlot, but for multiple slot components
|
|
120
|
+
*/
|
|
121
|
+
const getMultipleSlots = (children, SlotComponents, options) => {
|
|
122
|
+
const { errorMessage, throwOnMultipleSlotMatch } = options ?? {};
|
|
123
|
+
const slots = SlotComponents.map((SlotComponent, index) => getSingleSlot(children, SlotComponent, {
|
|
124
|
+
errorMessage: isArray(errorMessage) ? errorMessage[index] : errorMessage,
|
|
125
|
+
throwOnMultipleSlotMatch: isArray(throwOnMultipleSlotMatch) ? throwOnMultipleSlotMatch[index] : throwOnMultipleSlotMatch
|
|
126
|
+
}));
|
|
127
|
+
const regularChildren = getRegularChildren(children, SlotComponents);
|
|
128
|
+
return {
|
|
129
|
+
regularChildren,
|
|
130
|
+
slots
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* @description Returns all children that are not slot elements (i.e., don't match any of the provided slot components)
|
|
135
|
+
*/
|
|
136
|
+
const getRegularChildren = (children, SlotComponentOrComponents) => {
|
|
137
|
+
const actualChildren = isValidElement(children) && children.type === Fragment ? children.props.children : children;
|
|
138
|
+
const childrenArray = toArray(actualChildren);
|
|
139
|
+
const regularChildren = childrenArray.filter((child) => !matchesAnySlotComponent(child, toArray(SlotComponentOrComponents)));
|
|
140
|
+
return regularChildren;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
//#endregion
|
|
144
|
+
//#region src/utils/getSlotMap/getSlotMap.ts
|
|
145
|
+
/**
|
|
146
|
+
* Symbol used to identify SlotComponent instances
|
|
147
|
+
*/
|
|
148
|
+
const slotComponentSymbol = Symbol("slot-component");
|
|
149
|
+
/**
|
|
150
|
+
* @description Creates a map of named slots from React children. Returns an object mapping slot names to their children,
|
|
151
|
+
* with a default slot for unmatched children.
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```tsx
|
|
155
|
+
* import { type GetSlotComponentProps, SlotComponent } from "@zayne-labs/toolkit-react/utils"
|
|
156
|
+
*
|
|
157
|
+
* type SlotProps = GetSlotComponentProps<"header" | "footer">;
|
|
158
|
+
*
|
|
159
|
+
* function Parent({ children }: { children: React.ReactNode }) {
|
|
160
|
+
* const slots = getSlotMap<SlotProps>(children);
|
|
161
|
+
*
|
|
162
|
+
* return (
|
|
163
|
+
* <div>
|
|
164
|
+
* <header>{slots.header}</header>
|
|
165
|
+
* <main>{slots.default}</main>
|
|
166
|
+
* <footer>{slots.footer}</footer>
|
|
167
|
+
* </div>
|
|
168
|
+
* );
|
|
169
|
+
* }
|
|
170
|
+
* ```
|
|
171
|
+
*
|
|
172
|
+
* Usage:
|
|
173
|
+
* ```tsx
|
|
174
|
+
* <Parent>
|
|
175
|
+
* <SlotComponent name="header">Header Content</SlotComponent>
|
|
176
|
+
* <div>Random stuff</div>
|
|
177
|
+
* <SlotComponent name="footer">Footer Content</SlotComponent>
|
|
178
|
+
* </Parent>
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
const getSlotMap = (children) => {
|
|
182
|
+
const slots = { default: [] };
|
|
183
|
+
const isFragment = isValidElement(children) && children.type === Fragment;
|
|
184
|
+
const actualChildren = isFragment ? children.props.children : children;
|
|
185
|
+
const childrenArray = toArray(actualChildren);
|
|
186
|
+
for (const child of childrenArray) {
|
|
187
|
+
if (!isValidElement(child) || !isFunction(child.type)) {
|
|
188
|
+
slots.default.push(child);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const childType = child.type;
|
|
192
|
+
const isSlotElement = childType.slotSymbol === slotComponentSymbol && Boolean(childType.slotName ?? child.props.name);
|
|
193
|
+
if (!isSlotElement) {
|
|
194
|
+
slots.default.push(child);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
const slotName = childType.slotName ?? child.props.name;
|
|
198
|
+
if (slotName === "default") {
|
|
199
|
+
slots.default.push(child);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
slots[slotName] = child;
|
|
203
|
+
}
|
|
204
|
+
return slots;
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* @description Creates a slot component
|
|
208
|
+
*/
|
|
209
|
+
const createSlotComponent = () => {
|
|
210
|
+
const SlotComponent = (props) => props.children;
|
|
211
|
+
SlotComponent.slotSymbol = slotComponentSymbol;
|
|
212
|
+
return SlotComponent;
|
|
213
|
+
};
|
|
214
|
+
function DefaultSlotComponent(props) {
|
|
215
|
+
return props.children;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* @description Adds a slot symbol and name to a slot component passed in
|
|
219
|
+
*/
|
|
220
|
+
const withSlotNameAndSymbol = (name, SlotComponent = DefaultSlotComponent) => {
|
|
221
|
+
SlotComponent.slotSymbol = slotComponentSymbol;
|
|
222
|
+
SlotComponent.slotName = name;
|
|
223
|
+
return SlotComponent;
|
|
224
|
+
};
|
|
225
|
+
|
|
63
226
|
//#endregion
|
|
64
227
|
//#region src/utils/mergeTwoProps.ts
|
|
65
228
|
const isEventHandler = (key, value) => {
|
|
@@ -126,5 +289,5 @@ const mergeProps = (...propsObjectArray) => {
|
|
|
126
289
|
};
|
|
127
290
|
|
|
128
291
|
//#endregion
|
|
129
|
-
export { composeEventHandlers, composeRefs, composeTwoEventHandlers, mergeProps, mergeTwoProps, setRef, useComposeRefs };
|
|
292
|
+
export { composeEventHandlers, composeRefs, composeTwoEventHandlers, createSlotComponent, getMultipleSlots, getRegularChildren, getSingleSlot, getSlotMap, matchesAnySlotComponent, matchesSlotComponent, mergeProps, mergeTwoProps, setRef, slotComponentSymbol, useComposeRefs, withSlotNameAndSymbol };
|
|
130
293
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["result","accumulatedHandlers: AnyFunction | undefined","mergedRefCallBack: RefCallback<TRef>","accumulatedProps: Record<string, unknown>"],"sources":["../../../src/utils/composeEventHandlers.ts","../../../src/utils/composeRefs.ts","../../../src/utils/mergeTwoProps.ts","../../../src/utils/mergeProps.ts"],"sourcesContent":["import { type AnyFunction, isObject } from \"@zayne-labs/toolkit-type-helpers\";\n\nconst isSyntheticEvent = (event: unknown): event is React.SyntheticEvent => {\n\treturn isObject(event) && Object.hasOwn(event, \"nativeEvent\");\n};\n\nexport const composeTwoEventHandlers = (\n\tformerHandler: AnyFunction | undefined,\n\tlatterHandler: AnyFunction | undefined\n) => {\n\tconst mergedEventHandler = (event: unknown) => {\n\t\tif (isSyntheticEvent(event)) {\n\t\t\tconst result = latterHandler?.(event) as unknown;\n\n\t\t\tif (!event.defaultPrevented) {\n\t\t\t\tformerHandler?.(event);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\tconst result = latterHandler?.(event) as unknown;\n\t\tformerHandler?.(event);\n\t\treturn result;\n\t};\n\n\treturn mergedEventHandler;\n};\n\nexport const composeEventHandlers = (...eventHandlerArray: Array<AnyFunction | undefined>) => {\n\tconst mergedEventHandler = (event: unknown) => {\n\t\tif (eventHandlerArray.length === 0) return;\n\n\t\tif (eventHandlerArray.length === 1) {\n\t\t\treturn eventHandlerArray[0]?.(event) as unknown;\n\t\t}\n\n\t\tlet accumulatedHandlers: AnyFunction | undefined;\n\n\t\tfor (const eventHandler of eventHandlerArray) {\n\t\t\tif (!eventHandler) continue;\n\n\t\t\taccumulatedHandlers = composeTwoEventHandlers(accumulatedHandlers, eventHandler);\n\t\t}\n\n\t\treturn accumulatedHandlers?.(event) as unknown;\n\t};\n\n\treturn mergedEventHandler;\n};\n","import { isFunction } from \"@zayne-labs/toolkit-type-helpers\";\nimport { type RefCallback, useCallback } from \"react\";\n\ntype PossibleRef<TRef extends HTMLElement> = React.Ref<TRef> | undefined;\n\n/**\n * @description Set a given ref to a given value.\n *\n * This utility takes care of different types of refs: callback refs and RefObject(s)\n */\nexport const setRef = <TRef extends HTMLElement>(\n\tref: PossibleRef<TRef>,\n\tnode: TRef | null\n): ReturnType<RefCallback<TRef>> => {\n\tif (!ref) return;\n\n\tif (isFunction(ref)) {\n\t\treturn ref(node);\n\t}\n\n\t// eslint-disable-next-line no-param-reassign -- Mutation is needed here\n\tref.current = node;\n};\n\n/**\n * @description A utility to combine refs. Accepts callback refs and RefObject(s)\n */\nexport const composeRefs = <TRef extends HTMLElement>(\n\t...refs: Array<PossibleRef<TRef>>\n): RefCallback<TRef> => {\n\tconst mergedRefCallBack: RefCallback<TRef> = (node) => {\n\t\tconst cleanupFnArray = refs.map((ref) => setRef(ref, node));\n\n\t\tconst cleanupFn = () => cleanupFnArray.forEach((cleanup) => cleanup?.());\n\n\t\treturn cleanupFn;\n\t};\n\n\treturn mergedRefCallBack;\n};\n\nexport const useComposeRefs = <TRef extends HTMLElement>(...refs: Array<PossibleRef<TRef>>) => {\n\t// eslint-disable-next-line react-hooks/exhaustive-deps -- Allow\n\tconst mergedRef = useCallback(() => composeRefs(...refs), refs);\n\n\treturn mergedRef;\n};\n","import { type AnyFunction, isFunction } from \"@zayne-labs/toolkit-type-helpers\";\nimport { composeTwoEventHandlers } from \"./composeEventHandlers\";\n\n// == This approach is more efficient than using a regex.\nconst isEventHandler = (key: string, value: unknown): value is AnyFunction => {\n\tconst thirdCharCode = key.codePointAt(2);\n\n\tif (!isFunction(value) || thirdCharCode === undefined) {\n\t\treturn false;\n\t}\n\n\tconst isHandler = key.startsWith(\"on\") && thirdCharCode >= 65 /* A */ && thirdCharCode <= 90; /* Z */\n\n\treturn isHandler;\n};\n\nconst mergeTwoClassNames = (formerClassName: string | undefined, latterClassName: string | undefined) => {\n\tif (!latterClassName || !formerClassName) {\n\t\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Logical OR is fit for this case\n\t\treturn latterClassName || formerClassName;\n\t}\n\n\t// eslint-disable-next-line prefer-template -- String concatenation is more performant than template literals in this case\n\treturn formerClassName + \" \" + latterClassName;\n};\n\nexport const mergeTwoProps = <TProps extends Record<never, never>>(\n\tformerProps: TProps | undefined,\n\tlatterProps: TProps | undefined\n): TProps => {\n\t// == If no props are provided, return an empty object\n\tif (!latterProps || !formerProps) {\n\t\treturn latterProps ?? formerProps ?? ({} as TProps);\n\t}\n\n\tconst propsAccumulator = { ...formerProps } as Record<string, unknown>;\n\n\tfor (const latterPropName of Object.keys(latterProps)) {\n\t\tconst formerPropValue = (formerProps as Record<string, unknown>)[latterPropName];\n\t\tconst latterPropValue = (latterProps as Record<string, unknown>)[latterPropName];\n\n\t\t// == If the prop is `className` or `class`, we merge them\n\t\tif (latterPropName === \"className\" || latterPropName === \"class\") {\n\t\t\tpropsAccumulator[latterPropName] = mergeTwoClassNames(\n\t\t\t\tformerPropValue as string,\n\t\t\t\tlatterPropValue as string\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// == If the prop is `style`, we merge them\n\t\tif (latterPropName === \"style\") {\n\t\t\tpropsAccumulator[latterPropName] = {\n\t\t\t\t...(formerPropValue as object),\n\t\t\t\t...(latterPropValue as object),\n\t\t\t};\n\t\t\tcontinue;\n\t\t}\n\n\t\t// == If the handler exists on both, we compose them\n\t\tif (isEventHandler(latterPropName, latterPropValue)) {\n\t\t\tpropsAccumulator[latterPropName] = composeTwoEventHandlers(\n\t\t\t\tformerPropValue as AnyFunction | undefined,\n\t\t\t\tlatterPropValue\n\t\t\t);\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t// == latterProps override by default\n\t\tpropsAccumulator[latterPropName] = latterPropValue;\n\t}\n\n\treturn propsAccumulator as TProps;\n};\n","import { mergeTwoProps } from \"./mergeTwoProps\";\n\ntype UnionToIntersection<TUnion> =\n\t(TUnion extends unknown ? (param: TUnion) => void : \"\") extends (param: infer TParam) => void ? TParam\n\t:\t\"\";\n\n/**\n * Merges multiple sets of React props.\n *\n * - It follows the Object.assign pattern where the rightmost object's fields overwrite\n * the conflicting ones from others. This doesn't apply to event handlers, `className` and `style` props.\n * - Event handlers are merged such that they are called in sequence (the rightmost one being called first),\n * and allows the user to prevent the previous event handlers from being executed by calling the `preventDefault` method.\n * - It also merges the `className` and `style` props, whereby the classes are concatenated\n * and the rightmost styles overwrite the previous ones.\n *\n * @important **`ref` is not merged.**\n * @param props props to merge.\n * @returns the merged props.\n */\n\nconst mergeProps = <TProps extends Record<never, never>>(\n\t...propsObjectArray: Array<TProps | undefined>\n): UnionToIntersection<TProps> => {\n\tif (propsObjectArray.length === 0) {\n\t\treturn {} as never;\n\t}\n\n\tif (propsObjectArray.length === 1) {\n\t\treturn propsObjectArray[0] as never;\n\t}\n\n\tlet accumulatedProps: Record<string, unknown> = {};\n\n\tfor (const propsObject of propsObjectArray) {\n\t\tif (!propsObject) continue;\n\n\t\taccumulatedProps = mergeTwoProps(accumulatedProps, propsObject);\n\t}\n\n\treturn acc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;AAE1F,QAAO;;AAGR,MAAM,sBAAsB,iBAAqC,oBAAwC;AACxG,KAAI,CAAC,mBAAmB,CAAC,gBAExB,QAAO,mBAAmB;AAI3B,QAAO,kBAAkB,MAAM;;AAGhC,MAAa,iBACZ,aACA,gBACY;AAEZ,KAAI,CAAC,eAAe,CAAC,YACpB,QAAO,eAAe,eAAgB;CAGvC,MAAM,mBAAmB,EAAE,GAAG;AAE9B,MAAK,MAAM,kBAAkB,OAAO,KAAK,cAAc;EACtD,MAAM,kBAAmB,YAAwC;EACjE,MAAM,kBAAmB,YAAwC;AAGjE,MAAI,mBAAmB,eAAe,mBAAmB,SAAS;AACjE,oBAAiB,kBAAkB,mBAClC,iBACA;AAED;;AAID,MAAI,mBAAmB,SAAS;AAC/B,oBAAiB,kBAAkB;IAClC,GAAI;IACJ,GAAI;;AAEL;;AAID,MAAI,eAAe,gBAAgB,kBAAkB;AACpD,oBAAiB,kBAAkB,wBAClC,iBACA;AAGD;;AAID,mBAAiB,kBAAkB;;AAGpC,QAAO;;;;;;;;;;;;;;;;;;;ACpDR,MAAM,cACL,GAAG,qBAC8B;AACjC,KAAI,iBAAiB,WAAW,EAC/B,QAAO;AAGR,KAAI,iBAAiB,WAAW,EAC/B,QAAO,iBAAiB;CAGzB,IAAIC,mBAA4C;AAEhD,MAAK,MAAM,eAAe,kBAAkB;AAC3C,MAAI,CAAC,YAAa;AAElB,qBAAmB,cAAc,kBAAkB;;AAGpD,QAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["result","accumulatedHandlers: AnyFunction | undefined","mergedRefCallBack: RefCallback<TRef>","ReactFragment","slots: Record<string, TSlotComponentProps[\"children\"]> & { default: React.ReactNode[] }","ReactFragment","accumulatedProps: Record<string, unknown>"],"sources":["../../../src/utils/composeEventHandlers.ts","../../../src/utils/composeRefs.ts","../../../src/utils/getSlot/getSlot.ts","../../../src/utils/getSlotMap/getSlotMap.ts","../../../src/utils/mergeTwoProps.ts","../../../src/utils/mergeProps.ts"],"sourcesContent":["import { type AnyFunction, isObject } from \"@zayne-labs/toolkit-type-helpers\";\n\nconst isSyntheticEvent = (event: unknown): event is React.SyntheticEvent => {\n\treturn isObject(event) && Object.hasOwn(event, \"nativeEvent\");\n};\n\nexport const composeTwoEventHandlers = (\n\tformerHandler: AnyFunction | undefined,\n\tlatterHandler: AnyFunction | undefined\n) => {\n\tconst mergedEventHandler = (event: unknown) => {\n\t\tif (isSyntheticEvent(event)) {\n\t\t\tconst result = latterHandler?.(event) as unknown;\n\n\t\t\tif (!event.defaultPrevented) {\n\t\t\t\tformerHandler?.(event);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\tconst result = latterHandler?.(event) as unknown;\n\t\tformerHandler?.(event);\n\t\treturn result;\n\t};\n\n\treturn mergedEventHandler;\n};\n\nexport const composeEventHandlers = (...eventHandlerArray: Array<AnyFunction | undefined>) => {\n\tconst mergedEventHandler = (event: unknown) => {\n\t\tif (eventHandlerArray.length === 0) return;\n\n\t\tif (eventHandlerArray.length === 1) {\n\t\t\treturn eventHandlerArray[0]?.(event) as unknown;\n\t\t}\n\n\t\tlet accumulatedHandlers: AnyFunction | undefined;\n\n\t\tfor (const eventHandler of eventHandlerArray) {\n\t\t\tif (!eventHandler) continue;\n\n\t\t\taccumulatedHandlers = composeTwoEventHandlers(accumulatedHandlers, eventHandler);\n\t\t}\n\n\t\treturn accumulatedHandlers?.(event) as unknown;\n\t};\n\n\treturn mergedEventHandler;\n};\n","import { isFunction } from \"@zayne-labs/toolkit-type-helpers\";\nimport { type RefCallback, useCallback } from \"react\";\n\ntype PossibleRef<TRef extends HTMLElement> = React.Ref<TRef> | undefined;\n\n/**\n * @description Set a given ref to a given value.\n *\n * This utility takes care of different types of refs: callback refs and RefObject(s)\n */\nexport const setRef = <TRef extends HTMLElement>(\n\tref: PossibleRef<TRef>,\n\tnode: TRef | null\n): ReturnType<RefCallback<TRef>> => {\n\tif (!ref) return;\n\n\tif (isFunction(ref)) {\n\t\treturn ref(node);\n\t}\n\n\t// eslint-disable-next-line no-param-reassign -- Mutation is needed here\n\tref.current = node;\n};\n\n/**\n * @description A utility to combine refs. Accepts callback refs and RefObject(s)\n */\nexport const composeRefs = <TRef extends HTMLElement>(\n\t...refs: Array<PossibleRef<TRef>>\n): RefCallback<TRef> => {\n\tconst mergedRefCallBack: RefCallback<TRef> = (node) => {\n\t\tconst cleanupFnArray = refs.map((ref) => setRef(ref, node));\n\n\t\tconst cleanupFn = () => cleanupFnArray.forEach((cleanup) => cleanup?.());\n\n\t\treturn cleanupFn;\n\t};\n\n\treturn mergedRefCallBack;\n};\n\nexport const useComposeRefs = <TRef extends HTMLElement>(...refs: Array<PossibleRef<TRef>>) => {\n\t// eslint-disable-next-line react-hooks/exhaustive-deps -- Allow\n\tconst mergedRef = useCallback(() => composeRefs(...refs), refs);\n\n\treturn mergedRef;\n};\n","import { toArray } from \"@zayne-labs/toolkit-core\";\nimport type { InferProps } from \"@zayne-labs/toolkit-react/utils\";\nimport {\n\ttype AnyFunction,\n\tAssertionError,\n\ttype Prettify,\n\ttype UnknownObject,\n\tisArray,\n\tisFunction,\n} from \"@zayne-labs/toolkit-type-helpers\";\nimport { Fragment as ReactFragment, isValidElement } from \"react\";\n\nexport type FunctionalComponent<TProps extends UnknownObject = never> = React.FunctionComponent<TProps>;\n\nconst isWithSlotSymbol = <TFunction extends AnyFunction>(\n\tcomponent: TFunction\n): component is Record<\"slotSymbol\", unknown> & TFunction => {\n\treturn \"slotSymbol\" in component && Boolean(component.slotSymbol);\n};\n\nconst isWithSlotReference = <TFunction extends AnyFunction>(\n\tcomponent: TFunction\n): component is Record<\"slotReference\", unknown> & TFunction => {\n\treturn \"slotReference\" in component && Boolean(component.slotReference);\n};\n/**\n * @description Checks if a react child (within the children array) matches the provided SlotComponent using multiple matching strategies:\n * 1. Matches by slot symbol property\n * 2. Matches by component name\n */\n\nexport const matchesSlotComponent = (child: React.ReactNode, SlotComponent: FunctionalComponent) => {\n\tif (!isValidElement(child) || !isFunction(child.type)) {\n\t\treturn false;\n\t}\n\n\tconst resolvedChildType =\n\t\tisWithSlotReference(child.type) ? (child.type.slotReference as FunctionalComponent) : child.type;\n\n\tconst hasMatchingSlotSymbol =\n\t\tisWithSlotSymbol(resolvedChildType)\n\t\t&& isWithSlotSymbol(SlotComponent)\n\t\t&& resolvedChildType.slotSymbol === SlotComponent.slotSymbol;\n\n\tif (hasMatchingSlotSymbol) {\n\t\treturn true;\n\t}\n\n\tif (child.type.name === SlotComponent.name) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n/**\n * @description Checks if a react child (within the children array) matches any of the provided SlotComponents.\n */\nexport const matchesAnySlotComponent = (child: React.ReactNode, SlotComponents: FunctionalComponent[]) => {\n\tconst matchesSlot = SlotComponents.some((SlotComponent) => matchesSlotComponent(child, SlotComponent));\n\n\treturn matchesSlot;\n};\n\ntype SlotOptions = {\n\t/**\n\t * @description The error message to throw when multiple slots are found for a given slot component\n\t */\n\terrorMessage?: string;\n\t/**\n\t * @description When true, an AssertionError will be thrown if multiple slots are found for a given slot component\n\t */\n\tthrowOnMultipleSlotMatch?: boolean;\n};\n\n/**\n * @description Counts how many times a given slot component appears in an array of children\n * @internal\n */\nconst calculateSlotOccurrences = (\n\tchildrenArray: React.ReactNode[],\n\tSlotComponent: FunctionalComponent\n) => {\n\tlet count = 0;\n\n\tfor (const child of childrenArray) {\n\t\tif (!matchesSlotComponent(child, SlotComponent)) continue;\n\n\t\tcount += 1;\n\t}\n\n\treturn count;\n};\n\n/**\n * @description Retrieves a single slot element from a collection of React children that matches the provided SlotComponent component.\n *\n * @throws { AssertionError } when throwOnMultipleSlotMatch is true and multiple slots are found\n */\nexport const getSingleSlot = (\n\tchildren: React.ReactNode,\n\tSlotComponent: FunctionalComponent,\n\toptions: SlotOptions = {}\n) => {\n\tconst {\n\t\terrorMessage = \"Only one instance of the SlotComponent is allowed\",\n\t\tthrowOnMultipleSlotMatch = false,\n\t} = options;\n\n\tconst actualChildren =\n\t\tisValidElement<InferProps<typeof ReactFragment>>(children) && children.type === ReactFragment ?\n\t\t\tchildren.props.children\n\t\t:\tchildren;\n\n\tconst childrenArray = toArray<React.ReactNode>(actualChildren);\n\n\tconst shouldThrow =\n\t\tthrowOnMultipleSlotMatch && calculateSlotOccurrences(childrenArray, SlotComponent) > 1;\n\n\tif (shouldThrow) {\n\t\tthrow new AssertionError(errorMessage);\n\t}\n\n\tconst slotElement = childrenArray.find((child) => matchesSlotComponent(child, SlotComponent));\n\n\treturn slotElement;\n};\n\n// NOTE - You can imitate const type parameter by extending readonly[] | []\n\ntype MultipleSlotsOptions = {\n\t/**\n\t * @description The error message to throw when multiple slots are found for a given slot component\n\t * If a string is provided, the same message will be used for all slot components\n\t * If an array is provided, each string in the array will be used as the errorMessage for the corresponding slot component\n\t */\n\terrorMessage?: string | string[];\n\t/**\n\t * @description When true, an AssertionError will be thrown if multiple slots are found for a given slot component\n\t * If a boolean is provided, the same value will be used for all slot components\n\t * If an array is provided, each boolean in the array will be used as the throwOnMultipleSlotMatch value for the corresponding slot component\n\t */\n\tthrowOnMultipleSlotMatch?: boolean | boolean[];\n};\n\ntype GetMultipleSlotsResult<TSlotComponents extends FunctionalComponent[]> = {\n\tregularChildren: React.ReactNode[];\n\tslots: { [Key in keyof TSlotComponents]: ReturnType<TSlotComponents[Key]> };\n};\n\n/**\n * @description The same as getSingleSlot, but for multiple slot components\n */\nexport const getMultipleSlots = <const TSlotComponents extends FunctionalComponent[]>(\n\tchildren: React.ReactNode,\n\tSlotComponents: TSlotComponents,\n\toptions?: MultipleSlotsOptions\n): Prettify<GetMultipleSlotsResult<TSlotComponents>> => {\n\tconst { errorMessage, throwOnMultipleSlotMatch } = options ?? {};\n\n\tconst slots = SlotComponents.map((SlotComponent, index) =>\n\t\tgetSingleSlot(children, SlotComponent, {\n\t\t\terrorMessage: isArray(errorMessage) ? errorMessage[index] : errorMessage,\n\t\t\tthrowOnMultipleSlotMatch:\n\t\t\t\tisArray(throwOnMultipleSlotMatch) ? throwOnMultipleSlotMatch[index] : throwOnMultipleSlotMatch,\n\t\t})\n\t);\n\n\tconst regularChildren = getRegularChildren(children, SlotComponents);\n\n\treturn { regularChildren, slots } as GetMultipleSlotsResult<TSlotComponents>;\n};\n\n/**\n * @description Returns all children that are not slot elements (i.e., don't match any of the provided slot components)\n */\nexport const getRegularChildren = (\n\tchildren: React.ReactNode,\n\tSlotComponentOrComponents: FunctionalComponent | FunctionalComponent[]\n) => {\n\tconst actualChildren =\n\t\tisValidElement<InferProps<typeof ReactFragment>>(children) && children.type === ReactFragment ?\n\t\t\tchildren.props.children\n\t\t:\tchildren;\n\n\tconst childrenArray = toArray<React.ReactNode>(actualChildren);\n\n\tconst regularChildren = childrenArray.filter(\n\t\t(child) => !matchesAnySlotComponent(child, toArray(SlotComponentOrComponents))\n\t);\n\n\treturn regularChildren;\n};\n","import { toArray } from \"@zayne-labs/toolkit-core\";\nimport type { InferProps } from \"@zayne-labs/toolkit-react/utils\";\nimport {\n\ttype CallbackFn,\n\ttype EmptyObject,\n\ttype Prettify,\n\ttype UnionToIntersection,\n\ttype UnknownObject,\n\tisFunction,\n} from \"@zayne-labs/toolkit-type-helpers\";\nimport { Fragment as ReactFragment, isValidElement } from \"react\";\n\ntype GetSlotName<TSlotComponentProps extends GetSlotComponentProps> =\n\tstring extends TSlotComponentProps[\"name\"] ? never\n\t: \"default\" extends TSlotComponentProps[\"name\"] ? never\n\t: TSlotComponentProps[\"name\"];\n\ntype GetSpecificSlotsType<TSlotComponentProps extends GetSlotComponentProps> = {\n\t// This conditional before the remapping will prevent an Indexed Record type from showing up if the props are not passed, enhancing type safety\n\t[TName in keyof TSlotComponentProps as GetSlotName<TSlotComponentProps>]: Extract<\n\t\tTSlotComponentProps[\"children\"],\n\t\tReact.ReactNode\n\t>;\n};\n\n/**\n * Maps slot names to their corresponding children types\n */\nexport type GetSlotMapResult<TSlotComponentProps extends GetSlotComponentProps> = UnionToIntersection<\n\tGetSpecificSlotsType<TSlotComponentProps>\n> & { default: React.ReactNode[] };\n\n/**\n * Symbol used to identify SlotComponent instances\n */\nexport const slotComponentSymbol = Symbol(\"slot-component\");\n\n/**\n * @description Creates a map of named slots from React children. Returns an object mapping slot names to their children,\n * with a default slot for unmatched children.\n *\n * @example\n * ```tsx\n * import { type GetSlotComponentProps, SlotComponent } from \"@zayne-labs/toolkit-react/utils\"\n *\n * type SlotProps = GetSlotComponentProps<\"header\" | \"footer\">;\n *\n * function Parent({ children }: { children: React.ReactNode }) {\n * const slots = getSlotMap<SlotProps>(children);\n *\n * return (\n * <div>\n * <header>{slots.header}</header>\n * <main>{slots.default}</main>\n * <footer>{slots.footer}</footer>\n * </div>\n * );\n * }\n * ```\n *\n * Usage:\n * ```tsx\n * <Parent>\n * <SlotComponent name=\"header\">Header Content</SlotComponent>\n * <div>Random stuff</div>\n * <SlotComponent name=\"footer\">Footer Content</SlotComponent>\n * </Parent>\n * ```\n */\nexport const getSlotMap = <TSlotComponentProps extends GetSlotComponentProps>(\n\tchildren: React.ReactNode\n): Prettify<GetSlotMapResult<TSlotComponentProps>> => {\n\tconst slots: Record<string, TSlotComponentProps[\"children\"]> & { default: React.ReactNode[] } = {\n\t\tdefault: [],\n\t};\n\n\tconst isFragment = isValidElement<InferProps<HTMLElement>>(children) && children.type === ReactFragment;\n\n\tconst actualChildren = isFragment ? children.props.children : children;\n\n\tconst childrenArray = toArray<React.ReactNode>(actualChildren);\n\n\tfor (const child of childrenArray) {\n\t\tif (!isValidElement<TSlotComponentProps>(child) || !isFunction(child.type)) {\n\t\t\tslots.default.push(child);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst childType = child.type as SlotWithNameAndSymbol;\n\n\t\tconst isSlotElement =\n\t\t\tchildType.slotSymbol === slotComponentSymbol && Boolean(childType.slotName ?? child.props.name);\n\n\t\tif (!isSlotElement) {\n\t\t\tslots.default.push(child);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst slotName = childType.slotName ?? child.props.name;\n\n\t\tif (slotName === \"default\") {\n\t\t\tslots.default.push(child);\n\t\t\tcontinue;\n\t\t}\n\n\t\tslots[slotName] = child;\n\t}\n\n\treturn slots as GetSlotMapResult<TSlotComponentProps>;\n};\n\n/**\n * @description Produce props for the SlotComponent\n *\n * @example\n * ```ts\n * // Pattern One (slot or slots have same children type, which is just React.ReactNode by default)\n * type SlotProps = GetSlotComponentProps<\"header\" | \"content\" | \"footer\">;\n *\n * // Pattern Two (some slots can have different children type)\n * type SlotProps = GetSlotComponentProps<\"header\", React.ReactNode> | GetSlotComponentProps<\"header\", (renderProp: RenderProp) => React.ReactNode>;\n * ```\n */\nexport type GetSlotComponentProps<\n\tTName extends string = string,\n\tTChildren extends CallbackFn<never, React.ReactNode> | React.ReactNode =\n\t\t| CallbackFn<never, React.ReactNode>\n\t\t| React.ReactNode,\n> = {\n\tchildren: TChildren;\n\t/**\n\t * Name of the slot where content should be rendered\n\t */\n\tname: TName;\n};\n\n/**\n * @description Creates a slot component\n */\nexport const createSlotComponent = <TSlotComponentProps extends GetSlotComponentProps>() => {\n\tconst SlotComponent = (props: TSlotComponentProps) => props.children as React.ReactNode;\n\n\tSlotComponent.slotSymbol = slotComponentSymbol;\n\n\treturn SlotComponent;\n};\n\ntype SlotWithNameAndSymbol<\n\tTSlotComponentProps extends GetSlotComponentProps = GetSlotComponentProps,\n\tTOtherProps extends UnknownObject = EmptyObject,\n> = {\n\t(props: Pick<TSlotComponentProps, \"children\"> & TOtherProps): React.ReactNode;\n\treadonly slotName?: TSlotComponentProps[\"name\"];\n\treadonly slotSymbol?: symbol;\n};\n\nfunction DefaultSlotComponent(props: Pick<GetSlotComponentProps, \"children\">): React.ReactNode {\n\treturn props.children as React.ReactNode;\n}\n\n/**\n * @description Adds a slot symbol and name to a slot component passed in\n */\nexport const withSlotNameAndSymbol = <\n\tTSlotComponentProps extends GetSlotComponentProps,\n\tTOtherProps extends UnknownObject = EmptyObject,\n>(\n\tname: TSlotComponentProps[\"name\"],\n\tSlotComponent: SlotWithNameAndSymbol<TSlotComponentProps, TOtherProps> = DefaultSlotComponent\n) => {\n\t/* eslint-disable no-param-reassign -- This is necessary */\n\t// @ts-expect-error -- This is necessary for the time being, to prevent type errors and accidental overrides on consumer side\n\tSlotComponent.slotSymbol = slotComponentSymbol;\n\t// @ts-expect-error -- This is necessary for the time being, to prevent type errors and accidental overrides on consumer side\n\tSlotComponent.slotName = name;\n\n\t/* eslint-enable no-param-reassign -- This is necessary */\n\n\treturn SlotComponent;\n};\n","import { type AnyFunction, isFunction } from \"@zayne-labs/toolkit-type-helpers\";\nimport { composeTwoEventHandlers } from \"./composeEventHandlers\";\n\n// == This approach is more efficient than using a regex.\nconst isEventHandler = (key: string, value: unknown): value is AnyFunction => {\n\tconst thirdCharCode = key.codePointAt(2);\n\n\tif (!isFunction(value) || thirdCharCode === undefined) {\n\t\treturn false;\n\t}\n\n\tconst isHandler = key.startsWith(\"on\") && thirdCharCode >= 65 /* A */ && thirdCharCode <= 90; /* Z */\n\n\treturn isHandler;\n};\n\nconst mergeTwoClassNames = (formerClassName: string | undefined, latterClassName: string | undefined) => {\n\tif (!latterClassName || !formerClassName) {\n\t\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Logical OR is fit for this case\n\t\treturn latterClassName || formerClassName;\n\t}\n\n\t// eslint-disable-next-line prefer-template -- String concatenation is more performant than template literals in this case\n\treturn formerClassName + \" \" + latterClassName;\n};\n\nexport const mergeTwoProps = <TProps extends Record<never, never>>(\n\tformerProps: TProps | undefined,\n\tlatterProps: TProps | undefined\n): TProps => {\n\t// == If no props are provided, return an empty object\n\tif (!latterProps || !formerProps) {\n\t\treturn latterProps ?? formerProps ?? ({} as TProps);\n\t}\n\n\tconst propsAccumulator = { ...formerProps } as Record<string, unknown>;\n\n\tfor (const latterPropName of Object.keys(latterProps)) {\n\t\tconst formerPropValue = (formerProps as Record<string, unknown>)[latterPropName];\n\t\tconst latterPropValue = (latterProps as Record<string, unknown>)[latterPropName];\n\n\t\t// == If the prop is `className` or `class`, we merge them\n\t\tif (latterPropName === \"className\" || latterPropName === \"class\") {\n\t\t\tpropsAccumulator[latterPropName] = mergeTwoClassNames(\n\t\t\t\tformerPropValue as string,\n\t\t\t\tlatterPropValue as string\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// == If the prop is `style`, we merge them\n\t\tif (latterPropName === \"style\") {\n\t\t\tpropsAccumulator[latterPropName] = {\n\t\t\t\t...(formerPropValue as object),\n\t\t\t\t...(latterPropValue as object),\n\t\t\t};\n\t\t\tcontinue;\n\t\t}\n\n\t\t// == If the handler exists on both, we compose them\n\t\tif (isEventHandler(latterPropName, latterPropValue)) {\n\t\t\tpropsAccumulator[latterPropName] = composeTwoEventHandlers(\n\t\t\t\tformerPropValue as AnyFunction | undefined,\n\t\t\t\tlatterPropValue\n\t\t\t);\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t// == latterProps override by default\n\t\tpropsAccumulator[latterPropName] = latterPropValue;\n\t}\n\n\treturn propsAccumulator as TProps;\n};\n","import { mergeTwoProps } from \"./mergeTwoProps\";\n\ntype UnionToIntersection<TUnion> =\n\t(TUnion extends unknown ? (param: TUnion) => void : \"\") extends (param: infer TParam) => void ? TParam\n\t:\t\"\";\n\n/**\n * Merges multiple sets of React props.\n *\n * - It follows the Object.assign pattern where the rightmost object's fields overwrite\n * the conflicting ones from others. This doesn't apply to event handlers, `className` and `style` props.\n * - Event handlers are merged such that they are called in sequence (the rightmost one being called first),\n * and allows the user to prevent the previous event handlers from being executed by calling the `preventDefault` method.\n * - It also merges the `className` and `style` props, whereby the classes are concatenated\n * and the rightmost styles overwrite the previous ones.\n *\n * @important **`ref` is not merged.**\n * @param props props to merge.\n * @returns the merged props.\n */\n\nconst mergeProps = <TProps extends Record<never, never>>(\n\t...propsObjectArray: Array<TProps | undefined>\n): UnionToIntersection<TProps> => {\n\tif (propsObjectArray.length === 0) {\n\t\treturn {} as never;\n\t}\n\n\tif (propsObjectArray.length === 1) {\n\t\treturn propsObjectArray[0] as never;\n\t}\n\n\tlet accumulatedProps: Record<string, unknown> = {};\n\n\tfor (const propsObject of propsObjectArray) {\n\t\tif (!propsObject) continue;\n\n\t\taccumulatedProps = mergeTwoProps(accumulatedProps, propsObject);\n\t}\n\n\treturn accumulatedProps as never;\n};\n\nexport { mergeProps };\n"],"mappings":";;;;;AAEA,MAAM,oBAAoB,UAAkD;AAC3E,QAAO,SAAS,UAAU,OAAO,OAAO,OAAO;;AAGhD,MAAa,2BACZ,eACA,kBACI;CACJ,MAAM,sBAAsB,UAAmB;AAC9C,MAAI,iBAAiB,QAAQ;GAC5B,MAAMA,WAAS,gBAAgB;AAE/B,OAAI,CAAC,MAAM,iBACV,iBAAgB;AAGjB,UAAOA;;EAGR,MAAM,SAAS,gBAAgB;AAC/B,kBAAgB;AAChB,SAAO;;AAGR,QAAO;;AAGR,MAAa,wBAAwB,GAAG,sBAAsD;CAC7F,MAAM,sBAAsB,UAAmB;AAC9C,MAAI,kBAAkB,WAAW,EAAG;AAEpC,MAAI,kBAAkB,WAAW,EAChC,QAAO,kBAAkB,KAAK;EAG/B,IAAIC;AAEJ,OAAK,MAAM,gBAAgB,mBAAmB;AAC7C,OAAI,CAAC,aAAc;AAEnB,yBAAsB,wBAAwB,qBAAqB;;AAGpE,SAAO,sBAAsB;;AAG9B,QAAO;;;;;;;;;;ACtCR,MAAa,UACZ,KACA,SACmC;AACnC,KAAI,CAAC,IAAK;AAEV,KAAI,WAAW,KACd,QAAO,IAAI;AAIZ,KAAI,UAAU;;;;;AAMf,MAAa,eACZ,GAAG,SACoB;CACvB,MAAMC,qBAAwC,SAAS;EACtD,MAAM,iBAAiB,KAAK,KAAK,QAAQ,OAAO,KAAK;EAErD,MAAM,kBAAkB,eAAe,SAAS,YAAY;AAE5D,SAAO;;AAGR,QAAO;;AAGR,MAAa,kBAA4C,GAAG,SAAmC;CAE9F,MAAM,YAAY,kBAAkB,YAAY,GAAG,OAAO;AAE1D,QAAO;;;;;AC/BR,MAAM,oB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kBAAkB,KAAa,UAAyC;CAC7E,MAAM,gBAAgB,IAAI,YAAY;AAEtC,KAAI,CAAC,WAAW,UAAU,kBAAkB,OAC3C,QAAO;CAGR,MAAM,YAAY,IAAI,WAAW,SAAS,iBAAiB,MAAc,iBAAiB;AAE1F,QAAO;;AAGR,MAAM,sBAAsB,iBAAqC,oBAAwC;AACxG,KAAI,CAAC,mBAAmB,CAAC,gBAExB,QAAO,mBAAmB;AAI3B,QAAO,kBAAkB,MAAM;;AAGhC,MAAa,iBACZ,aACA,gBACY;AAEZ,KAAI,CAAC,eAAe,CAAC,YACpB,QAAO,eAAe,eAAgB;CAGvC,MAAM,mBAAmB,EAAE,GAAG;AAE9B,MAAK,MAAM,kBAAkB,OAAO,KAAK,cAAc;EACtD,MAAM,kBAAmB,YAAwC;EACjE,MAAM,kBAAmB,YAAwC;AAGjE,MAAI,mBAAmB,eAAe,mBAAmB,SAAS;AACjE,oBAAiB,kBAAkB,mBAClC,iBACA;AAED;;AAID,MAAI,mBAAmB,SAAS;AAC/B,oBAAiB,kBAAkB;IAClC,GAAI;IACJ,GAAI;;AAEL;;AAID,MAAI,eAAe,gBAAgB,kBAAkB;AACpD,oBAAiB,kBAAkB,wBAClC,iBACA;AAGD;;AAID,mBAAiB,kBAAkB;;AAGpC,QAAO;;;;;;;;;;;;;;;;;;;ACpDR,MAAM,cACL,GAAG,qBAC8B;AACjC,KAAI,iBAAiB,WAAW,EAC/B,QAAO;AAGR,KAAI,iBAAiB,WAAW,EAC/B,QAAO,iBAAiB;CAGzB,IAAIC,mBAA4C;AAEhD,MAAK,MAAM,eAAe,kBAAkB;AAC3C,MAAI,CAAC,YAAa;AAElB,qBAAmB,cAAc,kBAAkB;;AAGpD,QAAO"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CustomContextOptions } from "../index-C_W9xsBU.js";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react8 from "react";
|
|
3
3
|
import { StoreApi } from "@zayne-labs/toolkit-core";
|
|
4
4
|
import { AnyObject, Prettify, SelectorFn } from "@zayne-labs/toolkit-type-helpers";
|
|
5
5
|
import * as zustand0 from "zustand";
|
|
@@ -9,7 +9,7 @@ import { Mutate, StateCreator as StateCreator$1, StoreMutatorIdentifier, UseBoun
|
|
|
9
9
|
declare const createZustandContext: <TState extends Record<string, unknown>, TStore extends StoreApi<TState> = StoreApi<TState>>(options?: CustomContextOptions<TStore, true>) => [ZustandStoreContextProvider: (props: {
|
|
10
10
|
children: React.ReactNode;
|
|
11
11
|
store: TStore;
|
|
12
|
-
}) =>
|
|
12
|
+
}) => react8.FunctionComponentElement<react8.ProviderProps<TStore>>, useZustandStoreContext: <TResult = TState>(selector?: SelectorFn<TState, TResult>) => TResult];
|
|
13
13
|
//#endregion
|
|
14
14
|
//#region src/zustand/createZustandStoreWithCombine.d.ts
|
|
15
15
|
type Write<TInitialState, TExtraState> = Prettify<Omit<TInitialState, keyof TExtraState> & TExtraState>;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zayne-labs/toolkit-react",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.11.0",
|
|
5
5
|
"description": "A collection of utility functions, types and composables used by my other projects. Nothing too fancy but can be useful.",
|
|
6
6
|
"author": "Ryan Zayne",
|
|
7
7
|
"license": "MIT",
|
|
@@ -47,8 +47,8 @@
|
|
|
47
47
|
}
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@zayne-labs/toolkit-core": "0.
|
|
51
|
-
"@zayne-labs/toolkit-type-helpers": "0.
|
|
50
|
+
"@zayne-labs/toolkit-core": "0.11.0",
|
|
51
|
+
"@zayne-labs/toolkit-type-helpers": "0.11.0"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"@arethetypeswrong/cli": "^0.18.2",
|