-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
409 lines (339 loc) · 11.6 KB
/
script.js
File metadata and controls
409 lines (339 loc) · 11.6 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
/**
* Configuration object for interface generation
*/
const CONFIG = {
shouldUnwrapData: false,
indentSize: 2
};
/**
* Cache pour éviter la régénération d'interfaces identiques
*/
const interfaceCache = new Map();
/**
* Détermine le type TypeScript approprié pour une valeur JavaScript
* @param {*} value - La valeur à analyser
* @param {string} interfaceName - Nom de l'interface parente
* @param {string} key - Clé de la propriété
* @param {string} indent - Indentation courante
* @returns {string} Le type TypeScript correspondant
*/
function getTypeScriptType(value, interfaceName, key, indent = '') {
if (value === null) return 'null';
if (value === undefined) return 'undefined';
const jsType = typeof value;
switch (jsType) {
case 'string':
case 'number':
case 'boolean':
return jsType;
case 'object':
if (Array.isArray(value)) {
return getArrayType(value, interfaceName, key, indent);
}
if (value instanceof Date) {
return 'Date';
}
return getObjectType(value, interfaceName, key, indent);
default:
return 'unknown';
}
}
/**
* Détermine le type d'un tableau
* @param {Array} array - Le tableau à analyser
* @param {string} interfaceName - Nom de l'interface parente
* @param {string} key - Clé de la propriété
* @param {string} indent - Indentation courante
* @returns {string} Le type TypeScript du tableau
*/
function getArrayType(array, interfaceName, key, indent) {
if (array.length === 0) return 'unknown[]';
const firstElement = array[0];
const elementType = getTypeScriptType(firstElement, interfaceName, key, indent);
// Vérifier si tous les éléments ont le même type
const allSameType = array.every(item =>
getTypeScriptType(item, interfaceName, key, indent) === elementType
);
return allSameType ? `${elementType}[]` : 'unknown[]';
}
/**
* Génère le type d'un objet
* @param {Object} obj - L'objet à analyser
* @param {string} interfaceName - Nom de l'interface parente
* @param {string} key - Clé de la propriété
* @param {string} indent - Indentation courante
* @returns {string} Le type TypeScript de l'objet
*/
function getObjectType(obj, interfaceName, key, indent) {
const cacheKey = JSON.stringify(obj);
if (interfaceCache.has(cacheKey)) {
return interfaceCache.get(cacheKey);
}
const subIndent = indent + ' '.repeat(CONFIG.indentSize);
let typeStr = '{\n';
Object.entries(obj).forEach(([objKey, objValue]) => {
const propType = getTypeScriptType(objValue, interfaceName, objKey, subIndent);
typeStr += `${subIndent}${objKey}: ${propType};\n`;
});
typeStr += `${indent}}`;
interfaceCache.set(cacheKey, typeStr);
return typeStr;
}
/**
* Préprocesse les données JSON selon la configuration
* @param {*} data - Les données à préprocesser
* @returns {*} Les données préprocessées
*/
function preprocessData(data) {
if (!CONFIG.shouldUnwrapData) return data;
let processedData = data;
// Unwrap data property if it exists
if (processedData && typeof processedData === 'object' && processedData.hasOwnProperty('data')) {
processedData = processedData.data;
}
// Get first element if it's an array
if (Array.isArray(processedData) && processedData.length > 0) {
processedData = processedData[0];
}
return processedData;
}
/**
* Convertit un objet JSON en interface TypeScript
* @param {Object} jsonObj - L'objet JSON à convertir
* @param {string} interfaceName - Le nom de l'interface
* @param {string} indent - L'indentation (usage interne)
* @returns {string} L'interface TypeScript générée
*/
function jsonToInterface(jsonObj, interfaceName, indent = '') {
if (!jsonObj || typeof jsonObj !== 'object') {
throw new Error('L\'objet JSON fourni n\'est pas valide');
}
if (!interfaceName || typeof interfaceName !== 'string') {
throw new Error('Le nom de l\'interface doit être une chaîne non vide');
}
// Préprocesser les données
const processedData = preprocessData(jsonObj);
// Vider le cache pour chaque nouvelle génération d'interface
interfaceCache.clear();
let interfaceStr = `interface ${interfaceName} {\n`;
Object.entries(processedData).forEach(([key, value]) => {
const type = getTypeScriptType(value, interfaceName, key, indent + ' '.repeat(CONFIG.indentSize));
interfaceStr += `${indent} ${key}: ${type};\n`;
});
interfaceStr += `${indent}}`;
return interfaceStr;
}
/**
* Formate un objet JSON de manière lisible
* @param {*} json - L'objet à formater
* @returns {string} Le JSON formaté
*/
function formatJSON(json) {
try {
if (typeof json === "string") {
json = JSON.parse(json);
}
return JSON.stringify(json, null, 2);
} catch (error) {
console.error('Erreur lors du formatage JSON:', error);
return 'Erreur: JSON invalide';
}
}
/**
* Affiche un message toast à l'utilisateur
* @param {string} text - Le texte à afficher
* @param {string} type - Le type de toast ('success', 'error', 'info')
*/
function toast(text, type = 'info') {
const toastElement = document.querySelector('.toast');
if (!toastElement) {
console.warn('Élément toast non trouvé');
return;
}
toastElement.textContent = text;
toastElement.classList.add('show');
// Définir la couleur selon le type
const colors = {
success: '#28a745',
error: '#dc3545',
info: '#17a2b8'
};
toastElement.style.backgroundColor = colors[type] || colors.info;
setTimeout(() => {
toastElement.classList.remove('show');
}, 3000);
}
/**
* Configure la copie dans le presse-papiers pour un élément
* @param {string} elementSelector - Sélecteur de l'élément
* @param {string} text - Texte à copier
*/
function copyToClipboard(elementSelector, text) {
const element = document.querySelector(elementSelector);
if (!element) {
console.warn(`Élément ${elementSelector} non trouvé`);
return;
}
// Supprimer les anciens listeners pour éviter les doublons
const newElement = element.cloneNode(true);
element.parentNode.replaceChild(newElement, element);
newElement.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(text);
toast('Copié !', 'success');
} catch (error) {
console.error('Erreur lors de la copie:', error);
toast('Erreur lors de la copie', 'error');
}
});
}
/**
* Initialise les interactions SaaS
*/
function initializeSaaSFeatures() {
// Smooth scroll pour les liens d'ancrage
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
// Animation de parallaxe simple pour les cartes de fonctionnalités
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.opacity = '1';
entry.target.style.transform = 'translateY(0)';
}
});
}, observerOptions);
// Observer les cartes de fonctionnalités
document.querySelectorAll('.feature-card').forEach(card => {
card.style.opacity = '0';
card.style.transform = 'translateY(20px)';
card.style.transition = 'opacity 0.6s ease-out, transform 0.6s ease-out';
observer.observe(card);
});
// Bouton CTA du header
const ctaButton = document.querySelector('.cta-button');
if (ctaButton) {
ctaButton.addEventListener('click', () => {
const targetForm = document.querySelector('#myForm');
if (targetForm) {
targetForm.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
});
}
}
/**
* Initialise l'application
*/
function initializeApp() {
const form = document.querySelector("#myForm");
const switchInput = document.querySelector('.switch input[type="checkbox"]');
if (!form) {
console.error('Formulaire non trouvé');
return;
}
// Initialiser les fonctionnalités SaaS
initializeSaaSFeatures();
// Configuration du switch pour unwrap data
if (switchInput) {
switchInput.addEventListener('change', function () {
CONFIG.shouldUnwrapData = this.checked;
});
}
// Gestionnaire de soumission du formulaire
form.addEventListener("submit", async function (event) {
event.preventDefault();
const urlInput = document.querySelector("#url");
const interfaceNameInput = document.querySelector('#nameInterface');
const buttonText = document.querySelector('.button-text');
const buttonLoader = document.querySelector('.button-loader');
const submitButton = event.target.querySelector('button[type="submit"]');
if (!urlInput || !interfaceNameInput) {
toast('Éléments du formulaire manquants', 'error');
return;
}
const urlValue = urlInput.value.trim();
const interfaceName = interfaceNameInput.value.trim() || 'GeneratedInterface';
if (!urlValue) {
toast('Veuillez entrer une URL', 'error');
return;
}
// Activer l'état de chargement
if (submitButton) {
submitButton.disabled = true;
submitButton.classList.add('loading');
}
if (buttonText) buttonText.style.display = 'none';
if (buttonLoader) buttonLoader.style.display = 'inline';
try {
// Validation basique de l'URL
new URL(urlValue);
const response = await fetch(urlValue);
if (!response.ok) {
throw new Error(`Erreur HTTP: ${response.status}`);
}
const data = await response.json();
// Afficher le JSON formaté avec animation
const fetchElement = document.querySelector("#fetch");
if (fetchElement) {
fetchElement.textContent = formatJSON(data);
hljs.highlightBlock(fetchElement);
fetchElement.parentElement.classList.add('animate-in');
}
// Générer l'interface TypeScript avec animation
const interfaceStr = jsonToInterface(data, interfaceName);
const resultElement = document.querySelector("#result");
if (resultElement) {
resultElement.textContent = interfaceStr;
hljs.highlightBlock(resultElement);
resultElement.parentElement.classList.add('animate-in');
}
// Configurer la copie
copyToClipboard('.btn-copy', interfaceStr);
toast('Interface générée avec succès !', 'success');
} catch (error) {
console.error('Erreur:', error);
if (error instanceof TypeError && error.message.includes('URL')) {
toast('URL invalide', 'error');
} else if (error.message.includes('JSON')) {
toast('Réponse JSON invalide', 'error');
} else {
toast('Erreur lors de la récupération des données', 'error');
}
} finally {
// Désactiver l'état de chargement
if (submitButton) {
submitButton.disabled = false;
submitButton.classList.remove('loading');
}
if (buttonText) buttonText.style.display = 'inline';
if (buttonLoader) buttonLoader.style.display = 'none';
}
});
}
// Initialiser l'application quand le DOM est chargé
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeApp);
} else {
initializeApp();
}
// Appliquer highlight.js au contenu initial
document.addEventListener('DOMContentLoaded', function() {
hljs.highlightAll();
});