data-primals-engine 1.3.4 → 1.4.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 (42) hide show
  1. package/README.md +72 -2
  2. package/client/README.md +20 -0
  3. package/client/package-lock.json +712 -147
  4. package/client/package.json +38 -37
  5. package/client/src/App.jsx +9 -10
  6. package/client/src/App.scss +7 -1
  7. package/client/src/Dashboard.jsx +349 -208
  8. package/client/src/DashboardView.jsx +569 -547
  9. package/client/src/DataEditor.jsx +20 -2
  10. package/client/src/DataLayout.jsx +24 -12
  11. package/client/src/DataTable.jsx +807 -760
  12. package/client/src/DataTable.scss +187 -90
  13. package/client/src/Field.jsx +1783 -1656
  14. package/client/src/ModelCreator.jsx +2 -2
  15. package/client/src/ModelCreatorField.jsx +906 -804
  16. package/client/src/ModelList.jsx +2 -2
  17. package/client/src/PackGallery.jsx +391 -290
  18. package/client/src/PackGallery.scss +231 -210
  19. package/client/src/constants.js +16 -4
  20. package/client/src/translations.js +16750 -16392
  21. package/package.json +14 -11
  22. package/src/core.js +9 -0
  23. package/src/defaultModels.js +18 -10
  24. package/src/email.js +2 -1
  25. package/src/gameObject.js +1 -1
  26. package/src/i18n.js +501 -28
  27. package/src/modules/auth-google/index.js +51 -0
  28. package/src/modules/auth-microsoft/index.js +82 -0
  29. package/src/modules/auth-saml/index.js +90 -0
  30. package/src/modules/data/data.core.js +5 -1
  31. package/src/modules/data/data.history.js +489 -489
  32. package/src/modules/data/data.js +86 -12
  33. package/src/modules/data/data.routes.js +1691 -1663
  34. package/src/modules/user.js +19 -0
  35. package/src/modules/workflow.js +2 -12
  36. package/src/providers.js +110 -1
  37. package/src/sso.js +194 -0
  38. package/test/data.integration.test.js +3 -0
  39. package/test/user.test.js +1 -1
  40. package/client/public/demo/26899917-d1ba-4df4-bb33-48d09a8778da.jpg +0 -0
  41. package/client/public/demo/4b9894c7-12cd-466d-8fd3-a2757b09ec96.jpg +0 -0
  42. package/client/public/demo/7ed369ac-a1a2-4b45-b0cd-4fd5bcf5a75a.jpg +0 -0
