( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ
I have analyzed the collaboration features across `index.php`, `brand.js`, and the core logic files in `brandSync/js/`.
Here is a breakdown of how the collaboration system works:
### 1. Architecture Overview
The system uses a **hybrid approach** combining real-time WebSockets with HTTP polling fallback and backend persistence.
* **Entry Point**: [index.php](file:///c:\wamp64\www\thebrand\wow2\index.php#L325) initializes the collaboration via the `initBrandCollab` function.
* **UI Status**: [brand.js](file:///c:\wamp64\www\thebrand\wow2\js\unminified\brand.js#L11) manages the "Connected", "Saving...", and "User joined" notifications via `window.BrandLayoutStatus`.
* **Core Logic**: Split into two classes:
* **Base Layer (`CanvasCollaboration`)**: Handles WebSockets, real-time events, and cursor tracking ([canvas-sync.js](file:///c:\wamp64\www\thebrand\wow2\brandSync\js\canvas-sync.js)).
* **Enhanced Layer (`EnhancedCanvasCollaboration`)**: Extends the base layer to add persistence (Load/Save), Auto-Save, Undo/Redo, and Polling ([canvas-enhanced.js](file:///c:\wamp64\www\thebrand\wow2\brandSync\js\canvas-enhanced.js)).
### 2. Key Features & Implementation Details
#### **A. Real-Time Sync (`canvas-sync.js`)**
* **WebSockets**: Tries to connect to `/ws` or port `8080`.
* **Object Sync**: Listens for Fabric.js events (`object:added`, `object:modified`, `object:removed`) and broadcasts them.
* **Cursor Tracking**: Throttles mouse movements (50ms) and broadcasts coordinates to show colored cursors for other users.
* **Loop Prevention**: Uses an `isLocalChange` flag to distinguish between user actions and incoming remote updates to avoid infinite loops.
#### **B. Persistence & Reliability (`canvas-enhanced.js`)**
* **Backend Storage**: Interacts with `api/canvas-handler.php` to load initial state and save changes.
* **Auto-Save**: Automatically saves changes every 30 seconds if there are pending changes.
* **Polling Fallback**: If WebSockets fail, it switches to "long polling" (checking for changes every 2.5s - 12s depending on activity).
* **Undo/Redo**: Maintains a local history stack (max 50 steps) for undo/redo functionality.
#### **C. Integration (`index.php`)**
* **Initialization**: Waits for `fabric` and `brandCanvas` to be ready before starting.
* **Session Context**: Passes `userId`, `themeid`, and `pageId` to the collaboration instance.
* **UI Wiring**: Connects collaboration events (join/leave, save status) to the UI via `wireBrandCollabUI`.
### 3. Data Flow
1. **User Action**: User moves an object on canvas.
2. **Capture**: `object:modified` event fires.
3. **Broadcast**: `CanvasCollaboration` sends a JSON payload via WebSocket.
4. **Persist**: `EnhancedCanvasCollaboration` queues the change for the next HTTP Auto-Save.
5. **Remote Update**: Other users receive the WebSocket message, `applyRemoteChange` updates their canvas, and `isLocalChange` ensures they don't echo it back.
### 4. Backend Analysis (Added)
I have further analyzed the backend components to complete the picture:
#### **D. API Backend (`api/canvas-handler.php`)**
* **File Storage**: Saves full canvas states as JSON files in `../uploads/` with the naming pattern `theme_{themeid}_{userId}_{pageId}.json`.
* **Change Recording**: Logs individual actions (add/modify/remove) to a `canvas_changes` database table. This supports the polling mechanism and potential history replay.
* **Endpoints**:
* `save`: Saves the current canvas JSON to disk.
* `load`: Retrieves the canvas JSON from disk.
* `record_change`: Inserts a record into the database.
* `get_changes`: Retrieves recent changes for polling clients.
#### **E. WebSocket Server (`websocket/server.php`)**
* **Technology**: Built with **Ratchet** (PHP WebSocket library), running on port **8080**.
* **Room Management**: Users are grouped into rooms based on `themeid` and `page_id`.
* **State Distribution**: When a user joins, the server fetches the latest state (from DB/File) and sends it immediately.
* **Direct DB Integration**: The WebSocket server connects directly to the MySQL database (`thebrand`) to record changes as they happen, ensuring consistency between real-time and persisted data.
* **Rate Limiting**: Implements a limit of 5000 messages per minute per user to prevent abuse.
I am now fully familiar with the collaboration stack and ready for your next tasks.