@lynstack/recipe 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 +21 -0
- package/README.md +63 -0
- package/dist/index.d.ts +253 -0
- package/dist/index.js +153 -0
- package/dist/index.js.map +1 -0
- package/package.json +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tim Phan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# @lynstack/recipe
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@lynstack/recipe)
|
|
4
|
+
[](https://bundlephobia.com/package/@lynstack/recipe)
|
|
5
|
+
[](https://github.com/lynstack/recipe/actions/workflows/ci-recipe.yml)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
Fast, type-safe recipes for values of any type. Define a kind of recipe by
|
|
9
|
+
how it combines values, such as class names or style objects, then create
|
|
10
|
+
recipes of that kind: functions that map a component's variants to its
|
|
11
|
+
result.
|
|
12
|
+
|
|
13
|
+
**[Read the documentation](https://lynstack.github.io/recipe/recipe/)**
|
|
14
|
+
|
|
15
|
+
[`@lynstack/class-recipe`](https://www.npmjs.com/package/@lynstack/class-recipe)
|
|
16
|
+
is built on it. Use `@lynstack/class-recipe` to style components with class
|
|
17
|
+
names; use this package to create recipes for other values.
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install @lynstack/recipe
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { createRecipeKind } from "@lynstack/recipe";
|
|
29
|
+
|
|
30
|
+
type Style = Readonly<Record<string, string | number>>;
|
|
31
|
+
|
|
32
|
+
const styleRecipe = createRecipeKind({
|
|
33
|
+
initial: (base?: Style): Style => ({ ...base }),
|
|
34
|
+
reduce: (style, value: Style): Style => ({ ...style, ...value }),
|
|
35
|
+
finish: (style): Style => Object.freeze(style),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const text = styleRecipe({
|
|
39
|
+
base: { color: "black" },
|
|
40
|
+
variants: {
|
|
41
|
+
size: { sm: { fontSize: 12 }, lg: { fontSize: 24 } },
|
|
42
|
+
muted: { true: { opacity: 0.6 } },
|
|
43
|
+
},
|
|
44
|
+
compoundVariants: [
|
|
45
|
+
{ variants: { size: "lg", muted: true }, value: { fontWeight: 300 } },
|
|
46
|
+
],
|
|
47
|
+
defaultVariants: { size: "sm" },
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
text(); // => { color: "black", fontSize: 12 }
|
|
51
|
+
|
|
52
|
+
text({ size: "lg", muted: true });
|
|
53
|
+
// => { color: "black", fontSize: 24, opacity: 0.6, fontWeight: 300 }
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
See [Recipe kinds](https://lynstack.github.io/recipe/recipe/recipe-kinds/)
|
|
57
|
+
for what each function of a kind does, and
|
|
58
|
+
[Practices](https://lynstack.github.io/recipe/recipe/practices/) for how to
|
|
59
|
+
write kinds that stay fast.
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
[MIT](LICENSE)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Turns a type's intersections into a single object type, so editors show
|
|
4
|
+
* its properties instead of the types it was built from.
|
|
5
|
+
*/
|
|
6
|
+
type Simplify<Type> = { [Key in keyof Type]: Type[Key]; };
|
|
7
|
+
type OptionName<Options> = `${Extract<keyof Options, string | number>}`;
|
|
8
|
+
type BooleanName = "true" | "false";
|
|
9
|
+
type NumberOption<Options> = Extract<keyof Options, number>;
|
|
10
|
+
type BooleanOption<Name extends string> = [Extract<Name, BooleanName>] extends [never] ? never : BooleanName | boolean;
|
|
11
|
+
type BooleanVariantName<Variants> = { [Name in keyof Variants]: [OptionName<Variants[Name]>] extends [never] ? never : [OptionName<Variants[Name]>] extends [BooleanName] ? Name : never; }[keyof Variants];
|
|
12
|
+
/**
|
|
13
|
+
* The values accepted for one variant: the names of its options, as
|
|
14
|
+
* strings or, for numeric names, as numbers, plus `true`, `false`, `"true"`,
|
|
15
|
+
* and `"false"` when it declares an option named `"true"` or `"false"`.
|
|
16
|
+
*
|
|
17
|
+
* @typeParam Options - The options of the variant, keyed by option name.
|
|
18
|
+
*/
|
|
19
|
+
type VariantOption<Options> = OptionName<Options> | NumberOption<Options> | BooleanOption<OptionName<Options>>;
|
|
20
|
+
/**
|
|
21
|
+
* The variants a selection names. A variant with a default may be omitted,
|
|
22
|
+
* and so may a boolean variant, whose only options are `"true"` and
|
|
23
|
+
* `"false"`; any other variant is required.
|
|
24
|
+
*
|
|
25
|
+
* @typeParam Variants - The variant definitions, keyed by variant name.
|
|
26
|
+
* @typeParam DefaultedName - The names of the variants that have a default.
|
|
27
|
+
*/
|
|
28
|
+
type VariantSelection<Variants, DefaultedName extends keyof Variants> = Simplify<{ readonly [Name in Exclude<keyof Variants, DefaultedName | BooleanVariantName<Variants>>]: VariantOption<Variants[Name]>; } & { readonly [Name in DefaultedName | BooleanVariantName<Variants>]?: VariantOption<Variants[Name]> | undefined; }>;
|
|
29
|
+
/**
|
|
30
|
+
* The option each defaulted variant uses when a selection leaves it out.
|
|
31
|
+
*
|
|
32
|
+
* @typeParam Variants - The variant definitions, keyed by variant name.
|
|
33
|
+
* @typeParam DefaultedName - The names of the variants that have a default.
|
|
34
|
+
*/
|
|
35
|
+
type DefaultVariants<Variants, DefaultedName extends keyof Variants> = { readonly [Name in DefaultedName]: VariantOption<NoInfer<Variants>[Name]>; };
|
|
36
|
+
/**
|
|
37
|
+
* The condition of a compound variant: for each variant it names, the option
|
|
38
|
+
* or the list of options that it matches. A variant left out matches any
|
|
39
|
+
* option.
|
|
40
|
+
*
|
|
41
|
+
* @typeParam Variants - The variant definitions, keyed by variant name.
|
|
42
|
+
*/
|
|
43
|
+
type CompoundCondition<Variants> = { readonly [Name in keyof Variants]?: VariantOption<Variants[Name]> | readonly VariantOption<Variants[Name]>[] | undefined; };
|
|
44
|
+
/**
|
|
45
|
+
* A function that takes the properties of a selection, whose argument is
|
|
46
|
+
* optional when every property of `Props` is.
|
|
47
|
+
*
|
|
48
|
+
* @typeParam Props - The properties the function accepts.
|
|
49
|
+
* @typeParam Result - What the function returns.
|
|
50
|
+
*/
|
|
51
|
+
type RecipeFunction<Props, Result> = Partial<Props> extends Props ? (props?: Props) => Result : (props: Props) => Result;
|
|
52
|
+
type KeyName<Key> = Key extends string ? Key : Key extends number ? `${Key}` : never;
|
|
53
|
+
/**
|
|
54
|
+
* The name of each variant in a selection, as a string.
|
|
55
|
+
*
|
|
56
|
+
* @typeParam Selection - The variants a selector accepts.
|
|
57
|
+
*/
|
|
58
|
+
type VariantKey<Selection> = KeyName<keyof Selection>;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/variants.d.ts
|
|
61
|
+
/**
|
|
62
|
+
* Variant definitions in the loose shape the runtime works with: for each
|
|
63
|
+
* variant name, the value of each of its options.
|
|
64
|
+
*/
|
|
65
|
+
type LooseVariants<Value> = Readonly<Record<string, Readonly<Record<string, Value>>>>;
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region src/recipe-kind.d.ts
|
|
68
|
+
/**
|
|
69
|
+
* How a kind of recipe turns the values of a selection into its result,
|
|
70
|
+
* such as by joining class names or merging style objects.
|
|
71
|
+
*
|
|
72
|
+
* @typeParam Value - The value of an option.
|
|
73
|
+
* @typeParam Accumulator - What the values of a selection are reduced to.
|
|
74
|
+
* @typeParam Result - What a recipe of this kind returns.
|
|
75
|
+
*/
|
|
76
|
+
interface RecipeKind<Value, Accumulator, Result> {
|
|
77
|
+
/**
|
|
78
|
+
* Returns the accumulator that the values of a selection are reduced
|
|
79
|
+
* into, starting from the recipe's `base`, which is `undefined` when the
|
|
80
|
+
* recipe has none. It is called for each result a recipe builds, so it
|
|
81
|
+
* can return a new object each time.
|
|
82
|
+
*/
|
|
83
|
+
readonly initial: (base: Value | undefined) => Accumulator;
|
|
84
|
+
/**
|
|
85
|
+
* Adds a value to the accumulator and returns the accumulator. It is
|
|
86
|
+
* called with the values that apply to a selection, in order of
|
|
87
|
+
* precedence: the value of each variant's selected option, in the order
|
|
88
|
+
* of `variants`, then the value of each matching compound variant, in the
|
|
89
|
+
* order of `compoundVariants`. An option or compound variant whose value
|
|
90
|
+
* is `undefined` adds nothing.
|
|
91
|
+
*/
|
|
92
|
+
readonly reduce: (accumulator: Accumulator, value: Value) => Accumulator;
|
|
93
|
+
/**
|
|
94
|
+
* Turns the accumulator into the result, for example by freezing it.
|
|
95
|
+
* Without it, the result is the accumulator.
|
|
96
|
+
*/
|
|
97
|
+
readonly finish?: ((accumulator: Accumulator) => Result) | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Whether a recipe builds the result of each declared selection once and
|
|
100
|
+
* returns it again for the same selection. Defaults to `true`.
|
|
101
|
+
*/
|
|
102
|
+
readonly cache?: boolean | undefined;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Any selection, for variants whose names are not known at compile time,
|
|
106
|
+
* such as `Record<string, Record<string, string>>`.
|
|
107
|
+
*/
|
|
108
|
+
type AnySelection = Readonly<Record<string, unknown>>;
|
|
109
|
+
/** The selection of a recipe, or any selection for unknown variant names. */
|
|
110
|
+
type KindSelection<Variants, DefaultedName extends keyof Variants> = string extends keyof Variants ? AnySelection : VariantSelection<Variants, DefaultedName>;
|
|
111
|
+
/** The condition of a compound variant, or any for unknown variant names. */
|
|
112
|
+
type KindCompoundCondition<Variants> = string extends keyof Variants ? AnySelection : CompoundCondition<Variants>;
|
|
113
|
+
/** The default variants of a recipe, or any for unknown variant names. */
|
|
114
|
+
type KindDefaultVariants<Variants, DefaultedName extends keyof Variants> = string extends keyof Variants ? AnySelection : DefaultVariants<Variants, DefaultedName>;
|
|
115
|
+
/**
|
|
116
|
+
* The variants of a {@link KindRecipeConfig}: for each variant name, the
|
|
117
|
+
* value of each of its options.
|
|
118
|
+
*
|
|
119
|
+
* @typeParam Value - The value of an option.
|
|
120
|
+
*/
|
|
121
|
+
type KindVariants<Value> = LooseVariants<Value>;
|
|
122
|
+
/**
|
|
123
|
+
* A value added when several variants have particular options at the same
|
|
124
|
+
* time.
|
|
125
|
+
*
|
|
126
|
+
* @typeParam Variants - The variant definitions of the recipe.
|
|
127
|
+
* @typeParam Value - The value of an option.
|
|
128
|
+
*/
|
|
129
|
+
interface KindCompoundVariant<Variants, Value> {
|
|
130
|
+
/**
|
|
131
|
+
* The options that must all be selected for
|
|
132
|
+
* {@link KindCompoundVariant.value} to apply.
|
|
133
|
+
*/
|
|
134
|
+
readonly variants: KindCompoundCondition<Variants>;
|
|
135
|
+
/** The value added when the condition matches. */
|
|
136
|
+
readonly value: Value;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The configuration of a recipe made from a {@link RecipeKind}.
|
|
140
|
+
*
|
|
141
|
+
* @typeParam Value - The value of an option.
|
|
142
|
+
* @typeParam Variants - The variant definitions, keyed by variant name.
|
|
143
|
+
* @typeParam DefaultedName - The names of the variants that have a default.
|
|
144
|
+
*/
|
|
145
|
+
interface KindRecipeConfig<Value, Variants extends KindVariants<Value>, DefaultedName extends keyof Variants> {
|
|
146
|
+
/** The value that the values of every selection are added to. */
|
|
147
|
+
readonly base?: Value | undefined;
|
|
148
|
+
/** For each variant name, the value of each of its options. */
|
|
149
|
+
readonly variants: Variants;
|
|
150
|
+
/**
|
|
151
|
+
* Values added when several variants have particular options at the same
|
|
152
|
+
* time, applied in order after the values of the variants' options.
|
|
153
|
+
*/
|
|
154
|
+
readonly compoundVariants?: readonly KindCompoundVariant<NoInfer<Variants>, Value>[] | undefined;
|
|
155
|
+
/** The option each variant uses when the recipe is called without it. */
|
|
156
|
+
readonly defaultVariants?: KindDefaultVariants<Variants, DefaultedName> | undefined;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* A recipe made from a {@link RecipeKind}: a function that returns the
|
|
160
|
+
* result of a selection of variants, with the names of those variants in
|
|
161
|
+
* `variantKeys`.
|
|
162
|
+
*
|
|
163
|
+
* @typeParam Selection - The variants the recipe accepts.
|
|
164
|
+
* @typeParam Result - What the recipe returns.
|
|
165
|
+
*/
|
|
166
|
+
type KindRecipe<Selection, Result> = RecipeFunction<Selection, Result> & {
|
|
167
|
+
/**
|
|
168
|
+
* The names of the recipe's variants, in the order of
|
|
169
|
+
* `Object.keys(config.variants)`.
|
|
170
|
+
*/
|
|
171
|
+
readonly variantKeys: readonly VariantKey<Selection>[];
|
|
172
|
+
};
|
|
173
|
+
/**
|
|
174
|
+
* Creates recipes of one kind, the function that {@link createRecipeKind}
|
|
175
|
+
* returns.
|
|
176
|
+
*
|
|
177
|
+
* @typeParam Value - The value of an option.
|
|
178
|
+
* @typeParam Result - What a recipe of this kind returns.
|
|
179
|
+
* @param config - The base value, variants, compound variants, and default
|
|
180
|
+
* variants of the recipe.
|
|
181
|
+
* @returns The recipe.
|
|
182
|
+
*/
|
|
183
|
+
type CreateKindRecipe<Value, Result> = <const Variants extends KindVariants<Value>, const DefaultedName extends keyof Variants = never>(config: KindRecipeConfig<Value, Variants, DefaultedName>) => KindRecipe<KindSelection<Variants, DefaultedName>, Result>;
|
|
184
|
+
/**
|
|
185
|
+
* Creates a kind of recipe from how it turns the values of a selection into
|
|
186
|
+
* its result, and returns the function that creates recipes of that kind.
|
|
187
|
+
* A recipe maps a selection of variants to a result, as `cva` of
|
|
188
|
+
* `@lynstack/class-recipe` does for class names, for values of any type,
|
|
189
|
+
* such as style objects.
|
|
190
|
+
*
|
|
191
|
+
* @remarks
|
|
192
|
+
* For each selection, a recipe reduces the value of each variant's selected
|
|
193
|
+
* option and the value of each matching compound variant, with
|
|
194
|
+
* `kind.reduce`, into the accumulator that `kind.initial` returns for the
|
|
195
|
+
* recipe's base, then passes it to `kind.finish`. A variant whose only
|
|
196
|
+
* options are `"true"` and `"false"` defaults to `false`, an option that the
|
|
197
|
+
* config does not declare adds no value, and properties of the selection
|
|
198
|
+
* that are not variants are ignored. A recipe's `variantKeys` property lists
|
|
199
|
+
* the names of its variants.
|
|
200
|
+
*
|
|
201
|
+
* With the cache, a recipe builds the result of each declared selection
|
|
202
|
+
* once, and calling it again with the same variants returns the same
|
|
203
|
+
* result. Freeze an object result in `kind.finish` so that callers cannot
|
|
204
|
+
* change a result that later calls share. A selection with an undeclared
|
|
205
|
+
* option is built on every call.
|
|
206
|
+
*
|
|
207
|
+
* When the variant names are not known at compile time, as in a library
|
|
208
|
+
* that passes on a config it received, a recipe accepts any selection.
|
|
209
|
+
*
|
|
210
|
+
* @typeParam Value - The value of an option, inferred from the `value`
|
|
211
|
+
* parameter of `kind.reduce` or the `base` parameter of `kind.initial`.
|
|
212
|
+
* @typeParam Accumulator - What the values are reduced to, inferred from
|
|
213
|
+
* `kind.initial`.
|
|
214
|
+
* @typeParam Result - What a recipe returns, inferred from `kind.finish`,
|
|
215
|
+
* or the accumulator without it.
|
|
216
|
+
* @param kind - How a recipe turns the values of a selection into its
|
|
217
|
+
* result, and whether it caches the result.
|
|
218
|
+
* @returns The function that creates recipes of this kind.
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* ```ts
|
|
222
|
+
* type Style = Readonly<Record<string, string | number>>;
|
|
223
|
+
*
|
|
224
|
+
* const styleRecipe = createRecipeKind({
|
|
225
|
+
* initial: (base?: Style): Record<string, string | number> => ({ ...base }),
|
|
226
|
+
* reduce: (style, value: Style) => Object.assign(style, value),
|
|
227
|
+
* finish: (style): Style => Object.freeze(style),
|
|
228
|
+
* });
|
|
229
|
+
*
|
|
230
|
+
* const text = styleRecipe({
|
|
231
|
+
* base: { color: "black" },
|
|
232
|
+
* variants: {
|
|
233
|
+
* size: { sm: { fontSize: 12 }, lg: { fontSize: 24 } },
|
|
234
|
+
* muted: { true: { opacity: 0.6 } },
|
|
235
|
+
* },
|
|
236
|
+
* compoundVariants: [
|
|
237
|
+
* { variants: { size: "lg", muted: true }, value: { fontWeight: 300 } },
|
|
238
|
+
* ],
|
|
239
|
+
* defaultVariants: { size: "sm" },
|
|
240
|
+
* });
|
|
241
|
+
*
|
|
242
|
+
* text(); // => { color: "black", fontSize: 12 }
|
|
243
|
+
*
|
|
244
|
+
* text({ size: "lg", muted: true });
|
|
245
|
+
* // => { color: "black", fontSize: 24, opacity: 0.6, fontWeight: 300 }
|
|
246
|
+
*
|
|
247
|
+
* text.variantKeys; // => ["size", "muted"]
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
declare function createRecipeKind<Value, Accumulator, Result = Accumulator>(kind: RecipeKind<Value, Accumulator, Result>): CreateKindRecipe<Value, Result>;
|
|
251
|
+
//#endregion
|
|
252
|
+
export { type CompoundCondition, type CreateKindRecipe, type DefaultVariants, type KindCompoundVariant, type KindRecipe, type KindRecipeConfig, type KindVariants, type RecipeFunction, type RecipeKind, type VariantOption, type VariantSelection, createRecipeKind };
|
|
253
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
const noProps = Object.freeze({});
|
|
2
|
+
/**
|
|
3
|
+
* Prepares variants for selecting values. A variant that declares an option
|
|
4
|
+
* named `"true"` or `"false"` also declares the other one, with
|
|
5
|
+
* `config.noValue`, and a variant whose only options are those defaults to
|
|
6
|
+
* `"false"`. A compound variant that names an undeclared variant or option,
|
|
7
|
+
* or lists no option for a variant, never matches and is left out.
|
|
8
|
+
*/
|
|
9
|
+
function compileVariants(config) {
|
|
10
|
+
const names = Object.keys(config.variants);
|
|
11
|
+
const optionValues = names.map((name) => withBooleanOptions(config.variants[name] ?? {}, config.noValue));
|
|
12
|
+
const indexByOption = optionValues.map((valuesByOption) => new Map(Object.keys(valuesByOption).map((option, index) => [option, index + 1])));
|
|
13
|
+
const radixes = indexByOption.map((indexes) => indexes.size + 1);
|
|
14
|
+
return {
|
|
15
|
+
compounds: compileCompounds(config.compoundVariants, names, indexByOption),
|
|
16
|
+
defaultOptions: names.map((name, index) => toOptionName(config.defaultVariants[name]) ?? (isBooleanVariant(indexByOption[index]) ? "false" : void 0)),
|
|
17
|
+
indexByOption,
|
|
18
|
+
isCacheable: product(radixes) <= Number.MAX_SAFE_INTEGER,
|
|
19
|
+
names,
|
|
20
|
+
strides: radixes.map((_radix, index) => product(radixes.slice(0, index))),
|
|
21
|
+
valuesByIndex: valuesByIndexOf(optionValues, config.noValue)
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Writes the option index of each variant for `selected` into `indexes`
|
|
26
|
+
* and returns the selection's key, or {@link undeclared} when an option is
|
|
27
|
+
* not declared.
|
|
28
|
+
*/
|
|
29
|
+
function select(compiled, selected, indexes) {
|
|
30
|
+
let key = 0;
|
|
31
|
+
for (let variant = 0; variant < compiled.names.length; variant += 1) {
|
|
32
|
+
const index = selectIndex(compiled, selected, variant);
|
|
33
|
+
indexes[variant] = index ?? 0;
|
|
34
|
+
key = index === void 0 || key === -1 ? -1 : key + index * (compiled.strides[variant] ?? 0);
|
|
35
|
+
}
|
|
36
|
+
return key;
|
|
37
|
+
}
|
|
38
|
+
function selectIndex(compiled, selected, variant) {
|
|
39
|
+
const option = toOptionName(selected[compiled.names[variant] ?? ""]) ?? compiled.defaultOptions[variant];
|
|
40
|
+
return option === void 0 ? 0 : compiled.indexByOption[variant]?.get(option);
|
|
41
|
+
}
|
|
42
|
+
function valuesByIndexOf(optionValues, noValue) {
|
|
43
|
+
const valuesByIndex = [];
|
|
44
|
+
for (const valuesByOption of optionValues) valuesByIndex.push([noValue, ...Object.values(valuesByOption)]);
|
|
45
|
+
return valuesByIndex;
|
|
46
|
+
}
|
|
47
|
+
function product(numbers) {
|
|
48
|
+
return numbers.reduce((result, number) => result * number, 1);
|
|
49
|
+
}
|
|
50
|
+
function withBooleanOptions(valuesByOption, noValue) {
|
|
51
|
+
if (!Object.keys(valuesByOption).some((option) => isBooleanName(option))) return valuesByOption;
|
|
52
|
+
return {
|
|
53
|
+
false: noValue,
|
|
54
|
+
true: noValue,
|
|
55
|
+
...valuesByOption
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function compileCompounds(compoundVariants, names, indexByOption) {
|
|
59
|
+
return compoundVariants.flatMap(({ variants, value }) => {
|
|
60
|
+
const conditions = Object.keys(variants).filter((name) => variants[name] !== void 0).map((name) => compileCondition(indexByOption, names.indexOf(name), variants[name]));
|
|
61
|
+
return conditions.every(([, indexes]) => indexes.length > 0) ? [{
|
|
62
|
+
conditions,
|
|
63
|
+
value
|
|
64
|
+
}] : [];
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function compileCondition(indexByOption, variant, value) {
|
|
68
|
+
const indexes = indexByOption[variant];
|
|
69
|
+
return [variant, toOptionNames(value).map((option) => indexes?.get(option)).filter((index) => index !== void 0)];
|
|
70
|
+
}
|
|
71
|
+
function isBooleanVariant(indexByOption) {
|
|
72
|
+
return indexByOption !== void 0 && indexByOption.size > 0 && [...indexByOption.keys()].every((option) => isBooleanName(option));
|
|
73
|
+
}
|
|
74
|
+
function toOptionName(value) {
|
|
75
|
+
if (typeof value === "string") return value;
|
|
76
|
+
return typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
|
|
77
|
+
}
|
|
78
|
+
function toOptionNames(value) {
|
|
79
|
+
return (Array.isArray(value) ? value : [value]).map((option) => toOptionName(option)).filter((option) => option !== void 0);
|
|
80
|
+
}
|
|
81
|
+
/** Adds the names of the compiled variants to `recipe` as `variantKeys`. */
|
|
82
|
+
function withVariantKeys(recipe, compiled) {
|
|
83
|
+
return Object.assign(recipe, { variantKeys: Object.freeze([...compiled.names]) });
|
|
84
|
+
}
|
|
85
|
+
function isBooleanName(option) {
|
|
86
|
+
return option === "true" || option === "false";
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region src/selector.ts
|
|
90
|
+
/**
|
|
91
|
+
* Returns a function that builds the result of a selection from the option
|
|
92
|
+
* index of each variant, and treats a missing selection as an empty one.
|
|
93
|
+
* With `options.cache`, it builds the result of each declared selection
|
|
94
|
+
* once and caches it by the selection's key.
|
|
95
|
+
*/
|
|
96
|
+
function createSelector(compiled, build, options) {
|
|
97
|
+
const indexes = new Int32Array(compiled.names.length);
|
|
98
|
+
const results = options.cache && compiled.isCacheable ? /* @__PURE__ */ new Map() : void 0;
|
|
99
|
+
return (selected) => {
|
|
100
|
+
const key = select(compiled, selected ?? noProps, indexes);
|
|
101
|
+
const cachedResult = key === -1 ? void 0 : results?.get(key);
|
|
102
|
+
if (cachedResult !== void 0) return cachedResult;
|
|
103
|
+
const result = build(indexes);
|
|
104
|
+
if (key !== -1) results?.set(key, result);
|
|
105
|
+
return result;
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/reduce-values.ts
|
|
110
|
+
/** Whether every condition of `compound` matches the selected indexes. */
|
|
111
|
+
function matches(compound, indexes) {
|
|
112
|
+
for (const [variant, matchingIndexes] of compound.conditions) if (!matchingIndexes.includes(indexes[variant] ?? 0)) return false;
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Reduces the values that apply to a selection, in order of precedence: the
|
|
117
|
+
* value of each variant's option, then the value of each matching compound
|
|
118
|
+
* variant. A value that is undefined adds nothing.
|
|
119
|
+
*/
|
|
120
|
+
function reduceValues(compiled, indexes, reducer) {
|
|
121
|
+
const { reduce } = reducer;
|
|
122
|
+
let accumulator = reducer.initial();
|
|
123
|
+
for (let variant = 0; variant < compiled.valuesByIndex.length; variant += 1) {
|
|
124
|
+
const value = compiled.valuesByIndex[variant]?.[indexes[variant] ?? 0];
|
|
125
|
+
if (value !== void 0) accumulator = reduce(accumulator, value);
|
|
126
|
+
}
|
|
127
|
+
for (const compound of compiled.compounds) if (compound.value !== void 0 && matches(compound, indexes)) accumulator = reduce(accumulator, compound.value);
|
|
128
|
+
return accumulator;
|
|
129
|
+
}
|
|
130
|
+
//#endregion
|
|
131
|
+
//#region src/recipe-kind.ts
|
|
132
|
+
function createRecipeKind(kind) {
|
|
133
|
+
const { initial, reduce, finish } = kind;
|
|
134
|
+
const options = { cache: kind.cache ?? true };
|
|
135
|
+
return (config) => {
|
|
136
|
+
const { base } = config;
|
|
137
|
+
const compiled = compileVariants({
|
|
138
|
+
compoundVariants: config.compoundVariants ?? [],
|
|
139
|
+
defaultVariants: config.defaultVariants ?? {},
|
|
140
|
+
noValue: void 0,
|
|
141
|
+
variants: config.variants
|
|
142
|
+
});
|
|
143
|
+
const reducer = {
|
|
144
|
+
initial: () => initial(base),
|
|
145
|
+
reduce
|
|
146
|
+
};
|
|
147
|
+
return withVariantKeys(createSelector(compiled, finish === void 0 ? (indexes) => reduceValues(compiled, indexes, reducer) : (indexes) => finish(reduceValues(compiled, indexes, reducer)), options), compiled);
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
export { createRecipeKind };
|
|
152
|
+
|
|
153
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/variants.ts","../src/selector.ts","../src/reduce-values.ts","../src/recipe-kind.ts"],"sourcesContent":["/**\n * Variant definitions in the loose shape the runtime works with: for each\n * variant name, the value of each of its options.\n */\ntype LooseVariants<Value> = Readonly<\n Record<string, Readonly<Record<string, Value>>>\n>;\n\n/** A selection in the loose shape the runtime works with. */\ntype SelectedVariants = Readonly<Record<string, unknown>>;\n\n/** A compound variant in the loose shape the runtime works with. */\ninterface LooseCompoundVariant<Value> {\n readonly variants: SelectedVariants;\n readonly value: Value;\n}\n\n/** The variant's index and the option indexes that a condition matches. */\ntype CompoundCondition = readonly [number, readonly number[]];\n\n/** A compound variant prepared for matching. */\ninterface Compound<Value> {\n readonly conditions: readonly CompoundCondition[];\n readonly value: Value;\n}\n\n/** What {@link compileVariants} prepares. */\ninterface VariantsConfig<Value> {\n readonly variants: LooseVariants<Value>;\n readonly defaultVariants: SelectedVariants;\n readonly compoundVariants: readonly LooseCompoundVariant<Value>[];\n /**\n * The value of a variant without a selected option, and of a boolean\n * option that the variant does not declare.\n */\n readonly noValue: Value;\n}\n\n/**\n * Variants prepared for selecting values. Each variant numbers its options\n * from 1, and 0 stands for no option, so a selection is a list of option\n * indexes. Read together as the digits of a mixed-radix number, they form\n * the selection's key.\n */\ninterface CompiledVariants<Value> {\n readonly names: readonly string[];\n readonly defaultOptions: readonly (string | undefined)[];\n readonly indexByOption: readonly ReadonlyMap<string, number>[];\n /** The value of each variant's options, by option index. */\n readonly valuesByIndex: readonly (readonly Value[])[];\n readonly strides: readonly number[];\n readonly compounds: readonly Compound<Value>[];\n /** Whether every selection's key is a safe integer. */\n readonly isCacheable: boolean;\n}\n\n/** The option index of a variant without a selected option. */\nconst noOption = 0;\n\n/** The key of a selection with an option that a variant does not declare. */\nconst undeclared = -1;\n\nconst noProps: SelectedVariants = Object.freeze({});\n\n/**\n * Prepares variants for selecting values. A variant that declares an option\n * named `\"true\"` or `\"false\"` also declares the other one, with\n * `config.noValue`, and a variant whose only options are those defaults to\n * `\"false\"`. A compound variant that names an undeclared variant or option,\n * or lists no option for a variant, never matches and is left out.\n */\nfunction compileVariants<Value>(\n config: VariantsConfig<Value>,\n): CompiledVariants<Value> {\n const names = Object.keys(config.variants);\n const optionValues = names.map((name) =>\n withBooleanOptions(config.variants[name] ?? {}, config.noValue),\n );\n const indexByOption: readonly ReadonlyMap<string, number>[] =\n optionValues.map(\n (valuesByOption) =>\n new Map(\n Object.keys(valuesByOption).map((option, index) => [\n option,\n index + 1,\n ]),\n ),\n );\n const radixes = indexByOption.map((indexes) => indexes.size + 1);\n\n return {\n compounds: compileCompounds(config.compoundVariants, names, indexByOption),\n defaultOptions: names.map(\n (name, index) =>\n toOptionName(config.defaultVariants[name]) ??\n (isBooleanVariant(indexByOption[index]) ? \"false\" : undefined),\n ),\n indexByOption,\n isCacheable: product(radixes) <= Number.MAX_SAFE_INTEGER,\n names,\n strides: radixes.map((_radix, index) => product(radixes.slice(0, index))),\n valuesByIndex: valuesByIndexOf(optionValues, config.noValue),\n };\n}\n\n/**\n * Writes the option index of each variant for `selected` into `indexes`\n * and returns the selection's key, or {@link undeclared} when an option is\n * not declared.\n */\nfunction select(\n compiled: CompiledVariants<unknown>,\n selected: SelectedVariants,\n indexes: Int32Array,\n): number {\n let key = 0;\n for (let variant = 0; variant < compiled.names.length; variant += 1) {\n const index = selectIndex(compiled, selected, variant);\n indexes[variant] = index ?? noOption;\n key =\n index === undefined || key === undeclared\n ? undeclared\n : key + index * (compiled.strides[variant] ?? 0);\n }\n return key;\n}\n\nfunction selectIndex(\n compiled: CompiledVariants<unknown>,\n selected: SelectedVariants,\n variant: number,\n): number | undefined {\n const option =\n toOptionName(selected[compiled.names[variant] ?? \"\"]) ??\n compiled.defaultOptions[variant];\n return option === undefined\n ? noOption\n : compiled.indexByOption[variant]?.get(option);\n}\n\nfunction valuesByIndexOf<Value>(\n optionValues: readonly Readonly<Record<string, Value>>[],\n noValue: Value,\n): Value[][] {\n const valuesByIndex: Value[][] = [];\n for (const valuesByOption of optionValues) {\n valuesByIndex.push([noValue, ...Object.values(valuesByOption)]);\n }\n return valuesByIndex;\n}\n\nfunction product(numbers: readonly number[]): number {\n return numbers.reduce((result, number) => result * number, 1);\n}\n\nfunction withBooleanOptions<Value>(\n valuesByOption: Readonly<Record<string, Value>>,\n noValue: Value,\n): Readonly<Record<string, Value>> {\n const optionNames = Object.keys(valuesByOption);\n if (!optionNames.some((option) => isBooleanName(option))) {\n return valuesByOption;\n }\n return { false: noValue, true: noValue, ...valuesByOption };\n}\n\nfunction compileCompounds<Value>(\n compoundVariants: readonly LooseCompoundVariant<Value>[],\n names: readonly string[],\n indexByOption: readonly ReadonlyMap<string, number>[],\n): Compound<Value>[] {\n return compoundVariants.flatMap(({ variants, value }) => {\n const conditions = Object.keys(variants)\n .filter((name) => variants[name] !== undefined)\n .map((name) =>\n compileCondition(indexByOption, names.indexOf(name), variants[name]),\n );\n return conditions.every(([, indexes]) => indexes.length > 0)\n ? [{ conditions, value }]\n : [];\n });\n}\n\nfunction compileCondition(\n indexByOption: readonly ReadonlyMap<string, number>[],\n variant: number,\n value: unknown,\n): CompoundCondition {\n const indexes = indexByOption[variant];\n return [\n variant,\n toOptionNames(value)\n .map((option) => indexes?.get(option))\n .filter((index) => index !== undefined),\n ];\n}\n\nfunction isBooleanVariant(\n indexByOption: ReadonlyMap<string, number> | undefined,\n): boolean {\n return (\n indexByOption !== undefined &&\n indexByOption.size > 0 &&\n [...indexByOption.keys()].every((option) => isBooleanName(option))\n );\n}\n\nfunction toOptionName(value: unknown): string | undefined {\n if (typeof value === \"string\") {\n return value;\n }\n return typeof value === \"number\" || typeof value === \"boolean\"\n ? String(value)\n : undefined;\n}\n\nfunction toOptionNames(value: unknown): readonly string[] {\n const values: readonly unknown[] = Array.isArray(value) ? value : [value];\n return values\n .map((option) => toOptionName(option))\n .filter((option) => option !== undefined);\n}\n\n/** A recipe function with the names of its variants. */\ntype WithVariantKeys<Recipe> = Recipe & {\n readonly variantKeys: readonly string[];\n};\n\n/** Adds the names of the compiled variants to `recipe` as `variantKeys`. */\nfunction withVariantKeys<Recipe extends object>(\n recipe: Recipe,\n compiled: CompiledVariants<unknown>,\n): WithVariantKeys<Recipe> {\n return Object.assign(recipe, {\n variantKeys: Object.freeze([...compiled.names]),\n });\n}\n\nfunction isBooleanName(option: string): boolean {\n return option === \"true\" || option === \"false\";\n}\n\nexport {\n compileVariants,\n noOption,\n noProps,\n select,\n undeclared,\n withVariantKeys,\n};\nexport type {\n CompiledVariants,\n Compound,\n LooseCompoundVariant,\n LooseVariants,\n SelectedVariants,\n WithVariantKeys,\n};\n","import type { CompiledVariants, SelectedVariants } from \"./variants.js\";\nimport { noProps, select, undeclared } from \"./variants.js\";\n\n/** How a selector computes its results. */\ninterface SelectorOptions {\n /** Whether to cache the result of each declared selection. */\n readonly cache: boolean;\n}\n\n/**\n * Returns a function that builds the result of a selection from the option\n * index of each variant, and treats a missing selection as an empty one.\n * With `options.cache`, it builds the result of each declared selection\n * once and caches it by the selection's key.\n */\nfunction createSelector<Result>(\n compiled: CompiledVariants<unknown>,\n build: (indexes: Int32Array) => Result,\n options: SelectorOptions,\n): (selected?: SelectedVariants | null) => Result {\n const indexes = new Int32Array(compiled.names.length);\n const results =\n options.cache && compiled.isCacheable\n ? new Map<number, Result>()\n : undefined;\n\n return (selected) => {\n const key = select(compiled, selected ?? noProps, indexes);\n const cachedResult = key === undeclared ? undefined : results?.get(key);\n if (cachedResult !== undefined) {\n return cachedResult;\n }\n const result = build(indexes);\n if (key !== undeclared) {\n results?.set(key, result);\n }\n return result;\n };\n}\n\nexport { createSelector };\nexport type { SelectorOptions };\n","import type { CompiledVariants, Compound } from \"./variants.js\";\nimport { noOption } from \"./variants.js\";\n\n/** Whether every condition of `compound` matches the selected indexes. */\nfunction matches(compound: Compound<unknown>, indexes: Int32Array): boolean {\n for (const [variant, matchingIndexes] of compound.conditions) {\n if (!matchingIndexes.includes(indexes[variant] ?? noOption)) {\n return false;\n }\n }\n return true;\n}\n\n/** Reduces the values of a selection to an accumulator. */\ninterface Reducer<Value, Accumulator> {\n /** Returns the accumulator to start from. */\n readonly initial: () => Accumulator;\n /** Adds a value to the accumulator and returns the accumulator. */\n readonly reduce: (accumulator: Accumulator, value: Value) => Accumulator;\n}\n\n/**\n * Reduces the values that apply to a selection, in order of precedence: the\n * value of each variant's option, then the value of each matching compound\n * variant. A value that is undefined adds nothing.\n */\nfunction reduceValues<Value, Accumulator>(\n compiled: CompiledVariants<Value | undefined>,\n indexes: Int32Array,\n reducer: Reducer<Value, Accumulator>,\n): Accumulator {\n const { reduce } = reducer;\n let accumulator = reducer.initial();\n for (let variant = 0; variant < compiled.valuesByIndex.length; variant += 1) {\n const value =\n compiled.valuesByIndex[variant]?.[indexes[variant] ?? noOption];\n if (value !== undefined) {\n accumulator = reduce(accumulator, value);\n }\n }\n for (const compound of compiled.compounds) {\n if (compound.value !== undefined && matches(compound, indexes)) {\n accumulator = reduce(accumulator, compound.value);\n }\n }\n return accumulator;\n}\n\nexport { reduceValues };\nexport type { Reducer };\n","import type {\n CompoundCondition,\n DefaultVariants,\n RecipeFunction,\n VariantKey,\n VariantSelection,\n} from \"./types.js\";\nimport type {\n LooseVariants,\n SelectedVariants,\n WithVariantKeys,\n} from \"./variants.js\";\nimport { compileVariants, withVariantKeys } from \"./variants.js\";\nimport { createSelector } from \"./selector.js\";\nimport { reduceValues } from \"./reduce-values.js\";\n\n/**\n * How a kind of recipe turns the values of a selection into its result,\n * such as by joining class names or merging style objects.\n *\n * @typeParam Value - The value of an option.\n * @typeParam Accumulator - What the values of a selection are reduced to.\n * @typeParam Result - What a recipe of this kind returns.\n */\ninterface RecipeKind<Value, Accumulator, Result> {\n /**\n * Returns the accumulator that the values of a selection are reduced\n * into, starting from the recipe's `base`, which is `undefined` when the\n * recipe has none. It is called for each result a recipe builds, so it\n * can return a new object each time.\n */\n readonly initial: (base: Value | undefined) => Accumulator;\n /**\n * Adds a value to the accumulator and returns the accumulator. It is\n * called with the values that apply to a selection, in order of\n * precedence: the value of each variant's selected option, in the order\n * of `variants`, then the value of each matching compound variant, in the\n * order of `compoundVariants`. An option or compound variant whose value\n * is `undefined` adds nothing.\n */\n readonly reduce: (accumulator: Accumulator, value: Value) => Accumulator;\n /**\n * Turns the accumulator into the result, for example by freezing it.\n * Without it, the result is the accumulator.\n */\n readonly finish?: ((accumulator: Accumulator) => Result) | undefined;\n /**\n * Whether a recipe builds the result of each declared selection once and\n * returns it again for the same selection. Defaults to `true`.\n */\n readonly cache?: boolean | undefined;\n}\n\n/**\n * Any selection, for variants whose names are not known at compile time,\n * such as `Record<string, Record<string, string>>`.\n */\ntype AnySelection = Readonly<Record<string, unknown>>;\n\n/** The selection of a recipe, or any selection for unknown variant names. */\ntype KindSelection<\n Variants,\n DefaultedName extends keyof Variants,\n> = string extends keyof Variants\n ? AnySelection\n : VariantSelection<Variants, DefaultedName>;\n\n/** The condition of a compound variant, or any for unknown variant names. */\ntype KindCompoundCondition<Variants> = string extends keyof Variants\n ? AnySelection\n : CompoundCondition<Variants>;\n\n/** The default variants of a recipe, or any for unknown variant names. */\ntype KindDefaultVariants<\n Variants,\n DefaultedName extends keyof Variants,\n> = string extends keyof Variants\n ? AnySelection\n : DefaultVariants<Variants, DefaultedName>;\n\n/**\n * The variants of a {@link KindRecipeConfig}: for each variant name, the\n * value of each of its options.\n *\n * @typeParam Value - The value of an option.\n */\ntype KindVariants<Value> = LooseVariants<Value>;\n\n/**\n * A value added when several variants have particular options at the same\n * time.\n *\n * @typeParam Variants - The variant definitions of the recipe.\n * @typeParam Value - The value of an option.\n */\ninterface KindCompoundVariant<Variants, Value> {\n /**\n * The options that must all be selected for\n * {@link KindCompoundVariant.value} to apply.\n */\n readonly variants: KindCompoundCondition<Variants>;\n /** The value added when the condition matches. */\n readonly value: Value;\n}\n\n/**\n * The configuration of a recipe made from a {@link RecipeKind}.\n *\n * @typeParam Value - The value of an option.\n * @typeParam Variants - The variant definitions, keyed by variant name.\n * @typeParam DefaultedName - The names of the variants that have a default.\n */\ninterface KindRecipeConfig<\n Value,\n Variants extends KindVariants<Value>,\n DefaultedName extends keyof Variants,\n> {\n /** The value that the values of every selection are added to. */\n readonly base?: Value | undefined;\n /** For each variant name, the value of each of its options. */\n readonly variants: Variants;\n /**\n * Values added when several variants have particular options at the same\n * time, applied in order after the values of the variants' options.\n */\n readonly compoundVariants?:\n readonly KindCompoundVariant<NoInfer<Variants>, Value>[] | undefined;\n /** The option each variant uses when the recipe is called without it. */\n readonly defaultVariants?:\n KindDefaultVariants<Variants, DefaultedName> | undefined;\n}\n\n/**\n * A recipe made from a {@link RecipeKind}: a function that returns the\n * result of a selection of variants, with the names of those variants in\n * `variantKeys`.\n *\n * @typeParam Selection - The variants the recipe accepts.\n * @typeParam Result - What the recipe returns.\n */\ntype KindRecipe<Selection, Result> = RecipeFunction<Selection, Result> & {\n /**\n * The names of the recipe's variants, in the order of\n * `Object.keys(config.variants)`.\n */\n readonly variantKeys: readonly VariantKey<Selection>[];\n};\n\n/**\n * Creates recipes of one kind, the function that {@link createRecipeKind}\n * returns.\n *\n * @typeParam Value - The value of an option.\n * @typeParam Result - What a recipe of this kind returns.\n * @param config - The base value, variants, compound variants, and default\n * variants of the recipe.\n * @returns The recipe.\n */\ntype CreateKindRecipe<Value, Result> = <\n const Variants extends KindVariants<Value>,\n const DefaultedName extends keyof Variants = never,\n>(\n config: KindRecipeConfig<Value, Variants, DefaultedName>,\n) => KindRecipe<KindSelection<Variants, DefaultedName>, Result>;\n\ninterface LooseRecipeKind {\n readonly initial: (base: unknown) => unknown;\n readonly reduce: (accumulator: unknown, value: unknown) => unknown;\n readonly finish?: ((accumulator: unknown) => unknown) | undefined;\n readonly cache?: boolean | undefined;\n}\n\ninterface LooseKindRecipeConfig {\n readonly base?: unknown;\n readonly variants: KindVariants<unknown>;\n readonly compoundVariants?:\n | readonly {\n readonly variants: SelectedVariants;\n readonly value: unknown;\n }[]\n | undefined;\n readonly defaultVariants?: SelectedVariants | undefined;\n}\n\ntype LooseKindRecipe = WithVariantKeys<\n (selection?: SelectedVariants | null) => unknown\n>;\n\n/**\n * Creates a kind of recipe from how it turns the values of a selection into\n * its result, and returns the function that creates recipes of that kind.\n * A recipe maps a selection of variants to a result, as `cva` of\n * `@lynstack/class-recipe` does for class names, for values of any type,\n * such as style objects.\n *\n * @remarks\n * For each selection, a recipe reduces the value of each variant's selected\n * option and the value of each matching compound variant, with\n * `kind.reduce`, into the accumulator that `kind.initial` returns for the\n * recipe's base, then passes it to `kind.finish`. A variant whose only\n * options are `\"true\"` and `\"false\"` defaults to `false`, an option that the\n * config does not declare adds no value, and properties of the selection\n * that are not variants are ignored. A recipe's `variantKeys` property lists\n * the names of its variants.\n *\n * With the cache, a recipe builds the result of each declared selection\n * once, and calling it again with the same variants returns the same\n * result. Freeze an object result in `kind.finish` so that callers cannot\n * change a result that later calls share. A selection with an undeclared\n * option is built on every call.\n *\n * When the variant names are not known at compile time, as in a library\n * that passes on a config it received, a recipe accepts any selection.\n *\n * @typeParam Value - The value of an option, inferred from the `value`\n * parameter of `kind.reduce` or the `base` parameter of `kind.initial`.\n * @typeParam Accumulator - What the values are reduced to, inferred from\n * `kind.initial`.\n * @typeParam Result - What a recipe returns, inferred from `kind.finish`,\n * or the accumulator without it.\n * @param kind - How a recipe turns the values of a selection into its\n * result, and whether it caches the result.\n * @returns The function that creates recipes of this kind.\n *\n * @example\n * ```ts\n * type Style = Readonly<Record<string, string | number>>;\n *\n * const styleRecipe = createRecipeKind({\n * initial: (base?: Style): Record<string, string | number> => ({ ...base }),\n * reduce: (style, value: Style) => Object.assign(style, value),\n * finish: (style): Style => Object.freeze(style),\n * });\n *\n * const text = styleRecipe({\n * base: { color: \"black\" },\n * variants: {\n * size: { sm: { fontSize: 12 }, lg: { fontSize: 24 } },\n * muted: { true: { opacity: 0.6 } },\n * },\n * compoundVariants: [\n * { variants: { size: \"lg\", muted: true }, value: { fontWeight: 300 } },\n * ],\n * defaultVariants: { size: \"sm\" },\n * });\n *\n * text(); // => { color: \"black\", fontSize: 12 }\n *\n * text({ size: \"lg\", muted: true });\n * // => { color: \"black\", fontSize: 24, opacity: 0.6, fontWeight: 300 }\n *\n * text.variantKeys; // => [\"size\", \"muted\"]\n * ```\n */\nfunction createRecipeKind<Value, Accumulator, Result = Accumulator>(\n kind: RecipeKind<Value, Accumulator, Result>,\n): CreateKindRecipe<Value, Result>;\n\nfunction createRecipeKind(kind: LooseRecipeKind): unknown {\n const { initial, reduce, finish } = kind;\n const options = { cache: kind.cache ?? true };\n\n return (config: LooseKindRecipeConfig): LooseKindRecipe => {\n const { base } = config;\n const compiled = compileVariants<unknown>({\n compoundVariants: config.compoundVariants ?? [],\n defaultVariants: config.defaultVariants ?? {},\n noValue: undefined,\n variants: config.variants,\n });\n const reducer = { initial: (): unknown => initial(base), reduce };\n const build =\n finish === undefined\n ? (indexes: Int32Array): unknown =>\n reduceValues(compiled, indexes, reducer)\n : (indexes: Int32Array): unknown =>\n finish(reduceValues(compiled, indexes, reducer));\n return withVariantKeys(createSelector(compiled, build, options), compiled);\n };\n}\n\nexport { createRecipeKind };\nexport type {\n CreateKindRecipe,\n KindCompoundVariant,\n KindRecipe,\n KindRecipeConfig,\n KindVariants,\n RecipeKind,\n};\n"],"mappings":"AA8DA,MAAM,UAA4B,OAAO,OAAO,CAAC,CAAC;;;;;;;;AASlD,SAAS,gBACP,QACyB;CACzB,MAAM,QAAQ,OAAO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C9B,IAAI,SAAS,UAAU,KAAA,KAAa,QAAQ,UAAU,OAAO,GAC3D,cAAc,OAAO,aAAa,SAAS,KAAK;CAGpD,OAAO;AACT;;;ACoNA,SAAS,iBAAiB,MAAgC;CACxD,MAAM,EAAE,SAAS,QAAQ,WAAW;CACpC,MAAM,UAAU,EAAE,OAAO,KAAK,SAAS,KAAK;CAE5C,QAAQ,WAAmD;EACzD,MAAM,EAAE,SAAS;EACjB,MAAM,WAAW,gBAAyB;GACxC,kBAAkB,OAAO,oBAAoB,CAAC;GAC9C,iBAAiB,OAAO,mBAAmB,CAAC;GAC5C,SAAS,KAAA;GACT,UAAU,OAAO;EACnB,CAAC;EACD,MAAM,UAAU;GAAE,eAAwB,QAAQ,IAAI;GAAG;EAAO;EAOhE,OAAO,gBAAgB,eAAe,UALpC,WAAW,KAAA,KACN,YACC,aAAa,UAAU,SAAS,OAAO,KACxC,YACC,OAAO,aAAa,UAAU,SAAS,OAAO,CAAC,GACA,OAAO,GAAG,QAAQ;CAC3E;AACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@lynstack/recipe",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Fast, type-safe recipes for values of any type: define how a kind of recipe combines values, such as class names or styles, then create recipes of that kind.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"recipe",
|
|
7
|
+
"styles",
|
|
8
|
+
"variants"
|
|
9
|
+
],
|
|
10
|
+
"homepage": "https://lynstack.github.io/recipe/recipe/",
|
|
11
|
+
"bugs": "https://github.com/lynstack/recipe/issues",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/lynstack/recipe.git",
|
|
15
|
+
"directory": "packages/recipe"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"author": "Tim Phan",
|
|
19
|
+
"type": "module",
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./package.json": "./package.json"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsdown",
|
|
33
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.build.json --noEmit",
|
|
34
|
+
"lint": "oxlint",
|
|
35
|
+
"format:check": "prettier --check . --ignore-path ../../.gitignore --ignore-path ../../.prettierignore",
|
|
36
|
+
"test": "vitest run",
|
|
37
|
+
"test:watch": "vitest",
|
|
38
|
+
"test:coverage": "vitest run --coverage",
|
|
39
|
+
"test:consumer": "tsc -p fixtures/consumer/tsconfig.json",
|
|
40
|
+
"bench": "pnpm build && vitest bench --run",
|
|
41
|
+
"check": "pnpm build && pnpm typecheck && pnpm test:consumer && pnpm lint && pnpm format:check && pnpm test",
|
|
42
|
+
"prepack": "pnpm build"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
}
|
|
47
|
+
}
|