forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryContainerChildren.tsx
More file actions
246 lines (229 loc) · 8.51 KB
/
LibraryContainerChildren.tsx
File metadata and controls
246 lines (229 loc) · 8.51 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
import { FormattedMessage, useIntl } from '@edx/frontend-platform/i18n';
import {
useCallback, useContext, useEffect, useState,
} from 'react';
import {
ActionRow, Badge, Icon, Stack,
} from '@openedx/paragon';
import { Description } from '@openedx/paragon/icons';
import { InplaceTextEditor } from '@src/generic/inplace-text-editor';
import DraggableList, { SortableItem } from '../../generic/DraggableList';
import Loading from '../../generic/Loading';
import ErrorAlert from '../../generic/alert-error';
import { ContainerType, getBlockType } from '../../generic/key-utils';
import { useLibraryContext } from '../common/context/LibraryContext';
import {
useContainerChildren,
useUpdateContainer,
useUpdateContainerChildren,
} from '../data/apiHooks';
import { messages, subsectionMessages, sectionMessages } from './messages';
import containerMessages from '../containers/messages';
import { Container } from '../data/api';
import { ToastContext } from '../../generic/toast-context';
import TagCount from '../../generic/tag-count';
import { ContainerMenu } from '../components/ContainerCard';
import { useLibraryRoutes } from '../routes';
import { SidebarActions, useSidebarContext } from '../common/context/SidebarContext';
import { useRunOnNextRender } from '../../utils';
interface LibraryContainerChildrenProps {
containerKey: string;
/** set to true if it is rendered as preview */
readOnly?: boolean;
}
interface LibraryContainerMetadataWithUniqueId extends Container {
originalId: string;
}
interface ContainerRowProps extends LibraryContainerChildrenProps {
container: LibraryContainerMetadataWithUniqueId;
}
const ContainerRow = ({ containerKey, container, readOnly }: ContainerRowProps) => {
const intl = useIntl();
const { showToast } = useContext(ToastContext);
const updateMutation = useUpdateContainer(container.originalId, containerKey);
const { showOnlyPublished } = useLibraryContext();
const { navigateTo } = useLibraryRoutes();
const { setSidebarAction } = useSidebarContext();
const handleSaveDisplayName = async (newDisplayName: string) => {
try {
await updateMutation.mutateAsync({
displayName: newDisplayName,
});
showToast(intl.formatMessage(containerMessages.updateContainerSuccessMsg));
} catch (err) {
showToast(intl.formatMessage(containerMessages.updateContainerErrorMsg));
}
};
/* istanbul ignore next */
const scheduleJumpToTags = useRunOnNextRender(() => {
// TODO: Ugly hack to make sure sidebar shows manage tags section
// This needs to run after all changes to url takes place to avoid conflicts.
setTimeout(() => setSidebarAction(SidebarActions.JumpToManageTags), 250);
});
const jumpToManageTags = () => {
navigateTo({ selectedItemId: container.originalId });
scheduleJumpToTags();
};
return (
<>
{/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
<div
// Prevent parent card from being clicked.
onClick={(e) => e.stopPropagation()}
>
<InplaceTextEditor
onSave={handleSaveDisplayName}
text={showOnlyPublished ? (container.publishedDisplayName ?? container.displayName) : container.displayName}
textClassName="font-weight-bold small"
readOnly={readOnly || showOnlyPublished}
/>
</div>
<ActionRow.Spacer />
<Stack
direction="horizontal"
gap={3}
// Prevent parent card from being clicked.
/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */
onClick={(e) => e.stopPropagation()}
>
{!showOnlyPublished && container.hasUnpublishedChanges && (
<Badge
className="px-2 py-1"
variant="warning"
>
<Stack direction="horizontal" gap={1}>
<Icon size="xs" src={Description} />
<FormattedMessage {...messages.draftChipText} />
</Stack>
</Badge>
)}
<TagCount
size="sm"
count={container.tagsCount}
onClick={readOnly ? undefined : jumpToManageTags}
/>
{!readOnly && (
<ContainerMenu
containerKey={container.originalId}
displayName={container.displayName}
/>
)}
</Stack>
</>
);
};
/** Component to display container children subsections for section and units for subsection */
export const LibraryContainerChildren = ({ containerKey, readOnly }: LibraryContainerChildrenProps) => {
const intl = useIntl();
const [orderedChildren, setOrderedChildren] = useState<LibraryContainerMetadataWithUniqueId[]>([]);
const { showOnlyPublished, readOnly: libReadOnly } = useLibraryContext();
const { navigateTo } = useLibraryRoutes();
const { sidebarItemInfo } = useSidebarContext();
const [activeDraggingId, setActiveDraggingId] = useState<string | null>(null);
const orderMutator = useUpdateContainerChildren(containerKey);
const { showToast } = useContext(ToastContext);
const containerType = getBlockType(containerKey);
const handleReorder = useCallback(() => async (newOrder?: LibraryContainerMetadataWithUniqueId[]) => {
if (!newOrder) {
return;
}
const childrenKeys = newOrder.map((o) => o.originalId);
try {
await orderMutator.mutateAsync(childrenKeys);
showToast(intl.formatMessage(messages.orderUpdatedMsg));
} catch (e) {
showToast(intl.formatMessage(messages.failedOrderUpdatedMsg));
}
}, [orderMutator]);
const {
data: children,
isLoading,
isError,
error,
} = useContainerChildren(containerKey, showOnlyPublished);
useEffect(() => {
// Create new ids which are unique using index.
// This is required to support multiple components with same id under a container.
const newChildren = children?.map((child, idx) => {
const newChild: LibraryContainerMetadataWithUniqueId = {
...child,
id: `${child.id}----${idx}`,
originalId: child.id,
};
return newChild;
});
return setOrderedChildren(newChildren || []);
}, [children, setOrderedChildren]);
const handleChildClick = useCallback((child: LibraryContainerMetadataWithUniqueId, numberOfClicks: number) => {
const doubleClicked = numberOfClicks > 1;
if (!doubleClicked) {
navigateTo({ selectedItemId: child.originalId });
} else {
navigateTo({ containerId: child.originalId });
}
}, [navigateTo]);
const getComponentStyle = useCallback((childId: string) => {
const style: { marginBottom: string, borderRadius: string, outline?: string } = {
marginBottom: '1rem',
borderRadius: '8px',
};
if (activeDraggingId === childId) {
style.outline = '2px dashed gray';
}
return style;
}, [activeDraggingId]);
if (isLoading) {
return <Loading />;
}
if (isError) {
// istanbul ignore next
return <ErrorAlert error={error} />;
}
return (
<div className="ml-2 library-container-children">
{children?.length === 0 && (
<h4 className="ml-2">
{containerType === ContainerType.Section ? (
<FormattedMessage {...sectionMessages.noChildrenText} />
) : (
<FormattedMessage {...subsectionMessages.noChildrenText} />
)}
</h4>
)}
<DraggableList
itemList={orderedChildren}
setState={setOrderedChildren}
updateOrder={handleReorder}
activeId={activeDraggingId}
setActiveId={setActiveDraggingId}
>
{orderedChildren?.map((child) => (
// A container can have multiple instances of the same block
// eslint-disable-next-line react/no-array-index-key
<SortableItem
id={child.id}
key={child.id}
componentStyle={getComponentStyle(child.id)}
actionStyle={{
padding: '0.5rem 1rem',
background: '#FBFAF9',
borderRadius: '8px',
borderLeft: '8px solid #E1DDDB',
}}
isClickable={!readOnly}
onClick={(e) => !readOnly && handleChildClick(child, e.detail)}
disabled={readOnly || libReadOnly}
cardClassName={sidebarItemInfo?.id === child.originalId ? 'selected' : undefined}
actions={(
<ContainerRow
containerKey={containerKey}
container={child}
readOnly={readOnly || libReadOnly}
/>
)}
/>
))}
</DraggableList>
</div>
);
};