You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cryptpad/www/json/api.js

107 lines
2.9 KiB
JavaScript

require.config({ paths: { 'json.sortify': '/bower_components/json.sortify/dist/JSON.sortify' } });
define([
'/api/config?cb=' + Math.random().toString(16).substring(2),
'/common/crypto.js',
'/common/realtime-input.js',
'/json/listmap.js',
'/common/json-ot.js',
'json.sortify',
'/bower_components/textpatcher/TextPatcher.amd.js',
'/bower_components/jquery/dist/jquery.min.js',
], function (Config, Crypto, Realtime, ListMap, JsonOT, Sortify, TextPatcher) {
var api = {};
api.ListMap = ListMap;
var create = api.create = function (cfg) {
/* validate your inputs before proceeding */
if (['object', 'array'].indexOf(ListMap.type(cfg.data))) {
throw new Error('unsupported datatype');
}
var config = {
initialState: Sortify(cfg.data),
transformFunction: JsonOT.validate,
userName: Crypto.rand64(8),
channel: cfg.channel,
cryptKey: cfg.cryptKey,
crypto: Crypto,
websocketURL: Config.websocketURL,
};
var rt;
var proxy = ListMap.makeProxy(cfg.data);
var realtime;
var onInit = config.onInit = function (info) {
realtime = info.realtime;
// create your patcher
realtime.patchText = TextPatcher.create({
realtime: realtime,
logging: config.logging || false,
});
// onInit
cfg.onInit(info);
};
var onReady = config.onReady = function (info) {
var userDoc = realtime.getUserDoc();
var parsed = JSON.parse(userDoc);
// update your proxy to the state of the userDoc
Object.keys(parsed).forEach(function (key) {
proxy[key] = ListMap.recursiveProxies(parsed[key]);
});
// onReady
cfg.onReady(info);
};
// FIXME
var onLocal = config.onLocal = ListMap.onLocal = function () {
var strung = Sortify(proxy);
realtime.patchText(strung);
// try harder
if (realtime.getUserDoc() !== strung) {
realtime.patchText(strung);
}
// onLocal
if (cfg.onLocal) {
cfg.onLocal();
}
// TODO actually emit 'change' events, or something like them
};
var onRemote = config.onRemote = function (info) {
var userDoc = realtime.getUserDoc();
var parsed = JSON.parse(userDoc);
ListMap.update(proxy, parsed);
// onRemote
if (cfg.onRemote) {
cfg.onRemote(info);
}
};
var onAbort = config.onAbort = function (info) {
// onAbort
cfg.onAbort(info);
};
rt = Realtime.start(config);
rt.proxy = proxy;
rt.realtime = realtime;
return rt;
};
return api;
});