-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrules.tsx
More file actions
206 lines (193 loc) · 5.87 KB
/
Copy pathrules.tsx
File metadata and controls
206 lines (193 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { UserInputEventType } from '@metamask/snaps-sdk';
import type { GenericSnapElement } from '@metamask/snaps-sdk/jsx';
import { DropdownField } from '../ui/components/DropdownField';
import { InputField } from '../ui/components/InputField';
import type {
UserEventDispatcher,
UserEventHandler,
} from '../userEventDispatcher';
import type { BaseContext, RuleDefinition } from './types';
/**
* Renders a single rule with the provided configuration, context and metadata.
* @param options0 - The options object.
* @param options0.rule - The rule definition to render.
* @param options0.context - The current context state.
* @param options0.metadata - Additional metadata for error validation.
* @returns The rendered rule element or null if the rule value is undefined.
*/
export function renderRule<
TContext extends BaseContext,
TMetadata extends object,
>({
rule,
context,
metadata,
}: {
rule: RuleDefinition<TContext, TMetadata>;
context: TContext;
metadata: TMetadata;
}): GenericSnapElement | null {
const { label, type, name, isOptional } = rule;
const {
value,
error,
tooltip,
iconData,
isVisible,
options,
isAdjustmentAllowed,
} = rule.getRuleData({ context, metadata });
if (value === null || value === undefined || !isVisible) {
// If the value is not set, don't render the rule
return null;
}
const isDisabled = !isAdjustmentAllowed;
const removeButtonName = isOptional ? `${name}_removeButton` : undefined;
switch (type) {
case 'number':
case 'text': {
return (
<InputField
label={label}
name={name}
value={value ?? ''}
errorMessage={error}
disabled={isDisabled}
tooltip={tooltip}
type={type}
removeButtonName={removeButtonName}
iconData={iconData}
/>
);
}
case 'dropdown': {
if (!options) {
// todo: type constraint on this would be nice
throw new Error('Dropdown rule must have options');
}
return (
<DropdownField
label={label}
name={name}
options={options}
value={value ?? ''}
errorMessage={error}
disabled={isDisabled}
tooltip={tooltip}
/>
);
}
default: {
throw new Error(`Unknown rule type: ${type as string}`);
}
}
}
/**
* Renders a list of rules the the provided configuration, context and metadata.
* @param options0 - The options object.
* @param options0.rules - The array of rule definitions to render.
* @param options0.context - The current context state.
* @param options0.metadata - Additional metadata for error validation.
* @returns An array of rendered rule elements (or null for undefined rule values).
*/
export function renderRules<
TContext extends BaseContext,
TMetadata extends object,
>({
rules,
context,
metadata,
}: {
rules: RuleDefinition<TContext, TMetadata>[];
context: TContext;
metadata: TMetadata;
}): (GenericSnapElement | null)[] {
return rules.map((rule) => renderRule({ rule, context, metadata }));
}
/**
* Binds the handlers for the provided rules to the user event dispatcher.
* @param options0 - The options object.
* @param options0.rules - The array of rule definitions to bind handlers for.
* @param options0.userEventDispatcher - The user event dispatcher to bind handlers to.
* @param options0.interfaceId - The interface ID for the event handlers.
* @param options0.getContext - Function to get the current context state.
* @param options0.onContextChanged - Function called when context changes.
* @returns A function that unbinds the handlers when called.
*/
export function bindRuleHandlers<
TContext extends BaseContext,
TMetadata extends object,
>({
rules,
userEventDispatcher,
interfaceId,
getContext,
onContextChanged,
}: {
rules: RuleDefinition<TContext, TMetadata>[];
userEventDispatcher: UserEventDispatcher;
interfaceId: string;
getContext: () => TContext;
onContextChanged: (args: { context: TContext }) => Promise<void>;
}): () => void {
const handlers = rules.reduce<
{
elementName: string;
eventType: UserInputEventType;
handler: UserEventHandler<UserInputEventType>;
}[]
>((acc, rule) => {
const { name, isOptional } = rule;
const handleInputChange: UserEventHandler<
UserInputEventType.InputChangeEvent
> = async ({ event }) => {
const updatedContext = rule.updateContext(
getContext(),
event.value as string,
);
await onContextChanged({ context: updatedContext });
};
userEventDispatcher.on({
elementName: name,
eventType: UserInputEventType.InputChangeEvent,
interfaceId,
handler: handleInputChange,
});
acc.push({
elementName: name,
eventType: UserInputEventType.InputChangeEvent,
handler: handleInputChange as UserEventHandler<UserInputEventType>,
});
if (isOptional) {
const handleRemoveButtonClick: UserEventHandler<
UserInputEventType.ButtonClickEvent
> = async (_) => {
const updatedContext = rule.updateContext(getContext(), undefined);
await onContextChanged({ context: updatedContext });
};
userEventDispatcher.on({
elementName: `${rule.name}_removeButton`,
eventType: UserInputEventType.ButtonClickEvent,
interfaceId,
handler: handleRemoveButtonClick,
});
acc.push({
elementName: `${rule.name}_removeButton`,
eventType: UserInputEventType.ButtonClickEvent,
handler:
handleRemoveButtonClick as UserEventHandler<UserInputEventType>,
});
}
return acc;
}, []);
return () => {
handlers.forEach((handler) =>
userEventDispatcher.off({
elementName: handler.elementName,
eventType: handler.eventType,
interfaceId,
handler: handler.handler,
}),
);
};
}