-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathuseComponentsStore.ts
More file actions
1721 lines (1484 loc) · 64 KB
/
Copy pathuseComponentsStore.ts
File metadata and controls
1721 lines (1484 loc) · 64 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
/**
* Components Store
*
* Global state management for components
* Components are reusable layer trees stored globally
*/
import { create } from 'zustand';
import {
createComponentViaApi,
replaceLayerWithComponentInstance,
findLayerById,
cleanLayersForComponentCreation,
regenerateIdsWithInteractionRemapping,
} from '@/lib/layer-utils';
import { detachStyleFromLayers, updateLayersWithStyle } from '@/lib/layer-style-utils';
import { scheduleIdle } from '@/lib/schedule-idle';
import { generateId } from '@/lib/utils';
import type { Component, ComponentVariant, Layer, LayerStyle } from '@/types';
/**
* Per-component, per-variant working copy of layers used while editing a
* component. Outer key = componentId, inner key = variantId.
*/
type ComponentDraftMap = Record<string, Record<string, Layer[]>>;
/**
* Build a fresh `variants` array from the latest draft layers, falling back to
* each variant's persisted layers when no draft exists for it (e.g. the user
* never switched to that variant during this edit session).
*/
function buildVariantsFromDrafts(
component: Component,
drafts: Record<string, Layer[]> | undefined,
): ComponentVariant[] {
const variants = component.variants && component.variants.length > 0
? component.variants
: [{ id: generateId('cmpvar'), name: 'Default', layers: component.layers ?? [] }];
return variants.map(v => ({ ...v, layers: drafts?.[v.id] ?? v.layers }));
}
/** Pick the first variant id of a component, used as the safe default. */
function getPrimaryVariantId(component: Component | undefined): string | null {
if (!component) return null;
const variants = component.variants;
if (variants && variants.length > 0) return variants[0].id;
return null;
}
/** Remove variableLinks entries that point TO a given variable ID (as parent target). */
function removeVariableLinksPointingTo(layer: Layer, targetVariableId: string): Layer {
const links = layer.componentOverrides?.variableLinks;
if (!links) return layer;
const filtered = { ...links };
let changed = false;
for (const [childId, parentId] of Object.entries(filtered)) {
if (parentId === targetVariableId) {
delete filtered[childId];
changed = true;
}
}
if (!changed) return layer;
return {
...layer,
componentOverrides: {
...layer.componentOverrides,
variableLinks: Object.keys(filtered).length > 0 ? filtered : undefined,
},
};
}
/**
* Fire-and-forget thumbnail generation for a component.
* Dynamically imports the capture module to avoid bundling it in the initial load.
* Updates the components store when the thumbnail is ready.
*/
export function triggerThumbnailGeneration(
componentId: string,
layers: Layer[],
allComponents: Component[]
): void {
if (typeof window === 'undefined') return;
import('@/lib/client/thumbnail-capture').then(({ generateComponentThumbnail }) => {
generateComponentThumbnail(componentId, layers, allComponents).then((thumbnailUrl) => {
if (thumbnailUrl) {
const state = useComponentsStore.getState();
state.setComponents(
state.components.map((c) =>
c.id === componentId
? { ...c, thumbnail_url: thumbnailUrl, updated_at: new Date().toISOString() }
: c
)
);
}
});
}).catch((err) => console.error('Failed to generate thumbnail:', err));
}
interface ComponentsState {
components: Component[];
isLoading: boolean;
error: string | null;
/**
* Per-component, per-variant working copy of layers used while editing a
* component. Outer key = componentId, inner key = variantId.
*/
componentDrafts: ComponentDraftMap;
/**
* True when any variant draft for this component has been mutated since it
* was last loaded or persisted. Used to skip no-op saves and cross-page
* sync passes when leaving the component editor without making any changes.
* Tracked at component granularity (not per-variant) because saves always
* persist the whole `variants` array as one unit.
*/
componentDraftDirty: Record<string, boolean>;
isSaving: boolean;
saveTimeouts: Record<string, NodeJS.Timeout>;
}
/**
* Preview info for component deletion
*/
export interface DeletePreviewInfo {
affectedCount: number;
affectedEntities: Array<{
type: 'page' | 'component';
id: string;
name: string;
pageId?: string;
}>;
}
/**
* Result of deleting a component
*/
export interface DeleteComponentResult {
success: boolean;
affectedEntities?: Array<{
type: 'page' | 'component';
id: string;
name: string;
pageId?: string;
previousLayers: Layer[];
newLayers: Layer[];
}>;
}
interface ComponentsActions {
// Data loading
setComponents: (components: Component[]) => void;
loadComponents: () => Promise<void>;
/**
* Apply an authoritative component snapshot from the server (e.g. after the AI
* agent edits it). Replaces the record in `components` and rebuilds the
* component's drafts from its variants so the open canvas reflects the change
* without a manual reload. Marks the drafts clean so it doesn't trigger a save.
*/
applyServerComponent: (component: Component) => void;
// CRUD operations
createComponent: (name: string, layers: Layer[]) => Promise<Component | null>;
updateComponent: (id: string, updates: Partial<Pick<Component, 'name' | 'layers'>>) => Promise<void>;
deleteComponent: (id: string) => Promise<DeleteComponentResult>;
getDeletePreview: (id: string) => Promise<DeletePreviewInfo | null>;
// Draft management (for editing mode)
loadComponentDraft: (componentId: string) => Promise<void>;
updateComponentDraft: (componentId: string, variantId: string, layers: Layer[]) => void;
saveComponentDraft: (componentId: string) => Promise<void>;
clearComponentDraft: (componentId: string) => void;
/**
* Read the current draft layers for a component+variant, falling back to
* the persisted variant layers (or the legacy `layers` field) when no
* working copy exists yet for that variant.
*/
getComponentDraftLayers: (componentId: string, variantId?: string | null) => Layer[];
// Variant management
addVariant: (componentId: string, fromVariantId?: string | null) => Promise<string | null>;
renameVariant: (componentId: string, variantId: string, name: string) => Promise<void>;
duplicateVariant: (componentId: string, variantId: string) => Promise<string | null>;
deleteVariant: (componentId: string, variantId: string) => Promise<void>;
/** Persist a new ordering of a component's variants. Order matters because
* the first variant is the implicit "default" instances fall back to. */
reorderVariants: (componentId: string, orderedVariantIds: string[]) => Promise<void>;
// Convenience actions
renameComponent: (id: string, newName: string) => Promise<void>;
getComponentById: (id: string) => Component | undefined;
createComponentFromLayer: (componentId: string, layerId: string, componentName: string) => Promise<string | null>;
restoreComponents: (componentIds: string[]) => Promise<string[]>;
// Component variables
addTextVariable: (componentId: string, name: string) => Promise<string | null>;
addRichTextVariable: (componentId: string, name: string) => Promise<string | null>;
addImageVariable: (componentId: string, name: string) => Promise<string | null>;
addLinkVariable: (componentId: string, name: string) => Promise<string | null>;
addAudioVariable: (componentId: string, name: string) => Promise<string | null>;
addVideoVariable: (componentId: string, name: string) => Promise<string | null>;
addIconVariable: (componentId: string, name: string) => Promise<string | null>;
/** Add a `'variant'` typed variable. Variant variables expose a parent
* variable that drives the `componentVariantId` of any nested-instance layer
* whose `componentVariantVariableId` points at it. */
addVariantVariable: (componentId: string, name: string) => Promise<string | null>;
updateTextVariable: (componentId: string, variableId: string, updates: { name?: string; placeholder?: string; default_value?: any }) => Promise<void>;
reorderVariables: (componentId: string, orderedIds: string[]) => Promise<void>;
deleteTextVariable: (componentId: string, variableId: string) => Promise<void>;
// Layer style operations
updateStyleOnLayers: (styleId: string, stylesById: Map<string, LayerStyle>) => void;
detachStyleFromAllLayers: (styleId: string, stylesById?: Map<string, LayerStyle>) => void;
// State management
setError: (error: string | null) => void;
clearError: () => void;
setSaving: (value: boolean) => void;
}
type ComponentsStore = ComponentsState & ComponentsActions;
export const useComponentsStore = create<ComponentsStore>((set, get) => {
/**
* Apply a layer transform to every variant on every component (and to every
* working draft). Used by global style sync helpers below.
*/
const updateComponentLayers = (updateLayers: (layers: Layer[]) => Layer[]) => {
const { components, componentDrafts } = get();
const updatedComponents = components.map(component => {
const transformedVariants = (component.variants && component.variants.length > 0)
? component.variants.map(v => ({ ...v, layers: updateLayers(v.layers) }))
: undefined;
return {
...component,
layers: updateLayers(component.layers),
...(transformedVariants ? { variants: transformedVariants } : {}),
};
});
const updatedDrafts: ComponentDraftMap = {};
Object.entries(componentDrafts).forEach(([componentId, variantDrafts]) => {
updatedDrafts[componentId] = {};
Object.entries(variantDrafts).forEach(([variantId, layers]) => {
updatedDrafts[componentId][variantId] = updateLayers(layers);
});
});
set({ components: updatedComponents, componentDrafts: updatedDrafts });
};
return {
// Initial state
components: [],
isLoading: false,
error: null,
componentDrafts: {},
componentDraftDirty: {},
isSaving: false,
saveTimeouts: {},
// Set components (used by unified init)
setComponents: (components) => set({ components }),
// Apply an authoritative server snapshot (e.g. after AI edits a component).
applyServerComponent: (component) => {
const variants = component.variants && component.variants.length > 0
? component.variants
: [{ id: generateId('cmpvar'), name: 'Default', layers: component.layers ?? [] }];
// Rebuild the per-variant drafts so the open component canvas re-renders
// with the AI's changes. Deep-clone so later local edits don't mutate the
// stored component record.
const variantDrafts: Record<string, Layer[]> = {};
for (const variant of variants) {
variantDrafts[variant.id] = JSON.parse(JSON.stringify(variant.layers ?? []));
}
set((state) => ({
components: state.components.some((c) => c.id === component.id)
? state.components.map((c) => (c.id === component.id ? component : c))
: [component, ...state.components],
componentDrafts: {
...state.componentDrafts,
[component.id]: variantDrafts,
},
componentDraftDirty: {
...state.componentDraftDirty,
[component.id]: false,
},
}));
},
// Load all components
loadComponents: async () => {
set({ isLoading: true, error: null });
try {
const response = await fetch('/ycode/api/components');
const result = await response.json();
if (result.error) {
set({ error: result.error, isLoading: false });
return;
}
set({ components: result.data || [], isLoading: false });
} catch (error) {
console.error('Failed to load components:', error);
set({ error: 'Failed to load components', isLoading: false });
}
},
// Create a new component
createComponent: async (name, layers) => {
set({ isLoading: true, error: null });
try {
const response = await fetch('/ycode/api/components', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
layers,
}),
});
const result = await response.json();
if (result.error) {
set({ error: result.error, isLoading: false });
return null;
}
const newComponent = result.data;
set((state) => ({
components: [newComponent, ...state.components],
isLoading: false,
}));
// Generate thumbnail in the background (fire-and-forget)
triggerThumbnailGeneration(newComponent.id, newComponent.layers, get().components);
return newComponent;
} catch (error) {
console.error('Failed to create component:', error);
set({ error: 'Failed to create component', isLoading: false });
return null;
}
},
// Update a component
updateComponent: async (id, updates) => {
set({ isLoading: true, error: null });
try {
const response = await fetch(`/ycode/api/components/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updates),
});
const result = await response.json();
if (result.error) {
set({ error: result.error, isLoading: false });
return;
}
const updatedComponent = result.data;
set((state) => ({
components: state.components.map((c) => (c.id === id ? updatedComponent : c)),
isLoading: false,
}));
} catch (error) {
console.error('Failed to update component:', error);
set({ error: 'Failed to update component', isLoading: false });
}
},
// Get preview of what will be affected by deleting a component
getDeletePreview: async (id) => {
try {
const response = await fetch(`/ycode/api/components/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'preview-delete' }),
});
const result = await response.json();
if (result.error) {
console.error('Failed to get delete preview:', result.error);
return null;
}
return result.data as DeletePreviewInfo;
} catch (error) {
console.error('Failed to get delete preview:', error);
return null;
}
},
// Delete a component (soft delete with undo/redo support)
deleteComponent: async (id) => {
set({ isLoading: true, error: null });
try {
const response = await fetch(`/ycode/api/components/${id}`, {
method: 'DELETE',
});
const result = await response.json();
if (result.error) {
set({ error: result.error, isLoading: false });
return { success: false };
}
const { component, affectedEntities } = result.data;
// Update pages store for affected pages
if (affectedEntities && affectedEntities.length > 0) {
const { usePagesStore } = await import('./usePagesStore');
const pagesStore = usePagesStore.getState();
for (const entity of affectedEntities) {
if (entity.type === 'page' && entity.pageId) {
// Update the page draft with new layers (component detached)
const currentDraft = pagesStore.draftsByPageId[entity.pageId];
if (currentDraft) {
pagesStore.setDraftLayers(entity.pageId, entity.newLayers);
}
} else if (entity.type === 'component') {
// Update component in local store
set((state) => ({
components: state.components.map((c) =>
c.id === entity.id ? { ...c, layers: entity.newLayers } : c
),
}));
// Also update component draft if it's currently being edited.
// The legacy `layers` field mirrors the primary variant, so the
// detached layers replace that variant's draft.
const currentDraft = get().componentDrafts[entity.id];
const primaryVariantId = getPrimaryVariantId(get().getComponentById(entity.id));
if (currentDraft && primaryVariantId) {
get().updateComponentDraft(entity.id, primaryVariantId, entity.newLayers);
}
}
}
// Record undo/redo versions for affected entities
const { recordVersionViaApi, initializeVersionTracking } = await import('@/lib/version-tracking');
const { useEditorStore } = await import('./useEditorStore');
// Get current editor state to check if any affected entity is currently being edited
const editorState = useEditorStore.getState();
const currentPageId = editorState.currentPageId;
const editingComponentId = editorState.editingComponentId;
const selectedLayerId = editorState.selectedLayerId;
const lastSelectedLayerId = editorState.lastSelectedLayerId;
// Helper: Find all layer IDs of component instances in a layer tree
const findComponentInstanceLayerIds = (layers: Layer[], componentId: string): string[] => {
const instanceIds: string[] = [];
const traverse = (layerList: Layer[]) => {
for (const layer of layerList) {
if (layer.componentId === componentId) {
instanceIds.push(layer.id);
}
if (layer.children && layer.children.length > 0) {
traverse(layer.children);
}
}
};
traverse(layers);
return instanceIds;
};
// Record versions with component requirement metadata
for (const entity of affectedEntities) {
// Note: Component requirements are now auto-detected from layers
// We still explicitly add the deleted component ID for clarity and as a safety measure
const metadata: any = {
requirements: {
component_ids: [id], // The deleted component must be restored before undoing
},
};
// Build prioritized selection list
const layerIds: string[] = [];
// If this entity is currently being edited, capture current selection first
const isCurrentlyEditing =
(entity.type === 'page' && entity.pageId === currentPageId) ||
(entity.type === 'component' && entity.id === editingComponentId);
if (isCurrentlyEditing) {
if (selectedLayerId) layerIds.push(selectedLayerId);
if (lastSelectedLayerId && lastSelectedLayerId !== selectedLayerId) {
layerIds.push(lastSelectedLayerId);
}
}
// Always add the component instance layer IDs that are being detached
// These will be restored when undoing, so they're good selection candidates
const componentInstanceIds = findComponentInstanceLayerIds(entity.previousLayers, id);
for (const instanceId of componentInstanceIds) {
if (!layerIds.includes(instanceId)) {
layerIds.push(instanceId);
}
}
// Store selection metadata if we have any layer IDs
if (layerIds.length > 0) {
metadata.selection = {
layer_ids: layerIds,
};
}
if (entity.type === 'page' && entity.pageId) {
// Initialize cache with previous state (before detachment) if not already cached
initializeVersionTracking('page_layers', entity.pageId, entity.previousLayers);
// Record version with new state (after detachment)
await recordVersionViaApi('page_layers', entity.pageId, entity.newLayers, metadata);
} else if (entity.type === 'component') {
// Initialize cache with previous state (before detachment) if not already cached
initializeVersionTracking('component', entity.id, entity.previousLayers);
// Record version with new state (after detachment)
await recordVersionViaApi('component', entity.id, entity.newLayers, metadata);
}
}
}
// Remove the component from local store
set((state) => ({
components: state.components.filter((c) => c.id !== id),
isLoading: false,
}));
return { success: true, affectedEntities };
} catch (error) {
console.error('Failed to delete component:', error);
set({ error: 'Failed to delete component', isLoading: false });
return { success: false };
}
},
// Load component into draft for editing — clones every variant so the
// user can switch between them in the editor without losing edits.
loadComponentDraft: async (componentId) => {
const component = get().components.find((c) => c.id === componentId);
if (component) {
// Backfill a "Default" variant for components that pre-date the
// variants migration so the editor always has at least one entry.
const variants = component.variants && component.variants.length > 0
? component.variants
: [{ id: generateId('cmpvar'), name: 'Default', layers: component.layers ?? [] }];
const variantDrafts: Record<string, Layer[]> = {};
for (const variant of variants) {
variantDrafts[variant.id] = JSON.parse(JSON.stringify(variant.layers ?? []));
}
// Mark each variant as initializing BEFORE updating store to prevent
// false change detection. Undo/redo is scoped per variant.
try {
const { markEntityInitializing, updatePreviousState } = await import('@/hooks/use-undo-redo');
const { componentVersionEntityId } = await import('@/lib/version-tracking');
for (const variant of variants) {
const versionId = componentVersionEntityId(componentId, variant.id);
markEntityInitializing('component', versionId);
updatePreviousState('component', versionId, variantDrafts[variant.id]);
}
} catch (err) {
console.error('Failed to mark component as initializing:', err);
}
set((state) => ({
componentDrafts: {
...state.componentDrafts,
[componentId]: variantDrafts,
},
componentDraftDirty: {
...state.componentDraftDirty,
[componentId]: false,
},
}));
// Initialize version tracking with loaded state (per variant)
import('@/lib/version-tracking').then(({ initializeVersionTracking, componentVersionEntityId }) => {
for (const variant of variants) {
initializeVersionTracking(
'component',
componentVersionEntityId(componentId, variant.id),
variantDrafts[variant.id]
);
}
}).catch((err) => {
console.error('Failed to initialize component version tracking:', err);
});
}
},
// Update component variant draft (triggers auto-save). All variant drafts
// for the same component share a single debounced save so we always
// persist them together as one `variants` payload.
updateComponentDraft: (componentId, variantId, layers) => {
set((state) => ({
componentDrafts: {
...state.componentDrafts,
[componentId]: {
...(state.componentDrafts[componentId] || {}),
[variantId]: layers,
},
},
componentDraftDirty: {
...state.componentDraftDirty,
[componentId]: true,
},
}));
// Clear existing timeout for this component
const { saveTimeouts } = get();
if (saveTimeouts[componentId]) {
clearTimeout(saveTimeouts[componentId]);
}
// Set new timeout for auto-save (500ms debounce)
const timeout = setTimeout(() => {
get().saveComponentDraft(componentId);
}, 500);
set((state) => ({
saveTimeouts: {
...state.saveTimeouts,
[componentId]: timeout,
},
}));
},
getComponentDraftLayers: (componentId, variantId) => {
const component = get().components.find(c => c.id === componentId);
const drafts = get().componentDrafts[componentId];
const targetVariantId = variantId ?? getPrimaryVariantId(component);
if (drafts && targetVariantId && drafts[targetVariantId]) {
return drafts[targetVariantId];
}
// Fall back to persisted variant layers, then to the legacy `layers`.
if (component?.variants && component.variants.length > 0) {
const match = targetVariantId
? component.variants.find(v => v.id === targetVariantId)
: undefined;
return (match ?? component.variants[0]).layers ?? [];
}
return component?.layers ?? [];
},
// Save the entire variants payload for a component to the database.
saveComponentDraft: async (componentId) => {
const { componentDrafts, componentDraftDirty, components } = get();
const variantDrafts = componentDrafts[componentId];
if (!variantDrafts || Object.keys(variantDrafts).length === 0) {
console.warn(`No draft found for component ${componentId}`);
return;
}
// Skip the round-trip entirely when nothing has changed since the draft
// was loaded or last persisted.
if (!componentDraftDirty[componentId]) {
return;
}
const component = components.find(c => c.id === componentId);
if (!component) {
console.warn(`Component ${componentId} not found in store while saving draft`);
return;
}
// Rebuild the variants payload from the latest drafts. Variants the user
// never opened during this session keep their persisted layers.
const variantsBeingSaved = buildVariantsFromDrafts(component, variantDrafts);
// Snapshot the primary variant's layers for change-detection / undo.
const layersBeingSaved = variantsBeingSaved[0]?.layers ?? [];
set({ isSaving: true });
try {
const response = await fetch(`/ycode/api/components/${componentId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variants: variantsBeingSaved }),
});
const result = await response.json();
if (result.error) {
console.error('Failed to save component draft:', result.error);
set({ isSaving: false });
return;
}
const updatedComponent = result.data;
// Detect whether any variant changed during the save (e.g. undo/redo).
const currentDrafts = get().componentDrafts[componentId];
const currentVariantsJSON = JSON.stringify(buildVariantsFromDrafts(updatedComponent, currentDrafts));
const savedVariantsJSON = JSON.stringify(variantsBeingSaved);
if (currentVariantsJSON === savedVariantsJSON) {
set((state) => ({
components: state.components.map((c) => (c.id === componentId ? updatedComponent : c)),
componentDraftDirty: { ...state.componentDraftDirty, [componentId]: false },
isSaving: false,
}));
// Record a version per variant for undo/redo. Each variant has its
// own history; unchanged variants produce an empty patch and are
// skipped inside recordVersionViaApi.
import('@/lib/version-tracking').then(({ recordVersionViaApi, componentVersionEntityId }) => {
for (const variant of variantsBeingSaved) {
recordVersionViaApi(
'component',
componentVersionEntityId(componentId, variant.id),
variant.layers
);
}
}).catch((err) => {
console.error('Failed to record component version:', err);
});
} else {
// Variants changed mid-save — keep the local copy and let the next
// debounced save record the version.
set((state) => ({
components: state.components.map((c) => (c.id === componentId ? updatedComponent : c)),
isSaving: false,
}));
}
// Trigger component sync across all pages — pages render the primary
// variant for back-compat and per-instance variant resolution happens
// at render time.
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('componentUpdated', {
detail: { componentId, layers: layersBeingSaved }
}));
triggerThumbnailGeneration(componentId, layersBeingSaved, get().components);
}
// Regenerate CSS to include updated component classes. Collect layers
// from every variant so styles unique to a non-default variant are
// also captured. Run this off the critical path so navigation/UI is
// not blocked.
scheduleIdle(async () => {
try {
const { usePagesStore } = await import('./usePagesStore');
const { collectComponentIds } = await import('@/lib/component-utils');
// `collectComponentIds` (unlike `containsComponent`) also finds
// components embedded inside rich-text content and override text
// values, so a page that uses this component only inside a Rich
// Text block is still flagged for per-page CSS regeneration.
const referencesComponent = (layers: Layer[]) =>
collectComponentIds(layers).has(componentId);
const allDrafts = usePagesStore.getState().draftsByPageId;
const affectedPageIds: string[] = [];
Object.entries(allDrafts).forEach(([pid, pageDraft]) => {
if (pageDraft.layers && referencesComponent(pageDraft.layers)) {
affectedPageIds.push(pid);
}
});
if (affectedPageIds.length > 0) {
fetch('/ycode/api/css/generate-pages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pageIds: affectedPageIds }),
}).catch(() => {});
}
// Also regenerate global draft_css for builder preview.
// Start from all variant layers so non-default variant styles are
// included, then append affected page layers.
const { generateAndSaveCSS } = await import('@/lib/client/cssGenerator');
const allLayers: Layer[] = variantsBeingSaved.flatMap(v => v.layers);
Object.values(allDrafts).forEach((pageDraft) => {
if (pageDraft.layers && referencesComponent(pageDraft.layers)) {
allLayers.push(...pageDraft.layers);
}
});
await generateAndSaveCSS(allLayers);
} catch (cssError) {
console.error('Failed to generate CSS after component save:', cssError);
}
});
} catch (error) {
console.error('Failed to save component draft:', error);
set({ isSaving: false });
}
},
// Clear component draft from memory
clearComponentDraft: (componentId) => {
set((state) => {
const newDrafts = { ...state.componentDrafts };
delete newDrafts[componentId];
const newDirty = { ...state.componentDraftDirty };
delete newDirty[componentId];
const newTimeouts = { ...state.saveTimeouts };
if (newTimeouts[componentId]) {
clearTimeout(newTimeouts[componentId]);
delete newTimeouts[componentId];
}
return {
componentDrafts: newDrafts,
componentDraftDirty: newDirty,
saveTimeouts: newTimeouts,
};
});
},
// Rename a component with optimistic update (rolls back on failure)
renameComponent: async (id, newName) => {
const previousName = get().components.find((c) => c.id === id)?.name;
set((state) => ({
components: state.components.map((c) => (c.id === id ? { ...c, name: newName } : c)),
}));
try {
const response = await fetch(`/ycode/api/components/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName }),
});
const result = await response.json();
if (result.error) throw new Error(result.error);
set((state) => ({
components: state.components.map((c) => (c.id === id ? result.data : c)),
}));
} catch (error) {
console.error('Failed to rename component:', error);
if (previousName !== undefined) {
set((state) => ({
components: state.components.map((c) => (c.id === id ? { ...c, name: previousName } : c)),
error: 'Failed to rename component',
}));
}
}
},
// Get component by ID (convenience method)
getComponentById: (id) => {
return get().components.find((c) => c.id === id);
},
/**
* Create a component from a layer in a component draft.
*
* The action targets whichever variant the editor is currently focused on;
* extracting a sub-tree from one variant doesn't change the others.
*/
createComponentFromLayer: async (componentId, layerId, componentName) => {
const { componentDrafts, components } = get();
const variantDrafts = componentDrafts[componentId];
if (!variantDrafts) return null;
// Find the variant that actually contains the layer being extracted.
let activeVariantId: string | null = null;
let layers: Layer[] | null = null;
for (const [variantId, variantLayers] of Object.entries(variantDrafts)) {
if (findLayerById(variantLayers, layerId)) {
activeVariantId = variantId;
layers = variantLayers;
break;
}
}
if (!activeVariantId || !layers) return null;
const layerToCopy = findLayerById(layers, layerId);
if (!layerToCopy) return null;
// Regenerate IDs so the component's internal layers don't collide with
// the instance layer that keeps the original id in the parent tree.
const regeneratedLayer = regenerateIdsWithInteractionRemapping(layerToCopy);
// Strip CMS bindings that won't be valid inside a standalone component
const cleanedLayers = cleanLayersForComponentCreation([regeneratedLayer]);
const newComponent = await createComponentViaApi(componentName, cleanedLayers);
if (!newComponent) return null;
// Add to local store
set((state) => ({
components: [newComponent, ...state.components],
}));
// Replace the original layer with the new component instance in the
// variant we extracted from.
const newLayers = replaceLayerWithComponentInstance(layers, layerId, newComponent.id);
get().updateComponentDraft(componentId, activeVariantId, newLayers);
// Generate thumbnail in the background (fire-and-forget)
triggerThumbnailGeneration(newComponent.id, newComponent.layers, [...components, newComponent]);
return newComponent.id;
},
/**
* Restore required components for undo operations
* Checks if components exist, restores them if deleted
*/
restoreComponents: async (componentIds) => {
const { loadComponents } = get();
const restoredIds: string[] = [];
for (const componentId of componentIds) {
try {
// Check if component exists/is deleted
const response = await fetch(`/ycode/api/components/${componentId}`);
const result = await response.json();
// If component doesn't exist or is deleted, restore it
if (!result.data || result.error) {
// Restore the component via API
const restoreResponse = await fetch(`/ycode/api/components/${componentId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'restore' }),
});
const restoreResult = await restoreResponse.json();
if (restoreResult.data) {
restoredIds.push(componentId);
}
}
} catch (error) {
console.error(`[Store] Failed to check/restore required component ${componentId}:`, error);
// Continue with other components
}
}
// Reload all components if any were restored
if (restoredIds.length > 0) {
await loadComponents();
}
return restoredIds;
},
// Add a text variable to a component
addTextVariable: async (componentId, name) => {
const component = get().getComponentById(componentId);
if (!component) return null;
const variableId = generateId('cpv'); // CPV = Component Variable
const newVariable = { id: variableId, name };
const updatedVariables = [...(component.variables || []), newVariable];
try {
const response = await fetch(`/ycode/api/components/${componentId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variables: updatedVariables }),
});
const result = await response.json();
if (result.error) {
console.error('Failed to add text variable:', result.error);
return null;
}
// Update local state
set((state) => ({
components: state.components.map((c) =>
c.id === componentId ? { ...c, variables: updatedVariables } : c
),
}));
return variableId;
} catch (error) {
console.error('Failed to add text variable:', error);
return null;
}
},
addRichTextVariable: async (componentId, name) => {
const component = get().getComponentById(componentId);
if (!component) return null;