From 3f6c9bf7c76fdf2bdd90c978ffb10194dbbbb0cf Mon Sep 17 00:00:00 2001 From: silvertakana Date: Tue, 10 Mar 2026 11:50:07 +1300 Subject: [PATCH] feat: Add core application UI components including `AppShell`, `SearchBar`, and `FloatingWindow`, alongside search history, API key management, and globe interaction hooks. --- src/app/api/keys/verify/route.ts | 57 +++++++ src/components/common/FloatingWindow.tsx | 109 +++++++++--- src/components/common/LocationPinOverlay.tsx | 95 ----------- src/components/layout/AppShell.tsx | 2 - src/components/layout/SearchBar.tsx | 9 + src/components/layout/useSearch.tsx | 34 +++- src/components/layout/useSearchHistory.ts | 47 +++++ .../panels/DataConfig/ApiKeysTab.tsx | 161 ++++++++++++++---- src/core/globe/hooks/searchPinAnimation.ts | 108 ++++++++++++ src/core/globe/hooks/useCameraActions.ts | 4 +- src/core/plugins/PluginTypes.ts | 1 - tmp/test-firms.mjs | 10 ++ 12 files changed, 475 insertions(+), 162 deletions(-) create mode 100644 src/app/api/keys/verify/route.ts delete mode 100644 src/components/common/LocationPinOverlay.tsx create mode 100644 src/components/layout/useSearchHistory.ts create mode 100644 src/core/globe/hooks/searchPinAnimation.ts create mode 100644 tmp/test-firms.mjs diff --git a/src/app/api/keys/verify/route.ts b/src/app/api/keys/verify/route.ts new file mode 100644 index 00000000..8a9f45cf --- /dev/null +++ b/src/app/api/keys/verify/route.ts @@ -0,0 +1,57 @@ +import { NextResponse } from "next/server"; + +/** Minimum length sanity check before attempting verification. */ +const MIN_KEY_LENGTH = 20; + +async function verifyGoogleMaps(key: string): Promise<{ valid: boolean; error?: string }> { + // Use a minimal Places Autocomplete request as a probe + const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=a&key=${encodeURIComponent(key)}`; + const res = await fetch(url); + const data = await res.json(); + if (data.status === "OK" || data.status === "ZERO_RESULTS") { + return { valid: true }; + } + return { valid: false, error: data.error_message || data.status }; +} + +async function verifyNasaFirms(key: string): Promise<{ valid: boolean; error?: string }> { + // FIRMS returns 200 with "Invalid MAP_KEY." body on failure + const url = `https://firms.modaps.eosdis.nasa.gov/api/area/csv/${encodeURIComponent(key)}/VIIRS_SNPP_NRT/world/1`; + const res = await fetch(url); + const text = await res.text(); + if (text.trim().startsWith("Invalid MAP_KEY")) { + return { valid: false, error: "Invalid MAP_KEY" }; + } + return { valid: true }; +} + +export async function POST(request: Request) { + let body: { service?: string; key?: string }; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid request body" }, { status: 400 }); + } + + const { service, key } = body; + if (!service || !key || typeof key !== "string") { + return NextResponse.json({ error: "service and key are required" }, { status: 400 }); + } + if (key.length < MIN_KEY_LENGTH) { + return NextResponse.json({ valid: false, error: "Key is too short" }); + } + + try { + switch (service) { + case "google_maps": + return NextResponse.json(await verifyGoogleMaps(key)); + case "nasa_firms": + return NextResponse.json(await verifyNasaFirms(key)); + default: + return NextResponse.json({ error: `Unknown service: ${service}` }, { status: 400 }); + } + } catch (err) { + console.error("[KeyVerify] Unexpected error:", err); + return NextResponse.json({ error: "Verification request failed" }, { status: 500 }); + } +} diff --git a/src/components/common/FloatingWindow.tsx b/src/components/common/FloatingWindow.tsx index 68c27d72..90922b5b 100644 --- a/src/components/common/FloatingWindow.tsx +++ b/src/components/common/FloatingWindow.tsx @@ -1,7 +1,7 @@ "use client"; import React, { useState, useEffect, useRef, useCallback } from "react"; -import { X, Minus, Maximize2, Square } from "lucide-react"; +import { X } from "lucide-react"; interface FloatingWindowProps { id: string; @@ -30,44 +30,50 @@ export const FloatingWindow: React.FC = ({ const [size, setSize] = useState(initialSize); const [isDragging, setIsDragging] = useState(false); const [isResizing, setIsResizing] = useState(false); - const [dragStart, setDragStart] = useState({ x: 0, y: 0 }); + const dragStart = useRef({ x: 0, y: 0 }); + const posRef = useRef(pos); + const sizeRef = useRef(size); const windowRef = useRef(null); + // Keep refs in sync for use inside event callbacks + useEffect(() => { posRef.current = pos; }, [pos]); + useEffect(() => { sizeRef.current = size; }, [size]); + + // ── Mouse drag ──────────────────────────────────────────────────────────── const handleMouseDown = (e: React.MouseEvent) => { if ((e.target as HTMLElement).closest(".window-controls")) return; setIsDragging(true); - setDragStart({ x: e.clientX - pos.x, y: e.clientY - pos.y }); + dragStart.current = { x: e.clientX - pos.x, y: e.clientY - pos.y }; }; const handleResizeMouseDown = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); setIsResizing(true); - setDragStart({ x: e.clientX, y: e.clientY }); + dragStart.current = { x: e.clientX, y: e.clientY }; }; const handleMouseMove = useCallback((e: MouseEvent) => { if (isDragging) { - const newX = e.clientX - dragStart.x; - const newY = e.clientY - dragStart.y; - setPos({ x: newX, y: newY }); + setPos({ x: e.clientX - dragStart.current.x, y: e.clientY - dragStart.current.y }); } else if (isResizing) { - const deltaX = e.clientX - dragStart.x; - const deltaY = e.clientY - dragStart.y; - const newWidth = Math.max(minWidth, size.width + deltaX); - const newHeight = Math.max(minHeight, size.height + deltaY); - setSize({ width: newWidth, height: newHeight }); - setDragStart({ x: e.clientX, y: e.clientY }); + const deltaX = e.clientX - dragStart.current.x; + const deltaY = e.clientY - dragStart.current.y; + setSize(prev => ({ + width: Math.max(minWidth, prev.width + deltaX), + height: Math.max(minHeight, prev.height + deltaY), + })); + dragStart.current = { x: e.clientX, y: e.clientY }; } - }, [isDragging, isResizing, dragStart, pos, size, minWidth, minHeight]); + }, [isDragging, isResizing, minWidth, minHeight]); const handleMouseUp = useCallback(() => { if (isDragging || isResizing) { setIsDragging(false); setIsResizing(false); - onUpdate?.({ position: pos, size: size }); + onUpdate?.({ position: posRef.current, size: sizeRef.current }); } - }, [isDragging, isResizing, pos, size, onUpdate]); + }, [isDragging, isResizing, onUpdate]); useEffect(() => { if (isDragging || isResizing) { @@ -83,6 +89,60 @@ export const FloatingWindow: React.FC = ({ }; }, [isDragging, isResizing, handleMouseMove, handleMouseUp]); + // ── Touch drag ──────────────────────────────────────────────────────────── + const handleTouchStartDrag = (e: React.TouchEvent) => { + if ((e.target as HTMLElement).closest(".window-controls")) return; + const touch = e.touches[0]; + setIsDragging(true); + dragStart.current = { x: touch.clientX - posRef.current.x, y: touch.clientY - posRef.current.y }; + }; + + const handleTouchStartResize = (e: React.TouchEvent) => { + e.stopPropagation(); + const touch = e.touches[0]; + setIsResizing(true); + dragStart.current = { x: touch.clientX, y: touch.clientY }; + }; + + const handleTouchMove = useCallback((e: TouchEvent) => { + e.preventDefault(); // prevent page scroll while dragging + const touch = e.touches[0]; + if (isDragging) { + setPos({ x: touch.clientX - dragStart.current.x, y: touch.clientY - dragStart.current.y }); + } else if (isResizing) { + const deltaX = touch.clientX - dragStart.current.x; + const deltaY = touch.clientY - dragStart.current.y; + setSize(prev => ({ + width: Math.max(minWidth, prev.width + deltaX), + height: Math.max(minHeight, prev.height + deltaY), + })); + dragStart.current = { x: touch.clientX, y: touch.clientY }; + } + }, [isDragging, isResizing, minWidth, minHeight]); + + const handleTouchEnd = useCallback(() => { + if (isDragging || isResizing) { + setIsDragging(false); + setIsResizing(false); + onUpdate?.({ position: posRef.current, size: sizeRef.current }); + } + }, [isDragging, isResizing, onUpdate]); + + useEffect(() => { + const opts = { passive: false } as AddEventListenerOptions; + if (isDragging || isResizing) { + window.addEventListener("touchmove", handleTouchMove, opts); + window.addEventListener("touchend", handleTouchEnd); + } else { + window.removeEventListener("touchmove", handleTouchMove); + window.removeEventListener("touchend", handleTouchEnd); + } + return () => { + window.removeEventListener("touchmove", handleTouchMove); + window.removeEventListener("touchend", handleTouchEnd); + }; + }, [isDragging, isResizing, handleTouchMove, handleTouchEnd]); + return (
= ({ border: "1px solid rgba(255, 255, 255, 0.15)", boxShadow: "0 20px 40px rgba(0, 0, 0, 0.4)", overflow: "hidden", - color: "white" + color: "white", + touchAction: "none", // prevent browser gestures on the window itself }} > {/* Header / Title Bar */} @@ -114,9 +175,11 @@ export const FloatingWindow: React.FC = ({ backgroundColor: "rgba(255, 255, 255, 0.05)", borderBottom: "1px solid rgba(255, 255, 255, 0.1)", cursor: isDragging ? "grabbing" : "grab", - userSelect: "none" + userSelect: "none", + touchAction: "none", }} onMouseDown={handleMouseDown} + onTouchStart={handleTouchStartDrag} > {title} @@ -162,18 +225,20 @@ export const FloatingWindow: React.FC = ({ position: "absolute", bottom: 0, right: 0, - width: "16px", - height: "16px", + width: "24px", + height: "24px", cursor: "nwse-resize", zIndex: 1001, display: "flex", alignItems: "flex-end", justifyContent: "flex-end", - padding: "2px" + padding: "4px", + touchAction: "none", }} onMouseDown={handleResizeMouseDown} + onTouchStart={handleTouchStartResize} > -
+
); diff --git a/src/components/common/LocationPinOverlay.tsx b/src/components/common/LocationPinOverlay.tsx deleted file mode 100644 index 40a4d781..00000000 --- a/src/components/common/LocationPinOverlay.tsx +++ /dev/null @@ -1,95 +0,0 @@ -"use client"; - -import { useEffect, useState } from "react"; -import { dataBus } from "@/core/data/DataBus"; - -// Animation duration in ms — must match CSS --pin-duration -const ANIM_DURATION_MS = 2400; - -export function LocationPinOverlay() { - const [visible, setVisible] = useState(false); - - useEffect(() => { - const unsub = dataBus.on("showLocationPin", () => { - setVisible(true); - const t = setTimeout(() => setVisible(false), ANIM_DURATION_MS); - return () => clearTimeout(t); - }); - return unsub; - }, []); - - if (!visible) return null; - - return ( - ); } diff --git a/src/components/layout/SearchBar.tsx b/src/components/layout/SearchBar.tsx index 66ed6ede..824658da 100644 --- a/src/components/layout/SearchBar.tsx +++ b/src/components/layout/SearchBar.tsx @@ -26,6 +26,15 @@ export function SearchBar() { }, [setIsOpen]); const handleKeyDown = (e: React.KeyboardEvent) => { + const isArrow = e.key === "ArrowDown" || e.key === "ArrowUp"; + + // Open history dropdown when pressing arrows on empty bar + if (isArrow && !isOpen && !query.trim()) { + e.preventDefault(); + setIsOpen(true); + return; + } + if (!isOpen || flatResults.length === 0) return; if (e.key === "ArrowDown") { diff --git a/src/components/layout/useSearch.tsx b/src/components/layout/useSearch.tsx index bc0e7564..8ad462a5 100644 --- a/src/components/layout/useSearch.tsx +++ b/src/components/layout/useSearch.tsx @@ -1,7 +1,7 @@ "use client"; -import { useState, useEffect } from "react"; -import { MapPin, Building, LandmarkIcon, Globe } from "lucide-react"; +import { useState, useEffect, useMemo } from "react"; +import { MapPin, Building, LandmarkIcon, Globe, Clock } from "lucide-react"; import { useStore } from "@/core/state/store"; import { dataBus } from "@/core/data/DataBus"; import { pluginManager } from "@/core/plugins/PluginManager"; @@ -9,6 +9,7 @@ import type { GeoEntity } from "@/core/plugins/PluginTypes"; import { PluginIcon } from "@/components/common/PluginIcon"; import { buildUserKeyHeaders } from "@/lib/userApiKeys"; import { categorizePlace, getZoomForTypes, type PlaceCategory } from "./placeCategories"; +import { useSearchHistory } from "./useSearchHistory"; // ─── Types ─────────────────────────────────────────────────── export interface SearchResult { @@ -142,18 +143,38 @@ async function searchLocations(query: string): Promise { export function useSearch() { const [query, setQuery] = useState(""); const [isOpen, setIsOpen] = useState(false); - const [sections, setSections] = useState([]); + const [liveSections, setLiveSections] = useState([]); const [selectedIndex, setSelectedIndex] = useState(0); const layers = useStore((s) => s.layers); const setCameraPosition = useStore((s) => s.setCameraPosition); const setSelectedEntity = useStore((s) => s.setSelectedEntity); + const { history, addToHistory, clearHistory } = useSearchHistory(); + + // Build sections: history on empty query; history matches + live results when typing + const sections: SearchSection[] = useMemo(() => { + const q = query.trim().toLowerCase(); + if (!q) { + if (history.length === 0) return []; + return [{ title: "Recent", icon: , results: history, maxScore: 0 }]; + } + const matchingHistory = history.filter( + (r) => + r.label.toLowerCase().includes(q) || + (r.subLabel && r.subLabel.toLowerCase().includes(q)) + ); + const recentSection: SearchSection | null = + matchingHistory.length > 0 + ? { title: "Recent", icon: , results: matchingHistory, maxScore: 99 } + : null; + return recentSection ? [recentSection, ...liveSections] : liveSections; + }, [query, history, liveSections]); const flatResults = sections.flatMap((s) => s.results); // Debounced search useEffect(() => { if (!query.trim()) { - setSections([]); + setLiveSections([]); setSelectedIndex(0); return; } @@ -165,7 +186,7 @@ export function useSearch() { if (isStale) return; if (locationSection) newSections.push(locationSection); newSections.sort((a, b) => b.maxScore - a.maxScore); - setSections(newSections); + setLiveSections(newSections); setSelectedIndex(0); }; @@ -175,6 +196,7 @@ export function useSearch() { // Selection handler const handleSelect = async (result: SearchResult) => { + addToHistory(result); setIsOpen(false); setQuery(""); if (result.type === "entity" && result.entity) { @@ -214,6 +236,6 @@ export function useSearch() { return { query, setQuery, isOpen, setIsOpen, sections, selectedIndex, setSelectedIndex, - flatResults, handleSelect, + flatResults, handleSelect, clearHistory, }; } diff --git a/src/components/layout/useSearchHistory.ts b/src/components/layout/useSearchHistory.ts new file mode 100644 index 00000000..9ebf1646 --- /dev/null +++ b/src/components/layout/useSearchHistory.ts @@ -0,0 +1,47 @@ +/** + * useSearchHistory — localStorage-backed recent search cache. + * Stores up to MAX_HISTORY SearchResult items, most-recent-first. + */ + +import { useState, useCallback } from "react"; +import type { SearchResult } from "./useSearch"; + +const STORAGE_KEY = "wwv_search_history"; +const MAX_HISTORY = 10; + +function readHistory(): SearchResult[] { + try { + const raw = localStorage.getItem(STORAGE_KEY); + return raw ? (JSON.parse(raw) as SearchResult[]) : []; + } catch { + return []; + } +} + +function writeHistory(history: SearchResult[]): void { + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(history)); + } catch { + // Storage quota exceeded or SSR — silently ignore. + } +} + +export function useSearchHistory() { + const [history, setHistory] = useState(readHistory); + + const addToHistory = useCallback((result: SearchResult) => { + setHistory((prev) => { + const deduped = prev.filter((r) => r.id !== result.id); + const next = [result, ...deduped].slice(0, MAX_HISTORY); + writeHistory(next); + return next; + }); + }, []); + + const clearHistory = useCallback(() => { + writeHistory([]); + setHistory([]); + }, []); + + return { history, addToHistory, clearHistory }; +} diff --git a/src/components/panels/DataConfig/ApiKeysTab.tsx b/src/components/panels/DataConfig/ApiKeysTab.tsx index 24500867..27782233 100644 --- a/src/components/panels/DataConfig/ApiKeysTab.tsx +++ b/src/components/panels/DataConfig/ApiKeysTab.tsx @@ -1,5 +1,5 @@ -import { useState, useCallback } from "react"; -import { Eye, EyeOff, Trash2, Key } from "lucide-react"; +import { useState, useCallback, useEffect, useRef } from "react"; +import { Eye, EyeOff, Trash2, Key, CheckCircle, XCircle, Loader, ShieldCheck } from "lucide-react"; import { API_KEY_REGISTRY, getUserApiKey, @@ -8,6 +8,8 @@ import { } from "@/lib/userApiKeys"; import { sectionHeaderStyle, inputGroupStyle, labelStyle } from "./sharedStyles"; +type VerifyStatus = "idle" | "verifying" | "valid" | "invalid"; + const keyInputStyle: React.CSSProperties = { background: "var(--bg-tertiary)", border: "1px solid var(--border-subtle)", @@ -30,8 +32,24 @@ const toggleBtnStyle: React.CSSProperties = { alignItems: "center", }; +const DEBOUNCE_MS = 800; +const MIN_KEY_LENGTH = 20; + +function StatusIcon({ status }: { status: VerifyStatus }) { + if (status === "verifying") + return ( + + + + ); + if (status === "valid") + return ; + if (status === "invalid") + return ; + return null; +} + export function ApiKeysTab() { - // Initialise state from localStorage for each service const [keys, setKeys] = useState>(() => { const initial: Record = {}; API_KEY_REGISTRY.forEach((e) => { @@ -41,27 +59,73 @@ export function ApiKeysTab() { }); const [visible, setVisible] = useState>({}); + const [status, setStatus] = useState>({}); + const [errors, setErrors] = useState>({}); + const debounceRefs = useRef>>({}); + + const verifyKey = useCallback(async (service: string, key: string) => { + setStatus((prev) => ({ ...prev, [service]: "verifying" })); + setErrors((prev) => ({ ...prev, [service]: "" })); + try { + const res = await fetch("/api/keys/verify", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ service, key }), + }); + const data = await res.json(); + setStatus((prev) => ({ ...prev, [service]: data.valid ? "valid" : "invalid" })); + if (!data.valid) setErrors((prev) => ({ ...prev, [service]: data.error || "Invalid key" })); + } catch { + setStatus((prev) => ({ ...prev, [service]: "invalid" })); + setErrors((prev) => ({ ...prev, [service]: "Verification failed" })); + } + }, []); const handleChange = useCallback((service: string, value: string) => { setKeys((prev) => ({ ...prev, [service]: value })); setUserApiKey(service, value); + setStatus((prev) => ({ ...prev, [service]: "idle" })); + setErrors((prev) => ({ ...prev, [service]: "" })); + + clearTimeout(debounceRefs.current[service]); + if (value.length >= MIN_KEY_LENGTH) { + debounceRefs.current[service] = setTimeout(() => verifyKey(service, value), DEBOUNCE_MS); + } + }, [verifyKey]); + + const handleManualVerify = useCallback((service: string) => { + const key = keys[service]; + if (key && key.length >= MIN_KEY_LENGTH) verifyKey(service, key); + }, [keys, verifyKey]); + + // Verify pre-loaded keys on mount + useEffect(() => { + API_KEY_REGISTRY.forEach((e) => { + const key = getUserApiKey(e.service); + if (key.length >= MIN_KEY_LENGTH) verifyKey(e.service, key); + }); + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - const toggleVisibility = useCallback((service: string) => { - setVisible((prev) => ({ ...prev, [service]: !prev[service] })); - }, []); + const toggleVisibility = useCallback( + (service: string) => setVisible((prev) => ({ ...prev, [service]: !prev[service] })), + [] + ); const handleClearAll = useCallback(() => { clearAllUserApiKeys(); const cleared: Record = {}; API_KEY_REGISTRY.forEach((e) => (cleared[e.service] = "")); setKeys(cleared); + setStatus({}); + setErrors({}); }, []); const hasAnyKey = Object.values(keys).some((v) => v.length > 0); return ( <> +
@@ -72,36 +136,63 @@ export function ApiKeysTab() { Keys are stored only in your browser.
- {API_KEY_REGISTRY.map((entry) => ( -
-
- + {API_KEY_REGISTRY.map((entry) => { + const st = status[entry.service] ?? "idle"; + const err = errors[entry.service]; + const borderColor = + st === "valid" ? "rgba(34,197,94,0.5)" + : st === "invalid" ? "rgba(239,68,68,0.5)" + : "var(--border-subtle)"; + + return ( +
+
+ +
+
+ handleChange(entry.service, e.target.value)} + style={{ ...keyInputStyle, border: `1px solid ${borderColor}` }} + spellCheck={false} + autoComplete="new-password" + data-form-type="other" + data-lpignore="true" + name={`wwv-apikey-${entry.service}`} + /> + + + +
+ {st === "invalid" && err && ( +
{err}
+ )} + {st === "valid" && ( +
Key verified ✓
+ )}
-
- handleChange(entry.service, e.target.value)} - style={keyInputStyle} - spellCheck={false} - autoComplete="new-password" - data-form-type="other" - data-lpignore="true" - name={`wwv-apikey-${entry.service}`} - /> - -
-
- ))} + ); + })}
{hasAnyKey && ( diff --git a/src/core/globe/hooks/searchPinAnimation.ts b/src/core/globe/hooks/searchPinAnimation.ts new file mode 100644 index 00000000..6aa44c71 --- /dev/null +++ b/src/core/globe/hooks/searchPinAnimation.ts @@ -0,0 +1,108 @@ +import type { Viewer as CesiumViewer } from "cesium"; +import { Cartesian3, Cartesian2, Color, HeightReference } from "cesium"; + +/** Duration of the full animation sequence in ms */ +const TOTAL_DURATION_MS = 2500; +/** Duration of the drop bounce phase in ms */ +const DROP_DURATION_MS = 600; +/** Starting Y offset in pixels (above the target) */ +const DROP_START_PX = -80; +/** Billboard image: gold map-pin SVG encoded as data URI */ +const PIN_IMAGE = buildPinDataUri(); + +let _pinEntity: ReturnType | null = null; +let _animFrameId: number | null = null; + +/** + * Shows a temporary animated map-pin billboard at the given lat/lon. + * Pin drops from above, bounces, then fades out. + */ +export function showSearchPin(viewer: CesiumViewer, lat: number, lon: number) { + if (viewer.isDestroyed()) return; + + // Clean up previous pin if still active + cleanup(viewer); + + const position = Cartesian3.fromDegrees(lon, lat, 0); + + _pinEntity = viewer.entities.add({ + position, + billboard: { + image: PIN_IMAGE, + width: 36, + height: 48, + // Anchor at bottom-center of the pin so the tip points at the location + verticalOrigin: 1, // BOTTOM + horizontalOrigin: 0, // CENTER + pixelOffset: new Cartesian2(0, DROP_START_PX), + color: Color.WHITE, + heightReference: HeightReference.CLAMP_TO_GROUND, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + + const entity = _pinEntity; + const startTime = performance.now(); + + const animate = (now: number) => { + if (!entity.billboard || viewer.isDestroyed()) return; + + const elapsed = now - startTime; + + // Phase 1: Drop + bounce (0 → DROP_DURATION_MS) + if (elapsed < DROP_DURATION_MS) { + const t = elapsed / DROP_DURATION_MS; + const y = easeOutBounce(t) * DROP_START_PX * -1 + DROP_START_PX; + entity.billboard.pixelOffset = new Cartesian2(0, y) as any; + } + // Phase 2: Hold visible (DROP_DURATION_MS → TOTAL_DURATION_MS - 600) + else if (elapsed < TOTAL_DURATION_MS - 600) { + entity.billboard.pixelOffset = new Cartesian2(0, 0) as any; + } + // Phase 3: Fade out (last 600ms) + else if (elapsed < TOTAL_DURATION_MS) { + const fadeT = (elapsed - (TOTAL_DURATION_MS - 600)) / 600; + entity.billboard.pixelOffset = new Cartesian2(0, 0) as any; + entity.billboard.color = Color.fromAlpha(Color.WHITE, 1 - fadeT) as any; + } + // Done + else { + cleanup(viewer); + return; + } + + _animFrameId = requestAnimationFrame(animate); + }; + + _animFrameId = requestAnimationFrame(animate); +} + +function cleanup(viewer: CesiumViewer) { + if (_animFrameId !== null) { + cancelAnimationFrame(_animFrameId); + _animFrameId = null; + } + if (_pinEntity && !viewer.isDestroyed()) { + viewer.entities.remove(_pinEntity); + _pinEntity = null; + } +} + +/** Standard ease-out-bounce: t ∈ [0,1] → [0,1] */ +function easeOutBounce(t: number): number { + if (t < 1 / 2.75) return 7.5625 * t * t; + if (t < 2 / 2.75) { t -= 1.5 / 2.75; return 7.5625 * t * t + 0.75; } + if (t < 2.5 / 2.75) { t -= 2.25 / 2.75; return 7.5625 * t * t + 0.9375; } + t -= 2.625 / 2.75; + return 7.5625 * t * t + 0.984375; +} + +/** Builds a gold map-pin SVG as a data URI */ +function buildPinDataUri(): string { + const svg = ` + + + `; + return `data:image/svg+xml;base64,${btoa(svg)}`; +} diff --git a/src/core/globe/hooks/useCameraActions.ts b/src/core/globe/hooks/useCameraActions.ts index e036b750..90f58503 100644 --- a/src/core/globe/hooks/useCameraActions.ts +++ b/src/core/globe/hooks/useCameraActions.ts @@ -2,6 +2,7 @@ import { useEffect } from "react"; import type { Viewer as CesiumViewer } from "cesium"; import { Cartesian3, Ellipsoid, Math as CesiumMath, Transforms, Matrix4 } from "cesium"; import { dataBus } from "@/core/data/DataBus"; +import { showSearchPin } from "./searchPinAnimation"; export function useCameraActions(viewer: CesiumViewer | null, isReady: boolean) { useEffect(() => { @@ -110,7 +111,7 @@ export function useCameraActions(viewer: CesiumViewer | null, isReady: boolean) orientation: orientation, duration: 1.5, complete: () => { - dataBus.emit("showLocationPin", {}); + showSearchPin(viewer, lat, lon); }, }); }, 50); @@ -122,3 +123,4 @@ export function useCameraActions(viewer: CesiumViewer | null, isReady: boolean) }; }, [viewer, isReady]); } + diff --git a/src/core/plugins/PluginTypes.ts b/src/core/plugins/PluginTypes.ts index 09dbd10a..0d0a3e29 100644 --- a/src/core/plugins/PluginTypes.ts +++ b/src/core/plugins/PluginTypes.ts @@ -183,5 +183,4 @@ export type DataBusEvents = { cameraFaceTowards: { lat: number; lon: number; alt: number }; cameraGoTo: { lat: number; lon: number; alt: number; distance?: number; maxPitch?: number; heading?: number }; globeReady: Record; - showLocationPin: Record; }; diff --git a/tmp/test-firms.mjs b/tmp/test-firms.mjs new file mode 100644 index 00000000..e03d29b6 --- /dev/null +++ b/tmp/test-firms.mjs @@ -0,0 +1,10 @@ +async function testFirms() { + const key = "invalid_key_12345"; + const url = `https://firms.modaps.eosdis.nasa.gov/api/area/csv/${key}/VIIRS_SNPP_NRT/world/1`; + const response = await fetch(url); + const text = await response.text(); + console.log("Status:", response.status); + console.log("Text:", text); +} + +testFirms();