service.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. });
  71. // clear canvas after sending
  72. canvas.width = canvas.width;
  73. window.clearCurrentText();
  74. }
  75. function addToChatLog(msg) {
  76. const chatLog = document.getElementById("chat-log");
  77. const messageBox = document.createElement("div");
  78. messageBox.className = "message-box";
  79. if (msg.color && msg.color.startsWith('#')) {
  80. messageBox.style.borderColor = msg.color;
  81. messageBox.style.boxShadow = `0 4px 12px ${msg.color}33`;
  82. } else {
  83. messageBox.classList.add(`accent-${msg.color}`);
  84. }
  85. const messageHeader = document.createElement("div");
  86. messageHeader.className = "message-header";
  87. if (msg.color && msg.color.startsWith('#')) {
  88. messageHeader.style.color = msg.color;
  89. messageHeader.style.borderBottomColor = msg.color;
  90. }
  91. const usernameSpan = document.createElement("span");
  92. usernameSpan.className = "username";
  93. usernameSpan.textContent = msg.from;
  94. messageHeader.appendChild(usernameSpan);
  95. messageBox.appendChild(messageHeader);
  96. const canvasDiv = document.createElement("div");
  97. canvasDiv.className = "chat-canvas";
  98. const messageTextSpan = document.createElement("span");
  99. messageTextSpan.className = "message-text";
  100. messageTextSpan.innerHTML = msg.text.replace(/\n/g, "<br>");
  101. canvasDiv.appendChild(messageTextSpan);
  102. if (msg.doodle) {
  103. const img = document.createElement("img");
  104. img.src = msg.doodle;
  105. canvasDiv.appendChild(img);
  106. }
  107. messageBox.appendChild(canvasDiv);
  108. animatePreviousMessages(chatLog, false);
  109. chatLog.insertBefore(messageBox, chatLog.firstChild);
  110. }
  111. function addSystemMessageToChatLog(content) {
  112. const chatLog = document.getElementById("chat-log");
  113. const messageBox = document.createElement("div");
  114. messageBox.className = "system-message-box";
  115. messageBox.innerHTML = content;
  116. animatePreviousMessages(chatLog, true);
  117. chatLog.insertBefore(messageBox, chatLog.firstChild);
  118. }
  119. function animatePreviousMessages(chatLog, newIsSystem) {
  120. const previousMessages = chatLog.querySelectorAll(
  121. ".message-box, .system-message-box"
  122. );
  123. previousMessages.forEach((message) => {
  124. const prevIsSystem = message.classList.contains("system-message-box");
  125. const startTranslate = prevIsSystem
  126. ? newIsSystem
  127. ? "translateY(calc(100% + 5px))"
  128. : "translateY(calc(500% + 5px))"
  129. : newIsSystem
  130. ? "translateY(calc(20% + 5px))"
  131. : "translateY(calc(100% + 5px))";
  132. message.animate(
  133. [{ transform: startTranslate }, { transform: "translateY(0%)" }],
  134. {
  135. duration: 100,
  136. easing: "linear",
  137. fill: "forwards",
  138. }
  139. );
  140. });
  141. }
  142. // run when a new message is received from the server
  143. function handleMessage(msg) {
  144. const data = JSON.parse(msg);
  145. if (data.type === "system") {
  146. addSystemMessageToChatLog(data.content);
  147. return;
  148. }
  149. addToChatLog(data);
  150. }
  151. // listens for new messages from the server
  152. async function listen() {
  153. try {
  154. const response = await fetch("/api/messages");
  155. if (response.status === 200) {
  156. const msg = await response.text();
  157. handleMessage(msg);
  158. }
  159. } catch (err) {
  160. console.error("error listening messages:", err);
  161. } finally {
  162. // goes back to listening just after receiving a message or on error
  163. setTimeout(listen, 50); // small delay to avoid stack overflow
  164. }
  165. }
  166. // load backlog first, then start listening
  167. async function loadBacklog() {
  168. try {
  169. const response = await fetch("/api/backlog");
  170. if (response.status === 200) {
  171. const messages = await response.json();
  172. // append chronologically
  173. for (const msg of messages) {
  174. if (msg.type === "system") {
  175. addSystemMessageToChatLog(msg.content);
  176. } else {
  177. addToChatLog(msg);
  178. }
  179. }
  180. }
  181. } catch (err) {
  182. console.error("error loading backlog:", err);
  183. }
  184. }
  185. // start listening for messages right after loading the app backlog
  186. loadBacklog().then(() => listen());
  187. // sets the username label in the user message box
  188. const usernameLabel = document.querySelector(
  189. "#user-message-box > .message-header > .username"
  190. );
  191. usernameLabel.innerHTML = username;