@@ -1,291 +1,392 @@
1
- import React, { useState } from 'react';
2
- import {useMutation, useQuery, useQueryClient} from 'react-query';
3
- import { Trans, useTranslation } from 'react-i18next';
4
- import {FaBoxOpen, FaChevronLeft, FaDownload, FaPlus, FaStar, FaTag, FaUser} from 'react-icons/fa';
5
- import Button from './Button.jsx';
6
- import { useNotificationContext } from './NotificationProvider.jsx';
7
- import { useModelContext } from './contexts/ModelContext.jsx';
8
-
9
- import './PackGallery.scss';
10
- import {elementsPerPage} from "../../src/constants.js";
11
- import Markdown from "react-markdown";
12
- import {Dialog, DialogProvider} from "./Dialog.jsx";
13
- import {TextField} from "./Field.jsx";
14
-
15
- // --- API Fetching Functions ---
16
- const fetchPacks = async (sortBy, lang) => {
17
- const response = await fetch(`/api/packs?lang=${lang}&sortBy=${sortBy.field}&order=${sortBy.order}`);
18
- if (!response.ok) {
19
- throw new Error('Network response was not ok');
20
- }
21
- return response.json();
22
- };
23
-
24
- const fetchPackDetails = async (packId, lang) => {
25
- if (!packId) return null;
26
- const response = await fetch(`/api/packs/${packId}?lang=${lang}`);
27
- if (!response.ok) {
28
- throw new Error('Failed to fetch pack details');
29
- }
30
- return response.json();
31
- };
32
-
33
- // --- Sub-components ---
34
-
35
- // Carte pour afficher un pack dans la galerie
36
- const PackCard = ({ pack, onSelect }) => {
37
- const { t } = useTranslation();
38
- return (
39
- <div className="pack-card" onClick={() => onSelect(pack._id)}>
40
- <div className="pack-card-header">
41
- <h3><FaBoxOpen /> {pack.name}</h3>
42
- <span className="pack-stars"><FaStar /> {pack.stars || 0}</span>
43
- </div>
44
- <p className="pack-description">{pack.description?.substring(0, 120) || t('packs.noDescription', 'Aucune description.')}... </p>
45
- <div className="pack-card-footer">
46
- <span className="pack-author"><FaUser /> {pack._user}</span>
47
- <div className="pack-tags">
48
- {(pack.tags || []).map(tag => <span key={tag} className="tag"><FaTag /> {tag}</span>)}
49
- </div>
50
- </div>
51
- </div>
52
- );
53
- };
54
-
55
- // Vue détaillée d'un pack
56
- const PackDetail = ({ packId, onBack }) => {
57
- const { t,i18n } = useTranslation();
58
- const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
59
- const { addNotification } = useNotificationContext();
60
- const queryClient = useQueryClient();
61
- const { selectedModel, page, pagedFilters, pagedSort } = useModelContext();
62
- const { data: pack, isLoading, isError } = useQuery(['packDetails', packId], () => fetchPackDetails(packId, lang));
63
-
64
- const { mutate: installPack, isLoading: isInstalling } = useMutation(
65
- installPackMutationFn,
66
- {
67
- onSuccess: (data) => {
68
- addNotification({
69
- status: 'completed',
70
- title: t('datatable.pack.install.success', `Pack '${pack.name}' installé avec succès !`)
71
- });
72
- gtag('event', 'pack install '+pack.name);
73
- queryClient.invalidateQueries('api/models');
74
- queryClient.invalidateQueries(['api/data', selectedModel?.name, 'page', page, elementsPerPage, pagedFilters[selectedModel?.name], pagedSort[selectedModel?.name]]);
75
-
76
- onBack(); // Retourner à la galerie
77
- },
78
- onError: (error) => {
79
- addNotification({
80
- status: 'error',
81
- title: t('datatable.pack.install.error', `Échec de l'installation du pack`),
82
- message: error.message
83
- });
84
- }
85
- }
86
- );
87
-
88
- const handleInstall = async () => {
89
- addNotification({ status: 'info', title: t('packs.install.started', `Installation du pack '${pack.name}'...`) });
90
- installPack({ packId: pack._id, lang });
91
- };
92
-
93
- if (isLoading) return <div className="spinner-loader"></div>;
94
- if (isError) return <p className="error-text">{t('packs.error.details', 'Erreur lors du chargement des détails du pack.')}</p>;
95
- if (!pack) return null;
96
-
97
- const renderModelsList = (models) => {
98
- if (!models || models.length === 0) return t('packs.noModelsIncluded', 'Aucun modèle spécifié.');
99
-
100
- return models.map(model => {
101
- // Si l'élément est un objet, on prend sa propriété 'name', sinon on prend la chaîne de caractères
102
- const modelName = typeof model === 'object' && model !== null ? model.name : model;
103
- return modelName;
104
- }).join(', ');
105
- };
106
-
107
- return (
108
- <div className="pack-detail">
109
- <Button onClick={onBack} className="back-button"><FaChevronLeft /> <Trans i18nKey="btns.back">Retour</Trans></Button>
110
- <div className="pack-detail-header">
111
- <h1>{pack.name}</h1>
112
- <Button onClick={handleInstall} disabled={isInstalling}>
113
- <FaDownload /> {isInstalling ? t('packs.installing', 'Installation...') : t('packs.install', 'Installer')}
114
- </Button>
115
- </div>
116
- <div className="pack-meta">
117
- <span><FaUser /> {pack._user}</span>
118
- <span><FaStar /> {pack.stars || 0}</span>
119
- <span><FaTag /> {(pack.tags || []).join(', ')}</span>
120
- </div>
121
- <div className="pack-content">
122
- <h2><Trans i18nKey="packs.description">Description</Trans></h2>
123
-
124
- <div className="description-content"><Markdown>{pack.description}</Markdown></div>
125
-
126
- <h2><Trans i18nKey="packs.modelsIncluded">Modèles inclus</Trans></h2>
127
- <p>{renderModelsList(pack.models)}</p>
128
-
129
- <h2><Trans i18nKey="packs.dataPreview">Aperçu des données à installer</Trans></h2>
130
- <div className="data-preview">
131
- <pre>{JSON.stringify(pack.data, null, 2)}</pre>
132
- </div>
133
- </div>
134
-
135
-
136
- </div>
137
- );
138
- };
139
-
140
-
141
- // --- NOUVELLE FONCTION POUR LA MUTATION D'INSTALLATION ---
142
- const installPackMutationFn = async ({packId, lang}) => {
143
- const response = await fetch(`/api/packs/${packId}/install?lang=${lang}`, {
144
- method: 'POST',
145
- headers: {
146
- 'Content-Type': 'application/json',
147
- },
148
- });
149
- if (!response.ok) {
150
- const errorData = await response.json();
151
- throw new Error(errorData.error || 'Failed to install pack');
152
- }
153
- return response.json();
154
- };
155
-
156
- // --- Main Gallery Component ---
157
- const PackGallery = () => {
158
- const { t, i18n } = useTranslation();
159
- const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
160
- const { addNotification } = useNotificationContext();
161
-
162
- const [showManualInstallDialog, setShowManualInstallDialog] = useState(false);
163
- const [manualPackJson, setManualPackJson] = useState('');
164
- const [view, setView] = useState('list'); // 'list' ou 'detail'
165
- const [selectedPackId, setSelectedPackId] = useState(null);
166
- const [sortBy, setSortBy] = useState({ field: '_updatedAt', order: -1 });
167
-
168
- const queryClient = useQueryClient()
169
- const { data: packs, isLoading, isError } = useQuery(['packs', sortBy], () => fetchPacks(sortBy, lang));
170
-
171
- const handleSelectPack = (packId) => {
172
- setSelectedPackId(packId);
173
- setView('detail');
174
- };
175
-
176
- const handleManualInstall = async () => {
177
- try {
178
- const packData = JSON.parse(manualPackJson.trim());
179
- addNotification({ status: 'info', title: t('packs.install.started', `Installation du pack personnalisé...`) });
180
-
181
- const response = await fetch('/api/packs/install', {
182
- method: 'POST',
183
- headers: {
184
- 'Content-Type': 'application/json',
185
- },
186
- body: JSON.stringify({ packData, lang }),
187
- });
188
-
189
- if (!response.ok) {
190
- throw new Error(await response.text());
191
- }
192
-
193
- addNotification({
194
- status: 'completed',
195
- title: t('datatable.pack.install.success', 'Pack installé avec succès !')
196
- });
197
- setShowManualInstallDialog(false);
198
- setManualPackJson('');
199
- queryClient.invalidateQueries(['packs', sortBy]); // Rafraîchir la liste
200
-
201
- } catch (error) {
202
- addNotification({
203
- status: 'error',
204
- title: t('datatable.pack.install.error', `Échec de l'installation`),
205
- message: error.message
206
- });
207
- }
208
- };
209
-
210
- const handleBackToList = () => {
211
- setSelectedPackId(null);
212
- setView('list');
213
- };
214
-
215
- const renderContent = () => {
216
- if (view === 'detail') {
217
- return <PackDetail packId={selectedPackId} onBack={handleBackToList} />;
218
- }
219
-
220
- // Vue 'list'
221
- if (isLoading) return <div className="spinner-loader"></div>;
222
- if (isError) return <p className="error-text">{t('packs.error.loading', 'Erreur lors du chargement des packs.')}</p>;
223
- if (!packs || packs.length === 0) return <p>{t('packs.noPacks', 'Aucun pack n\'est disponible pour le moment.')}</p>;
224
-
225
- return (
226
- <>
227
- <div className="gallery-header">
228
- <h1><Trans i18nKey="packs.galleryTitle">Galerie de Packs</Trans></h1>
229
- <div className="header-actions">
230
- <div className="sort-options">
231
- <span><Trans i18nKey="packs.sortBy">Trier par :</Trans></span>
232
- <Button onClick={() => setSortBy({ field: '_updatedAt', order: -1 })} className={sortBy.field === '_updatedAt' ? 'active' : ''}>
233
- <Trans i18nKey="packs.sort.lastUpdated">Derniers ajouts</Trans>
234
- </Button>
235
- <Button onClick={() => setSortBy({ field: 'stars', order: -1 })} className={sortBy.field === 'stars' ? 'active' : ''}>
236
- <Trans i18nKey="packs.sort.mostStarred">Plus populaires</Trans>
237
- </Button>
238
- </div>
239
- <Button
240
- onClick={() => setShowManualInstallDialog(true)}
241
- className="add-pack-button"
242
- >
243
- <FaPlus /> <Trans i18nKey="packs.manualInstall">Importer</Trans>
244
- </Button>
245
- </div>
246
- </div>
247
- {showManualInstallDialog && (
248
- <DialogProvider>
249
- <Dialog
250
- isModal={true}
251
- onClose={() => setShowManualInstallDialog(false)}
252
- title={t('packs.manualInstall.title', 'Installation manuelle de pack')}
253
- >
254
- <div className="manual-install-dialog">
255
- <p>
256
- <Trans i18nKey="packs.manualInstall.instructions">
257
- Collez ici le JSON de configuration du pack que vous souhaitez installer.
258
- </Trans>
259
- </p>
260
- <TextField
261
- multiline={true}
262
- value={manualPackJson}
263
- onChange={(e) => setManualPackJson(e.target.value)}
264
- placeholder={t('packs.manualInstall.placeholder', '{"name": "Mon Pack", "description": "...", "models": [...], "data": [...]}')}
265
- rows={15}
266
- />
267
- <div className="flex actions right">
268
- <Button onClick={() => setShowManualInstallDialog(false)}><Trans i18nKey={"btns.cancel"}>Annuler</Trans></Button>
269
- <Button disabled={!manualPackJson.trim()} className="btn-primary" onClick={() => handleManualInstall()}><Trans i18nKey={"packs.install"}>Installer</Trans></Button>
270
- </div>
271
- </div>
272
- </Dialog>
273
- </DialogProvider>
274
- )}
275
- <div className="pack-list">
276
- {packs.map(pack => (
277
- <PackCard key={pack._id} pack={pack} onSelect={handleSelectPack} />
278
- ))}
279
- </div>
280
- </>
281
- );
282
- };
283
-
284
- return (
285
- <div className="pack-gallery-container">
286
- {renderContent()}
287
- </div>
288
- );
289
- };
290
-
1
+ import React, { useState } from 'react';
2
+ import {useMutation, useQuery, useQueryClient} from 'react-query';
3
+ import { Trans, useTranslation } from 'react-i18next';
4
+ import {FaBoxOpen, FaChevronLeft, FaDownload, FaPlus, FaStar, FaTag, FaUser, FaUserCircle, FaTimes} from 'react-icons/fa';
5
+ import Button from './Button.jsx';
6
+ import { useNotificationContext } from './NotificationProvider.jsx';
7
+ import { useModelContext } from './contexts/ModelContext.jsx';
8
+ import { useAuthContext } from './contexts/AuthContext.jsx';
9
+
10
+ import './PackGallery.scss';
11
+ import {elementsPerPage} from "../../src/constants.js";
12
+ import Markdown from "react-markdown";
13
+ import {Dialog, DialogProvider} from "./Dialog.jsx";
14
+ import {TextField, CheckboxField} from "./Field.jsx";
15
+
16
+ // --- API Fetching Functions ---
17
+ const fetchPacks = async (sortBy, lang, filterByUser = false, user) => {
18
+ const url = `/api/packs?lang=${lang}&sortBy=${sortBy.field}&order=${sortBy.order}${filterByUser ? '&user='+user.username : ''}`;
19
+ const response = await fetch(url);
20
+ if (!response.ok) {
21
+ throw new Error('Network response was not ok');
22
+ }
23
+ return response.json();
24
+ };
25
+
26
+ const fetchPackDetails = async (packId, lang) => {
27
+ if (!packId) return null;
28
+ const response = await fetch(`/api/packs/${packId}?lang=${lang}`);
29
+ if (!response.ok) {
30
+ throw new Error('Failed to fetch pack details');
31
+ }
32
+ return response.json();
33
+ };
34
+
35
+ // --- Sub-components ---
36
+
37
+ // Carte pour afficher un pack dans la galerie
38
+ const PackCard = ({ pack, onSelect }) => {
39
+ const { t } = useTranslation();
40
+ const { me: user } = useAuthContext();
41
+
42
+ return (
43
+ <div className="pack-card" onClick={() => onSelect(pack._id)}>
44
+ <div className="pack-card-header">
45
+ <h3><FaBoxOpen /> {pack.name}</h3>
46
+ <div className="pack-header-right">
47
+ <span className="pack-stars"><FaStar /> {pack.stars || 0}</span>
48
+ {user && pack._user === user.username && (
49
+ <span className="my-pack-badge" title={t('packs.myPack', 'Mon pack')}>
50
+ <FaUserCircle />
51
+ </span>
52
+ )}
53
+ </div>
54
+ </div>
55
+ <p className="pack-description">{pack.description?.substring(0, 120) || t('packs.noDescription', 'Aucune description.')}... </p>
56
+ <div className="pack-card-footer">
57
+ <span className="pack-author"><FaUser /> {pack._user}</span>
58
+ <div className="pack-tags">
59
+ {(pack.tags || []).map(tag => <span key={tag} className="tag"><FaTag /> {tag}</span>)}
60
+ </div>
61
+ </div>
62
+ </div>
63
+ );
64
+ };
65
+
66
+ // Vue détaillée d'un pack
67
+ const PackDetail = ({ packId, onBack }) => {
68
+ const { t,i18n } = useTranslation();
69
+ const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
70
+ const { addNotification } = useNotificationContext();
71
+ const queryClient = useQueryClient();
72
+ const { selectedModel, page, pagedFilters, pagedSort } = useModelContext();
73
+ const { me: user } = useAuthContext();
74
+ const { data: pack, isLoading, isError } = useQuery(['packDetails', packId], () => fetchPackDetails(packId, lang));
75
+
76
+ const { mutate: updatePack, isLoading: isUpdating } = useMutation(
77
+ updatePackMutationFn,
78
+ {
79
+ onSuccess: () => {
80
+ addNotification({ status: 'completed', title: t('packs.update.success', 'Pack mis à jour avec succès !') });
81
+ queryClient.invalidateQueries(['packDetails', packId]);
82
+ queryClient.invalidateQueries('packs');
83
+ },
84
+ onError: (error) => {
85
+ addNotification({ status: 'error', title: t('packs.update.error', 'Échec de la mise à jour du pack'), message: error.message });
86
+ }
87
+ }
88
+ );
89
+
90
+ const { mutate: installPack, isLoading: isInstalling } = useMutation(
91
+ installPackMutationFn,
92
+ {
93
+ onSuccess: (data) => {
94
+ addNotification({
95
+ status: 'completed',
96
+ title: t('datatable.pack.install.success', `Pack '${pack.name}' installé avec succès !`)
97
+ });
98
+ gtag('event', 'pack install '+pack.name);
99
+ queryClient.invalidateQueries('api/models');
100
+ queryClient.invalidateQueries(['api/data', selectedModel?.name, 'page', page, elementsPerPage, pagedFilters[selectedModel?.name], pagedSort[selectedModel?.name]]);
101
+
102
+ onBack();
103
+ },
104
+ onError: (error) => {
105
+ addNotification({
106
+ status: 'error',
107
+ title: t('datatable.pack.install.error', `Échec de l'installation du pack`),
108
+ message: error.message
109
+ });
110
+ }
111
+ }
112
+ );
113
+
114
+ const handleInstall = async () => {
115
+ addNotification({ status: 'info', title: t('packs.install.started', `Installation du pack '${pack.name}'...`) });
116
+ installPack({ packId: pack._id, lang });
117
+ };
118
+
119
+ const handlePublicToggle = (e) => {
120
+ const pr = !e;
121
+ updatePack({ packId: pack._id, updateData: { private: pr } });
122
+ };
123
+
124
+ if (isLoading) return <div className="spinner-loader"></div>;
125
+ if (isError) return <p className="error-text">{t('packs.error.details', 'Erreur lors du chargement des détails du pack.')}</p>;
126
+ if (!pack) return null;
127
+
128
+ const renderModelsList = (models) => {
129
+ if (!models || models.length === 0) return t('packs.noModelsIncluded', 'Aucun modèle spécifié.');
130
+
131
+ return models.map(model => {
132
+ const modelName = typeof model === 'object' && model !== null ? model.name : model;
133
+ return modelName;
134
+ }).join(', ');
135
+ };
136
+
137
+ return (
138
+ <div className="pack-detail">
139
+ <Button onClick={onBack} className="back-button"><FaChevronLeft /> <Trans i18nKey="btns.back">Retour</Trans></Button>
140
+ <div className="pack-detail-header">
141
+ <h1>{pack.name}</h1>
142
+ <div className="pack-detail-actions">
143
+ {user && pack._user === user.username && (
144
+ <div className="owner-actions">
145
+ <span className="my-pack-indicator">
146
+ <FaUserCircle /> <Trans i18nKey="packs.myPack">Mon pack</Trans>
147
+ </span>
148
+ <CheckboxField
149
+ label={t('packs.public', 'Public')}
150
+ checked={!pack.private}
151
+ onChange={handlePublicToggle}
152
+ disabled={isUpdating}
153
+ title={t('packs.public.tooltip', 'Rendre ce pack visible par les autres utilisateurs dans la galerie.')}
154
+ />
155
+ </div>
156
+ )}
157
+ <Button onClick={handleInstall} disabled={isInstalling}>
158
+ <FaDownload /> {isInstalling ? t('packs.installing', 'Installation...') : t('Installer')}
159
+ </Button>
160
+ </div>
161
+ </div>
162
+ <div className="pack-meta">
163
+ <span><FaUser /> {pack._user}</span>
164
+ <span><FaStar /> {pack.stars || 0}</span>
165
+ <span><FaTag /> {(pack.tags || []).join(', ')}</span>
166
+ </div>
167
+ <div className="pack-content">
168
+ <h2><Trans i18nKey="packs.description">Description</Trans></h2>
169
+ <div className="description-content"><Markdown>{pack.description}</Markdown></div>
170
+
171
+ <h2><Trans i18nKey="packs.modelsIncluded">Modèles inclus</Trans></h2>
172
+ <p>{renderModelsList(pack.models)}</p>
173
+
174
+ <h2><Trans i18nKey="packs.dataPreview">Aperçu des données à installer</Trans></h2>
175
+ <div className="data-preview">
176
+ <pre>{JSON.stringify(pack.data, null, 2)}</pre>
177
+ </div>
178
+ </div>
179
+ </div>
180
+ );
181
+ };
182
+
183
+ const installPackMutationFn = async ({packId, lang}) => {
184
+ const response = await fetch(`/api/packs/${packId}/install?lang=${lang}`, {
185
+ method: 'POST',
186
+ headers: {
187
+ 'Content-Type': 'application/json',
188
+ },
189
+ });
190
+ if (!response.ok) {
191
+ const errorData = await response.json();
192
+ throw new Error(errorData.error || 'Failed to install pack');
193
+ }
194
+ return response.json();
195
+ };
196
+
197
+ const updatePackMutationFn = async ({ packId, updateData }) => {
198
+ const response = await fetch(`/api/packs/${packId}`, {
199
+ method: 'PATCH',
200
+ headers: {
201
+ 'Content-Type': 'application/json',
202
+ },
203
+ body: JSON.stringify(updateData),
204
+ });
205
+ if (!response.ok) {
206
+ const errorData = await response.json();
207
+ throw new Error(errorData.error || 'Failed to update pack');
208
+ }
209
+ return response.json();
210
+ };
211
+
212
+ // --- Main Gallery Component ---
213
+ const PackGallery = () => {
214
+ const { t, i18n } = useTranslation();
215
+ const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
216
+ const { addNotification } = useNotificationContext();
217
+ const { me: user } = useAuthContext();
218
+
219
+ const [showManualInstallDialog, setShowManualInstallDialog] = useState(false);
220
+ const [manualPackJson, setManualPackJson] = useState('');
221
+ const [view, setView] = useState('list');
222
+ const [selectedPackId, setSelectedPackId] = useState(null);
223
+ const [sortBy, setSortBy] = useState({ field: '_updatedAt', order: -1 });
224
+ const [showOnlyMyPacks, setShowOnlyMyPacks] = useState(false);
225
+
226
+ const queryClient = useQueryClient()
227
+ const { data: packs, isLoading, isError } = useQuery(
228
+ ['packs', sortBy, showOnlyMyPacks],
229
+ () => fetchPacks(sortBy, lang, showOnlyMyPacks, user)
230
+ );
231
+
232
+ const handleSelectPack = (packId) => {
233
+ setSelectedPackId(packId);
234
+ setView('detail');
235
+ };
236
+
237
+ const handleManualInstall = async () => {
238
+ try {
239
+ const packData = JSON.parse(manualPackJson.trim());
240
+ addNotification({ status: 'info', title: t('packs.install.started', `Installation du pack personnalisé...`) });
241
+
242
+ const response = await fetch('/api/packs/install', {
243
+ method: 'POST',
244
+ headers: {
245
+ 'Content-Type': 'application/json',
246
+ },
247
+ body: JSON.stringify({ packData, lang }),
248
+ });
249
+
250
+ if (!response.ok) {
251
+ throw new Error(await response.text());
252
+ }
253
+
254
+ addNotification({
255
+ status: 'completed',
256
+ title: t('datatable.pack.install.success', 'Pack installé avec succès !')
257
+ });
258
+ setShowManualInstallDialog(false);
259
+ setManualPackJson('');
260
+ queryClient.invalidateQueries(['packs', sortBy, showOnlyMyPacks]);
261
+
262
+ } catch (error) {
263
+ addNotification({
264
+ status: 'error',
265
+ title: t('datatable.pack.install.error', `Échec de l'installation`),
266
+ message: error.message
267
+ });
268
+ }
269
+ };
270
+
271
+ const handleBackToList = () => {
272
+ setSelectedPackId(null);
273
+ setView('list');
274
+ };
275
+
276
+ const toggleMyPacksFilter = () => {
277
+ setShowOnlyMyPacks(!showOnlyMyPacks);
278
+ };
279
+
280
+ const clearMyPacksFilter = () => {
281
+ setShowOnlyMyPacks(false);
282
+ };
283
+
284
+ const renderContent = () => {
285
+ if (view === 'detail') {
286
+ return <PackDetail packId={selectedPackId} onBack={handleBackToList} />;
287
+ }
288
+
289
+ if (isLoading) return <div className="spinner-loader"></div>;
290
+ if (isError) return <p className="error-text">{t('packs.error.loading', 'Erreur lors du chargement des packs.')}</p>;
291
+
292
+ return (
293
+ <>
294
+ <div className="gallery-header">
295
+ <h1>
296
+ {showOnlyMyPacks
297
+ ? <Trans i18nKey="packs.myPacksTitle">Mes Packs</Trans>
298
+ : <Trans i18nKey="packs.galleryTitle">Galerie de Packs</Trans>
299
+ }
300
+ </h1>
301
+ <div className="header-actions">
302
+ <div className="sort-options">
303
+ <span><Trans i18nKey="packs.sortBy">Trier par :</Trans></span>
304
+ <Button onClick={() => setSortBy({ field: '_updatedAt', order: -1 })} className={sortBy.field === '_updatedAt' ? 'active' : ''}>
305
+ <Trans i18nKey="packs.sort.lastUpdated">Derniers ajouts</Trans>
306
+ </Button>
307
+ <Button onClick={() => setSortBy({ field: 'stars', order: -1 })} className={sortBy.field === 'stars' ? 'active' : ''}>
308
+ <Trans i18nKey="packs.sort.mostStarred">Plus populaires</Trans>
309
+ </Button>
310
+ </div>
311
+ <div className="filter-actions">
312
+ {showOnlyMyPacks && (
313
+ <Button onClick={clearMyPacksFilter} className="clear-filter-btn">
314
+ <FaTimes /> <Trans i18nKey="packs.clearFilter">Voir tous les packs</Trans>
315
+ </Button>
316
+ )}
317
+ {user && !showOnlyMyPacks && (
318
+ <Button
319
+ onClick={toggleMyPacksFilter}
320
+ className="my-packs-btn"
321
+ >
322
+ <FaUserCircle /> <Trans i18nKey="packs.myPacks">Mes packs</Trans>
323
+ </Button>
324
+ )}
325
+ <Button
326
+ onClick={() => setShowManualInstallDialog(true)}
327
+ className="add-pack-button"
328
+ >
329
+ <FaPlus /> <Trans i18nKey="packs.manualInstall">Importer</Trans>
330
+ </Button>
331
+ </div>
332
+ </div>
333
+ </div>
334
+
335
+ {showOnlyMyPacks && (
336
+ <div className="filter-indicator">
337
+ <FaUserCircle />
338
+ <Trans i18nKey="packs.filteringMyPacks">Affichage de vos packs uniquement</Trans>
339
+ </div>
340
+ )}
341
+
342
+ {showManualInstallDialog && (
343
+ <DialogProvider>
344
+ <Dialog
345
+ isModal={true}
346
+ onClose={() => setShowManualInstallDialog(false)}
347
+ title={t('packs.manualInstall.title', 'Installation manuelle de pack')}
348
+ >
349
+ <div className="manual-install-dialog">
350
+ <p>
351
+ <Trans i18nKey="packs.manualInstall.instructions">
352
+ Collez ici le JSON de configuration du pack que vous souhaitez installer.
353
+ </Trans>
354
+ </p>
355
+ <TextField
356
+ multiline={true}
357
+ value={manualPackJson}
358
+ onChange={(e) => setManualPackJson(e.target.value)}
359
+ placeholder={t('packs.manualInstall.placeholder', '{"name": "Mon Pack", "description": "...", "models": [...], "data": [...]}')}
360
+ rows={15}
361
+ />
362
+ <div className="flex actions right">
363
+ <Button onClick={() => setShowManualInstallDialog(false)}><Trans i18nKey={"btns.cancel"}>Annuler</Trans></Button>
364
+ <Button disabled={!manualPackJson.trim()} className="btn-primary" onClick={() => handleManualInstall()}><Trans i18nKey={"packs.install"}>Installer</Trans></Button>
365
+ </div>
366
+ </div>
367
+ </Dialog>
368
+ </DialogProvider>
369
+ )}
370
+
371
+ {(!packs || packs.length === 0) ? (
372
+ showOnlyMyPacks
373
+ ? <p className="no-packs-message">{t('packs.noMyPacks', 'Vous n\'avez créé aucun pack.')}</p>
374
+ : <p className="no-packs-message">{t('packs.noPacks', 'Aucun pack n\'est disponible pour le moment.')}</p>
375
+ ) : (
376
+ <div className="pack-list">
377
+ {packs.map(pack => (
378
+ <PackCard key={pack._id} pack={pack} onSelect={handleSelectPack} />
379
+ ))}
380
+ </div>
381
+ )}
382
+ </>
383
+ );
384
+ };
385
+ return (
386
+ <div className="pack-gallery-container">
387
+ {renderContent()}
388
+ </div>
389
+ );
390
+ };
391
+
291
392
  export default PackGallery;