A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
import React, { useRef, useEffect, useCallback, useState } from 'react';
import {
AnimationTimeline,
BrushSettings,
CanvasColorMode,
CanvasDimensions,
DocumentTab,
LayerItem,
hasTileBackedLayer,
} from '../types/editor';
import {
CollabPeer,
CollabPeerCamera,
CollabSharedBrushSnapshot,
LayerActionMessage,
LayerClearableField,
LayerMaskDataMessage,
LayerTreeSyncMessage,
LayerUpdateMessage,
MultiplayerMessage,
StrokeChunkMessage,
StrokeFinishMessage,
StrokeStartMessage,
WireLayerItem,
} from '../types/multiplayer';
import { PerspectiveRuler, StraightRuler } from '../types/perspective';
import { ResizeCanvasOptions } from '../types/settings';
import { RemoteTileBatchInfo, useMultiplayer } from './useMultiplayer';
import { getNextCollabLayerName } from './useLayerManager';
import { multiplayerService } from '../services/multiplayerService';
import {
deepEqualWireValue,
diffWireLayerTrees,
serializeLayerForWire,
serializeLayersForWireCached,
} from '../utils/collabSyncUtils';
import {
canDeleteLayer,
canEditLayer,
canMutateCanvas,
canToggleLayerOwnerLock,
filterDeletableLayerIds,
peerIdEquals,
} from '../utils/collabPermissions';
import {
hydrateBrushSettingsForLocalUse,
onBrushAssetReady,
onBrushAssetRegistered,
} from '../utils/brushAssetSync';
import {
buildCameraSyncSnapshot,
buildSaveableCspBrush,
buildTryBrushSettings,
computeFollowedCameraTransform,
hasSignificantCameraDelta,
resolveBrushDisplayName,
resolveShareableBrushTool,
stepInterpolatedFollowCamera,
} from '../utils/collabFeatures';
import { saveCustomBrush } from '../utils/brushStorage';
import {
NativeVectorStrokePath,
clearNativeLayer,
nativeCollabRemotePeerDispose,
nativeCollabRemoteStrokeChunk,
nativeCollabRemoteStrokeDispose,
nativeCollabRemoteStrokeFinish,
nativeCollabRemoteStrokeStart,
nativeRasterizeVectorLayer,
setNativeCollabPointsEnabled,
} from '../utils/nativeEngineBridge';
import {
documentStoreActions,
toolStoreActions,
uiStoreActions,
useDocumentStore,
useToolStore,
} from '../stores';
import { PushHistoryStepFn } from './drawing/types';
import type { CanvasNavigationHandle } from './useCanvasNavigation';
import { t, td } from '../i18n';
function normalizeAnimForSync(
tl: AnimationTimeline | null,
prevSynced: AnimationTimeline | null
): AnimationTimeline | null {
if (!tl) return null;
// Suppress per-tick currentFrame broadcasts during local playback preview
const effectiveFrame =
tl.isPlaying && prevSynced ? prevSynced.currentFrame : tl.currentFrame;
return {
...tl,
currentFrame: effectiveFrame,
isPlaying: false,
};
}
export interface UseCollabSyncParams {
hasOpenDocument: boolean;
dimensions: CanvasDimensions;
colorMode: CanvasColorMode;
layers: LayerItem[];
activeLayerId: string;
selectedLayerIds: string[];
perspectiveRuler?: PerspectiveRuler | null;
straightRuler?: StraightRuler | null;
animationTimeline?: AnimationTimeline | null;
pushHistoryStepRef: React.MutableRefObject<PushHistoryStepFn | null>;
selectiveUndoRef: React.MutableRefObject<
(peerId?: string | number, strokeId?: string) => unknown
>;
resetZoomAndCenter: (dims?: CanvasDimensions) => void;
navigation?: CanvasNavigationHandle;
viewportRef?: React.RefObject<HTMLDivElement | null>;
resetHistory?: (targetDocumentId?: string) => void;
setLayers: React.Dispatch<React.SetStateAction<LayerItem[]>>;
setActiveLayerId: (id: string) => void;
toggleLock: (id: string) => void;
addLayer: (
type?: 'raster' | 'folder' | 'vector',
parentId?: string | null,
customName?: string,
customId?: string,
selectNew?: boolean
) => LayerItem;
addRemoteLayer: (
layerItem: LayerItem | WireLayerItem,
insertIndex?: number,
onCommitted?: (nextLayers: LayerItem[]) => void
) => void;
deleteLayer: (id: string) => void;
deleteRemoteLayer: (id: string, onCommitted?: (nextLayers: LayerItem[]) => void) => void;
applyRemoteLayerUpdate: (
layerId: string,
patch: Partial<WireLayerItem>,
clearedFields?: LayerClearableField[],
onCommitted?: (nextLayers: LayerItem[]) => void
) => void;
applyRemoteLayerTree: (
wireLayers: WireLayerItem[],
removedLayerIds?: string[],
onCommitted?: (nextLayers: LayerItem[]) => void
) => void;
applyRemoteMaskData: (
msg: LayerMaskDataMessage,
onCommitted?: (nextLayers: LayerItem[]) => void
) => void;
deleteSelectedLayers: () => void;
groupSelectedLayers: () => void;
syncRemoteDocument: (
layers: Array<LayerItem | WireLayerItem>,
assignedLayerId?: string,
targetDocumentId?: string,
syncDims?: CanvasDimensions,
onCommitted?: (nextLayers: LayerItem[]) => void
) => void;
resizeCanvas?: (newDims: CanvasDimensions, options: ResizeCanvasOptions) => void;
renameLayer: (id: string, newName: string) => void;
toggleVisibility: (id: string) => void;
setOpacity: (id: string, opacity: number) => void;
clearActiveLayer: () => void;
updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
showToast: (msg: string) => void;
}
export function useCollabSync({
hasOpenDocument,
dimensions,
colorMode,
layers,
activeLayerId,
selectedLayerIds,
perspectiveRuler = null,
straightRuler = null,
animationTimeline = null,
pushHistoryStepRef,
selectiveUndoRef,
resetZoomAndCenter,
navigation,
viewportRef,
resetHistory,
setLayers,
setActiveLayerId,
toggleLock,
addLayer,
addRemoteLayer,
deleteLayer,
deleteRemoteLayer,
applyRemoteLayerUpdate,
applyRemoteLayerTree,
applyRemoteMaskData,
deleteSelectedLayers,
groupSelectedLayers,
syncRemoteDocument,
resizeCanvas,
renameLayer,
toggleVisibility,
setOpacity,
clearActiveLayer,
updateLayerThumbnail,
showToast,
}: UseCollabSyncParams) {
const pendingAssignedLayerIdRef = useRef<string | undefined>(undefined);
// Track active remote peer GPU draft strokes (rendered directly by Rust ink-engine DX12 compositor)
const activeRemoteStrokesRef = useRef<
Map<string, { peerId: string | number; layerId: string }>
>(new Map());
const hasPendingTilesForLayerRef = useRef<(layerId: string) => boolean>(() => false);
const dimensionsRef = useRef(dimensions);
dimensionsRef.current = dimensions;
const layersRef = useRef(layers);
layersRef.current = layers;
// Canonical last-synced snapshots to compute minimal diffs and prevent echo loops
const lastSyncedSourceLayersRef = useRef<LayerItem[]>([]);
const lastSyncedWireLayersRef = useRef<WireLayerItem[]>([]);
const wasConnectedRef = useRef(false);
const lastSyncedPerspectiveRef = useRef<PerspectiveRuler | null>(perspectiveRuler);
const lastSyncedStraightRef = useRef<StraightRuler | null>(straightRuler);
const lastSyncedAnimationRef = useRef<AnimationTimeline | null>(
normalizeAnimForSync(animationTimeline, null)
);
const markRemoteLayersSynced = useCallback((committedLayers: LayerItem[]) => {
const nextWire = serializeLayersForWireCached(
committedLayers,
lastSyncedSourceLayersRef.current,
lastSyncedWireLayersRef.current
);
lastSyncedSourceLayersRef.current = committedLayers;
lastSyncedWireLayersRef.current = nextWire;
}, []);
// Follow Camera state & refs
const [followingPeerId, setFollowingPeerId] = useState<string | number | null>(null);
const followingPeerIdRef = useRef<string | number | null>(null);
const followTargetCamRef = useRef<CollabPeerCamera | null>(null);
const followRafRef = useRef<number | null>(null);
const followLastTsRef = useRef<number>(0);
const lastBroadcastCamRef = useRef<Omit<CollabPeerCamera, 'updatedAt'> | null>(null);
const navigationRef = useRef(navigation);
navigationRef.current = navigation;
const viewportRefRef = useRef(viewportRef);
viewportRefRef.current = viewportRef;
// Grab Artist's Brush state & refs
const [grabbingPeerId, setGrabbingPeerId] = useState<string | number | null>(null);
const [activeGrabbedBrush, setActiveGrabbedBrush] = useState<{
peerId: string | number;
peerName: string;
brushName: string;
settings: BrushSettings;
} | null>(null);
const pendingBrushGrabRef = useRef<{
peerId: string | number;
fallbackTimer: ReturnType<typeof setTimeout> | null;
timeoutTimer: ReturnType<typeof setTimeout> | null;
} | null>(null);
const pendingAssetWaitCleanupsRef = useRef<Array<() => void>>([]);
const pendingAssetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const getLocalViewportSize = useCallback((): { width: number; height: number } => {
const vp = viewportRefRef.current?.current;
if (vp && vp.clientWidth > 0 && vp.clientHeight > 0) {
return { width: vp.clientWidth, height: vp.clientHeight };
}
if (typeof window !== 'undefined') {
return {
width: Math.max(300, window.innerWidth - 300),
height: Math.max(300, window.innerHeight - 80),
};
}
return { width: 1280, height: 720 };
}, []);
const clearFollowRaf = useCallback(() => {
if (followRafRef.current !== null) {
cancelAnimationFrame(followRafRef.current);
followRafRef.current = null;
}
}, []);
const clearPendingBrushTimers = useCallback(() => {
if (pendingBrushGrabRef.current) {
if (pendingBrushGrabRef.current.fallbackTimer !== null) {
clearTimeout(pendingBrushGrabRef.current.fallbackTimer);
}
if (pendingBrushGrabRef.current.timeoutTimer !== null) {
clearTimeout(pendingBrushGrabRef.current.timeoutTimer);
}
pendingBrushGrabRef.current = null;
}
for (const unsub of pendingAssetWaitCleanupsRef.current) {
try {
unsub();
} catch {
// ignore
}
}
pendingAssetWaitCleanupsRef.current = [];
if (pendingAssetTimeoutRef.current !== null) {
clearTimeout(pendingAssetTimeoutRef.current);
pendingAssetTimeoutRef.current = null;
}
}, []);
// Dispose any active remote GPU draft sessions, Follow Camera loop & brush waiters on unmount
useEffect(() => {
return () => {
clearFollowRaf();
clearPendingBrushTimers();
for (const [strokeId, meta] of activeRemoteStrokesRef.current.entries()) {
void nativeCollabRemoteStrokeDispose(String(meta.peerId), strokeId);
}
activeRemoteStrokesRef.current.clear();
};
}, [clearFollowRaf, clearPendingBrushTimers]);
const broadcastMyCamera = useCallback(
(immediate = false) => {
const nav = navigationRef.current;
if (!nav || !multiplayerService.isConnected()) return;
const { width, height } = getLocalViewportSize();
const snap = buildCameraSyncSnapshot(
nav.getCameraState(),
width,
height,
dimensionsRef.current
);
if (!immediate && !hasSignificantCameraDelta(lastBroadcastCamRef.current, snap)) {
return;
}
lastBroadcastCamRef.current = snap;
multiplayerService.sendCameraSync(snap, immediate);
},
[getLocalViewportSize]
);
const ensureFollowGlideLoop = useCallback(() => {
if (followRafRef.current !== null) return;
followLastTsRef.current =
typeof performance !== 'undefined' ? performance.now() : Date.now();
const step = (now: number) => {
followRafRef.current = null;
const nav = navigationRef.current;
const targetCam = followTargetCamRef.current;
if (!followingPeerIdRef.current || !targetCam || !nav?.setCameraLive) {
return;
}
const dt = Math.max(0.001, (now - followLastTsRef.current) / 1000);
followLastTsRef.current = now;
const { width, height } = getLocalViewportSize();
const { next, settled } = stepInterpolatedFollowCamera(
nav.getCameraState(),
targetCam,
width,
height,
dimensionsRef.current,
dt
);
nav.setCameraLive(next, settled, 'programmatic');
if (!settled) {
followRafRef.current = requestAnimationFrame(step);
}
};
if (typeof requestAnimationFrame === 'function') {
followRafRef.current = requestAnimationFrame(step);
} else {
const nav = navigationRef.current;
const targetCam = followTargetCamRef.current;
if (nav?.setCameraLive && targetCam) {
const { width, height } = getLocalViewportSize();
const target = computeFollowedCameraTransform(
targetCam,
width,
height,
dimensionsRef.current
);
nav.setCameraLive(target, true, 'programmatic');
}
}
}, [getLocalViewportSize]);
const handleRemoteCameraSync = useCallback(
(peerId: string | number, camera: CollabPeerCamera) => {
if (
followingPeerIdRef.current !== null &&
peerIdEquals(followingPeerIdRef.current, peerId)
) {
followTargetCamRef.current = camera;
ensureFollowGlideLoop();
}
},
[ensureFollowGlideLoop]
);
const handleCameraSyncRequest = useCallback(() => {
broadcastMyCamera(true);
}, [broadcastMyCamera]);
const getLocalShareableBrush = useCallback((): {
brushSettings: BrushSettings;
tool: 'brush' | 'decoration';
brushName: string;
} => {
const toolState = useToolStore.getState();
const isDirectPaint = toolState.tool === 'brush' || toolState.tool === 'decoration';
const bs = isDirectPaint
? toolState.brushSettings
: toolState.lastPaintTool === 'decoration' && toolState.lastDecorationSettings
? toolState.lastDecorationSettings
: toolState.lastBrushSettings || toolState.brushSettings;
const tool = resolveShareableBrushTool(
isDirectPaint ? toolState.tool : toolState.lastPaintTool,
bs.preset
);
const brushName = resolveBrushDisplayName(bs);
return { brushSettings: bs, tool, brushName };
}, []);
const handleBrushRequest = useCallback(
(requesterPeerId: string | number) => {
const { brushSettings, tool, brushName } = getLocalShareableBrush();
multiplayerService.sendBrushShare(brushSettings, tool, brushName, {
targetPeerId: requesterPeerId,
explicit: false,
forceAssets: true,
});
},
[getLocalShareableBrush]
);
const applyGrabbedBrushSnapshot = useCallback(
(snapshot: CollabSharedBrushSnapshot) => {
clearPendingBrushTimers();
const commitApply = () => {
clearPendingBrushTimers();
const { hydrated } = hydrateBrushSettingsForLocalUse(
snapshot.brushSettings,
snapshot.brushAssetRefs
);
const toolState = useToolStore.getState();
const trySettings = buildTryBrushSettings({
hydratedSettings: hydrated,
brushAssetRefs: snapshot.brushAssetRefs,
peerId: snapshot.peerId,
peerName: snapshot.peerName,
brushName: snapshot.brushName,
localPrimaryColor: toolState.primaryColor,
localSecondaryColor: toolState.secondaryColor,
localIsTransparentInk: toolState.isTransparentColor,
});
toolStoreActions.applySharedBrush(trySettings, snapshot.tool);
setActiveGrabbedBrush({
peerId: snapshot.peerId,
peerName: snapshot.peerName,
brushName: snapshot.brushName,
settings: trySettings,
});
setGrabbingPeerId(null);
showToast(
t('Trying {peerName}\'s "{brushName}" brush', {
peerName: snapshot.peerName,
brushName: td(snapshot.brushName),
})
);
};
const { missingHashes, pendingHashes } = hydrateBrushSettingsForLocalUse(
snapshot.brushSettings,
snapshot.brushAssetRefs
);
for (const hash of missingHashes) {
multiplayerService.sendBrushAssetRequest(hash, snapshot.peerId);
}
// In headless environments without Image(), wait for binary registration instead of DOM Image decode
const isHeadless = typeof Image === 'undefined';
const hashesToWait = isHeadless
? new Set<string>(missingHashes)
: new Set<string>([...missingHashes, ...pendingHashes]);
if (hashesToWait.size === 0) {
commitApply();
return;
}
for (const hash of hashesToWait) {
const onDone = () => {
hashesToWait.delete(hash);
if (hashesToWait.size === 0) {
commitApply();
}
};
const unsub = isHeadless
? onBrushAssetRegistered(hash, onDone)
: onBrushAssetReady(hash, onDone);
pendingAssetWaitCleanupsRef.current.push(unsub);
}
pendingAssetTimeoutRef.current = setTimeout(() => {
commitApply();
}, 2500);
},
[clearPendingBrushTimers, showToast]
);
const handleRemoteBrushShare = useCallback(
(snapshot: CollabSharedBrushSnapshot) => {
if (
pendingBrushGrabRef.current &&
peerIdEquals(pendingBrushGrabRef.current.peerId, snapshot.peerId)
) {
applyGrabbedBrushSnapshot(snapshot);
}
},
[applyGrabbedBrushSnapshot]
);
const disposePeerStrokeSessions = useCallback((peerId: string | number) => {
const peerKey = String(peerId);
for (const [strokeId, meta] of activeRemoteStrokesRef.current.entries()) {
if (String(meta.peerId) === peerKey) {
activeRemoteStrokesRef.current.delete(strokeId);
}
}
void nativeCollabRemotePeerDispose(peerKey);
}, []);
const disposeLayerAwaitingSessions = useCallback((layerId: string) => {
for (const [strokeId, meta] of activeRemoteStrokesRef.current.entries()) {
if (meta.layerId === layerId) {
void nativeCollabRemoteStrokeDispose(String(meta.peerId), strokeId);
activeRemoteStrokesRef.current.delete(strokeId);
}
}
}, []);
const disposePeerSessions = useCallback(
(peerId: string | number) => {
disposePeerStrokeSessions(peerId);
if (
followingPeerIdRef.current !== null &&
peerIdEquals(followingPeerIdRef.current, peerId)
) {
clearFollowRaf();
followTargetCamRef.current = null;
followingPeerIdRef.current = null;
setFollowingPeerId(null);
}
if (
pendingBrushGrabRef.current &&
peerIdEquals(pendingBrushGrabRef.current.peerId, peerId)
) {
clearPendingBrushTimers();
setGrabbingPeerId(null);
}
},
[clearFollowRaf, clearPendingBrushTimers, disposePeerStrokeSessions]
);
const handleRemoteStrokeStart = useCallback(
(msg: StrokeStartMessage) => {
const peerKey = String(msg.peerId);
disposePeerStrokeSessions(msg.peerId);
activeRemoteStrokesRef.current.set(msg.strokeId, {
peerId: msg.peerId,
layerId: msg.layerId,
});
const bs = msg.brushSettings;
void nativeCollabRemoteStrokeStart({
peerId: peerKey,
strokeId: msg.strokeId,
layerId: msg.layerId,
color: bs?.color || '#000000',
size: Math.max(0.5, bs?.size ?? 10),
opacity: Math.max(0.01, Math.min(1, bs?.opacity ?? 1)),
hardness: Math.max(0, Math.min(1, bs?.hardness ?? 0.9)),
isEraser: msg.tool === 'eraser' || Boolean(bs?.isTransparentInk),
usePressureSize: bs?.usePressure !== false,
});
if (msg.startPoint) {
void nativeCollabRemoteStrokeChunk(peerKey, msg.strokeId, [
{
x: msg.startPoint.x,
y: msg.startPoint.y,
pressure: msg.startPoint.pressure ?? 0.5,
},
]);
}
},
[disposePeerStrokeSessions]
);
const handleRemoteStrokeChunk = useCallback((msg: StrokeChunkMessage) => {
if (!msg.points || msg.points.length === 0) return;
void nativeCollabRemoteStrokeChunk(
String(msg.peerId),
msg.strokeId,
msg.points.map((p) => ({
x: p.x,
y: p.y,
pressure: p.pressure ?? 0.5,
}))
);
}, []);
const handleRemoteStrokeFinish = useCallback(
(msg: StrokeFinishMessage) => {
const peerKey = String(msg.peerId);
if (msg.endPoint) {
void nativeCollabRemoteStrokeChunk(peerKey, msg.strokeId, [
{
x: msg.endPoint.x,
y: msg.endPoint.y,
pressure: msg.endPoint.pressure ?? 0.5,
},
]);
}
// Vector strokes commit via native Rust vector rasterizer; raster strokes commit via CODE_TILE_DELTA
if (msg.vectorStroke) {
let targetLayer = layersRef.current.find((l) => l.id === msg.layerId);
if (!targetLayer) {
targetLayer = layersRef.current.find(
(l) => l.type === 'vector' && l.id.includes(peerKey)
);
}
const dims = dimensionsRef.current;
if (targetLayer && targetLayer.type === 'vector' && dims.width > 0 && dims.height > 0) {
const targetLayerId = targetLayer.id;
const beforeStrokes = [...(targetLayer.vectorStrokes || [])];
const afterStrokes = [...beforeStrokes, msg.vectorStroke];
targetLayer.vectorStrokes = afterStrokes;
lastSyncedWireLayersRef.current = lastSyncedWireLayersRef.current.map((wl) =>
wl.id === targetLayerId ? { ...wl, vectorStrokes: afterStrokes } : wl
);
const nativePaths: NativeVectorStrokePath[] = afterStrokes
.filter((s) => !s.deleted && s.knots && s.knots.length > 0)
.map((s) => ({
id: s.id,
points: s.knots.map((k) => ({
x: k.x,
y: k.y,
pressure: k.pressure ?? 0.5,
width: k.width,
})),
color: s.color || '#000000',
size: s.baseWidth || 4,
opacity: s.opacity ?? 1,
hardness: 0.9,
closed: Boolean(s.closed),
}));
void nativeRasterizeVectorLayer(targetLayerId, nativePaths, false).then(() => {
updateLayerThumbnail(targetLayerId, true);
});
const b = msg.vectorStroke.bounds;
const vPad = Math.ceil(Math.max(16, msg.vectorStroke.baseWidth || 10));
const vx = b ? Math.max(0, Math.floor(b.minX - vPad)) : 0;
const vy = b ? Math.max(0, Math.floor(b.minY - vPad)) : 0;
const vw = b
? Math.max(0, Math.min(dims.width, Math.ceil(b.maxX + vPad)) - vx)
: dims.width;
const vh = b
? Math.max(0, Math.min(dims.height, Math.ceil(b.maxY + vPad)) - vy)
: dims.height;
pushHistoryStepRef.current?.(
'brush',
t('Remote Vector Stroke'),
null,
null,
targetLayerId,
vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : undefined,
undefined,
{ before: beforeStrokes, after: afterStrokes },
msg.peerId,
msg.strokeId
);
}
activeRemoteStrokesRef.current.delete(msg.strokeId);
void nativeCollabRemoteStrokeDispose(peerKey, msg.strokeId);
return;
}
const expectedTiles =
typeof msg.expectedTileCount === 'number' && msg.expectedTileCount >= 0
? msg.expectedTileCount
: 1;
activeRemoteStrokesRef.current.delete(msg.strokeId);
void nativeCollabRemoteStrokeFinish(peerKey, msg.strokeId, expectedTiles);
},
[pushHistoryStepRef, updateLayerThumbnail]
);
const handleRemoteDocSync = useCallback(
(
syncDims: CanvasDimensions,
syncMode: CanvasColorMode,
syncLayers: WireLayerItem[],
assignedLayerId?: string,
roomName?: string,
syncPerspectiveRuler: PerspectiveRuler | null = null,
syncStraightRuler: StraightRuler | null = null,
syncAnimationTimeline: AnimationTimeline | null = null,
isReconnect: boolean = false
) => {
const existingActiveDocId = useDocumentStore.getState().activeDocumentId;
const newDocId =
isReconnect && existingActiveDocId && existingActiveDocId.startsWith('doc-collab-')
? existingActiveDocId
: `doc-collab-${Date.now()}`;
const effectiveAssignedId = assignedLayerId || pendingAssignedLayerIdRef.current;
pendingAssignedLayerIdRef.current = undefined;
const resolvedActiveLayerId =
isReconnect && activeLayerId && syncLayers.some((l) => l.id === activeLayerId)
? activeLayerId
: effectiveAssignedId && syncLayers.some((l) => l.id === effectiveAssignedId)
? effectiveAssignedId
: syncLayers.find(
(l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
)?.id ||
syncLayers[0]?.id ||
'layer-1';
const tabName = (roomName || '').trim() || t('Collab Session');
// Bind documentStore session BEFORE LZ4 BINARY_TILE / BINARY_MASK packets arrive
syncRemoteDocument(
syncLayers,
resolvedActiveLayerId,
newDocId,
syncDims,
markRemoteLayersSynced
);
// Prime document-state refs before updating store so subscribers do not echo back
const normalizedAnim = normalizeAnimForSync(syncAnimationTimeline, null);
lastSyncedPerspectiveRef.current = syncPerspectiveRuler;
lastSyncedStraightRef.current = syncStraightRuler;
lastSyncedAnimationRef.current = normalizedAnim;
documentStoreActions.setDimensions(syncDims);
documentStoreActions.setColorMode(syncMode);
const newDoc: DocumentTab = {
id: newDocId,
name: tabName,
dimensions: syncDims,
colorMode: syncMode,
layers: layersRef.current,
activeLayerId: resolvedActiveLayerId,
perspectiveRuler: syncPerspectiveRuler,
straightRuler: syncStraightRuler,
animation: normalizedAnim,
};
documentStoreActions.setDocuments([newDoc]);
documentStoreActions.setActiveDocumentId(newDocId);
documentStoreActions.setDocumentName(tabName);
documentStoreActions.setPerspectiveRuler(syncPerspectiveRuler, { recordHistory: false });
documentStoreActions.setStraightRuler(syncStraightRuler, { recordHistory: false });
documentStoreActions.setAnimationTimeline(normalizedAnim);
uiStoreActions.setAppView('workspace');
if (!isReconnect) {
requestAnimationFrame(() => {
resetZoomAndCenter(syncDims);
});
}
},
[activeLayerId, markRemoteLayersSynced, resetZoomAndCenter, syncRemoteDocument]
);
const handleRemoteAssignedLayer = useCallback(
(layerId: string) => {
pendingAssignedLayerIdRef.current = layerId;
setActiveLayerId(layerId);
},
[setActiveLayerId]
);
const handleRemoteJoinRequest = useCallback(
(peer: CollabPeer) => {
const layerName = getNextCollabLayerName(peer.name, layersRef.current);
const layerId = `layer-${peer.id}-1`;
const newLayer = addLayer('raster', null, layerName, layerId, false);
const ownedLayer: LayerItem = {
...newLayer,
ownerPeerId: peer.id,
ownerPeerName: peer.name,
};
setLayers((prev) => {
const next = prev.map((l) =>
l.id === ownedLayer.id
? { ...l, ownerPeerId: peer.id, ownerPeerName: peer.name }
: l
);
layersRef.current = next;
return next;
});
const updated = layersRef.current.some((l) => l.id === ownedLayer.id)
? layersRef.current.map((l) =>
l.id === ownedLayer.id ? { ...l, ownerPeerId: peer.id, ownerPeerName: peer.name } : l
)
: [ownedLayer, ...layersRef.current];
const insertIndex = updated.findIndex((l) => l.id === ownedLayer.id);
lastSyncedSourceLayersRef.current = updated;
lastSyncedWireLayersRef.current = updated.map(serializeLayerForWire);
multiplayerService.sendLayerAdd(ownedLayer, insertIndex >= 0 ? insertIndex : 0);
return {
assignedLayerId: layerId,
updatedLayers: updated,
};
},
[addLayer, setLayers]
);
const handleRemoteLayerAction = useCallback(
(msg: MultiplayerMessage) => {
if (msg.type === 'LAYER_TREE_SYNC') {
const treeMsg = msg as LayerTreeSyncMessage;
applyRemoteLayerTree(treeMsg.layers, treeMsg.removedLayerIds, markRemoteLayersSynced);
return;
}
if (msg.type === 'LAYER_UPDATE') {
const updMsg = msg as LayerUpdateMessage;
applyRemoteLayerUpdate(
updMsg.layerId,
updMsg.patch,
updMsg.clearedFields,
markRemoteLayersSynced
);
return;
}
const action = msg as LayerActionMessage;
if (action.type === 'LAYER_ADD') {
if (action.layerItem) {
addRemoteLayer(action.layerItem, action.insertIndex, markRemoteLayersSynced);
}
} else if (action.type === 'LAYER_DELETE') {
if (action.layerId) {
disposeLayerAwaitingSessions(action.layerId);
deleteRemoteLayer(action.layerId, markRemoteLayersSynced);
}
} else if (action.type === 'LAYER_CLEAR' && action.layerId) {
disposeLayerAwaitingSessions(action.layerId);
const layerId = action.layerId;
const target = layersRef.current.find((l) => l.id === layerId);
if (target?.type === 'vector') {
target.vectorStrokes = [];
lastSyncedWireLayersRef.current = lastSyncedWireLayersRef.current.map((wl) =>
wl.id === layerId ? { ...wl, vectorStrokes: [] } : wl
);
}
const docId = useDocumentStore.getState().activeDocumentId;
if (docId) {
void clearNativeLayer(docId, layerId, false).then(() => {
updateLayerThumbnail(layerId, true);
});
} else {
updateLayerThumbnail(layerId, true);
}
} else if (action.type === 'LAYER_RENAME') {
if (action.layerId && action.newName) {
applyRemoteLayerUpdate(
action.layerId,
{ name: action.newName },
undefined,
markRemoteLayersSynced
);
}
} else if (action.type === 'LAYER_VISIBILITY') {
if (action.layerId && action.visible !== undefined) {
applyRemoteLayerUpdate(
action.layerId,
{ visible: action.visible },
undefined,
markRemoteLayersSynced
);
}
} else if (action.type === 'LAYER_OPACITY') {
if (action.layerId && action.opacity !== undefined) {
applyRemoteLayerUpdate(
action.layerId,
{ opacity: action.opacity },
undefined,
markRemoteLayersSynced
);
}
}
},
[
addRemoteLayer,
deleteRemoteLayer,
disposeLayerAwaitingSessions,
applyRemoteLayerUpdate,
applyRemoteLayerTree,
markRemoteLayersSynced,
updateLayerThumbnail,
]
);
const handleRemoteMaskData = useCallback(
(msg: LayerMaskDataMessage) => {
applyRemoteMaskData(msg, markRemoteLayersSynced);
},
[applyRemoteMaskData, markRemoteLayersSynced]
);
const handleRemotePerspectiveRuler = useCallback((ruler: PerspectiveRuler | null) => {
lastSyncedPerspectiveRef.current = ruler;
documentStoreActions.setPerspectiveRuler(ruler, { recordHistory: false });
}, []);
const handleRemoteStraightRuler = useCallback((ruler: StraightRuler | null) => {
lastSyncedStraightRef.current = ruler;
documentStoreActions.setStraightRuler(ruler, { recordHistory: false });
}, []);
const handleRemoteAnimationSync = useCallback((timeline: AnimationTimeline | null) => {
const normalized = normalizeAnimForSync(timeline, null);
lastSyncedAnimationRef.current = normalized;
documentStoreActions.setAnimationTimeline(normalized);
const activeDocId = useDocumentStore.getState().activeDocumentId;
if (activeDocId) {
documentStoreActions.setDocuments((docs) =>
docs.map((d) => (d.id === activeDocId ? { ...d, animation: normalized } : d))
);
}
}, []);
const handleRemoteCanvasResize = useCallback(
(newDims: CanvasDimensions, options: ResizeCanvasOptions) => {
resizeCanvas?.(newDims, options);
documentStoreActions.setDimensions(newDims, useDocumentStore.getState().activeDocumentId);
resetZoomAndCenter(newDims);
resetHistory?.();
lastSyncedSourceLayersRef.current = layersRef.current;
lastSyncedWireLayersRef.current = layersRef.current.map(serializeLayerForWire);
showToast(
t('Canvas resized remotely to {width} × {height} px', {
width: newDims.width,
height: newDims.height,
})
);
},
[resizeCanvas, resetZoomAndCenter, resetHistory, showToast]
);
const handleRemoteTileApplied = useCallback(
(layerId: string, _batchInfo?: RemoteTileBatchInfo) => {
updateLayerThumbnail(layerId, false);
},
[updateLayerThumbnail]
);
const mp = useMultiplayer({
dimensions,
colorMode,
layers,
perspectiveRuler,
straightRuler,
animationTimeline,
onRemoteStrokeStart: handleRemoteStrokeStart,
onRemoteStrokeChunk: handleRemoteStrokeChunk,
onRemoteStrokeFinish: handleRemoteStrokeFinish,
onRemoteDocSync: handleRemoteDocSync,
onRemoteJoinRequest: handleRemoteJoinRequest,
onRemoteAssignedLayer: handleRemoteAssignedLayer,
onRemoteLayerAction: handleRemoteLayerAction,
onRemoteMaskData: handleRemoteMaskData,
onRemotePerspectiveRuler: handleRemotePerspectiveRuler,
onRemoteStraightRuler: handleRemoteStraightRuler,
onRemoteAnimationSync: handleRemoteAnimationSync,
onRemoteCanvasResize: handleRemoteCanvasResize,
onRemoteSelectiveUndo: (strokeId, peerId) => {
const pending = selectiveUndoRef.current(peerId, strokeId);
Promise.resolve(pending).then((undone: unknown) => {
const layerId =
undone && typeof undone === 'object' && 'layerId' in undone
? (undone as { layerId?: string }).layerId
: undefined;
if (!layerId) return;
const target = layersRef.current.find((l) => l.id === layerId);
if (target?.type === 'vector') {
lastSyncedWireLayersRef.current = lastSyncedWireLayersRef.current.map((wl) =>
wl.id === layerId ? { ...wl, vectorStrokes: target.vectorStrokes } : wl
);
}
});
},
onRemoteTileApplied: handleRemoteTileApplied,
onRemotePeerLeft: disposePeerSessions,
onRemoteCameraSync: handleRemoteCameraSync,
onCameraSyncRequest: handleCameraSyncRequest,
onBrushRequest: handleBrushRequest,
onRemoteBrushShare: handleRemoteBrushShare,
showToast,
});
hasPendingTilesForLayerRef.current = mp.hasPendingTilesForLayer;
const stopFollowing = useCallback(
(silent = false) => {
clearFollowRaf();
followTargetCamRef.current = null;
const prevId = followingPeerIdRef.current;
if (prevId === null) return;
const prevPeer = mp.peers.find((p) => peerIdEquals(p.id, prevId));
followingPeerIdRef.current = null;
setFollowingPeerId(null);
if (!silent) {
showToast(t('Stopped following {name}', { name: prevPeer?.name || t('participant') }));
}
},
[clearFollowRaf, mp.peers, showToast]
);
const followPeer = useCallback(
(peerId: string | number) => {
if (!mp.isConnected || peerIdEquals(peerId, mp.myPeer.id)) return;
const targetPeer = mp.peers.find((p) => peerIdEquals(p.id, peerId));
clearFollowRaf();
followingPeerIdRef.current = peerId;
setFollowingPeerId(peerId);
const cachedCam = mp.peerCamerasRef.current.get(String(peerId)) ?? null;
followTargetCamRef.current = cachedCam;
if (cachedCam) {
ensureFollowGlideLoop();
}
multiplayerService.sendCameraSyncRequest(peerId);
showToast(t("Following {name}'s camera", { name: targetPeer?.name || t('participant') }));
},
[
mp.isConnected,
mp.myPeer.id,
mp.peers,
mp.peerCamerasRef,
clearFollowRaf,
ensureFollowGlideLoop,
showToast,
]
);
const toggleFollowPeer = useCallback(
(peerId: string | number) => {
if (
followingPeerIdRef.current !== null &&
peerIdEquals(followingPeerIdRef.current, peerId)
) {
stopFollowing(false);
} else {
followPeer(peerId);
}
},
[followPeer, stopFollowing]
);
const grabPeerBrush = useCallback(
(peerId: string | number) => {
if (!mp.isConnected || peerIdEquals(peerId, mp.myPeer.id)) return;
clearPendingBrushTimers();
setGrabbingPeerId(peerId);
const fallbackTimer = setTimeout(() => {
const cached = mp.peerBrushesRef.current[String(peerId)];
if (cached && pendingBrushGrabRef.current && peerIdEquals(pendingBrushGrabRef.current.peerId, peerId)) {
applyGrabbedBrushSnapshot(cached);
}
}, 600);
const timeoutTimer = setTimeout(() => {
if (pendingBrushGrabRef.current && peerIdEquals(pendingBrushGrabRef.current.peerId, peerId)) {
const cached = mp.peerBrushesRef.current[String(peerId)];
if (cached) {
applyGrabbedBrushSnapshot(cached);
} else {
clearPendingBrushTimers();
setGrabbingPeerId(null);
showToast(t("Couldn't fetch that participant's brush yet — try again in a moment"));
}
}
}, 2800);
pendingBrushGrabRef.current = { peerId, fallbackTimer, timeoutTimer };
multiplayerService.sendBrushRequest(peerId);
},
[
mp.isConnected,
mp.myPeer.id,
mp.peerBrushesRef,
clearPendingBrushTimers,
applyGrabbedBrushSnapshot,
showToast,
]
);
const trySharedBrush = useCallback(
(snapshot: Omit<CollabSharedBrushSnapshot, 'updatedAt'>) => {
applyGrabbedBrushSnapshot({ ...snapshot, updatedAt: Date.now() });
},
[applyGrabbedBrushSnapshot]
);
const shareMyBrush = useCallback(() => {
if (!mp.isConnected) return;
const { brushSettings, tool, brushName } = getLocalShareableBrush();
const sent = multiplayerService.sendBrushShare(brushSettings, tool, brushName, {
explicit: true,
forceAssets: true,
});
if (sent) {
mp.appendLocalSharedBrushChat({
peerId: sent.peerId,
peerName: sent.peerName,
brushName: sent.brushName,
tool: sent.tool,
brushSettings: sent.brushSettings,
brushAssetRefs: sent.brushAssetRefs,
});
showToast(t('Shared "{name}" brush with the room', { name: td(brushName) }));
}
}, [mp.isConnected, mp.appendLocalSharedBrushChat, getLocalShareableBrush, showToast]);
const saveActiveGrabbedBrush = useCallback(async () => {
if (!activeGrabbedBrush) return;
const cspBrush = buildSaveableCspBrush(
activeGrabbedBrush.settings,
activeGrabbedBrush.settings.brushName || activeGrabbedBrush.brushName
);
await saveCustomBrush(cspBrush);
showToast(t('Saved "{name}" to Custom Brushes', { name: cspBrush.name }));
setActiveGrabbedBrush(null);
}, [activeGrabbedBrush, showToast]);
const dismissActiveGrabbedBrush = useCallback(() => {
setActiveGrabbedBrush(null);
}, []);
// Auto-hide the "Trying <Artist>'s Brush" banner if user switches to a different brush preset
useEffect(() => {
if (!activeGrabbedBrush) return;
const targetPreset = activeGrabbedBrush.settings.preset;
return useToolStore.subscribe(() => {
const curPreset = useToolStore.getState().brushSettings.preset;
if (curPreset !== targetPreset && curPreset !== 'tool-eraser') {
setActiveGrabbedBrush(null);
}
});
}, [activeGrabbedBrush]);
// Camera broadcast + auto-unfollow on user pan/zoom/rotate + resize re-projection
useEffect(() => {
if (!mp.isConnected) {
clearFollowRaf();
for (const [strokeId, meta] of activeRemoteStrokesRef.current.entries()) {
void nativeCollabRemoteStrokeDispose(String(meta.peerId), strokeId);
}
activeRemoteStrokesRef.current.clear();
followTargetCamRef.current = null;
followingPeerIdRef.current = null;
setFollowingPeerId(null);
lastBroadcastCamRef.current = null;
clearPendingBrushTimers();
setGrabbingPeerId(null);
return;
}
broadcastMyCamera(true);
if (!navigation) return;
return navigation.subscribeCamera((_cam, meta) => {
const source = meta?.source ?? 'user';
if (source === 'programmatic') return;
if (source === 'resize') {
if (followingPeerIdRef.current !== null && followTargetCamRef.current) {
const { width, height } = getLocalViewportSize();
const target = computeFollowedCameraTransform(
followTargetCamRef.current,
width,
height,
dimensionsRef.current
);
navigation.setCameraLive?.(target, true, 'programmatic');
} else {
broadcastMyCamera(false);
}
return;
}
// User manually panned/zoomed/rotated -> break free from Follow Camera cleanly
if (followingPeerIdRef.current !== null) {
stopFollowing(false);
}
broadcastMyCamera(false);
});
}, [
mp.isConnected,
navigation,
broadcastMyCamera,
clearFollowRaf,
clearPendingBrushTimers,
getLocalViewportSize,
stopFollowing,
]);
// Reactive full layer-tree & property diff broadcaster (catches every UI/menu/shortcut/auto-action mutation)
useEffect(() => {
if (!mp.isConnected) {
wasConnectedRef.current = false;
lastSyncedSourceLayersRef.current = [];
lastSyncedWireLayersRef.current = [];
return;
}
if (!wasConnectedRef.current) {
wasConnectedRef.current = true;
lastSyncedSourceLayersRef.current = layers;
lastSyncedWireLayersRef.current = layers.map(serializeLayerForWire);
return;
}
if (layers === lastSyncedSourceLayersRef.current) {
return;
}
const nextWire = serializeLayersForWireCached(
layers,
lastSyncedSourceLayersRef.current,
lastSyncedWireLayersRef.current
);
if (!canMutateCanvas(mp.myRole)) {
lastSyncedSourceLayersRef.current = layers;
lastSyncedWireLayersRef.current = nextWire;
return;
}
const prevWire = lastSyncedWireLayersRef.current;
lastSyncedSourceLayersRef.current = layers;
lastSyncedWireLayersRef.current = nextWire;
if (nextWire === prevWire) return;
const diff = diffWireLayerTrees(prevWire, nextWire);
if (diff.kind === 'none') return;
if (diff.kind === 'single-update') {
const patchKeys = Object.keys(diff.patch);
if (diff.clearedFields.length === 0 && patchKeys.length === 1) {
const onlyKey = patchKeys[0];
if (onlyKey === 'name' && typeof diff.patch.name === 'string') {
multiplayerService.sendLayerRename(diff.layerId, diff.patch.name);
} else if (onlyKey === 'visible' && typeof diff.patch.visible === 'boolean') {
multiplayerService.sendLayerVisibility(diff.layerId, diff.patch.visible);
} else if (onlyKey === 'opacity' && typeof diff.patch.opacity === 'number') {
multiplayerService.sendLayerOpacity(diff.layerId, diff.patch.opacity);
} else {
multiplayerService.sendLayerUpdate(diff.layerId, diff.patch);
}
} else {
multiplayerService.sendLayerUpdate(diff.layerId, diff.patch, diff.clearedFields);
}
if (diff.maskCreated) {
const target = layers.find((l) => l.id === diff.layerId);
if (target && (target.hasMask || target.maskCanvas)) {
multiplayerService.sendNativeLayerMask(target.id);
}
}
if (diff.rasterized) {
multiplayerService.streamNativeLayerTiles(diff.layerId);
}
return;
}
// Structural mutation: reorder, group, multi-delete, duplicate, merge, split frame folder, paste/import, batch toggle
const dirtyTileLayerIds: string[] = [];
for (const addedId of diff.addedLayerIds) {
const addedLayer = layers.find((l) => l.id === addedId);
if (
addedLayer &&
hasTileBackedLayer(addedLayer) &&
addedLayer.type !== 'text' &&
addedLayer.type !== 'balloon'
) {
dirtyTileLayerIds.push(addedId);
}
}
// Fast-path pure single-layer addition via granular LAYER_ADD (avoids broadcasting full tree
// and converges cleanly with concurrent reorders on other peers)
let sentGranularAdd = false;
if (
diff.addedLayerIds.length === 1 &&
diff.removedLayerIds.length === 0 &&
nextWire.length === prevWire.length + 1
) {
const addedId = diff.addedLayerIds[0];
const insertIndex = nextWire.findIndex((l) => l.id === addedId);
if (insertIndex >= 0) {
const remaining = nextWire.filter((l) => l.id !== addedId);
if (diffWireLayerTrees(prevWire, remaining).kind === 'none') {
multiplayerService.sendLayerAdd(nextWire[insertIndex], insertIndex);
sentGranularAdd = true;
}
}
}
if (!sentGranularAdd) {
multiplayerService.sendLayerTreeSync(nextWire, {
dirtyTileLayerIds,
removedLayerIds: diff.removedLayerIds,
});
}
for (const tileLayerId of dirtyTileLayerIds) {
multiplayerService.streamNativeLayerTiles(tileLayerId);
}
for (const maskLayerId of diff.maskCreatedIds) {
const maskLayer = layers.find((l) => l.id === maskLayerId);
if (maskLayer && (maskLayer.hasMask || maskLayer.maskCanvas)) {
multiplayerService.sendNativeLayerMask(maskLayer.id);
}
}
}, [layers, mp.isConnected, mp.myRole]);
// Only stream full committed stroke point arrays from Rust when multiplayer is connected
useEffect(() => {
void setNativeCollabPointsEnabled(Boolean(mp.isConnected));
return () => {
void setNativeCollabPointsEnabled(false);
};
}, [mp.isConnected]);
// Reactive document-level state broadcaster: Perspective Ruler, Straight Ruler, Animation Timeline
useEffect(() => {
const state = useDocumentStore.getState();
lastSyncedPerspectiveRef.current = state.perspectiveRuler;
lastSyncedStraightRef.current = state.straightRuler;
lastSyncedAnimationRef.current = normalizeAnimForSync(state.animationTimeline, null);
if (!mp.isConnected || !canMutateCanvas(mp.myRole)) return;
return useDocumentStore.subscribe(() => {
if (!multiplayerService.isConnected()) return;
const nextState = useDocumentStore.getState();
if (!deepEqualWireValue(nextState.perspectiveRuler, lastSyncedPerspectiveRef.current)) {
lastSyncedPerspectiveRef.current = nextState.perspectiveRuler;
multiplayerService.sendPerspectiveRulerSync(nextState.perspectiveRuler);
}
if (!deepEqualWireValue(nextState.straightRuler, lastSyncedStraightRef.current)) {
lastSyncedStraightRef.current = nextState.straightRuler;
multiplayerService.sendStraightRulerSync(nextState.straightRuler);
}
const normalizedAnim = normalizeAnimForSync(
nextState.animationTimeline,
lastSyncedAnimationRef.current
);
if (!deepEqualWireValue(normalizedAnim, lastSyncedAnimationRef.current)) {
lastSyncedAnimationRef.current = normalizedAnim;
multiplayerService.sendAnimationSync(normalizedAnim);
}
});
}, [mp.isConnected, mp.myRole]);
const isSessionActive = mp.isConnected || mp.isReconnecting;
const canEditLayerById = useCallback(
(layerId: string) => {
if (!isSessionActive) return { allowed: true };
const target = layersRef.current.find((l) => l.id === layerId);
return canEditLayer(target, mp.myPeer.id, mp.myRole);
},
[isSessionActive, mp.myPeer.id, mp.myRole]
);
const canDeleteLayerById = useCallback(
(layerId: string) => {
if (!isSessionActive) return { allowed: true };
return canDeleteLayer(layerId, layersRef.current, mp.myPeer.id, mp.myRole);
},
[isSessionActive, mp.myPeer.id, mp.myRole]
);
const canToggleOwnerLockById = useCallback(
(layerId: string) => {
if (!isSessionActive) return { allowed: true };
const target = layersRef.current.find((l) => l.id === layerId);
return canToggleLayerOwnerLock(target, mp.myPeer.id, mp.myRole);
},
[isSessionActive, mp.myPeer.id, mp.myRole]
);
const activeLayerObj = layers.find((l) => l.id === activeLayerId);
const canEditActiveLayer = !isSessionActive
? true
: canEditLayer(activeLayerObj, mp.myPeer.id, mp.myRole).allowed;
const prepareHostLayers = useCallback(
(finalHostName: string) => {
const hostPeerId = mp.myPeer.id;
// Stamp ownership synchronously so any subsequent renameLayer reads the stamped layersRef
const stamped = layersRef.current.map((l) => {
if (l.id === 'layer-bg' || l.id.startsWith('layer-bg')) return l;
if (l.ownerPeerId !== undefined) return l;
return { ...l, ownerPeerId: hostPeerId, ownerPeerName: finalHostName };
});
layersRef.current = stamped;
setLayers(stamped);
const defaultLayer =
stamped.find((l) => l.id === activeLayerId) ||
stamped.find(
(l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
);
if (
defaultLayer &&
(defaultLayer.name === 'Layer 1' ||
!defaultLayer.name.toLowerCase().startsWith(finalHostName.toLowerCase()))
) {
const hostLayerName = getNextCollabLayerName(
finalHostName,
stamped.filter((l) => l.id !== defaultLayer.id)
);
renameLayer(defaultLayer.id, hostLayerName);
}
},
[mp.myPeer.id, activeLayerId, renameLayer, setLayers]
);
const handleStartHosting = useCallback(
async (
roomName: string,
port: number,
hostNickname?: string,
isGlobal?: boolean,
onStatus?: (status: string) => void
) => {
if (!hasOpenDocument) {
showToast(t('Please create or open a canvas before hosting a session.'));
return false;
}
const finalHostName = (hostNickname || mp.myPeer.name || 'Artist').trim();
prepareHostLayers(finalHostName);
return await mp.startHosting(roomName, port, finalHostName, isGlobal, onStatus);
},
[hasOpenDocument, showToast, mp.myPeer.name, prepareHostLayers, mp.startHosting]
);
const handleStartWebRtcHosting = useCallback(
async (
roomName: string,
hostNickname?: string,
onStatus?: (status: string) => void
) => {
if (!hasOpenDocument) {
showToast(t('Please create or open a canvas before hosting a session.'));
return false;
}
const finalHostName = (hostNickname || mp.myPeer.name || 'Artist').trim();
prepareHostLayers(finalHostName);
return await mp.startWebRtcHosting(roomName, finalHostName, onStatus);
},
[hasOpenDocument, showToast, mp.myPeer.name, prepareHostLayers, mp.startWebRtcHosting]
);
const handleAddLayer = useCallback(
(type: 'raster' | 'folder' | 'vector' = 'raster') => {
if (isSessionActive && !canMutateCanvas(mp.myRole)) {
showToast(t('Viewers have read-only access'));
return;
}
const created =
isSessionActive && type === 'raster'
? addLayer('raster', null, getNextCollabLayerName(mp.myPeer.name, layersRef.current))
: addLayer(type);
if (isSessionActive && created) {
const ownerId = mp.myPeer.id;
const ownerName = mp.myPeer.name;
setLayers((prev) => {
const next = prev.map((l) =>
l.id === created.id ? { ...l, ownerPeerId: ownerId, ownerPeerName: ownerName } : l
);
layersRef.current = next;
return next;
});
}
},
[isSessionActive, mp.myRole, mp.myPeer.id, mp.myPeer.name, addLayer, setLayers, showToast]
);
const handleDeleteLayer = useCallback(
(id: string) => {
if (isSessionActive) {
const perm = canDeleteLayer(id, layersRef.current, mp.myPeer.id, mp.myRole);
if (!perm.allowed) {
showToast(
perm.reason ? td(perm.reason) : t('You do not have permission to delete this layer')
);
return;
}
}
deleteLayer(id);
},
[isSessionActive, mp.myPeer.id, mp.myRole, deleteLayer, showToast]
);
const handleDeleteSelectedLayers = useCallback(() => {
if (selectedLayerIds && selectedLayerIds.length > 1) {
if (isSessionActive) {
const { allowedIds, blockedReasons } = filterDeletableLayerIds(
selectedLayerIds,
layersRef.current,
mp.myPeer.id,
mp.myRole
);
if (allowedIds.length === 0) {
showToast(
blockedReasons[0] ? td(blockedReasons[0]) : t('Selected layers cannot be deleted')
);
return;
}
if (blockedReasons.length > 0) {
for (const allowedId of allowedIds) {
deleteLayer(allowedId);
}
showToast(
t('Deleted {deleted} layer(s); protected {protected} other user layer(s)', {
deleted: allowedIds.length,
protected: blockedReasons.length,
})
);
return;
}
}
deleteSelectedLayers();
showToast(t('Deleted {count} layers', { count: selectedLayerIds.length }));
} else {
handleDeleteLayer(activeLayerId);
}
}, [
selectedLayerIds,
isSessionActive,
mp.myPeer.id,
mp.myRole,
deleteLayer,
deleteSelectedLayers,
handleDeleteLayer,
activeLayerId,
showToast,
]);
const handleGroupSelectedLayers = useCallback(() => {
if (isSessionActive && !canMutateCanvas(mp.myRole)) {
showToast(t('Viewers have read-only access'));
return;
}
groupSelectedLayers();
showToast(t('Grouped layers into folder'));
}, [isSessionActive, mp.myRole, groupSelectedLayers, showToast]);
const handleToggleVisibility = useCallback(
(id: string) => {
if (isSessionActive) {
const perm = canEditLayerById(id);
if (!perm.allowed) {
showToast(perm.reason ? td(perm.reason) : t('Cannot modify this layer'));
return;
}
}
toggleVisibility(id);
},
[isSessionActive, canEditLayerById, toggleVisibility, showToast]
);
const handleSetOpacity = useCallback(
(id: string, opacity: number) => {
if (isSessionActive) {
const perm = canEditLayerById(id);
if (!perm.allowed) {
showToast(perm.reason ? td(perm.reason) : t('Cannot modify this layer'));
return;
}
}
setOpacity(id, opacity);
},
[isSessionActive, canEditLayerById, setOpacity, showToast]
);
const handleRenameLayer = useCallback(
(id: string, newName: string) => {
if (isSessionActive) {
const perm = canEditLayerById(id);
if (!perm.allowed) {
showToast(perm.reason ? td(perm.reason) : t('Cannot rename this layer'));
return;
}
}
renameLayer(id, newName);
},
[isSessionActive, canEditLayerById, renameLayer, showToast]
);
const handleToggleLock = useCallback(
(id: string) => {
if (isSessionActive) {
const perm = canEditLayerById(id);
if (!perm.allowed) {
showToast(perm.reason ? td(perm.reason) : t('Cannot modify lock on this layer'));
return;
}
}
toggleLock(id);
},
[isSessionActive, canEditLayerById, toggleLock, showToast]
);
const handleToggleOwnerLock = useCallback(
(id: string) => {
const target = layersRef.current.find((l) => l.id === id);
if (!target) return;
if (isSessionActive) {
const perm = canToggleLayerOwnerLock(target, mp.myPeer.id, mp.myRole);
if (!perm.allowed) {
showToast(perm.reason ? td(perm.reason) : t('Cannot toggle owner lock on this layer'));
return;
}
}
const isCurrentlyReserved =
target.reservedByPeerId !== undefined && target.reservedByPeerId !== '';
if (isCurrentlyReserved) {
setLayers((prev) =>
prev.map((l) => {
if (l.id !== id) return l;
const { reservedByPeerId: _id, reservedByPeerName: _name, ...rest } = l;
return rest;
})
);
showToast(t('Unlocked "{name}" for collaboration', { name: target.name }));
} else {
const lockPeerId =
mp.myRole === 'host' && target.ownerPeerId && !peerIdEquals(target.ownerPeerId, mp.myPeer.id)
? target.ownerPeerId
: mp.myPeer.id;
const lockPeerName =
mp.myRole === 'host' && target.ownerPeerId && !peerIdEquals(target.ownerPeerId, mp.myPeer.id)
? target.ownerPeerName || t('Owner')
: mp.myPeer.name;
setLayers((prev) =>
prev.map((l) =>
l.id === id
? {
...l,
ownerPeerId: l.ownerPeerId ?? lockPeerId,
ownerPeerName: l.ownerPeerName ?? lockPeerName,
reservedByPeerId: lockPeerId,
reservedByPeerName: lockPeerName,
}
: l
)
);
showToast(t('Locked "{name}" to {owner}', { name: target.name, owner: lockPeerName }));
}
},
[isSessionActive, mp.myPeer.id, mp.myPeer.name, mp.myRole, setLayers, showToast]
);
const handleClearActiveLayer = useCallback(() => {
if (isSessionActive) {
const perm = canEditLayerById(activeLayerId);
if (!perm.allowed) {
showToast(perm.reason ? td(perm.reason) : t('Cannot clear this layer'));
return;
}
}
const active = layersRef.current.find((l) => l.id === activeLayerId);
if (active?.type === 'vector') {
active.vectorStrokes = [];
}
clearActiveLayer();
if (mp.isConnected) {
multiplayerService.sendLayerClear(activeLayerId);
if (activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg')) {
multiplayerService.streamNativeLayerTiles(activeLayerId);
}
}
}, [isSessionActive, canEditLayerById, clearActiveLayer, mp.isConnected, activeLayerId, showToast]);
return {
...mp,
followingPeerId,
followPeer,
stopFollowing,
toggleFollowPeer,
grabbingPeerId,
grabPeerBrush,
trySharedBrush,
shareMyBrush,
activeGrabbedBrush,
saveActiveGrabbedBrush,
dismissActiveGrabbedBrush,
canEditActiveLayer,
canEditLayerById,
canDeleteLayerById,
canToggleOwnerLockById,
handleStartHosting,
handleStartWebRtcHosting,
handleAddLayer,
handleDeleteLayer,
handleDeleteSelectedLayers,
handleGroupSelectedLayers,
handleToggleVisibility,
handleSetOpacity,
handleRenameLayer,
handleToggleLock,
handleToggleOwnerLock,
handleClearActiveLayer,
};
}