fix(crdt): sync groups and bgConfig via Yjs (Issue #6)

This commit is contained in:
2026-06-29 23:42:03 +02:00
parent cf62a777d2
commit 8493138b4b
3 changed files with 167 additions and 4 deletions
+44 -2
View File
@@ -266,7 +266,14 @@ const CADEditor: React.FC<CADEditorProps> = ({ projectId, token, onNavigateBack
setDataLoaded(true);
// Push initial data to Yjs CRDT after load
if (collab.status === 'connected') {
collab.loadFromState({ elements: data.elements, layers: data.layers, blocks: data.blocks });
const bgConfigs = bgConfig ? [bgConfig] : [];
collab.loadFromState({
elements: data.elements,
layers: data.layers,
blocks: data.blocks,
groups,
bgConfigs,
});
}
} catch (err) {
console.error('Failed to load project:', err);
@@ -316,8 +323,43 @@ const CADEditor: React.FC<CADEditorProps> = ({ projectId, token, onNavigateBack
collab.blocks.every((b, i) => b.id === blocks[i]?.id);
if (!sameBlocks) setBlocks(collab.blocks);
}
// Sync groups from remote → local
if (collab.groups.length > 0) {
const sameGroups = collab.groups.length === groups.length &&
collab.groups.every((g, i) => g.id === groups[i]?.id);
if (!sameGroups) setGroups(collab.groups);
}
// Sync bgConfig from remote → local
if (collab.bgConfigs.length > 0) {
const remoteBg = collab.bgConfigs[0];
if (!bgConfig || remoteBg.src !== bgConfig.src || remoteBg.scale !== bgConfig.scale ||
remoteBg.offsetX !== bgConfig.offsetX || remoteBg.offsetY !== bgConfig.offsetY ||
remoteBg.visible !== bgConfig.visible || remoteBg.opacity !== bgConfig.opacity) {
setBgConfig(remoteBg);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [collab.elements, collab.layers, collab.blocks, collab.status]);
}, [collab.elements, collab.layers, collab.blocks, collab.groups, collab.bgConfigs, collab.status]);
// Sync local → remote: push local groups to Yjs when groups change
React.useEffect(() => {
if (collab.status !== 'connected') return;
for (const group of groups) {
collab.setGroup(group);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [groups, collab.status]);
// Sync local → remote: push local bgConfig to Yjs when bgConfig changes
React.useEffect(() => {
if (collab.status !== 'connected') return;
if (bgConfig) {
collab.setBgConfig(bgConfig.name || 'default', bgConfig);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [bgConfig, collab.status]);
const handleElementCreated = useCallback((el: CADElement) => {
const elWithLayer = el.layerId ? el : { ...el, layerId: activeLayerId };