-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathPlayground.tsx
410 lines (384 loc) · 16.3 KB
/
Playground.tsx
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import React, {useState, useEffect, useRef} from "react"
import {Button, Tabs, message} from "antd"
import ViewNavigation from "./ViewNavigation"
import NewVariantModal from "./NewVariantModal"
import {fetchVariants, saveNewVariant} from "@/services/api"
import {fetchEnvironments} from "@/services/deployment"
import {Variant, PlaygroundTabsItem, Environment} from "@/lib/Types"
import {AppstoreOutlined, SyncOutlined} from "@ant-design/icons"
import {useRouter} from "next/router"
import {useQueryParam} from "@/hooks/useQuery"
import AlertPopup from "../AlertPopup/AlertPopup"
import useBlockNavigation from "@/hooks/useBlockNavigation"
import type {DragEndEvent} from "@dnd-kit/core"
import {DndContext, PointerSensor, useSensor} from "@dnd-kit/core"
import {arrayMove, SortableContext, horizontalListSortingStrategy} from "@dnd-kit/sortable"
import DraggableTabNode from "../DraggableTabNode/DraggableTabNode"
import {useLocalStorage} from "usehooks-ts"
import TestContextProvider from "./TestContextProvider"
import {checkIfResourceValidForDeletion} from "@/lib/helpers/evaluate"
import ResultComponent from "../ResultComponent/ResultComponent"
const Playground: React.FC = () => {
const router = useRouter()
const appId = router.query.app_id as string
const [templateVariantName, setTemplateVariantName] = useState("") // We use this to save the template variant name when the user creates a new variant
const [activeKey, setActiveKey] = useQueryParam("variant")
const [isModalOpen, setIsModalOpen] = useState(false)
const [variants, setVariants] = useState<Variant[]>([]) // These are the variants that exist in the backend
const [isLoading, setIsLoading] = useState(true)
const [isError, setIsError] = useState(false)
const [newVariantName, setNewVariantName] = useState("") // This is the name of the new variant that the user is creating
const [messageApi, contextHolder] = message.useMessage()
const [unsavedVariants, setUnsavedVariants] = useState<{[name: string]: boolean}>({})
const variantHelpers = useRef<{[name: string]: {save: Function; delete: Function}}>({})
const sensor = useSensor(PointerSensor, {activationConstraint: {distance: 50}}) // Initializes a PointerSensor with a specified activation distance.
const [compareMode, setCompareMode] = useLocalStorage("compareMode", false)
const tabID = useRef("")
const addTab = async () => {
// Find the template variant
const templateVariant = variants.find(
(variant) => variant.variantName === templateVariantName,
)
// Check if the template variant exists
if (!templateVariant) {
message.error("Template variant not found. Please choose a valid variant.")
return
}
// Get TemplateVariant and Variant Name
const newTemplateVariantName = templateVariant.templateVariantName
? templateVariant.templateVariantName
: templateVariantName
const updateNewVariantName = `${templateVariant.baseName}.${newVariantName}`
// Check if variant with the same name already exists
const existingVariant = variants.find(
(variant) => variant.variantName === updateNewVariantName,
)
// Check if the variant exists
if (existingVariant) {
message.error(
"A variant with this name already exists. Please choose a different name.",
)
return
}
const newVariant: Partial<Variant> = {
variantName: updateNewVariantName,
templateVariantName: newTemplateVariantName,
previousVariantName: templateVariant.variantName,
persistent: false,
parameters: templateVariant.parameters,
baseId: templateVariant.baseId,
baseName: templateVariant.baseName || newTemplateVariantName,
configName: newVariantName,
}
try {
await saveNewVariant(
newVariant.baseId!,
newVariant.variantName!,
newVariant.configName!,
[],
)
setVariants((prevState: any) => [...prevState, newVariant])
setActiveKey(updateNewVariantName)
setUnsavedVariants((prev) => ({...prev, [newVariant.variantName!]: false}))
} catch (error) {
message.error("Failed to add new variant. Please try again later.")
console.error("Error adding new variant:", error)
}
}
const removeTab = () => {
const toDelete = compareMode
? variants.find((item) => item.variantId === tabID.current)?.variantName || ""
: activeKey
const newVariants = variants.filter((variant) => variant.variantName !== toDelete)
if (newVariants.length < 1) {
router.push(`/apps`)
return
}
let newActiveKey = ""
if (newVariants.length > 0) {
newActiveKey = newVariants[newVariants.length - 1].variantName
}
setVariants(newVariants)
setUnsavedVariants((prev) => {
const newUnsavedVariants = {...prev}
delete newUnsavedVariants[toDelete]
return newUnsavedVariants
})
setActiveKey(newActiveKey)
}
const fetchData = async () => {
try {
const backendVariants = await fetchVariants(appId)
if (backendVariants.length > 0) {
setVariants(backendVariants)
if (!activeKey) setActiveKey(backendVariants[0].variantName)
}
setIsLoading(false)
} catch (error) {
setIsError(true)
setIsLoading(false)
}
}
useEffect(() => {
fetchData()
}, [appId, activeKey])
// Load environments
const [environments, setEnvironments] = useState<Environment[]>([])
const loadEnvironments = async () => {
const response: Environment[] = await fetchEnvironments(appId)
if (response.length === 0) return
setEnvironments(response)
}
useEffect(() => {
if (!appId) return
loadEnvironments()
}, [appId, activeKey])
useBlockNavigation(
Object.values(unsavedVariants).reduce((acc, curr) => acc || curr, false),
{
title: "Unsaved changes",
message: (
<span>
You have unsaved changes in your Variant(s). Do you want to save these changes
before leaving the page?
</span>
),
width: 500,
okText: "Save",
onOk: async () => {
const promises = Object.keys(unsavedVariants).map((name) =>
unsavedVariants[name] ? variantHelpers.current[name].save() : Promise.resolve(),
)
await Promise.all(promises)
return true
},
onCancel: async () => {
setUnsavedVariants({})
return true
},
cancelText: "Proceed without saving",
},
(newRoute) => !newRoute.includes("playground"),
)
if (isError)
return (
<ResultComponent
status="error"
title={`Failed to load variants`}
subtitle={`App ID: ${appId}`}
/>
)
if (isLoading)
return <ResultComponent status="info" title="Loading variants..." spinner={true} />
/**
* Called when the variant is saved for the first time to the backend
* after this point, the variant cannot be removed from the tab menu
* but only through the button
* @param variantName
*/
function handlePersistVariant(variantName: string) {
setVariants((prevVariants) => {
return prevVariants.map((variant) => {
if (variant.variantName === variantName) {
return {...variant, persistent: true}
}
return variant
})
})
}
const deleteVariant = (deleteAction?: Function) => {
AlertPopup({
title: "Delete Variant",
message: (
<span>
You're about to delete this variant. This action is irreversible.
<br />
Are you sure you want to proceed?
</span>
),
okButtonProps: {
type: "primary",
danger: true,
},
onOk: async () => {
try {
const variantId =
variants.find((item) => item.variantId === tabID.current)?.variantId ||
variants.find((item) => item.variantName === activeKey)?.variantId
if (
variantId &&
!(await checkIfResourceValidForDeletion({
resourceType: "variant",
resourceIds: [variantId],
}))
)
return
if (deleteAction) await deleteAction()
removeTab()
messageApi.open({
type: "success",
content: "Variant removed successfully!",
})
} catch {}
},
})
}
/**
* Handles the drag-and-drop event for tabs. It reorders the tabs in the `variants` array
* based on the drag result. The function checks if a tab is dropped over a different tab
* and updates the order accordingly.
*
* @param event The drag end event with active (dragged item) and over (drop target) properties.
*/
const onDragEnd = (event: DragEndEvent) => {
const {active, over} = event
if (over && active.id !== over.id) {
const activeId = active.id as string
const overId = over.id as string
setVariants((prev) => {
const activeIndex = prev.findIndex((variant) => variant.variantName === activeId)
const overIndex = prev.findIndex((variant) => variant.variantName === overId)
if (activeIndex !== -1 && overIndex !== -1) {
return arrayMove(prev, activeIndex, overIndex)
}
return prev
})
}
}
// Map the variants array to create the items array conforming to the Tab interface
const tabItems: PlaygroundTabsItem[] = variants.map((variant, index) => ({
key: variant.variantName,
label: `Variant ${variant.variantName}`,
children: (
<ViewNavigation
compareMode={compareMode}
variant={variant}
handlePersistVariant={handlePersistVariant}
environments={environments}
deleteVariant={deleteVariant}
onStateChange={(isDirty) =>
setUnsavedVariants((prev) => ({...prev, [variant.variantName]: isDirty}))
}
getHelpers={(helpers) => (variantHelpers.current[variant.variantName] = helpers)}
tabID={tabID}
/>
),
closable: !variant.persistent,
}))
return (
<div>
{contextHolder}
<TestContextProvider>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "right",
gap: 10,
margin: "10px 0",
}}
>
{compareMode && (
<Button
onClick={() => {
setIsModalOpen(true)
}}
>
Add Variant
</Button>
)}
<Button
onClick={() => setCompareMode(!compareMode)}
icon={<AppstoreOutlined />}
>
{!compareMode ? "Side-by-Side View" : "Tab View"}
</Button>
<Button
type="primary"
icon={<SyncOutlined />}
onClick={() => {
setIsLoading(true)
fetchData()
}}
ghost
>
Refresh
</Button>
</div>
{compareMode ? (
<div style={{display: "flex", width: "100%", gap: 10, overflowX: "scroll"}}>
<DndContext sensors={[sensor]} onDragEnd={onDragEnd}>
<SortableContext
items={variants.map((variant) => variant.variantName)}
strategy={horizontalListSortingStrategy}
>
{variants.map((variant, ix) => (
<Tabs
key={variant.variantName}
className="editable-card"
type="card"
style={{minWidth: 650, width: "100%"}}
items={[tabItems[ix]]}
renderTabBar={(tabBarProps, DefaultTabBar) => (
<DefaultTabBar {...tabBarProps}>
{(node) => (
<DraggableTabNode
{...node.props}
key={node.key}
>
{node}
</DraggableTabNode>
)}
</DefaultTabBar>
)}
/>
))}
</SortableContext>
</DndContext>
</div>
) : (
<Tabs
className="editable-card"
type="editable-card"
activeKey={activeKey}
onChange={setActiveKey}
onEdit={(_, action) => {
if (action === "add") {
setIsModalOpen(true)
} else if (action === "remove") {
deleteVariant()
}
}}
items={tabItems}
renderTabBar={(tabBarProps, DefaultTabBar) => (
<DndContext sensors={[sensor]} onDragEnd={onDragEnd}>
<SortableContext
items={tabItems.map((i) => i.key)}
strategy={horizontalListSortingStrategy}
>
<DefaultTabBar {...tabBarProps}>
{(node) => (
<DraggableTabNode {...node.props} key={node.key}>
{node}
</DraggableTabNode>
)}
</DefaultTabBar>
</SortableContext>
</DndContext>
)}
/>
)}
</TestContextProvider>
<NewVariantModal
isModalOpen={isModalOpen}
setIsModalOpen={setIsModalOpen}
addTab={addTab}
variants={variants}
setNewVariantName={setNewVariantName}
newVariantName={newVariantName}
setTemplateVariantName={setTemplateVariantName}
/>
</div>
)
}
export default Playground