Debian Codegraph @

_examples/history_pagination/index.html

raw
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 input[type="text"] { width: 300px; }
8 .muted {color: #CCCCCC; font-size: 10px;}
9 </style>
10 <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/centrifugal/centrifuge-js@master/dist/centrifuge.min.js"></script>
11 <script type="text/javascript">
12 // helper functions to work with escaping html.
13 const tagsToReplace = {'&': '&amp;', '<': '&lt;', '>': '&gt;'};
14 function replaceTag(tag) {return tagsToReplace[tag] || tag;}
15 function safeTagsReplace(str) {return str.replace(/[&<>]/g, replaceTag);}
16
17 const channel = "chat:index";
18
19 // Manually keep last seen stream position.
20 let streamPosition = null;
21
22 window.addEventListener('load', function() {
23 const input = document.getElementById('input');
24 const container = document.getElementById('messages');
25
26 const centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket');
27
28 centrifuge.on('connect', function(ctx){
29 drawText('Connected with client ID ' + ctx.client + ' over ' + ctx.transport + ' with data: ' + JSON.stringify(ctx.data));
30 input.removeAttribute("disabled");
31 });
32
33 centrifuge.on('disconnect', function(ctx){
34 drawText('Disconnected: ' + ctx.reason + (ctx.reconnect?", will try to reconnect":", won't try to reconnect"));
35 input.setAttribute("disabled", 'true');
36 });
37
38 const sub = centrifuge.subscribe(channel, handleMessage)
39 .on("unsubscribe", handleUnsubscribe)
40 .on("subscribe", handleSubscribe)
41 .on("error", handleSubscribeError);
42
43 centrifuge.connect();
44
45 async function restoreMissedPublications() {
46 let recovered = false;
47 while (true) {
48 if (recovered) {
49 break;
50 }
51 let resp;
52 try {
53 const limit = 10;
54 drawText("Since offset " + streamPosition.offset + " with limit " + limit)
55 resp = await sub.history({since: streamPosition, limit: limit});
56 } catch (e) {
57 return false;
58 }
59 const pubs = resp.publications;
60 if (pubs && pubs.length > 0) {
61 for (let i in pubs) {
62 if (!pubs.hasOwnProperty(i)) {
63 continue
64 }
65 handleMessage(pubs[i]);
66 if (pubs[i].offset === resp.offset) {
67 recovered = true;
68 break;
69 }
70 }
71 } else {
72 recovered = true;
73 break;
74 }
75 }
76 return recovered;
77 }
78
79 async function handleSubscribe(ctx) {
80 drawText('Subscribed on channel ' + ctx.channel + ' (resubscribed: ' + ctx.isResubscribe + ')');
81 if (streamPosition == null) {
82 streamPosition = ctx.streamPosition;
83 } else {
84 drawText("Start missed publications recovery")
85 const ok = await restoreMissedPublications();
86 if (!ok) {
87 drawText("Oops, seems like we can't recover");
88 centrifuge.disconnect();
89 return;
90 }
91 drawText("Successfully recovered")
92 }
93 }
94
95 function handleSubscribeError(err) {
96 drawText('Error subscribing on channel ' + err.channel + ': ' + err.message);
97 }
98
99 function handleMessage(message) {
100 if (message.offset !== streamPosition.offset + 1) {
101 return;
102 }
103 drawMessage(message)
104 streamPosition.offset = message.offset;
105 }
106
107 function drawMessage(message) {
108 let clientID;
109 if (message.info){
110 clientID = message.info.client;
111 } else {
112 clientID = null;
113 }
114 const inputText = message.data["input"].toString();
115 const text = safeTagsReplace(inputText) + ' <span class="muted">from ' + clientID + '</span>';
116 drawText(text);
117 }
118
119 function handleUnsubscribe(sub) {
120 drawText('Unsubscribed from channel ' + sub.channel);
121 }
122
123 function drawText(text) {
124 let e = document.createElement('li');
125 e.innerHTML = [(new Date()).toString(), ' ' + text].join(':');
126 container.insertBefore(e, container.firstChild);
127 }
128
129 document.getElementById('form').addEventListener('submit', function(event) {
130 event.preventDefault();
131 sub.publish({"input": input.value}).then(function() {
132 drawText("Successfully published to channel");
133 }, function(err) {
134 drawText("Publish error: " + JSON.stringify(err));
135 });
136 input.value = '';
137 });
138 });
139 </script>
140 </head>
141 <body>
142 <form id="form">
143 <label for="input"></label><input type="text" id="input" autocomplete="off" />
144 <input type="submit" id="submit" value="ยป">
145 </form>
146 <ul id="messages"></ul>
147 </body>
148 </html>