Connecting to the shared job sheet...
The form will appear when the shared answers have loaded.
JSON definition · shared/definitions/fill-together.json
View on GitHub
{
"title": "Job sheet",
"completeText": "Finish job sheet",
"description": "Filled together by the dispatcher and the technician",
"elements": [
{
"type": "panel",
"name": "dispatch",
"title": "Dispatcher",
"elements": [
{
"type": "text",
"name": "customer",
"title": "Customer",
"isRequired": true
},
{
"type": "text",
"name": "address",
"title": "Site address"
},
{
"type": "dropdown",
"name": "job_type",
"title": "Job type",
"choices": [
"Installation",
"Repair",
"Inspection"
]
},
{
"type": "comment",
"name": "dispatch_notes",
"title": "Notes for the technician"
}
]
},
{
"type": "panel",
"name": "onsite",
"title": "Technician",
"elements": [
{
"type": "comment",
"name": "findings",
"title": "What did you find?"
},
{
"type": "checkbox",
"name": "parts",
"title": "Parts used",
"choices": [
"Filter",
"Valve",
"Pump",
"Sensor"
],
"showOtherItem": true
},
{
"type": "text",
"name": "hours",
"title": "Hours on site",
"inputType": "number",
"min": 0,
"step": 0.25
},
{
"type": "boolean",
"name": "resolved",
"title": "Issue resolved?"
}
]
}
]
}
Client · shared/client/fill-together.js · sjs:fill-together.save
View on GitHub
// Ask the relay to save once and confirm the result to every participant
function completeJobSheet(sender, options) {
completionOptions = options;
if (responseId !== null) {
sender.completedHtml = `<h3>The job sheet has been saved.</h3><p>Response ID: ${responseId}</p>`;
return options.showSaveSuccess();
}
if (!ready || ws.readyState !== WebSocket.OPEN) {
sender.completedHtml = "<h3>The job sheet hasn't been saved.</h3>";
return options.showSaveError("Reconnect to the shared session, then try again.");
}
sender.completedHtml = "<h3>Saving the job sheet...</h3>";
options.showSaveInProgress();
saveOptions = options;
setLocked(true);
ws.send(JSON.stringify({ type: "complete", data: sender.data }));
}
Client · shared/client/fill-together.js · sjs:fill-together.client
View on GitHub
// Transport the plugin's answer and presence messages over a WebSocket
function applySharedState(message) {
const draft = survey?.data;
const previousSession = sessionId;
if (!collab) {
survey = new Model(message.seed);
survey.completeText = "Finish job sheet";
collab = new CollaborationPlugin(survey, { getInviteLink: partnerLink });
collab.onEvent.add((_, { message }) => {
if (ready && responseId === null && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
});
survey.onComplete.add(completeJobSheet);
mountSurvey(survey);
}
sessionId = message.sessionId;
ready = true;
collab.apply(message);
// Restore the local draft if an empty session replaces the disconnected one
if (previousSession && previousSession !== sessionId && !message.responseId && !message.peers.length) survey.data = draft;
form.hidden = false;
document.getElementById("collaboration-loading").hidden = true;
setLocked(false);
if (message.responseId) confirmCompletion(message.responseId, message.values);
}
Server · src/main/java/io/surveyjs/examples/FillTogetherRelay.java · sjs:fill-together.server
View on GitHub
// The relay runs in this app's process, on its port, and relays JSON: it never parses the definition
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
Map<String, Object> attributes) {
String recordId = request.getURI().getPath().substring("/ws/rooms/".length());
// Spring Security's filter chain ran on the upgrade request: the demo_user cookie stands in for your real session check
User user = request.getPrincipal() instanceof Authentication auth && auth.getPrincipal() instanceof User u ? u : null;
String roomKey = roomKeys.forId(recordId);
if (!RECORD_ID.matcher(recordId).matches() || user == null || roomKey == null) {
response.setStatusCode(HttpStatus.FORBIDDEN); // the browser sees a refused handshake
return false;
}
attributes.putAll(Map.of("user", user, "recordId", recordId, "roomKey", roomKey));
return true;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) {
User user = (User) session.getAttributes().get("user");
FillRoom room = rooms.join(roomKey(session), () -> seed((String) session.getAttributes().get("recordId"))); // definition + saved answers
room.lock().lock();
try {
Participant client = room.add(session, Participant.displayName(session, user.name()));
client.send(Participant.message("type", "init", "clientId", client.id(), "name", client.name(), "colorIndex", room.colorIndex(client),
"seed", room.seed(), "values", room.values(), "peers", room.roster(client),
"sessionId", room.sessionId(), "responseId", room.responseId())); // init first
} finally {
room.lock().unlock();
}
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage text) {
JsonNode message = parse(text.getPayload()); // objects stay objects: {} is relayed as {}
FillRoom room = rooms.room(roomKey(session));
Participant client = Participant.of(session);
switch (message.path("type").asString("")) {
case "complete" -> {
if (message.get("data") instanceof ObjectNode data) {
complete(room, client, data);
}
}
case "value" -> {
if (message.path("key").isString()) { // last write wins; ignored once the room's response is saved
room.value(client, message.get("key").asString(), message.path("value").isMissingNode() ? null : message.get("value"));
}
}
case "presence" -> {
if (message.hasNonNull("state") && text.getPayloadLength() <= 4096) { // stamp identity, relay
room.presence(client, message.get("state"), !message.path("retain").isBoolean() || message.get("retain").asBoolean());
}
}
default -> { } // unknown types: ignore
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
rooms.leave(roomKey(session), Participant.of(session)); // peer-left to the others; the room is dropped 2 s after the last leaves
}
Server · src/main/java/io/surveyjs/examples/FillTogetherRelay.java · sjs:fill-together.complete
View on GitHub
// Save once per room session and send the same confirmation to every participant
private void complete(FillRoom room, Participant sender, ObjectNode data) {
room.lock().lock(); // two completes at once: the second waits, then finds the saved id
try {
if (room.responseId() == null) {
try {
room.saved(storedJson.insertResponse("job-sheet", data), data); // as save-response stores it
} catch (RuntimeException e) {
log.error("fill-together: couldn't save the job sheet", e);
sender.send(Participant.message("type", "save-error", "error", "Couldn't save the job sheet. Please try again."));
return;
}
}
room.sendAll(Participant.message("type", "completed", "id", room.responseId(), "data", room.values()));
} finally {
room.lock().unlock();
}
}