all repos — felt @ 76c217511d1cff22d16c8c29d615579a830fd796

virtual tabletop for dungeons and dragons (and similar) using Go, MongoDB, and websockets

static/socket.js (raw)

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
const tableKey = {
  name: "",
  passcode: ""
}

let conn = null;
let offline = false;
const msgQ = [];

function dial() {
  // get tableKey from UI
  const tblNameInput = $("input_table_name");
  const tblPassInput = $("input_table_pass");
  const joinTblBtn = $("table_join");
  const leaveTblBtn = $("table_leave");
  
  if (tblNameInput && tblPassInput && tblNameInput.value && tblPassInput.value) {
    if (isTableKeyValid(tblNameInput.value, tblPassInput.value)) {
      tableKey.name = tblNameInput.value;
      tableKey.passcode = tblPassInput.value;
      
      if (conn) {
        conn.close(1000);
      }
      const wsProto = location.protocol == "https:" ? "wss" : "ws";
      conn = new WebSocket(`${wsProto}://${location.host}/subscribe`, `${tableKey.name}.${tableKey.passcode}`);
      
      conn.addEventListener("close", e => {
        offline = true;
        
        if (e.code == 1006 && e.wasClean) {
          setErr("Table not found - check the name and passcode are correct");
          
        } else if (e.code > 1001) {
          const lagDiv = $("lag");
          if (lagDiv) {
            lagDiv.style.display = "block";
            setTimeout(dial, 1000)
          }
        } else {
        
          tblNameInput.readOnly = false;
          tblPassInput.readOnly = false;
          joinTblBtn.style.display = adminToken ? "none" : "inline";
          leaveTblBtn.style.display = "none";
          
          tabletop = $("tabletop");
          if (tabletop) {
            tabletop.style.display = "none";
          }
          
          while (tokens.some(t=>t)) {
            tokens[0].m.removeFrom(map);
            tokens.shift();
          }
          
          if (mapImg) {
            mapImg.removeFrom(map);
            mapImg = null;
          }
        }
      });
      
      conn.addEventListener("open", e => {
      
        offline = false;
        tblNameInput.readOnly = true;
        tblPassInput.readOnly = true;
        joinTblBtn.style.display = "none";
        leaveTblBtn.style.display = adminToken ? "none" : "inline";
        lagDiv = $("lag");
        if (lagDiv) {
          lagDiv.style.display = "none";
        }
        
        while (msgQ.some(m=>m)) {
          publish(msgQ[0]);
          msgQ.shift();
        }
        
        closeErr();
        tabletop = $("tabletop");
        if (tabletop) {
          tabletop.style.display = "block";
        }
      });
      
      conn.addEventListener("error", e => {
        setErr(`Websocket error`);
        conn.close(3000);
      })
      
      conn.addEventListener("message", e => {
        const data = JSON.parse(e.data);

        if (data.diceRolls) {
          // dicerolls are treated as a byte array when marshalling to json, so we have to decode them
          data.diceRolls.forEach(r=>{
            r.roll = Uint8Array.from(atob(r.roll), c => c.charCodeAt(0))
          })
          makeUpToDate(data);
        } else {
          if (data.diceRoll) {
            data.diceRoll.roll = Uint8Array.from(atob(data.diceRoll.roll), c => c.charCodeAt(0));
          }
          makeUpToDate(data);
        }
        
        console.log(data);
      });
      
    } else {
      setErr("Table name and passcode can only be alphanumeric and underscores");
    }
  }else {
    setErr("Table name and passcode required");
  }
}

async function publish(msg) {
  if (offline) {
    msgQ.push(msg);
    
  } else {
    msg.key = tableKey;
    
    const res = await fetch('/publish', {
      method: 'POST',
      body: JSON.stringify(msg)
    });
    
    if (!res.ok) {
      setErr("Failed to publish message");
    }
  }
}

