File size: 9,130 Bytes
0ff9b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useEffect, useState, useRef, useCallback } from "react";
import { useStore } from "../state/store";
import { useNavigate } from "react-router-dom";
import "./Orbit.css";

const API_BASE = process.env.REACT_APP_API_BASE || "";

export function Orbit() {
  const { setUi } = useStore();
  const navigate = useNavigate();
  const [isActive, setIsActive] = useState(false);
  const [position, setPosition] = useState({ x: 100, y: 100 });
  const [size, setSize] = useState(30);

  const synthRef = useRef(window.speechSynthesis);
  const recognitionRef = useRef(null);
  const sleepTimeoutRef = useRef(null);
  const draggingRef = useRef(false);
  const resizingRef = useRef(false);
  const offsetRef = useRef({ x: 0, y: 0 });
  const audioRef = useRef(null);

  // Gesture refs
  const lastTapRef = useRef(0);
  const longPressTimerRef = useRef(null);
  const isLongPressRef = useRef(false);
  const disableSleepRef = useRef(false);

  // ๐ŸŽจ Orb visual state
  const setOrbStyle = useCallback((state) => {
    const root = document.documentElement;
    const styles = {
      dormant: {
        "--orb-core": "rgba(100,100,255,0.3)",
        "--orb-glow": "rgba(80,80,220,0.2)",
        "--orb-ray": "transparent",
        "--orb-scale": "0.8",
        "--orb-opacity": "0.4",
      },
      wake: {
        "--orb-core": "rgba(120,120,255,0.8)",
        "--orb-glow": "rgba(100,100,255,0.5)",
        "--orb-ray": "transparent",
        "--orb-scale": "1",
        "--orb-opacity": "1",
      },
      listening: {
        "--orb-core": "rgba(0,230,255,0.9)",
        "--orb-glow": "rgba(0,200,255,0.6)",
        "--orb-ray": "transparent",
        "--orb-scale": "1.1",
        "--orb-opacity": "1",
      },
      thinking: {
        "--orb-core": "rgba(255,180,0,0.8)",
        "--orb-glow": "rgba(255,160,0,0.5)",
        "--orb-ray": "transparent",
        "--orb-scale": "1.05",
        "--orb-opacity": "1",
      },
      speaking: {
        "--orb-core": "rgba(255,241,118,0.9)",
        "--orb-glow": "rgba(255,225,100,0.5)",
        "--orb-ray": "rgba(255,241,118,0.3)",
        "--orb-scale": "1",
        "--orb-opacity": "1",
      },
      error: {
        "--orb-core": "rgba(255,80,80,0.8)",
        "--orb-glow": "rgba(220,60,60,0.5)",
        "--orb-ray": "transparent",
        "--orb-scale": "1",
        "--orb-opacity": "1",
      },
      warning: {
        "--orb-core": "rgba(255,165,0,0.8)",
        "--orb-glow": "rgba(255,140,0,0.5)",
        "--orb-ray": "transparent",
        "--orb-scale": "1",
        "--orb-opacity": "1",
      },
    };
    const selected = styles[state] || styles["dormant"];
    Object.keys(selected).forEach((key) => root.style.setProperty(key, selected[key]));
  }, []);

  // ๐Ÿ“ด Stop & sleep
  const stopAll = useCallback(() => {
    if (synthRef.current.speaking) synthRef.current.cancel();
    if (recognitionRef.current) {
      try { recognitionRef.current.stop(); } catch {}
    }
    setUi((u) => ({ ...u, orbit: "dormant" }));
    setOrbStyle("dormant");
    setIsActive(false);
    if (sleepTimeoutRef.current) clearTimeout(sleepTimeoutRef.current);
  }, [setUi, setOrbStyle]);

  // ๐Ÿ—ฃ Speak
  const speak = useCallback((text, after) => {
    if (!text) return;
    setOrbStyle("speaking");
    setUi((u) => ({ ...u, orbit: "speaking" }));

    const utter = new SpeechSynthesisUtterance(text);
    utter.onend = () => {
      if (isActive) {
        setOrbStyle("listening");
        setUi((u) => ({ ...u, orbit: "listening" }));
        if (!disableSleepRef.current) resetSleepTimer();
      } else {
        setOrbStyle("dormant");
      }
      if (after) after();
    };
    utter.onerror = () => setOrbStyle("error");
    synthRef.current.speak(utter);
  }, [isActive, setUi, setOrbStyle]);

  // โฒ Sleep timer
  const resetSleepTimer = useCallback(() => {
    if (disableSleepRef.current) return;
    if (sleepTimeoutRef.current) clearTimeout(sleepTimeoutRef.current);
    sleepTimeoutRef.current = setTimeout(() => {
      speak("Going to sleep", stopAll);
    }, 15000);
  }, [speak, stopAll]);

  // ๐Ÿ’ฌ Send text to backend chat
  const queryBackend = async (message) => {
    try {
      setOrbStyle("thinking");
      setUi((u) => ({ ...u, orbit: "thinking" }));

      const token = localStorage.getItem("token");
      const formData = new FormData();
      formData.append("text", message);

      const res = await fetch(`${API_BASE}/v1/chat`, {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
        body: formData,
      });
      const data = await res.json();
      const reply = data.reply || "I donโ€™t have an answer right now.";
      speak(reply);
    } catch (err) {
      console.error("Backend error:", err);
      speak("Sorry, I couldnโ€™t reach the knowledge base.");
      setOrbStyle("warning");
      setUi((u) => ({ ...u, orbit: "warning" }));
    }
  };

  // ๐ŸŽ™ Speech Recognition
  useEffect(() => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) return console.warn("SpeechRecognition not supported");

    recognitionRef.current = new SR();
    recognitionRef.current.continuous = true;
    recognitionRef.current.interimResults = false;
    recognitionRef.current.lang = "en-US";

    recognitionRef.current.onresult = (e) => {
      const transcript = e.results[e.results.length - 1][0].transcript.trim();
      console.log("Heard:", transcript);

      if (!isActive) return;
      if (transcript.toLowerCase().includes("go to sleep")) {
        speak("Going to sleep", stopAll);
        return;
      }
      queryBackend(transcript);
    };

    recognitionRef.current.onend = () => recognitionRef.current.start();
    recognitionRef.current.start();

    return () => recognitionRef.current && recognitionRef.current.stop();
  }, [isActive, stopAll, speak]);

  // ๐Ÿ‘† Tap/longpress handlers
  const handlePointerDown = () => {
    const now = Date.now();
    if (now - lastTapRef.current < 300) {
      // Double tap โ†’ go to chat
      navigate("/chat");
    }
    lastTapRef.current = now;

    longPressTimerRef.current = setTimeout(() => {
      isLongPressRef.current = true;
      disableSleepRef.current = true;
      setIsActive(true);
      setOrbStyle("wake");
      setUi((u) => ({ ...u, orbit: "listening" }));
      if (audioRef.current) audioRef.current.play().catch(() => {});
      speak("Long press mode active. I'm listening continuously.");
    }, 600);
  };

  const handlePointerUp = () => {
    if (longPressTimerRef.current) clearTimeout(longPressTimerRef.current);
    if (isLongPressRef.current) {
      isLongPressRef.current = false;
      disableSleepRef.current = false;
      resetSleepTimer();
      speak("Long press released. Sleep timer re-enabled.");
    }
  };

  // ๐Ÿ–ฑ Drag + resize
  const handleMouseDown = (e, mode) => {
    if (mode === "drag") draggingRef.current = true;
    if (mode === "resize") resizingRef.current = true;
    offsetRef.current = { x: e.clientX, y: e.clientY };
  };

  const handleMouseMove = (e) => {
    if (draggingRef.current) {
      setPosition((pos) => {
        const newPos = { x: pos.x + (e.clientX - offsetRef.current.x), y: pos.y + (e.clientY - offsetRef.current.y) };
        offsetRef.current = { x: e.clientX, y: e.clientY };
        return newPos;
      });
    }
    if (resizingRef.current) {
      setSize((s) => Math.max(80, s + (e.clientX - offsetRef.current.x)));
      offsetRef.current = { x: e.clientX, y: e.clientY };
    }
  };

  const handleMouseUp = () => {
    draggingRef.current = false;
    resizingRef.current = false;
  };

  useEffect(() => {
    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("mouseup", handleMouseUp);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    };
  }, []);

  // ๐Ÿ’พ Save/load state
  useEffect(() => {
    const saved = JSON.parse(localStorage.getItem("orbit_state") || "{}");
    if (saved.x && saved.y) setPosition({ x: saved.x, y: saved.y });
    if (saved.size) setSize(saved.size);
  }, []);
  useEffect(() => {
    localStorage.setItem("orbit_state", JSON.stringify({ ...position, size }));
  }, [position, size]);

  return (
    <div

      className="orbit-wrapper"

      style={{ left: position.x, top: position.y, width: size, height: size }}

    >

      <audio ref={audioRef} src="/orbit.wav" preload="auto" />

      <div

        className="orbit"

        onMouseDown={(e) => handleMouseDown(e, "drag")}

        onPointerDown={handlePointerDown}

        onPointerUp={handlePointerUp}

        title="Orbit Assistant"

      />

      <div

        className="orbit-resize-handle"

        onMouseDown={(e) => handleMouseDown(e, "resize")}

      />

    </div>
  );
}