feat: Add core application UI components including AppShell, SearchBar, and FloatingWindow, alongside search history, API key management, and globe interaction hooks.
This commit is contained in:
1 parent
3df54a8c47
commit
3f6c9bf7c7
12 files changed
+475
-162
No files matched your search
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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<FloatingWindowProps> = ({
|
||||
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<HTMLDivElement>(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<FloatingWindowProps> = ({
|
||||
};
|
||||
}, [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 (
|
||||
<div
|
||||
ref={windowRef}
|
||||
@@ -101,7 +161,8 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
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<FloatingWindowProps> = ({
|
||||
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}
|
||||
>
|
||||
<span style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255, 255, 255, 0.8)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
|
||||
{title}
|
||||
@@ -162,18 +225,20 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
|
||||
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}
|
||||
>
|
||||
<div style={{ width: "4px", height: "4px", backgroundColor: "rgba(255, 255, 255, 0.3)", borderRadius: "1px" }} />
|
||||
<div style={{ width: "6px", height: "6px", backgroundColor: "rgba(255, 255, 255, 0.3)", borderRadius: "1px" }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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 (
|
||||
<div
|
||||
className="location-pin-overlay"
|
||||
aria-hidden="true"
|
||||
style={{
|
||||
position: "fixed",
|
||||
inset: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
pointerEvents: "none",
|
||||
zIndex: 9999,
|
||||
}}
|
||||
>
|
||||
{/* Ripple rings */}
|
||||
<div className="location-pin-ripple" />
|
||||
|
||||
{/* Pin icon */}
|
||||
<div className="location-pin-icon">
|
||||
<svg width="40" height="52" viewBox="0 0 40 52" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
d="M20 0C8.954 0 0 8.954 0 20C0 34 20 52 20 52C20 52 40 34 40 20C40 8.954 31.046 0 20 0Z"
|
||||
fill="rgba(255, 220, 60, 0.95)"
|
||||
/>
|
||||
<circle cx="20" cy="20" r="8" fill="rgba(0,0,0,0.55)" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<style>{`
|
||||
@keyframes pin-drop {
|
||||
0% { transform: translateY(-60px); opacity: 0; }
|
||||
30% { transform: translateY(6px); opacity: 1; }
|
||||
45% { transform: translateY(-10px); }
|
||||
55% { transform: translateY(3px); }
|
||||
65% { transform: translateY(0); }
|
||||
80% { transform: translateY(0); opacity: 1; }
|
||||
100% { transform: translateY(0); opacity: 0; }
|
||||
}
|
||||
|
||||
@keyframes ripple-out {
|
||||
0% { transform: scale(0.2); opacity: 0.7; }
|
||||
100% { transform: scale(3.5); opacity: 0; }
|
||||
}
|
||||
|
||||
.location-pin-icon {
|
||||
position: absolute;
|
||||
/* Shift up so the pin tip lands at screen center */
|
||||
transform: translateY(-26px);
|
||||
animation: pin-drop 2.4s cubic-bezier(0.4, 0, 0.6, 1) forwards;
|
||||
filter: drop-shadow(0 6px 12px rgba(0,0,0,0.5));
|
||||
}
|
||||
|
||||
.location-pin-ripple {
|
||||
position: absolute;
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border-radius: 50%;
|
||||
border: 3px solid rgba(255, 220, 60, 0.8);
|
||||
animation: ripple-out 1.4s ease-out 1.2s forwards;
|
||||
}
|
||||
|
||||
.location-pin-ripple::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 50%;
|
||||
border: 3px solid rgba(255, 200, 30, 0.5);
|
||||
animation: ripple-out 1.4s ease-out 1.5s forwards;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -20,7 +20,6 @@ import { dataBus } from "@/core/data/DataBus";
|
||||
import { PanelToggleArrows } from "@/components/layout/PanelToggleArrows";
|
||||
import { FloatingVideoManager } from "@/components/video/FloatingVideoManager";
|
||||
import { BootOverlay } from "@/components/common/BootOverlay";
|
||||
import { LocationPinOverlay } from "@/components/common/LocationPinOverlay";
|
||||
import { useBootSequence } from "@/core/hooks/useBootSequence";
|
||||
import { useIsMobile } from "@/core/hooks/useIsMobile";
|
||||
import { DataBusSubscriber } from "./DataBusSubscriber";
|
||||
@@ -107,7 +106,6 @@ export function AppShell() {
|
||||
<EntityInfoCard />
|
||||
<Timeline />
|
||||
<FloatingVideoManager />
|
||||
<LocationPinOverlay />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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") {
|
||||
|
||||
@@ -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<SearchSection | null> {
|
||||
export function useSearch() {
|
||||
const [query, setQuery] = useState("");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [sections, setSections] = useState<SearchSection[]>([]);
|
||||
const [liveSections, setLiveSections] = useState<SearchSection[]>([]);
|
||||
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: <Clock size={16} />, 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: <Clock size={16} />, 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,
|
||||
};
|
||||
}
|
||||
@@ -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<SearchResult[]>(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 };
|
||||
}
|
||||
@@ -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 (
|
||||
<span style={{ display: "flex", alignItems: "center", color: "var(--text-muted)" }}>
|
||||
<Loader size={13} style={{ animation: "spin 1s linear infinite" }} />
|
||||
</span>
|
||||
);
|
||||
if (status === "valid")
|
||||
return <CheckCircle size={13} style={{ color: "#22c55e", flexShrink: 0 }} />;
|
||||
if (status === "invalid")
|
||||
return <XCircle size={13} style={{ color: "#ef4444", flexShrink: 0 }} />;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ApiKeysTab() {
|
||||
// Initialise state from localStorage for each service
|
||||
const [keys, setKeys] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
API_KEY_REGISTRY.forEach((e) => {
|
||||
@@ -41,27 +59,73 @@ export function ApiKeysTab() {
|
||||
});
|
||||
|
||||
const [visible, setVisible] = useState<Record<string, boolean>>({});
|
||||
const [status, setStatus] = useState<Record<string, VerifyStatus>>({});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const debounceRefs = useRef<Record<string, ReturnType<typeof setTimeout>>>({});
|
||||
|
||||
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<string, string> = {};
|
||||
API_KEY_REGISTRY.forEach((e) => (cleared[e.service] = ""));
|
||||
setKeys(cleared);
|
||||
setStatus({});
|
||||
setErrors({});
|
||||
}, []);
|
||||
|
||||
const hasAnyKey = Object.values(keys).some((v) => v.length > 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>
|
||||
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
@@ -72,36 +136,63 @@ export function ApiKeysTab() {
|
||||
Keys are stored only in your browser.
|
||||
</div>
|
||||
|
||||
{API_KEY_REGISTRY.map((entry) => (
|
||||
<div key={entry.service} style={{ marginBottom: "var(--space-md)" }}>
|
||||
<div style={{ ...inputGroupStyle, marginBottom: "var(--space-xs)" }}>
|
||||
<label style={labelStyle}>{entry.label}</label>
|
||||
{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 (
|
||||
<div key={entry.service} style={{ marginBottom: "var(--space-md)" }}>
|
||||
<div style={{ ...inputGroupStyle, marginBottom: "var(--space-xs)" }}>
|
||||
<label style={labelStyle}>{entry.label}</label>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
|
||||
<input
|
||||
type={visible[entry.service] ? "text" : "password"}
|
||||
value={keys[entry.service]}
|
||||
placeholder={entry.placeholder}
|
||||
onChange={(e) => 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}`}
|
||||
/>
|
||||
<StatusIcon status={st} />
|
||||
<button
|
||||
onClick={() => handleManualVerify(entry.service)}
|
||||
disabled={!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying"}
|
||||
title="Verify key"
|
||||
style={{
|
||||
...toggleBtnStyle,
|
||||
color: st === "valid" ? "#22c55e" : st === "invalid" ? "#ef4444" : "var(--text-muted)",
|
||||
opacity: (!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying") ? 0.4 : 1,
|
||||
cursor: (!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying") ? "not-allowed" : "pointer",
|
||||
}}
|
||||
>
|
||||
<ShieldCheck size={14} />
|
||||
</button>
|
||||
<button
|
||||
style={toggleBtnStyle}
|
||||
onClick={() => toggleVisibility(entry.service)}
|
||||
title={visible[entry.service] ? "Hide" : "Show"}
|
||||
>
|
||||
{visible[entry.service] ? <EyeOff size={14} /> : <Eye size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
{st === "invalid" && err && (
|
||||
<div style={{ fontSize: 10, color: "#ef4444", marginTop: 3 }}>{err}</div>
|
||||
)}
|
||||
{st === "valid" && (
|
||||
<div style={{ fontSize: 10, color: "#22c55e", marginTop: 3 }}>Key verified ✓</div>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: 4 }}>
|
||||
<input
|
||||
type={visible[entry.service] ? "text" : "password"}
|
||||
value={keys[entry.service]}
|
||||
placeholder={entry.placeholder}
|
||||
onChange={(e) => 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}`}
|
||||
/>
|
||||
<button
|
||||
style={toggleBtnStyle}
|
||||
onClick={() => toggleVisibility(entry.service)}
|
||||
title={visible[entry.service] ? "Hide" : "Show"}
|
||||
>
|
||||
{visible[entry.service]
|
||||
? <EyeOff size={14} />
|
||||
: <Eye size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{hasAnyKey && (
|
||||
|
||||
@@ -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<CesiumViewer["entities"]["add"]> | 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 = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="52" viewBox="0 0 40 52">
|
||||
<path d="M20 0C8.954 0 0 8.954 0 20C0 34 20 52 20 52C20 52 40 34 40 20C40 8.954 31.046 0 20 0Z"
|
||||
fill="rgba(255, 220, 60, 0.95)"/>
|
||||
<circle cx="20" cy="20" r="8" fill="rgba(0,0,0,0.55)"/>
|
||||
</svg>`;
|
||||
return `data:image/svg+xml;base64,${btoa(svg)}`;
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
|
||||
@@ -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<string, never>;
|
||||
showLocationPin: Record<string, never>;
|
||||
};
|
||||
@@ -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();
|
||||
Reference in new issue
Block a user