Compare commits

..
Author SHA1 Message Date
Antigravity AI a1f6f88ebe fix(core): resolve generic TS errors and update type definitions across plugins [Patch]
- add npx prisma generate to CI action before type checks [Patch]

- fix missing globSync import in workspace type tests [Patch]

- fix GlobeView undefined indexing for entity rendering [Patch]

- fix OSMSearchPlugin zoom property to flyToBaseDistance [Patch]

- allow getSidebarComponent to accept an optional plugin prop [Patch]

- map categories for embassies and spaceports [Patch]
2026-04-16 00:56:08 +12:00
SilvertakanaandAntigravity AI 6be56b9966 feat: Expand OSM Search Plugin with curated chips and live Taginfo autocomplete (#23)
* feat(osm-search): expand quick preset tags with OSINT categories

* feat(osm-search): add live Taginfo autocomplete for unlisted tags

* chore: bump version to 1.2.0 for osm autocomplete feature

* fix(osm-search): align tsconfig to prevent TS6059 in CI

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-16 00:23:44 +12:00
SilvertakanaandAntigravity AI 4951a2d047 feat(osm-search): implement OSM Search plugin with Bellingcat-style proximity (#21)
* feat(osm): setup plugin shell and state

* feat(osm): implement locking b-box overlay

* feat(api): overpass dumb proxy

* feat(osm): implement sidebar and search query builder

* feat(osm): register osm search plugin

* feat(osm-search): implement OSM Search plugin with Bellingcat-style proximity [Minor]

- implement @worldwideview/wwv-plugin-osm-search package [Minor]
- add Next.js proxy route for Overpass API with mirror fallback [Patch]
- implement real-time bounding box selection with dynamic updates [Patch]
- implement advanced proximity intersection mode using 'around' queries [Minor]
- fix core rendering issues (visibility, depth-test, eyeOffset) [Patch]
- refactor viewer initialization for instant plugin loading [Patch]
- align Cesium/Resium versions and fix JSDOM localStorage tests [Patch]

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-15 17:04:05 +12:00
SilvertakanaandAntigravity AI 3fa1aeb80c chore: update repo tooling (#19)
* chore(core): add ci workflow and update gitignore [Patch]

- add github actions CI pipeline [Patch]

- update gitignore for scripts and IDEs [Patch]

* chore(core): add worktree testing script [Patch]

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-15 01:06:52 +12:00
SilvertakanaandAntigravity AI c6b27a6079 feat: Conditional loading of Google 3D Tiles via custom API key (#15)
* feat(core): conditionally load Google 3D Tiles via custom API key [Minor]

- change default baseLayerId to bing-aerial [Patch]
- useViewerInit skips Google 3D layer unless key present [Minor]
- add reload prompt to ApiKeysTab on Google Maps key save [Patch]

* fix(map): implement persistent user layer intent and ui fallback highlighting

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-15 00:56:10 +12:00
SilvertakanaandAntigravity AI c8c619210f chore: update repo tooling and worktree testing (#17)
* chore(core): add ci workflow and update gitignore [Patch]

- add github actions CI pipeline [Patch]

- update gitignore for scripts and IDEs [Patch]

* chore(core): add worktree testing script [Patch]

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-15 00:13:07 +12:00
SilvertakanaandAntigravity AI 01f923b806 chore: change pull_request to pull_request_target for fork PR security scopes (#16)
Co-authored-by: Antigravity AI <[email protected]>
2026-04-14 22:25:06 +12:00
111r1ck 487cb46f03 feat: implement USGS earthquakes layer pipeline (#12) 2026-04-14 22:12:01 +12:00
d05f93e610 chore: add agentic Claude workflow comment to globals.css (#7)
* chore: add agentic Claude workflow comment

Add a marker comment at the top of src/app/globals.css documenting
the active agentic Claude workflow as of April 2026.

Co-Authored-By: Claude Haiku 4.5 <[email protected]>

* chore: duplicate agentic Claude workflow comment at top of globals.css

Co-authored-by: Silvertakana <[email protected]>

* fix(data-engine): restore Prisma schema URL and fix TypeScript strict mode error [Patch]

- Restore url = env("SUPABASE_DATABASE_URL") to prisma/schema.prisma (regressed in 76243e0)
- Delete invalid prisma.config.ts that Prisma cannot parse
- Fix TS18046 strict mode error in seeders/cyberAttacks.ts by narrowing unknown error type
- Bump version to 1.2.1

---------

Co-authored-by: Antigravity AI <[email protected]>
Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Silvertakana <[email protected]>
2026-04-14 18:13:12 +12:00
Silvertakana 701b7b3b23 Merge pull request #5 from silvertakana/add-claude-github-actions-1776077011251
Add Claude Code GitHub Workflow
2026-04-14 11:51:37 +12:00
Silvertakana 84129f1d9e "Claude Code Review workflow" 2026-04-13 22:43:36 +12:00
Silvertakana 60dbc5af66 "Claude PR Assistant workflow" 2026-04-13 22:43:34 +12:00
56 changed files with 1921 additions and 227 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
.agents
+57
View File
@@ -0,0 +1,57 @@
name: CI
on:
pull_request:
branches: [main]
jobs:
typecheck:
name: Type Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: npx prisma generate
- run: pnpm exec tsc --noEmit
test:
name: Unit Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm test
build:
name: Build
runs-on: ubuntu-latest
needs: [typecheck, test]
env:
DATABASE_URL: file:./data/wwv.db
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
NEXT_PUBLIC_WWV_EDITION: local
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm build
+44
View File
@@ -0,0 +1,44 @@
name: Claude Code Review
on:
pull_request_target:
types: [opened, synchronize, ready_for_review, reopened]
# Optional: Only run on specific file changes
# paths:
# - "src/**/*.ts"
# - "src/**/*.tsx"
# - "src/**/*.js"
# - "src/**/*.jsx"
jobs:
claude-review:
# Optional: Filter by PR author
# if: |
# github.event.pull_request.user.login == 'external-contributor' ||
# github.event.pull_request.user.login == 'new-developer' ||
# github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code Review
id: claude-review
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
plugin_marketplaces: 'https://github.com/anthropics/claude-code.git'
plugins: 'code-review@claude-code-plugins'
prompt: '/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }}'
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://code.claude.com/docs/en/cli-reference for available options
+50
View File
@@ -0,0 +1,50 @@
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
# This is an optional setting that allows Claude to read CI results on PRs
additional_permissions: |
actions: read
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
# prompt: 'Update the pull request description to include a summary of changes.'
# Optional: Add claude_args to customize behavior and configuration
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://code.claude.com/docs/en/cli-reference for available options
# claude_args: '--allowed-tools Bash(gh pr:*)'
+6 -3
View File
@@ -22,6 +22,7 @@ node_modules/
# claude code IDE config
/.claude/
/.cline/
# performance
/performance/
@@ -29,9 +30,8 @@ node_modules/
# artifacts
/artifacts/
# scripts
/scripts/
!/scripts/setup.mjs
# scripts (tracked, but temporary scratchpads should go in /local-scripts/)
# local database
/data/
@@ -80,3 +80,6 @@ packages/*/dist/
# Developmental scripts & temporary sandbox
/local-scripts/
# git worktrees
/.worktrees/
-2
View File
@@ -89,5 +89,3 @@ We are actively looking for contributors to help build new data plugins and opti
- Want to build something? Check out our **[Pinned Plugin Wishlist](https://github.com/silvertakana/worldwideview/issues)** for great first issues!
> **Fair-Use Notice:** This application may contain copyrighted material the use of which has not always been specifically authorized by the copyright owner. Such material is made available for educational purposes, situational awareness, and to advance understanding of global events under "fair use" (Section 107 of the US Copyright Law).
✅ **vibe-kanban is working**
+1
View File
@@ -22,6 +22,7 @@ const nextConfig: NextConfig = {
"@worldwideview/wwv-plugin-international-sanctions",
"@worldwideview/wwv-plugin-sdk",
"@worldwideview/wwv-plugin-wildfire",
"@worldwideview/wwv-plugin-osm-search",
"resium",
"react-player",
"satellite.js"
+2 -1
View File
@@ -1,9 +1,10 @@
{
"name": "worldwideview",
"version": "1.7.1",
"version": "1.8.3",
"private": true,
"scripts": {
"setup": "node scripts/setup.mjs",
"test-worktree": "node scripts/test-worktree.mjs",
"clean": "node -e \"const fs=require('fs');fs.rmSync('.next',{recursive:true,force:true})\"",
"dev": "next dev --webpack",
"dev:all": "npx concurrently \"pnpm dev\" \"pnpm --filter wwv-data-engine dev\"",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-data-engine",
"version": "1.2.0",
"version": "1.2.1",
"description": "WWV Data Engine - Dual-tier Shared Backend",
"main": "dist/server.js",
"scripts": {
-25
View File
@@ -1,25 +0,0 @@
import fs from "fs";
import path from "path";
let dbUrl = process.env.SUPABASE_DATABASE_URL;
if (!dbUrl) {
try {
const envPath = path.resolve(process.cwd(), "../../.env.local");
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, "utf8");
const match = envContent.match(/^SUPABASE_DATABASE_URL=(.*)$/m);
if (match) {
dbUrl = match[1].trim();
}
}
} catch (e) {
// Ignore
}
}
export default {
datasource: {
url: dbUrl,
},
};
@@ -7,6 +7,7 @@ generator client {
datasource db {
provider = "postgresql"
url = env("SUPABASE_DATABASE_URL")
}
model IranwarEvent {
@@ -51,7 +51,8 @@ export async function seedCyberAttacks() {
headers: { 'X-OTX-API-KEY': apiKey, 'User-Agent': 'WWV-Data-Engine' },
});
} catch(err) {
console.error('[CyberAttacks] Fetch error details:', err.message);
const msg = err instanceof Error ? err.message : String(err);
console.error('[CyberAttacks] Fetch error details:', msg);
throw err;
}
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-plugin-earthquakes",
"version": "1.0.2",
"version": "1.1.0",
"main": "src/index.ts",
"dependencies": {
"@worldwideview/wwv-plugin-sdk": "workspace:*",
+77 -33
View File
@@ -10,15 +10,14 @@ import { BaseIncidentPlugin } from "@worldwideview/wwv-lib-incidents";
export class EarthquakesPlugin extends BaseIncidentPlugin {
id = "earthquakes";
name = "Earthquakes";
description = "USGS Real-Time Earthquakes (4.5+)";
description = "Recent seismic activity from USGS";
icon = Activity;
category = "natural-disaster" as const;
version = "1.0.2";
version = "1.1.0";
protected defaultLayerColor = "#f97316";
protected getSeverityValue(entity: GeoEntity): number {
return (entity.properties.magnitude as number) || 4.5;
return Number(entity.properties.magnitude ?? 0) || 0;
}
protected getSeverityColor(mag: number): string {
@@ -37,40 +36,89 @@ export class EarthquakesPlugin extends BaseIncidentPlugin {
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
try {
const res = await globalThis.fetch("/api/external/earthquakes");
if (!res.ok) throw new Error(`Earthquakes API returned ${res.status}`);
const data = await res.json();
if (!data.items || !Array.isArray(data.items)) return [];
const res = await globalThis.fetch("/api/earthquake");
if (!res.ok) {
this.context?.onError(new Error(`Earthquakes API returned ${res.status}`));
return [];
}
return data.items.map((eq: any): GeoEntity => ({
id: eq.id,
pluginId: this.id,
latitude: eq.lat,
longitude: eq.lon,
timestamp: new Date(eq.occurredAt),
label: `M${eq.magnitude} - ${eq.place}`,
properties: {
magnitude: eq.magnitude,
depth_km: eq.depth_km,
place: eq.place,
url: eq.url,
nearTestSite: eq.nearTestSite,
nearestSiteName: eq.nearestSiteName,
},
}));
const data = await res.json();
const features = Array.isArray(data?.features) ? data.features : [];
return features.flatMap((feature: any): GeoEntity[] => {
const coordinates = feature?.geometry?.coordinates;
const time = feature?.properties?.time;
if (
!Array.isArray(coordinates)
|| coordinates.length < 2
|| !Number.isFinite(coordinates[0])
|| !Number.isFinite(coordinates[1])
|| !Number.isFinite(time)
) {
return [];
}
const magnitude = Number(feature?.properties?.mag ?? 0) || 0;
return [{
id: `${this.id}-${feature.id}`,
pluginId: this.id,
latitude: coordinates[1],
longitude: coordinates[0],
altitude: 0,
timestamp: new Date(time),
label: `M${feature?.properties?.mag ?? "?"}`,
properties: {
magnitude,
depth: Number(feature?.geometry?.coordinates?.[2] ?? 0) || 0,
place: feature?.properties?.place ?? null,
url: feature?.properties?.url ?? null,
updated: feature?.properties?.updated ?? null,
status: feature?.properties?.status ?? null,
tsunami: feature?.properties?.tsunami ?? null,
sig: feature?.properties?.sig ?? null,
magType: feature?.properties?.magType ?? null,
},
}];
});
} catch (err) {
console.error("[EarthquakesPlugin] Fetch error:", err);
const error = err instanceof Error ? err : new Error("Failed to fetch earthquakes");
this.context?.onError(error);
return [];
}
}
getPollingInterval(): number {
return 120000;
}
getServerConfig(): ServerPluginConfig {
return { apiBasePath: "/api/external/earthquakes", pollingIntervalMs: 0, historyEnabled: true };
return { apiBasePath: "/api/earthquake", pollingIntervalMs: 120000, historyEnabled: false };
}
getLayerConfig() {
return {
color: "#ef4444",
clusterEnabled: true,
clusterDistance: 40,
maxEntities: 2000,
};
}
renderEntity(entity: GeoEntity) {
const magnitude = this.getSeverityValue(entity);
return {
type: "point" as const,
color: this.getSeverityColor(magnitude),
size: this.getSeveritySize(magnitude),
outlineColor: "#000000",
outlineWidth: 1,
labelText: entity.label,
};
}
getLegend(): { label: string; color: string; filterId?: string; filterValue?: string }[] {
return [
{ label: "M < 5.0", color: "#fcd34d", filterId: "magnitude", filterValue: "4.5" },
{ label: "M < 5.0", color: "#fcd34d", filterId: "magnitude", filterValue: "0" },
{ label: "M 5.0 - 5.9", color: "#f97316", filterId: "magnitude", filterValue: "5.0" },
{ label: "M 6.0 - 6.9", color: "#ef4444", filterId: "magnitude", filterValue: "6.0" },
{ label: "M ≥ 7.0", color: "#7f1d1d", filterId: "magnitude", filterValue: "7.0" },
@@ -79,12 +127,8 @@ export class EarthquakesPlugin extends BaseIncidentPlugin {
getFilterDefinitions(): FilterDefinition[] {
return [
{ id: "magnitude", label: "Magnitude", type: "range", propertyKey: "magnitude", range: { min: 4.5, max: 10.0, step: 0.1 } },
{ id: "depth", label: "Depth (km)", type: "range", propertyKey: "depth_km", range: { min: 0, max: 800, step: 10 } },
{
id: "nuclear", label: "Nuclear Site Proximity", type: "select", propertyKey: "nearTestSite",
options: [{ value: "true", label: "Suspicious (<10km from test site)" }],
}
{ id: "magnitude", label: "Magnitude", type: "range", propertyKey: "magnitude", range: { min: 0, max: 10, step: 0.1 } },
{ id: "depth", label: "Depth (km)", type: "range", propertyKey: "depth", range: { min: 0, max: 800, step: 10 } },
];
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-plugin-embassies",
"version": "1.0.2",
"version": "1.0.3",
"description": "WorldWideView plugin — Global embassies, consulates, and diplomatic missions from OpenStreetMap",
"main": "src/index.ts",
"types": "src/index.ts",
+2 -2
View File
@@ -6,8 +6,8 @@ export class EmbassiesConsulatesPlugin extends BaseFacilityPlugin {
name = "Embassies & Consulates";
description = "Global embassies, consulates, and diplomatic missions from OpenStreetMap";
icon = Landmark;
category = "government" as const;
version = "1.0.2";
category = "infrastructure" as const;
version = "1.0.3";
protected defaultLayerColor = "#a855f7";
protected maxEntities = 1000;
@@ -0,0 +1,19 @@
{
"name": "@worldwideview/wwv-plugin-osm-search",
"version": "1.2.1",
"description": "OSM Search Plugin for WorldWideView",
"main": "src/index.ts",
"type": "module",
"dependencies": {
"@worldwideview/wwv-plugin-sdk": "workspace:*",
"cesium": "^1.139.0",
"lucide-react": "^0.576.0",
"react": "19.2.3",
"resium": "1.19.4",
"zustand": "^5.0.11"
},
"devDependencies": {
"@types/react": "^19.0.2",
"typescript": "^5.4.5"
}
}
@@ -0,0 +1,83 @@
import React, { useEffect, useMemo } from "react";
import { Color, Cartesian3, Rectangle, PolygonHierarchy, ClassificationType, ArcType } from "cesium";
import { Entity, PolygonGraphics, PolylineGraphics, CustomDataSource } from "resium";
import { useOsmStore } from "../store";
export function OSMBboxOverlay({ viewer, enabled }: { viewer: any; enabled: boolean }) {
const { bboxLocked, showBbox, lockedBbox, currentBbox, setCurrentBbox } = useOsmStore();
useEffect(() => {
if (!viewer || !enabled) return;
const updateBbox = () => {
if (bboxLocked) return;
const rect = viewer.camera.computeViewRectangle(viewer.scene.globe.ellipsoid);
if (rect) {
const marginLat = (rect.north - rect.south) * 0.15;
const marginLon = (rect.east - rect.west) * 0.15;
setCurrentBbox(new Rectangle(
rect.west + marginLon, rect.south + marginLat,
rect.east - marginLon, rect.north - marginLat
));
}
};
// Use 'changed' for continuous updates during movement
viewer.camera.changed.addEventListener(updateBbox);
viewer.camera.moveEnd.addEventListener(updateBbox);
// Initial attempt
updateBbox();
// Temporary interval for 2 seconds to force updates while the globe/camera settles
const initInterval = setInterval(updateBbox, 100);
const timeout = setTimeout(() => clearInterval(initInterval), 2000);
return () => {
clearInterval(initInterval);
clearTimeout(timeout);
if (viewer && !viewer.isDestroyed()) {
viewer.camera.changed.removeEventListener(updateBbox);
viewer.camera.moveEnd.removeEventListener(updateBbox);
}
};
}, [viewer, enabled, bboxLocked, setCurrentBbox]);
const activeBbox = bboxLocked ? lockedBbox : currentBbox;
const positions = useMemo(() => {
if (!activeBbox) return [];
return Cartesian3.fromRadiansArray([
activeBbox.west, activeBbox.south,
activeBbox.east, activeBbox.south,
activeBbox.east, activeBbox.north,
activeBbox.west, activeBbox.north,
activeBbox.west, activeBbox.south,
]);
}, [activeBbox]);
// Don't render if layer is disabled OR if user has hidden the box
if (!enabled || !activeBbox || !showBbox) return null;
return (
<CustomDataSource name="OSMSearchBBox">
<Entity>
<PolygonGraphics
hierarchy={new PolygonHierarchy(positions)}
fill={true}
material={Color.RED.withAlpha(0.25)}
classificationType={ClassificationType.BOTH}
arcType={ArcType.GEODESIC}
height={0}
/>
<PolylineGraphics
positions={positions}
width={3}
material={Color.RED}
clampToGround={true}
arcType={ArcType.GEODESIC}
/>
</Entity>
</CustomDataSource>
);
}
@@ -0,0 +1,347 @@
import React, { useState } from "react";
import { Math as CesiumMath } from "cesium";
import { Eye, EyeOff } from "lucide-react";
import { useOsmStore } from "../store";
const COMMON_TAGS = [
// Military & Security
"military=base", "military=bunker", "amenity=police", "amenity=prison",
// Aviation & Maritime
"aeroway=aerodrome", "aeroway=helipad", "aeroway=hangar", "man_made=pier", "harbour=yes",
// Infrastructure & Utilities
"power=plant", "power=substation", "telecom=antenna", "man_made=communications_tower", "man_made=water_tower",
// Transport
"highway=bus_stop", "railway=station", "amenity=fuel", "amenity=parking",
// Medical & Emergency
"amenity=hospital", "amenity=fire_station", "amenity=clinic",
// General Commercial & Industrial
"shop=supermarket", "tourism=hotel", "industrial=factory", "landuse=industrial",
// Education & Amenities
"amenity=school", "amenity=university", "amenity=cafe", "building=house"
];
interface OSMSidebarProps {
plugin?: any; // OSMSearchPlugin
}
export function OSMSidebar({ plugin }: OSMSidebarProps) {
const { bboxLocked, showBbox, setShowBbox, setBboxLocked, currentBbox, setLockedBbox, lockedBbox } = useOsmStore();
const [mode, setMode] = useState<"bellingcat" | "turbo">("bellingcat");
const [rawQuery, setRawQuery] = useState("[out:json];\nnode[amenity=cafe]({{bbox}});\nout center;");
const [searchText, setSearchText] = useState("");
const [activeTags, setActiveTags] = useState<string[]>([]);
const [distance, setDistance] = useState(500);
const [isScanning, setIsScanning] = useState(false);
// Taginfo dynamic search states
const [dynamicTags, setDynamicTags] = useState<string[]>([]);
const [isSearchingApi, setIsSearchingApi] = useState(false);
// Fetch dynamic tags when search text changes
React.useEffect(() => {
if (searchText.length < 3) {
setDynamicTags([]);
return;
}
const timer = setTimeout(async () => {
setIsSearchingApi(true);
try {
const res = await fetch(`https://taginfo.openstreetmap.org/api/4/search/by_keyword?query=${encodeURIComponent(searchText)}`);
const data = await res.json();
if (data && data.data) {
const tags = data.data
.filter((item: any) => item.key && item.value)
.map((item: any) => `${item.key}=${item.value}`)
.slice(0, 15);
setDynamicTags(tags);
}
} catch (err) {
console.error("Taginfo fetch failed", err);
} finally {
setIsSearchingApi(false);
}
}, 500);
return () => clearTimeout(timer);
}, [searchText]);
const toggleLock = () => {
if (!bboxLocked) {
setLockedBbox(currentBbox);
setBboxLocked(true);
} else {
setBboxLocked(false);
setLockedBbox(null);
}
};
const handleScan = async () => {
if (!bboxLocked) {
setLockedBbox(currentBbox);
setBboxLocked(true);
}
const bboxParams = lockedBbox || currentBbox;
if (!bboxParams) {
alert("Please wait for map viewport to initialize");
return;
}
// Overpass bbox order: south, west, north, east (in degrees)
const s = CesiumMath.toDegrees(bboxParams.south).toFixed(6);
const w = CesiumMath.toDegrees(bboxParams.west).toFixed(6);
const n = CesiumMath.toDegrees(bboxParams.north).toFixed(6);
const e = CesiumMath.toDegrees(bboxParams.east).toFixed(6);
const bboxString = `${s},${w},${n},${e}`;
let ql = "";
if (mode === "turbo") {
ql = rawQuery.replace(/{{bbox}}/g, bboxString);
} else {
// Bellingcat-style proximity search
if (activeTags.length === 1) {
const [key, val] = activeTags[0].split("=");
ql = `[out:json][timeout:25];
nwr["${key}"="${val}"](${bboxString});
out center;`;
} else if (activeTags.length > 1) {
// Chain search: Find A, then find B near A, then find C near B...
// Using .t0, .t1, .t2 as set names
ql = `[out:json][timeout:25];\n`;
activeTags.forEach((tag, idx) => {
const [key, val] = tag.split("=");
if (idx === 0) {
ql += `nwr["${key}"="${val}"](${bboxString})->.t0;\n`;
} else {
ql += `nwr["${key}"="${val}"](around.t${idx - 1}:${distance})->.t${idx};\n`;
}
});
// Final output: the last set in the chain
ql += `.t${activeTags.length - 1} out center;`;
}
}
setIsScanning(true);
try {
const res = await fetch("/api/plugins/osm-search", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: ql })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || "Search failed");
if (plugin?.pushResults && plugin?.mapOverpassToEntities) {
const entities = plugin.mapOverpassToEntities(data.data || []);
plugin.pushResults(entities);
} else {
console.warn("Plugin bridge not available in OSMSidebar", data.data);
}
} catch (err) {
console.error(err);
alert("Search failed: " + (err as Error).message);
} finally {
setIsScanning(false);
}
};
// Combine filtered common tags with newly fetched dynamic tags, removing duplicates
const filteredCommon = searchText
? COMMON_TAGS.filter(t => t.toLowerCase().includes(searchText.toLowerCase()))
: COMMON_TAGS;
const renderedTags = Array.from(new Set([...filteredCommon, ...dynamicTags]));
return (
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<div style={{ background: "rgba(255,255,255,0.05)", padding: "10px", borderRadius: "6px", border: "1px solid rgba(255,255,255,0.1)" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "8px" }}>
<span style={{ fontSize: "12px", color: "var(--text-secondary)" }}>Viewport Bounding Box</span>
<div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<button
onClick={() => setShowBbox(!showBbox)}
title={showBbox ? "Hide Box" : "Show Box"}
style={{
background: "none", border: "none", color: "var(--text-muted)", cursor: "pointer",
display: "flex", alignItems: "center", padding: "2px"
}}
>
{showBbox ? <Eye size={14} /> : <EyeOff size={14} />}
</button>
<span style={{
fontSize: "10px",
padding: "2px 6px",
borderRadius: "10px",
background: bboxLocked ? "#ef444422" : "#22c55e22",
color: bboxLocked ? "#ef4444" : "#22c55e",
border: `1px solid ${bboxLocked ? "#ef444444" : "#22c55e44"}`
}}>
{bboxLocked ? "LOCKED" : "FOLLOWING"}
</span>
</div>
</div>
<button
onClick={toggleLock}
style={{
width: "100%",
padding: "6px",
background: "var(--bg-secondary)",
border: "1px solid var(--border-subtle)",
borderRadius: "4px",
color: "var(--text-primary)",
fontSize: "12px",
cursor: "pointer"
}}
>
{bboxLocked ? "Unlock Viewport" : "Lock Selection Box"}
</button>
</div>
<div style={{ display: "flex", gap: "4px", background: "rgba(0,0,0,0.2)", padding: "2px", borderRadius: "6px" }}>
<button
style={{
flex: 1,
padding: "6px",
border: "none",
borderRadius: "4px",
fontSize: "12px",
backgroundColor: mode === "bellingcat" ? "var(--bg-tertiary)" : "transparent",
color: mode === "bellingcat" ? "var(--text-primary)" : "var(--text-muted)",
cursor: "pointer"
}}
onClick={() => setMode("bellingcat")}
>
Quick Presets
</button>
<button
style={{
flex: 1,
padding: "6px",
border: "none",
borderRadius: "4px",
fontSize: "12px",
backgroundColor: mode === "turbo" ? "var(--bg-tertiary)" : "transparent",
color: mode === "turbo" ? "var(--text-primary)" : "var(--text-muted)",
cursor: "pointer"
}}
onClick={() => setMode("turbo")}
>
Overpass QL
</button>
</div>
{mode === "bellingcat" && (
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
{activeTags.length > 1 && (
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", background: "rgba(0,0,0,0.2)", padding: "8px", borderRadius: "4px" }}>
<label style={{ fontSize: "11px", color: "var(--text-muted)" }}>Intersection Radius: <strong>{distance}m</strong></label>
<input
type="range" min="50" max="2000" step="50"
value={distance} onChange={e => setDistance(Number(e.target.value))}
style={{ width: "100px", accentColor: "var(--accent-blue)" }}
/>
</div>
)}
<div style={{ position: "relative" }}>
<input
style={{
width: "100%",
padding: "8px",
paddingRight: "24px",
backgroundColor: "rgba(0,0,0,0.3)",
color: "#fff",
border: "1px solid var(--border-subtle)",
borderRadius: "4px",
fontSize: "13px"
}}
placeholder="Filter or search OSM for tags..."
value={searchText}
onChange={e => setSearchText(e.target.value)}
/>
{isSearchingApi && (
<span style={{
position: "absolute",
right: "8px",
top: "50%",
transform: "translateY(-50%)",
fontSize: "10px",
color: "var(--text-muted)"
}}>
⏳
</span>
)}
</div>
<div style={{ display: "flex", flexWrap: "wrap", gap: "6px", maxHeight: "150px", overflowY: "auto", padding: "4px" }}>
{renderedTags.map(tag => {
const isActive = activeTags.includes(tag);
return (
<button
key={tag}
style={{
background: isActive ? "var(--accent-blue)" : "rgba(255,255,255,0.05)",
color: isActive ? "#fff" : "var(--text-secondary)",
padding: "4px 10px",
borderRadius: "14px",
border: `1px solid ${isActive ? "transparent" : "rgba(255,255,255,0.1)"}`,
fontSize: "11px",
cursor: "pointer",
transition: "all 0.2s"
}}
onClick={() => setActiveTags(prev => prev.includes(tag) ? prev.filter(t=>t!==tag) : [...prev, tag])}
>
{tag.replace("=", ": ")}
</button>
);
})}
</div>
</div>
)}
{mode === "turbo" && (
<div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
<label style={{ fontSize: "11px", color: "var(--text-muted)" }}>Raw Overpass Query</label>
<textarea
style={{
backgroundColor: "rgba(0,0,0,0.3)",
color: "#fff",
border: "1px solid var(--border-subtle)",
padding: "8px",
width: "100%",
borderRadius: "4px",
fontSize: "12px",
fontFamily: "monospace",
resize: "vertical"
}}
value={rawQuery}
onChange={e => setRawQuery(e.target.value)}
rows={6}
/>
<span style={{ fontSize: "10px", color: "var(--text-muted)" }}>Use {'{{bbox}}'} as placeholder</span>
</div>
)}
<button
onClick={handleScan}
disabled={isScanning || (mode === "bellingcat" && activeTags.length === 0)}
style={{
padding: "10px",
background: isScanning ? "var(--bg-tertiary)" : "var(--accent-blue)",
color: "white",
marginTop: "4px",
border: "none",
borderRadius: "4px",
fontWeight: 600,
cursor: isScanning ? "not-allowed" : "pointer",
opacity: (mode === "bellingcat" && activeTags.length === 0) ? 0.5 : 1
}}
>
{isScanning ? "SCANNING OVERPASS..." : `SCAN AREA (${mode === "turbo" ? "TURBO" : activeTags.length + " TAGS"})`}
</button>
</div>
);
}
@@ -0,0 +1,87 @@
import { Search } from "lucide-react";
import type { PluginManifest, WorldPlugin, PluginContext, TimeRange, GeoEntity, LayerConfig, CesiumEntityOptions } from "@worldwideview/wwv-plugin-sdk";
import { OSMBboxOverlay } from "./components/OSMBboxOverlay";
import { OSMSidebar } from "./components/OSMSidebar";
import { manifest } from "./manifest";
export class OSMSearchPlugin implements WorldPlugin {
id = manifest.id;
name = manifest.name;
description = manifest.description!;
icon = Search;
category = manifest.category as any;
version = manifest.version;
private ctx!: PluginContext;
async initialize(ctx: PluginContext) {
this.ctx = ctx;
}
destroy() {}
async fetch(timeRange: TimeRange): Promise<GeoEntity[]> { return []; }
getPollingInterval() { return 999999999; }
getLayerConfig(): LayerConfig {
return { color: "#ff0000", clusterEnabled: true, clusterDistance: 50 };
}
renderEntity(entity: GeoEntity): CesiumEntityOptions {
return {
type: "point",
color: "#ff0000",
size: 8,
// Ensure points are always visible and don't sink into terrain
disableDepthTestDistance: Number.POSITIVE_INFINITY
};
}
/** Configures how the camera and UI behaves when an OSM entity is selected */
getSelectionBehavior(entity: GeoEntity) {
return {
// Default "go-to" distance in meters.
// 500m provides a good "street-level" view for OSM features.
flyToBaseDistance: 500,
showTrail: false
};
}
getSidebarComponent() { return OSMSidebar; }
getGlobeComponent() { return OSMBboxOverlay; }
/** Public bridge for the sidebar component to push search results into the main map state */
pushResults(entities: GeoEntity[]) {
if (this.ctx) {
this.ctx.onDataUpdate(entities);
}
}
/** Maps Overpass API elements to WorldWideView GeoEntities */
mapOverpassToEntities(elements: any[]): GeoEntity[] {
return elements
.filter(el => (el.lat && el.lon) || el.center)
.map(el => {
const lat = el.lat || el.center?.lat;
const lon = el.lon || el.center?.lon;
const name = el.tags?.name || el.tags?.amenity || el.tags?.shop || el.tags?.highway || `OSM ${el.type} ${el.id}`;
return {
id: `osm-${el.type}-${el.id}`,
pluginId: this.id,
latitude: lat,
longitude: lon,
timestamp: new Date(),
label: name,
properties: {
osm_id: el.id,
osm_type: el.type,
...el.tags
}
};
});
}
}
export { manifest };
@@ -0,0 +1,13 @@
import type { PluginManifest } from "@worldwideview/wwv-plugin-sdk";
export const manifest: PluginManifest = {
id: "osm-search",
name: "OSM Search",
version: "1.0.0",
description: "Configurable Overpass API search. Includes Bellingcat-style proximity search and Overpass Turbo raw QL.",
type: "data-layer",
format: "bundle",
trust: "built-in",
capabilities: ["data:own", "ui:sidebar", "globe:overlay"],
category: "custom"
};
@@ -0,0 +1,24 @@
import { create } from "zustand";
import { Rectangle } from "cesium";
interface OsmPluginState {
bboxLocked: boolean;
showBbox: boolean;
currentBbox: Rectangle | null;
lockedBbox: Rectangle | null;
setBboxLocked: (locked: boolean) => void;
setShowBbox: (show: boolean) => void;
setCurrentBbox: (rect: Rectangle | null) => void;
setLockedBbox: (rect: Rectangle | null) => void;
}
export const useOsmStore = create<OsmPluginState>((set) => ({
bboxLocked: false,
showBbox: true,
currentBbox: null,
lockedBbox: null,
setBboxLocked: (locked) => set({ bboxLocked: locked }),
setShowBbox: (show) => set({ showBbox: show }),
setCurrentBbox: (rect) => set({ currentBbox: rect }),
setLockedBbox: (rect) => set({ lockedBbox: rect }),
}));
@@ -0,0 +1,29 @@
import { describe, it, expect } from "vitest";
import { OSMSearchPlugin } from "../src/index";
describe("OSMSearchPlugin", () => {
it("should instantiate with correct id", () => {
const plugin = new OSMSearchPlugin();
expect(plugin.id).toBe("osm-search");
expect(plugin.category).toBe("custom");
});
it("should map overpass elements to geo entities", () => {
const plugin = new OSMSearchPlugin();
const elements = [
{
type: "node",
id: 123,
lat: 45.0,
lon: 90.0,
tags: { name: "Test Node", amenity: "cafe" }
}
];
const entities = plugin.mapOverpassToEntities(elements);
expect(entities.length).toBe(1);
expect(entities[0].id).toBe("osm-node-123");
expect(entities[0].latitude).toBe(45.0);
expect(entities[0].label).toBe("Test Node");
expect(entities[0].properties.amenity).toBe("cafe");
});
});
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"noEmit": true
},
"include": [
"src"
]
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-plugin-sdk",
"version": "1.2.0",
"version": "1.2.1",
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
"main": "dist/index.js",
"types": "dist/index.d.ts",
+1 -1
View File
@@ -231,7 +231,7 @@ export interface WorldPlugin {
getServerConfig?(): ServerPluginConfig;
getFilterDefinitions?(): FilterDefinition[];
getLegend?(): { label: string; color: string; filterId?: string; filterValue?: string }[];
getSidebarComponent?(): ComponentType;
getSidebarComponent?(): ComponentType<{ plugin?: any } | any>;
getDetailComponent?(): ComponentType<{ entity: GeoEntity }>;
getSettingsComponent?(): ComponentType<{ pluginId: string }>;
/** Custom React component injected into the Globe view for rendering primitives/data sources (e.g. GeoJSON). */
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-plugin-spaceports",
"version": "1.0.1",
"version": "1.0.2",
"description": "WorldWideView plugin — Space launch sites worldwide from OSM",
"main": "src/index.ts",
"types": "src/index.ts",
+2 -2
View File
@@ -6,8 +6,8 @@ export class SpaceportsPlugin extends BaseFacilityPlugin {
name = "Spaceports";
description = "Space launch sites worldwide from OSM";
icon = Rocket;
category = "science" as const;
version = "1.0.1";
category = "space" as const;
version = "1.0.2";
protected defaultLayerColor = "#7c3aed";
protected maxEntities = 1000;
+41 -2
View File
@@ -130,7 +130,7 @@ importers:
version: 8.20.0
zustand:
specifier: ^5.0.11
version: 5.0.12(@types/[email protected])([email protected])
version: 5.0.12(@types/[email protected])([email protected])([email protected]([email protected]))
devDependencies:
'@testing-library/dom':
specifier: ^10.4.1
@@ -515,6 +515,34 @@ importers:
specifier: workspace:*
version: link:../wwv-plugin-sdk
packages/wwv-plugin-osm-search:
dependencies:
'@worldwideview/wwv-plugin-sdk':
specifier: workspace:*
version: link:../wwv-plugin-sdk
cesium:
specifier: ^1.139.0
version: 1.139.1
lucide-react:
specifier: ^0.576.0
version: 0.576.0([email protected])
react:
specifier: 19.2.3
version: 19.2.3
resium:
specifier: 1.19.4
version: 1.19.4([email protected])([email protected]([email protected]))([email protected])
zustand:
specifier: ^5.0.11
version: 5.0.12(@types/[email protected])([email protected])([email protected]([email protected]))
devDependencies:
'@types/react':
specifier: ^19.0.2
version: 19.2.14
typescript:
specifier: ^5.4.5
version: 5.9.3
packages/wwv-plugin-satellite:
dependencies:
'@worldwideview/wwv-plugin-sdk':
@@ -3747,6 +3775,11 @@ packages:
[email protected]:
resolution: {integrity: sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ==}
[email protected]:
resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
[email protected]:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
@@ -6998,6 +7031,11 @@ snapshots:
[email protected]: {}
[email protected]([email protected]):
dependencies:
react: 19.2.3
optional: true
[email protected]: {}
[email protected]: {}
@@ -7168,7 +7206,8 @@ snapshots:
[email protected]: {}
[email protected](@types/[email protected])([email protected]):
[email protected](@types/[email protected])([email protected])([email protected]([email protected])):
optionalDependencies:
'@types/react': 19.2.14
react: 19.2.3
use-sync-external-store: 1.6.0([email protected])
+139
View File
@@ -0,0 +1,139 @@
import fs from 'node:fs';
import path from 'node:path';
import { spawn, execSync } from 'node:child_process';
import net from 'node:net';
// 1. Get branch argument
const branchName = process.argv[2];
if (!branchName) {
console.error('\x1b[31mError: Please provide a worktree branch name.\x1b[0m');
console.error('Usage: pnpm run test-worktree <branch-name>');
process.exit(1);
}
const rootDir = process.cwd();
const worktreeDirName = branchName.replace(/\//g, '-');
const worktreePath = path.join(rootDir, '.worktrees', worktreeDirName);
// 2. Validate worktree exists
if (!fs.existsSync(worktreePath)) {
console.error(`\x1b[31mError: Worktree directory not found at ${worktreePath}\x1b[0m`);
console.error(`Ensure you have created it using 'git worktree add .worktrees/${worktreeDirName} -b ${branchName}'`);
process.exit(1);
}
// 3. Setup Environment
console.log(`\x1b[34m[1/5] Checking environment in ${worktreePath}...\x1b[0m`);
const rootEnvPath = path.join(rootDir, '.env.local');
const worktreeEnvPath = path.join(worktreePath, '.env.local');
if (!fs.existsSync(worktreeEnvPath) && fs.existsSync(rootEnvPath)) {
fs.copyFileSync(rootEnvPath, worktreeEnvPath);
console.log('Copied .env.local from root.');
}
// 4. Install Dependencies
console.log(`\x1b[34m[2/5] Symlinking modules and generating local clients...\x1b[0m`);
console.log('Running pnpm install in worktree...');
execSync('pnpm install', { cwd: worktreePath, stdio: 'inherit' });
console.log('Generating Prisma Clients (Root)...');
execSync('npx prisma generate', { cwd: worktreePath, stdio: 'inherit' });
console.log('Generating Prisma Clients (Data Engine)...');
const enginePath = path.join(worktreePath, 'packages', 'wwv-data-engine');
if (fs.existsSync(enginePath)) {
try {
execSync('npx prisma generate', { cwd: enginePath, stdio: 'inherit' });
} catch (err) {
console.warn('\x1b[33m[Warning] Could not generate Data Engine Prisma client. This happens on Windows when another workspace is running and locking the shared pnpm DLL. It is safe to ignore as the client already exists in the cache.\x1b[0m');
}
}
// 5. Setup databases
console.log(`\x1b[34m[3/5] Setting up local databases...\x1b[0m`);
const rootDataDir = path.join(worktreePath, 'data');
const engineDataDir = path.join(enginePath, 'data');
if (!fs.existsSync(rootDataDir)) fs.mkdirSync(rootDataDir, { recursive: true });
if (fs.existsSync(enginePath) && !fs.existsSync(engineDataDir)) fs.mkdirSync(engineDataDir, { recursive: true });
// 6. Port utility
function findFreePort(startPort) {
return new Promise((resolve, reject) => {
const server = net.createServer();
// Fastify binds to 0.0.0.0, so we must probe 0.0.0.0 instead of localhost
// otherwise Node might successfully check IPv6 while IPv4 is taken
server.listen(startPort, '0.0.0.0', () => {
const port = server.address().port;
server.close(() => resolve(port));
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
resolve(findFreePort(startPort + 1));
} else {
reject(err);
}
});
});
}
// 7. Start the Servers
async function start() {
console.log(`\x1b[34m[4/5] Assigning isolated ports...\x1b[0m`);
// Start scanning *after* the default main dev ports to absolutely ensure we don't accidentally grab them
const frontendPort = await findFreePort(3002);
const backendPort = await findFreePort(5002);
console.log(`Next.js Frontend Port: \x1b[32m${frontendPort}\x1b[0m`);
console.log(`Data Engine Backend Port: \x1b[32m${backendPort}\x1b[0m`);
console.log(`\x1b[34m[4/5] Booting isolated servers...\x1b[0m`);
// Start Backend First
const backendEnv = { ...process.env, PORT: backendPort.toString() };
const backendProcess = spawn('pnpm', ['--filter', 'wwv-data-engine', 'dev'], {
cwd: worktreePath,
env: backendEnv,
stdio: 'pipe',
shell: true
});
backendProcess.stdout.on('data', (data) => process.stdout.write(`[\x1b[36mEngine\x1b[0m] ${data}`));
backendProcess.stderr.on('data', (data) => process.stderr.write(`[\x1b[31mEngine Error\x1b[0m] ${data}`));
// Start Frontend
const frontendEnv = {
...process.env,
PORT: frontendPort.toString(),
WWV_DATA_ENGINE_URL: `http://127.0.0.1:${backendPort}`,
NEXT_PUBLIC_WS_ENGINE_URL: `ws://127.0.0.1:${backendPort}/stream`
};
const frontendProcess = spawn('pnpm', ['dev'], {
cwd: worktreePath,
env: frontendEnv,
stdio: 'pipe',
shell: true
});
frontendProcess.stdout.on('data', (data) => process.stdout.write(`[\x1b[35mNext.js\x1b[0m] ${data}`));
frontendProcess.stderr.on('data', (data) => process.stderr.write(`[\x1b[31mNext.js Error\x1b[0m] ${data}`));
// 7. Open Browser
console.log(`\x1b[34m[5/5] Launching browser...\x1b[0m`);
setTimeout(() => {
const url = `http://localhost:${frontendPort}`;
console.log(`Opening \x1b[32m${url}\x1b[0m...`);
const startCmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
execSync(`${startCmd} ${url}`);
}, 4000); // Wait 4 seconds for Next to hook up
process.on('SIGINT', () => {
backendProcess.kill('SIGINT');
frontendProcess.kill('SIGINT');
process.exit();
});
}
start().catch(console.error);
+53
View File
@@ -0,0 +1,53 @@
import { NextResponse } from "next/server";
export const revalidate = 120;
const FEED_URL = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson";
function isValidFeature(feature: any): boolean {
const coordinates = feature?.geometry?.coordinates;
const time = feature?.properties?.time;
return Array.isArray(coordinates)
&& coordinates.length >= 2
&& Number.isFinite(coordinates[0])
&& Number.isFinite(coordinates[1])
&& Number.isFinite(time);
}
export async function GET() {
try {
const response = await fetch(FEED_URL, {
headers: {
Accept: "application/geo+json, application/json",
"User-Agent": "WorldWideView/1.0",
},
next: { revalidate },
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to fetch earthquake feed" },
{ status: 502 },
);
}
const data = await response.json();
const features = Array.isArray(data?.features)
? data.features.filter(isValidFeature)
: [];
return NextResponse.json({
type: "FeatureCollection",
metadata: data?.metadata,
bbox: data?.bbox,
features,
});
} catch (error) {
console.error("[EarthquakeRoute] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch earthquake feed" },
{ status: 502 },
);
}
}
+3 -3
View File
@@ -35,7 +35,7 @@ export async function GET(request: Request) {
]);
const manifests = records
.map((r): PluginManifest | null => {
.map((r: any): PluginManifest | null => {
try {
const manifest = JSON.parse(r.config);
if (!manifest.id) manifest.id = r.pluginId;
@@ -44,7 +44,7 @@ export async function GET(request: Request) {
return null;
}
})
.filter((m): m is PluginManifest => {
.filter((m: any): m is PluginManifest => {
if (!m) return false;
// Skip built-in plugins — already registered by AppShell
if (m.trust === "built-in") return false;
@@ -62,7 +62,7 @@ export async function GET(request: Request) {
const { valid } = validateManifest(m);
return valid;
})
.map((m) => {
.map((m: any) => {
// Re-stamp trust against the live registry so revoked plugins
// are correctly gated by the unverified dialog on the client.
if (m.trust !== "built-in") {
+2 -2
View File
@@ -26,10 +26,10 @@ export async function GET(request: Request) {
try {
const dbPlugins = await getInstalledPlugins();
const dbMap = new Map(dbPlugins.map((p) => [p.pluginId, p]));
const dbMap = new Map(dbPlugins.map((p: any) => [p.pluginId, p]));
// Collect active DB plugins (exclude disabled ones)
const activeDbPlugins = dbPlugins.filter((p) => p.enabled !== false);
const activeDbPlugins = dbPlugins.filter((p: any) => p.enabled !== false);
// Add built-in plugins that aren't in the DB at all (default = installed)
const builtInRecords = BUILT_IN_PLUGIN_IDS
+72
View File
@@ -0,0 +1,72 @@
import { NextResponse } from "next/server";
const OVERPASS_MIRRORS = [
"https://overpass-api.de/api/interpreter",
"https://lz4.overpass-api.de/api/interpreter",
"https://overpass.kumi.systems/api/interpreter"
];
async function tryMirror(url: string, query: string, timeout: number) {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `data=${encodeURIComponent(query)}`,
signal: AbortSignal.timeout(timeout)
});
return res;
}
export async function POST(req: Request) {
try {
const body = await req.json();
const { query } = body;
if (!query) {
return NextResponse.json({ error: "Missing query" }, { status: 400 });
}
console.log(`[OSMSearchProxy] Querying Overpass API mirrors... (length: ${query.length})`);
let lastError = null;
for (const mirror of OVERPASS_MIRRORS) {
try {
console.log(`[OSMSearchProxy] Trying mirror: ${mirror}`);
const res = await tryMirror(mirror, query, 25000); // 25s per mirror
if (res.ok) {
const data = await res.json();
if (data.elements) {
return NextResponse.json({ data: data.elements });
}
if (data.remark) {
console.warn(`[OSMSearchProxy] ${mirror} returned remark: ${data.remark}`);
// If it's a specific query error (remark), don't bother retrying mirrors
return NextResponse.json({ error: data.remark }, { status: 400 });
}
} else {
const text = await res.text();
console.warn(`[OSMSearchProxy] Mirror ${mirror} failed: ${res.status} ${res.statusText}`);
lastError = { status: res.status, statusText: res.statusText, details: text };
// If it's a 4xx error (except 429), it's probably a bad query, so don't retry
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
break;
}
}
} catch (err: any) {
console.warn(`[OSMSearchProxy] Mirror ${mirror} threw error:`, err.message);
lastError = { status: 500, statusText: "Internal Error", details: err.message };
}
}
return NextResponse.json(
{
error: "All Overpass mirrors failed or timed out. The OSM servers are likely under heavy load.",
lastError
},
{ status: lastError?.status || 504 }
);
} catch (e: any) {
console.error(`[OSMSearchProxy] Internal error:`, e);
return NextResponse.json({ error: e.message }, { status: 500 });
}
}
+23
View File
@@ -1,3 +1,5 @@
/* Agentic Claude workflow active - April 2026 */
/* Agentic Claude workflow active - April 2026 */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
/* ─── Design Tokens ───────────────────────────────────────── */
@@ -1755,6 +1757,27 @@ html, body {
color: var(--text-primary);
}
.imagery-item--failed .imagery-item__thumbnail {
border-color: rgba(239, 68, 68, 0.6);
box-shadow: 0 0 10px rgba(239, 68, 68, 0.2);
background: rgba(239, 68, 68, 0.05);
}
.imagery-item--failed .imagery-item__name {
color: var(--accent-red);
}
.imagery-item--fallback .imagery-item__thumbnail {
border-color: rgba(34, 197, 94, 0.8);
box-shadow: 0 0 10px rgba(34, 197, 94, 0.2);
background: rgba(34, 197, 94, 0.05);
}
.imagery-item--fallback .imagery-item__icon,
.imagery-item--fallback .imagery-item__name {
color: #22c55e;
}
/* ─── Camera Stats Panel ─────────────────────────────────── */
.camera-stats {
position: fixed;
+2
View File
@@ -27,6 +27,7 @@ import { CivilUnrestPlugin } from "@worldwideview/wwv-plugin-civil-unrest";
import { SurveillanceSatellitesPlugin } from "@worldwideview/wwv-plugin-surveillance-satellites";
import { CyberAttacksPlugin } from "@worldwideview/wwv-plugin-cyber-attacks";
import { InternationalSanctionsPlugin } from "@worldwideview/wwv-plugin-international-sanctions";
import { OSMSearchPlugin } from "@worldwideview/wwv-plugin-osm-search";
import { useStore } from "@/core/state/store";
import { dataBus } from "@/core/data/DataBus";
import { PanelToggleArrows } from "@/components/layout/PanelToggleArrows";
@@ -97,6 +98,7 @@ export function AppShell() {
new SurveillanceSatellitesPlugin(),
new CyberAttacksPlugin(),
new InternationalSanctionsPlugin(),
new OSMSearchPlugin(),
];
for (const plugin of builtIns) {
@@ -7,6 +7,7 @@ import {
clearAllUserApiKeys,
} from "@/lib/userApiKeys";
import { sectionHeaderStyle, inputGroupStyle, labelStyle } from "./sharedStyles";
import ReloadToast from "@/components/ui/ReloadToast";
type VerifyStatus = "idle" | "verifying" | "valid" | "invalid";
@@ -61,6 +62,7 @@ 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 [needsReload, setNeedsReload] = useState(false);
const debounceRefs = useRef<Record<string, ReturnType<typeof setTimeout>>>({});
const verifyKey = useCallback(async (service: string, key: string) => {
@@ -74,7 +76,11 @@ export function ApiKeysTab() {
});
const data = await res.json();
setStatus((prev) => ({ ...prev, [service]: data.valid ? "valid" : "invalid" }));
if (!data.valid) setErrors((prev) => ({ ...prev, [service]: data.error || "Invalid key" }));
if (!data.valid) {
setErrors((prev) => ({ ...prev, [service]: data.error || "Invalid key" }));
} else if (service === "google_maps") {
setNeedsReload(true);
}
} catch {
setStatus((prev) => ({ ...prev, [service]: "invalid" }));
setErrors((prev) => ({ ...prev, [service]: "Verification failed" }));
@@ -217,6 +223,8 @@ export function ApiKeysTab() {
Clear All Keys
</button>
)}
{needsReload && <ReloadToast message="Google Maps API Key validated. Reload to apply." />}
</>
);
}
+187 -28
View File
@@ -1,11 +1,162 @@
import { useStore } from "@/core/state/store";
import { pluginManager } from "@/core/plugins/PluginManager";
import { PluginIcon } from "@/components/common/PluginIcon";
import { Eye, MapPin, Lock, Unlock, Star, ExternalLink, Maximize2 } from "lucide-react";
import { Eye, MapPin, Lock, Unlock, Star, ExternalLink, Maximize2, Filter, RotateCcw } from "lucide-react";
import { dataBus } from "@/core/data/DataBus";
import { sectionHeaderStyle } from "./sharedStyles";
import { TimestampProperty } from "../properties/TimestampProperty";
import { DynamicPropertiesRender } from "../properties/DynamicPropertiesRender";
import { useRef, useEffect } from "react";
function LegendItem({
label,
color,
pluginId,
colorOverrides,
updatePluginSettings,
isFilterable = false,
isActive = true,
toggleFilter = () => {},
isDefault = false,
customLayerColor = null
}: {
label: string,
color: string,
pluginId: string,
colorOverrides?: Record<string, string>,
updatePluginSettings: (id: string, s: any) => void,
isFilterable?: boolean,
isActive?: boolean,
toggleFilter?: () => void,
isDefault?: boolean,
customLayerColor?: string | null
}) {
const inputRef = useRef<HTMLInputElement>(null);
const displayColor = isDefault
? (customLayerColor || color)
: (colorOverrides?.[color] || color);
const hasOverride = isDefault
? !!customLayerColor
: !!colorOverrides?.[color];
const actualColorForInput = displayColor.startsWith("#") ? displayColor : "#3b82f6";
return (
<div
style={{
display: "flex",
alignItems: "center",
gap: "var(--space-md)",
background: "rgba(255,255,255,0.03)",
padding: "var(--space-sm) var(--space-md)",
borderRadius: "var(--radius-md)",
cursor: "pointer",
opacity: isActive ? 1 : 0.4,
transition: "all var(--duration-fast)",
border: "1px solid rgba(255,255,255,0.05)",
position: "relative",
overflow: "hidden"
}}
onClick={() => inputRef.current?.click()}
onMouseEnter={(e) => {
e.currentTarget.style.background = "rgba(255,255,255,0.06)";
e.currentTarget.style.borderColor = "rgba(255,255,255,0.1)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = "rgba(255,255,255,0.03)";
e.currentTarget.style.borderColor = "rgba(255,255,255,0.05)";
}}
>
<input
ref={inputRef}
type="color"
value={actualColorForInput}
onChange={(e) => {
if (isDefault) {
updatePluginSettings(pluginId, { customLayerColor: e.target.value });
} else if (colorOverrides) {
updatePluginSettings(pluginId, {
colorOverrides: { ...colorOverrides, [color]: e.target.value }
});
}
}}
style={{ position: "absolute", opacity: 0, width: 0, height: 0, pointerEvents: "none" }}
/>
<div style={{
position: "absolute",
top: 0,
left: 0,
width: "3px",
height: "100%",
background: displayColor,
boxShadow: `0 0 10px ${displayColor}88`
}} />
<div style={{
width: 16,
height: 16,
borderRadius: "var(--radius-sm)",
backgroundColor: displayColor,
border: "1px solid rgba(255,255,255,0.2)",
boxShadow: `0 0 8px ${displayColor}44`,
flexShrink: 0
}} />
<div style={{ flex: 1, display: "flex", flexDirection: "column", gap: "1px" }}>
<span style={{ fontSize: 13, fontWeight: 500, color: "var(--text-primary)" }}>{label}</span>
<span style={{ fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--text-muted)", letterSpacing: "0.02em" }}>{displayColor.toUpperCase()}</span>
</div>
<div style={{ display: "flex", alignItems: "center", gap: "var(--space-xs)" }}>
{isFilterable && (
<button
onClick={(e) => { e.stopPropagation(); toggleFilter(); }}
title={isActive ? "Disable filter" : "Enable filter"}
style={{
background: isActive ? "rgba(0, 255, 255, 0.1)" : "transparent",
border: "none",
color: isActive ? "var(--accent-cyan)" : "var(--text-muted)",
padding: "6px",
borderRadius: "var(--radius-sm)",
display: "flex",
cursor: "pointer"
}}
>
<Filter size={14} />
</button>
)}
{hasOverride && (
<button
onClick={(e) => {
e.stopPropagation();
if (isDefault) {
updatePluginSettings(pluginId, { customLayerColor: null });
} else if (colorOverrides) {
const newOverrides = { ...colorOverrides };
delete newOverrides[color];
updatePluginSettings(pluginId, { colorOverrides: newOverrides });
}
}}
title="Reset to default"
style={{
background: "transparent",
border: "none",
color: "var(--text-muted)",
padding: "6px",
borderRadius: "var(--radius-sm)",
display: "flex",
cursor: "pointer"
}}
>
<RotateCcw size={14} />
</button>
)}
</div>
</div>
);
}
export function IntelTab() {
const selectedEntity = useStore((s) => s.selectedEntity);
@@ -17,15 +168,20 @@ export function IntelTab() {
const highlightLayerId = useStore((s) => s.highlightLayerId);
const filters = useStore((s) => s.filters);
const setFilter = useStore((s) => s.setFilter);
const addFloatingStream = useStore((s) => s.addFloatingStream);
const updatePluginSettings = useStore((s) => s.updatePluginSettings);
const pluginSettings = useStore((s) => s.dataConfig.pluginSettings);
if (!selectedEntity) {
if (highlightLayerId) {
const layerPlugin = pluginManager.getPlugin(highlightLayerId);
if (layerPlugin) {
const layerConfig = layerPlugin.plugin.getLayerConfig();
const SidebarComp = layerPlugin.plugin.getSidebarComponent?.();
const defaultColor = layerConfig?.color || "var(--accent-cyan)";
const legend = layerPlugin.plugin.getLegend?.();
const pluginId = layerPlugin.plugin.id;
const settings = pluginSettings[pluginId] || {};
const colorOverrides = settings.colorOverrides || {};
return (
<div style={{ padding: "var(--space-md)" }}>
@@ -38,13 +194,20 @@ export function IntelTab() {
<div style={{ color: "var(--text-secondary)", fontSize: 13, marginBottom: "var(--space-lg)", lineHeight: 1.5 }}>
{layerPlugin.plugin.description}
</div>
{SidebarComp && (
<div style={{ marginBottom: "var(--space-lg)", paddingBottom: "var(--space-lg)", borderBottom: "1px solid var(--border-subtle)" }}>
<SidebarComp plugin={layerPlugin.plugin} />
</div>
)}
<div style={{ display: "flex", flexDirection: "column", gap: "var(--space-sm)" }}>
<span style={{ fontSize: 11, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.05em" }}>
{legend && legend.length > 1 ? "Data Point Colors" : "Data Point Color"}
</span>
{legend && legend.length > 0 ? (
<div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
<div style={{ display: "flex", flexDirection: "column", gap: "var(--space-sm)" }}>
{legend.map((item, idx) => {
const isFilterable = Boolean(item.filterId && item.filterValue);
const currentFilter = isFilterable ? filters[layerPlugin.plugin.id]?.[item.filterId!] : undefined;
@@ -57,7 +220,6 @@ export function IntelTab() {
const toggleFilter = () => {
if (!isFilterable) return;
const pluginId = layerPlugin.plugin.id;
const filterId = item.filterId!;
const filterVal = item.filterValue!;
@@ -79,34 +241,29 @@ export function IntelTab() {
};
return (
<div
key={idx}
style={{
display: "flex",
alignItems: "center",
gap: "var(--space-sm)",
background: "rgba(255,255,255,0.03)",
padding: "var(--space-sm)",
borderRadius: "var(--radius-sm)",
cursor: isFilterable ? "pointer" : "default",
opacity: isActive ? 1 : 0.4,
transition: "opacity var(--duration-fast)"
}}
onClick={toggleFilter}
title={isFilterable ? "Click to filter by this category" : ""}
>
<span style={{ width: 14, height: 14, borderRadius: "50%", backgroundColor: item.color, display: "inline-block", border: "1px solid rgba(255,255,255,0.2)", boxShadow: "0 0 6px rgba(0,0,0,0.5)", flexShrink: 0 }} />
<span style={{ fontSize: 13, color: "var(--text-primary)" }}>{item.label}</span>
<span style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--text-muted)", marginLeft: "auto" }}>{item.color}</span>
</div>
<LegendItem
key={idx}
label={item.label}
color={item.color}
pluginId={pluginId}
colorOverrides={colorOverrides}
updatePluginSettings={updatePluginSettings}
isFilterable={isFilterable}
isActive={isActive}
toggleFilter={toggleFilter}
/>
);
})}
</div>
) : (
<div style={{ display: "flex", alignItems: "center", gap: "var(--space-sm)", background: "rgba(255,255,255,0.03)", padding: "var(--space-sm)", borderRadius: "var(--radius-sm)" }}>
<span style={{ width: 14, height: 14, borderRadius: "50%", backgroundColor: defaultColor, display: "inline-block", border: "1px solid rgba(255,255,255,0.2)", boxShadow: "0 0 6px rgba(0,0,0,0.5)" }} />
<span style={{ fontSize: 13, fontFamily: "var(--font-mono)", color: "var(--text-primary)" }}>{defaultColor}</span>
</div>
<LegendItem
label="Default Layer Color"
color={defaultColor}
pluginId={pluginId}
updatePluginSettings={updatePluginSettings}
isDefault={true}
customLayerColor={settings.customLayerColor}
/>
)}
</div>
</div>
@@ -215,10 +372,12 @@ export function IntelTab() {
title="Go to entity"
onClick={() => {
console.log("[Intel] Go To button clicked", selectedEntity.latitude, selectedEntity.longitude);
const behavior = managed?.plugin.getSelectionBehavior?.(selectedEntity);
dataBus.emit("cameraGoTo", {
lat: selectedEntity.latitude,
lon: selectedEntity.longitude,
alt: selectedEntity.altitude || 0,
distance: behavior?.flyToBaseDistance
});
}}
>
+29 -11
View File
@@ -9,6 +9,7 @@ import { GraphicsSettings } from "./GraphicsSettings";
export function ImageryPicker() {
const baseLayerId = useStore((s) => s.mapConfig.baseLayerId);
const fallbackLayerId = useStore((s) => s.mapConfig.fallbackLayerId);
const sceneMode = useStore((s) => s.mapConfig.sceneMode);
const updateMapConfig = useStore((s) => s.updateMapConfig);
@@ -46,18 +47,35 @@ export function ImageryPicker() {
<div className="imagery-picker__section">
<div className="imagery-picker__title">Imagery Layer</div>
<div className="imagery-picker__grid">
{IMAGERY_LAYERS.map((layer) => (
<div
key={layer.id}
className={`imagery-item ${baseLayerId === layer.id ? "imagery-item--active" : ""}`}
onClick={() => { updateMapConfig({ baseLayerId: layer.id }); trackEvent("imagery-layer-change", { layer: layer.id }); }}
>
<div className="imagery-item__thumbnail">
<Layers size={20} className="imagery-item__icon" />
{IMAGERY_LAYERS.map((layer) => {
const isSelected = baseLayerId === layer.id;
const isFallbackMode = fallbackLayerId !== null;
const isThisFallback = fallbackLayerId === layer.id;
const isFailedTarget = isFallbackMode && isSelected;
const isActive = isFallbackMode ? isThisFallback : isSelected;
let className = "imagery-item";
if (isFailedTarget) className += " imagery-item--failed";
else if (isThisFallback) className += " imagery-item--fallback";
else if (isActive) className += " imagery-item--active";
return (
<div
key={layer.id}
className={className}
onClick={() => {
updateMapConfig({ baseLayerId: layer.id, fallbackLayerId: null });
trackEvent("imagery-layer-change", { layer: layer.id });
}}
title={isFailedTarget ? "Error: Missing API Key" : (isThisFallback ? "Active Fallback" : "")}
>
<div className="imagery-item__thumbnail">
<Layers size={20} className="imagery-item__icon" />
</div>
<div className="imagery-item__name">{layer.name}</div>
</div>
<div className="imagery-item__name">{layer.name}</div>
</div>
))}
);
})}
</div>
</div>
+12 -4
View File
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import styles from "./ReloadToast.module.css";
interface ReloadToastProps {
@@ -10,13 +11,19 @@ interface ReloadToastProps {
/**
* Floating toast prompting user to reload after plugin changes.
* Dismissible, with a Reload button that triggers a full page refresh.
* Rendered via portal to escape panel boundaries and z-index contexts.
*/
export default function ReloadToast({ message }: ReloadToastProps) {
const [dismissed, setDismissed] = useState(false);
const [mounted, setMounted] = useState(false);
if (dismissed) return null;
useEffect(() => {
setMounted(true);
}, []);
return (
if (dismissed || !mounted) return null;
return createPortal(
<div className={styles.overlay}>
<div className={styles.toast}>
<span className={styles.icon}>🔄</span>
@@ -37,6 +44,7 @@ export default function ReloadToast({ message }: ReloadToastProps) {
✕
</button>
</div>
</div>
</div>,
document.body
);
}
+7 -3
View File
@@ -1,5 +1,5 @@
import { expect, test, describe } from "vitest";
import { readFileSync, globSync } from "fs";
import * as fs from "fs";
import { join } from "path";
describe("Monorepo Workspace Integrity", () => {
@@ -8,15 +8,19 @@ describe("Monorepo Workspace Integrity", () => {
// __dirname is dist/core/__tests__ when transpiled or src/core/__tests__ when running tsx/vitest natively
const rootDir = process.cwd(); // vitest runs from workspace root
const packageDirs = fs.readdirSync(join(rootDir, "packages"), { withFileTypes: true })
.filter(d => d.isDirectory())
.map(d => `packages/${d.name}/package.json`)
.filter(p => fs.existsSync(join(rootDir, p)));
const packageJsonFiles = [
"package.json",
...globSync("packages/**/package.json", { cwd: rootDir, ignore: ["**/node_modules/**"] })
...packageDirs
];
let failedFiles: string[] = [];
for (const file of packageJsonFiles) {
const content = readFileSync(join(rootDir, file), "utf-8");
const content = fs.readFileSync(join(rootDir, file), "utf-8");
const pkg = JSON.parse(content);
const deps = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies };
+1 -1
View File
@@ -224,7 +224,7 @@ function processEntity(
return;
}
if (!item.options.disableManualHorizonCulling) {
if (!item.options.disableManualHorizonCulling || primitive.disableDepthTestDistance === Number.POSITIVE_INFINITY) {
// Mathematical horizon culling (extremely fast, precise for sphere)
item._occluded = Cartesian3.dot(posRef, camPos) <= R2;
if (item._occluded) {
+28 -8
View File
@@ -61,6 +61,7 @@ export default function GlobeView() {
shadowsEnabled, enableLighting,
}), [showFps, resolutionScale, antiAliasing, maxScreenSpaceError, shadowsEnabled, enableLighting]);
const filters = useStore((s) => s.filters);
const pluginSettings = useStore((s) => s.dataConfig.pluginSettings);
const lockedEntityId = useStore((s) => s.lockedEntityId);
const setCameraPosition = useStore((s) => s.setCameraPosition);
const setFps = useStore((s) => s.setFps);
@@ -71,20 +72,36 @@ export default function GlobeView() {
const visibleEntities = useMemo(() => {
const result: Array<{ entity: GeoEntity; options: CesiumEntityOptions }> = [];
pluginManager.getAllPlugins().forEach((managed) => {
if (!layers[managed.plugin.id]?.enabled) return;
const pluginId = managed.plugin.id;
if (!layers[pluginId]?.enabled) return;
if (managed.plugin.getLayerConfig().disableDefaultRendering) return;
const entities = entitiesByPlugin[managed.plugin.id];
const entities = entitiesByPlugin[pluginId];
if (!Array.isArray(entities)) return;
const settings = pluginSettings[pluginId];
const colorOverrides = settings?.colorOverrides;
const customLayerColor = settings?.customLayerColor;
const defs = managed.plugin.getFilterDefinitions?.() || [];
const active = filters[managed.plugin.id] || {};
const active = filters[pluginId] || {};
applyFilters(entities, defs, active).forEach((entity) => {
result.push({ entity, options: getCachedRenderOptions(managed.plugin, entity) });
const originalOptions = getCachedRenderOptions(managed.plugin, entity);
// Apply color overrides
let options = originalOptions;
if (originalOptions.color && colorOverrides && colorOverrides[originalOptions.color]) {
options = { ...originalOptions, color: colorOverrides[originalOptions.color] };
} else if (customLayerColor) {
options = { ...originalOptions, color: customLayerColor };
}
result.push({ entity, options });
});
});
return result;
}, [layers, entitiesByPlugin, filters]);
}, [layers, entitiesByPlugin, filters, pluginSettings]);
const { isGoogle3D } = useImageryManager(viewerRef.current);
const { isGoogle3D } = useImageryManager(viewerRef.current, viewerReady);
useBorders(viewerRef.current, showLabels, isGoogle3D);
useSelectionAnchor(viewerRef.current, viewerReady, selectedEntity, lockedEntityId, selectionEntityRef, animatablesMapRef);
@@ -201,14 +218,17 @@ export default function GlobeView() {
}, [lockedEntityId, viewerReady]);
const PluginGlobeComponents = useMemo(() => {
return pluginManager.getAllPlugins()
const components = pluginManager.getAllPlugins()
.filter(managed => managed.plugin.getGlobeComponent)
.map(managed => {
const Comp = managed.plugin.getGlobeComponent!();
const enabled = layers[managed.plugin.id]?.enabled ?? false;
console.log(`[GlobeView] Rendering plugin globe component: ${managed.plugin.id}, enabled: ${enabled}`);
return <Comp key={managed.plugin.id} viewer={viewerRef.current} enabled={enabled} />;
});
}, [layers]);
console.log(`[GlobeView] Recomputing PluginGlobeComponents. Count: ${components.length}`);
return components;
}, [layers, viewerReady]);
return (
<Viewer
+72 -66
View File
@@ -1,8 +1,10 @@
import { useCallback, useRef, useState } from "react";
import type { Viewer as CesiumViewer } from "cesium";
import { Cartesian3, CameraEventType, KeyboardEventModifier, createGooglePhotorealistic3DTileset, createOsmBuildingsAsync, GoogleMaps } from "cesium";
import { Cartesian3, CameraEventType, KeyboardEventModifier, createGooglePhotorealistic3DTileset, GoogleMaps } from "cesium";
import { dataBus } from "@/core/data/DataBus";
import { initPrimitiveCollections } from "../EntityRenderer";
import { getUserApiKey } from "@/lib/userApiKeys";
import { useStore } from "@/core/state/store";
export function useViewerInitialization(sceneSettings: any) {
const viewerRef = useRef<CesiumViewer | null>(null);
@@ -10,17 +12,44 @@ export function useViewerInitialization(sceneSettings: any) {
const handleViewerReady = useCallback(async (viewer: CesiumViewer) => {
viewerRef.current = viewer;
// 1. Core Viewer Settings (Sync)
viewer.imageryLayers.removeAll();
viewer.scene.requestRenderMode = true;
viewer.scene.maximumRenderTimeChange = 0.5;
// viewer.scene.orderIndependentTranslucency is read-only in newer Cesium versions and no longer configurable
viewer.scene.debugShowFramesPerSecond = sceneSettings.showFps;
viewer.resolutionScale = sceneSettings.resolutionScale;
viewer.scene.postProcessStages.fxaa.enabled = sceneSettings.antiAliasing === "fxaa";
viewer.scene.msaaSamples = sceneSettings.antiAliasing === "none" || sceneSettings.antiAliasing === "fxaa" ? 1 : parseInt(sceneSettings.antiAliasing.replace("msaa", "").replace("x", ""), 10) || 1;
viewer.scene.globe.depthTestAgainstTerrain = true;
// Configure Screen Space Camera
const sscc = viewer.scene.screenSpaceCameraController;
sscc.tiltEventTypes = [
CameraEventType.MIDDLE_DRAG,
CameraEventType.RIGHT_DRAG,
CameraEventType.PINCH,
{ eventType: CameraEventType.LEFT_DRAG, modifier: KeyboardEventModifier.CTRL },
{ eventType: CameraEventType.RIGHT_DRAG, modifier: KeyboardEventModifier.CTRL }
];
sscc.zoomEventTypes = [CameraEventType.WHEEL, CameraEventType.PINCH];
if ("ontouchstart" in window || navigator.maxTouchPoints > 0) {
(sscc as any)._zoomFactor = 15;
(sscc as any)._translateFactor = 2;
(sscc as any)._tiltFactor = 50;
}
// Initialize collections so renderers can start immediately
initPrimitiveCollections(viewer);
// Initial Camera Position (Sync)
viewer.camera.setView({ destination: Cartesian3.fromDegrees(0, 20, 10000000) });
// Signal ready NOW so UI and Overlays (OSM Box) appear instantly
setViewerReady(true);
// 2. Heavy/Async Data Loading (Background)
let globeFired = false;
const fireGlobeReady = () => {
if (globeFired) return;
@@ -30,83 +59,60 @@ export function useViewerInitialization(sceneSettings: any) {
}
dataBus.emit("globeReady", {} as Record<string, never>);
};
const globalTimeout = setTimeout(() => {
console.warn("[GlobeView] Global tile-init timeout (15s) — forcing globe ready.");
fireGlobeReady();
}, 15_000);
try {
// We are commenting this out because the Google Maps API key provided in .env.local
// returns a 404 "Requested entity was not found" from Google's servers.
// Using Cesium Ion's proxy key inherently works, so we rely on that instead.
// if (process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY) {
// GoogleMaps.defaultApiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;
// }
const envKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;
const userGoogleKey = getUserApiKey("google_maps");
const activeKey = (userGoogleKey && userGoogleKey.length >= 20) ? userGoogleKey : envKey;
const tileset = await createGooglePhotorealistic3DTileset({
onlyUsingWithGoogleGeocoder: true,
...({ enableCollision: true } as Record<string, unknown>),
});
if (viewer.isDestroyed()) {
console.warn("[GlobeView] Viewer destroyed during tileset init — aborting.");
clearTimeout(globalTimeout);
return;
}
tileset.maximumScreenSpaceError = sceneSettings.maxScreenSpaceError;
// Increase the local cache of downloaded tiles from the default 512MB to 2048MB.
// This massively mitigates duplicate tile API requests hitting Google when users
// pan around the map in local areas.
tileset.maximumMemoryUsage = 2048;
viewer.scene.primitives.add(tileset);
const removeListener = tileset.initialTilesLoaded.addEventListener(() => {
console.log("[GlobeView] Initial tiles loaded — globe ready.");
clearTimeout(globalTimeout);
fireGlobeReady();
removeListener();
});
} catch (err) {
console.warn("[GlobeView] Failed to initialize Google 3D Tiles, checking OSM fallback...", err);
let googleLoaded = false;
if (!viewer.isDestroyed()) {
if (activeKey && activeKey.length >= 20) {
GoogleMaps.defaultApiKey = activeKey;
try {
const osmBuildings = await createOsmBuildingsAsync();
viewer.scene.primitives.add(osmBuildings);
console.log("[GlobeView] Successfully fell back to Cesium OSM Buildings.");
} catch (fallbackErr) {
console.warn("[GlobeView] Failed to load OSM Buildings fallback:", fallbackErr);
const tileset = await createGooglePhotorealistic3DTileset({
onlyUsingWithGoogleGeocoder: true,
...({ enableCollision: true } as Record<string, unknown>),
});
if (viewer.isDestroyed()) {
clearTimeout(globalTimeout);
return;
}
tileset.maximumScreenSpaceError = sceneSettings.maxScreenSpaceError;
(tileset as any).maximumMemoryUsage = 2048;
viewer.scene.primitives.add(tileset);
const removeListener = tileset.initialTilesLoaded.addEventListener(() => {
console.log("[GlobeView] Initial tiles loaded — syncing state.");
useStore.getState().updateMapConfig({ baseLayerId: "google-3d" });
clearTimeout(globalTimeout);
fireGlobeReady();
removeListener();
});
googleLoaded = true;
} catch (err: any) {
console.error("[GlobeView] Failed to initialize Google 3D Tiles:", err);
}
}
clearTimeout(globalTimeout);
if (!googleLoaded) {
if (useStore.getState().mapConfig.baseLayerId === "google-3d") {
useStore.getState().updateMapConfig({ fallbackLayerId: "bing-aerial" });
}
clearTimeout(globalTimeout);
fireGlobeReady();
}
} catch (err) {
console.error("[GlobeView] Unexpected error during early globe init:", err);
fireGlobeReady();
}
if (viewer.isDestroyed()) return;
initPrimitiveCollections(viewer);
const sscc = viewer.scene.screenSpaceCameraController;
sscc.tiltEventTypes = [
CameraEventType.MIDDLE_DRAG,
CameraEventType.RIGHT_DRAG,
CameraEventType.PINCH,
{ eventType: CameraEventType.LEFT_DRAG, modifier: KeyboardEventModifier.CTRL },
{ eventType: CameraEventType.RIGHT_DRAG, modifier: KeyboardEventModifier.CTRL }
];
sscc.zoomEventTypes = [
CameraEventType.WHEEL,
CameraEventType.PINCH
];
if ("ontouchstart" in window || navigator.maxTouchPoints > 0) {
(sscc as any)._zoomFactor = 15;
(sscc as any)._translateFactor = 2;
(sscc as any)._tiltFactor = 50;
}
setViewerReady(true);
}, [sceneSettings]);
return { viewerRef, viewerReady, handleViewerReady };
+8 -1
View File
@@ -27,6 +27,13 @@ export function getBaseSize(): number {
/** Padding ratio — the icon fills (1 - 2*INSET) of the canvas. */
const ICON_INSET = 0.12;
/**
* Background circle size ratio (relative to canvas radius).
* Adjust this to scale the black half-transparent backdrop.
* 1.0 = fills canvas, 0.8 = 80% of canvas radius.
*/
const BG_RADIUS_RATIO = 1.0;
/** Default backdrop behind the icon for terrain contrast. */
const DEFAULT_BG = "rgba(15, 23, 42, 0.55)";
@@ -74,7 +81,7 @@ export function getHiResIcon(srcUrl: string, bgColor = DEFAULT_BG): Promise<stri
// Subtle circle backdrop for terrain contrast
const cx = pxSize / 2;
ctx.beginPath();
ctx.arc(cx, cx, cx, 0, Math.PI * 2);
ctx.arc(cx, cx, cx * BG_RADIUS_RATIO, 0, Math.PI * 2);
ctx.fillStyle = bgColor;
ctx.fill();
+21 -3
View File
@@ -63,6 +63,15 @@ export function updateExistingItem(
item.baseColor = color;
item.baseOutlineColor = getCachedColor(options.outlineColor) || Color.BLACK;
const isGroundBased = (entity.altitude || 0) < 100;
const disableDepthTestDistance = isGroundBased
? Number.POSITIVE_INFINITY
: options.disableDepthTestDistance;
if (item.primitive.disableDepthTestDistance !== disableDepthTestDistance) {
item.primitive.disableDepthTestDistance = disableDepthTestDistance;
}
const billboardColor = (options as any)._isAutoSVG ? Color.WHITE : color;
if (!Color.equals(item.primitive.color, billboardColor)) item.primitive.color = billboardColor;
@@ -115,6 +124,14 @@ export function createNewItem(
const baseSize = getBaseSize();
const billboardColor = (options as any)._isAutoSVG ? Color.WHITE : color;
// Performance optimization: Ground-based entities (altitude < 100m) should disable
// Cesium's heavy depth testing and instead use our efficient manual horizon culling.
// Air-based entities keep depth testing enabled for realistic occlusion against mountains.
const isGroundBased = (entity.altitude || 0) < 100;
const disableDepthTestDistance = isGroundBased
? Number.POSITIVE_INFINITY
: options.disableDepthTestDistance;
const addedPrimitive = options.iconUrl
? billboards.add({
position: newPosition, image: resolvedIcon,
@@ -123,17 +140,18 @@ export function createNewItem(
verticalOrigin: VerticalOrigin.CENTER, horizontalOrigin: HorizontalOrigin.CENTER,
rotation: options.rotation ? -CesiumMath.toRadians(options.rotation) : 0,
color: billboardColor, scaleByDistance: new NearFarScalar(1e6, 1.0, 2e7, 0.5), id: clickId,
eyeOffset: new Cartesian3(0, 0, options.depthBias ?? -10000), // Small depth bias for far-range terrain
// eyeOffset: new Cartesian3(0, 0, options.depthBias ?? -10000), // Small depth bias for far-range terrain
// WARNING: Do NOT use heightReference: HeightReference.CLAMP_TO_GROUND here.
// It causes severe lag/performance drops with thousands of dynamic entities.
disableDepthTestDistance: options.disableDepthTestDistance, distanceDisplayCondition: ddc,
disableDepthTestDistance, distanceDisplayCondition: ddc,
})
: points.add({
position: newPosition, pixelSize: options.size || defaultPointSize(), color, outlineColor,
outlineWidth: options.outlineWidth || 1, show: false,
scaleByDistance: new NearFarScalar(1e6, 1.0, 2e7, 0.5), id: clickId,
disableDepthTestDistance: options.disableDepthTestDistance, distanceDisplayCondition: ddc,
disableDepthTestDistance, distanceDisplayCondition: ddc,
});
existingMap.set(entity.id, {
primitive: addedPrimitive, labelPrimitive: undefined, entity, posRef: newPosition,
options, baseColor: color, baseOutlineColor: outlineColor, lastHighlightState: 'normal'
+15 -3
View File
@@ -19,6 +19,12 @@ const hubScaleByDistance = new NearFarScalar(2.0e6, 1.0, 1.5e7, 0.5);
/** Duration of expand/collapse animation in ms. */
const ANIM_DURATION_MS = 220;
/**
* Radius of the cluster hub background circle.
* Adjust this to scale the black half-transparent badge.
*/
const HUB_BG_RADIUS = 14;
/** Reusable scratch Cartesian2 to avoid allocation. */
const scratchOffset = new Cartesian2();
@@ -37,7 +43,7 @@ function getClusterIcon(count: number, hexColor: string): string {
const textStr = count > 99 ? '99+' : count.toString();
const fillValue = "rgba(15, 23, 42, 0.95)";
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}">
<circle cx="${center}" cy="${center}" r="16" fill="${fillValue}" stroke="${hexColor}" stroke-width="2.5"/>
<circle cx="${center}" cy="${center}" r="${HUB_BG_RADIUS}" fill="${fillValue}" stroke="${hexColor}" stroke-width="2.5"/>
<text x="${center}" y="${center + 1}" font-family="Inter, sans-serif" font-size="14px" font-weight="bold" fill="#ffffff" text-anchor="middle" dominant-baseline="middle">${textStr}</text>
</svg>`;
@@ -157,8 +163,14 @@ function tickSingle(stack: EntityStack, now: number, billboards: BillboardCollec
function manageDedicatedHub(stack: EntityStack, billboards: BillboardCollection) {
let bb = hubBillboards.get(stack.id);
const count = stack.children.length;
// Caching CSS color string per stack rather than generating it every frame
const cssColor = (stack.hubItem as any)._cachedCssColor ?? ((stack.hubItem as any)._cachedCssColor = stack.hubItem.baseColor?.toCssColorString() ?? "#ffffff");
// Check if the hubItem's baseColor has changed since we last cached it
const currentBaseColor = stack.hubItem.baseColor?.toCssColorString() ?? "#ffffff";
if ((stack.hubItem as any)._cachedCssColor !== currentBaseColor) {
(stack.hubItem as any)._cachedCssColor = currentBaseColor;
}
const cssColor = (stack.hubItem as any)._cachedCssColor;
const expectedImage = getClusterIcon(count, cssColor);
const anyExpanded = isAnyStackExpanded();
+14 -10
View File
@@ -8,16 +8,20 @@ import {
import { useStore } from "@/core/state/store";
import { createImageryProvider } from "./ImageryProviderFactory";
export function useImageryManager(viewer: CesiumViewer | null) {
export function useImageryManager(viewer: CesiumViewer | null, viewerReady: boolean) {
const baseLayerId = useStore((s) => s.mapConfig.baseLayerId);
const fallbackLayerId = useStore((s) => s.mapConfig.fallbackLayerId);
const sceneMode = useStore((s) => s.mapConfig.sceneMode);
// Resolve runtime truth:
const activeLayerId = fallbackLayerId || baseLayerId;
const currentImageryLayerRef = useRef<ImageryLayer | null>(null);
const googleTilesetRef = useRef<Cesium3DTileset | null>(null);
// 1. Manage Scene Mode (2D / 3D / Columbus)
useEffect(() => {
if (!viewer || viewer.isDestroyed()) return;
if (!viewer || !viewerReady || viewer.isDestroyed()) return;
let targetMode = SceneMode.SCENE3D;
if (sceneMode === 1) targetMode = SceneMode.COLUMBUS_VIEW;
@@ -28,17 +32,17 @@ export function useImageryManager(viewer: CesiumViewer | null) {
else if (targetMode === SceneMode.SCENE3D) viewer.scene.morphTo3D(1.0);
else if (targetMode === SceneMode.COLUMBUS_VIEW) viewer.scene.morphToColumbusView(1.0);
}
}, [viewer, sceneMode]);
}, [viewer, viewerReady, sceneMode]);
// 2. Manage Imagery Layer and Google 3D Tiles
useEffect(() => {
if (!viewer || viewer.isDestroyed()) return;
if (!viewer || !viewerReady || viewer.isDestroyed()) return;
async function updateImagery() {
if (!viewer || viewer.isDestroyed()) return;
if (!viewer || !viewerReady || viewer.isDestroyed()) return;
// Handle Google 3D Tiles specifically
const isGoogle3D = baseLayerId === "google-3d";
const isGoogle3D = activeLayerId === "google-3d";
// Toggle Google 3D Tileset visibility if it exists
// Or find it in primitives
@@ -73,7 +77,7 @@ export function useImageryManager(viewer: CesiumViewer | null) {
} else {
// Instantiate and Add new imagery provider
try {
const provider = await createImageryProvider(baseLayerId);
const provider = await createImageryProvider(activeLayerId);
const newLayer = new ImageryLayer(provider);
if (currentImageryLayerRef.current) {
@@ -84,15 +88,15 @@ export function useImageryManager(viewer: CesiumViewer | null) {
viewer.imageryLayers.add(newLayer, 0);
currentImageryLayerRef.current = newLayer;
} catch (err) {
console.error("[useImageryManager] Failed to load imagery:", baseLayerId, err);
console.error("[useImageryManager] Failed to load imagery:", activeLayerId, err);
}
}
}
updateImagery();
}, [viewer, baseLayerId]);
}, [viewer, viewerReady, baseLayerId, fallbackLayerId]);
return {
isGoogle3D: baseLayerId === "google-3d"
isGoogle3D: activeLayerId === "google-3d"
};
}
+9 -4
View File
@@ -27,6 +27,7 @@ export interface MapConfig {
shadowsEnabled: boolean;
enableLighting: boolean;
baseLayerId: string;
fallbackLayerId: string | null;
sceneMode: 1 | 2 | 3; // 1: Columbus View, 2: 2D, 3: 3D
}
@@ -61,7 +62,8 @@ export const createConfigSlice: StateCreator<AppStore, [], [], ConfigSlice> = (s
maxScreenSpaceError: 32, // Increase from 16 to 32 to significantly reduce 3D tile network requests and costs
shadowsEnabled: false,
enableLighting: false,
baseLayerId: "google-3d",
baseLayerId: (typeof window !== "undefined" && window.localStorage && typeof window.localStorage.getItem === "function") ? (localStorage.getItem("wwv_map_layer") || "google-3d") : "google-3d",
fallbackLayerId: null,
sceneMode: 3,
},
updateDataConfig: (config) =>
@@ -69,9 +71,12 @@ export const createConfigSlice: StateCreator<AppStore, [], [], ConfigSlice> = (s
dataConfig: { ...state.dataConfig, ...config },
})),
updateMapConfig: (config) =>
set((state) => ({
mapConfig: { ...state.mapConfig, ...config },
})),
set((state) => {
if (config.baseLayerId && typeof window !== "undefined" && window.localStorage && typeof window.localStorage.setItem === "function") {
localStorage.setItem("wwv_map_layer", config.baseLayerId);
}
return { mapConfig: { ...state.mapConfig, ...config } };
}),
setPollingInterval: (pluginId, intervalMs) =>
set((state) => ({
dataConfig: {
+1
View File
@@ -10,4 +10,5 @@ export const BUILT_IN_PLUGIN_IDS = [
"wildfire",
"camera",
"borders",
"osm-search",
] as const;
+1 -1
View File
@@ -55,5 +55,5 @@ export async function getDisabledPluginIds(): Promise<Set<string>> {
where: { enabled: false },
select: { pluginId: true },
});
return new Set(records.map((r) => r.pluginId));
return new Set(records.map((r: any) => r.pluginId));
}
@@ -0,0 +1,67 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { GET } from "@/app/api/earthquake/route";
const validFeature = {
id: "ak123",
type: "Feature",
geometry: { type: "Point", coordinates: [-149.9, 61.2, 12.3] },
properties: {
mag: 4.6,
place: "10km S of Somewhere",
time: 1_710_000_000_000,
},
};
describe("/api/earthquake", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it("returns a filtered feature collection from the USGS feed", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
type: "FeatureCollection",
metadata: { count: 3 },
features: [
validFeature,
{
id: "bad-1",
type: "Feature",
geometry: { type: "Point", coordinates: ["x", 2] },
properties: { time: 1_710_000_000_000 },
},
{
id: "bad-2",
type: "Feature",
geometry: { type: "Point", coordinates: [-10, 10] },
properties: {},
},
],
}),
}));
const response = await GET();
const json = await response.json();
expect(response.status).toBe(200);
expect(json.type).toBe("FeatureCollection");
expect(Array.isArray(json.features)).toBe(true);
expect(json.features).toHaveLength(1);
expect(json.features[0]).toMatchObject(validFeature);
});
it("returns 502 when the upstream feed fails", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: false,
status: 503,
}));
const response = await GET();
const json = await response.json();
expect(response.status).toBe(502);
expect(json).toEqual({ error: "Failed to fetch earthquake feed" });
});
});
@@ -0,0 +1,92 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { LayerPanel } from "@/components/panels/LayerPanel";
import { useStore } from "@/core/state/store";
import { EarthquakesPlugin } from "@worldwideview/wwv-plugin-earthquakes";
const plugin = new EarthquakesPlugin();
const pluginManagerMock = vi.hoisted(() => ({
getAllPlugins: vi.fn(),
getPlugin: vi.fn(),
getManifest: vi.fn(),
enablePlugin: vi.fn(),
disablePlugin: vi.fn(),
}));
vi.mock("@/core/hooks/useIsMobile", () => ({
useIsMobile: () => false,
}));
vi.mock("@/lib/analytics", () => ({
trackEvent: vi.fn(),
}));
vi.mock("@/components/panels/ImageryPicker", () => ({
ImageryPicker: () => <div>Imagery</div>,
}));
vi.mock("@/components/panels/FavoritesTab", () => ({
FavoritesTab: () => <div>Favorites</div>,
}));
vi.mock("@/plugins/geojson/ImportPanel", () => ({
ImportPanel: () => <div>Import</div>,
}));
vi.mock("@/components/panels/PluginsTab", () => ({
PluginsTab: () => <div>Plugins</div>,
}));
vi.mock("@/core/plugins/PluginManager", () => ({
pluginManager: pluginManagerMock,
}));
describe("Earthquakes layer in LayerPanel", () => {
beforeEach(() => {
vi.clearAllMocks();
pluginManagerMock.getAllPlugins.mockReturnValue([{
plugin,
enabled: false,
entities: [],
context: {} as never,
}]);
pluginManagerMock.getPlugin.mockReturnValue({ plugin });
pluginManagerMock.getManifest.mockReturnValue(undefined);
useStore.setState({
leftSidebarOpen: true,
openMobilePanel: null,
highlightLayerId: null,
configPanelOpen: false,
activeConfigTab: "filters",
selectedEntity: null,
entitiesByPlugin: {},
layers: {
earthquakes: {
enabled: false,
entityCount: 0,
loading: false,
},
},
});
});
it("shows Earthquakes in the layer list and toggles it on and off", () => {
const { container } = render(<LayerPanel />);
expect(screen.getByText("Data Sources")).toBeTruthy();
expect(screen.getByText("Earthquakes")).toBeTruthy();
const toggle = container.querySelector(".layer-item__toggle");
expect(toggle).not.toBeNull();
fireEvent.click(toggle!);
expect(pluginManagerMock.enablePlugin).toHaveBeenCalledWith("earthquakes");
expect(useStore.getState().layers.earthquakes.enabled).toBe(true);
fireEvent.click(toggle!);
expect(pluginManagerMock.disablePlugin).toHaveBeenCalledWith("earthquakes");
expect(useStore.getState().layers.earthquakes.enabled).toBe(false);
});
});
@@ -0,0 +1,147 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { EarthquakesPlugin } from "@worldwideview/wwv-plugin-earthquakes";
function makePlugin() {
const plugin = new EarthquakesPlugin();
return plugin;
}
describe("EarthquakesPlugin", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it("maps a GeoJSON feature into a GeoEntity", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
type: "FeatureCollection",
features: [
{
id: "us7000",
type: "Feature",
geometry: { type: "Point", coordinates: [-122.3, 37.8, 9.7] },
properties: {
mag: 4.2,
place: "Near the coast",
time: 1_710_000_000_000,
updated: 1_710_000_300_000,
status: "reviewed",
tsunami: 0,
sig: 271,
magType: "ml",
url: "https://example.com/event",
},
},
],
}),
}));
const plugin = makePlugin();
await plugin.initialize({
apiBaseUrl: "",
timeRange: { start: new Date(), end: new Date() },
onDataUpdate: () => {},
onError: () => {},
getPluginSettings: () => undefined,
isPlaybackMode: () => false,
getCurrentTime: () => new Date(),
});
const entities = await plugin.fetch({ start: new Date(), end: new Date() });
expect(entities).toHaveLength(1);
expect(entities[0]).toMatchObject({
id: "earthquakes-us7000",
pluginId: "earthquakes",
latitude: 37.8,
longitude: -122.3,
altitude: 0,
label: "M4.2",
properties: {
magnitude: 4.2,
depth: 9.7,
place: "Near the coast",
updated: 1_710_000_300_000,
status: "reviewed",
tsunami: 0,
sig: 271,
magType: "ml",
url: "https://example.com/event",
},
});
expect(entities[0].timestamp).toEqual(new Date(1_710_000_000_000));
});
it("returns an empty array on non-200 responses", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: false,
status: 502,
}));
const plugin = makePlugin();
const entities = await plugin.fetch({ start: new Date(), end: new Date() });
expect(entities).toEqual([]);
});
it("renders earthquake points with original 4-tier magnitude styling", () => {
const plugin = makePlugin();
const yellow = plugin.renderEntity({
id: "yellow",
pluginId: "earthquakes",
latitude: 0,
longitude: 0,
timestamp: new Date(),
properties: { magnitude: 4.8 },
});
const orange = plugin.renderEntity({
id: "orange",
pluginId: "earthquakes",
latitude: 0,
longitude: 0,
timestamp: new Date(),
properties: { magnitude: 5.4 },
});
const red = plugin.renderEntity({
id: "red",
pluginId: "earthquakes",
latitude: 0,
longitude: 0,
timestamp: new Date(),
properties: { magnitude: 6.0 },
});
const darkRed = plugin.renderEntity({
id: "dark-red",
pluginId: "earthquakes",
latitude: 0,
longitude: 0,
timestamp: new Date(),
properties: { magnitude: 7.2 },
});
expect(yellow).toMatchObject({
type: "point",
color: "#fcd34d",
size: 5,
outlineColor: "#000000",
outlineWidth: 1,
});
expect(orange).toMatchObject({
type: "point",
color: "#f97316",
size: 8,
});
expect(red).toMatchObject({
type: "point",
color: "#ef4444",
size: 12,
});
expect(darkRed).toMatchObject({
type: "point",
color: "#7f1d1d",
size: 16,
});
});
});
+3
View File
@@ -64,6 +64,9 @@
],
"@worldwideview/wwv-plugin-undersea-cables": [
"./packages/wwv-plugin-undersea-cables/src"
],
"@worldwideview/wwv-plugin-osm-search": [
"./packages/wwv-plugin-osm-search/src"
]
}
},
+1 -1
View File
@@ -10,6 +10,6 @@ export default defineConfig({
alias: {
'@': path.resolve(__dirname, './src'),
},
include: ['src/lib/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/core/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/plugins/**/*.{test,spec}.{js,ts,jsx,tsx}'],
include: ['src/lib/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/core/**/*.{test,spec}.{js,ts,jsx,tsx}', 'src/plugins/**/*.{test,spec}.{js,ts,jsx,tsx}', 'packages/**/*.{test,spec}.{js,ts,jsx,tsx}'],
},
});