@capytale/meta-player 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.eslintrc.json +35 -0
  2. package/.prettierrc.json +4 -0
  3. package/README.md +27 -0
  4. package/index.html +15 -0
  5. package/package.json +48 -0
  6. package/public/themes/lara-dark-blue/fonts/Inter-italic.var.woff2 +0 -0
  7. package/public/themes/lara-dark-blue/fonts/Inter-roman.var.woff2 +0 -0
  8. package/public/themes/lara-dark-blue/theme.css +7015 -0
  9. package/public/themes/lara-light-blue/fonts/Inter-italic.var.woff2 +0 -0
  10. package/public/themes/lara-light-blue/fonts/Inter-roman.var.woff2 +0 -0
  11. package/public/themes/lara-light-blue/theme.css +7005 -0
  12. package/src/App.tsx +116 -0
  13. package/src/AppRedux.css +39 -0
  14. package/src/MetaPlayer.tsx +51 -0
  15. package/src/app/createAppSlice.ts +6 -0
  16. package/src/app/hooks.ts +12 -0
  17. package/src/app/store.ts +46 -0
  18. package/src/app.module.scss +56 -0
  19. package/src/demo.tsx +81 -0
  20. package/src/features/activityData/IsDirtySetter.tsx +17 -0
  21. package/src/features/activityData/OptionSetter.tsx +35 -0
  22. package/src/features/activityData/activityDataSlice.ts +250 -0
  23. package/src/features/activityData/metaPlayerOptions.ts +17 -0
  24. package/src/features/activityJS/ActivityJSProvider.tsx +110 -0
  25. package/src/features/activityJS/AfterSaveAction.tsx +23 -0
  26. package/src/features/activityJS/BeforeSaveAction.tsx +23 -0
  27. package/src/features/activityJS/Saver.tsx +147 -0
  28. package/src/features/activityJS/hooks.ts +93 -0
  29. package/src/features/activityJS/saverSlice.ts +58 -0
  30. package/src/features/layout/layoutSlice.ts +76 -0
  31. package/src/features/navbar/ActivityInfo.tsx +41 -0
  32. package/src/features/navbar/ActivityMenu.tsx +56 -0
  33. package/src/features/navbar/ActivityQuickActions.tsx +52 -0
  34. package/src/features/navbar/ActivitySidebarActions.tsx +52 -0
  35. package/src/features/navbar/CapytaleMenu.tsx +183 -0
  36. package/src/features/navbar/GradingNav.tsx +120 -0
  37. package/src/features/navbar/ReviewNavbar.tsx +18 -0
  38. package/src/features/navbar/SidebarContent.tsx +125 -0
  39. package/src/features/navbar/index.tsx +33 -0
  40. package/src/features/navbar/navbarSlice.ts +51 -0
  41. package/src/features/navbar/student-utils.ts +11 -0
  42. package/src/features/navbar/style.module.scss +162 -0
  43. package/src/features/pedago/AnswerSheetEditor.tsx +65 -0
  44. package/src/features/pedago/InstructionsEditor.tsx +82 -0
  45. package/src/features/pedago/index.tsx +219 -0
  46. package/src/features/pedago/style.module.scss +104 -0
  47. package/src/features/theming/ThemeSwitcher.tsx +51 -0
  48. package/src/features/theming/themingSlice.ts +93 -0
  49. package/src/hooks/index.ts +8 -0
  50. package/src/index.css +30 -0
  51. package/src/index.tsx +6 -0
  52. package/src/logo.svg +1 -0
  53. package/src/my_json_data.js +4146 -0
  54. package/src/settings.ts +6 -0
  55. package/src/setupTests.ts +1 -0
  56. package/src/utils/ErrorBoundary.tsx +41 -0
  57. package/src/utils/PopupButton.tsx +135 -0
  58. package/src/utils/activity.ts +8 -0
  59. package/src/utils/breakpoints.ts +5 -0
  60. package/src/utils/clipboard.ts +11 -0
  61. package/src/utils/test-utils.tsx +65 -0
  62. package/src/utils/useFullscreen.ts +65 -0
  63. package/src/vite-env.d.ts +1 -0
  64. package/tsconfig.json +27 -0
  65. package/tsconfig.node.json +9 -0
  66. package/vite.config.ts +17 -0
