helper.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. (function() {
  2. const WS_URL = 'ws://' + window.location.host;
  3. let ws = null;
  4. let eventQueue = [];
  5. function connect() {
  6. ws = new WebSocket(WS_URL);
  7. ws.onopen = () => {
  8. eventQueue.forEach(e => ws.send(JSON.stringify(e)));
  9. eventQueue = [];
  10. };
  11. ws.onmessage = (msg) => {
  12. const data = JSON.parse(msg.data);
  13. if (data.type === 'reload') {
  14. window.location.reload();
  15. }
  16. };
  17. ws.onclose = () => {
  18. setTimeout(connect, 1000);
  19. };
  20. }
  21. function sendEvent(event) {
  22. event.timestamp = Date.now();
  23. if (ws && ws.readyState === WebSocket.OPEN) {
  24. ws.send(JSON.stringify(event));
  25. } else {
  26. eventQueue.push(event);
  27. }
  28. }
  29. // Capture clicks on choice elements
  30. document.addEventListener('click', (e) => {
  31. const target = e.target.closest('[data-choice]');
  32. if (!target) return;
  33. sendEvent({
  34. type: 'click',
  35. text: target.textContent.trim(),
  36. choice: target.dataset.choice,
  37. id: target.id || null
  38. });
  39. // Update indicator bar (defer so toggleSelect runs first)
  40. setTimeout(() => {
  41. const indicator = document.getElementById('indicator-text');
  42. if (!indicator) return;
  43. const container = target.closest('.options') || target.closest('.cards');
  44. const selected = container ? container.querySelectorAll('.selected') : [];
  45. if (selected.length === 0) {
  46. indicator.textContent = 'Click an option above, then return to the terminal';
  47. } else if (selected.length === 1) {
  48. const label = selected[0].querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || selected[0].dataset.choice;
  49. indicator.innerHTML = '<span class="selected-text">' + label + ' selected</span> — return to terminal to continue';
  50. } else {
  51. indicator.innerHTML = '<span class="selected-text">' + selected.length + ' selected</span> — return to terminal to continue';
  52. }
  53. }, 0);
  54. });
  55. // Frame UI: selection tracking
  56. window.selectedChoice = null;
  57. window.toggleSelect = function(el) {
  58. const container = el.closest('.options') || el.closest('.cards');
  59. const multi = container && container.dataset.multiselect !== undefined;
  60. if (container && !multi) {
  61. container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected'));
  62. }
  63. if (multi) {
  64. el.classList.toggle('selected');
  65. } else {
  66. el.classList.add('selected');
  67. }
  68. window.selectedChoice = el.dataset.choice;
  69. };
  70. // Expose API for explicit use
  71. window.brainstorm = {
  72. send: sendEvent,
  73. choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })
  74. };
  75. connect();
  76. })();