-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
203 lines (176 loc) · 5.4 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import { Context, Controller } from "@hotwired/stimulus";
class Wrapped<T extends object> {
// @ts-ignore
private _ = undefined;
}
/**
* Strongly type Object values
* ```ts
* const values = {
* address: Object_<{ street: string }>
* }
* ```
*/
export const Object_ = Wrapped;
export const ObjectAs = Object_;
/**
* Strongly type custom targets
* ```ts
* const targets = {
* select: Target<CustomSelect>
* }
* ```
*/
export const Target = Wrapped;
/**
* Identifier to camel case (admin--user-status to adminUserStatus)
*/
type CamelCase<K extends string> = K extends `${infer Head}-${infer Tail}`
? `${Head}${Capitalize<CamelCase<Tail>>}`
: K;
type ElementType<C> = C extends Controller<infer E> ? E : never;
type Singular<T, Suffix extends string> = {
[K in keyof T as `${CamelCase<K & string>}${Suffix}`]: T[K];
};
type Existential<T, Suffix extends string> = {
[K in keyof T as `has${Capitalize<CamelCase<K & string>>}${Suffix}`]: boolean;
};
type Plural<T, Suffix extends string> = {
[K in keyof T as `${CamelCase<K & string>}${Suffix}s`]: T[K][];
};
type Elemental<T, Suffix extends string> = {
[K in keyof T as `${CamelCase<K & string>}${Suffix}Element`]: ElementType<T[K]>;
} & {
[K in keyof T as `${CamelCase<K & string>}${Suffix}Elements`]: ElementType<T[K]>[];
};
type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};
type MagicProperties<T, Kind extends string> = (Kind extends "Value"
? Singular<T, Kind>
: Readonly<Singular<T, Kind>>) &
Readonly<Existential<T, Kind>> &
Readonly<Kind extends "Target" | "Outlet" ? Plural<T, Kind> : unknown> &
Readonly<Kind extends "Outlet" ? Elemental<T, Kind> : unknown>;
type Constructor<T = {}> = new (...args: any[]) => T;
type TypeFromConstructor<C> = C extends StringConstructor
? string
: C extends NumberConstructor
? number
: C extends BooleanConstructor
? boolean
: C extends Constructor<infer T>
? T extends Wrapped<infer O>
? O
: Object extends T
? unknown
: T
: never;
/**
* Map `{ [key:string]: Constructor<T> } to { [key:string]: T }`
*/
type TransformType<T extends {}> = {
[K in keyof T]: TypeFromConstructor<T[K]>;
};
/**
* Transform `{ [key:string]: ValueTypeConstant | ValueTypeObject }`
*/
type TransformValueDefinition<T extends {}> = TransformType<{
[K in keyof T]: T[K] extends { type: infer U } ? U : T[K];
}>;
// tweak stimulus value definition map to support typed array and object
type ValueDefinitionMap = {
[token: string]: ValueTypeDefinition;
};
type ValueTypeConstant =
| typeof Array<any>
| typeof Boolean
| typeof Number
| typeof Object
| typeof String
| typeof Object_;
type ValueTypeDefault = Array<any> | boolean | number | Object | typeof Object_ | string;
type ValueTypeObject = Partial<{
type: ValueTypeConstant;
default: ValueTypeDefault;
}>;
type ValueTypeDefinition = ValueTypeConstant | ValueTypeObject;
type TargetDefinitionMap = {
[token: string]: typeof Element | typeof Target;
};
type OutletDefinitionMap = {
[token: string]: Constructor<Controller>;
};
type Statics<
Values extends ValueDefinitionMap,
Targets extends TargetDefinitionMap,
Outlets extends OutletDefinitionMap,
> = {
values?: Values;
targets?: Targets;
outlets?: Outlets;
};
type StimulusProperties<
Values extends ValueDefinitionMap,
Targets extends TargetDefinitionMap,
Outlets extends OutletDefinitionMap,
> = Simplify<
MagicProperties<TransformValueDefinition<Values>, "Value"> &
MagicProperties<TransformType<Targets>, "Target"> &
MagicProperties<TransformType<Outlets>, "Outlet">
>;
/**
* Convert typed Object_ to ObjectConstructor before passing values to Stimulus
*/
function patchValueTypeDefinitionMap(values: ValueDefinitionMap) {
const patchObject = (def: ValueTypeDefinition) => {
if ("type" in def) {
return {
type: def.type === Object_ ? Object : def.type,
default: def.default,
};
} else {
return def === Object_ ? Object : def;
}
};
return Object.entries(values).reduce((result, [key, def]) => {
result[key] = patchObject(def);
return result;
}, {} as ValueDefinitionMap);
}
/**
* Strongly typed Controller!
* ```ts
* const values = {
* name: String,
* alias: Array<string>,
* address: Object_<{ street: string }>
* }
* const targets = { form: HTMLFormElement, "select": Target<CustomSelect> }
* const outlets = { "user-status": UserStatusController }
*
* class MyController extends Typed(Controller, { values, targets, outlets }) {
* // Look Ma, no "declare ..."
* this.nameValue.split(' ')
* this.aliasValue.map(alias => alias.toUpperCase())
* this.addressValue.street
* this.formTarget.submit()
* this.selectTarget.search = "stimulus";
* this.userStatusOutlets.forEach(status => status.markAsSelected(event))
* }
* ```
*/
export function Typed<
Values extends ValueDefinitionMap,
Targets extends TargetDefinitionMap,
Outlets extends OutletDefinitionMap,
Base extends Constructor<Controller>,
>(Base: Base, statics: Statics<Values, Targets, Outlets>) {
const { values, targets, outlets } = statics;
const derived = class extends Base {
static values = patchValueTypeDefinitionMap(values ?? {});
static targets = Object.getOwnPropertyNames(targets ?? {});
static outlets = Object.getOwnPropertyNames(outlets ?? {});
};
return derived as unknown as {
new (context: Context): InstanceType<Base> & StimulusProperties<Values, Targets, Outlets>;
};
}