-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyValueEntriesSection.tsx
More file actions
240 lines (216 loc) · 11.7 KB
/
KeyValueEntriesSection.tsx
File metadata and controls
240 lines (216 loc) · 11.7 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import { isKeySecret } from '@lib/utils';
import Label from '@shared/Label';
import StyledInput from '@shared/StyledInput';
import { KeyValueEntryWithId } from '@typedefs/deeploys';
import { useEffect, useState } from 'react';
import {
Controller,
FieldValues,
useFieldArray,
UseFieldArrayAppend,
UseFieldArrayRemove,
useFormContext,
} from 'react-hook-form';
import SecretValueToggle from './SecretValueToggle';
import VariableSectionControls from './VariableSectionControls';
import VariableSectionIndex from './VariableSectionIndex';
import VariableSectionRemove from './VariableSectionRemove';
// This component assumes it's being used in the deployment step
export default function KeyValueEntriesSection({
name,
displayLabel = 'entries',
label,
maxEntries = 50,
predefinedEntries,
disabledKeys,
placeholders = ['KEY', 'VALUE'],
enableSecretValues = false,
parentMethods,
}: {
name: string;
displayLabel?: string;
label?: string;
maxEntries?: number;
predefinedEntries?: { key: string; value: string }[];
disabledKeys?: string[];
placeholders?: [string, string];
enableSecretValues?: boolean;
parentMethods?: {
fields: Record<'id', string>[];
append: UseFieldArrayAppend<FieldValues, string>;
remove: UseFieldArrayRemove;
};
}) {
const { control, formState, trigger } = useFormContext();
const { fields, append, remove } =
parentMethods ??
useFieldArray({
control,
name,
});
// Explicitly type the fields to match the expected structure
const entries = fields as KeyValueEntryWithId[];
const [isFieldSecret, setFieldSecret] = useState<{ [id: string]: boolean }>({});
useEffect(() => {
entries.forEach((entry) => {
if (isFieldSecret[entry.id] === undefined) {
setFieldSecret((previous) => ({
...previous,
[entry.id]: isKeySecret(entry.key),
}));
}
});
}, [entries]);
// Get array-level errors
const errors = name.split('.').reduce<unknown>((acc, segment) => {
if (!acc || typeof acc !== 'object') {
return undefined;
}
return (acc as Record<string, unknown>)[segment];
}, formState.errors as unknown) as any;
return (
<div className="col gap-4">
{(entries.length > 0 || (!!predefinedEntries && predefinedEntries.length > 0)) && (
<div className="col w-full gap-2">
{!!label && (
<div className="row">
<Label value={label} />
</div>
)}
<div className="col gap-2">
{!!predefinedEntries && predefinedEntries.length > 0 && (
<>
{predefinedEntries.map((entry, index) => (
<div key={entry.key} className="flex gap-3">
<VariableSectionIndex index={index} />
{enableSecretValues && (
<SecretValueToggle isSecret={isKeySecret(entry.key)} isDisabled />
)}
<div className="flex w-full gap-2">
<StyledInput value={entry.key} isDisabled />
<StyledInput value={entry.value} isDisabled />
</div>
{/* Displayed for styling purposes */}
<div className="invisible">
<VariableSectionRemove onClick={() => {}} />
</div>
</div>
))}
</>
)}
{entries.map((entry: KeyValueEntryWithId, index) => {
// Get the error for this specific entry
const entryError = errors?.[index];
return (
<div key={entry.id} className="flex gap-3">
<VariableSectionIndex index={index + (predefinedEntries?.length ?? 0)} />
{enableSecretValues && (
<SecretValueToggle
isSecret={isFieldSecret[entry.id]}
onClick={() => {
setFieldSecret((previous) => ({
...previous,
[entry.id]: !previous[entry.id],
}));
}}
/>
)}
<div className="flex w-full gap-2">
<Controller
name={`${name}.${index}.key`}
control={control}
render={({ field, fieldState }) => {
// Check for specific error on this key input or array-level error
const specificKeyError = entryError?.key;
const hasError =
!!fieldState.error || !!specificKeyError || !!errors?.root?.message;
return (
<StyledInput
placeholder={placeholders[0]}
value={field.value ?? ''}
onChange={async (e) => {
const value = e.target.value;
field.onChange(value);
// Re-validate on change if field has error to clear it immediately
if (hasError) {
await trigger(`${name}.${index}.key`);
}
}}
onBlur={async () => {
field.onBlur();
// Trigger validation for the entire array to check for duplicate keys
if (entries.length > 1) {
await trigger(name);
}
}}
isInvalid={hasError}
errorMessage={
fieldState.error?.message ||
specificKeyError?.message ||
(errors?.root?.message && index === 0
? errors.root.message
: undefined)
}
isDisabled={disabledKeys?.includes(field.value)}
/>
);
}}
/>
<Controller
name={`${name}.${index}.value`}
control={control}
render={({ field, fieldState }) => {
// Check for specific error on this value input
const specificValueError = entryError?.value;
const hasError = !!fieldState.error || !!specificValueError;
return (
<StyledInput
placeholder={placeholders[1]}
value={field.value ?? ''}
onChange={async (e) => {
const value = e.target.value;
field.onChange(value);
// Re-validate on change if field has error to clear it immediately
if (hasError) {
await trigger(`${name}.${index}.value`);
}
}}
onBlur={async () => {
field.onBlur();
}}
isInvalid={hasError}
errorMessage={fieldState.error?.message || specificValueError?.message}
type={isFieldSecret[entry.id] ? 'password' : 'text'}
/>
);
}}
/>
</div>
<div className={disabledKeys?.includes(entry.key) ? 'invisible' : ''}>
<VariableSectionRemove
onClick={() => {
remove(index);
setFieldSecret((previous) => {
const next = { ...previous };
delete next[entry.id];
return next;
});
}}
/>
</div>
</div>
);
})}
</div>
</div>
)}
<VariableSectionControls
displayLabel={displayLabel}
onClick={() => append({ key: '', value: '' })}
fieldsLength={entries.length}
maxFields={maxEntries}
remove={remove}
/>
</div>
);
}