@@ -0,0 +1,250 @@
1
+ import type { PayloadAction } from "@reduxjs/toolkit";
2
+ import { createAppSlice } from "../../app/createAppSlice";
3
+ import { ActivityMode } from "@capytale/activity.js/activity/activitySession";
4
+ import { TimeRange } from "@capytale/activity.js/common/field";
5
+ import { InitialEditorStateType } from "@capytale/capytale-rich-text-editor";
6
+ import {
7
+ MetaPlayerOptions,
8
+ defaultMetaPlayerOptions,
9
+ } from "./metaPlayerOptions";
10
+ import { wf } from "@capytale/activity.js/activity/field/workflow";
11
+
12
+ export type StudentInfo = {
13
+ firstName: string;
14
+ lastName: string;
15
+ class: string;
16
+ };
17
+
18
+ export type Instructions = {
19
+ value: InitialEditorStateType | null;
20
+ htmlValue: string | null;
21
+ format: "html" | "markdown" | "lexical";
22
+ };
23
+
24
+ export type Icon = {
25
+ path: string;
26
+ style: any;
27
+ };
28
+
29
+ interface ActivityJSData {
30
+ title: string;
31
+ mode: ActivityMode;
32
+ isDirty: boolean;
33
+ returnUrl: string;
34
+ helpUrl: string;
35
+ code: string;
36
+ nid: number;
37
+ activityNid: number;
38
+ accessTrMode: string;
39
+ accessTimerange: TimeRange | null;
40
+ studentInfo: StudentInfo | null;
41
+ instructions: Instructions | null;
42
+ answerSheetContent: InitialEditorStateType | null;
43
+ codeLink: string;
44
+ icon: Icon | null;
45
+ friendlyType: string;
46
+ comments: string | null;
47
+ grading: string | null;
48
+ workflow: wf | null | undefined;
49
+ }
50
+
51
+ type SaveState = "idle" | "should-save" | "saving";
52
+
53
+ interface UIState {
54
+ canSaveInstructions: boolean;
55
+ canSaveAnswerSheet: boolean;
56
+ saveState: SaveState;
57
+ }
58
+
59
+ export interface ActivityDataState
60
+ extends ActivityJSData,
61
+ MetaPlayerOptions,
62
+ UIState {}
63
+
64
+ const initialState: ActivityDataState = {
65
+ title: "",
66
+ mode: "view",
67
+ isDirty: false,
68
+ returnUrl: "",
69
+ helpUrl: "",
70
+ code: "",
71
+ nid: 0,
72
+ activityNid: 0,
73
+ accessTrMode: "",
74
+ accessTimerange: null,
75
+ studentInfo: {
76
+ firstName: "",
77
+ lastName: "",
78
+ class: "",
79
+ },
80
+ instructions: null,
81
+ answerSheetContent: null,
82
+ codeLink: "",
83
+ icon: null,
84
+ friendlyType: "",
85
+ comments: null,
86
+ grading: null,
87
+ workflow: null,
88
+
89
+ ...defaultMetaPlayerOptions,
90
+
91
+ canSaveInstructions: true,
92
+ canSaveAnswerSheet: true,
93
+ saveState: "idle",
94
+ };
95
+
96
+ // If you are not using async thunks you can use the standalone `createSlice`.
97
+ export const activityDataSlice = createAppSlice({
98
+ name: "activityData",
99
+ // `createSlice` will infer the state type from the `initialState` argument
100
+ initialState,
101
+ // The `reducers` field lets us define reducers and generate associated actions
102
+ reducers: (create) => ({
103
+ toRemove: create.reducer((state) => {
104
+ state.hasInstructions = false;
105
+ }),
106
+ // Use the `PayloadAction` type to declare the contents of `action.payload`
107
+ setActivityJSData: create.reducer(
108
+ (state, action: PayloadAction<ActivityJSData>) => {
109
+ state.title = action.payload.title;
110
+ state.mode = action.payload.mode;
111
+ state.returnUrl = action.payload.returnUrl;
112
+ state.helpUrl = action.payload.helpUrl;
113
+ state.code = action.payload.code;
114
+ state.accessTrMode = action.payload.accessTrMode;
115
+ state.accessTimerange = action.payload.accessTimerange;
116
+ state.studentInfo = action.payload.studentInfo;
117
+ state.instructions = action.payload.instructions;
118
+ state.codeLink = action.payload.codeLink;
119
+ state.icon = action.payload.icon;
120
+ state.friendlyType = action.payload.friendlyType;
121
+ state.comments = action.payload.comments;
122
+ state.grading = action.payload.grading;
123
+ state.nid = action.payload.nid;
124
+ state.activityNid = action.payload.activityNid;
125
+ state.workflow = action.payload.workflow;
126
+ },
127
+ ),
128
+ setPlayerSettings: create.reducer(
129
+ (state, action: PayloadAction<MetaPlayerOptions>) => {
130
+ state.hasInstructions = action.payload.hasInstructions;
131
+ state.pedagoLayout = action.payload.pedagoLayout;
132
+ state.supportsLightTheme = action.payload.supportsLightTheme;
133
+ state.supportsDarkTheme = action.payload.supportsDarkTheme;
134
+ },
135
+ ),
136
+ setCanSaveInstructions: create.reducer(
137
+ (state, action: PayloadAction<boolean>) => {
138
+ state.canSaveInstructions = action.payload;
139
+ },
140
+ ),
141
+ setCanSaveAnswerSheet: create.reducer(
142
+ (state, action: PayloadAction<boolean>) => {
143
+ state.canSaveAnswerSheet = action.payload;
144
+ },
145
+ ),
146
+ setLexicalInstructionsState: create.reducer(
147
+ (state, action: PayloadAction<InitialEditorStateType>) => {
148
+ state.instructions = {
149
+ format: "lexical",
150
+ value: action.payload,
151
+ htmlValue: null,
152
+ };
153
+ },
154
+ ),
155
+ setLexicalAnswerSheetState: create.reducer(
156
+ (state, action: PayloadAction<InitialEditorStateType>) => {
157
+ state.answerSheetContent = action.payload;
158
+ },
159
+ ),
160
+ setSaveState: create.reducer((state, action: PayloadAction<SaveState>) => {
161
+ state.saveState = action.payload;
162
+ }),
163
+ setGrading: create.reducer((state, action: PayloadAction<string>) => {
164
+ state.grading = action.payload;
165
+ }),
166
+ setComments: create.reducer((state, action: PayloadAction<string>) => {
167
+ state.comments = action.payload;
168
+ }),
169
+ setWorkflow: create.reducer((state, action: PayloadAction<wf>) => {
170
+ state.workflow = action.payload;
171
+ }),
172
+ setIsDirty: create.reducer((state, action: PayloadAction<boolean>) => {
173
+ state.isDirty = action.payload;
174
+ }),
175
+ }),
176
+ // You can define your selectors here. These selectors receive the slice
177
+ // state as their first argument.
178
+ selectors: {
179
+ selectMode: (data) => data.mode,
180
+ selectActivityInfo: (data) => ({
181
+ title: data.title,
182
+ studentInfo: data.studentInfo,
183
+ }),
184
+ selectSharingInfo: (data) => ({
185
+ code: data.code,
186
+ codeLink: data.codeLink,
187
+ }),
188
+ selectInstructions: (data) => data.instructions,
189
+ selectAnswerSheetContent: (data) => data.answerSheetContent,
190
+ selectComments: (data) => data.comments,
191
+ selectGrading: (data) => data.grading,
192
+ selectHasInstructions: (data) => data.hasInstructions,
193
+ selectPedagoLayout: (data) => data.pedagoLayout,
194
+ selectHasGradingOrComments: (data) => !!(data.grading || data.comments),
195
+ selectSaveState: (data) => data.saveState,
196
+ selectReturnUrl: (data) => data.returnUrl,
197
+ selectNid: (data) => data.nid,
198
+ selectActivityNid: (data) => data.activityNid,
199
+ selectIcon: (data) => data.icon,
200
+ selectWorkflow: (data) => data.workflow,
201
+ selectIsDirty: (data) => data.isDirty,
202
+
203
+ selectCanChoosePedagoLayout: (data) =>
204
+ data.pedagoLayout === "default-horizontal" ||
205
+ data.pedagoLayout === "default-vertical",
206
+
207
+ selectCanChooseTheme: (data) =>
208
+ data.supportsDarkTheme && data.supportsLightTheme,
209
+ },
210
+ });
211
+
212
+ // Action creators are generated for each case reducer function.
213
+ export const {
214
+ toRemove,
215
+ setActivityJSData,
216
+ setPlayerSettings,
217
+ setCanSaveInstructions,
218
+ setCanSaveAnswerSheet,
219
+ setLexicalInstructionsState,
220
+ setLexicalAnswerSheetState,
221
+ setSaveState,
222
+ setGrading,
223
+ setComments,
224
+ setWorkflow,
225
+ setIsDirty,
226
+ } = activityDataSlice.actions;
227
+
228
+ // Selectors returned by `slice.selectors` take the root state as their first argument.
229
+ export const {
230
+ selectMode,
231
+ selectActivityInfo,
232
+ selectSharingInfo,
233
+ selectInstructions,
234
+ selectAnswerSheetContent,
235
+ selectComments,
236
+ selectGrading,
237
+ selectHasInstructions,
238
+ selectPedagoLayout,
239
+ selectHasGradingOrComments,
240
+ selectSaveState,
241
+ selectReturnUrl,
242
+ selectNid,
243
+ selectActivityNid,
244
+ selectIcon,
245
+ selectWorkflow,
246
+ selectIsDirty,
247
+
248
+ selectCanChoosePedagoLayout,
249
+ selectCanChooseTheme,
250
+ } = activityDataSlice.selectors;
@@ -0,0 +1,17 @@
1
+ export type MetaPlayerOptions = {
2
+ hasInstructions: boolean;
3
+ pedagoLayout:
4
+ | "horizontal"
5
+ | "vertical"
6
+ | "default-horizontal"
7
+ | "default-vertical";
8
+ supportsLightTheme: boolean;
9
+ supportsDarkTheme: boolean;
10
+ };
11
+
12
+ export const defaultMetaPlayerOptions: MetaPlayerOptions = {
13
+ hasInstructions: true,
14
+ pedagoLayout: "default-horizontal",
15
+ supportsLightTheme: true,
16
+ supportsDarkTheme: false,
17
+ };
@@ -0,0 +1,110 @@
1
+ import {
2
+ FC,
3
+ PropsWithChildren,
4
+ ReactNode,
5
+ createContext,
6
+ useContext,
7
+ useState,
8
+ } from "react";
9
+
10
+ import {
11
+ ActivitySessionLoaderReturnValue,
12
+ LoadOptions,
13
+ useActivitySessionLoader,
14
+ } from "./hooks";
15
+ import { getIdFromUrl } from "../../utils/activity";
16
+ import { useAppDispatch } from "../../app/hooks";
17
+ import ActivitySession from "@capytale/activity.js/activity/activitySession";
18
+ import { setActivityJSData } from "../activityData/activityDataSlice";
19
+
20
+ const ActivityJSContext = createContext<ActivitySessionLoaderReturnValue>({
21
+ state: "loading",
22
+ activitySession: null,
23
+ });
24
+
25
+ type ActivityJSProviderProps = PropsWithChildren<{
26
+ options?: LoadOptions;
27
+ loadingFallback?: ReactNode;
28
+ }>;
29
+
30
+ export const ActivityJSProvider: FC<ActivityJSProviderProps> = (props) => {
31
+ const [loaded, setLoaded] = useState(false);
32
+ const activityId = getIdFromUrl();
33
+ const dispatch = useAppDispatch();
34
+
35
+ const callback = (data: ActivitySession) => {
36
+ //@ts-expect-error
37
+ window.capy = data;
38
+
39
+ const ab = data.activityBunch;
40
+ /*
41
+ console.log("Test accès");
42
+ console.log(ab.assignmentNode?.answer_sheet.value);
43
+ console.log(ab.activityNode.answer_sheet.value);
44
+ */
45
+ /*
46
+ const answerSheetContent =
47
+ ab.assignmentNode?.answer_sheet.value ||
48
+ ab.activityNode.answer_sheet.value ||
49
+ null;
50
+ */
51
+ const answerSheetContent = null;
52
+ dispatch(
53
+ setActivityJSData({
54
+ title: ab.title.value || "",
55
+ mode: data.mode,
56
+ isDirty: false,
57
+ returnUrl: data.returnUrl,
58
+ helpUrl: data.type.helpUrl,
59
+ nid: ab.mainNode.nid,
60
+ activityNid: ab.activityNode.nid,
61
+ code: ab.code.value || "",
62
+ accessTrMode: ab.access_tr_mode.value || "",
63
+ accessTimerange: ab.access_timerange.value,
64
+ studentInfo: data.student
65
+ ? {
66
+ firstName: data.student.prenom || "",
67
+ lastName: data.student.nom || "",
68
+ class: data.student.classe || "",
69
+ }
70
+ : null,
71
+ instructions: ab.instructions.value.lexical
72
+ ? {
73
+ value: ab.instructions.value.lexical,
74
+ htmlValue: ab.instructions.value.html,
75
+ format: "lexical",
76
+ }
77
+ : {
78
+ value: null,
79
+ htmlValue: ab.instructions.value.html,
80
+ format: "html",
81
+ },
82
+ answerSheetContent: answerSheetContent,
83
+ codeLink: data.codeLink || "",
84
+ icon: data.icon || null,
85
+ friendlyType: data.friendlyType,
86
+ comments: ab.assignmentNode?.comments.value || null,
87
+ grading: ab.assignmentNode?.grading.value || null,
88
+ workflow: ab.assignmentNode?.workflow,
89
+ }),
90
+ );
91
+ setLoaded(true);
92
+ };
93
+
94
+ if (!activityId) {
95
+ throw new Error("No activity id found in the URL");
96
+ }
97
+ const value = useActivitySessionLoader(activityId, props.options, callback);
98
+ if (!loaded) {
99
+ return <>{props.loadingFallback}</>;
100
+ }
101
+ return (
102
+ <ActivityJSContext.Provider value={value}>
103
+ {props.children}
104
+ </ActivityJSContext.Provider>
105
+ );
106
+ };
107
+
108
+ export const useActivityJS = () => {
109
+ return useContext(ActivityJSContext);
110
+ };
@@ -0,0 +1,23 @@
1
+ import { FC, useEffect } from "react";
2
+ import {
3
+ SaveCallback,
4
+ addAfterSave,
5
+ removeAfterSave,
6
+ } from "./saverSlice";
7
+ import { useAppDispatch } from "../../app/hooks";
8
+
9
+ type AfterSaveActionProps = SaveCallback;
10
+
11
+ const AfterSaveAction: FC<AfterSaveActionProps> = (props) => {
12
+ const dispatch = useAppDispatch();
13
+ useEffect(() => {
14
+ dispatch(addAfterSave(props));
15
+ return () => {
16
+ // Remove the callback when the component is unmounted
17
+ dispatch(removeAfterSave(props.name));
18
+ };
19
+ }, [props]);
20
+ return null;
21
+ };
22
+
23
+ export default AfterSaveAction;
@@ -0,0 +1,23 @@
1
+ import { FC, useEffect } from "react";
2
+ import {
3
+ SaveCallback,
4
+ addBeforeSave,
5
+ removeBeforeSave,
6
+ } from "./saverSlice";
7
+ import { useAppDispatch } from "../../app/hooks";
8
+
9
+ type BeforeSaveActionProps = SaveCallback;
10
+
11
+ const BeforeSaveAction: FC<BeforeSaveActionProps> = (props) => {
12
+ const dispatch = useAppDispatch();
13
+ useEffect(() => {
14
+ dispatch(addBeforeSave(props));
15
+ return () => {
16
+ // Remove the callback when the component is unmounted
17
+ dispatch(removeBeforeSave(props.name));
18
+ };
19
+ }, [props]);
20
+ return null;
21
+ };
22
+
23
+ export default BeforeSaveAction;
@@ -0,0 +1,147 @@
1
+ import { FC, useEffect, useRef } from "react";
2
+ import { useAppDispatch, useAppSelector } from "../../app/hooks";
3
+ import {
4
+ selectAnswerSheetContent,
5
+ selectComments,
6
+ selectGrading,
7
+ selectInstructions,
8
+ selectSaveState,
9
+ selectWorkflow,
10
+ setSaveState,
11
+ } from "../activityData/activityDataSlice";
12
+ import { useActivityJS } from "./ActivityJSProvider";
13
+ import { Toast } from "primereact/toast";
14
+ import { selectBeforeSave, selectAfterSave } from "./saverSlice";
15
+
16
+ const Saver: FC<{}> = () => {
17
+ const dispatch = useAppDispatch();
18
+ const activityJs = useActivityJS();
19
+ const instructions = useAppSelector(selectInstructions);
20
+ const answerSheetContent = useAppSelector(selectAnswerSheetContent);
21
+ const comments = useAppSelector(selectComments);
22
+ const grading = useAppSelector(selectGrading);
23
+ const beforeSave = useAppSelector(selectBeforeSave);
24
+ const afterSave = useAppSelector(selectAfterSave);
25
+ const workflow = useAppSelector(selectWorkflow);
26
+
27
+ const toast = useRef<Toast>(null);
28
+
29
+ const executePrepareSave = () => {};
30
+ const save = async () => {
31
+ if (!activityJs.activitySession) {
32
+ throw new Error("No activity session to save");
33
+ }
34
+ for (const callback of Object.values(beforeSave)) {
35
+ try {
36
+ const v = callback();
37
+ if (v instanceof Promise) {
38
+ await v;
39
+ }
40
+ } catch (e) {
41
+ console.error("Error in beforeSave callback", e);
42
+ dispatch(setSaveState("idle"));
43
+ toast.current!.show({
44
+ summary: "Erreur : enregistrement annulé",
45
+ detail: (e as any).toString(),
46
+ severity: "error",
47
+ life: 10000,
48
+ });
49
+ return;
50
+ }
51
+ }
52
+ const ab = activityJs.activitySession.activityBunch;
53
+ if (activityJs.activitySession.mode === "create") {
54
+ ab.instructions.value = {
55
+ lexical:
56
+ instructions?.format === "lexical"
57
+ ? typeof instructions.value === "string"
58
+ ? instructions.value
59
+ : JSON.stringify(instructions.value)
60
+ : null,
61
+ html:
62
+ instructions?.format === "lexical"
63
+ ? instructions.htmlValue
64
+ : (instructions?.value as string),
65
+ };
66
+ /*
67
+ ab.activityNode.answer_sheet.value =
68
+ typeof answerSheetContent === "string"
69
+ ? answerSheetContent
70
+ : JSON.stringify(answerSheetContent);
71
+ */
72
+ }
73
+ if (activityJs.activitySession.mode === "review") {
74
+ ab.assignmentNode!.comments.value = comments || "";
75
+ ab.assignmentNode!.grading.value = grading || "";
76
+ }
77
+ if (
78
+ activityJs.activitySession.mode === "review" ||
79
+ activityJs.activitySession.mode === "assignment"
80
+ ) {
81
+ ab.assignmentNode!.answer_sheet.value =
82
+ typeof answerSheetContent === "string"
83
+ ? answerSheetContent
84
+ : JSON.stringify(answerSheetContent);
85
+ }
86
+ if (
87
+ activityJs.activitySession.mode === "assignment" ||
88
+ activityJs.activitySession.mode === "review"
89
+ ) {
90
+ console.log("Workflow:", workflow);
91
+ ab.assignmentNode!.workflow = workflow!;
92
+ }
93
+ try {
94
+ const saveData = await ab.save();
95
+ console.log("Save return data", saveData);
96
+ dispatch(setSaveState("idle"));
97
+ toast.current!.show({
98
+ summary: "Sauvegarde réussie",
99
+ detail: "L'activité a bien été enregistrée.",
100
+ severity: "success",
101
+ life: 2000,
102
+ });
103
+ for (const callback of Object.values(afterSave)) {
104
+ try {
105
+ const v = callback();
106
+ if (v instanceof Promise) {
107
+ await v;
108
+ }
109
+ } catch (e) {
110
+ console.error("Error in afterSave callback", e);
111
+ dispatch(setSaveState("idle"));
112
+ toast.current!.show({
113
+ summary: "Erreur après sauvegarde",
114
+ detail: (e as any).toString(),
115
+ severity: "error",
116
+ life: 10000,
117
+ });
118
+ }
119
+ }
120
+ } catch (error: any) {
121
+ console.error("Error saving", error);
122
+ dispatch(setSaveState("idle"));
123
+ toast.current!.show({
124
+ summary: "Erreur lors de l'enregistrement",
125
+ detail: error.toString(),
126
+ severity: "error",
127
+ life: 10000,
128
+ });
129
+ }
130
+ };
131
+
132
+ const saveState = useAppSelector(selectSaveState);
133
+ useEffect(() => {
134
+ if (saveState === "should-save") {
135
+ dispatch(setSaveState("saving"));
136
+ executePrepareSave();
137
+ save();
138
+ }
139
+ }, [saveState]);
140
+ return (
141
+ <>
142
+ <Toast position="bottom-right" ref={toast} />
143
+ </>
144
+ );
145
+ };
146
+
147
+ export default Saver;
@@ -0,0 +1,93 @@
1
+ import { useEffect, useState, useRef } from "react";
2
+
3
+ import { autoLoad } from "@capytale/activity.js";
4
+
5
+ import type ActivitySession from "@capytale/activity.js/activity/activitySession/uni";
6
+
7
+ import type { ActivityBunchOptions as LoadOptions } from "@capytale/activity.js/activity/activityBunch/uni/backend";
8
+
9
+ export type { LoadOptions };
10
+
11
+ export type ActivitySessionLoaderReturnValue = {
12
+ state: "loading" | "loaded" | "error";
13
+ activitySession: ActivitySession | null;
14
+ error?: any;
15
+ };
16
+
17
+ /**
18
+ * Un hook pour utiliser activity.js
19
+ * Charge une activité de façon réactive.
20
+ *
21
+ * @param id id de l'activité à charger
22
+ * @param loadOptions les options de chargement
23
+ * @param callback une callback appelée avec l'activité chargée
24
+ * @returns un objet contenant l'état de chargement de l'activité et l'activité dès qu'elle est chargée
25
+ */
26
+
27
+ export function useActivitySessionLoader(
28
+ id: number,
29
+ loadOptions?: LoadOptions,
30
+ callback?: (activitySession: ActivitySession) => void,
31
+ ): ActivitySessionLoaderReturnValue {
32
+ const callbackW = useHandlerWrapper(callback);
33
+ const [state, setState] = useState<ActivitySessionLoaderReturnValue>({
34
+ state: "loading",
35
+ activitySession: null,
36
+ });
37
+ useEffect(() => {
38
+ let cancelled = false;
39
+ autoLoad(loadOptions)
40
+ .then((data) => {
41
+ if (cancelled) return;
42
+ callbackW(data);
43
+ setState({
44
+ state: "loaded",
45
+ activitySession: data,
46
+ });
47
+ (window as any).capy = data;
48
+ })
49
+ .catch((error) => {
50
+ if (cancelled) return;
51
+ setState({
52
+ state: "error",
53
+ activitySession: null,
54
+ error,
55
+ });
56
+ });
57
+ return () => {
58
+ cancelled = true;
59
+ setState({
60
+ state: "loading",
61
+ activitySession: null,
62
+ });
63
+ };
64
+ }, [id, loadOptions?.binaryDataType, loadOptions?.readOnly]);
65
+ return state;
66
+ }
67
+
68
+ /**
69
+ * Si un handler est passé en props à un composant, il peut changer. Il n'y a pas trop de raison mais
70
+ * rien ne l'interdit.
71
+ * Si un useEffect invoque ce handler, il faudrait que le handler figure dans les dépendances du useEffect.
72
+ * Du coup, si le handler change, le useEffect est ré-exécuté.
73
+ * Ce hook crée un wrapper immuable autour du handler passé en props. Ce wrapper ne change jamais et n'a donc
74
+ * pas besoin de figurer dans les dépendances du useEffect.
75
+ *
76
+ * @param handler
77
+ */
78
+ export function useHandlerWrapper<H extends () => any>(
79
+ handler?: H,
80
+ ): () => ReturnType<H> | void;
81
+ export function useHandlerWrapper<H extends (...args: any[]) => any>(
82
+ handler?: H,
83
+ ): (...p: Parameters<H>) => ReturnType<H> | void;
84
+ export function useHandlerWrapper<H extends (...args: any[]) => any>(
85
+ handler?: H,
86
+ ): (...p: Parameters<H>) => ReturnType<H> | void {
87
+ const handlerRef = useRef<H>();
88
+ handlerRef.current = handler;
89
+ return useRef((...p: Parameters<H>) => {
90
+ if (null == handlerRef.current) return;
91
+ return handlerRef.current(...p);
92
+ }).current;
93
+ }