-
Notifications
You must be signed in to change notification settings - Fork 415
Expand file tree
/
Copy pathapi-connect-wizard.tsx
More file actions
287 lines (264 loc) · 11 KB
/
api-connect-wizard.tsx
File metadata and controls
287 lines (264 loc) · 11 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import { TransportProvider } from '@connectrpc/connect-query';
import { Markdown } from '@redpanda-data/ui';
import { useNavigate, useRouter } from '@tanstack/react-router';
import PageContent from 'components/misc/page-content';
import { Button } from 'components/redpanda-ui/components/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from 'components/redpanda-ui/components/card';
import { Spinner } from 'components/redpanda-ui/components/spinner';
import { defineStepper } from 'components/redpanda-ui/components/stepper';
import { Heading } from 'components/redpanda-ui/components/typography';
import { config } from 'config';
import { useControlplaneTransport } from 'hooks/use-controlplane-transport';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useGetOnboardingCodeSnippetQuery } from 'react-query/api/onboarding';
import { useGetServerlessClusterQuery } from 'react-query/api/serverless';
import { useAPIWizardStore } from 'state/api-wizard-store';
import { uiState } from 'state/ui-state';
import { capitalizeFirst } from 'utils/utils';
import { useShallow } from 'zustand/react/shallow';
import { AddTopicStep } from '../rp-connect/onboarding/add-topic-step';
import { AddUserStep } from '../rp-connect/onboarding/add-user-step';
import type { AddTopicFormData, BaseStepRef, UserStepRef } from '../rp-connect/types/wizard';
import { handleStepResult } from '../rp-connect/utils/wizard';
const APIWizardStep = {
ADD_DATA: 'add-data-step',
ADD_TOPIC: 'add-topic-step',
ADD_USER: 'add-user-step',
CONNECT_CLUSTER: 'connect-cluster-step',
};
const apiWizardStepDefinitions = [
{ id: APIWizardStep.ADD_DATA, title: 'Add data' },
{ id: APIWizardStep.ADD_TOPIC, title: 'Add a topic' },
{ id: APIWizardStep.ADD_USER, title: 'Add a user' },
{ id: APIWizardStep.CONNECT_CLUSTER, title: 'Connect cluster' },
];
const APIStepper = defineStepper(...apiWizardStepDefinitions);
const APIWizardStepper = APIStepper.Stepper;
type APIWizardStepperSteps = typeof APIStepper.Steps;
type HowToConnectProps = {
topicName?: string;
username?: string;
saslMechanism?: string;
};
const HowToConnectComponent = ({ topicName, username, saslMechanism }: HowToConnectProps) => {
const connectionName = useAPIWizardStore(useShallow((state) => state.connectionName));
const { data: codeSnippet, isLoading: isLoadingCodeSnippet } = useGetOnboardingCodeSnippetQuery({
language: connectionName,
});
const { data: cluster } = useGetServerlessClusterQuery({
id: config.clusterId,
});
const bootstrapServerUrl = cluster?.serverlessCluster?.kafkaApi?.seedBrokers.join(',') as string;
const formattedCodeSnippet = useMemo(() => {
let codeSnippetWithVariables = codeSnippet;
if (bootstrapServerUrl) {
codeSnippetWithVariables = codeSnippetWithVariables?.replaceAll('<bootstrap-server-address>', bootstrapServerUrl);
}
if (topicName) {
codeSnippetWithVariables = codeSnippetWithVariables?.replaceAll('demo-topic', topicName);
}
if (username) {
codeSnippetWithVariables = codeSnippetWithVariables?.replaceAll('<username>', username);
}
if (saslMechanism) {
codeSnippetWithVariables = codeSnippetWithVariables
?.replaceAll('<scram-sha-256 or scram-sha-512>', saslMechanism)
?.replaceAll('<SCRAM-SHA-256 or SCRAM-SHA-512>', saslMechanism);
}
return codeSnippetWithVariables;
}, [codeSnippet, bootstrapServerUrl, topicName, username, saslMechanism]);
const content = useMemo(() => {
if (isLoadingCodeSnippet) {
return (
<div className="flex items-center justify-center p-8">
<div className="text-muted-foreground">Loading code snippet...</div>
</div>
);
}
if (formattedCodeSnippet) {
return <Markdown showLineNumbers>{formattedCodeSnippet}</Markdown>;
}
return (
<div className="flex items-center justify-center p-8">
<div className="text-muted-foreground">No code snippet found</div>
</div>
);
}, [isLoadingCodeSnippet, formattedCodeSnippet]);
return (
<Card size="full">
<CardHeader className="mb-2">
<CardTitle>
<Heading level={2}>Connect to your cluster</Heading>
</CardTitle>
<CardDescription>
Follow the instructions below to connect to your cluster using the {capitalizeFirst(connectionName ?? '')}{' '}
API.
</CardDescription>
</CardHeader>
<CardContent className="relative flex max-h-[50vh] min-h-[400px] gap-8 overflow-y-auto">
<div className="max-w-4xl rounded-md border border-base-200 bg-slate-100 p-6">{content}</div>
</CardContent>
</Card>
);
};
const HowToConnectStep = ({ topicName, username, saslMechanism }: HowToConnectProps) => {
const controlplaneTransport = useControlplaneTransport();
return (
<TransportProvider transport={controlplaneTransport}>
<HowToConnectComponent saslMechanism={saslMechanism} topicName={topicName} username={username} />
</TransportProvider>
);
};
export const APIConnectWizard = () => {
const navigate = useNavigate();
const router = useRouter();
const { reset: resetApiWizardStore } = useAPIWizardStore();
const [topicName, setTopicName] = useState<string | undefined>(undefined);
const [username, setUsername] = useState<string | undefined>(undefined);
const [saslMechanism, setSaslMechanism] = useState<string | undefined>(undefined);
const addTopicStepRef = useRef<BaseStepRef<AddTopicFormData>>(null);
const addUserStepRef = useRef<UserStepRef>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const handleNext = async (methods: APIWizardStepperSteps) => {
switch (methods.current.id) {
case APIWizardStep.ADD_TOPIC: {
setIsSubmitting(true);
const topicResult = await addTopicStepRef.current?.triggerSubmit().finally(() => setIsSubmitting(false));
if (topicResult?.success) {
setTopicName(topicResult.data?.topicName);
}
handleStepResult(topicResult, methods.next);
break;
}
case APIWizardStep.ADD_USER: {
setIsSubmitting(true);
const userResult = await addUserStepRef.current?.triggerSubmit().finally(() => setIsSubmitting(false));
if (userResult?.success && userResult.data && 'username' in userResult.data) {
// SASL user data
setUsername(userResult.data.username);
setSaslMechanism(userResult.data.saslMechanism);
}
// Service account data doesn't set username/saslMechanism
handleStepResult(userResult, methods.next);
break;
}
default:
methods.next();
}
};
const handleSkip = (methods: APIWizardStepperSteps) => {
methods.next();
};
const handleCancel = useCallback(() => {
resetApiWizardStore();
router.history.back();
}, [router, resetApiWizardStore]);
useEffect(() => {
uiState.pageTitle = 'Connect to your cluster';
uiState.pageBreadcrumbs = [
{ title: 'Cluster Overview', linkTo: '/overview' },
{ title: 'Connect to your cluster', linkTo: '' },
];
}, []);
useEffect(() => {
useAPIWizardStore.persist.rehydrate();
return () => {
// Only clear if we're not on the get-started/api route (user navigated away)
const currentPath = window.location.pathname;
if (!currentPath.includes('/get-started/api')) {
resetApiWizardStore();
}
};
}, [resetApiWizardStore]);
const handleCreate = useCallback(() => {
resetApiWizardStore();
navigate({ to: '/overview' });
window.location.reload(); // Required because we want to load Cloud UI's overview, not Console UI.
}, [navigate, resetApiWizardStore]);
return (
<PageContent>
<APIWizardStepper.Provider className="space-y-2" initialStep={APIWizardStep.ADD_TOPIC}>
{({ methods }) => (
<div className="relative flex flex-col gap-6">
<div className="flex h-full flex-col gap-6 pt-4">
<div className="flex flex-col space-y-2 text-center">
<APIWizardStepper.Navigation>
{apiWizardStepDefinitions.map((step) => (
<APIWizardStepper.Step
key={step.id}
of={step.id}
onClick={() => {
if (step.id === APIWizardStep.ADD_DATA) {
router.history.back();
} else {
methods.goTo(step.id);
}
}}
>
<APIWizardStepper.Title>{step.title}</APIWizardStepper.Title>
</APIWizardStepper.Step>
))}
</APIWizardStepper.Navigation>
</div>
{methods.switch({
[APIWizardStep.ADD_TOPIC]: () => <AddTopicStep defaultTopicName={topicName} ref={addTopicStepRef} />,
[APIWizardStep.ADD_USER]: () => (
<AddUserStep defaultUsername={username} ref={addUserStepRef} topicName={topicName} />
),
[APIWizardStep.CONNECT_CLUSTER]: () => (
<HowToConnectStep saslMechanism={saslMechanism} topicName={topicName} username={username} />
),
})}
</div>
<APIWizardStepper.Controls className="justify-between">
<div className="flex gap-2">
{!(methods.isFirst || methods.isLast) && (
<Button
onClick={
methods.current.id === APIWizardStep.ADD_TOPIC
? () => {
router.history.back();
}
: methods.prev
}
type="button"
variant="secondary-outline"
>
<ChevronLeftIcon />
Previous
</Button>
)}
<Button onClick={handleCancel} type="button" variant="secondary-ghost">
Cancel
</Button>
</div>
<div className="flex gap-2">
{!methods.isLast && (
<Button onClick={() => handleSkip(methods)} type="button" variant="secondary-ghost">
Skip
</Button>
)}
{methods.isLast ? (
<Button onClick={handleCreate} type="button">
Create
</Button>
) : (
<Button className="min-w-[70px]" disabled={isSubmitting} onClick={() => handleNext(methods)}>
{isSubmitting ? (
<Spinner />
) : (
<>
Next <ChevronRightIcon />
</>
)}
</Button>
)}
</div>
</APIWizardStepper.Controls>
</div>
)}
</APIWizardStepper.Provider>
</PageContent>
);
};