This repository was archived by the owner on Feb 23, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer.js
More file actions
2486 lines (2185 loc) · 94.6 KB
/
renderer.js
File metadata and controls
2486 lines (2185 loc) · 94.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let config = {
spaces: [{ id: 'default', name: 'Général', projects: [] }],
activeSpaceId: 'default',
settings: {
githubToken: '',
gitlabToken: '',
theme: null,
language: 'fr',
globalTags: [
{ id: '1', name: 'En cours', color: '#38bdf8' },
{ id: '2', name: 'Terminé', color: '#10b981' }
],
personalization: {
appName: 'CODEPILOT',
accentColor: '#8b5cf6',
fontFamily: "'Outfit', sans-serif",
glassBlur: 10,
borderRadius: 12,
cardSize: 280,
animationLevel: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
sidebarOpacity: 80,
bgGlow: true,
compactMode: false,
autoStart: false,
foregroundStart: true,
trayMode: true,
performanceMode: false
}
}
};
let editingProjectId = null;
let currentDetailProject = null;
let selectedProjectTags = []; // Temporary storage for modal
let activeFilters = {
tags: [],
frameworks: [],
statuses: []
};
let currentRenderId = 0;
let contextMenuTarget = null;
let timeTrackerInterval = null;
const STATUS_OPTIONS = [
{ id: 'idea', color: '#a855f7', labelKey: 'status_idea' },
{ id: 'active', color: '#22c55e', labelKey: 'status_active' },
{ id: 'paused', color: '#f59e0b', labelKey: 'status_paused' },
{ id: 'done', color: '#14b8a6', labelKey: 'status_done' }
];
const PRIORITY_OPTIONS = [
{ id: 'low', color: '#38bdf8', labelKey: 'priority_low' },
{ id: 'normal', color: '#94a3b8', labelKey: 'priority_normal' },
{ id: 'high', color: '#f59e0b', labelKey: 'priority_high' },
{ id: 'urgent', color: '#ef4444', labelKey: 'priority_urgent' }
];
const translations = {
fr: {
workspaces: "Espaces",
all_projects: "Tous les projets",
my_projects: "Mes Projets",
quick_search: "Recherche rapide (Ctrl+K)...",
new_project: "+ Nouveau Projet",
new_space: "Nouvel Espace",
settings: "Configuration",
language: "Langue",
appearance: "Thème & Apparence",
tokens: "Jetons & Accès",
interface: "Interface & Nom",
labels: "Étiquettes",
save: "Sauvegarder",
cancel: "Annuler",
close: "Fermer",
reset: "Réinitialiser",
load: "Charger",
export: "Exporter",
app_name: "Nom de l'application",
font: "Police principale",
card_size: "Taille des cartes",
animations: "Animations",
sidebar_opacity: "Opacité Sidebar",
blur: "Flou",
radius: "Arrondi",
glow: "Lueur",
compact: "Mode Compact",
auto_start: "Lancement auto",
foreground: "Affichage actif",
background: "Réduire en arrière-plan",
glow: "Lueur néon",
performance: "Mode Performance",
general: "Général",
appearance_title: "Apparence",
system: "Système",
delete_proj_confirm: "Supprimer ce projet ?",
delete_space_confirm: "Supprimer cet espace et tous ses projets ?",
no_projects: "Prêt à coder ?",
add_first: "Ajoute ton premier projet pour commencer.",
frameworks: "Frameworks",
tags: "Étiquettes",
clear: "Effacer",
toast_save: "Configuration sauvegardée",
v_vscode: "Ouvrir VSCode",
v_terminal: "Terminal",
v_folder: "Dossier",
v_settings: "Réglages",
v_release: "Release",
v_repo: "Repo",
v_git_gui: "Git GUI",
v_roadmap: "Roadmap",
v_scripts: "Scripts npm",
v_notes: "Notes & Mémo",
v_scheduled: "Prévu le",
v_finished: "Terminé le",
v_upcoming: "À venir",
v_done: "Terminé",
v_add_step: "Ajouter une étape",
status_label: "Statut",
priority_label: "Priorité",
status_idea: "Idée",
status_active: "Actif",
status_paused: "En pause",
status_done: "Terminé",
priority_low: "Faible",
priority_normal: "Normal",
priority_high: "Élevé",
priority_urgent: "Urgent",
tasks_title: "Tâches",
tasks_add: "Ajouter",
tasks_empty: "Aucune tâche pour l'instant.",
links_title: "Liens rapides",
links_add: "Ajouter",
links_empty: "Aucun lien ajouté.",
time_title: "Time Tracker",
time_start: "Démarrer",
time_stop: "Stop",
time_reset: "Réinitialiser",
stats_progress: "Progression",
stats_overdue: "En retard",
stats_last_opened: "Dernière ouverture",
stats_time: "Temps",
stats_never: "Jamais",
forced_update_title: "Mise à jour obligatoire",
forced_update_desc: "Vous êtes sur une version obsolète de CodePilot. Pour profiter des dernières fonctionnalités et pour des raisons de sécurité, vous devez mettre à jour CodePilot avant de continuer.",
update_btn: "Mettre à jour maintenant"
},
en: {
workspaces: "Workspaces",
all_projects: "All Projects",
my_projects: "My Projects",
quick_search: "Quick search (Ctrl+K)...",
new_project: "+ New Project",
new_space: "New Space",
settings: "Settings",
language: "Language",
appearance: "Theme & Appearance",
tokens: "Tokens & Access",
interface: "Interface & Name",
labels: "Labels",
save: "Save",
cancel: "Cancel",
close: "Close",
reset: "Reset",
load: "Load",
export: "Export",
app_name: "Application Name",
font: "Primary Font",
card_size: "Card Size",
animations: "Animations",
sidebar_opacity: "Sidebar Opacity",
blur: "Blur",
radius: "Radius",
glow: "Glow",
compact: "Compact Mode",
auto_start: "Auto Launch",
foreground: "Active Display",
background: "Minimize to Tray",
glow: "Neon Glow",
performance: "Performance Mode",
general: "General",
appearance_title: "Appearance",
system: "System",
delete_proj_confirm: "Delete this project?",
delete_space_confirm: "Delete this workspace and all its projects?",
no_projects: "Ready to code?",
add_first: "Add your first project to get started.",
frameworks: "Frameworks",
tags: "Tags",
clear: "Clear",
toast_save: "Settings saved",
v_vscode: "Open VSCode",
v_terminal: "Terminal",
v_folder: "Folder",
v_settings: "Settings",
v_release: "Release",
v_repo: "Repo",
v_git_gui: "Git GUI",
v_roadmap: "Roadmap",
v_scripts: "NPM Scripts",
v_notes: "Notes & Memo",
v_scheduled: "Scheduled on",
v_finished: "Finished on",
v_upcoming: "Upcoming",
v_done: "Done",
v_add_step: "Add a step",
status_label: "Status",
priority_label: "Priority",
status_idea: "Idea",
status_active: "Active",
status_paused: "Paused",
status_done: "Done",
priority_low: "Low",
priority_normal: "Normal",
priority_high: "High",
priority_urgent: "Urgent",
tasks_title: "Tasks",
tasks_add: "Add",
tasks_empty: "No tasks yet.",
links_title: "Quick links",
links_add: "Add",
links_empty: "No links yet.",
time_title: "Time Tracker",
time_start: "Start",
time_stop: "Stop",
time_reset: "Reset",
stats_progress: "Progress",
stats_overdue: "Overdue",
stats_last_opened: "Last opened",
stats_time: "Time",
stats_never: "Never",
forced_update_title: "Mandatory Update",
forced_update_desc: "You are using an obsolete version of CodePilot. To enjoy the latest features and for security reasons, you must update CodePilot before continuing.",
update_btn: "Update Now"
}
};
let APP_VERSION = '0.0.0';
function truncatePath(path) {
if (!path) return '';
const parts = path.split(/[\\/]/);
if (parts.length <= 3) return path;
return parts[0] + '/.../' + parts.slice(-2).join('/');
}
function ensureProjectDefaults(project) {
if (!project.status) project.status = 'active';
if (!project.priority) project.priority = 'normal';
if (!Array.isArray(project.tasks)) project.tasks = [];
if (!Array.isArray(project.links)) project.links = [];
if (!project.timeTracking) project.timeTracking = { totalMs: 0, isRunning: false, startedAt: null };
if (!project.createdAt) project.createdAt = Date.now();
if (project.lastOpenedAt === undefined) project.lastOpenedAt = null;
if (project.lastActivityAt === undefined) project.lastActivityAt = null;
}
function normalizeConfig() {
if (!config.spaces) return;
config.spaces.forEach(space => {
if (!Array.isArray(space.projects)) space.projects = [];
space.projects.forEach(project => ensureProjectDefaults(project));
});
}
function getStatusMeta(id) {
return STATUS_OPTIONS.find(status => status.id === id) || STATUS_OPTIONS[1];
}
function getPriorityMeta(id) {
return PRIORITY_OPTIONS.find(priority => priority.id === id) || PRIORITY_OPTIONS[1];
}
function getStatusLabel(id) {
const meta = getStatusMeta(id);
return t(meta.labelKey);
}
function getPriorityLabel(id) {
const meta = getPriorityMeta(id);
return t(meta.labelKey);
}
function getTaskCounts(project) {
const tasks = project.tasks || [];
const total = tasks.length;
const done = tasks.filter(task => task.done).length;
return { total, done };
}
function getOverdueTasksCount(project) {
const now = new Date();
return (project.tasks || []).filter(task => {
if (!task.dueDate || task.done) return false;
const due = new Date(`${task.dueDate}T23:59:59`);
return due < now;
}).length;
}
function getOverdueUpdatesCount(project) {
const now = new Date();
return (project.updates || []).filter(update => {
if (update.status === 'finished') return false;
if (!update.scheduledDate) return false;
return new Date(update.scheduledDate) < now;
}).length;
}
function getTrackedMs(project) {
const tracking = project.timeTracking || { totalMs: 0, isRunning: false, startedAt: null };
if (tracking.isRunning && tracking.startedAt) {
return tracking.totalMs + (Date.now() - tracking.startedAt);
}
return tracking.totalMs || 0;
}
function formatDuration(ms) {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}
function formatRelativeTime(timestamp) {
if (!timestamp) return t('stats_never');
const delta = Date.now() - timestamp;
const seconds = Math.floor(delta / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h`;
const days = Math.floor(hours / 24);
return `${days}d`;
}
function formatDateShort(dateValue) {
if (!dateValue) return '';
const date = new Date(dateValue);
if (Number.isNaN(date.getTime())) return dateValue;
return date.toLocaleDateString(config.settings.language || 'fr', { day: '2-digit', month: 'short' });
}
function touchProjectActivity(project) {
if (!project) return;
project.lastActivityAt = Date.now();
save();
renderDetailStats();
renderProjects();
}
// DOM Elements
const spacesList = document.getElementById('spaces-list');
const projectsGrid = document.getElementById('projects-grid');
const currentSpaceName = document.getElementById('current-space-name');
const projectsCount = document.getElementById('projects-count');
const emptyState = document.getElementById('empty-state');
const projectSearch = document.getElementById('project-search');
// Modals
const spaceModal = document.getElementById('space-modal');
const projectModal = document.getElementById('project-modal');
const detailModal = document.getElementById('project-detail-modal');
const updateModal = document.getElementById('update-modal');
const releaseModal = document.getElementById('release-modal');
const settingsModal = document.getElementById('settings-modal');
const gitModal = document.getElementById('git-modal');
// Buttons
const addSpaceBtn = document.getElementById('add-space-btn');
const addProjectBtn = document.getElementById('add-project-btn');
const addProjectUpdateBtn = document.getElementById('add-project-update-btn');
const showSettingsBtn = document.getElementById('show-settings-btn');
const createReleaseBtn = document.getElementById('detail-create-release');
// Detail Elements
const detailName = document.getElementById('detail-name');
const detailPath = document.getElementById('detail-path');
const detailBadges = document.getElementById('detail-badges');
const detailNotes = document.getElementById('detail-notes');
const detailScriptsList = document.getElementById('detail-scripts-list');
const detailUpdatesList = document.getElementById('detail-updates-list');
const detailOpenEditorText = document.getElementById('detail-open-editor-text');
// Initialize
async function init() {
// 1. Fetch Basic Info
APP_VERSION = await window.electronAPI.getAppVersion();
const versionDisplay = document.getElementById('app-version-display');
if (versionDisplay) versionDisplay.textContent = `v${APP_VERSION}`;
let savedConfig = null;
try {
savedConfig = await window.electronAPI.getConfig();
} catch (e) {
console.error("Renderer: Failed to fetch config:", e);
}
if (savedConfig) {
config = savedConfig;
}
// 2. Default structure safety
if (!config.spaces || config.spaces.length === 0) config.spaces = [{ id: 'default', name: 'Général', projects: [] }];
if (!config.activeSpaceId) config.activeSpaceId = config.spaces[0].id;
if (!config.settings) config.settings = {};
if (!config.settings.personalization) config.settings.personalization = {};
if (!config.settings.globalTags) {
config.settings.globalTags = [
{ id: '1', name: 'En cours', color: '#38bdf8' },
{ id: '2', name: 'Terminé', color: '#10b981' }
];
}
normalizeConfig();
save();
// 3. Apply Environment
if (config.settings.theme) applyTheme(config.settings.theme);
applyPersonalization();
applyLanguage();
setupEventListeners();
// 4. Initial Render
renderSpaces();
renderProjects();
// 5. Background tasks
checkForUpdates();
// Global Shortcuts
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
const searchInput = document.getElementById('project-search');
if (searchInput) searchInput.focus();
}
});
}
function applyPersonalization() {
const p = config.settings.personalization || {};
const root = document.documentElement;
// Apply values to CSS variables
if (p.accentColor) {
root.style.setProperty('--primary', p.accentColor);
// Sync glow with accent color (mix with black to keep it subtle and dark)
root.style.setProperty('--bg-lighting', `radial-gradient(circle at 50% 0%, color-mix(in srgb, ${p.accentColor}, black 60%), transparent 75%)`);
}
if (p.fontFamily) root.style.setProperty('--font-main', p.fontFamily);
if (p.glassBlur !== undefined) root.style.setProperty('--glass-blur', `${p.glassBlur}px`);
if (p.borderRadius !== undefined) root.style.setProperty('--radius', `${p.borderRadius}px`);
if (p.cardSize !== undefined) root.style.setProperty('--card-width', `${p.cardSize}px`);
if (p.animationLevel) root.style.setProperty('--anim-speed', p.animationLevel);
if (p.sidebarOpacity !== undefined) root.style.setProperty('--sidebar-opacity', p.sidebarOpacity / 100);
// Apply classes to body
document.body.classList.toggle('compact', !!p.compactMode);
document.body.classList.toggle('no-glow', !p.bgGlow);
// Apply App Name
const logo = document.querySelector('.logo');
if (logo) logo.textContent = p.appName || 'CODEPILOT';
document.title = p.appName || 'CodePilot';
// Apply Win Settings
if (p.autoStart !== undefined) window.electronAPI.setLaunchAtStartup(p.autoStart);
if (p.foregroundStart) {
window.electronAPI.setWindowState({ focus: true });
}
if (p.trayMode !== undefined) window.electronAPI.setTrayMode(p.trayMode);
// Performance Mode logic
document.body.classList.toggle('performance-mode', !!p.performanceMode);
if (!!p.performanceMode) {
root.style.setProperty('--glass-blur', '0px');
root.style.setProperty('--anim-speed', '0s');
document.body.classList.add('performance-mode');
} else {
document.body.classList.remove('performance-mode');
}
}
async function checkForUpdates(manual = false) {
if (config.settings.personalization && config.settings.personalization.performanceMode && !manual) return;
const result = await window.electronAPI.checkUpdates();
if (result.success) {
const latest = result.version;
const current = APP_VERSION;
const latestParts = latest.split('.').map(Number);
const currentParts = current.split('.').map(Number);
// Forced update if major or minor is higher
const isForced = latestParts[0] > currentParts[0] || latestParts[1] > currentParts[1];
if (isForced) {
const forcedModal = document.getElementById('forced-update-modal');
if (forcedModal) {
forcedModal.classList.remove('hidden');
document.getElementById('forced-update-btn').onclick = () => startUpdate();
}
return; // Block execution
}
let isNewer = false;
for (let i = 0; i < 3; i++) {
if (latestParts[i] > currentParts[i]) {
isNewer = true;
break;
} else if (latestParts[i] < currentParts[i]) {
break;
}
}
if (isNewer && !manual) {
showToast("Mise à jour disponible", `La version ${latest} est disponible ! Cliquez pour l'installer.`, () => {
startUpdate();
});
} else if (manual) {
if (isNewer) {
if (confirm(`Une nouvelle version (${latest}) est disponible. Voulez-vous l'installer maintenant ? L'application redémarrera.`)) {
startUpdate();
}
} else {
showToast("À jour", "Vous utilisez déjà la dernière version.");
}
}
} else if (manual) {
alert("Erreur lors de la vérification des mises à jour.");
}
}
async function startUpdate() {
showToast("Mise à jour", "Téléchargement des fichiers en cours...");
const res = await window.electronAPI.downloadUpdate();
if (!res.success) {
alert("La mise à jour a échoué : " + res.error);
}
}
function applyTheme(theme) {
if (!theme) return;
const root = document.documentElement;
// Apply colors (existing functionality)
if (theme.colors) {
Object.entries(theme.colors).forEach(([prop, value]) => {
root.style.setProperty(prop, value);
});
}
// Apply typography
if (theme.typography) {
Object.entries(theme.typography).forEach(([prop, value]) => {
root.style.setProperty(prop, value);
});
}
// Apply dimensions
if (theme.dimensions) {
Object.entries(theme.dimensions).forEach(([prop, value]) => {
root.style.setProperty(prop, value);
});
}
// Apply effects
if (theme.effects) {
Object.entries(theme.effects).forEach(([prop, value]) => {
root.style.setProperty(prop, value);
});
}
// Apply interface settings
if (theme.interface) {
const iface = theme.interface;
// App name
if (iface.appName) {
const logo = document.querySelector('.logo');
if (logo) logo.textContent = iface.appName;
document.title = iface.appName;
}
// Background glow
if (iface.bgGlow !== undefined) {
document.body.classList.toggle('no-glow', !iface.bgGlow);
}
// Compact mode
if (iface.compactMode !== undefined) {
document.body.classList.toggle('compact', iface.compactMode);
}
}
// Display theme metadata
const themeName = theme.name || 'Thème personnalisé';
const themeInfo = theme.author ? `${themeName} par ${theme.author}` : themeName;
document.getElementById('current-theme-name').textContent = themeInfo;
// Optional: Log theme info to console for debugging
if (theme.version || theme.description) {
console.log(`🎨 Thème chargé: ${themeName}`);
if (theme.version) console.log(` Version: ${theme.version}`);
if (theme.description) console.log(` Description: ${theme.description}`);
if (theme.author) console.log(` Auteur: ${theme.author}`);
}
}
// Rendering
function renderSpaces() {
spacesList.innerHTML = '';
const allItem = document.createElement('div');
allItem.className = `nav-item ${config.activeSpaceId === 'all' ? 'active' : ''}`;
allItem.innerHTML = `<span>🚀 ${t('all_projects')}</span>`;
allItem.onclick = () => {
config.activeSpaceId = 'all';
renderSpaces();
renderProjects();
save();
};
spacesList.appendChild(allItem);
config.spaces.forEach(space => {
const item = document.createElement('div');
item.className = `nav-item ${space.id === config.activeSpaceId ? 'active' : ''}`;
item.innerHTML = `
<span>${space.name}</span>
${space.id !== 'default' ? `<span class="delete-space" data-id="${space.id}">✕</span>` : ''}
`;
item.onclick = (e) => {
if (e.target.classList.contains('delete-space')) {
deleteSpace(space.id);
} else {
config.activeSpaceId = space.id;
renderSpaces();
renderProjects();
save();
}
};
// Drag & Drop for spaces
item.ondragover = (e) => {
e.preventDefault();
item.classList.add('drag-over');
};
item.ondragleave = () => {
item.classList.remove('drag-over');
};
item.ondrop = (e) => {
e.preventDefault();
item.classList.remove('drag-over');
const projectId = e.dataTransfer.getData('projectId');
if (projectId) {
moveProjectToSpace(projectId, space.id);
}
};
spacesList.appendChild(item);
});
}
function moveProjectToSpace(projectId, targetSpaceId) {
let sourceSpace = null;
let projectIdx = -1;
// Localize the project first
config.spaces.forEach(s => {
const idx = s.projects.findIndex(p => p.id == projectId);
if (idx !== -1) {
sourceSpace = s;
projectIdx = idx;
}
});
if (sourceSpace && sourceSpace.id !== targetSpaceId) {
// Remove from source
const projectToMove = sourceSpace.projects.splice(projectIdx, 1)[0];
// Add to target
const targetSpace = config.spaces.find(s => s.id === targetSpaceId);
if (targetSpace) {
targetSpace.projects.push(projectToMove);
save();
renderProjects();
showToast(t('all_projects'), `Projet déplacé vers ${targetSpace.name}`);
} else {
// Rollback if target not found (safety)
sourceSpace.projects.splice(projectIdx, 0, projectToMove);
}
} else {
// Same space or not found: cancel operation (nothing to do)
}
}
async function renderProjects() {
const renderId = ++currentRenderId;
let projects = [];
if (config.activeSpaceId === 'all') {
currentSpaceName.textContent = t('all_projects');
projects = config.spaces.flatMap(s => s.projects);
} else {
const activeSpace = config.spaces.find(s => s.id === config.activeSpaceId);
if (!activeSpace) {
currentSpaceName.textContent = t('all_projects');
projects = config.spaces.flatMap(s => s.projects);
} else {
currentSpaceName.textContent = activeSpace.name;
projects = activeSpace.projects;
}
}
projects.forEach(project => ensureProjectDefaults(project));
const searchTerm = projectSearch.value.toLowerCase();
if (searchTerm) {
projects = projects.filter(p => {
const statusLabel = getStatusLabel(p.status).toLowerCase();
const priorityLabel = getPriorityLabel(p.priority).toLowerCase();
const taskMatch = (p.tasks || []).some(task => task.title && task.title.toLowerCase().includes(searchTerm));
const linkMatch = (p.links || []).some(link => link.label && link.label.toLowerCase().includes(searchTerm));
return (
p.name.toLowerCase().includes(searchTerm) ||
p.path.toLowerCase().includes(searchTerm) ||
(p.notes && p.notes.toLowerCase().includes(searchTerm)) ||
statusLabel.includes(searchTerm) ||
priorityLabel.includes(searchTerm) ||
taskMatch ||
linkMatch
);
});
}
// Filter by Tags
if (activeFilters.tags.length > 0) {
projects = projects.filter(p =>
(p.tags || []).some(tId => activeFilters.tags.includes(tId))
);
}
// Filter by Status
if (activeFilters.statuses.length > 0) {
projects = projects.filter(p => activeFilters.statuses.includes(p.status));
}
// Filter by Framework (skipped in performance mode to save RAM)
const isPerf = !!(config.settings.personalization && config.settings.personalization.performanceMode);
if (activeFilters.frameworks.length > 0 && !isPerf) {
const results = await Promise.all(projects.map(async p => {
const pkg = await window.electronAPI.readPackageJson(p.path);
const fw = detectFramework(pkg);
return { project: p, fw };
}));
projects = results
.filter(r => r.fw && activeFilters.frameworks.includes(r.fw.id))
.map(r => r.project);
}
const priorityOrder = { urgent: 0, high: 1, normal: 2, low: 3 };
projects.sort((a, b) => {
const pinScore = (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0);
if (pinScore !== 0) return pinScore;
return (priorityOrder[a.priority] ?? 99) - (priorityOrder[b.priority] ?? 99);
});
projectsCount.textContent = `${projects.length} projet${projects.length > 1 ? 's' : ''}`;
projectsGrid.innerHTML = '';
if (!projects || projects.length === 0) {
emptyState.classList.remove('hidden');
projectsGrid.innerHTML = '';
} else {
emptyState.classList.add('hidden');
for (const project of projects) {
if (renderId !== currentRenderId) return;
const card = await createProjectCard(project);
if (renderId !== currentRenderId) return;
projectsGrid.appendChild(card);
}
}
}
async function createProjectCard(project) {
const isPerf = !!(config.settings.personalization && config.settings.personalization.performanceMode);
const card = document.createElement('div');
card.className = `project-card ${project.pinned ? 'pinned' : ''} ${isPerf ? 'perf' : ''}`;
ensureProjectDefaults(project);
const statusMeta = getStatusMeta(project.status);
const priorityMeta = getPriorityMeta(project.priority);
const taskCounts = getTaskCounts(project);
const progress = taskCounts.total ? Math.round((taskCounts.done / taskCounts.total) * 100) : 0;
const overdueCount = getOverdueTasksCount(project) + getOverdueUpdatesCount(project);
const statusStyle = `style="border-color: ${statusMeta.color}55; background: ${statusMeta.color}22; color: ${statusMeta.color};"`;
const priorityStyle = `style="border-color: ${priorityMeta.color}55; background: ${priorityMeta.color}22; color: ${priorityMeta.color};"`;
const tasksLabel = taskCounts.total ? `${taskCounts.done}/${taskCounts.total} ${t('tasks_title')}` : '';
let framework = null;
if (!isPerf) {
const pkg = await window.electronAPI.readPackageJson(project.path);
framework = detectFramework(pkg);
}
card.innerHTML = `
<div class="project-card-header ${isPerf ? 'hidden' : ''}">
<button class="card-action-btn pin-project ${project.pinned ? 'active' : ''}">
${project.pinned ? '★' : '☆'}
</button>
<button class="card-action-btn edit-project">✎</button>
<button class="card-action-btn delete-project">✕</button>
</div>
<div class="project-info">
<h3 style="${isPerf ? 'font-size: 0.9rem;' : ''}">${project.name}</h3>
<p style="${isPerf ? 'display:none;' : ''}">${truncatePath(project.path)}</p>
<div class="project-tags" style="${isPerf ? 'margin-top: 5px;' : 'margin-top: 12px;'}">
${framework ? `<span class="fw-badge ${framework.id}">${framework.name}</span>` : ''}
${isPerf ? '' : (project.tags || []).map(tagId => {
const tag = config.settings.globalTags.find(t => t.id === tagId);
if (!tag) return '';
return `<span class="tag" style="--tag-color: ${tag.color};">${tag.name}</span>`;
}).join('')}
</div>
<div class="project-meta-row">
<span class="status-badge" ${statusStyle}>${getStatusLabel(project.status)}</span>
<span class="priority-badge" ${priorityStyle}>${getPriorityLabel(project.priority)}</span>
${tasksLabel ? `<span class="project-meta-text">${tasksLabel}</span>` : ''}
${overdueCount ? `<span class="detail-stat-chip alert">${t('stats_overdue')}: ${overdueCount}</span>` : ''}
</div>
${tasksLabel ? `<div class="project-progress"><div class="project-progress-fill" style="width: ${progress}%;"></div></div>` : ''}
</div>
`;
card.onclick = (e) => {
if (!e.target.closest('.project-card-header')) openDetailModal(project);
};
card.querySelector('.delete-project').onclick = (e) => {
e.stopPropagation();
deleteProject(project.id);
};
const editBtn = card.querySelector('.edit-project');
if (editBtn) {
editBtn.onclick = (e) => {
e.stopPropagation();
openEditModal(project);
};
}
const pinBtn = card.querySelector('.pin-project');
if (pinBtn) {
pinBtn.onclick = (e) => {
e.stopPropagation();
togglePin(project.id);
};
}
// Drag support
card.draggable = true;
card.ondragstart = (e) => {
e.dataTransfer.setData('projectId', project.id);
card.classList.add('dragging');
};
card.ondragend = () => {
card.classList.remove('dragging');
};
card._project = project; // Store for context menu
return card;
}
// Detail View Logic
async function openDetailModal(project) {
currentDetailProject = project;
ensureProjectDefaults(project);
project.lastOpenedAt = Date.now();
project.lastActivityAt = Date.now();
save();
detailName.textContent = project.name;
detailPath.textContent = project.path;
detailNotes.textContent = project.notes || 'Aucune note pour ce projet.';
// Update editor button text
const editorCmd = project.editor || 'code';
let editorName = 'VSCode';
if (editorCmd !== 'code') {
editorName = editorCmd.charAt(0).toUpperCase() + editorCmd.slice(1);
}
detailOpenEditorText.textContent = `Ouvrir ${editorName}`;
// Render tags in detail
const tagsContainer = document.createElement('div');
tagsContainer.className = 'project-tags';
tagsContainer.style.marginBottom = '20px';
tagsContainer.innerHTML = (project.tags || []).map(tagId => {
const tag = config.settings.globalTags.find(t => t.id === tagId);
if (!tag) return '';
return `<span class="tag" style="--tag-color: ${tag.color}; border-color: ${tag.color}44; background: ${tag.color}11;">${tag.name}</span>`;
}).join('');
// Clear old tags if re-opening (though modal is hidden)
const existingTags = detailPath.parentElement.querySelector('.project-tags');
if (existingTags) existingTags.remove();
detailPath.after(tagsContainer);
const pkg = await window.electronAPI.readPackageJson(project.path);
const framework = detectFramework(pkg);
detailBadges.innerHTML = framework ? `<span class="fw-badge ${framework.id}">${framework.name}</span>` : '';
const scripts = pkg && pkg.scripts ? Object.keys(pkg.scripts) : [];
detailScriptsList.innerHTML = '';
if (scripts.length > 0) {
document.getElementById('detail-scripts-container').classList.remove('hidden');
scripts.forEach(script => {
const tag = document.createElement('div');
tag.className = 'detail-script-tag';
tag.textContent = `npm run ${script}`;
tag.onclick = () => {
window.electronAPI.runNpmScript({ projectPath: project.path, script });
touchProjectActivity(project);
};
detailScriptsList.appendChild(tag);
});
} else {
document.getElementById('detail-scripts-container').classList.add('hidden');
}
renderProjectUpdates();
renderProjectTasks();
renderProjectLinks();
renderDetailStats();
startDetailTicker();
const gitBtn = document.getElementById('detail-open-git');
const gitGuiBtn = document.getElementById('detail-open-git-gui');
if (project.repoUrl) {
gitBtn.classList.remove('hidden');
gitBtn.onclick = () => {
window.electronAPI.openExternal(project.repoUrl);
touchProjectActivity(project);
};
createReleaseBtn.classList.remove('hidden');
} else {
gitBtn.classList.add('hidden');
createReleaseBtn.classList.add('hidden');
}
// Check for local .git
const hasGit = await window.electronAPI.checkGitRepo(project.path);
if (hasGit) {
gitGuiBtn.classList.remove('hidden');
} else {
gitGuiBtn.classList.add('hidden');
}
detailModal.classList.remove('hidden');
}
async function openGitModal(project) {
document.getElementById('git-project-path').textContent = project.path;
gitModal.classList.remove('hidden');
// Ensure textarea is accessible
const msgBox = document.getElementById('git-commit-message');
if (msgBox) {
msgBox.disabled = false;
setTimeout(() => msgBox.focus(), 100);
}
await refreshGitStatus();
}
async function refreshGitStatus() {
const projectPath = currentDetailProject.path;
const { success, files, error } = await window.electronAPI.gitStatus(projectPath);
const list = document.getElementById('git-changes-list');
list.innerHTML = '';
if (!success) {
list.innerHTML = `<p class="error-text">Erreur: ${error}</p>`;
return;
}
if (files.length === 0) {
list.innerHTML = '<p class="text-muted" style="font-size: 0.8rem; padding: 10px;">Aucun changement détecté.</p>';
} else {
files.forEach(file => {
const item = document.createElement('div');
item.className = 'git-change-item';