-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpalindrom-client.html
335 lines (333 loc) · 16.5 KB
/
palindrom-client.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
<!-- palindrom-polymer-client version: 8.0.1 | MIT License -->
<!--
`palindrom-client` element binds [Palindrom](https://github.com/Palindrom/Palindrom) with [Polymer's template binding](https://www.polymer-project.org/2.0/docs/devguide/templates.html).
That keeps your Polymer app, or just `dom-bind` template in sync with any server-side
data-model using Palindrom & [JSON Patch](https://tools.ietf.org/html/rfc6902) flow.
You get three-way data binding server - JS - HTML, kept in flawless sync.
<palindrom-client
obj="{{model}}"></palindrom-client>
It establishes the Palindrom connection when attached. All the changes made
in browser are sent to the server via WebSocket or HTTP, as
[JSON Patch](https://tools.ietf.org/html/rfc6902)es.
All the changes from server are also received and propagated to your HTML.
-->
<script src="../Palindrom/dist/palindrom-dom.min.js"></script>
<script>
(function () {
const defaultProps = {
"remoteUrl": window.location.href,
"useWebSocket": true,
"debug": false,
"localVersionPath": '/_ver#c$',
"remoteVersionPath": '/_ver#s',
"ot": true,
"purity": false,
"pingIntervalS": 60,
"path": '/',
"devToolsOpen": false,
"fatalErrorReloadAfterS": 5
}
const defaultAttribs = ['remote-url', 'use-web-socket', 'debug', 'local-version-path', 'remote-version-path', 'ot', 'purity', 'listen-to', 'ping-interval-s', 'purity', 'fatal-error-reload-after-s', 'path'];
class PalindromClient extends HTMLElement {
constructor() {
super();
// assign default properties
Object.assign(this, defaultProps);
}
static get observedAttributes() {
return ['merged-notifications-threshold'];
}
reconnectNow() {
this.palindrom.reconnectNow();
}
reload() {
window.location.reload();
}
cancelReloading() {
clearInterval(this.reloadingInterval);
delete this.reloadingInterval;
}
/**
* assigns an instance of Palindrom according to given params, attaches it to .palindrom property
*
*/
connectedCallback() {
// assign attributes to props
for (let i = 0; i < this.attributes.length; i++) {
const attrib = this.attributes[i];
if (defaultAttribs.includes(attrib.name)) {
const prop = kebebCaseToCamelCase(attrib.name);
if (typeof this[prop] === "boolean") {
this[prop] = (attrib.value === "true");
}
else {
this[prop] = attrib.value;
}
}
}
const whereToBind = this.getAttribute("ref");
let listenTo = this.listenTo;
const pingIntervalS = this.pingIntervalS / 1;
if (listenTo) {
listenTo = typeof listenTo == "string" ? document.getElementById(listenTo) : listenTo;
}
let palindrom = PalindromDOM.instances && PalindromDOM.instances.get(this.remoteUrl);
if (!palindrom) {
/**
* To tell whether we connected to an existing instance,
* or created our own. This is useful for detachement, we don't want
* to destroy Palindrom instances that we don't own
* */
this.isUsingOwnInstanceOfPalindrom = true;
this.palindrom = palindrom = new PalindromDOM({
remoteUrl: this.remoteUrl,
pingIntervalS,
useWebSocket: this.useWebSocket,
debug: this.debug,
ot: this.ot,
purity: this.purity,
localVersionPath: this.localVersionPath,
remoteVersionPath: this.remoteVersionPath,
listenTo,
onLocalChange: this.onLocalChange.bind(this),
onRemoteChange: this.onPatchApplied.bind(this),
onPatchReceived: this.onPatchReceived.bind(this),
onIncomingPatchValidationError: this.onGenericError.bind(this),
onOutgoingPatchValidationError: this.onGenericError.bind(this),
onError: this.onGenericError.bind(this),
onPatchSent: this.onPatchSent.bind(this),
onSocketStateChanged: this.onSocketStateChanged.bind(this),
onConnectionError: this.onConnectionError.bind(this),
onReconnectionCountdown: this.onReconnectionCountdown.bind(this),
onReconnectionEnd: this.onReconnectionEnd.bind(this),
onStateReset: obj => {
this.obj = obj;
if (whereToBind) {
this.bindTo(whereToBind);
}
this.onPatchApplied([{ op: 'replace', path: '', value: obj }], [{ removed: this.obj }])
}
});
if (!PalindromDOM.instances) {
PalindromDOM.instances = new Map();
}
PalindromDOM.instances.set(this.remoteUrl, palindrom);
} else {
this.isUsingOwnInstanceOfPalindrom = false;
// with already established connection we cannot change listenTo parameter
this.palindrom = palindrom;
palindrom.onLocalChange = this.onLocalChange.bind(this);
palindrom.onRemoteChange = this.onPatchApplied.bind(this);
palindrom.onPatchReceived = this.onPatchReceived.bind(this);
palindrom.onIncomingPatchValidationError = this.onGenericError.bind(this);
palindrom.onOutgoingPatchValidationError = this.onGenericError.bind(this);
palindrom.onError = this.onGenericError.bind(this);
palindrom.onPatchSent = this.onPatchSent.bind(this);
palindrom.onSocketStateChanged = this.onSocketStateChanged.bind(this);
palindrom.onConnectionError = this.onConnectionError.bind(this);
palindrom.onReconnectionCountdown = this.onReconnectionCountdown.bind(this);
palindrom.onReconnectionEnd = this.onReconnectionEnd.bind(this);
palindrom.onStateReset = obj => {
this.obj = obj;
if (whereToBind) {
this.bindTo(whereToBind);
}
this.onPatchApplied([{ op: 'replace', path: '', value: obj }], [{ removed: this.obj }])
}
// if already established (re-)set state
if (palindrom.obj) {
palindrom.onStateReset(palindrom.obj);
}
}
this.network = palindrom.network;
this.morphUrl = palindrom.morphUrl.bind(palindrom)
}
disconnectedCallback() {
if (this.isUsingOwnInstanceOfPalindrom) {
this.palindrom.unlisten();
// hacky way to stop Palindrom connection
this.palindrom.useWebSocket = false;
PalindromDOM.instances.delete(this.remoteUrl);
}
}
bindTo(elementOrId) {
// use node id or node itself;
const element = typeof elementOrId == "string" ? document.getElementById(elementOrId) : elementOrId;
if (!element) {
throw new Error("Provided 'ref' configuration is not a valid element or existing element's id");
}
element.model = this.obj;
this.bound = element;
}
propagateDomBind(sequence) {
if (this.bound) {
this.notifyTemplateDomBind(this.bound.model, sequence, this.bound, "model");
}
else {
this.notifyTemplateDomBind(this.obj, sequence, this, "obj");
}
}
onLocalChange(patches) {
// todo #26
this.propagateDomBind({ patches, results: patches.map(() => { }) });
}
fire(name, detail) {
this.dispatchEvent(new CustomEvent(name, { detail }));
}
onPatchReceived(data, url, method) {
this.fire("patchreceived", {
data,
url,
method
});
}
onPatchSent(data, url, method) {
this.fire("patchsent", {
data,
url,
method
});
}
onSocketStateChanged(state, url, data, statusCode, reason) {
this.fire("socketstatechanged", {
state,
url,
data,
statusCode,
reason
});
}
onConnectionError(palindromConnectionError) {
const eventDetail = {
error: palindromConnectionError,
handled: false
};
this.fire("connection-error", eventDetail);
}
onGenericError(error) {
const eventDetail = {
error
};
this.fire("generic-error", eventDetail);
}
onReconnectionCountdown(milliseconds) {
const eventDetail = {
milliseconds,
handled: false
};
this.fire("reconnection-countdown", eventDetail);
}
onReconnectionEnd() {
const eventDetail = {
handled: false
};
this.fire("reconnection-end", eventDetail);
}
onPatchApplied(patches, results) {
this.propagateDomBind({ patches, results });
this.fire("patch-applied", {
patches
});
}
notifyTemplateDomBind(tree, patchesAndResults, templateDomBind, polymerPathPrefix) {
let operation;
let polymerPath;
for (let operationNo = 0, len = patchesAndResults.patches.length; operationNo < len; operationNo++) {
operation = patchesAndResults.patches[operationNo];
const result = patchesAndResults.results[operationNo];
if (operation.path == "") {
// Replate the original object with the new one.
templateDomBind.set('model', this.obj);
// By the time we're here all the operations in the patch
// are applied to the object by Palindrom.
// As we notified the root about the entire object change,
// there is no need to notify individual properties.
// https://github.com/Palindrom/Palindrom/blob/c38cf23/src/palindrom.js#L814-L843
return;
}
polymerPath = polymerPathPrefix + translateJSONPointerToPolymerPath(operation.path);
if (operation.op === 'test') {
// we assume that jsonpatch covered it already
} else if (operation.op === 'move' || operation.op === 'copy') {
console.warn("move, and copy operations are not supported yet.")
} else {
// for add and remove we need to check whether it's an array or not
const lastSeparator = operation.path.lastIndexOf('/');
let name = operation.path.substr(lastSeparator + 1);
const parentsPolymerPath = polymerPathPrefix + translateJSONPointerToPolymerPath(operation.path.substring(0, lastSeparator));
const parent = templateDomBind.get(parentsPolymerPath);
if (Array.isArray(parent) && (name === '-' || isNormalInteger(name))) {
switch (operation.op) {
case 'add':
// JSONPatch push
if (name === '-') {
name = result.index;
}
templateDomBind.notifySplices(parentsPolymerPath,
[{
index: parseInt(name, 10),
removed: [],
addedCount: 1,
object: parent,
type: 'splice'
}]
);
break;
case 'replace':
templateDomBind.notifySplices(parentsPolymerPath,
[{
index: parseInt(name, 10),
removed: (result && [result.removed]) || [],
addedCount: 1,
object: parent,
type: 'splice'
}]
);
break;
case 'remove':
templateDomBind.notifySplices(parentsPolymerPath,
[{
index: parseInt(name, 10),
removed: (result && [result.removed]) || [],
addedCount: 0,
object: parent,
type: 'splice'
}]
);
break;
}
} else {
switch (operation.op) {
case 'add':
case 'replace':
if (typeof operation.value === 'object') {
templateDomBind.notifyPath(polymerPath);
} else {
templateDomBind.notifyPath(polymerPath, operation.value, false);
}
break;
case 'remove':
//console.warn('Polymer does not support unsetting properties https://github.com/Polymer/polymer/issues/2565');
//console.warn('remove is translated to JSON incompatible set to `undefined`, as there is no remove method in Polymer.')
templateDomBind.notifyPath(polymerPath, null, false);
templateDomBind.notifyPath(polymerPath, undefined, false);
break;
}
}
}
}
}
}
customElements.define('palindrom-client', PalindromClient);
function translateJSONPointerToPolymerPath(pointer) {
return pointer.replace(/\//g, '.');
}
function isNormalInteger(str) {
const n = ~~Number(str);
return String(n) === str && n >= 0;
}
function kebebCaseToCamelCase(str) {
return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
}
})();
</script>