-
Notifications
You must be signed in to change notification settings - Fork 9
/
GridLayout.tsx
320 lines (297 loc) · 12 KB
/
GridLayout.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
import 'react-grid-layout/css/styles.css';
import './GridLayout.scss';
import ReactGridLayout, { Layout, ReactGridLayoutProps } from 'react-grid-layout';
import ResizeHandleIcon from './resize-handle.svg';
import GridTile, { SetWidgetAttribute } from './GridTile';
import { useEffect, useMemo, useRef, useState } from 'react';
import { isWidgetType } from '../Widgets/widgetTypes';
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
import { currentDropInItemAtom } from '../../state/currentDropInItemAtom';
import { widgetMappingAtom } from '../../state/widgetMappingAtom';
import { layoutVariantAtom } from '../../state/layoutAtom';
import { templateAtom, templateIdAtom } from '../../state/templateAtom';
import DebouncePromise from 'awesome-debounce-promise';
import React from 'react';
import {
ExtendedLayoutItem,
LayoutTypes,
Variants,
extendLayout,
getDashboardTemplates,
getDefaultTemplate,
getWidgetIdentifier,
mapTemplateConfigToExtendedTemplateConfig,
patchDashboardTemplate,
} from '../../api/dashboard-templates';
import useCurrentUser from '../../hooks/useCurrentUser';
import { EmptyState, EmptyStateBody, EmptyStateHeader, EmptyStateIcon, EmptyStateVariant, PageSection } from '@patternfly/react-core';
import { GripVerticalIcon, PlusCircleIcon } from '@patternfly/react-icons';
import { getWidget } from '../Widgets/widgetDefaults';
import { drawerExpandedAtom } from '../../state/drawerExpandedAtom';
import { columns, dropping_elem_id } from '../../consts';
import { useAddNotification } from '../../state/notificationsAtom';
import { currentlyUsedWidgetsAtom } from '../../state/currentlyUsedWidgetsAtom';
export const breakpoints: {
[key in Variants]: number;
} = { xl: 1550, lg: 1400, md: 1100, sm: 800 };
const getResizeHandle = (resizeHandleAxis: string, ref: React.Ref<HTMLDivElement>) => {
return (
<div ref={ref} className={`react-resizable-handle react-resizable-handle-${resizeHandleAxis}`}>
<img src={ResizeHandleIcon} />
</div>
);
};
const LayoutEmptyState = () => {
const setDrawerExpanded = useSetAtom(drawerExpandedAtom);
useEffect(() => {
setDrawerExpanded(true);
}, []);
return (
<PageSection className="empty-layout pf-v5-u-p-0">
<EmptyState variant={EmptyStateVariant.lg} className="pf-v5-u-p-sm">
<EmptyStateHeader titleText="No dashboard content" headingLevel="h2" icon={<EmptyStateIcon icon={PlusCircleIcon} />} />
<EmptyStateBody>
You don’t have any widgets on your dashboard. To populate your dashboard, drag <GripVerticalIcon /> items from the blue widget bank to this
dashboard body here.
</EmptyStateBody>
{/* TODO: Add link to documentation once available [HCCDOC-2108]
<EmptyStateActions>
<Button variant="link" icon={<ExternalLinkAltIcon />} iconPosition="end" component="a" href={`#`}>
Learn about your widget dashboard
</Button>
</EmptyStateActions> */}
</EmptyState>
</PageSection>
);
};
const debouncedPatchDashboardTemplate = DebouncePromise(patchDashboardTemplate, 1500, {
onlyResolvesLast: true,
});
const GridLayout = ({ isLayoutLocked = false, layoutType = 'landingPage' }: { isLayoutLocked?: boolean; layoutType?: LayoutTypes }) => {
const [isDragging, setIsDragging] = useState(false);
const [isInitialRender, setIsInitialRender] = useState(true);
const [isLoaded, setIsLoaded] = useState(false);
const [layoutVariant, setLayoutVariant] = useAtom(layoutVariantAtom);
const [template, setTemplate] = useAtom(templateAtom);
const [templateId, setTemplateId] = useAtom(templateIdAtom);
const [layoutWidth, setLayoutWidth] = useState<number>(1200);
const layoutRef = useRef<HTMLDivElement>(null);
const { currentUser } = useCurrentUser();
const widgetMapping = useAtomValue(widgetMappingAtom);
const addNotification = useAddNotification();
const setCurrentlyUsedWidgets = useSetAtom(currentlyUsedWidgetsAtom);
const [currentDropInItem, setCurrentDropInItem] = useAtom(currentDropInItemAtom);
const droppingItemTemplate: ReactGridLayoutProps['droppingItem'] = useMemo(() => {
if (currentDropInItem && isWidgetType(widgetMapping, currentDropInItem)) {
return {
...widgetMapping[currentDropInItem].defaults,
i: dropping_elem_id,
widgetType: currentDropInItem,
title: 'New title',
config: widgetMapping[currentDropInItem].config,
};
}
}, [currentDropInItem]);
const setWidgetAttribute: SetWidgetAttribute = (id, attributeName, value) =>
setTemplate((prev) =>
Object.entries(prev).reduce(
(acc, [size, layout]) => ({
...acc,
[size]: layout.map((widget) => (widget.i === id ? { ...widget, [attributeName]: value } : widget)),
}),
prev
)
);
const removeWidget = (id: string) =>
setTemplate((prev) =>
Object.entries(prev).reduce(
(acc, [size, layout]) => ({
...acc,
[size]: layout.filter((widget) => widget.i !== id),
}),
prev
)
);
const onDrop: ReactGridLayoutProps['onDrop'] = (_layout: ExtendedLayoutItem[], layoutItem: ExtendedLayoutItem, event: DragEvent) => {
const data = event.dataTransfer?.getData('text') || '';
if (isWidgetType(widgetMapping, data)) {
setCurrentDropInItem(undefined);
setTemplate((prev) =>
Object.entries(prev).reduce((acc, [size, layout]) => {
const newWidget = {
...layoutItem,
...widgetMapping[data].defaults,
// make sure the configuration is valid for all layout sizes
w: size === layoutVariant ? layoutItem.w : Math.min(widgetMapping[data].defaults.w, columns[size as Variants]),
x: size === layoutVariant ? layoutItem.x : Math.min(layoutItem.x, columns[size as Variants]),
widgetType: data,
i: getWidgetIdentifier(data),
title: 'New title',
config: widgetMapping[data].config,
};
return {
...acc,
[size]: layout.reduce<ExtendedLayoutItem[]>(
(acc, curr) => {
if (curr.x + curr.w > newWidget.x && curr.y + curr.h <= newWidget.y) {
acc.push(curr);
} else {
// push the current items down on the Y axis if they are supposed to be below the new widget
acc.push({ ...curr, y: curr.y + curr.h });
}
return acc;
},
[newWidget]
),
};
}, prev)
);
}
event.preventDefault();
};
const onLayoutChange = async (currentLayout: Layout[]) => {
if (isInitialRender) {
setIsInitialRender(false);
setCurrentlyUsedWidgets(activeLayout.map((item) => item.widgetType));
return;
}
if (isLayoutLocked || templateId < 0 || !layoutVariant || currentDropInItem) {
return;
}
const data = extendLayout({ ...template, [layoutVariant]: currentLayout });
setCurrentlyUsedWidgets(activeLayout.map((item) => item.widgetType));
setTemplate(data);
try {
await debouncedPatchDashboardTemplate(templateId, { templateConfig: data });
} catch (error) {
console.error(error);
addNotification({
variant: 'danger',
title: 'Failed to patch dashboard configuration',
description: 'Your dashboard changes were unable to be saved.',
});
}
};
useEffect(() => {
if (!currentUser || templateId >= 0) {
return;
}
// TODO template type should be pulled from app config for reusability
getDashboardTemplates(layoutType)
.then((templates) => {
const customDefaultTemplate = getDefaultTemplate(templates);
if (!customDefaultTemplate) {
throw new Error('No custom default template found');
}
const extendedTemplateConfig = mapTemplateConfigToExtendedTemplateConfig(customDefaultTemplate.templateConfig);
const currentWidth = layoutRef?.current?.clientWidth || document.body.clientWidth;
let targetVariant: Variants;
if (currentWidth > breakpoints.lg) {
targetVariant = 'xl';
} else if (breakpoints.lg >= currentWidth && currentWidth > breakpoints.md) {
targetVariant = 'lg';
} else if (breakpoints.md >= currentWidth && currentWidth > breakpoints.sm) {
targetVariant = 'md';
} else {
targetVariant = 'sm';
}
setTemplate(extendedTemplateConfig);
setTemplateId(customDefaultTemplate.id);
setLayoutVariant(targetVariant);
})
.catch((err) => {
console.error(err);
addNotification({
variant: 'danger',
title: 'Failed to fetch dashboard template',
description: 'Try reloading the page.',
});
})
.finally(() => {
setIsLoaded(true);
});
}, [currentUser, templateId]);
function getGridDimensions(currentWidth: number) {
let variant: Variants = 'xl';
Object.entries(breakpoints).forEach(([breakpoint, value]) => {
if (value >= currentWidth) {
variant = breakpoint as Variants;
}
});
return variant;
}
useEffect(() => {
const currentWidth = layoutRef.current?.getBoundingClientRect().width ?? 1200;
const variant: Variants = getGridDimensions(currentWidth);
setLayoutVariant(variant);
setLayoutWidth(currentWidth);
const observer = new ResizeObserver((entries) => {
if (!entries[0]) return;
const currentWidth = entries[0].contentRect.width;
const variant: Variants = getGridDimensions(currentWidth);
setLayoutVariant(variant);
setLayoutWidth(currentWidth);
});
if (layoutRef.current) {
observer.observe(layoutRef.current);
}
return () => {
observer.disconnect();
};
}, []);
const activeLayout = template[layoutVariant] || [];
return (
// {/* relative position is required for the grid layout to properly calculate
// child translation while dragging is in progress */}
<div id="widget-layout-container" style={{ position: 'relative' }} ref={layoutRef}>
{activeLayout.length === 0 && !currentDropInItem && isLoaded && <LayoutEmptyState />}
<ReactGridLayout
// Critical key, we need to reset the grid when layout variant changes
key={'grid-' + layoutVariant}
draggableHandle=".drag-handle"
layout={template[layoutVariant]}
cols={columns[layoutVariant]}
rowHeight={56}
width={layoutWidth}
isDraggable={!isLayoutLocked}
isResizable={!isLayoutLocked}
resizeHandle={getResizeHandle}
resizeHandles={['sw', 'nw', 'se', 'ne']}
// add droppping item default based on dragged template
droppingItem={droppingItemTemplate}
isDroppable={!isLayoutLocked}
onDrop={onDrop}
useCSSTransforms
verticalCompact
onLayoutChange={onLayoutChange}
>
{activeLayout
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.map(({ widgetType, title, ...rest }, index) => {
const widget = getWidget(widgetMapping, widgetType);
if (!widget) {
return null;
}
const config = widgetMapping[widgetType]?.config;
return (
<div key={rest.i} data-grid={rest} tabIndex={index} className={`widget-columns-${rest.w} widget-rows-${rest.h}`}>
<GridTile
isDragging={isDragging}
setIsDragging={setIsDragging}
widgetType={widgetType}
// these will be dynamically calculated once the dimensions are calculated
widgetConfig={{ ...rest, colWidth: 1200 / 4, config }}
setWidgetAttribute={setWidgetAttribute}
removeWidget={removeWidget}
>
{rest.i}
</GridTile>
</div>
);
})
.filter((layoutItem) => layoutItem !== null)}
</ReactGridLayout>
</div>
);
};
export default GridLayout;