JSON definition · shared/definitions/creator-load-save.json
View on GitHub
{
"title": "Support request",
"elements": [
{
"type": "dropdown",
"name": "product",
"title": "Product",
"choices": [
"Form Library",
"Survey Creator",
"Dashboard",
"PDF Generator"
]
},
{
"type": "comment",
"name": "issue",
"title": "Describe the issue",
"isRequired": true
},
{
"type": "radiogroup",
"name": "urgency",
"title": "How urgent is it?",
"choices": [
"Low",
"Normal",
"Blocking"
]
},
{
"type": "boolean",
"name": "callback",
"title": "Call me back"
}
]
}
Client · shared/client/edit-together.js · sjs:edit-together.save
View on GitHub
// Save the synchronized schema separately from the room's temporary edit log
function configureSaving() {
saver = createSchemaSaver(() => creator.JSON, async json => {
if (!connected()) throw new Error("Reconnect before saving the shared form.");
const response = await fetch(`/api/forms/${formId}`, {
method: "PUT", headers: { "Content-Type": "application/json" }, body: json
});
if (!response.ok) throw await responseError(response, "Couldn't save the form schema. Please try again.");
}, ({ state, error }) => {
showError(state === "error" ? error : "");
retrySave.hidden = state !== "error";
formSelector.disabled = state === "saving";
});
creator.saveSurveyFunc = async (saveNo, callback) => {
const saved = await saver.save();
callback(saveNo, saved);
// Creator says "not saved" in the callback; show the server's reason after it
if (!saved) creator.notify(saver.error, "error");
};
creator.onModified.add(() => { if (ready && !collab.isApplying) saver.changed(); });
}
Client · shared/client/edit-together.js · sjs:edit-together.client
View on GitHub
// Rebuild the shared form from its saved schema and ordered edit log
function initialize(message) {
creator?.dispose();
creator = new SurveyCreator({ showTranslationTab: true });
creator.JSON = message.seed;
collab = new CollaborationPlugin(creator, { roomId: formId, getInviteLink: sharedFormLink });
creator.addPlugin("collaboration", collab);
collab.setClientId(message.clientId);
configureSaving();
saver.markSaved();
if (message.log.length) collab.apply(message.log);
const append = (_, { record }) => send({ type: "append", payload: record });
collab.onRecordAdded.add(append);
collab.onRecordChanged.add(append);
collab.onStateChanged.add(() => send({ type: "presence", state: collab.getState() }));
}
Server · src/main/java/io/surveyjs/examples/EditTogetherRelay.java · sjs:edit-together.server
View on GitHub
// The same kind of relay as Fill Forms Together, keeping an append-only log instead of a value map:
// Creator records must be replayed in order. It runs in this app's process, on its port.
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
Map<String, Object> attributes) {
String formId = request.getURI().getPath().substring("/ws/forms/".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(formId);
if (!FORM_ID.matcher(formId).matches() || user == null || !user.editor() || roomKey == null) { // like saving, editing together is for editors
response.setStatusCode(HttpStatus.FORBIDDEN); // the browser sees a refused handshake
return false;
}
attributes.putAll(Map.of("user", user, "formId", formId, "roomKey", roomKey));
return true;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) {
User user = (User) session.getAttributes().get("user");
EditRoom room = rooms.join(roomKey(session), () -> savedDefinition((String) session.getAttributes().get("formId"))); // seed = the saved definition
room.lock().lock();
try {
Participant client = room.add(session, Participant.displayName(session, user.name()));
client.send(Participant.message("type", "init", "clientId", client.id(), "colorIndex", client.slot(), "color", room.color(client),
"seed", room.seed(), "log", room.log())); // init first
List<Map<String, Object>> peers = room.roster(client);
if (!peers.isEmpty()) {
client.send(Participant.message("type", "presence-sync", "peers", peers));
}
} finally {
room.lock().unlock();
}
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage text) {
JsonNode message = parse(text.getPayload()); // records stay opaque: {} is relayed as {}
EditRoom room = rooms.room(roomKey(session));
Participant client = Participant.of(session);
switch (message.path("type").asString("")) {
case "append" -> {
if (message.hasNonNull("payload")) { // append, then fan out
room.append(client, message.get("payload"));
}
}
case "presence" -> {
if (message.hasNonNull("state") && text.getPayloadLength() <= 4096) {
room.presence(client, message.get("state"));
}
}
default -> { } // unknown types: ignore
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
rooms.leave(roomKey(session), Participant.of(session)); // presence-leave to the others; the log lives until the room empties
}