-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2015 lines (1749 loc) · 95.2 KB
/
script.js
File metadata and controls
2015 lines (1749 loc) · 95.2 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
import * as data from './data.js';
import { initializeDragDrop } from './dragDrop.js';
import { aiService } from './aiService.js';
import { handleCardTextareaKeydown } from './cardShortcuts.js'; // Import the handler
document.addEventListener('DOMContentLoaded', () => {
// --- DOM Elements ---
const sidebar = document.getElementById('sidebar');
const resizer = document.getElementById('resizer');
const mainContent = document.getElementById('main-content');
const columnsContainer = document.getElementById('columnsContainer');
const addProjectBtn = document.getElementById('add-project-btn');
const importProjectBtn = document.getElementById('import-project-btn'); // Added
const projectListContainer = document.getElementById('project-list');
// AI Settings Elements (Passed to aiService)
const aiSettingsTitle = document.getElementById('ai-settings-title');
const aiProviderUrlInput = document.getElementById('ai-provider-url');
const aiModelNameInput = document.getElementById('ai-model-name');
const aiApiKeyInput = document.getElementById('ai-api-key');
const aiTemperatureInput = document.getElementById('ai-temperature');
// --- Constants --- (UI/Rendering related)
const GROUP_HEADER_PREVIEW_LENGTH = 60; // Max chars for content preview in group header
const CARD_NAME_MAX_LENGTH = 50;
const AI_PLACEHOLDER_TEXT = "AI is thinking..."; // Keep UI constant here
const AI_RESPONSE_SEPARATOR = '---'; // Keep UI constant here
const SIDEBAR_COLLAPSED_KEY = 'sidebarCollapsed';
const STORAGE_KEY_ONBOARDING = 'onboardingComplete';
const DEFAULT_ONBOARDING_PROJECT_URL = 'examples/new-onboarding.json'; // Relative path if served
// --- State ---
let isAiActionInProgress = false; // Flag to prevent concurrent conflicting actions
// --- Helper Functions (DOM/UI specific) ---
function getCardElement(cardId) {
return document.getElementById(`card-${cardId}`);
}
function getGroupElement(parentId) {
return document.getElementById(`group-${parentId}`);
}
function getColumnElementByIndex(index) {
if (index < 0 || index >= columnsContainer.children.length) return null;
return columnsContainer.children[index];
}
// Helper to get column index from element
function getColumnIndex(columnElement) {
if (!columnElement) return -1;
return Array.from(columnsContainer.children).indexOf(columnElement);
}
function autoResizeTextarea(event) {
const textarea = event.target;
textarea.style.height = 'auto';
const computedHeight = window.getComputedStyle(textarea).height;
textarea.style.height = computedHeight;
textarea.style.height = `${textarea.scrollHeight}px`;
}
function scrollIntoViewIfNeeded(element) {
if (element) {
// Use 'nearest' to avoid unnecessary scrolling if already visible
element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
}
}
/**
* Scrolls the hierarchy related to a given card ID.
* - Centers the focused card.
* - Centers all ancestor cards in their respective containers.
* - Scrolls descendant groups (top if taller than viewport, center otherwise).
* @param {string} cardId - The ID of the card initiating the scroll.
*/
function scrollHierarchy(cardId) {
const cardEl = getCardElement(cardId);
if (!cardEl) return; // Exit if the target card element doesn't exist
// Keep track of containers we've already scrolled to prevent redundant animations
const scrolledContainers = new Set();
/**
* Helper function to scroll a container to bring a target element into view.
* @param {HTMLElement} container - The scrollable container element.
* @param {HTMLElement} targetElement - The element to scroll to within the container.
* @param {boolean} [center=true] - Whether to center the element vertically.
* @param {boolean} [scrollToTopIfTaller=false] - If the element is taller than the viewport, scroll to its top instead of centering.
*/
const scrollToTarget = (container, targetElement, center = true, scrollToTopIfTaller = false) => {
// Basic validation and check if already scrolled
if (!container || !targetElement || scrolledContainers.has(container)) {
return;
}
// Get dimensions and positions relative to the viewport
const containerRect = container.getBoundingClientRect();
const elementRect = targetElement.getBoundingClientRect();
// Calculate the element's top position relative to the container's scrollable content
const relativeElementTop = elementRect.top - containerRect.top + container.scrollTop;
const relativeElementHeight = elementRect.height;
const containerHeight = container.clientHeight; // Visible height of the container
let targetScroll; // The desired scrollTop value for the container
// Determine the target scroll position based on options
if (scrollToTopIfTaller && relativeElementHeight > window.innerHeight) {
// If the element is taller than the viewport, just scroll to its top
targetScroll = relativeElementTop;
} else if (center) {
// Calculate scroll position to center the element vertically
targetScroll = relativeElementTop - (containerHeight / 2) + (relativeElementHeight / 2);
} else {
// Default: scroll to bring the element's top into view (if not centering)
targetScroll = relativeElementTop;
}
// Perform the scroll animation, ensuring scroll position isn't negative
container.scrollTo({
top: Math.max(0, targetScroll), // Prevent scrolling above the top
behavior: 'smooth' // Use smooth scrolling animation
});
// Mark this container as scrolled
scrolledContainers.add(container);
};
// --- Scrolling Logic ---
// 1. Scroll the column containing the initially focused card to center that card.
const focusedScrollContainer = cardEl.closest('.column')?.querySelector('.cards-container');
scrollToTarget(focusedScrollContainer, cardEl, true); // Center the primary target card
// 2. Scroll the columns containing ancestor cards to center each ancestor.
// This brings the lineage leading to the focused card into view.
const ancestorIds = data.getAncestorIds(cardId); // Get IDs from data layer
ancestorIds.forEach(ancestorId => {
const ancestorEl = getCardElement(ancestorId); // Find the ancestor's DOM element
if (ancestorEl) {
const ancestorScrollContainer = ancestorEl.closest('.column')?.querySelector('.cards-container');
scrollToTarget(ancestorScrollContainer, ancestorEl, true); // Center each ancestor
}
});
// 3. Scroll the columns containing descendant groups to bring those groups into view.
// This ensures the start of the focused card's sub-tree is visible.
const descendantIds = data.getDescendantIds(cardId); // Get all descendant IDs
// Include the focused card itself, as it might be a parent with children in the next column
const allIdsToCheckForGroups = [cardId, ...descendantIds];
allIdsToCheckForGroups.forEach(currentId => {
const currentCardData = data.getCard(currentId); // Get card data
if (!currentCardData) return; // Skip if card data is missing for the current ID
// For every card in the hierarchy (focused card + descendants),
// attempt to find its corresponding group header in the *next* column
// and scroll it into view. This ensures the potential drop zone or
// child area for the card is visible.
const groupEl = getGroupElement(currentId); // Group ID matches the parent card ID (currentId)
// Check if the group element actually exists in the DOM.
// It might not exist if the next column hasn't been rendered yet,
// or if the parent card was just created and the next column's
// render hasn't completed.
if (groupEl) {
// Verify the group element is in the correct column (next column relative to the parent card)
const groupColumnEl = groupEl.closest('.column');
const groupColumnIndex = groupColumnEl ? parseInt(groupColumnEl.dataset.columnIndex, 10) : -1;
if (groupColumnIndex === currentCardData.columnIndex + 1) {
// Find the scroll container for that group
const groupScrollContainer = groupColumnEl.querySelector('.cards-container');
// Scroll the group header into view. Center it, but scroll to top if the group itself is very tall.
scrollToTarget(groupScrollContainer, groupEl, true, true);
}
}
});
}
function highlightHierarchy(cardId) {
clearHighlights();
const targetCardData = data.getCard(cardId);
if (!targetCardData) return;
const ancestors = data.getAncestorIds(cardId);
const descendants = data.getDescendantIds(cardId);
const allToHighlight = [cardId, ...ancestors, ...descendants];
allToHighlight.forEach(id => {
const cardEl = getCardElement(id);
if (cardEl) cardEl.classList.add('highlight');
const groupEl = getGroupElement(id); // Highlight group headers too
if (groupEl) groupEl.classList.add('highlight');
});
}
function clearHighlights() {
document.querySelectorAll('.card.highlight, .card.editing, .card-group.highlight').forEach(el => {
el.classList.remove('highlight', 'editing');
});
}
/**
* Updates the display text and title of a group header based on its parent card's data.
* @param {string} parentCardId - The ID of the card whose data determines the group header.
*/
function updateGroupHeaderDisplay(parentCardId) {
const groupEl = getGroupElement(parentCardId);
if (!groupEl) return; // Group might not exist in the DOM yet
const parentCardData = data.getCard(parentCardId);
if (!parentCardData) return; // Parent card data not found
const groupHeaderContainer = groupEl.querySelector('.group-header');
if (!groupHeaderContainer) return; // Header element not found
let groupHeaderText = '';
let groupHeaderTitle = '';
if (parentCardData.name) {
const truncatedParentName = parentCardData.name.length > CARD_NAME_MAX_LENGTH ? parentCardData.name.substring(0, CARD_NAME_MAX_LENGTH) + '...' : parentCardData.name;
groupHeaderText = `>> ${truncatedParentName}`;
groupHeaderTitle = `Children of ${parentCardData.name}`;
} else {
const idPart = `#${parentCardId.slice(-4)}`;
const contentPreview = parentCardData.content?.trim().substring(0, GROUP_HEADER_PREVIEW_LENGTH) || '';
const ellipsis = (parentCardData.content?.trim().length || 0) > GROUP_HEADER_PREVIEW_LENGTH ? '...' : '';
const previewText = contentPreview ? `: ${contentPreview}${ellipsis}` : '';
groupHeaderText = `>> ${idPart}${previewText}`;
groupHeaderTitle = `Children of ${idPart}${contentPreview ? `: ${parentCardData.content?.trim()}` : ''}`;
}
groupHeaderContainer.textContent = groupHeaderText;
groupHeaderContainer.title = groupHeaderTitle;
// console.log(`Updated group header display for parent: ${parentCardId}`);
}
/**
* Finds a card's textarea, focuses it, sets cursor position, and scrolls into view.
* @param {string} cardId - The ID of the card to focus.
* @param {'start' | 'end' | 'preserve' | number} [position='preserve'] - Cursor position.
*/
function focusCardTextarea(cardId, position = 'preserve') {
const cardEl = getCardElement(cardId);
if (!cardEl) return;
const textarea = cardEl.querySelector('textarea.card-content');
if (!textarea) return;
textarea.style.display = '';
textarea.focus();
requestAnimationFrame(() => {
try {
if (typeof position === 'number') {
const pos = Math.max(0, Math.min(textarea.value.length, position));
textarea.setSelectionRange(pos, pos);
} else if (position === 'start') {
textarea.setSelectionRange(0, 0);
} else if (position === 'end') {
const len = textarea.value.length;
textarea.setSelectionRange(len, len);
}
} catch (e) {
console.error(`Error setting selection range for card ${cardId}:`, e);
}
scrollHierarchy(cardId);
highlightHierarchy(cardId);
});
console.log(`Focused card ${cardId}, position: ${position}`);
}
/**
* Creates and displays a modal dialog.
* @param {string} title - The title of the modal.
* @param {string} contentHtml - HTML string for the modal's body content. Must include elements with unique IDs if they need to be accessed.
* @param {string} submitButtonText - Text for the primary action button.
* @param {(modalElement: HTMLElement) => void} onSubmit - Callback function executed when the submit button is clicked. Receives the modal element.
* @param {() => void} [onCancel] - Optional callback function executed on cancellation (Cancel button, Escape key, overlay click).
*/
function createModal(title, contentHtml, submitButtonText, onSubmit, onCancel) {
// Remove any existing modal first
document.querySelector('.modal-overlay')?.remove();
const overlay = document.createElement('div');
overlay.className = 'modal-overlay';
const modal = document.createElement('div');
modal.className = 'modal-content';
modal.innerHTML = `
<h4>${title}</h4>
${contentHtml}
<div class="modal-actions">
<button class="modal-cancel-btn">Cancel</button>
<button class="modal-submit-btn primary">${submitButtonText}</button>
</div>
`;
overlay.appendChild(modal);
document.body.appendChild(overlay);
const cancelButton = modal.querySelector('.modal-cancel-btn');
const submitButton = modal.querySelector('.modal-submit-btn');
const closeModal = () => {
if (overlay.parentNode === document.body) {
document.body.removeChild(overlay);
}
// Clean up keydown listener
document.removeEventListener('keydown', handleKeyDown);
};
const handleKeyDown = (e) => {
if (e.key === 'Escape') {
e.preventDefault();
if (onCancel) onCancel();
closeModal();
} else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
// Allow Ctrl/Cmd+Enter submit primarily for textareas
if (e.target.tagName === 'TEXTAREA') {
e.preventDefault();
submitButton.click();
}
}
};
cancelButton.addEventListener('click', () => {
if (onCancel) onCancel();
closeModal();
});
submitButton.addEventListener('click', () => {
onSubmit(modal); // Pass the modal element to the submit handler
closeModal();
});
// Close on overlay click
overlay.addEventListener('click', (e) => {
if (e.target === overlay) {
if (onCancel) onCancel();
closeModal();
}
});
// Add keydown listener for Escape and potentially Ctrl+Enter
document.addEventListener('keydown', handleKeyDown);
// Auto-focus the first input or textarea within the modal content
const firstInput = modal.querySelector('input, textarea');
if (firstInput) {
firstInput.focus();
if (typeof firstInput.select === 'function') {
firstInput.select(); // Select text if possible (useful for inputs)
}
}
}
// --- Action Locking Helpers ---
function disableConflictingActions() {
console.log("Disabling conflicting actions...");
isAiActionInProgress = true;
document.body.classList.add('ai-busy'); // Add class for potential global styling/cursor changes
// Disable buttons that modify structure/content significantly
columnsContainer.querySelectorAll('.add-card-btn, .delete-card-btn, .add-child-btn, .add-column-btn, .delete-column-btn').forEach(btn => {
btn.disabled = true;
btn.classList.add('disabled-by-ai'); // Add a specific class for targeted re-enabling
});
// Disable drag handles (card headers)
columnsContainer.querySelectorAll('.card-header').forEach(header => {
header.draggable = false;
header.classList.add('disabled-by-ai');
});
// Disable project deletion/switching
projectListContainer.querySelectorAll('.delete-project-btn, .project-item').forEach(el => {
if (el.classList.contains('project-item')) {
el.style.pointerEvents = 'none'; // Prevent switching
} else {
el.disabled = true;
}
el.classList.add('disabled-by-ai');
});
addProjectBtn.disabled = true;
addProjectBtn.classList.add('disabled-by-ai');
}
function enableConflictingActions() {
console.log("Enabling conflicting actions...");
isAiActionInProgress = false;
document.body.classList.remove('ai-busy');
// Re-enable specifically disabled elements
document.querySelectorAll('.disabled-by-ai').forEach(el => {
if (el.tagName === 'BUTTON') {
// Re-enable button, but respect original disabled state for delete column
if (!(el.classList.contains('delete-column-btn') && el.classList.contains('hidden'))) {
el.disabled = false;
}
} else if (el.classList.contains('card-header')) {
el.draggable = true;
} else if (el.classList.contains('project-item')) {
el.style.pointerEvents = ''; // Restore switching
}
el.classList.remove('disabled-by-ai');
});
// Explicitly re-check delete column button state
updateAllToolbarButtons();
}
// --- Rendering Functions ---
function createCardElement(cardData) {
const cardEl = document.createElement('div');
cardEl.id = `card-${cardData.id}`;
cardEl.className = 'card';
cardEl.dataset.cardId = cardData.id;
// Color should be pre-calculated by data.js
cardEl.style.backgroundColor = cardData.color || data.getColorForCard(cardData); // Fallback just in case
const displayName = cardData.name ? cardData.name : `#${cardData.id.slice(-4)}`;
const truncatedDisplayName = displayName.length > CARD_NAME_MAX_LENGTH ? displayName.substring(0, CARD_NAME_MAX_LENGTH) + '...' : displayName;
const aiReady = aiService.areAiSettingsValid();
cardEl.innerHTML = `
<div class="card-header" draggable="true">
<span class="card-name-display" title="${displayName}">${truncatedDisplayName}</span>
<div class="card-ai-actions ai-feature">
<button class="ai-continue-btn" title="Continue Writing (in this column)" ${!aiReady ? 'disabled' : ''}>⬇️</button>
<button class="ai-expand-btn" title="Expand (to next column)" ${!aiReady ? 'disabled' : ''}>↕️</button>
<button class="ai-summarize-btn" title="Reduce (in this column)" ${!aiReady ? 'disabled' : ''}>⏪</button>
<button class="ai-breakdown-btn" title="Brainstorm (to next column)" ${!aiReady ? 'disabled' : ''}>🧠</button>
<button class="ai-custom-btn" title="Custom Prompt (to next column)" ${!aiReady ? 'disabled' : ''}>✨</button>
</div>
<div class="card-actions">
<button class="add-child-btn" title="Add Child Card (to next column)">➕</button>
<button class="delete-card-btn" title="Delete Card">🗑️</button>
</div>
</div>
<textarea class="card-content" placeholder="Enter text...">${cardData.content || ''}</textarea>
`;
// --- Add Event Listeners ---
// Note: Drag listeners are handled by initializeDragDrop via delegation
const textarea = cardEl.querySelector('.card-content');
const nameDisplaySpan = cardEl.querySelector('.card-name-display');
nameDisplaySpan.addEventListener('dblclick', () => makeCardNameEditable(cardData.id, cardEl));
textarea.addEventListener('blur', handleTextareaBlur);
textarea.addEventListener('focus', handleTextareaFocus);
textarea.addEventListener('input', autoResizeTextarea);
requestAnimationFrame(() => autoResizeTextarea({ target: textarea })); // Initial resize
// Standard Actions
cardEl.querySelector('.add-child-btn').addEventListener('click', (e) => {
e.stopPropagation();
handleAddChildCard(cardData.id); // Use specific handler
});
cardEl.querySelector('.delete-card-btn').addEventListener('click', (e) => {
e.stopPropagation();
handleDeleteCard(cardData.id); // Use specific handler
});
// AI Actions
cardEl.querySelector('.ai-continue-btn').addEventListener('click', (e) => { e.stopPropagation(); handleAiContinue(cardData.id); });
cardEl.querySelector('.ai-breakdown-btn').addEventListener('click', (e) => { e.stopPropagation(); handleAiBreakdown(cardData.id); });
cardEl.querySelector('.ai-expand-btn').addEventListener('click', (e) => { e.stopPropagation(); handleAiExpand(cardData.id); });
cardEl.querySelector('.ai-summarize-btn').addEventListener('click', (e) => { e.stopPropagation(); handleAiSummarize(cardData.id); });
cardEl.querySelector('.ai-custom-btn').addEventListener('click', (e) => { e.stopPropagation(); handleAiCustom(cardData.id); });
return cardEl;
}
function createGroupElement(parentId) {
const parentCardData = data.getCard(parentId);
if (!parentCardData) return null;
const groupEl = document.createElement('div');
let groupHeaderText = '';
let groupHeaderTitle = '';
if (parentCardData.name) {
const truncatedParentName = parentCardData.name.length > CARD_NAME_MAX_LENGTH ? parentCardData.name.substring(0, CARD_NAME_MAX_LENGTH) + '...' : parentCardData.name;
groupHeaderText = `>> ${truncatedParentName}`;
groupHeaderTitle = `Children of ${parentCardData.name}`;
} else {
const idPart = `#${parentId.slice(-4)}`;
const contentPreview = parentCardData.content?.trim().substring(0, GROUP_HEADER_PREVIEW_LENGTH) || '';
const ellipsis = (parentCardData.content?.trim().length || 0) > GROUP_HEADER_PREVIEW_LENGTH ? '...' : '';
const previewText = contentPreview ? `: ${contentPreview}${ellipsis}` : '';
groupHeaderText = `>> ${idPart}${previewText}`;
groupHeaderTitle = `Children of ${idPart}${contentPreview ? `: ${parentCardData.content?.trim()}` : ''}`;
}
groupEl.id = `group-${parentId}`;
groupEl.className = 'card-group';
groupEl.dataset.parentId = parentId;
groupEl.innerHTML = `<div class="group-header" title="${groupHeaderTitle}">${groupHeaderText}</div>`;
// Add double-click listener to create a child card in this group
groupEl.addEventListener('dblclick', (e) => {
// Ignore dblclick if it's inside the textarea or any part of a card within the group
if (e.target.closest('textarea.card-content') || e.target.closest('.card')) {
return;
}
e.stopPropagation();
const parentId = groupEl.dataset.parentId;
const columnEl = groupEl.closest('.column');
if (parentId && columnEl) {
const columnIndex = parseInt(columnEl.dataset.columnIndex, 10);
if (!isNaN(columnIndex)) {
handleAddCard(columnIndex, parentId); // Add child card
}
}
});
// Note: Drag listeners handled by delegation
return groupEl;
}
function createColumnElement(columnIndex) {
const columnEl = document.createElement('div');
columnEl.className = 'column';
columnEl.dataset.columnIndex = columnIndex;
const aiReady = aiService.areAiSettingsValid();
const columnData = data.getColumnData(columnIndex); // Use data helper
const promptIndicator = columnData?.prompt ? '📝' : '';
const globalPromptIndicator = data.getGlobalPromptData() ? '📝' : '';
const globalPromptButton = columnIndex === 0 ?
`<button class="global-prompt-btn ai-feature" title="Set Global Prompt" ${!aiReady ? 'disabled' : ''}>Global Prompt ${globalPromptIndicator}</button>`
: '';
columnEl.innerHTML = `
<div class="column-toolbar">
<div class="toolbar-left">
<button class="add-card-btn">Add Card</button>
${globalPromptButton}
<button class="add-prompt-btn ai-feature" title="Set Column Prompt" ${!aiReady ? 'disabled' : ''}>Prompt ${promptIndicator}</button>
</div>
<div class="toolbar-right">
<button class="add-column-btn">Add Column</button>
<button class="delete-column-btn">Delete Column</button>
</div>
</div>
<div class="cards-container"></div>
`;
const cardsContainer = columnEl.querySelector('.cards-container');
// Add Listeners
columnEl.querySelector('.add-card-btn').addEventListener('click', () => handleAddCard(columnIndex, null)); // Add root card
columnEl.querySelector('.add-column-btn').addEventListener('click', handleAddColumn);
columnEl.querySelector('.delete-column-btn').addEventListener('click', () => handleDeleteColumn(columnIndex));
columnEl.querySelector('.add-prompt-btn').addEventListener('click', () => handleSetColumnPrompt(columnIndex));
if (columnIndex === 0) {
const gpBtn = columnEl.querySelector('.global-prompt-btn');
if (gpBtn) gpBtn.addEventListener('click', handleSetGlobalPrompt);
}
// Double-click on empty space in first column adds root card
cardsContainer.addEventListener('dblclick', (e) => {
// Ignore dblclick if it's inside the textarea
if (e.target.closest('textarea.card-content')) {
return;
}
if (e.target === cardsContainer && columnIndex === 0) {
handleAddCard(columnIndex, null);
}
});
// Note: Drag listeners handled by delegation
return columnEl;
}
/**
* Renders the content (cards or groups) within a specific column element.
* Clears existing content and rebuilds based on the current project data.
* @param {HTMLElement} columnEl - The DOM element of the column to render into.
* @param {number} columnIndex - The index of the column being rendered.
*/
function renderColumnContent(columnEl, columnIndex) {
const cardsContainer = columnEl.querySelector('.cards-container');
if (!cardsContainer) {
console.error(`Cards container not found in column element for index ${columnIndex}`);
return;
}
cardsContainer.innerHTML = ''; // Clear previous content before rendering new content
if (columnIndex === 0) {
// --- Render Root Cards (Column 0) ---
// Column 0 only contains root cards (cards with no parentId).
const rootCards = data.getColumnCards(0).filter(c => !c.parentId);
// Cards are assumed to be sorted by 'order' by the data.getColumnCards function.
rootCards.forEach(cardData => {
const cardEl = createCardElement(cardData); // Create the card DOM element
cardsContainer.appendChild(cardEl); // Add it to the container
});
} else {
// --- Render Groups and Child Cards (Columns > 0) ---
// Columns after the first display cards grouped by their parent from the *previous* column.
// Get all cards from the previous column; these are the potential parents for groups in this column.
const parentCards = data.getColumnCards(columnIndex - 1); // Sorted by order
parentCards.forEach(parentCardData => {
// Create a group header element for *each* potential parent card from the previous column.
// This ensures a group container exists even if it currently has no children in this column.
const groupEl = createGroupElement(parentCardData.id);
if (!groupEl) {
// This might happen if the parent card data is inconsistent or removed unexpectedly.
console.warn(`Failed to create group element for parent ${parentCardData.id} in column ${columnIndex}`);
return; // Skip rendering this group if creation failed
}
// Get the children of this specific parent *that belong in the current column*.
const childCards = data.getChildCards(parentCardData.id, columnIndex); // Sorted by order
// If this parent has children in the current column, create and append their card elements.
if (childCards.length > 0) {
childCards.forEach(childCardData => {
const cardEl = createCardElement(childCardData); // Create child card element
groupEl.appendChild(cardEl); // Append card *inside* the group element
});
}
// If childCards.length is 0, the group element remains empty, acting as a visual container.
// Append the complete group element (header + any child cards) to the column's container.
cardsContainer.appendChild(groupEl);
});
}
// After rendering content, update the state of toolbar buttons for this specific column.
updateToolbarButtons(columnEl, columnIndex);
}
/**
* Renders the entire application structure (all columns and their content).
* Clears the main columns container and rebuilds it based on the active project's data.
*/
function renderApp() {
// Clear the main container holding all columns.
columnsContainer.innerHTML = '';
const projectData = data.getActiveProjectData(); // Get data for the currently active project
// Handle cases where no project is active or data is missing/corrupted.
if (!projectData) {
columnsContainer.innerHTML = '<p style="padding: 20px; text-align: center;">Error: No project selected or data corrupted.</p>';
console.error("renderApp called with no active project data.");
return;
}
// Determine how many columns need to be rendered in the DOM.
// This is the maximum of the minimum required columns (data.MIN_COLUMNS)
// and the actual number of columns defined in the project data.
const columnsToRenderCount = Math.max(data.MIN_COLUMNS, projectData.columns.length);
// Loop through the required number of columns.
for (let i = 0; i < columnsToRenderCount; i++) {
// Create the basic structure (toolbar, container) for each column.
const columnEl = createColumnElement(i);
columnsContainer.appendChild(columnEl); // Add the column structure to the main container.
// Check if data actually exists for this column index in the project data.
if (i < projectData.columns.length) {
// If data exists, render the cards/groups within this column.
renderColumnContent(columnEl, i);
} else {
// If rendering a column beyond what's in the data (due to MIN_COLUMNS),
// it will be an empty column structure. Just update its toolbar buttons.
// This scenario should be less common if addColumnData ensures data exists.
updateToolbarButtons(columnEl, i);
}
}
// After all columns are created and potentially rendered, update all toolbar buttons
// across all columns to ensure correct states (e.g., enable/disable delete/add column).
updateAllToolbarButtons();
console.log(`App rendered for project: ${data.projects[data.activeProjectId]?.title}`);
}
function updateToolbarButtons(columnEl, columnIndex) {
const addCardBtn = columnEl.querySelector('.add-card-btn');
const addColBtn = columnEl.querySelector('.add-column-btn');
const delColBtn = columnEl.querySelector('.delete-column-btn');
const addPromptBtn = columnEl.querySelector('.add-prompt-btn');
const globalPromptBtn = columnEl.querySelector('.global-prompt-btn');
const projectData = data.getActiveProjectData();
if (!projectData) return; // Should not happen if renderApp checks
const numColumnsInData = projectData.columns.length;
const isRightmost = columnIndex === numColumnsInData - 1;
addCardBtn.classList.toggle('hidden', columnIndex !== 0); // Only show on first column
addColBtn.classList.toggle('hidden', !isRightmost); // Only show on last column
const columnCards = data.getColumnCards(columnIndex); // Use data helper
const canDelete = isRightmost && numColumnsInData > data.MIN_COLUMNS && columnCards.length === 0;
delColBtn.classList.toggle('hidden', !canDelete);
delColBtn.disabled = !canDelete;
if (addPromptBtn) {
const columnData = data.getColumnData(columnIndex); // Use data helper
const promptIndicator = columnData?.prompt ? '📝' : '';
addPromptBtn.textContent = `Prompt ${promptIndicator}`;
addPromptBtn.disabled = !aiService.areAiSettingsValid();
}
if (globalPromptBtn && columnIndex === 0) {
const globalPromptIndicator = data.getGlobalPromptData() ? '📝' : '';
globalPromptBtn.textContent = `Global Prompt ${globalPromptIndicator}`;
globalPromptBtn.disabled = !aiService.areAiSettingsValid();
}
}
function updateAllToolbarButtons() {
Array.from(columnsContainer.children).forEach((col, idx) => {
updateToolbarButtons(col, idx);
});
}
// --- Project Sidebar Rendering & Interactions ---
function renderProjectList() {
projectListContainer.innerHTML = '';
const sortedProjects = Object.values(data.projects).sort((a, b) => b.lastModified - a.lastModified);
sortedProjects.forEach(project => {
const item = document.createElement('div');
item.className = 'project-item';
item.dataset.projectId = project.id;
if (project.id === data.activeProjectId) { // Use data state
item.classList.add('active');
}
item.innerHTML = `
<span class="project-title" title="${project.title}">${project.title}</span>
<div class="project-actions">
<button class="export-project-btn" title="Export Project">📤</button>
<button class="delete-project-btn" title="Delete Project">🗑️</button>
</div>
`;
item.addEventListener('click', (e) => {
if (!e.target.closest('button') && !e.target.closest('.project-title-input')) {
handleSwitchProject(project.id); // Use handler
}
});
const titleSpan = item.querySelector('.project-title');
titleSpan.addEventListener('dblclick', () => makeProjectTitleEditable(project.id, item));
item.querySelector('.export-project-btn').addEventListener('click', (e) => {
e.stopPropagation();
handleExportProject(project.id, e); // Pass event to handler
});
item.querySelector('.delete-project-btn').addEventListener('click', (e) => {
e.stopPropagation();
handleDeleteProject(project.id); // Use handler
});
projectListContainer.appendChild(item);
});
}
function makeProjectTitleEditable(projectId, projectItemElement) {
const titleSpan = projectItemElement.querySelector('.project-title');
const currentTitle = data.projects[projectId].title; // Use data state
const input = document.createElement('input');
input.type = 'text';
input.value = currentTitle;
input.className = 'project-title-input';
titleSpan.replaceWith(input);
input.focus();
input.select();
const finishEditing = (saveChanges) => {
const newTitle = input.value.trim();
let updated = false;
if (saveChanges && newTitle && newTitle !== currentTitle) {
// Call data function to update title and lastModified
if (data.updateProjectTitle(projectId, newTitle)) {
data.saveProjectsData(); // Save changes
titleSpan.textContent = newTitle;
titleSpan.title = newTitle;
updated = true;
}
}
if (!updated) {
// Restore original if cancelled, empty, or no change
titleSpan.textContent = currentTitle;
}
input.replaceWith(titleSpan);
// Re-render list only if title changed (might affect sorting later)
// if (updated) renderProjectList(); // Avoid re-render for now unless order changes
};
input.addEventListener('blur', () => finishEditing(true));
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); finishEditing(true); }
else if (e.key === 'Escape') { e.preventDefault(); finishEditing(false); }
});
}
// --- Action Handlers (Orchestration) ---
function handleAddProject() {
const title = prompt("Enter a title for the new project:", "New Project");
if (title === null) return;
const newProject = data.addProjectData(title); // Use data function
data.saveProjectsData(); // Save the new project list
handleSwitchProject(newProject.id); // Switch to the new project
// renderProjectList() will be called by handleSwitchProject's renderApp
}
function handleDeleteProject(projectIdToDelete) {
const projectTitle = data.projects[projectIdToDelete]?.title;
if (!projectTitle) return;
if (!confirm(`Are you sure you want to delete the project "${projectTitle}" and all its content? This cannot be undone.`)) {
return;
}
const originalActiveId = data.activeProjectId; // Store the ID *before* deletion
const deleteResult = data.deleteProjectData(projectIdToDelete); // Use data function
if (deleteResult.deleted) {
data.saveProjectsData(); // Save the deletion
data.saveActiveProjectId(); // Save the potentially new active ID
// Check if the *original* active project was the one deleted
if (originalActiveId === projectIdToDelete) {
// Active project *was* deleted, load the new one
console.log(`Active project ${projectIdToDelete} deleted. Rendering new active project: ${data.activeProjectId}`);
renderApp(); // Render the new active project
renderProjectList(); // Update sidebar highlighting and active state
} else {
// Active project didn't change, just update list
console.log(`Non-active project ${projectIdToDelete} deleted. Updating project list.`);
renderProjectList();
}
}
}
function handleSwitchProject(newProjectId) {
if (data.switchActiveProject(newProjectId)) { // Use data function
data.saveActiveProjectId(); // Persist the choice
renderApp(); // Render the new project
renderProjectList(); // Update sidebar highlighting
console.log(`Switched to project: ${data.projects[data.activeProjectId].title} (${data.activeProjectId})`);
}
}
// --- Export Functions ---
function exportProjectAsText(projectId) {
const project = data.projects[projectId];
if (!project) return;
let content = '';
const projectData = project.data; // Use specific project's data
// Need temporary local versions of traversal helpers using specific project data
const getCardLocal = (id) => projectData.cards[id];
const getChildCardsLocal = (parentId, targetColumnIndex = null) => {
let children = Object.values(projectData.cards).filter(card => card.parentId === parentId);
if (targetColumnIndex !== null) {
children = children.filter(card => card.columnIndex === targetColumnIndex);
}
return children.sort((a, b) => a.order - b.order);
};
const getColumnCardsLocal = (columnIndex) => {
return Object.values(projectData.cards)
.filter(card => card.columnIndex === columnIndex && !card.parentId) // Only root cards
.sort((a, b) => a.order - b.order);
};
function traverse(cardId) {
const card = getCardLocal(cardId);
if (!card) return;
const cardContent = card.content?.trim();
if (cardContent) {
content += cardContent + '\n\n';
}
const children = getChildCardsLocal(cardId, card.columnIndex + 1);
children.forEach(child => traverse(child.id));
}
const rootCards = getColumnCardsLocal(0);
rootCards.forEach(rootCard => traverse(rootCard.id));
// File download logic
const blob = new Blob([content.trim()], { type: 'text/plain;charset=utf-8' });
// Use UTC for timestamp consistency, replace invalid chars
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `ProjectExport_${project.title.replace(/[^a-zA-Z0-9_-]/g, '_')}_${timestamp}.txt`;
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
console.log(`Exported project as TEXT: ${project.title}`);
}
function exportProjectAsJson(projectId) {
const project = data.projects[projectId];
if (!project) return;
// Create an object containing both title and data for export
const projectExportObject = {
title: project.title, // Include the project title
data: project.data // Include the existing data structure
};
try {
const jsonContent = JSON.stringify(projectExportObject, null, 2); // Pretty print JSON
const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8' });
// Use UTC for timestamp consistency, replace invalid chars
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `ProjectExport_${project.title.replace(/[^a-zA-Z0-9_-]/g, '_')}_${timestamp}.json`;
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
console.log(`Exported project as JSON: ${project.title}`);
} catch (error) {
console.error("Error exporting project as JSON:", error);
alert("Failed to export project as JSON. Check console for details.");
}
}
function displayExportOptions(projectId, buttonElement) {
// Remove any existing menus
const existingMenu = document.getElementById('export-options-menu');
if (existingMenu) existingMenu.remove();
const menu = document.createElement('div');
menu.id = 'export-options-menu';
menu.className = 'export-options-menu'; // Add class for styling
const textButton = document.createElement('button');
textButton.textContent = 'Export Text';
textButton.onclick = (e) => {
e.stopPropagation();
exportProjectAsText(projectId);
menu.remove();
};
const jsonButton = document.createElement('button');
jsonButton.textContent = 'Export JSON';
jsonButton.onclick = (e) => {
e.stopPropagation();
exportProjectAsJson(projectId);
menu.remove();
};
menu.appendChild(textButton);
menu.appendChild(jsonButton);
// Positioning relative to the button
const rect = buttonElement.getBoundingClientRect();
menu.style.position = 'absolute';
menu.style.top = `${rect.bottom + window.scrollY}px`;
menu.style.left = `${rect.left + window.scrollX}px`;
menu.style.zIndex = '1000'; // Ensure it's on top
document.body.appendChild(menu);
// Click outside to close
const clickOutsideHandler = (event) => {
if (!menu.contains(event.target) && event.target !== buttonElement) {
menu.remove();
document.removeEventListener('click', clickOutsideHandler, true); // Clean up listener
}
};
// Use capture phase to catch clicks early
document.addEventListener('click', clickOutsideHandler, true);
}
// Modified handler to show options
function handleExportProject(projectId, event) {
const buttonElement = event.currentTarget; // Get the button that was clicked
displayExportOptions(projectId, buttonElement);
}
// --- Import Functions ---
async function processImportedData(jsonDataString, sourceDescription) {