-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheditor.tsx
More file actions
413 lines (371 loc) · 17.3 KB
/
editor.tsx
File metadata and controls
413 lines (371 loc) · 17.3 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
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
411
412
413
import { Components } from "@frontend/common";
import {
useBackendAdminClient,
useCreateMutation,
useListQuery,
useRemovePreparedMutation,
useSchemaQuery,
useUpdatePreparedMutation,
} from "@frontend/common/src/hooks/useAdminAPI";
import { useCommonContext } from "@frontend/common/src/hooks/useCommonContext";
import { Autocomplete, Box, Button, Card, CardContent, CircularProgress, Stack, styled, Tab, Tabs, TextField, Typography } from "@mui/material";
import { DateTimePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterLuxon } from "@mui/x-date-pickers/AdapterLuxon";
import { PickerValue } from "@mui/x-date-pickers/internals";
import { ErrorBoundary, Suspense } from "@suspensive/react";
import { DateTime } from "luxon";
import { enqueueSnackbar, OptionsObject } from "notistack";
import * as React from "react";
import { useParams } from "react-router-dom";
import { ErrorFallback } from "../../elements/error_fallback";
import { AdminEditor } from "../../layouts/admin_editor";
const DUMMY_UUID = "00000000-0000-4000-8000-000000000000";
type enumItemType = { const: string | null; title: string };
type SpeakerSchemaType = {
schema: {
type: "object";
properties: {
id: { type: ["string", "null"]; format: "uuid"; readOnly: true };
str_repr: { type: "string"; readOnly: true };
user: { type: "integer"; oneOf: enumItemType[] };
image: { type: ["string", "null"]; oneOf: enumItemType[] };
biography_ko?: { type: ["string", "null"] };
biography_en?: { type: ["string", "null"] };
};
required?: string[];
$schema?: string;
};
ui_schema?: Record<string, { "ui:widget"?: string; "ui:field"?: string }>;
translation_fields?: string[];
};
type OnMemoeryPresentationSpeaker = {
id?: string;
trackId: string;
presentation: string;
user: string | null;
image: string | null;
biography_ko: string;
biography_en: string;
};
type PresentationSpeaker = Omit<OnMemoeryPresentationSpeaker, "trackId"> & {
id: string;
user: string;
};
const MUIStyledFieldset = styled("fieldset")(({ theme }) => ({
color: theme.palette.text.secondary,
margin: 0,
border: `1px solid ${theme.palette.info}`,
borderRadius: theme.shape.borderRadius,
}));
const MDXRendererContainer = styled(Box)(({ theme }) => ({
width: "50%",
maxWidth: "50%",
"& .markdown-body": {
width: "100%",
p: { margin: theme.spacing(2, 0) },
a: { color: theme.palette.primary.main },
},
}));
type PresentationSpeakerFormPropType = {
schema: SpeakerSchemaType;
disabled?: boolean;
speaker: OnMemoeryPresentationSpeaker;
onChange: (speaker: OnMemoeryPresentationSpeaker) => void;
onRemove: (speaker: OnMemoeryPresentationSpeaker) => void;
};
type PresentationSpeakerFormStateType = {
tab: "ko" | "en";
};
type AutoCompleteType = {
name: string;
value: string | null;
label: string;
};
const PresentationSpeakerForm: React.FC<PresentationSpeakerFormPropType> = ({ disabled, schema, speaker, onChange, onRemove }) => {
const { baseUrl, mdxComponents } = useCommonContext();
const [formState, setFormState] = React.useState<PresentationSpeakerFormStateType>({ tab: "ko" });
const setLanguage = (_: React.SyntheticEvent, tab: "ko" | "en") => setFormState((ps) => ({ ...ps, tab }));
const userOptions: AutoCompleteType[] = schema.schema.properties.user.oneOf.map((item) => ({
name: "user",
value: item.const || "",
label: item.title,
}));
const currentSelectedUser = userOptions.find((u) => u.value === speaker.user?.toString());
const imageOptions: AutoCompleteType[] = schema.schema.properties.image.oneOf.map((item) => ({
name: "image",
value: item.const || "",
label: item.title,
}));
const currentSelectedImage = imageOptions.find((u) => u.value === speaker.image?.toString());
const bioField = formState.tab === "ko" ? "biography_ko" : "biography_en";
const onSpeakerBioChange = (value?: string) => onChange({ ...speaker, [bioField]: value || "" });
const onSpeakerChange = (fieldName: string) => (_: React.SyntheticEvent, selected: AutoCompleteType | null) => {
onChange({ ...speaker, [fieldName]: selected?.value || "" });
};
const onSpeakerRemove = () => {
if (window.confirm("발표자를 삭제하시겠습니까?")) onRemove(speaker);
};
return (
<Card>
<CardContent>
<Stack spacing={2}>
<Autocomplete
fullWidth
defaultValue={currentSelectedUser}
value={currentSelectedUser}
onChange={onSpeakerChange("user")}
// inputValue={currentSelectedUser?.label || ""}
options={userOptions}
renderInput={(params) => <TextField {...params} label="발표자" />}
/>
<Autocomplete
fullWidth
defaultValue={currentSelectedImage}
value={currentSelectedImage}
// inputValue={currentSelectedImage?.label || ""}
options={imageOptions}
renderInput={(params) => <TextField {...params} label="발표자 이미지" />}
onChange={onSpeakerChange("image")}
/>
<Stack direction="row" spacing={2}>
<Tabs orientation="vertical" onChange={setLanguage} value={formState.tab} scrollButtons={false}>
<Tab value="ko" label="한국어" />
<Tab value="en" label="영어" />
</Tabs>
<Stack direction="column" spacing={2} sx={{ width: "100%", maxWidth: "100%" }}>
<MUIStyledFieldset>
<Typography variant="subtitle2" component="legend" children="발표자 소개" />
<Stack direction="row" spacing={2}>
<Box sx={{ width: "50%", maxWidth: "50%" }}>
<Components.MarkdownEditor disabled={disabled} value={speaker[bioField]} name={bioField} onChange={onSpeakerBioChange} />
</Box>
<MDXRendererContainer>
<Components.MDXRenderer text={speaker[bioField]} format="md" baseUrl={baseUrl} mdxComponents={mdxComponents} />
</MDXRendererContainer>
</Stack>
</MUIStyledFieldset>
</Stack>
</Stack>
<Button variant="outlined" color="error" onClick={onSpeakerRemove} children="발표자 삭제" />
</Stack>
</CardContent>
</Card>
);
};
type ScheduleSchemaType = {
schema: {
type: "object";
properties: {
room: { type: "string"; oneOf: enumItemType[] };
presentation: { type: "string"; oneOf: enumItemType[] };
start_at: { type: "string"; format: "date-time" };
end_at: { type: "string"; format: "date-time" };
};
required?: string[];
$schema?: string;
};
ui_schema?: Record<string, { "ui:widget"?: string; "ui:field"?: string }>;
translation_fields?: string[];
};
type OnMemorySchedule = {
id?: string;
trackId: string; // Unique identifier for the schedule item, used for local state management
room: string;
presentation: string;
start_at: string; // ISO 8601 date-time string
end_at: string; // ISO 8601 date-time string
};
type Schedule = Omit<OnMemorySchedule, "trackId"> & { id: string };
type ScheduleFormPropType = {
schema: ScheduleSchemaType;
disabled?: boolean;
schedule: OnMemorySchedule;
onChange: (schedule: OnMemorySchedule) => void;
onRemove: (schedule: OnMemorySchedule) => void;
};
const PresentationScheduleForm: React.FC<ScheduleFormPropType> = ({ schema, disabled, schedule, onChange, onRemove }) => {
const roomOptions: AutoCompleteType[] = schema.schema.properties.room.oneOf.map((item) => ({
name: "room",
value: item.const || "",
label: item.title,
}));
const currentSelectedRoom = roomOptions.find((r) => r.value === schedule.room?.toString());
const onSelectChange = (fieldName: string) => (_: React.SyntheticEvent, selected: AutoCompleteType | null) => {
onChange({ ...schedule, [fieldName]: selected?.value || "" });
};
const onScheduleTimeChange = (fieldName: string) => (value: PickerValue) => {
if (!value || !DateTime.isDateTime(value)) {
console.warn(`Invalid date-time value for ${fieldName}:`, value);
return;
}
onChange({ ...schedule, [fieldName]: value.toISO({ includeOffset: false }) });
};
const onScheduleRemove = () => window.confirm("스케줄을 삭제하시겠습니까?") && onRemove(schedule);
return (
<Card>
<CardContent>
<Stack spacing={2}>
<Autocomplete
fullWidth
defaultValue={currentSelectedRoom}
value={currentSelectedRoom}
onChange={onSelectChange("room")}
options={roomOptions}
disabled={disabled}
renderInput={(params) => <TextField {...params} label="발표 장소" />}
/>
<LocalizationProvider dateAdapter={AdapterLuxon} adapterLocale="ko-kr">
<DateTimePicker
disabled={disabled}
name="start_at"
label="시작 시각"
value={DateTime.fromISO(schedule.start_at)}
onChange={onScheduleTimeChange("start_at")}
minDateTime={DateTime.local(2000, 1, 1, 0, 0, 0)}
maxDateTime={DateTime.local(2100, 12, 31, 23, 59, 59)}
disablePast
/>
<DateTimePicker
disabled={disabled}
name="end_at"
label="종료 시각"
value={DateTime.fromISO(schedule.end_at)}
onChange={onScheduleTimeChange("end_at")}
minDateTime={DateTime.local(2000, 1, 1, 0, 0, 0)}
maxDateTime={DateTime.local(2100, 12, 31, 23, 59, 59)}
disablePast
/>
</LocalizationProvider>
<Button variant="outlined" color="error" onClick={onScheduleRemove} children="스케줄 삭제" />
</Stack>
</CardContent>
</Card>
);
};
type PresentationEditorStateType = {
speakers: OnMemoeryPresentationSpeaker[];
schedules: OnMemorySchedule[];
};
export const AdminPresentationEditor: React.FC = ErrorBoundary.with(
{ fallback: ErrorFallback },
Suspense.with({ fallback: <CircularProgress /> }, () => {
const { id } = useParams<{ id?: string }>();
const addSnackbar = (c: string | React.ReactNode, variant: OptionsObject["variant"]) =>
enqueueSnackbar(c, { variant, anchorOrigin: { vertical: "bottom", horizontal: "center" } });
const backendAdminAPIClient = useBackendAdminClient();
const speakerQueryParams = [backendAdminAPIClient, "event", "presentationspeaker"] as const;
const presentation = id || DUMMY_UUID;
const speakerCreateMutation = useCreateMutation<OnMemoeryPresentationSpeaker>(...speakerQueryParams);
const speakerUpdateMutation = useUpdatePreparedMutation<PresentationSpeaker>(...speakerQueryParams);
const speakerDeleteMutation = useRemovePreparedMutation(...speakerQueryParams);
const { data: speakerJsonSchema } = useSchemaQuery(...speakerQueryParams);
const { data: speakerInitialData } = useListQuery<PresentationSpeaker>(...speakerQueryParams, { presentation });
const speakers = speakerInitialData.map((s) => ({ ...s, trackId: s.id || Math.random().toString(36).substring(2, 15) }));
const scheduleQueryParams = [backendAdminAPIClient, "event", "roomschedule"] as const;
const scheduleCreateMutation = useCreateMutation<OnMemorySchedule>(...scheduleQueryParams);
const scheduleUpdateMutation = useUpdatePreparedMutation<Schedule>(...scheduleQueryParams);
const scheduleDeleteMutation = useRemovePreparedMutation(...scheduleQueryParams);
const { data: scheduleJsonSchema } = useSchemaQuery(...scheduleQueryParams);
const { data: scheduleInitialData } = useListQuery<Schedule>(...scheduleQueryParams, { presentation });
const schedules = scheduleInitialData.map((s) => ({ ...s, trackId: s.id || Math.random().toString(36).substring(2, 15) }));
const createEmptySpeaker = (): OnMemoeryPresentationSpeaker => ({
trackId: Math.random().toString(36).substring(2, 15),
presentation,
user: null,
image: null,
biography_ko: "",
biography_en: "",
});
const createEmptySchedule = (): OnMemorySchedule => ({
trackId: Math.random().toString(36).substring(2, 15),
room: "",
presentation,
start_at: DateTime.now().toISO({ includeOffset: false }),
end_at: DateTime.now().plus({ hours: 1 }).toISO({ includeOffset: false }),
});
const [editorState, setEditorState] = React.useState<PresentationEditorStateType>({ speakers, schedules });
const onSpeakerCreate = () => setEditorState((ps) => ({ ...ps, speakers: [...ps.speakers, createEmptySpeaker()] }));
const onSpeakerRemove = (oldSpeaker: OnMemoeryPresentationSpeaker) =>
setEditorState((ps) => ({ ...ps, speakers: ps.speakers.filter((s) => s.trackId !== oldSpeaker.trackId) }));
const onSpeakerChange = (newSpeaker: OnMemoeryPresentationSpeaker) =>
setEditorState((ps) => ({ ...ps, speakers: ps.speakers.map((s) => (s.trackId === newSpeaker.trackId ? newSpeaker : s)) }));
const onScheduleCreate = () => setEditorState((ps) => ({ ...ps, schedules: [...ps.schedules, createEmptySchedule()] }));
const onScheduleRemove = (oldSchedule: OnMemorySchedule) =>
setEditorState((ps) => ({ ...ps, schedules: ps.schedules.filter((s) => s.trackId !== oldSchedule.trackId) }));
const onScheduleChange = (newSchedule: OnMemorySchedule) =>
setEditorState((ps) => ({
...ps,
schedules: ps.schedules.map((s) => (s.trackId === newSchedule.trackId ? newSchedule : s)),
}));
const onSpeakerSubmit = () => {
if (!id) return;
addSnackbar("발표자 정보를 저장하는 중입니다...", "info");
const newSpeakers = editorState.speakers;
const editorSpeakerIds = newSpeakers.filter((s) => s.id).map((s) => s.id!);
const deletedSpeakerIds = speakerInitialData.filter((s) => !editorSpeakerIds.includes(s.id)).map((s) => s.id!);
const deleteMut = deletedSpeakerIds.map((id) => speakerDeleteMutation.mutateAsync(id));
const createMut = newSpeakers.filter((s) => s.id === undefined).map((s) => speakerCreateMutation.mutateAsync(s));
const updateMut = newSpeakers.filter((s) => s.id !== undefined).map((s) => speakerUpdateMutation.mutateAsync(s as PresentationSpeaker));
return Promise.all([...deleteMut, ...createMut, ...updateMut]).then(() => addSnackbar("발표자 정보가 저장되었습니다.", "success"));
};
const onScheduleSubmit = () => {
if (!id) return;
addSnackbar("스케줄 정보를 저장하는 중입니다...", "info");
const newSchedules = editorState.schedules;
const editorScheduleIds = newSchedules.filter((s) => s.id).map((s) => s.id!);
const deletedScheduleIds = scheduleInitialData.filter((s) => !editorScheduleIds.includes(s.id)).map((s) => s.id!);
const deleteMut = deletedScheduleIds.map((id) => scheduleDeleteMutation.mutateAsync(id));
const createMut = newSchedules.filter((s) => s.id === undefined).map((s) => scheduleCreateMutation.mutateAsync(s));
const updateMut = newSchedules.filter((s) => s.id !== undefined).map((s) => scheduleUpdateMutation.mutateAsync(s as Schedule));
return Promise.all([...deleteMut, ...createMut, ...updateMut]).then(() => addSnackbar("스케줄 정보가 저장되었습니다.", "success"));
};
const onPresentationSubmit = () => {
if (!id) return;
addSnackbar("발표 정보를 저장하는 중입니다...", "info");
return Promise.all([onSpeakerSubmit(), onScheduleSubmit()]).then(() => addSnackbar("발표 정보가 저장되었습니다.", "success"));
};
return (
<AdminEditor app="event" resource="presentation" id={id} afterSubmit={onPresentationSubmit}>
{id ? (
<Stack sx={{ mb: 2 }} spacing={2}>
<Components.Fieldset legend="스케줄 정보">
<Typography variant="h6">스케줄 정보</Typography>
<Stack spacing={2}>
{editorState.schedules.map((s) => (
<PresentationScheduleForm
key={s.trackId}
schema={scheduleJsonSchema as ScheduleSchemaType}
schedule={s}
onChange={onScheduleChange}
onRemove={onScheduleRemove}
/>
))}
<Button variant="outlined" onClick={onScheduleCreate} children="스케줄 추가" />
</Stack>
</Components.Fieldset>
<Components.Fieldset legend="발표자 정보">
<Typography variant="h6">발표자 정보</Typography>
<Stack spacing={2}>
{editorState.speakers.map((s) => (
<PresentationSpeakerForm
key={s.id}
schema={speakerJsonSchema as SpeakerSchemaType}
speaker={s}
onChange={onSpeakerChange}
onRemove={onSpeakerRemove}
/>
))}
<Button variant="outlined" onClick={onSpeakerCreate} children="발표자 추가" />
</Stack>
</Components.Fieldset>
</Stack>
) : (
<Stack>
<Typography variant="h6">발표자 & 스케줄 정보</Typography>
<Typography variant="body1">발표자나 스케줄 정보를 추가하려면 발표를 먼저 저장하세요.</Typography>
</Stack>
)}
</AdminEditor>
);
})
);