Loading document parsing libraries...
# Client
Class
## About
`Client` keeps one `Editor` synchronized with a `Server` over WebSocket. It authenticates the user, opens the server's current document, sends local changes, receives remote changes, shares pointer and selection activity, and manages node locks.
## Event Definitions
| Name | Parameters | Return Type | Description |
| --- | :---: | :---: | --- |
| AccessChanged | documentID As String <br> access As GraffitiProEditor.CollaborationAccess | (None) | Raised when the server changes this client's access. With Read the editor becomes read-only. None means the server revoked the document: the editor's document is cleared and the connection ends. An empty documentID means the access of the connection itself changed. |
| Authenticated | userName As String <br> access As GraffitiProEditor.CollaborationAccess | (None) | Raised after connection authentication succeeds and reports the server-granted access level. |
| ConflictResolved | documentID As String <br> revision As Integer | (None) | Raised after a stale document revision is reconciled with the current server snapshot. |
| Connected | (None) | (None) | Raised when the built-in WebSocket transport completes its handshake. |
| Disconnected | (None) | (None) | Raised when the built-in WebSocket transport closes. |
| DocumentOpened | documentID As String <br> access As GraffitiProEditor.CollaborationAccess <br> revision As Integer | (None) | Raised after a document snapshot is authenticated, received, and applied to the attached editor. |
| DocumentsReceived | requestID As String <br> response As JSONItem | (None) | Raised when the server returns application-defined JSON document-list data for a request. |
| DocumentUpdated | documentID As String <br> revision As Integer <br> collaborator As GraffitiProEditor.Network.User | (None) | Raised after the client accepts a synchronized document revision. |
| Error | code As String <br> message As String | (None) | Raised when authentication, protocol validation, transport integration, or synchronization fails. |
| NodeLockDenied | nodeID As String <br> collaborator As GraffitiProEditor.Network.User | (None) | Raised when another collaborator already owns the requested node lock. |
| OfflineChangesDetected | documentID As String <br> localSnapshot As String <br> serverSnapshot As String | (None) | Raised when a locally retained snapshot differs from the server snapshot opened for the document. |
| PresenceReceived | collaborator As GraffitiProEditor.Network.User | (None) | Raised when current pointer, selection, and editing presence arrives from another collaborator. |
| UpgradeRequired | documentID As String <br> minimumDocumentVersion As Integer | (None) | Raised when the document requires a newer document format than this client supports. |
## Methods
| Name | Parameters | Return Type | Description |
| --- | :---: | :---: | --- |
| Access | (None) | GraffitiProEditor.CollaborationAccess | Returns the access level granted for the currently opened document or authenticated connection. |
| AttachEditor | editor As GraffitiProEditor.Editor | (None) | Attaches this client to an editor so document changes and collaboration presence can be synchronized. |
| Authenticate | userName As String <br> passwordHash As String | (None) | Begins nonce-based authentication using the supplied user name and precomputed password hash. |
| Connect | host As String <br> port As Integer <br> path As String = "/" <br> secure As Boolean = False | (None) | Opens the client's built-in WebSocket transport to the supplied server. Pass secure = True for a TLS (wss) connection. |
| Constructor | (None) | (None) | Creates a WebSocket collaboration client. |
| DetachEditor | (None) | (None) | Stops synchronizing the attached editor and releases any node lock held by this client. |
| Disconnect | (None) | (None) | Closes the built-in WebSocket transport, if open. |
| IsAuthenticated | (None) | Boolean | Returns whether the server has authenticated this collaboration connection. |
| IsConnected | (None) | Boolean | Returns whether the built-in WebSocket transport has completed its handshake. |
| OpenDocument | documentID As String | (None) | Requests access to an existing server document after connection authentication succeeds. |
| RequestDocuments | request As JSONItem = Nil | String | Requests an application-defined JSON document listing after connection authentication and returns the request identifier. |
| User | (None) | GraffitiProEditor.Network.User | Returns the user object representing this client's current document session, or Nil before a document is opened. |
## Notes
### Document Listing
Call `RequestDocuments` after connection authentication succeeds. Its optional `JSONItem` is sent to the server unchanged and can contain application-defined filters, search text, paging values, or other listing options. The method returns a request ID. `DocumentsReceived` supplies that same ID and the application-defined JSON returned by the server.
The collaboration library does not require a particular response shape and does not automatically expose documents stored by `Server`. The client and server receive separate copies of the JSON, so an event handler may safely modify its copy. Opening a listed document still calls `OpenDocument`, which performs a separate authentication and authorization check.
### Document Opening and Conflicts
The server's saved document is the shared source of truth. `OpenDocument` does not upload or merge the editor's current contents. After access is approved, the server returns its current document and revision number. The client then replaces the editor's content with that document inside an update batch.
If an unsent local copy differs from the received server copy, the client raises `OfflineChangesDetected(documentID, localSnapshot, serverSnapshot)` after loading the server copy. The collaboration system does not automatically merge, save, or restore the replaced local content. Application code may save it, compare both versions, or offer a recovery choice.
Every document change includes the revision on which it was based. If another user's change was accepted first, the server still applies this change when the two touched different top-level nodes (and did not both change document settings, or both reorder or remove nodes). The client then receives its own change as a normal update and continues without reloading the document. Otherwise, or when the change would affect a node locked by another user, the server rejects the whole change. It returns `document.conflict` with its current document, revision, document format version, and checksum.
The client checks the checksum, clears the rejected change, and normally loads the server copy. If the client still owns a node lock and has unsent edits for that node, it keeps that node's local content and submits a new change based on the updated revision. This recovery applies only to the locked node. It is not a general document merge, and the server copy wins everywhere else.
Conflict recovery raises `OfflineChangesDetected` with the local and server copies from before recovery. It raises `ConflictResolved` after the editor has been updated. Applications may use these events for status, logging, recovery copies, or a custom comparison window.
### Lifecycle
Call `AttachEditor` before authentication. The client then receives private editor notifications without taking over the public `ContentChanged`, `SelectionChanged`, or `PointerMoved` events. Application code remains free to implement those events.
Call `Connect` to open the WebSocket. From the `Connected` event, call `Authenticate`. From the `Authenticated` event, call `OpenDocument`. Before discarding the client or attaching another editor, call `Disconnect` and `DetachEditor`. Detaching removes the client from the editor, restores the editor's previous read-only setting, and releases the client's node lock.
A local `Disconnect`, a valid WebSocket close handshake, or a server shutdown announced by `collaboration.ended` raises `Disconnected` without raising `Error`. `transport-disconnected` is reserved for a connection that disappears without completing the expected shutdown cycle.
The server can change this client's access while a document is open; `AccessChanged` reports it. With `Read`, the editor becomes read-only and the client drops its node lock. With `Edit`, the client asks again for a lock on the selected node. When the server revokes the document with `Server.DisconnectUser(user, True)`, `AccessChanged` reports `None`, the editor's document and undo history are cleared, and the connection ends. When the server ends the session with `DisconnectUser`, the client raises `Error` with the code `session-ended` and then `Disconnected`.
### Synchronization and Performance
Saved changes are sent as all-or-nothing batches. A batch contains only changed top-level nodes, removed node IDs, a changed node order, and changed document settings. While a user types, the client waits briefly and combines rapid edits into one update. Dragging and resizing send one update when the interaction ends. Complete documents are sent only when opening a document or recovering from a revision conflict. Pointer and selection activity is live-only and is not stored in the document database.
Incoming WebSocket messages are placed in a queue instead of being applied inside the socket event. The client processes one document or lock message per event-loop turn, allowing the editor to paint and accept input between remote changes. If several pointer or selection updates are waiting, only the newest is kept. The queue has a fixed limit and reports `message-backlog` instead of consuming memory without limit.
The client uses different timing for different work. Adding, deleting, and rearranging nodes uses a short delay. Text editing waits until typing pauses, restarting that wait after each keystroke. Edits made while another update is awaiting a reply are sent after that reply arrives.
The client keeps its own copy of the last document confirmed by the server, stored per top-level node. While text is being edited, an update converts and compares only the top-level nodes that changed since the previous update, so the cost of an update does not grow with document length. Structural changes, document settings, and changes made outside text editing compare the whole document, so a change that does not identify its node is never missed. Remote changes update the confirmed copy node by node rather than reprocessing the complete document. Comparisons distinguish letter case, so a change such as "word" to "Word" is always sent.
When a document opens, the response includes current users, locks, pointer positions, and selections before the client tries to lock its own selection. When a remote user clears the selection, `RemoteSelectionChanged` intentionally receives `Nil` for the node.
The server must grant a node lock before the editor enables commands that change that node. Other users may still select and inspect it. When deleting several nodes, the editor skips locked top-level nodes and nodes containing locked children, then deletes the remaining choices. The server checks locks again before saving every change. If another user locked one of the deleted nodes at nearly the same time, the server keeps that node and deletes the others; the client then restores the kept node in the editor and removes it from the undo history. A change to the content of a node another user has locked is still rejected, and the server returns its current document. Remote changes do not add to or clear the receiving editor's undo and redo history.
### Transport Contract
Call `Connect` to open the WebSocket transport. The client validates the HTTP upgrade, masks outgoing frames, accepts fragmented text messages, answers pings, performs the close handshake, and enforces protocol and message-size limits. Pass `secure = True` to `Connect` for a `wss` connection; TLS is negotiated before the WebSocket upgrade. Without it the connection is unencrypted `ws`, which should be limited to trusted networks or placed behind a TLS-terminating reverse proxy.
Xojo's `SSLSocket` documentation does not state whether a client verifies the server's certificate chain and host name, or which certificate file format Windows requires. Confirm both on every target platform before relying on `wss` across untrusted networks; until then, a TLS-terminating reverse proxy with verified certificates remains the conservative choice for internet-facing services.
## Examples
Attach the client to an editor, connect the application's transport, authenticate the connection, and open a document from the `Authenticated` event.
### Client Setup
```xojo
'// mClient is a window property, so the client outlives this method.
mClient = New GraffitiProEditor.Network.Client
mClient.AttachEditor(Editor)
AddHandler mClient.Connected, AddressOf CollaborationConnected
AddHandler mClient.Authenticated, AddressOf CollaborationAuthenticated
AddHandler mClient.Error, AddressOf CollaborationError
mClient.Connect("collaboration.example.com", 443, "/editor", True)
```
The fourth argument requests a TLS (`wss`) connection. Omit it, or pass `False`, for an unencrypted `ws` connection on a trusted network.
Call `Authenticate` from `Connected`. After `Authenticated` grants non-`None` access, call `OpenDocument` with a document identifier returned by the application. Handlers added with `AddHandler` take the client as their first parameter:
```xojo
Private Sub CollaborationConnected(sender As GraffitiProEditor.Network.Client)
sender.Authenticate(UserName, PasswordHash)
End Sub
Private Sub CollaborationAuthenticated(sender As GraffitiProEditor.Network.Client, userName As String, access As GraffitiProEditor.CollaborationAccess)
#Pragma Unused userName
If access <> GraffitiProEditor.CollaborationAccess.None Then sender.OpenDocument(DocumentID)
End Sub
```
### Handling Offline Changes
`OfflineChangesDetected` supplies the previous local document and the server's current document. The server copy has already been loaded into the attached editor when this event is raised. Save the local copy elsewhere or show an application-specific comparison or recovery window. Returning from the event does not merge the documents.
```xojo
Private Sub CollaborationOfflineChangesDetected(sender As GraffitiProEditor.Network.Client, documentID As String, localSnapshot As String, serverSnapshot As String)
#Pragma Unused sender
#Pragma Unused serverSnapshot
SaveRecoverySnapshot(documentID, localSnapshot)
ShowOfflineChangesNotice(documentID)
End Sub
```
### Requesting Documents
```xojo
Var request As New JSONItem
request.Value("search") = SearchField.Text
request.Value("page") = 1
Var requestID As String = client.RequestDocuments(request)
```
Handle `DocumentsReceived(requestID, response)` to read the JSON shape defined by your server application. The library does not require the response to use a specific set of fields.