Răsfoiți Sursa

feat: add browser helper library for event capture

Jesse Vincent 7 luni în urmă
părinte
comite
e532c6dbbe
1 a modificat fișierele cu 97 adăugiri și 2 ștergeri
  1. 97 2
      lib/brainstorm-server/helper.js

+ 97 - 2
lib/brainstorm-server/helper.js

@@ -1,2 +1,97 @@
-// Placeholder - will be implemented in Task 2
-// This file captures user interactions and sends them via WebSocket
+(function() {
+  const WS_URL = 'ws://' + window.location.host;
+  let ws = null;
+  let eventQueue = [];
+
+  function connect() {
+    ws = new WebSocket(WS_URL);
+
+    ws.onopen = () => {
+      // Send any queued events
+      eventQueue.forEach(e => ws.send(JSON.stringify(e)));
+      eventQueue = [];
+    };
+
+    ws.onmessage = (msg) => {
+      const data = JSON.parse(msg.data);
+      if (data.type === 'reload') {
+        window.location.reload();
+      }
+    };
+
+    ws.onclose = () => {
+      // Reconnect after 1 second
+      setTimeout(connect, 1000);
+    };
+  }
+
+  function send(event) {
+    event.timestamp = Date.now();
+    if (ws && ws.readyState === WebSocket.OPEN) {
+      ws.send(JSON.stringify(event));
+    } else {
+      eventQueue.push(event);
+    }
+  }
+
+  // Auto-capture clicks on interactive elements
+  document.addEventListener('click', (e) => {
+    const target = e.target.closest('button, a, [data-choice], [role="button"], input[type="submit"]');
+    if (!target) return;
+
+    // Don't capture regular link navigation
+    if (target.tagName === 'A' && !target.dataset.choice) return;
+
+    e.preventDefault();
+
+    send({
+      type: 'click',
+      text: target.textContent.trim(),
+      choice: target.dataset.choice || null,
+      id: target.id || null,
+      className: target.className || null
+    });
+  });
+
+  // Auto-capture form submissions
+  document.addEventListener('submit', (e) => {
+    e.preventDefault();
+    const form = e.target;
+    const formData = new FormData(form);
+    const data = {};
+    formData.forEach((value, key) => { data[key] = value; });
+
+    send({
+      type: 'submit',
+      formId: form.id || null,
+      formName: form.name || null,
+      data: data
+    });
+  });
+
+  // Auto-capture input changes (debounced)
+  let inputTimeout = null;
+  document.addEventListener('input', (e) => {
+    const target = e.target;
+    if (!target.matches('input, textarea, select')) return;
+
+    clearTimeout(inputTimeout);
+    inputTimeout = setTimeout(() => {
+      send({
+        type: 'input',
+        name: target.name || null,
+        id: target.id || null,
+        value: target.value,
+        inputType: target.type || target.tagName.toLowerCase()
+      });
+    }, 500); // 500ms debounce
+  });
+
+  // Expose for explicit use if needed
+  window.brainstorm = {
+    send: send,
+    choice: (value, metadata = {}) => send({ type: 'choice', value, ...metadata })
+  };
+
+  connect();
+})();