react-polymorphic 1.0.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.
- package/LICENSE +201 -0
- package/NOTICE +5 -0
- package/README.md +351 -0
- package/dist/createPolymorph.d.ts +335 -0
- package/dist/createPolymorph.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +37 -0
- package/dist/index.js.map +1 -0
- package/package.json +83 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Dashice
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
# react-polymorphic
|
|
2
|
+
|
|
3
|
+
[](https://github.com/Dashice/react-polymorphic/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/react-polymorphic)
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
|
|
7
|
+
*Great to Perfect. The catalyst for your design-system.*
|
|
8
|
+
|
|
9
|
+
A single component factory function for polymorphic React components. Built for React 19+ with strong TypeScript inference.
|
|
10
|
+
|
|
11
|
+
```tsx
|
|
12
|
+
import { createPolymorph } from 'react-polymorphic';
|
|
13
|
+
|
|
14
|
+
const Button = createPolymorph<'button'>(({ as: Tag = 'button', ...rest }) => {
|
|
15
|
+
return <Tag {...rest} />
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
const App = () => {
|
|
19
|
+
return <Button as="a" href="/">Home</Button>
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Table of Contents
|
|
24
|
+
|
|
25
|
+
- [Why Polymorphic Components?](#why-polymorphic-components)
|
|
26
|
+
- [Features](#features)
|
|
27
|
+
- [Installation](#installation)
|
|
28
|
+
- [Examples](#examples)
|
|
29
|
+
- [1 — Basic Usage](#1--basic-usage)
|
|
30
|
+
- [2 — Using `ref`](#2--using-ref)
|
|
31
|
+
- [3 — Config & Branded Types](#3--config--branded-types)
|
|
32
|
+
- [4 — Advanced `as` Composition with `root`](#4--advanced-as-composition-with-root)
|
|
33
|
+
- [5 — Advanced Composition & Inference](#5--advanced-composition--inference)
|
|
34
|
+
- [API](#api)
|
|
35
|
+
- [`createPolymorph`](#createpolymorph)
|
|
36
|
+
- [Component Props](#component-props)
|
|
37
|
+
- [Generics](#generics)
|
|
38
|
+
- [Utility Types](#utility-types)
|
|
39
|
+
- [Compatibility](#compatibility)
|
|
40
|
+
- [Contributing + Changesets](#contributing--changesets)
|
|
41
|
+
- [Local setup](#local-setup)
|
|
42
|
+
- [PR requirements](#pr-requirements)
|
|
43
|
+
- [Automation](#automation)
|
|
44
|
+
- [License](#license)
|
|
45
|
+
|
|
46
|
+
## Why Polymorphic Components?
|
|
47
|
+
|
|
48
|
+
Design systems need components that are reusable **without** being rigid.
|
|
49
|
+
A `<Button />` might need to render as a native `<button />` in one context and as an `<a />` in another. A heading component may need to shift from `<h1 />` to `<h3 />` based on document hierarchy.
|
|
50
|
+
|
|
51
|
+
Polymorphic components let you keep one consistent API while swapping the rendered element to match context (`button -> a`, `div -> section`, `h1 -> h3`), preserving semantics, accessibility, and developer ergonomics.
|
|
52
|
+
|
|
53
|
+
`react-polymorphic` is built to take this beyond a basic `as` prop, with an API that gives you precise control over inherited props, component composition, and render behavior.
|
|
54
|
+
|
|
55
|
+
## Features
|
|
56
|
+
|
|
57
|
+
- **Polymorphism Beyond `as`**
|
|
58
|
+
Supports intrinsic elements, React components, and composed polymorphic components.
|
|
59
|
+
|
|
60
|
+
- **`root` Override for Composition**
|
|
61
|
+
Control the final rendered element when nesting polymorphic components.
|
|
62
|
+
|
|
63
|
+
- **Type-safe Inherited Prop Control**
|
|
64
|
+
Use `PolymorphicConfig` with `Inherit` and `Unset` to preserve, remove, or reshape inherited props.
|
|
65
|
+
|
|
66
|
+
- **Ref Inference that Follows Render Target**
|
|
67
|
+
`ref` types track the active element/component target.
|
|
68
|
+
|
|
69
|
+
- **Inference Utilities Included**
|
|
70
|
+
`InferPolymorphElement`, `InferPolymorphProps`, and `InferPolymorphConfig` for advanced typing workflows.
|
|
71
|
+
|
|
72
|
+
- **TypeScript 7 Ready**
|
|
73
|
+
Compatible with TypeScript 5.4+ and optimized for TypeScript 7.
|
|
74
|
+
|
|
75
|
+
- **Built for React 19+**
|
|
76
|
+
Leverages React 19's handling of `ref`, eliminating `forwardRef` and convoluted type gymnastics.
|
|
77
|
+
|
|
78
|
+
- **ESM Exclusive**
|
|
79
|
+
No CommonJS, no legacy build artifacts. Tree-shakable and optimized for modern bundlers.
|
|
80
|
+
|
|
81
|
+
## Installation
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
npm install react-polymorphic
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Use the equivalent command for your package manager of choice.
|
|
88
|
+
|
|
89
|
+
## Examples
|
|
90
|
+
|
|
91
|
+
### 1 — Basic Usage
|
|
92
|
+
|
|
93
|
+
Most polymorphic components are simple wrappers that combine custom props with inferred DOM attributes.
|
|
94
|
+
|
|
95
|
+
```tsx
|
|
96
|
+
import { createPolymorph } from 'react-polymorphic';
|
|
97
|
+
|
|
98
|
+
type Props = {
|
|
99
|
+
variant: 'primary' | 'secondary';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const Pane = createPolymorph<'div', Props>((props) => {
|
|
103
|
+
const { as: Tag = 'div', variant, className, ...rest } = props;
|
|
104
|
+
const variantClasses = variant === 'primary' ? 'bg-white' : 'bg-blue-50';
|
|
105
|
+
|
|
106
|
+
return <Tag className={`p-4 ${variantClasses} ${className}`} {...rest} />
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
const App = () => {
|
|
110
|
+
return (
|
|
111
|
+
<>
|
|
112
|
+
<Pane as="section" variant="primary" aria-label="...">...</Pane>
|
|
113
|
+
<Pane as="aside" variant="secondary" aria-label="...">...</Pane>
|
|
114
|
+
</>
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`Props` and the intrinsic attributes of `'div'` are merged into one contract. Consumers can then switch semantics with `as` (`section`, `aside`, etc.) while keeping the same component API.
|
|
120
|
+
|
|
121
|
+
### 2 — Using `ref`
|
|
122
|
+
|
|
123
|
+
`ref` is inferred from the active render target. With React 19, you can use `ref` directly without `forwardRef`.
|
|
124
|
+
|
|
125
|
+
```tsx
|
|
126
|
+
import { useRef } from 'react';
|
|
127
|
+
import { createPolymorph } from 'react-polymorphic';
|
|
128
|
+
|
|
129
|
+
const Component = createPolymorph<'div'>((props) => {
|
|
130
|
+
const { as: Tag = 'div', ...rest } = props;
|
|
131
|
+
return <Tag {...rest} />
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
const App = () => {
|
|
135
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
136
|
+
const aRef = useRef<HTMLAnchorElement>(null);
|
|
137
|
+
|
|
138
|
+
return (
|
|
139
|
+
<>
|
|
140
|
+
<Component ref={ref} />
|
|
141
|
+
<Component as="a" ref={aRef} />
|
|
142
|
+
</>
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
`ref` follows `as` automatically (and also follows `root` when composing with polymorphic components).
|
|
148
|
+
|
|
149
|
+
### 3 — Config & Branded Types
|
|
150
|
+
|
|
151
|
+
Use `PolymorphicConfig` to reshape inferred props: remove, preserve, override, or require attributes.
|
|
152
|
+
|
|
153
|
+
```tsx
|
|
154
|
+
import { createPolymorph } from 'react-polymorphic';
|
|
155
|
+
import type { PolymorphicConfig, Unset, Inherit } from 'react-polymorphic';
|
|
156
|
+
|
|
157
|
+
type Props = {
|
|
158
|
+
loading: boolean;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
type Config = PolymorphicConfig<'button', {
|
|
162
|
+
'aria-loading': Unset;
|
|
163
|
+
children: string;
|
|
164
|
+
href: string;
|
|
165
|
+
target?: '_blank';
|
|
166
|
+
type: Inherit;
|
|
167
|
+
}>;
|
|
168
|
+
|
|
169
|
+
const Button = createPolymorph<'button', Props, Config>((props) => {
|
|
170
|
+
const { as: Tag = 'button', children, loading, ...rest } = props;
|
|
171
|
+
|
|
172
|
+
return (
|
|
173
|
+
<Tag aria-loading={loading} {...rest}>
|
|
174
|
+
{loading ? 'Loading...' : children}
|
|
175
|
+
</Tag>
|
|
176
|
+
)
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
const App = () => {
|
|
180
|
+
return (
|
|
181
|
+
<>
|
|
182
|
+
<Button type="button">Calculate</Button>
|
|
183
|
+
<Button as="a" href="/">Back to home</Button>
|
|
184
|
+
</>
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
- `Unset` removes an inferred prop from the resulting contract.
|
|
190
|
+
- `Inherit` preserves the inferred type (useful when making a prop required or composing unions).
|
|
191
|
+
- Adding `href` and `target` to `Config` prepares the component for common `as="a"` usage.
|
|
192
|
+
- `PolymorphicConfig` is optional, but recommended for code hints and safer attribute authoring.
|
|
193
|
+
|
|
194
|
+
### 4 — Advanced `as` Composition with `root`
|
|
195
|
+
|
|
196
|
+
When `as` points to another polymorphic component, `root` lets you control that component's final underlying element.
|
|
197
|
+
|
|
198
|
+
```tsx
|
|
199
|
+
import { createPolymorph } from 'react-polymorphic';
|
|
200
|
+
|
|
201
|
+
const OtherComponent = createPolymorph<'div'>(...);
|
|
202
|
+
|
|
203
|
+
const Component = createPolymorph<'div'>((props) => {
|
|
204
|
+
const { as: Tag = 'div', ...rest } = props;
|
|
205
|
+
return <Tag {...rest} />
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const App = () => {
|
|
209
|
+
return <Component as={OtherComponent} root="section" />
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
`root` behaves similarly to `key`: it influences rendering behavior but is not part of the consumed `props` inside your render function.
|
|
214
|
+
|
|
215
|
+
### 5 — Advanced Composition & Inference
|
|
216
|
+
|
|
217
|
+
You can extract generics from existing polymorphic components and reuse them when extending third-party components.
|
|
218
|
+
|
|
219
|
+
```tsx
|
|
220
|
+
import { createPolymorph } from 'react-polymorphic';
|
|
221
|
+
import type {
|
|
222
|
+
InferPolymorphElement,
|
|
223
|
+
InferPolymorphProps,
|
|
224
|
+
InferPolymorphConfig
|
|
225
|
+
} from 'react-polymorphic';
|
|
226
|
+
import { TheirButton } from 'some-library';
|
|
227
|
+
|
|
228
|
+
type TheirElement = InferPolymorphElement<typeof TheirButton>;
|
|
229
|
+
// 'button'
|
|
230
|
+
|
|
231
|
+
type TheirProps = InferPolymorphProps<typeof TheirButton>;
|
|
232
|
+
// { message: string }
|
|
233
|
+
|
|
234
|
+
type TheirConfig = InferPolymorphConfig<typeof TheirButton>;
|
|
235
|
+
// { id?: number; title: string }
|
|
236
|
+
|
|
237
|
+
type Props = { ... }
|
|
238
|
+
|
|
239
|
+
const OurButton = createPolymorph<typeof TheirButton, Props>((props) => {
|
|
240
|
+
const { as: Tag = TheirButton, ...rest } = props;
|
|
241
|
+
return <Tag {...rest} />
|
|
242
|
+
})
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
This pattern keeps your extension aligned with the base component contract while still allowing consumers to swap `as`.
|
|
246
|
+
|
|
247
|
+
If swapping out the base would break core behavior, preserve the base and expose only its internal polymorphism:
|
|
248
|
+
|
|
249
|
+
```tsx
|
|
250
|
+
const OurButton = createPolymorph<TheirElement, Props & TheirProps, TheirConfig>(
|
|
251
|
+
(props) => {
|
|
252
|
+
const { as = 'button', ...rest } = props;
|
|
253
|
+
return <TheirButton as={as} {...rest} />
|
|
254
|
+
}
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
const App = () => {
|
|
258
|
+
return <OurButton as="a" />
|
|
259
|
+
}
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
In this version, `OurButton` always renders `TheirButton`, and `as` only controls what `TheirButton` itself renders to the DOM.
|
|
263
|
+
|
|
264
|
+
## API
|
|
265
|
+
|
|
266
|
+
### `createPolymorph`
|
|
267
|
+
|
|
268
|
+
Creates polymorphic components with strong inference for `as`, `root`, and `ref`.
|
|
269
|
+
|
|
270
|
+
| Export | Kind |
|
|
271
|
+
| ----------------- | ---------- |
|
|
272
|
+
| `createPolymorph` | `function` |
|
|
273
|
+
|
|
274
|
+
#### Component Props
|
|
275
|
+
|
|
276
|
+
| Prop | Type | Notes |
|
|
277
|
+
| ------ | ---------------------------------- | ------------------------ |
|
|
278
|
+
| `as?` | element \| component | Swaps target. |
|
|
279
|
+
| `root?` | element \| `Fragment` | Overrides nested target. |
|
|
280
|
+
| `ref?` | inferred from final target | Follows `as`/`root`. |
|
|
281
|
+
|
|
282
|
+
#### Generics
|
|
283
|
+
|
|
284
|
+
| Generic | Meaning |
|
|
285
|
+
| ------- | ------------------------------------ |
|
|
286
|
+
| `T` | Default render target. |
|
|
287
|
+
| `P` | Custom component props. |
|
|
288
|
+
| `C` | Prop config via `PolymorphicConfig`. |
|
|
289
|
+
|
|
290
|
+
### Utility Types
|
|
291
|
+
|
|
292
|
+
| Export | Purpose |
|
|
293
|
+
| -------------------------- | ------------------------------ |
|
|
294
|
+
| `PolymorphicConfig<T, C>` | Configures inherited props. |
|
|
295
|
+
| `Inherit` | Preserves inferred prop type. |
|
|
296
|
+
| `Unset` | Removes an inferred prop. |
|
|
297
|
+
| `InferPolymorphElement<T>` | Extracts default target type. |
|
|
298
|
+
| `InferPolymorphProps<T>` | Extracts custom props type. |
|
|
299
|
+
| `InferPolymorphConfig<T>` | Extracts config type. |
|
|
300
|
+
|
|
301
|
+
## Compatibility
|
|
302
|
+
|
|
303
|
+
| Package | Version |
|
|
304
|
+
| ------------ | ---------- |
|
|
305
|
+
| `react` | `>=19.0.0` |
|
|
306
|
+
| `react-dom` | `>=19.0.0` |
|
|
307
|
+
| `typescript` | `>=5.4.0` |
|
|
308
|
+
|
|
309
|
+
## Contributing + Changesets
|
|
310
|
+
|
|
311
|
+
Contributions are welcome. For bug fixes, improvements, or new features, please open a PR with a clear summary of the change.
|
|
312
|
+
|
|
313
|
+
### Local setup
|
|
314
|
+
|
|
315
|
+
```bash
|
|
316
|
+
pnpm install
|
|
317
|
+
pnpm typecheck
|
|
318
|
+
pnpm test:run
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
### PR requirements
|
|
322
|
+
|
|
323
|
+
- Keep changes focused and include tests when behavior changes.
|
|
324
|
+
- Add a changeset for all user-facing package changes:
|
|
325
|
+
|
|
326
|
+
```bash
|
|
327
|
+
pnpm changeset
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
When prompted, choose the correct bump type:
|
|
331
|
+
|
|
332
|
+
- `patch` → fixes and small improvements
|
|
333
|
+
- `minor` → new backward-compatible features
|
|
334
|
+
- `major` → breaking changes
|
|
335
|
+
|
|
336
|
+
If a PR does not require a release, you can create an empty changeset:
|
|
337
|
+
|
|
338
|
+
```bash
|
|
339
|
+
pnpm changeset --empty
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
### Automation
|
|
343
|
+
|
|
344
|
+
- **Pre-commit** runs `biome check --write` on staged files.
|
|
345
|
+
- **Pre-push** runs `pnpm typecheck` and `pnpm test:run`.
|
|
346
|
+
- **CI** validates formatting, linting, type-checking, tests, and build.
|
|
347
|
+
- **Release** runs only after CI succeeds on `main`, using Changesets to version and publish.
|
|
348
|
+
|
|
349
|
+
## License
|
|
350
|
+
|
|
351
|
+
Apache-2.0. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
/** biome-ignore-all lint/suspicious/noExplicitAny: -- */
|
|
2
|
+
/** biome-ignore-all lint/complexity/noBannedTypes: -- */
|
|
3
|
+
import type { ComponentProps, ComponentRef, ExoticComponent, FragmentProps, FunctionComponent, JSX, ReactElement, ReactPortal, Ref } from 'react';
|
|
4
|
+
/**
|
|
5
|
+
* Performs a distributive omit on a union type.
|
|
6
|
+
* @see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
|
|
7
|
+
*/
|
|
8
|
+
type DistributiveOmit<T, K extends PropertyKey> = T extends any ? Omit<T, K> : never;
|
|
9
|
+
/** Helper to check if a type is exactly `any` */
|
|
10
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
11
|
+
/** Extracts all properties from `R` which are set to `Unset` type. */
|
|
12
|
+
type ExtractUnset<R> = {
|
|
13
|
+
[K in keyof R as IsAny<R[K]> extends true ? never : R[K] extends Unset ? K : never]: R[K];
|
|
14
|
+
};
|
|
15
|
+
/** Check if a key in an object type has the optional modifier (?) */
|
|
16
|
+
type IsOptionalKey<T, K extends keyof T> = {} extends Pick<T, K> ? true : false;
|
|
17
|
+
/** Merges `T` and `Y`, overwriting properties in `T` with those in `Y` */
|
|
18
|
+
type Overwrite<T, Y> = DistributiveOmit<T, keyof Y> & Y;
|
|
19
|
+
/** Extracts all keys in obj `T` whom are required as a string union. */
|
|
20
|
+
type RequiredKeys<T> = {
|
|
21
|
+
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
|
|
22
|
+
}[keyof T];
|
|
23
|
+
/** Sets all keys in `K` of type `T` to required. */
|
|
24
|
+
type Require<T, K extends PropertyKey> = Overwrite<T, Required<Pick<T, K extends keyof T ? K : never>>>;
|
|
25
|
+
/**
|
|
26
|
+
* All valid HTML & SVG elements in string format (`"div"`, `"svg"`, `"input"`)
|
|
27
|
+
*/
|
|
28
|
+
type ElementType = keyof JSX.IntrinsicElements;
|
|
29
|
+
/** A React Fragment component. */
|
|
30
|
+
type FragmentType = ExoticComponent<FragmentProps>;
|
|
31
|
+
/**
|
|
32
|
+
* Valid candidates to fulfill the `root` prop when `as` is a
|
|
33
|
+
* `FunctionComponent` derivative. This may be:
|
|
34
|
+
* - A string representing a valid HTML or SVG element
|
|
35
|
+
* - A React Fragment component
|
|
36
|
+
*/
|
|
37
|
+
type RootType = FragmentType | ElementType | '';
|
|
38
|
+
/**
|
|
39
|
+
* Valid candidates to fulfill the `as` prop. This may be:
|
|
40
|
+
* - A string representing a valid HTML or SVG element
|
|
41
|
+
* - A React FunctionComponent
|
|
42
|
+
*/
|
|
43
|
+
type PolymorphicElementType<P = any> = ElementType | FunctionComponent<P>;
|
|
44
|
+
/**
|
|
45
|
+
* Required return type of `createPolymorph`; a slightly more restrictive
|
|
46
|
+
* version of `ReactNode`.
|
|
47
|
+
*/
|
|
48
|
+
type PolymorphicElement<T extends PolymorphicElementType> = ReactElement<T> | ReactPortal | null;
|
|
49
|
+
/** A generic props object. */
|
|
50
|
+
type Props = Record<PropertyKey, unknown>;
|
|
51
|
+
/**
|
|
52
|
+
* Infers the element type of `PolymorphicExoticComponent`, falling back to `T`
|
|
53
|
+
* if `TT` it is not a `PolymorphicExoticComponent`. In essence, if `as` prop
|
|
54
|
+
* is not specified, the element type will be `T`.
|
|
55
|
+
*/
|
|
56
|
+
type ElementOf<TT, T> = TT extends PolymorphicExoticComponent<infer E, any, any> ? E : TT extends PolymorphicElementType ? TT : T;
|
|
57
|
+
/**
|
|
58
|
+
* Used in `PolymorphicExoticComponent` to determine fallback of `TT`.
|
|
59
|
+
* Attempts to extract a `PolymorphicElementType` from props of P, if present,
|
|
60
|
+
* otherwise falls back to `T`.
|
|
61
|
+
*/
|
|
62
|
+
type AsProp<T extends PolymorphicElementType, P extends Props> = 'as' extends keyof P ? P['as'] extends PolymorphicElementType ? P['as'] : T : T;
|
|
63
|
+
/**
|
|
64
|
+
* Used in `PolymorphicProps` to determine `ref` property value of `T` if it is
|
|
65
|
+
* a valid `PolymorphicElementType`, otherwise returns an empty object. This is
|
|
66
|
+
* used to ensure that `ref` prop is only available for valid element types.
|
|
67
|
+
*/
|
|
68
|
+
type RefOf<T extends PolymorphicElementType> = ComponentRef<T> extends never ? {} : {
|
|
69
|
+
ref?: Ref<ComponentRef<T>>;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Used in `PolymorphicProps` to determine `as` property value of `P['as']` if
|
|
73
|
+
* it is a valid `PolymorphicElementType`, otherwise returns `T`. Respects
|
|
74
|
+
* property optionality.
|
|
75
|
+
*/
|
|
76
|
+
type AsOf<T extends PolymorphicElementType, P extends Props> = 'as' extends keyof P ? P['as'] extends PolymorphicElementType ? IsOptionalKey<P, 'as'> extends true ? {
|
|
77
|
+
as?: P['as'];
|
|
78
|
+
} : {
|
|
79
|
+
as: P['as'];
|
|
80
|
+
} : {
|
|
81
|
+
as?: T;
|
|
82
|
+
} : {
|
|
83
|
+
as?: T;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Base props of a component created using `createPolymorph` function,
|
|
87
|
+
* available during implementation.
|
|
88
|
+
*
|
|
89
|
+
* @property as - The element type to render.
|
|
90
|
+
* @property ref - The ref to the underlying element.
|
|
91
|
+
*/
|
|
92
|
+
type PolymorphicProps<T extends PolymorphicElementType, P extends Props> = AsOf<T, P> & RefOf<T>;
|
|
93
|
+
/**
|
|
94
|
+
* Base props of a component created using `createPolymorph` function,
|
|
95
|
+
* available during rendering.
|
|
96
|
+
*
|
|
97
|
+
* @property as - Element type to render.
|
|
98
|
+
* @property root - Root element type to render when `as` is a `FunctionComponent`.
|
|
99
|
+
* @property ref - Ref of the underlying element.
|
|
100
|
+
*/
|
|
101
|
+
type PolymorphicExoticProps<T extends PolymorphicElementType, R extends RootType> = {
|
|
102
|
+
as?: T | PolymorphicElementType | PolymorphicExoticComponent<any, any, any>;
|
|
103
|
+
root?: FragmentType | Exclude<R | ElementType, ''>;
|
|
104
|
+
} & RefOf<R extends '' ? T : R>;
|
|
105
|
+
/**
|
|
106
|
+
* Composite props of a component created using `createPolymorph` function,
|
|
107
|
+
* available during implementation. Combines props `P` with inherited element
|
|
108
|
+
* props `T`, modified using `Config` type `C`.
|
|
109
|
+
*
|
|
110
|
+
* @property as - Element type to render.
|
|
111
|
+
* @property ref - Ref of underlying element.
|
|
112
|
+
*/
|
|
113
|
+
type PolymorphicComponentProps<T extends PolymorphicElementType, P extends Props, C extends Config<T>> = Overwrite<Overwrite<ApplyConfig<T, C>, Omit<P, 'as'>>, PolymorphicProps<T, P>>;
|
|
114
|
+
/**
|
|
115
|
+
* Composite props of a component created using `createPolymorph` function,
|
|
116
|
+
* available during rendering. Comines props `P` with inherited element props
|
|
117
|
+
* `T`, modified using `Config` type `C`.
|
|
118
|
+
*
|
|
119
|
+
* @property as - Element type to render.
|
|
120
|
+
* @property root - Root element type to render when `as` is a `FunctionComponent`.
|
|
121
|
+
* @property ref - Ref of underlying element.
|
|
122
|
+
*/
|
|
123
|
+
type PolymorphicExoticComponentProps<T extends PolymorphicElementType, P extends Props, C extends Config<T>, R extends RootType> = Overwrite<Overwrite<ApplyConfig<R extends '' ? T : R, C>, P>, PolymorphicExoticProps<T, R>>;
|
|
124
|
+
/**
|
|
125
|
+
* Component render function passed into `createPolymorph` during
|
|
126
|
+
* initialization as first argument.
|
|
127
|
+
*
|
|
128
|
+
* @param props - Props passed to component.
|
|
129
|
+
* @returns React element to render.
|
|
130
|
+
*/
|
|
131
|
+
type PolymorphicRenderFunction<T extends PolymorphicElementType, P extends Props, C extends Config<T>> = {
|
|
132
|
+
(props: PolymorphicComponentProps<T, P, C>): PolymorphicElement<T>;
|
|
133
|
+
displayName?: string;
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* A component created using `createPolymorph` function, which can render
|
|
137
|
+
* different element types based on the `as` prop.
|
|
138
|
+
*
|
|
139
|
+
* When `props` are passed with a modified `as` prop from the default `T`,
|
|
140
|
+
* props will be inferred from the new externally set `as` value; changing
|
|
141
|
+
* inferred props from `T` to `TT` element type.
|
|
142
|
+
*
|
|
143
|
+
* If, in addition to a modified external `as` (`TT`), a `root` prop is also
|
|
144
|
+
* set; the `root` prop will be used to determine the final element type to render,
|
|
145
|
+
* and props will be inferred from the `root` element type instead of the `as`
|
|
146
|
+
* element type.
|
|
147
|
+
*
|
|
148
|
+
* @param props - Props passed to component; including `as` and `root` props.
|
|
149
|
+
* @returns React element to render.
|
|
150
|
+
*/
|
|
151
|
+
type PolymorphicExoticComponent<T extends PolymorphicElementType, P extends Props, C extends Config<T>> = {
|
|
152
|
+
<TT = AsProp<T, P>, R extends RootType = ''>(props: TT extends T ? PolymorphicComponentProps<T, P, C> : TT extends PolymorphicExoticComponent<any, any, any> ? PolymorphicExoticComponentProps<ElementOf<TT, T>, Overwrite<P, InferPolymorphProps<TT>>, Overwrite<C, InferPolymorphConfig<TT>>, R> : PolymorphicComponentProps<ElementOf<TT, T>, Overwrite<P, InferPolymorphProps<TT>>, Overwrite<C, InferPolymorphConfig<TT>>>): PolymorphicElement<ElementOf<TT, T>>;
|
|
153
|
+
displayName?: string;
|
|
154
|
+
};
|
|
155
|
+
/** A generic config object. */
|
|
156
|
+
type Config<T extends PolymorphicElementType> = {
|
|
157
|
+
[K in keyof ComponentProps<T> | (string & {})]?: unknown;
|
|
158
|
+
};
|
|
159
|
+
type ResolveInherit<CK, PK> = [Extract<CK, Inherit>] extends [never] ? CK : [Exclude<CK, Inherit>] extends [never] ? PK : Exclude<CK, Inherit> | PK;
|
|
160
|
+
type ApplyValues<P, C, PS = Omit<P, keyof (ExtractUnset<C> & JSX.IntrinsicAttributes)>> = {
|
|
161
|
+
[K in keyof PS]: K extends keyof C ? ResolveInherit<C[K], PS[K]> : PS[K];
|
|
162
|
+
};
|
|
163
|
+
type ApplyConfig<T extends PolymorphicElementType, C extends Config<T>> = Require<ApplyValues<ComponentProps<T & {}>, C>, RequiredKeys<C>>;
|
|
164
|
+
/**
|
|
165
|
+
* A branded type used in `Config` to indicate that a prop should be removed
|
|
166
|
+
* from inferred props of `as`.
|
|
167
|
+
*/
|
|
168
|
+
export type Unset = {
|
|
169
|
+
readonly _unset: unique symbol;
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* A branded type used in `Config` to indicate that a prop should be inherited
|
|
173
|
+
* from inferred props of `as`.
|
|
174
|
+
*/
|
|
175
|
+
export type Inherit = {
|
|
176
|
+
readonly _inherit: unique symbol;
|
|
177
|
+
};
|
|
178
|
+
/**
|
|
179
|
+
* A code-hinting friendly `Config` creator for `createPolymorph`, displaying
|
|
180
|
+
* all available props for the given `as` element type. This type-helper is
|
|
181
|
+
* not required to create a valid `Config` type, but is useful for code-hinting
|
|
182
|
+
* and auto-completion in IDEs.
|
|
183
|
+
*
|
|
184
|
+
* @example ```tsx
|
|
185
|
+
* type Config = PolymorphicConfig<'button', {
|
|
186
|
+
* title: string | number;
|
|
187
|
+
* onClick: Inherit
|
|
188
|
+
* type: Unset
|
|
189
|
+
* }>
|
|
190
|
+
*
|
|
191
|
+
* const Component = createPolymorph<'button', Props, Config>(...);
|
|
192
|
+
*/
|
|
193
|
+
export type PolymorphicConfig<T extends PolymorphicElementType, C extends Config<T>> = C & {
|
|
194
|
+
readonly _tag?: T;
|
|
195
|
+
};
|
|
196
|
+
/**
|
|
197
|
+
* Infers the `as` prop type from a `PolymorphicExoticComponent`.
|
|
198
|
+
*
|
|
199
|
+
* @example ```tsx
|
|
200
|
+
* const Component = createPolymorph<'div', Props, Config>(...);
|
|
201
|
+
* type Result = InferPolymorphElement<typeof Component>; // 'div'
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
export type InferPolymorphElement<T> = T extends PolymorphicExoticComponent<infer Tag, any, any> ? Tag : unknown;
|
|
205
|
+
/**
|
|
206
|
+
* Infers the props type from a `PolymorphicExoticComponent`.
|
|
207
|
+
*
|
|
208
|
+
* @example ```tsx
|
|
209
|
+
* const Component = createPolymorph<'div', Props, Config>(...);
|
|
210
|
+
* type Result = InferPolymorphProps<typeof Component>; // Props
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
export type InferPolymorphProps<T> = T extends PolymorphicExoticComponent<any, infer P, any> ? P : {};
|
|
214
|
+
/**
|
|
215
|
+
* Infers the config type from a `PolymorphicExoticComponent`.
|
|
216
|
+
*
|
|
217
|
+
* @example ```tsx
|
|
218
|
+
* const Component = createPolymorph<'div', Props, Config>(...);
|
|
219
|
+
* type Result = InferPolymorphConfig<typeof Component>; // Config
|
|
220
|
+
* ```
|
|
221
|
+
*/
|
|
222
|
+
export type InferPolymorphConfig<T> = T extends PolymorphicExoticComponent<any, any, infer C> ? C : {};
|
|
223
|
+
type CreatePolymorph = <T extends PolymorphicElementType, P extends Props = {}, C extends PolymorphicConfig<T, Config<T>> = {}>(render: NoInfer<PolymorphicRenderFunction<T, P, C>>) => NoInfer<PolymorphicExoticComponent<T, P, C>>;
|
|
224
|
+
/**
|
|
225
|
+
* **Creates a polymorphic component.**
|
|
226
|
+
* This combines user-provided props `P`, inherited props from `T`, and any
|
|
227
|
+
* optional modifications to `T` specified in `C`.
|
|
228
|
+
*
|
|
229
|
+
* In addition to inherited and user-provided props; exposes following props:
|
|
230
|
+
* - `as`: Specifies the element type to render to DOM.
|
|
231
|
+
* - `root`: When `as` is set to another `createPolymorph` created component,
|
|
232
|
+
* `root` overrides the internal `as` prop of the component being rendered,
|
|
233
|
+
* allowing for a different element type to be rendered.
|
|
234
|
+
*
|
|
235
|
+
* @param render - Render function of `PolymorphicExoticComponent`.
|
|
236
|
+
*
|
|
237
|
+
* @returns `PolymorphicExoticComponent`
|
|
238
|
+
*
|
|
239
|
+
* ---
|
|
240
|
+
* **Simple Usage**
|
|
241
|
+
*
|
|
242
|
+
* This is the most common use-case for `createPolymorph`, where a component is
|
|
243
|
+
* created with a default element type `T` and basic props `P`.
|
|
244
|
+
*
|
|
245
|
+
* @example
|
|
246
|
+
* ```tsx
|
|
247
|
+
* type DefaultTag = 'button'
|
|
248
|
+
*
|
|
249
|
+
* type ButtonProps = {
|
|
250
|
+
* variant: 'primary' | 'secondary';
|
|
251
|
+
* }
|
|
252
|
+
*
|
|
253
|
+
* const Button = createPolymorph<DefaultTag, ButtonProps>(
|
|
254
|
+
* ({ as: Tag = 'button', variant, ...rest }) => {
|
|
255
|
+
* const isPrimary = variant === 'primary'
|
|
256
|
+
* return <Tag className={isPrimary ? 'bg-black' : 'bg-gray'} {...rest} />
|
|
257
|
+
* }
|
|
258
|
+
* )
|
|
259
|
+
*
|
|
260
|
+
* const App = () => {
|
|
261
|
+
* return <Button as="a" href="/" variant="primary">Home</Button>
|
|
262
|
+
* }
|
|
263
|
+
* ```
|
|
264
|
+
*
|
|
265
|
+
* **Advanced Usage**
|
|
266
|
+
*
|
|
267
|
+
* This use-case leverages as many features of `createPolymorph` as possible in
|
|
268
|
+
* an effort to showcase deeper capabilities. Leverages `Button` from
|
|
269
|
+
* "**Simple Usage**".
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* ```tsx
|
|
273
|
+
* type DefaultTag = typeof Button;
|
|
274
|
+
*
|
|
275
|
+
* type AdvancedButtonProps = {
|
|
276
|
+
* loading?: boolean;
|
|
277
|
+
* size: 'small' | 'medium' | 'large';
|
|
278
|
+
* }
|
|
279
|
+
*
|
|
280
|
+
* type AdvancedButtonConfig = PolymorphicConfig<DefaultTag, {
|
|
281
|
+
* // Set as required and change type
|
|
282
|
+
* children: string | number;
|
|
283
|
+
* // Set as required and inherit type from `T`
|
|
284
|
+
* onClick: Inherit;
|
|
285
|
+
* // Change type
|
|
286
|
+
* title?: number;
|
|
287
|
+
* // Remove property
|
|
288
|
+
* type: Unset;
|
|
289
|
+
* // If `as` is set to an element containing `href`, require it.
|
|
290
|
+
* href: Inherit
|
|
291
|
+
* }>
|
|
292
|
+
*
|
|
293
|
+
* const AdvancedButton = createPolymorph<
|
|
294
|
+
* DefaultTag,
|
|
295
|
+
* AdvancedButtonProps,
|
|
296
|
+
* AdvancedButtonConfig
|
|
297
|
+
* >(
|
|
298
|
+
* ({ as: Tag = Button, loading, size, ...rest }) => {
|
|
299
|
+
* const sizeClass = (() => {
|
|
300
|
+
* if (size === 'small') return 'h-8';
|
|
301
|
+
* if (size === 'medium') return 'h-10';
|
|
302
|
+
* if (size === 'large') return 'h-12';
|
|
303
|
+
* return '';
|
|
304
|
+
* }())
|
|
305
|
+
*
|
|
306
|
+
* return (
|
|
307
|
+
* <Tag
|
|
308
|
+
* className={`${className} ${sizeClass}`}
|
|
309
|
+
* aria-loading={loading}
|
|
310
|
+
* {...rest}
|
|
311
|
+
* />
|
|
312
|
+
* )
|
|
313
|
+
* }
|
|
314
|
+
* )
|
|
315
|
+
*
|
|
316
|
+
* const App = () => {
|
|
317
|
+
* return (
|
|
318
|
+
* <AdvancedButton
|
|
319
|
+
* as="a"
|
|
320
|
+
* href="/"
|
|
321
|
+
* variant="primary"
|
|
322
|
+
* size="large"
|
|
323
|
+
* loading={true}
|
|
324
|
+
* title={24}
|
|
325
|
+
* onClick={() => console.log('clicked')}
|
|
326
|
+
* >
|
|
327
|
+
* Home
|
|
328
|
+
* </AdvancedButton>
|
|
329
|
+
* )
|
|
330
|
+
* }
|
|
331
|
+
* ```
|
|
332
|
+
*/
|
|
333
|
+
export declare const createPolymorph: CreatePolymorph;
|
|
334
|
+
export {};
|
|
335
|
+
//# sourceMappingURL=createPolymorph.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createPolymorph.d.ts","sourceRoot":"","sources":["../src/createPolymorph.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,yDAAyD;AAEzD,OAAO,KAAK,EACX,cAAc,EACd,YAAY,EACZ,eAAe,EACf,aAAa,EACb,iBAAiB,EACjB,GAAG,EACH,YAAY,EACZ,WAAW,EACX,GAAG,EACH,MAAM,OAAO,CAAC;AA+Bf;;;GAGG;AACH,KAAK,gBAAgB,CAAC,CAAC,EAAE,CAAC,SAAS,WAAW,IAAI,CAAC,SAAS,GAAG,GAC5D,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,G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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4GG;AACH,eAAO,MAAM,eAAe,EA+CtB,eAAe,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// src/createPolymorph.ts
|
|
2
|
+
import { version } from "react";
|
|
3
|
+
var __DEV__ = process.env.NODE_ENV !== "production";
|
|
4
|
+
function assert(condition, message, errorType) {
|
|
5
|
+
if (condition) return;
|
|
6
|
+
throw new (errorType || Error)(message);
|
|
7
|
+
}
|
|
8
|
+
if (__DEV__) {
|
|
9
|
+
assert(
|
|
10
|
+
parseInt(version.split(".")[0], 10) >= 19,
|
|
11
|
+
"createPolymorph requires React >= 19. Please upgrade your React version."
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
var createPolymorph = ((render) => {
|
|
15
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
16
|
+
const _render = (props) => {
|
|
17
|
+
const { as, root, ...rest } = props;
|
|
18
|
+
let _as = as;
|
|
19
|
+
if (typeof as === "function" && root) {
|
|
20
|
+
const map = cache.get(as) ?? /* @__PURE__ */ new Map();
|
|
21
|
+
cache.set(as, map);
|
|
22
|
+
if (!map.has(root)) {
|
|
23
|
+
const adapter = (props2) => as({ ...props2, as: root });
|
|
24
|
+
if ("displayName" in as) adapter.displayName = as.displayName;
|
|
25
|
+
map.set(root, adapter);
|
|
26
|
+
}
|
|
27
|
+
_as = map.get(root) ?? as;
|
|
28
|
+
}
|
|
29
|
+
return render({ ...rest, as: _as });
|
|
30
|
+
};
|
|
31
|
+
_render.displayName = render.displayName || render.name || "PolymorphicComponent";
|
|
32
|
+
return _render;
|
|
33
|
+
});
|
|
34
|
+
export {
|
|
35
|
+
createPolymorph
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/createPolymorph.ts"],"sourcesContent":["/** biome-ignore-all lint/suspicious/noExplicitAny: -- */\n/** biome-ignore-all lint/complexity/noBannedTypes: -- */\n\nimport type {\n\tComponentProps,\n\tComponentRef,\n\tExoticComponent,\n\tFragmentProps,\n\tFunctionComponent,\n\tJSX,\n\tReactElement,\n\tReactPortal,\n\tRef\n} from 'react';\nimport { version } from 'react';\n\n// Version Check -------------------------------------------------------------\n\nconst __DEV__ = process.env.NODE_ENV !== 'production';\n\n/**\n * Asserts that a condition is true, throwing an error if it is not.\n * @param condition The condition to assert.\n * @param message The error message to throw if the assertion fails.\n * @param errorType Error type to throw if assertion fails. Defaults to `Error`.\n */\nfunction assert(\n\tcondition: unknown,\n\tmessage: string,\n\terrorType?: ErrorConstructor\n): asserts condition {\n\tif (condition) return;\n\tthrow new (errorType || Error)(message);\n}\n\nif (__DEV__) {\n\tassert(\n\t\tparseInt(version.split('.')[0], 10) >= 19,\n\t\t'createPolymorph requires React >= 19. Please upgrade your React version.'\n\t);\n}\n\n// Utilities ------------------------------------------------------------------\n\n/**\n * Performs a distributive omit on a union type.\n * @see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends any\n\t? Omit<T, K>\n\t: never;\n\n/** Helper to check if a type is exactly `any` */\ntype IsAny<T> = 0 extends 1 & T ? true : false;\n\n/** Extracts all properties from `R` which are set to `Unset` type. */\ntype ExtractUnset<R> = {\n\t[K in keyof R as IsAny<R[K]> extends true\n\t\t? never\n\t\t: R[K] extends Unset\n\t\t\t? K\n\t\t\t: never]: R[K];\n};\n\n/** Check if a key in an object type has the optional modifier (?) */\ntype IsOptionalKey<T, K extends keyof T> = {} extends Pick<T, K> ? true : false;\n\n/** Merges `T` and `Y`, overwriting properties in `T` with those in `Y` */\ntype Overwrite<T, Y> = DistributiveOmit<T, keyof Y> & Y;\n\n/** Extracts all keys in obj `T` whom are required as a string union. */\ntype RequiredKeys<T> = {\n\t[K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n}[keyof T];\n\n/** Sets all keys in `K` of type `T` to required. */\ntype Require<T, K extends PropertyKey> = Overwrite<\n\tT,\n\tRequired<Pick<T, K extends keyof T ? K : never>>\n>;\n\n// Tag ------------------------------------------------------------------------\n\n/**\n * All valid HTML & SVG elements in string format (`\"div\"`, `\"svg\"`, `\"input\"`)\n */\ntype ElementType = keyof JSX.IntrinsicElements;\n\n/** A React Fragment component. */\ntype FragmentType = ExoticComponent<FragmentProps>;\n\n/**\n * Valid candidates to fulfill the `root` prop when `as` is a\n * `FunctionComponent` derivative. This may be:\n * - A string representing a valid HTML or SVG element\n * - A React Fragment component\n */\ntype RootType = FragmentType | ElementType | '';\n\n/**\n * Valid candidates to fulfill the `as` prop. This may be:\n * - A string representing a valid HTML or SVG element\n * - A React FunctionComponent\n */\ntype PolymorphicElementType<P = any> = ElementType | FunctionComponent<P>;\n\n/**\n * Required return type of `createPolymorph`; a slightly more restrictive\n * version of `ReactNode`.\n */\ntype PolymorphicElement<T extends PolymorphicElementType> =\n\t| ReactElement<T>\n\t| ReactPortal\n\t| null;\n\n/** A generic props object. */\ntype Props = Record<PropertyKey, unknown>;\n\n/**\n * Infers the element type of `PolymorphicExoticComponent`, falling back to `T`\n * if `TT` it is not a `PolymorphicExoticComponent`. In essence, if `as` prop\n * is not specified, the element type will be `T`.\n */\ntype ElementOf<TT, T> =\n\tTT extends PolymorphicExoticComponent<infer E, any, any>\n\t\t? E\n\t\t: TT extends PolymorphicElementType\n\t\t\t? TT\n\t\t\t: T;\n\n/**\n * Used in `PolymorphicExoticComponent` to determine fallback of `TT`.\n * Attempts to extract a `PolymorphicElementType` from props of P, if present,\n * otherwise falls back to `T`.\n */\ntype AsProp<\n\tT extends PolymorphicElementType,\n\tP extends Props\n> = 'as' extends keyof P\n\t? P['as'] extends PolymorphicElementType\n\t\t? P['as']\n\t\t: T\n\t: T;\n\n/**\n * Used in `PolymorphicProps` to determine `ref` property value of `T` if it is\n * a valid `PolymorphicElementType`, otherwise returns an empty object. This is\n * used to ensure that `ref` prop is only available for valid element types.\n */\ntype RefOf<T extends PolymorphicElementType> =\n\tComponentRef<T> extends never ? {} : { ref?: Ref<ComponentRef<T>> };\n\n/**\n * Used in `PolymorphicProps` to determine `as` property value of `P['as']` if\n * it is a valid `PolymorphicElementType`, otherwise returns `T`. Respects\n * property optionality.\n */\ntype AsOf<\n\tT extends PolymorphicElementType,\n\tP extends Props\n> = 'as' extends keyof P\n\t? P['as'] extends PolymorphicElementType\n\t\t? IsOptionalKey<P, 'as'> extends true\n\t\t\t? { as?: P['as'] }\n\t\t\t: { as: P['as'] }\n\t\t: { as?: T }\n\t: { as?: T };\n\n// Props ----------------------------------------------------------------------\n\n/**\n * Base props of a component created using `createPolymorph` function,\n * available during implementation.\n *\n * @property as - The element type to render.\n * @property ref - The ref to the underlying element.\n */\ntype PolymorphicProps<T extends PolymorphicElementType, P extends Props> = AsOf<\n\tT,\n\tP\n> &\n\tRefOf<T>;\n\n/**\n * Base props of a component created using `createPolymorph` function,\n * available during rendering.\n *\n * @property as - Element type to render.\n * @property root - Root element type to render when `as` is a `FunctionComponent`.\n * @property ref - Ref of the underlying element.\n */\ntype PolymorphicExoticProps<\n\tT extends PolymorphicElementType,\n\tR extends RootType\n> = {\n\tas?: T | PolymorphicElementType | PolymorphicExoticComponent<any, any, any>;\n\troot?: FragmentType | Exclude<R | ElementType, ''>;\n} & RefOf<R extends '' ? T : R>;\n\n/**\n * Composite props of a component created using `createPolymorph` function,\n * available during implementation. Combines props `P` with inherited element\n * props `T`, modified using `Config` type `C`.\n *\n * @property as - Element type to render.\n * @property ref - Ref of underlying element.\n */\ntype PolymorphicComponentProps<\n\tT extends PolymorphicElementType,\n\tP extends Props,\n\tC extends Config<T>\n> = Overwrite<\n\tOverwrite<ApplyConfig<T, C>, Omit<P, 'as'>>,\n\tPolymorphicProps<T, P>\n>;\n\n/**\n * Composite props of a component created using `createPolymorph` function,\n * available during rendering. Comines props `P` with inherited element props\n * `T`, modified using `Config` type `C`.\n *\n * @property as - Element type to render.\n * @property root - Root element type to render when `as` is a `FunctionComponent`.\n * @property ref - Ref of underlying element.\n */\ntype PolymorphicExoticComponentProps<\n\tT extends PolymorphicElementType,\n\tP extends Props,\n\tC extends Config<T>,\n\tR extends RootType\n> = Overwrite<\n\tOverwrite<ApplyConfig<R extends '' ? T : R, C>, P>,\n\tPolymorphicExoticProps<T, R>\n>;\n\n/**\n * Component render function passed into `createPolymorph` during\n * initialization as first argument.\n *\n * @param props - Props passed to component.\n * @returns React element to render.\n */\ntype PolymorphicRenderFunction<\n\tT extends PolymorphicElementType,\n\tP extends Props,\n\tC extends Config<T>\n> = {\n\t(props: PolymorphicComponentProps<T, P, C>): PolymorphicElement<T>;\n\tdisplayName?: string;\n};\n\n/**\n * A component created using `createPolymorph` function, which can render\n * different element types based on the `as` prop.\n *\n * When `props` are passed with a modified `as` prop from the default `T`,\n * props will be inferred from the new externally set `as` value; changing\n * inferred props from `T` to `TT` element type.\n *\n * If, in addition to a modified external `as` (`TT`), a `root` prop is also\n * set; the `root` prop will be used to determine the final element type to render,\n * and props will be inferred from the `root` element type instead of the `as`\n * element type.\n *\n * @param props - Props passed to component; including `as` and `root` props.\n * @returns React element to render.\n */\ntype PolymorphicExoticComponent<\n\tT extends PolymorphicElementType,\n\tP extends Props,\n\tC extends Config<T>\n> = {\n\t<TT = AsProp<T, P>, R extends RootType = ''>(\n\t\tprops: TT extends T\n\t\t\t? PolymorphicComponentProps<T, P, C>\n\t\t\t: TT extends PolymorphicExoticComponent<any, any, any>\n\t\t\t\t? PolymorphicExoticComponentProps<\n\t\t\t\t\t\tElementOf<TT, T>,\n\t\t\t\t\t\tOverwrite<P, InferPolymorphProps<TT>>,\n\t\t\t\t\t\tOverwrite<C, InferPolymorphConfig<TT>>,\n\t\t\t\t\t\tR\n\t\t\t\t\t>\n\t\t\t\t: PolymorphicComponentProps<\n\t\t\t\t\t\tElementOf<TT, T>,\n\t\t\t\t\t\tOverwrite<P, InferPolymorphProps<TT>>,\n\t\t\t\t\t\tOverwrite<C, InferPolymorphConfig<TT>>\n\t\t\t\t\t>\n\t): PolymorphicElement<ElementOf<TT, T>>;\n\tdisplayName?: string;\n};\n\n// Config ---------------------------------------------------------------------\n\n/** A generic config object. */\ntype Config<T extends PolymorphicElementType> = {\n\t[K in keyof ComponentProps<T> | (string & {})]?: unknown;\n};\n\ntype ResolveInherit<CK, PK> = [Extract<CK, Inherit>] extends [never]\n\t? CK\n\t: [Exclude<CK, Inherit>] extends [never]\n\t\t? PK\n\t\t: Exclude<CK, Inherit> | PK;\n\ntype ApplyValues<\n\tP,\n\tC,\n\tPS = Omit<P, keyof (ExtractUnset<C> & JSX.IntrinsicAttributes)>\n> = {\n\t[K in keyof PS]: K extends keyof C ? ResolveInherit<C[K], PS[K]> : PS[K];\n};\n\ntype ApplyConfig<\n\tT extends PolymorphicElementType,\n\tC extends Config<T>\n> = Require<ApplyValues<ComponentProps<T & {}>, C>, RequiredKeys<C>>;\n\n// Helpers --------------------------------------------------------------------\n\n/**\n * A branded type used in `Config` to indicate that a prop should be removed\n * from inferred props of `as`.\n */\nexport type Unset = { readonly _unset: unique symbol };\n\n/**\n * A branded type used in `Config` to indicate that a prop should be inherited\n * from inferred props of `as`.\n */\nexport type Inherit = { readonly _inherit: unique symbol };\n\n/**\n * A code-hinting friendly `Config` creator for `createPolymorph`, displaying\n * all available props for the given `as` element type. This type-helper is\n * not required to create a valid `Config` type, but is useful for code-hinting\n * and auto-completion in IDEs.\n *\n * @example ```tsx\n * type Config = PolymorphicConfig<'button', {\n * title: string | number;\n * onClick: Inherit\n * type: Unset\n * }>\n *\n * const Component = createPolymorph<'button', Props, Config>(...);\n */\nexport type PolymorphicConfig<\n\tT extends PolymorphicElementType,\n\tC extends Config<T>\n> = C & { readonly _tag?: T };\n\n/**\n * Infers the `as` prop type from a `PolymorphicExoticComponent`.\n *\n * @example ```tsx\n * const Component = createPolymorph<'div', Props, Config>(...);\n * type Result = InferPolymorphElement<typeof Component>; // 'div'\n * ```\n */\nexport type InferPolymorphElement<T> =\n\tT extends PolymorphicExoticComponent<infer Tag, any, any> ? Tag : unknown;\n\n/**\n * Infers the props type from a `PolymorphicExoticComponent`.\n *\n * @example ```tsx\n * const Component = createPolymorph<'div', Props, Config>(...);\n * type Result = InferPolymorphProps<typeof Component>; // Props\n * ```\n */\nexport type InferPolymorphProps<T> =\n\tT extends PolymorphicExoticComponent<any, infer P, any> ? P : {};\n\n/**\n * Infers the config type from a `PolymorphicExoticComponent`.\n *\n * @example ```tsx\n * const Component = createPolymorph<'div', Props, Config>(...);\n * type Result = InferPolymorphConfig<typeof Component>; // Config\n * ```\n */\nexport type InferPolymorphConfig<T> =\n\tT extends PolymorphicExoticComponent<any, any, infer C> ? C : {};\n\n// Implementation -------------------------------------------------------------\n\ntype CreatePolymorph = <\n\tT extends PolymorphicElementType,\n\tP extends Props = {},\n\tC extends PolymorphicConfig<T, Config<T>> = {}\n>(\n\trender: NoInfer<PolymorphicRenderFunction<T, P, C>>\n) => NoInfer<PolymorphicExoticComponent<T, P, C>>;\n\n/**\n * **Creates a polymorphic component.**\n * This combines user-provided props `P`, inherited props from `T`, and any\n * optional modifications to `T` specified in `C`.\n *\n * In addition to inherited and user-provided props; exposes following props:\n * - `as`: Specifies the element type to render to DOM.\n * - `root`: When `as` is set to another `createPolymorph` created component,\n * `root` overrides the internal `as` prop of the component being rendered,\n * allowing for a different element type to be rendered.\n *\n * @param render - Render function of `PolymorphicExoticComponent`.\n *\n * @returns `PolymorphicExoticComponent`\n *\n * ---\n * **Simple Usage**\n *\n * This is the most common use-case for `createPolymorph`, where a component is\n * created with a default element type `T` and basic props `P`.\n *\n * @example\n * ```tsx\n * type DefaultTag = 'button'\n *\n * type ButtonProps = {\n * variant: 'primary' | 'secondary';\n * }\n *\n * const Button = createPolymorph<DefaultTag, ButtonProps>(\n * ({ as: Tag = 'button', variant, ...rest }) => {\n * const isPrimary = variant === 'primary'\n * return <Tag className={isPrimary ? 'bg-black' : 'bg-gray'} {...rest} />\n * }\n * )\n *\n * const App = () => {\n * return <Button as=\"a\" href=\"/\" variant=\"primary\">Home</Button>\n * }\n * ```\n *\n * **Advanced Usage**\n *\n * This use-case leverages as many features of `createPolymorph` as possible in\n * an effort to showcase deeper capabilities. Leverages `Button` from\n * \"**Simple Usage**\".\n *\n * @example\n * ```tsx\n * type DefaultTag = typeof Button;\n *\n * type AdvancedButtonProps = {\n * loading?: boolean;\n * size: 'small' | 'medium' | 'large';\n * }\n *\n * type AdvancedButtonConfig = PolymorphicConfig<DefaultTag, {\n * // Set as required and change type\n * children: string | number;\n * // Set as required and inherit type from `T`\n * onClick: Inherit;\n * // Change type\n * title?: number;\n * // Remove property\n * type: Unset;\n * // If `as` is set to an element containing `href`, require it.\n * href: Inherit\n * }>\n *\n * const AdvancedButton = createPolymorph<\n * DefaultTag,\n * AdvancedButtonProps,\n * AdvancedButtonConfig\n * >(\n * ({ as: Tag = Button, loading, size, ...rest }) => {\n * const sizeClass = (() => {\n * if (size === 'small') return 'h-8';\n * if (size === 'medium') return 'h-10';\n * if (size === 'large') return 'h-12';\n * return '';\n * }())\n *\n * return (\n * <Tag\n * className={`${className} ${sizeClass}`}\n * aria-loading={loading}\n * {...rest}\n * />\n * )\n * }\n * )\n *\n * const App = () => {\n * return (\n * <AdvancedButton\n * as=\"a\"\n * href=\"/\"\n * variant=\"primary\"\n * size=\"large\"\n * loading={true}\n * title={24}\n * onClick={() => console.log('clicked')}\n * >\n * Home\n * </AdvancedButton>\n * )\n * }\n * ```\n */\nexport const createPolymorph = (<\n\tT extends PolymorphicElementType,\n\tP extends Props = {},\n\tC extends PolymorphicConfig<T, Config<T>> = {}\n>(\n\trender: NoInfer<PolymorphicRenderFunction<T, P, C>>\n): NoInfer<PolymorphicExoticComponent<T, P, C>> => {\n\ttype AdapterFunction = {\n\t\t(props: Props): ReturnType<FunctionComponent>;\n\t\tdisplayName?: string;\n\t};\n\n\tconst cache = new WeakMap<\n\t\tFunction,\n\t\tMap<ElementType | FragmentType, AdapterFunction>\n\t>();\n\n\tconst _render = (\n\t\tprops: PolymorphicComponentProps<T, P, C> & {\n\t\t\troot?: FragmentType | ElementType;\n\t\t}\n\t) => {\n\t\tconst { as, root, ...rest } = props;\n\n\t\tlet _as = as;\n\n\t\tif (typeof as === 'function' && root) {\n\t\t\tconst map = cache.get(as) ?? new Map();\n\t\t\tcache.set(as, map);\n\n\t\t\tif (!map.has(root)) {\n\t\t\t\tconst adapter: AdapterFunction = (props) => as({ ...props, as: root });\n\n\t\t\t\tif ('displayName' in as) adapter.displayName = as.displayName;\n\t\t\t\tmap.set(root, adapter);\n\t\t\t}\n\n\t\t\t_as = map.get(root) ?? as;\n\t\t}\n\n\t\treturn render({ ...rest, as: _as } as PolymorphicComponentProps<T, P, C>);\n\t};\n\n\t_render.displayName =\n\t\trender.displayName || render.name || 'PolymorphicComponent';\n\n\treturn _render as PolymorphicExoticComponent<T, P, C>;\n}) as CreatePolymorph;\n"],"mappings":";AAcA,SAAS,eAAe;AAIxB,IAAM,UAAU,QAAQ,IAAI,aAAa;AAQzC,SAAS,OACR,WACA,SACA,WACoB;AACpB,MAAI,UAAW;AACf,QAAM,KAAK,aAAa,OAAO,OAAO;AACvC;AAEA,IAAI,SAAS;AACZ;AAAA,IACC,SAAS,QAAQ,MAAM,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK;AAAA,IACvC;AAAA,EACD;AACD;AA+cO,IAAM,mBAAmB,CAK/B,WACkD;AAMlD,QAAM,QAAQ,oBAAI,QAGhB;AAEF,QAAM,UAAU,CACf,UAGI;AACJ,UAAM,EAAE,IAAI,MAAM,GAAG,KAAK,IAAI;AAE9B,QAAI,MAAM;AAEV,QAAI,OAAO,OAAO,cAAc,MAAM;AACrC,YAAM,MAAM,MAAM,IAAI,EAAE,KAAK,oBAAI,IAAI;AACrC,YAAM,IAAI,IAAI,GAAG;AAEjB,UAAI,CAAC,IAAI,IAAI,IAAI,GAAG;AACnB,cAAM,UAA2B,CAACA,WAAU,GAAG,EAAE,GAAGA,QAAO,IAAI,KAAK,CAAC;AAErE,YAAI,iBAAiB,GAAI,SAAQ,cAAc,GAAG;AAClD,YAAI,IAAI,MAAM,OAAO;AAAA,MACtB;AAEA,YAAM,IAAI,IAAI,IAAI,KAAK;AAAA,IACxB;AAEA,WAAO,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,CAAuC;AAAA,EACzE;AAEA,UAAQ,cACP,OAAO,eAAe,OAAO,QAAQ;AAEtC,SAAO;AACR;","names":["props"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "react-polymorphic",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Create polymorphic React 19+ components with strong TypeScript inference.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"react",
|
|
7
|
+
"typescript",
|
|
8
|
+
"polymorphic",
|
|
9
|
+
"component-library",
|
|
10
|
+
"design-system",
|
|
11
|
+
"as-prop",
|
|
12
|
+
"headless-ui",
|
|
13
|
+
"ui"
|
|
14
|
+
],
|
|
15
|
+
"author": "Dashice",
|
|
16
|
+
"license": "Apache-2.0",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/Dashice/react-polymorphic.git"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://github.com/Dashice/react-polymorphic#readme",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/Dashice/react-polymorphic/issues"
|
|
24
|
+
},
|
|
25
|
+
"type": "module",
|
|
26
|
+
"types": "dist/index.d.ts",
|
|
27
|
+
"files": [
|
|
28
|
+
"dist",
|
|
29
|
+
"README.md",
|
|
30
|
+
"LICENSE",
|
|
31
|
+
"NOTICE"
|
|
32
|
+
],
|
|
33
|
+
"exports": {
|
|
34
|
+
".": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"import": "./dist/index.js"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"packageManager": "pnpm@10.20.0",
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=22.0.0"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"clean": "rm -rf dist",
|
|
45
|
+
"build": "pnpm clean && tsup && tsc -p tsconfig.build.json",
|
|
46
|
+
"prepack": "pnpm build",
|
|
47
|
+
"format": "biome format . --write",
|
|
48
|
+
"format:check": "biome format .",
|
|
49
|
+
"lint": "biome lint .",
|
|
50
|
+
"lint:fix": "biome lint . --write",
|
|
51
|
+
"check": "biome check . --write",
|
|
52
|
+
"test": "vitest",
|
|
53
|
+
"test:run": "vitest run",
|
|
54
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
55
|
+
"lint:staged": "lint-staged",
|
|
56
|
+
"changeset": "changeset",
|
|
57
|
+
"version:packages": "changeset version",
|
|
58
|
+
"release": "changeset publish",
|
|
59
|
+
"prepare": "husky"
|
|
60
|
+
},
|
|
61
|
+
"dependencies": {},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@biomejs/biome": "^2.4.16",
|
|
64
|
+
"@changesets/cli": "^2.31.1",
|
|
65
|
+
"@testing-library/dom": "^10.4.1",
|
|
66
|
+
"@testing-library/react": "^16.3.2",
|
|
67
|
+
"@types/node": "^24.0.0",
|
|
68
|
+
"@types/react": "^19.2.15",
|
|
69
|
+
"happy-dom": "^20.9.0",
|
|
70
|
+
"husky": "^9.1.7",
|
|
71
|
+
"lint-staged": "^17.2.0",
|
|
72
|
+
"react": "^19.2.7",
|
|
73
|
+
"react-dom": "^19.2.7",
|
|
74
|
+
"tsup": "^8.5.1",
|
|
75
|
+
"typescript": "^7.0.2",
|
|
76
|
+
"vitest": "^2.1.9"
|
|
77
|
+
},
|
|
78
|
+
"peerDependencies": {
|
|
79
|
+
"react": ">=19.0.0",
|
|
80
|
+
"react-dom": ">=19.0.0",
|
|
81
|
+
"typescript": ">=5.4.0"
|
|
82
|
+
}
|
|
83
|
+
}
|