service.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. const sendButton = document.querySelector("button#send");
  2. const username =
  3. new URLSearchParams(window.location.search).get("u") || "Anonymous";
  4. const isStreamMode = new URLSearchParams(window.location.search).get("stream") === "1";
  5. if (isStreamMode) {
  6. document.body.classList.add("stream-mode");
  7. }
  8. sendButton.addEventListener("click", send);
  9. function send() {
  10. const messageText = window.getCurrentText ? window.getCurrentText() : "";
  11. let data = canvas.toDataURL("image/png");
  12. // Crop white space top and bottom if there's no text preventing it
  13. if (!messageText || messageText.trim() === "") {
  14. const ctx = canvas.getContext("2d");
  15. const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  16. const data32 = new Uint32Array(imgData.data.buffer);
  17. let top = canvas.height;
  18. let bottom = -1;
  19. for (let y = 0; y < canvas.height; y++) {
  20. let rowHasPixel = false;
  21. for (let x = 0; x < canvas.width; x++) {
  22. const p = data32[y * canvas.width + x];
  23. // ABGR: 0xFFFFFFFF is white. 0x00000000 is transparent.
  24. if (p !== 0xFFFFFFFF && p !== 0) {
  25. rowHasPixel = true;
  26. break;
  27. }
  28. }
  29. if (rowHasPixel) {
  30. if (y < top) top = y;
  31. if (y > bottom) bottom = y;
  32. }
  33. }
  34. if (top <= bottom) {
  35. // Add a little padding
  36. const padding = 10;
  37. top = Math.max(0, top - padding);
  38. bottom = Math.min(canvas.height - 1, bottom + padding);
  39. const cropHeight = bottom - top + 1;
  40. const tempCanvas = document.createElement("canvas");
  41. tempCanvas.width = canvas.width;
  42. tempCanvas.height = cropHeight;
  43. const tempCtx = tempCanvas.getContext("2d");
  44. tempCtx.putImageData(ctx.getImageData(0, top, canvas.width, cropHeight), 0, 0);
  45. data = tempCanvas.toDataURL("image/png");
  46. } else {
  47. // Canvas is entirely white/blank
  48. const tempCanvas = document.createElement("canvas");
  49. tempCanvas.width = canvas.width;
  50. tempCanvas.height = 20; // extremely minimal height
  51. const tempCtx = tempCanvas.getContext("2d");
  52. tempCtx.fillStyle = "white";
  53. tempCtx.fillRect(0, 0, canvas.width, 20);
  54. data = tempCanvas.toDataURL("image/png");
  55. }
  56. }
  57. const payload = {
  58. from: username,
  59. text: messageText,
  60. doodle: data,
  61. color: userColor,
  62. timestamp: new Date().toISOString(),
  63. };
  64. fetch("/api/messages", {
  65. method: "POST",
  66. headers: {
  67. "Content-Type": "application/json",
  68. },
  69. body: JSON.stringify(payload),
  70. }).then(response => {
  71. if (response.status === 401) {
  72. window.location.href = "/";
  73. }
  74. });
  75. // clear canvas after sending
  76. canvas.width = canvas.width;
  77. window.clearCurrentText();
  78. }
  79. function addToChatLog(msg) {
  80. const chatLog = document.getElementById("chat-log");
  81. const messageBox = document.createElement("div");
  82. messageBox.className = "message-box";
  83. if (msg.color && msg.color.startsWith('#')) {
  84. messageBox.style.borderColor = msg.color;
  85. messageBox.style.boxShadow = `0 4px 12px ${msg.color}33`;
  86. } else {
  87. messageBox.classList.add(`accent-${msg.color}`);
  88. }
  89. const messageHeader = document.createElement("div");
  90. messageHeader.className = "message-header";
  91. if (msg.color && msg.color.startsWith('#')) {
  92. messageHeader.style.color = msg.color;
  93. messageHeader.style.borderBottomColor = msg.color;
  94. }
  95. const usernameSpan = document.createElement("span");
  96. usernameSpan.className = "username";
  97. usernameSpan.textContent = msg.from;
  98. messageHeader.appendChild(usernameSpan);
  99. messageBox.appendChild(messageHeader);
  100. const canvasDiv = document.createElement("div");
  101. canvasDiv.className = "chat-canvas";
  102. const messageTextSpan = document.createElement("span");
  103. messageTextSpan.className = "message-text";
  104. messageTextSpan.innerHTML = msg.text.replace(/\n/g, "<br>");
  105. canvasDiv.appendChild(messageTextSpan);
  106. if (msg.doodle) {
  107. const img = document.createElement("img");
  108. img.src = msg.doodle;
  109. canvasDiv.appendChild(img);
  110. }
  111. messageBox.appendChild(canvasDiv);
  112. animatePreviousMessages(chatLog, false);
  113. chatLog.insertBefore(messageBox, chatLog.firstChild);
  114. }
  115. function addSystemMessageToChatLog(content) {
  116. const chatLog = document.getElementById("chat-log");
  117. const messageBox = document.createElement("div");
  118. messageBox.className = "system-message-box";
  119. messageBox.innerHTML = content;
  120. animatePreviousMessages(chatLog, true);
  121. chatLog.insertBefore(messageBox, chatLog.firstChild);
  122. }
  123. function animatePreviousMessages(chatLog, newIsSystem) {
  124. const previousMessages = chatLog.querySelectorAll(
  125. ".message-box, .system-message-box"
  126. );
  127. previousMessages.forEach((message) => {
  128. const prevIsSystem = message.classList.contains("system-message-box");
  129. const startTranslate = prevIsSystem
  130. ? newIsSystem
  131. ? "translateY(calc(100% + 5px))"
  132. : "translateY(calc(500% + 5px))"
  133. : newIsSystem
  134. ? "translateY(calc(20% + 5px))"
  135. : "translateY(calc(100% + 5px))";
  136. message.animate(
  137. [{ transform: startTranslate }, { transform: "translateY(0%)" }],
  138. {
  139. duration: 100,
  140. easing: "linear",
  141. fill: "forwards",
  142. }
  143. );
  144. });
  145. }
  146. // run when a new message is received from the server
  147. function handleMessage(msg) {
  148. const data = JSON.parse(msg);
  149. if (data.type === "system") {
  150. addSystemMessageToChatLog(data.content);
  151. return;
  152. }
  153. addToChatLog(data);
  154. }
  155. // listens for new messages from the server
  156. async function listen() {
  157. try {
  158. const response = await fetch("/api/messages");
  159. if (response.status === 401) {
  160. window.location.href = "/";
  161. return;
  162. }
  163. if (response.status === 200) {
  164. const msg = await response.text();
  165. handleMessage(msg);
  166. }
  167. } catch (err) {
  168. console.error("error listening messages:", err);
  169. } finally {
  170. // goes back to listening just after receiving a message or on error
  171. setTimeout(listen, 50); // small delay to avoid stack overflow
  172. }
  173. }
  174. // load backlog first, then start listening
  175. async function loadBacklog() {
  176. try {
  177. const response = await fetch("/api/backlog");
  178. if (response.status === 200) {
  179. const messages = await response.json();
  180. // append chronologically
  181. for (const msg of messages) {
  182. if (msg.type === "system") {
  183. addSystemMessageToChatLog(msg.content);
  184. } else {
  185. addToChatLog(msg);
  186. }
  187. }
  188. }
  189. } catch (err) {
  190. console.error("error loading backlog:", err);
  191. }
  192. }
  193. // start listening for messages right after loading the app backlog
  194. loadBacklog().then(() => listen());
  195. // sets the username label in the user message box
  196. const usernameLabel = document.querySelector(
  197. "#user-message-box > .message-header > .username"
  198. );
  199. usernameLabel.innerHTML = username;