aboutsummaryrefslogtreecommitdiff
path: root/jb-ui/src/components/EventMarquee.tsx
blob: 4ce4f15a1fd967a6147acf5fc0824bc4b764223c (plain)
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
import { EventEnvelope, EventType, TaskEnterPayload, TaskFinishPayload } from "@/api_fsb";
import { formatSecondsVerbose, formatSource, formatStatus, truncate } from "@/lib/utils";
import { selectAllEvents, selectCurrentSpeed } from "@/models/grlEventsSlice";
import getUnicodeFlagIcon from 'country-flag-icons/unicode';
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";

// ─── Config ───────────────────────────────────────────────────────────────────

const SPEED_EASING = 0.025;  // how quickly speed transitions (per frame)

interface EventItemProps {
    event: EventEnvelope;
}

const EventTaskEnter = ({ event }: EventItemProps) => {
    const payload = event.payload as TaskEnterPayload;

    return (
        <>
            <span className="px-2 text-lg">{getUnicodeFlagIcon(payload.country_iso)}</span>
            <p>
                {truncate(event.product_user_id!, 6, "*****")} Entered{" "}
                {formatSource(payload.source)}{" "}
                (#{truncate(payload.survey_id!, 5, "***")})
            </p>
        </>
    )
}

const EventTaskFinish = ({ event }: EventItemProps) => {
    const payload = event.payload as TaskFinishPayload;

    return (
        <>
            <span className="px-2 text-lg">{getUnicodeFlagIcon(event.payload.country_iso)}</span>
            <p>
                {truncate(event.product_user_id!, 6, "*****")}{" "}
                {formatStatus(payload.status)} {formatSource(payload.source)}{" "}
                (#{truncate(payload.survey_id!, 5, "***")}) in{" "}
                {formatSecondsVerbose(payload.duration_sec!)}
            </p>
        </>
    )
}

const EventUserCreated = ({ event }: EventItemProps) => {

    return (
        <>
            <span className="px-2 text-lg">{getUnicodeFlagIcon(event.payload.country_iso)}</span>
            <p>{truncate(event.product_user_id!, 6, "*****")} Created</p>
        </>
    )
}


const EventComponent = ({ event }: EventItemProps) => {

    const renderContent = () => {
        switch (event.event_type) {
            case EventType.TaskEnter:
                return <EventTaskEnter event={event} />
            case EventType.TaskFinish:
                return <EventTaskFinish event={event} />
            case EventType.UserCreated:
                return <EventUserCreated event={event} />
            default:
                return <><p>Unknown event</p></>
        }
    }

    return (
        <div key={event.event_uuid!}
            className="inline-flex items-center text-[10px]
            font-mono px-2">
            {renderContent()}

            {/* <span className="text-red-500 pl-5">◆</span> */}
        </div >
    )
}


// ─── Main Component ───────────────────────────────────────────────────────────
export default function NewsTicker() {
    // --- Redux ---
    const reduxItems = useSelector(selectAllEvents);
    const targetSpeedRedux = useSelector(selectCurrentSpeed); // px/sec

    // --- Scroll state (all refs — no re-renders from animation) ---
    const containerRef = useRef<HTMLDivElement | null>(null);  // The ticker band 
    const stripRef = useRef<HTMLDivElement | null>(null);  // Scrolling strip
    const translateX = useRef(0);
    const currentSpeed = useRef(targetSpeedRedux);
    const targetSpeed = useRef(targetSpeedRedux);

    // Only state and refs persist across renders, the rest are re-initialized,
    // that is why this isn't just a standard variable.
    // Request Animation Frame reference (stores the animation frame ID)
    const rafRef = useRef<number | null>(null);
    const lastTime = useRef<number | null>(null);

    // --- Item tracking ---
    // Track which IDs are already in the scroller to only append 
    // genuinely new ones.
    const seenUUIDs = useRef(new Set<string>());
    const pendingQueue = useRef<EventEnvelope[]>([]);
    const [scrollItems, setScrollItems] = useState<EventEnvelope[]>([]);

    // --- Sync Redux → pendingQueue (only new items) ---
    useEffect(() => {
        const newItems = reduxItems.filter((item) => !seenUUIDs.current.has(item.event_uuid!));
        if (newItems.length === 0) return;

        newItems.forEach(item => seenUUIDs.current.add(item.event_uuid!));
        pendingQueue.current.push(...newItems);
    }, [reduxItems]);

    // --- Sync target speed from Redux ---
    useEffect(() => {
        targetSpeed.current = targetSpeedRedux;
    }, [targetSpeedRedux]);

    // --- RAF loop ---
    useEffect(() => {
        // This timestamp is a "high-resolution timestamp" provided by 
        // the browser, which is more accurate for measuring frame intervals 
        // than Date.now()
        const loop = (timestamp: number) => {
            console.log("RAF loop, timestamp:", timestamp, lastTime.current);

            if (!lastTime.current) lastTime.current = timestamp;
            const delta = (timestamp - lastTime.current) / 1000;
            lastTime.current = timestamp;

            // Slow easement towards targetSpeed
            currentSpeed.current +=
                (targetSpeed.current - currentSpeed.current) * SPEED_EASING;

            // flush pending queue into React state
            if (pendingQueue.current.length > 0) {
                const incoming = pendingQueue.current.splice(0);
                setScrollItems((prev) => [...prev, ...incoming]);
            }

            // Advance strip, slides it over left by X pixels
            translateX.current -= currentSpeed.current * delta;
            if (stripRef.current) {
                stripRef.current.style.transform = `translateX(${translateX.current}px)`;
            }

            // prune items that have fully exited the left edge
            if (stripRef.current && containerRef.current) {
                const children = Array.from(stripRef.current.children);
                const containerLeft = containerRef.current.getBoundingClientRect().left;
                let pruneCount = 0;
                let removedWidth = 0;

                for (const child of children) {
                    const rect = child.getBoundingClientRect();
                    if (rect.right < containerLeft - 20) {
                        pruneCount++;
                        removedWidth += rect.width;
                    } else {
                        break;
                    }
                }

                if (pruneCount > 0) {
                    translateX.current += removedWidth;
                    setScrollItems((prev) => prev.slice(pruneCount));
                }
            }

            // Assign the next loop
            rafRef.current = requestAnimationFrame(loop);
        };

        rafRef.current = requestAnimationFrame(loop);
        return () => cancelAnimationFrame(rafRef.current!);
    }, []);

    return (
        <div style={{
            minHeight: "3vh", display: "flex", flexDirection: "column",
            justifyContent: "center", alignItems: "center", gap: "0"
        }}>

            {/* Ticker wrapper */}
            <div style={{ width: "100%", position: "relative" }}>

                {/* The ticker band */}
                <div
                    ref={containerRef}
                    style={{
                        overflow: "hidden",
                        padding: "0",
                        position: "relative",
                    }}
                >

                    {/* Scrolling strip */}
                    <div
                        ref={stripRef}
                        style={{
                            display: "inline-flex",
                            alignItems: "center",
                            whiteSpace: "nowrap",
                            padding: "10px 0",
                            willChange: "transform",
                            position: "relative",
                            zIndex: 2,
                        }}
                    >
                        {scrollItems.map(item => (
                            <EventComponent event={item} />
                        ))}

                        {/* Trailing spacer so new content doesn't immediately snap in */}
                        <span style={{ paddingRight: "100vw", display: "inline-block" }} />

                    </div>
                </div>

            </div>

        </div>
    );
}