function makeUpToDate(msg) {
  if (msg) {
    // map image has to be set before tokens can be handled!
    if (msg.mapImg) {
      setMapImg(msg.mapImg);
    }
    
    if (msg.auxMsg) {
      setAuxMsg(msg.auxMsg);
    }
    
    if (msg.diceRolls) {
      logDice(msg.diceRolls);
    } else if (msg.diceRoll) {
      logDice(msg.diceRoll);
    }
    
    if (msg.tokens) {
      updateTokens(msg.tokens);
    } else if (msg.token) {
      updateTokens([msg.token]);
    }
  }
}

function fmtLeading(n) {
  return n < 10 ? "0" + n : String(n);
}

function formatDice(r) {
  const date = new Date(r.timestamp)
  const p = document.createElement("p");
  
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();
  
  p.innerHTML = `${date.getFullYear()}-${fmtLeading(month)}-${fmtLeading(day)} ${fmtLeading(hours)}:${fmtLeading(minutes)}:${fmtLeading(seconds)} ${r.player} rolled ${r.roll.length}d${r.faces} ${(r.note ? "(" + r.note + ")" : "")}<br>[${r.roll}] (total ${r.roll.reduce((a,c)=>a+c,0)})`;
  
  return p;
}

function logDice(dice) {
  const diceLog = $("dice_log");
  if (!Array.isArray(dice)) {
    dice = [ dice ];
  } else {
    if (diceLog) {
      diceLog.innerHTML = "";
    }
  }
  if (diceLog) {
      for(const r of dice) {
        try{
        const p = formatDice(r);
        diceLog.append(p);
        p.scrollIntoView();
        } catch{}
      }
  }
}

function setAuxMsg(msg) {
  const auxDiv = $("aux");
  if (auxDiv) {
    auxDiv.innerText = msg;
  }
}

function updateTokens(tokens) {
  // update internal token array and map
  processTokens(tokens);
  // update token select window
  renderTokenSelect();
  // if admin, update token master list
  renderTokenMasterList();
}

function renderTokenSelect() {
  const tokenSelect = $("token_select");
  
  if (tokenSelect) {
    const scroll = tokenSelect.scrollTop;
    tokenSelect.innerHTML = tokens.reduce((s, t) => { 
      return s + `<li><a href="#" onclick="initSpritePreviewById('${t.t.id}')">${t.t.name}</a><button onclick="toggleActive('${t.t.id}');return false">${(t.t.active ? "Deactivate" : "Activate")}</button></li>\n`;
    }, "");
    tokenSelect.scrollTop = scroll;
  }
}

// the following few functions aren't socket related but they directly relate to the previous function

function initSpritePreviewById(id) {
  const token = tokens.find(t=>t.t.id == id);
  let img = null;
  
  if (token && id) {
    
    img = document.createElement("img");
    img.src = token.t.sprite;
    const hdnTokenId = $("token_preview_id");
    if (hdnTokenId) {
      hdnTokenId.value = id;
    }

    img.onload = () => {
      scaleAltSpritePreview();
    }
  }
  
  const previewClearBtn = $("token_preview_clear");
  if (previewClearBtn) {
    previewClearBtn.style.display = (token && id) ? "block" : "none";
  }
  const tokenPreview = $("token_preview");
  if (tokenPreview) {
    tokenPreview.innerHTML = "";
    if (img) {
      tokenPreview.appendChild(img);
    }
  }
}

function dismissPreview() {
  initSpritePreviewById(null);
}

function scaleAltSpritePreview() {
  const hdnTokenId = $("token_preview_id");
  const tokenPreview = $("token_preview");
  if (tokenPreview && hdnTokenId && mapImg && mapImg._image) {
    const id = hdnTokenId.value;
    const scaleFactor = mapImg._image.clientWidth / mapImg._image.naturalWidth;
    const img = tokenPreview.children[0];
    const token = tokens.find(t=>t.t.id == id);
    if (img && token) {
        img.width = token.t.w * scaleFactor;
        img.height = token.t.h * scaleFactor;
    }
  }
}

function setMapImg(url) {
  initializeMap(url);
}

function isTableKeyValid(name, passcode) {
  const r = /^[a-zA-Z0-9_]+$/;
  return r.test(name) && r.test(passcode);
}

function leave() {
  conn.close(1000);
  tableKey.name = "";
  tableKey.passcode = "";
}