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 · examples/consumers/edit_together.py · 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.
async def connect(self):
form_id, user = self.scope["url_route"]["kwargs"]["form_id"], self.scope["user"]
key = room_key.for_scope(self.scope, form_id)
if not await acan(user, "edit-forms") or not FORM_ID.match(form_id) or key is None: # like saving, editing together is for editors
await self.close() # before accept(): the browser sees a refused handshake
return
await self.accept()
self.room = await edit_room.join(key, lambda: database_sync_to_async(saved_definition)(form_id)) # seed = the saved definition
async with self.room.lock: # the log in init, then every record after it: none twice, none missed
self.participant = self.room.add(display_name(self.scope, user.get_full_name()))
await self.channel_layer.group_add(self.room.group, self.channel_name)
await self.send(text_data=dumps({"type": "init", "clientId": self.participant.id, "colorIndex": self.participant.slot,
"color": self.room.color(self.participant), "seed": self.room.seed,
"log": self.room.log})) # init first
if peers := self.room.roster(self.participant):
await self.send(text_data=dumps({"type": "presence-sync", "peers": peers}))
async def receive(self, text_data=None, bytes_data=None):
message = parse(text_data) # records stay opaque: {} is relayed as {}
if not isinstance(message, dict):
return
if message.get("type") == "append" and message.get("payload") is not None: # append, then fan out
async with self.room.lock:
self.room.log.append(message["payload"])
await self.broadcast({"type": "record", "from": self.participant.id, "payload": message["payload"]})
elif message.get("type") == "presence" and message.get("state") is not None and len(text_data) <= 4096:
self.participant.state = message["state"]
await self.broadcast({"type": "presence", "peer": self.room.peer(self.participant)})
# unknown types: ignore
async def disconnect(self, code):
if hasattr(self, "participant"): # presence-leave to the others; the log lives until the room empties
edit_room.leave(self.room, self.participant)
await self.broadcast({"type": "presence-leave", "clientId": self.participant.id})
await self.channel_layer.group_discard(self.room.group, self.channel_name)