-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathBuilder.tsx
More file actions
2815 lines (2567 loc) · 115 KB
/
Builder.tsx
File metadata and controls
2815 lines (2567 loc) · 115 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 React, { useState, useEffect, useCallback, useRef } from 'react';
import { UserProfile, BlockData, BlockType, SavedBento, AvatarStyle } from '../types';
import Block from './Block';
import EditorSidebar from './EditorSidebar';
import ProfileDropdown from './ProfileDropdown';
import SettingsModal from './SettingsModal';
import ImageCropModal from './ImageCropModal';
import { useHistory } from '../hooks/useHistory';
import { useSaveStatus } from '../hooks/useSaveStatus';
import AvatarStyleModal from './AvatarStyleModal';
import AIGeneratorModal from './AIGeneratorModal';
import { exportSite, type ExportDeploymentTarget } from '../services/export';
import {
initializeApp,
updateBentoData,
setActiveBentoId,
downloadBentoJSON,
loadBentoFromFile,
renameBento,
GRID_VERSION,
} from '../services/storageService';
import { getSocialPlatformOption, buildSocialUrl, formatFollowerCount } from '../socialPlatforms';
import { getMobileLayout, MOBILE_GRID_CONFIG } from '../utils/mobileLayout';
import {
Download,
Layout,
Share2,
X,
Check,
Plus,
Eye,
Smartphone,
Monitor,
Home,
Globe,
BarChart3,
RefreshCw,
AlertTriangle,
Settings,
Upload,
FileDown,
Camera,
Pencil,
Palette,
Sparkles,
Save,
AlertCircle,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
interface BuilderProps {
onBack?: () => void;
}
const GRID_COLS = 9; // 9 columns for finer control (allows small social icons)
const GRID_MAX_SEARCH_ROWS = 200;
const MAX_ROW_SPAN = 50; // Allow tall blocks for scrollable content
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
// Migrate blocks from old 3-col grid to new 9-col grid
// Old blocks had colSpan 1-3, new blocks use colSpan 1-9
// Regular blocks (not SOCIAL_ICON) should take 3x3 cells minimum
const migrateBlocksToNewGrid = (blocks: BlockData[]): BlockData[] => {
const needsMigration = blocks.some((b) => {
// SOCIAL_ICON and SPACER with 9 cols are already new format
if (b.type === BlockType.SOCIAL_ICON) return false;
if (b.type === BlockType.SPACER && b.colSpan === 9) return false;
// If colSpan is 1, 2, or 3 for a regular block, it's old format
// New format regular blocks have colSpan of 3, 6, or 9
return b.colSpan <= 3 && b.rowSpan <= 3;
});
if (!needsMigration) return blocks;
return blocks.map((block) => {
// Skip new-format blocks
if (block.type === BlockType.SOCIAL_ICON) return block;
if (block.type === BlockType.SPACER && block.colSpan === 9) return block;
// Migrate old format: multiply dimensions by 3
const newColSpan = Math.min(block.colSpan * 3, 9);
const newRowSpan = Math.min(block.rowSpan * 3, MAX_ROW_SPAN);
// Migrate positions: multiply by 3 and adjust for 1-based indexing
const newGridColumn =
block.gridColumn !== undefined ? (block.gridColumn - 1) * 3 + 1 : undefined;
const newGridRow = block.gridRow !== undefined ? (block.gridRow - 1) * 3 + 1 : undefined;
return {
...block,
colSpan: newColSpan,
rowSpan: newRowSpan,
gridColumn: newGridColumn,
gridRow: newGridRow,
};
});
};
const blocksOverlap = (a: BlockData, b: BlockData) => {
if (
a.gridColumn === undefined ||
a.gridRow === undefined ||
b.gridColumn === undefined ||
b.gridRow === undefined
)
return false;
const aCols = Math.min(a.colSpan, GRID_COLS);
const bCols = Math.min(b.colSpan, GRID_COLS);
const aRight = a.gridColumn + aCols;
const aBottom = a.gridRow + a.rowSpan;
const bRight = b.gridColumn + bCols;
const bBottom = b.gridRow + b.rowSpan;
return !(
aRight <= b.gridColumn ||
a.gridColumn >= bRight ||
aBottom <= b.gridRow ||
a.gridRow >= bBottom
);
};
const getOccupiedCells = (blocks: BlockData[], excludeIds: string[] = []) => {
const cells = new Set<string>();
for (const block of blocks) {
if (excludeIds.includes(block.id)) continue;
if (block.gridColumn === undefined || block.gridRow === undefined) continue;
const cols = Math.min(block.colSpan, GRID_COLS);
for (let c = block.gridColumn; c < block.gridColumn + cols; c++) {
for (let r = block.gridRow; r < block.gridRow + block.rowSpan; r++) {
cells.add(`${c}-${r}`);
}
}
}
return cells;
};
const findNextAvailablePosition = (block: BlockData, occupiedCells: Set<string>, startRow = 1) => {
const neededCols = Math.min(block.colSpan, GRID_COLS);
const fromRow = Math.max(1, startRow);
const scan = (rowStart: number, rowEnd: number) => {
for (let row = rowStart; row <= rowEnd; row++) {
for (let col = 1; col <= GRID_COLS - neededCols + 1; col++) {
let canPlace = true;
for (let c = col; c < col + neededCols && canPlace; c++) {
for (let r = row; r < row + block.rowSpan && canPlace; r++) {
if (occupiedCells.has(`${c}-${r}`)) canPlace = false;
}
}
if (canPlace) return { col, row };
}
}
return null;
};
const forward = scan(fromRow, GRID_MAX_SEARCH_ROWS);
if (forward) return forward;
const wrap = scan(1, fromRow - 1);
if (wrap) return wrap;
return { col: 1, row: GRID_MAX_SEARCH_ROWS + 1 };
};
const ensureBlocksHavePositions = (blocks: BlockData[]) => {
let didChange = false;
const hasMissing = blocks.some((b) => b.gridColumn === undefined || b.gridRow === undefined);
const needsClamp = blocks.some((b) => {
if (b.gridColumn === undefined) return false;
const col = clamp(b.gridColumn, 1, GRID_COLS);
const colSpan = clamp(b.colSpan, 1, GRID_COLS);
return col !== b.gridColumn || colSpan !== b.colSpan || col + colSpan - 1 > GRID_COLS;
});
if (!hasMissing && !needsClamp) return blocks;
const occupiedCells = new Set<string>();
const markOccupied = (block: BlockData) => {
if (block.gridColumn === undefined || block.gridRow === undefined) return;
const cols = Math.min(block.colSpan, GRID_COLS);
for (let c = block.gridColumn; c < block.gridColumn + cols; c++) {
for (let r = block.gridRow; r < block.gridRow + block.rowSpan; r++) {
occupiedCells.add(`${c}-${r}`);
}
}
};
// First pass: normalize existing positioned blocks and mark occupancy.
const normalized = blocks.map((block) => {
if (block.gridColumn === undefined || block.gridRow === undefined) return block;
const nextGridColumn = clamp(block.gridColumn, 1, GRID_COLS);
const nextGridRow = Math.max(1, block.gridRow);
const nextColSpanRaw = clamp(block.colSpan, 1, GRID_COLS);
const nextColSpan = Math.min(nextColSpanRaw, GRID_COLS - nextGridColumn + 1);
const nextRowSpan = clamp(block.rowSpan, 1, MAX_ROW_SPAN);
const changed =
nextGridColumn !== block.gridColumn ||
nextGridRow !== block.gridRow ||
nextColSpan !== block.colSpan ||
nextRowSpan !== block.rowSpan;
const nextBlock = changed
? {
...block,
gridColumn: nextGridColumn,
gridRow: nextGridRow,
colSpan: nextColSpan,
rowSpan: nextRowSpan,
}
: block;
if (changed) didChange = true;
markOccupied(nextBlock);
return nextBlock;
});
// Second pass: place missing blocks.
const placed = normalized.map((block) => {
if (block.gridColumn !== undefined && block.gridRow !== undefined) return block;
const nextColSpanRaw = clamp(block.colSpan, 1, GRID_COLS);
const nextColSpan = nextColSpanRaw;
const nextRowSpan = clamp(block.rowSpan, 1, MAX_ROW_SPAN);
const neededCols = Math.min(nextColSpan, GRID_COLS);
let found: { col: number; row: number } | null = null;
for (let row = 1; row <= GRID_MAX_SEARCH_ROWS && !found; row++) {
for (let col = 1; col <= GRID_COLS - neededCols + 1 && !found; col++) {
let canPlace = true;
for (let c = col; c < col + neededCols && canPlace; c++) {
for (let r = row; r < row + nextRowSpan && canPlace; r++) {
if (occupiedCells.has(`${c}-${r}`)) canPlace = false;
}
}
if (canPlace) found = { col, row };
}
}
const pos = found ?? { col: 1, row: GRID_MAX_SEARCH_ROWS + 1 };
const nextBlock = {
...block,
gridColumn: pos.col,
gridRow: pos.row,
colSpan: nextColSpan,
rowSpan: nextRowSpan,
};
markOccupied(nextBlock);
didChange = true;
return nextBlock;
});
return didChange ? placed : blocks;
};
const resizeBlockAndResolve = (
blocks: BlockData[],
blockId: string,
requestedColSpan: number,
requestedRowSpan: number
) => {
const target = blocks.find((b) => b.id === blockId);
if (!target || target.gridColumn === undefined || target.gridRow === undefined) return blocks;
// Clamp to grid bounds (9 cols, unlimited rows)
const colSpan = clamp(
requestedColSpan,
1,
Math.min(GRID_COLS - target.gridColumn + 1, GRID_COLS)
);
const rowSpan = clamp(requestedRowSpan, 1, MAX_ROW_SPAN);
if (colSpan === target.colSpan && rowSpan === target.rowSpan) return blocks;
const resized = { ...target, colSpan, rowSpan };
// Move resized block to end of array (appears on top)
const nextBlocks = [...blocks.filter((b) => b.id !== blockId), resized];
return nextBlocks;
};
// Reflow grid: clear all positions and re-place blocks in order (compacts the grid)
const reflowGrid = (blocks: BlockData[]): BlockData[] => {
if (blocks.length === 0) return blocks;
// Sort blocks by their current position (row first, then column)
const sorted = [...blocks].sort((a, b) => {
const aRow = a.gridRow ?? 999;
const bRow = b.gridRow ?? 999;
if (aRow !== bRow) return aRow - bRow;
const aCol = a.gridColumn ?? 999;
const bCol = b.gridColumn ?? 999;
return aCol - bCol;
});
// Clear all positions and re-place using auto-placement
const cleared = sorted.map((b) => ({ ...b, gridColumn: undefined, gridRow: undefined }));
// Use ensureBlocksHavePositions to re-place all blocks
return ensureBlocksHavePositions(cleared as BlockData[]);
};
// Resolve overlaps: check all blocks and move any that overlap
const resolveOverlaps = (blocks: BlockData[]): BlockData[] => {
if (blocks.length === 0) return blocks;
// Sort by position to maintain visual order
const sorted = [...blocks].sort((a, b) => {
const aRow = a.gridRow ?? 999;
const bRow = b.gridRow ?? 999;
if (aRow !== bRow) return aRow - bRow;
const aCol = a.gridColumn ?? 999;
const bCol = b.gridColumn ?? 999;
return aCol - bCol;
});
const result: BlockData[] = [];
const occupiedCells = new Set<string>();
const markOccupied = (block: BlockData) => {
if (block.gridColumn === undefined || block.gridRow === undefined) return;
const cols = Math.min(block.colSpan, GRID_COLS);
for (let c = block.gridColumn; c < block.gridColumn + cols; c++) {
for (let r = block.gridRow; r < block.gridRow + block.rowSpan; r++) {
occupiedCells.add(`${c}-${r}`);
}
}
};
const hasOverlap = (block: BlockData): boolean => {
if (block.gridColumn === undefined || block.gridRow === undefined) return false;
const cols = Math.min(block.colSpan, GRID_COLS);
for (let c = block.gridColumn; c < block.gridColumn + cols; c++) {
for (let r = block.gridRow; r < block.gridRow + block.rowSpan; r++) {
if (occupiedCells.has(`${c}-${r}`)) return true;
}
}
return false;
};
for (const block of sorted) {
if (block.gridColumn === undefined || block.gridRow === undefined || hasOverlap(block)) {
// Find new position for this block
const pos = findNextAvailablePosition(block, occupiedCells, 1);
const movedBlock = { ...block, gridColumn: pos.col, gridRow: pos.row };
markOccupied(movedBlock);
result.push(movedBlock);
} else {
// No overlap, keep position
markOccupied(block);
result.push(block);
}
}
return result;
};
const Builder: React.FC<BuilderProps> = ({ onBack }) => {
// Load initial data from localStorage
const [activeBento, setActiveBento] = useState<SavedBento | null>(null);
const [gridVersion, setGridVersion] = useState<number>(GRID_VERSION);
const [editingBlockId, setEditingBlockId] = useState<string | null>(null);
const [isSidebarOpen, setIsSidebarOpen] = useState(true);
const [showDeployModal, setShowDeployModal] = useState(false);
const [showAnalyticsModal, setShowAnalyticsModal] = useState(false);
const [showSettingsModal, setShowSettingsModal] = useState(false);
const [showAvatarCropModal, setShowAvatarCropModal] = useState(false);
const [showAvatarStyleModal, setShowAvatarStyleModal] = useState(false);
const [showAIGeneratorModal, setShowAIGeneratorModal] = useState(false);
const [pendingAvatarSrc, setPendingAvatarSrc] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<'desktop' | 'mobile'>('desktop');
const [isLoading, setIsLoading] = useState(true);
const {
state: siteData,
set: setSiteData,
undo,
redo,
reset,
} = useHistory({
profile: null as any,
blocks: [] as any[],
});
const profile = siteData.profile;
const blocks = siteData.blocks;
const [deployTarget, setDeployTarget] = useState<ExportDeploymentTarget>(() => {
try {
const stored = localStorage.getItem('openbento_deploy_target');
if (
stored === 'vercel' ||
stored === 'netlify' ||
stored === 'github-pages' ||
stored === 'docker' ||
stored === 'vps' ||
stored === 'heroku'
) {
return stored;
}
} catch {
// ignore
}
return 'vercel';
});
const [hasDownloadedExport, setHasDownloadedExport] = useState(false);
const [isExporting, setIsExporting] = useState(false);
const [exportError, setExportError] = useState<string | null>(null);
const [analyticsDays, setAnalyticsDays] = useState<number>(30);
const [analyticsAdminToken, setAnalyticsAdminToken] = useState<string>(() => {
try {
return sessionStorage.getItem('openbento_analytics_admin_token') || '';
} catch {
return '';
}
});
const [analyticsData, setAnalyticsData] = useState<any>(null);
const [analyticsError, setAnalyticsError] = useState<string | null>(null);
const [isLoadingAnalytics, setIsLoadingAnalytics] = useState(false);
const [supabaseSetupMode, setSupabaseSetupMode] = useState<'existing' | 'create'>('existing');
const [supabaseSetupProjectRef, setSupabaseSetupProjectRef] = useState('');
const [supabaseSetupDbPassword, setSupabaseSetupDbPassword] = useState('');
const [supabaseSetupProjectName, setSupabaseSetupProjectName] = useState('');
const [supabaseSetupRegion, setSupabaseSetupRegion] = useState('eu-west-1');
const [supabaseSetupOpen, setSupabaseSetupOpen] = useState(false);
const [supabaseSetupRunning, setSupabaseSetupRunning] = useState(false);
const [supabaseSetupError, setSupabaseSetupError] = useState<string | null>(null);
const [supabaseSetupResult, setSupabaseSetupResult] = useState<any>(null);
const [draggedBlockId, setDraggedBlockId] = useState<string | null>(null);
const [dragOverBlockId, setDragOverBlockId] = useState<string | null>(null);
const [dragOverSlotIndex, setDragOverSlotIndex] = useState<number | null>(null);
const [resizingBlockId, setResizingBlockId] = useState<string | null>(null);
const [extraRows, setExtraRows] = useState(0); // Extra rows added by user
const {
status: saveStatus,
lastSavedAt,
timeAgo,
setSaving,
setSaved,
setError,
} = useSaveStatus();
const gridRef = useRef<HTMLElement | null>(null);
// Store the offset from mouse to block's top-left corner when dragging
// const dragOffsetRef = useRef<{ col: number; row: number }>({ col: 0, row: 0 });
const resizeSessionRef = useRef<{
blockId: string;
startCol: number;
startRow: number;
lastColSpan: number;
lastRowSpan: number;
} | null>(null);
// Inline editing state
const [editingField, setEditingField] = useState<'name' | 'bio' | null>(null);
const [tempName, setTempName] = useState('');
const [tempBio, setTempBio] = useState('');
const avatarInputRef = useRef<HTMLInputElement>(null);
const nameInputRef = useRef<HTMLInputElement>(null);
const bioInputRef = useRef<HTMLTextAreaElement>(null);
// Load bento on mount and migrate old grid format if needed
useEffect(() => {
const loadBento = async () => {
try {
const bento = await initializeApp();
const dataGridVersion = bento.data.gridVersion ?? GRID_VERSION;
// Migrate blocks from old 3-col grid to new 9-col grid (legacy only)
const migratedBlocks =
dataGridVersion < GRID_VERSION
? migrateBlocksToNewGrid(bento.data.blocks)
: bento.data.blocks;
const normalizedBlocks = ensureBlocksHavePositions(migratedBlocks);
const nextGridVersion = GRID_VERSION;
setActiveBento({
...bento,
data: { ...bento.data, blocks: normalizedBlocks, gridVersion: nextGridVersion },
});
reset({ profile: bento.data.profile, blocks: normalizedBlocks });
setGridVersion(nextGridVersion);
// Save migrated/normalized blocks if they changed
if (normalizedBlocks !== bento.data.blocks || nextGridVersion !== bento.data.gridVersion) {
updateBentoData(bento.id, {
profile: bento.data.profile,
blocks: normalizedBlocks,
gridVersion: nextGridVersion,
});
}
} catch (e) {
console.error('Failed to load bento:', e);
} finally {
setIsLoading(false);
}
};
loadBento();
}, [reset]);
// Auto-save function - immediate save with status indicator
const autoSave = useCallback(
(newProfile: UserProfile, newBlocks: BlockData[]) => {
if (!activeBento) return;
setSaving();
try {
// Save immediately
updateBentoData(activeBento.id, {
profile: newProfile,
blocks: newBlocks,
gridVersion,
});
// Show "saved" status briefly
setTimeout(() => {
setSaved();
}, 300);
} catch {
setError();
}
},
[activeBento, gridVersion, setSaving, setSaved, setError]
);
// Manual save function for button and keyboard shortcut
const handleManualSave = useCallback(() => {
if (!activeBento || !profile) return;
autoSave(profile, blocks);
}, [activeBento, profile, blocks, autoSave]);
// Keyboard shortcut: Ctrl/Cmd + S to save
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
handleManualSave();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleManualSave]);
// Handle profile changes with auto-save
const handleSetProfile = useCallback(
(newProfile: UserProfile | ((prev: UserProfile) => UserProfile)) => {
const updated = typeof newProfile === 'function' ? newProfile(profile!) : newProfile;
setSiteData({ profile: updated, blocks });
autoSave(updated, blocks);
},
[profile, blocks, setSiteData, autoSave]
);
// Handle blocks changes with auto-save - always resolve overlaps
const handleSetBlocks = useCallback(
(newBlocks: BlockData[] | ((prev: BlockData[]) => BlockData[])) => {
const updated = typeof newBlocks === 'function' ? newBlocks(blocks) : newBlocks;
const normalized = ensureBlocksHavePositions(updated);
const resolved = resolveOverlaps(normalized);
// Ενημερώνουμε το ενιαίο state (snapshot)
setSiteData({ profile, blocks: resolved });
if (profile) autoSave(profile, resolved);
},
[profile, blocks, setSiteData, autoSave]
);
const applyImportedBento = useCallback(
(newBento: SavedBento) => {
const nextGridVersion = newBento.data.gridVersion ?? GRID_VERSION;
const normalizedBlocks = ensureBlocksHavePositions(newBento.data.blocks);
setActiveBento(newBento);
setGridVersion(nextGridVersion);
setActiveBentoId(newBento.id);
reset({
profile: newBento.data.profile,
blocks: normalizedBlocks,
});
setEditingBlockId(null);
},
[reset]
);
// Note: Block positioning is handled when blocks are created (addBlock function)
// No automatic repositioning to avoid conflicts with user-placed blocks
// Handle bento change from dropdown
const handleBentoChange = useCallback(
(bento: SavedBento) => {
// Save current before switching
if (activeBento && profile) {
updateBentoData(activeBento.id, { profile, blocks, gridVersion });
}
const dataGridVersion = bento.data.gridVersion ?? GRID_VERSION;
const migratedBlocks =
dataGridVersion < GRID_VERSION
? migrateBlocksToNewGrid(bento.data.blocks)
: bento.data.blocks;
const normalizedBlocks = ensureBlocksHavePositions(migratedBlocks);
const nextGridVersion = GRID_VERSION;
setGridVersion(nextGridVersion);
setActiveBentoId(bento.id);
setActiveBento({
...bento,
data: { ...bento.data, blocks: normalizedBlocks, gridVersion: nextGridVersion },
});
reset({ profile: bento.data.profile, blocks: normalizedBlocks });
setEditingBlockId(null);
if (normalizedBlocks !== bento.data.blocks || nextGridVersion !== bento.data.gridVersion) {
updateBentoData(bento.id, {
profile: bento.data.profile,
blocks: normalizedBlocks,
gridVersion: nextGridVersion,
});
}
},
[activeBento, profile, blocks, gridVersion, reset]
);
const addBlock = (type: BlockType) => {
// Check for pending position from grid cell click
let gridPosition: { col?: number; row?: number } = {};
const pendingPosition = sessionStorage.getItem('pendingBlockPosition');
if (pendingPosition) {
try {
const { col, row } = JSON.parse(pendingPosition);
gridPosition = { col, row };
} catch {
// ignore
}
sessionStorage.removeItem('pendingBlockPosition');
}
// Calculate spans based on block type
// Regular blocks: 3x3 cells on 9-col grid (equivalent to 1x1 on old 3-col grid)
// SOCIAL_ICON: 1x1 cell (small icon)
// SPACER: full width (9 cols)
const getSpans = () => {
if (type === BlockType.SOCIAL_ICON) return { colSpan: 1, rowSpan: 1 };
if (type === BlockType.SPACER) return { colSpan: 9, rowSpan: 1 };
return { colSpan: 3, rowSpan: 3 }; // Regular blocks take 3x3 cells
};
const { colSpan, rowSpan } = getSpans();
const newBlock: BlockData = {
id: Math.random().toString(36).substr(2, 9),
type,
title:
type === BlockType.SOCIAL
? 'X'
: type === BlockType.SOCIAL_ICON
? ''
: type === BlockType.MAP
? 'Location'
: type === BlockType.SPACER
? 'Spacer'
: 'New Block',
content: '',
colSpan,
rowSpan,
color:
type === BlockType.SPACER
? 'bg-transparent'
: type === BlockType.SOCIAL_ICON
? 'bg-gray-100'
: 'bg-white',
textColor: 'text-gray-900',
gridColumn: gridPosition.col,
gridRow: gridPosition.row,
...(type === BlockType.SOCIAL ? { socialPlatform: 'x' as const, socialHandle: '' } : {}),
...(type === BlockType.SOCIAL_ICON
? { socialPlatform: 'instagram' as const, socialHandle: '' }
: {}),
};
handleSetBlocks([...blocks, newBlock]);
setEditingBlockId(newBlock.id);
if (!isSidebarOpen) setIsSidebarOpen(true);
};
const updateBlock = (updatedBlock: BlockData) => {
const oldBlock = blocks.find((b) => b.id === updatedBlock.id);
const sizeChanged =
oldBlock &&
(oldBlock.colSpan !== updatedBlock.colSpan || oldBlock.rowSpan !== updatedBlock.rowSpan);
const updatedBlocks = blocks.map((b) => (b.id === updatedBlock.id ? updatedBlock : b));
// If size changed, reflow the entire grid to compact it
if (sizeChanged) {
handleSetBlocks(reflowGrid(updatedBlocks));
} else {
handleSetBlocks(updatedBlocks);
}
};
const deleteBlock = (id: string) => {
const remaining = blocks.filter((b) => b.id !== id);
// Reflow to compact the grid after deletion
handleSetBlocks(reflowGrid(remaining));
if (editingBlockId === id) setEditingBlockId(null);
};
const duplicateBlock = useCallback(
(id: string) => {
let duplicated: BlockData | null = null;
handleSetBlocks((prev) => {
const source = prev.find((b) => b.id === id);
if (!source) return prev;
const generateId = () => {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return Math.random().toString(36).slice(2, 11);
};
const clone: BlockData = {
...source,
id: generateId(),
gridColumn: undefined,
gridRow: undefined,
zIndex: undefined,
mediaPosition: source.mediaPosition ? { ...source.mediaPosition } : undefined,
youtubeVideos: source.youtubeVideos
? source.youtubeVideos.map((vid) => ({ ...vid }))
: undefined,
};
const occupiedCells = getOccupiedCells(prev);
const startRow = source.gridRow ?? 1;
const position = findNextAvailablePosition(clone, occupiedCells, startRow);
clone.gridColumn = position.col;
clone.gridRow = position.row;
duplicated = clone;
return [...prev, clone];
});
if (duplicated) {
setEditingBlockId(duplicated.id);
if (!isSidebarOpen) setIsSidebarOpen(true);
}
},
[handleSetBlocks, isSidebarOpen]
);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
if (!(event.metaKey || event.ctrlKey)) return;
if (event.key.toLowerCase() !== 'd') return;
if (!editingBlockId) return;
const activeElement = (document.activeElement as HTMLElement) || null;
const targetElement = (event.target as HTMLElement) || null;
const shouldSkip =
(activeElement &&
(activeElement.tagName === 'INPUT' ||
activeElement.tagName === 'TEXTAREA' ||
activeElement.isContentEditable)) ||
(targetElement &&
(targetElement.tagName === 'INPUT' ||
targetElement.tagName === 'TEXTAREA' ||
targetElement.isContentEditable));
if (shouldSkip) return;
event.preventDefault();
duplicateBlock(editingBlockId);
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [duplicateBlock, editingBlockId]);
const handleExport = () => {
setHasDownloadedExport(false);
setExportError(null);
setShowDeployModal(true);
};
// Export current bento as JSON file
const handleExportJSON = () => {
if (!activeBento) return;
// Update bento with current state before exporting
const currentBento = {
...activeBento,
data: { profile, blocks, gridVersion },
};
downloadBentoJSON(currentBento);
};
// Import bento from JSON file
const handleImportJSON = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const bento = await loadBentoFromFile(file);
const dataGridVersion = bento.data.gridVersion ?? GRID_VERSION;
const migratedBlocks =
dataGridVersion < GRID_VERSION
? migrateBlocksToNewGrid(bento.data.blocks)
: bento.data.blocks;
const normalizedBlocks = ensureBlocksHavePositions(migratedBlocks);
const nextGridVersion = GRID_VERSION;
setGridVersion(nextGridVersion);
setActiveBento({
...bento,
data: { ...bento.data, blocks: normalizedBlocks, gridVersion: nextGridVersion },
});
reset({ profile: bento.data.profile, blocks: normalizedBlocks });
setEditingBlockId(null);
updateBentoData(bento.id, {
profile: bento.data.profile,
blocks: normalizedBlocks,
gridVersion: nextGridVersion,
});
} catch (err) {
console.error('Failed to import bento:', err);
alert('Failed to import bento. Please check the JSON file.');
}
// Reset file input
e.target.value = '';
};
// Inline avatar upload - opens crop modal
const handleAvatarUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
const dataUrl = event.target?.result as string;
setPendingAvatarSrc(dataUrl);
setShowAvatarCropModal(true);
};
reader.readAsDataURL(file);
e.target.value = '';
};
// Get avatar style classes
const getAvatarClasses = (style?: AvatarStyle) => {
const _s = style || { shape: 'rounded', shadow: true, border: true };
const classes: string[] = [
'w-full',
'h-full',
'object-cover',
'transition-transform',
'duration-500',
'group-hover:scale-110',
];
return classes.join(' ');
};
// Get avatar container classes based on style
const getAvatarContainerClasses = (style?: AvatarStyle) => {
const s = style || { shape: 'rounded', shadow: true, border: true };
const classes: string[] = [
'w-40',
'h-40',
'overflow-hidden',
'relative',
'z-10',
'bg-gray-100',
];
// Shape
if (s.shape === 'circle') classes.push('rounded-full');
else if (s.shape === 'square') classes.push('rounded-none');
else classes.push('rounded-3xl');
// Shadow
if (s.shadow) classes.push('shadow-2xl');
return classes.join(' ');
};
// Get avatar container style
const getAvatarContainerStyle = (style?: AvatarStyle): React.CSSProperties => {
const s = style || {
shape: 'rounded',
shadow: true,
border: true,
borderColor: '#ffffff',
borderWidth: 4,
};
const styles: React.CSSProperties = {};
if (s.border) {
styles.border = `${s.borderWidth || 4}px solid ${s.borderColor || '#ffffff'}`;
}
return styles;
};
// Handle avatar style change
const handleAvatarStyleChange = (newStyle: AvatarStyle) => {
handleSetProfile((prev) => ({ ...prev, avatarStyle: newStyle }));
};
// Start inline editing
const startEditingName = () => {
setTempName(profile.name);
setEditingField('name');
setTimeout(() => nameInputRef.current?.focus(), 10);
};
const startEditingBio = () => {
setTempBio(profile.bio);
setEditingField('bio');
setTimeout(() => bioInputRef.current?.focus(), 10);
};
// Save inline edits
const saveNameEdit = () => {
if (tempName.trim()) {
handleSetProfile((prev) => ({ ...prev, name: tempName.trim() }));
}
setEditingField(null);
};
const saveBioEdit = () => {
handleSetProfile((prev) => ({ ...prev, bio: tempBio }));
setEditingField(null);
};
// Handle key events for inline editing
const handleNameKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault();
saveNameEdit();
} else if (e.key === 'Escape') {
setEditingField(null);
}
};
const handleBioKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Escape') {
setEditingField(null);
}
// Allow Enter for new lines in bio
};
useEffect(() => {
try {
localStorage.setItem('openbento_deploy_target', deployTarget);
} catch {
// ignore
}
}, [deployTarget]);
const downloadExport = useCallback(async () => {
if (!profile) return;
setIsExporting(true);
setExportError(null);
try {
await exportSite(
{ profile, blocks },
{ siteId: activeBento?.id, deploymentTarget: deployTarget }
);
setHasDownloadedExport(true);
} catch (e) {
const message = e instanceof Error ? e.message : 'Export failed.';
setExportError(message);
setHasDownloadedExport(false);
} finally {
setIsExporting(false);
}
}, [profile, blocks, activeBento?.id, deployTarget]);
const fetchAnalytics = useCallback(async () => {
if (!profile) return;
const supabaseUrl = profile.analytics?.supabaseUrl?.trim().replace(/\/+$/, '') || '';
if (!supabaseUrl) {
setAnalyticsError('Set your Supabase URL in Analytics settings.');
return;
}
if (!activeBento?.id) {
setAnalyticsError('Missing siteId (active bento).');
return;
}
if (!analyticsAdminToken.trim()) {