Compare commits

...
Author SHA1 Message Date
Antigravity AI 433004598d Merge branch 'fix/lint-cleanups'
# Conflicts:
#	eslint.config.mjs
#	package.json
2026-05-17 22:08:13 +12:00
Antigravity AI 02d8355a83 feat: add inverted app icon and update lockfile dependencies 2026-05-17 22:05:48 +12:00
Silvertakana 89010b2425 feat(ui): Bottom Panel System and E2E Testing (#147)
* test(bottom-panel): add e2e resize testing and data-testid

* test(e2e): fix playwright drag events skipping React state
2026-05-17 20:14:18 +12:00
Antigravity AI 0ff1d23e4a chore(lint): clean up legacy linting errors and hallucinated rules 2026-05-17 20:04:13 +12:00
Silvertakanaandsnyk-bot fd29865e7a [Snyk] Security upgrade ws from 8.20.0 to 8.20.1 (#151)
* fix: package.json to reduce vulnerabilities

The following vulnerabilities are fixed with an upgrade:
- https://snyk.io/vuln/SNYK-JS-WS-16722635

* fix: update pnpm-lock.yaml for ws dependency bump and bump version to 2.15.11

---------

Co-authored-by: snyk-bot <[email protected]>
2026-05-17 19:54:03 +12:00
Silvertakana 42564b537f ci(playwright): Add multi-browser test matrix (#150)
* ci(playwright): Add multi-browser test matrix (Patch)

* fix(cesium): Disable MSAA in Firefox to prevent readPixels crash (Patch)
2026-05-17 19:14:54 +12:00
Antigravity AI 598e00171c fix(cesium): Disable MSAA in Firefox to prevent readPixels crash (Patch) 2026-05-17 18:35:09 +12:00
devangpratap b849bb2b4d feat(api): add ISS Tracker proxy routes (#143)
* feat(api): add ISS position proxy route

Server-side proxy to the Where the ISS at? API (NORAD 25544).
Returns current latitude, longitude, altitude, velocity, visibility,
and footprint with 10-second revalidation and input validation.

Closes #8

* test(iss): add unit tests for ISS position route

Covers: valid response, field stripping, upstream failure,
invalid coordinates, and network error scenarios.

* feat(api): add ISS TLE orbit data route

Exposes the latest Two-Line Element set for NORAD 25544 via
/api/iss/tle. TLE data enables client-side orbit prediction
with satellite.js. Cached for 1 hour since TLEs update infrequently.

* test(iss): add unit tests for ISS TLE route

Covers: valid TLE response, field normalization (snake_case to
camelCase), upstream failure, empty TLE lines, and network errors.

* feat(api): add ISS historical positions route with tests

Batch endpoint at /api/iss/positions?timestamps=t1,t2,... returns
multiple past positions for orbit trail rendering. Validates input
(max 10 timestamps, numeric only), filters invalid upstream data,
and strips extraneous fields. Includes 7 test cases covering
happy path, validation, overflow, and upstream failure.

* fix(iss): harden validation and add missing edge case tests

- Remove unused TypeScript interfaces from route validators,
  align with earthquake route's bare validation style
- Add velocity validation to positions route (was missing,
  inconsistent with main route)
- Add null body tests for position and TLE routes
- Add empty string timestamps test for positions route
- Add NaN velocity rejection test for positions route
- Add network error test for positions route (was missing)
2026-05-17 17:36:51 +12:00
SilvertakanaandCopilot Autofix powered by AI fc7dd02ee2 refactor(core): harden typescript and fix linting violations (#146)
* chore(merge): resolve conflicts, fix mockWs error, and apply refactor standards

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fix(ci): Stabilize github actions and resolve test failures

- fix(tests): update WsClient mock to use standard function for Vitest constructor compatibility

- fix(db): correct PrismaClient import path to use generated output directory

- fix(e2e): add predev database boot step to playwright CI workflow

- chore: sync pnpm-lock.yaml after merge conflict resolution

* refactor(plugins): decouple GeoJSON plugin and implement data bus lifecycle

- feat(sdk): [Minor] Added dynamicPluginCreate, dynamicPluginRemove, and pluginUnregistered to DataBusEvents.

- feat(core): [Minor] Implemented unregisterPlugin in PluginManager.ts for automated IndexedDB caching cleanup and polling teardown.

- feat(core): [Minor] Added removeLayer to layersSlice.ts to support safe removal of plugin states.

- refactor(plugins): [Patch] Refactored useGeoJsonImport.ts and ImportedLayerList.tsx to decouple from direct manager imports, utilizing DataBus for lifecycle events.

- refactor(core): [Patch] Added pluginUnregistered listener to DataBusSubscriber.tsx to handle state and cache cleanup synchronously via event.

* fix(types): resolve PluginManager type errors

* refactor(core): decouple PluginManager and fix rendering invariants

- refactor(core): Replace Zustand mutations in PluginManager with DataBus events (Patch)
- refactor(sdk): Add layerLoadingChanged, pluginError, pluginUnregistered to DataBusEvents (Patch)
- refactor(ui): Subscribe to new DataBus events in DataBusSubscriber (Patch)
- fix(plugins): Remove size from BaseAviationPlugin to fix model rendering clipping (Patch)
- fix(plugins): Migrate BaseIncidentPlugin from size to iconScale to fix billboard clipping (Patch)

* chore: resolve lockfile conflict

* fix: restore BottomPanelManager in AppShell and fix vitest config

* fix(layout): restore bottom panel positioning and transition styling

This commit corrects the missing bottom panel issue by resolving CSS aggregation errors and fixing transition logic. The version is bumped to 2.15.5.

* refactor(core): harden typescript and fix linting violations

This commit addresses the remaining any types and linting errors across the core engine.

* fix(eslint): resolve react-hook immutability and cascading render violations

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-17 17:36:33 +12:00
Antigravity AI caf1638fdc ci(playwright): Add multi-browser test matrix (Patch) 2026-05-17 15:51:48 +12:00
SilvertakanaandCopilot Autofix powered by AI ad3c7845a5 fix: restore bottom panel system and resolve E2E test failure (#145)
* chore(merge): resolve conflicts, fix mockWs error, and apply refactor standards

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fix(ci): Stabilize github actions and resolve test failures

- fix(tests): update WsClient mock to use standard function for Vitest constructor compatibility

- fix(db): correct PrismaClient import path to use generated output directory

- fix(e2e): add predev database boot step to playwright CI workflow

- chore: sync pnpm-lock.yaml after merge conflict resolution

* refactor(plugins): decouple GeoJSON plugin and implement data bus lifecycle

- feat(sdk): [Minor] Added dynamicPluginCreate, dynamicPluginRemove, and pluginUnregistered to DataBusEvents.

- feat(core): [Minor] Implemented unregisterPlugin in PluginManager.ts for automated IndexedDB caching cleanup and polling teardown.

- feat(core): [Minor] Added removeLayer to layersSlice.ts to support safe removal of plugin states.

- refactor(plugins): [Patch] Refactored useGeoJsonImport.ts and ImportedLayerList.tsx to decouple from direct manager imports, utilizing DataBus for lifecycle events.

- refactor(core): [Patch] Added pluginUnregistered listener to DataBusSubscriber.tsx to handle state and cache cleanup synchronously via event.

* fix(types): resolve PluginManager type errors

* refactor(core): decouple PluginManager and fix rendering invariants

- refactor(core): Replace Zustand mutations in PluginManager with DataBus events (Patch)
- refactor(sdk): Add layerLoadingChanged, pluginError, pluginUnregistered to DataBusEvents (Patch)
- refactor(ui): Subscribe to new DataBus events in DataBusSubscriber (Patch)
- fix(plugins): Remove size from BaseAviationPlugin to fix model rendering clipping (Patch)
- fix(plugins): Migrate BaseIncidentPlugin from size to iconScale to fix billboard clipping (Patch)

* chore: resolve lockfile conflict

* fix: restore BottomPanelManager in AppShell and fix vitest config

* fix(layout): restore bottom panel positioning and transition styling

This commit corrects the missing bottom panel issue by resolving CSS aggregation errors and fixing transition logic. The version is bumped to 2.15.5.

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-16 15:33:43 +12:00
Silvertakana 339bf6c0f3 fix(plugins): ensure plugin fetch uses HTTP scheme (#140)
* fix(plugin-manager): downgrade non-fatal 'Failed to fetch' errors to warn, remove polling re-throw

* fix(codeql): resolve format string vulnerability in console logging

* fix(ci): restore playwright dependencies and configure tsconfig properly

* fix(plugins): ensure plugin fetch uses HTTP scheme instead of WSS
2026-05-16 13:03:50 +12:00
SilvertakanaandCopilot Autofix powered by AI 16c82c9184 refactor(lint): address React 19 hook purity and immutability violations (#136)
* chore(merge): resolve conflicts, fix mockWs error, and apply refactor standards

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Potential fix for pull request finding 'CodeQL / Incomplete URL substring sanitization'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fix(ci): Stabilize github actions and resolve test failures

- fix(tests): update WsClient mock to use standard function for Vitest constructor compatibility

- fix(db): correct PrismaClient import path to use generated output directory

- fix(e2e): add predev database boot step to playwright CI workflow

- chore: sync pnpm-lock.yaml after merge conflict resolution

* refactor(plugins): decouple GeoJSON plugin and implement data bus lifecycle

- feat(sdk): [Minor] Added dynamicPluginCreate, dynamicPluginRemove, and pluginUnregistered to DataBusEvents.

- feat(core): [Minor] Implemented unregisterPlugin in PluginManager.ts for automated IndexedDB caching cleanup and polling teardown.

- feat(core): [Minor] Added removeLayer to layersSlice.ts to support safe removal of plugin states.

- refactor(plugins): [Patch] Refactored useGeoJsonImport.ts and ImportedLayerList.tsx to decouple from direct manager imports, utilizing DataBus for lifecycle events.

- refactor(core): [Patch] Added pluginUnregistered listener to DataBusSubscriber.tsx to handle state and cache cleanup synchronously via event.

* fix(types): resolve PluginManager type errors

* refactor(core): decouple PluginManager and fix rendering invariants

- refactor(core): Replace Zustand mutations in PluginManager with DataBus events (Patch)
- refactor(sdk): Add layerLoadingChanged, pluginError, pluginUnregistered to DataBusEvents (Patch)
- refactor(ui): Subscribe to new DataBus events in DataBusSubscriber (Patch)
- fix(plugins): Remove size from BaseAviationPlugin to fix model rendering clipping (Patch)
- fix(plugins): Migrate BaseIncidentPlugin from size to iconScale to fix billboard clipping (Patch)

* chore: resolve lockfile conflict

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-16 13:03:05 +12:00
Silvertakana ad324a6592 feat(ui): bottom panel plugin architecture testing (#141)
* test(ui): implement playwright end-to-end testing for bottom panel architecture

* docs(e2e): improve playwright testing rules and create mock plugin guide
2026-05-16 12:29:09 +12:00
devangpratap 0a51e198d7 feat(globe): add OSM 3D Buildings overlay for non-Google imagery layers (#135)
Loads Cesium OSM Buildings (Ion asset 96188) as a 3DTileset when the
active base layer is not Google Photorealistic 3D Tiles. Buildings
only render in 3D scene mode and are automatically removed when
switching to Google 3D, 2D, or Columbus View.

Adds a "3D Buildings" toggle in Graphics Settings, persisted via
the existing wwv_graphics cookie.
2026-05-16 12:06:30 +12:00
Silvertakana 1d6381182e fix(plugin-manager): downgrade non-fatal 'Failed to fetch' errors to warn (#139)
* fix(plugin-manager): downgrade non-fatal 'Failed to fetch' errors to warn, remove polling re-throw

* fix(codeql): resolve format string vulnerability in console logging

* fix(ci): restore playwright dependencies and configure tsconfig properly
2026-05-16 11:39:41 +12:00
Antigravity AI beb295445f fix(data-engine): properly respect NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL in getLocalWsUrl and align port with engineManifest 2026-05-15 22:59:47 +12:00
Silvertakana dd62116351 feat(ui): bottom panel system refinements and visual polish (#137)
- Major: Add DESIGN.md source-of-truth document

- Minor: Update Bottom Panel plugin SDK to include 'enabled' prop

- Fix: Resolve React 19 hydration error in root layout script tag

- Fix: Refine bottom panel transparency, contrast, and resize clamps

- Fix: Transition pill styling for empty panel states
2026-05-15 21:31:39 +12:00
GodisDeadxandAntigravity AI d675d91441 Fix(Plugins): Fix sync-local-plugins looking in wrong location (#102)
Co-authored-by: Antigravity AI <[email protected]>
2026-05-15 15:15:38 +12:00
SilvertakanaandCopilot Autofix powered by AI fb07195ec2 feat(testing): stabilize Playwright E2E Tests infrastructure (#134)
* feat(testing): add Playwright E2E infrastructure and stabilize test suite

- Add Playwright E2E configuration and ui-navigation / plugin-system tests
- Add GitHub Actions workflow for Playwright CI tests
- Add test helpers and fixtures (e2e-mock-plugin)
- fix(testing): resolve UnverifiedPluginBatchDialog UI blocking issue in E2E tests
- fix(testing): limit Playwright to 2 workers locally to avoid Next.js/Prisma exhaustion
- fix(api): replace deprecated processAuthCodeResponse with authorizationCodeGrant
- test(ui): add data-testid to PanelToggleArrows and AppShell

* Potential fix for pull request finding 'CodeQL / Workflow does not contain permissions'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fix(ci): restrict GITHUB_TOKEN permissions to read contents

* docs(e2e): document Playwright infrastructure and mock plugin lifecycle

* fix(e2e): explicitly load .env in teardown and fix dev command pathing

* fix(ci): resolve playwright environment setup and database initialization

Changes:
- Patch: Added pnpm run setup step to .github/workflows/playwright.yml to generate .env in CI
- Patch: Added explicit loadEnv() helper to 	ests/global.setup.ts and 	ests/global.teardown.ts to ensure database credentials are fresh
- Patch: Hardened scripts/safe-db-push.mjs to detect missing DATABASE_URL and explicitly prompt for pnpm run setup rather than assuming production
- Patch: Updated scripts/dev.mjs to execute pnpm exec next dev instead of raw
ext dev to resolve pathing issues
- Patch: Bumped version in package.json to 2.14.4

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-05-15 14:57:37 +12:00
devangpratap 1838f1a5cd fix(setup): remove broken legacy migration banner from setup page (#130)
The setup page unconditionally displays a banner telling users to run
scripts/migrate-legacy.mjs, but that script does not exist in the repo
or the Docker image. Every user hitting /setup sees a broken command,
including fresh installs with no legacy data.

The docker-entrypoint.sh already detects prisma/dev.db and logs a
migration warning for actual upgraders.

Closes #129
2026-05-15 13:20:27 +12:00
278 changed files with 9238 additions and 4976 deletions

No files matched your search

+14
View File
@@ -39,6 +39,17 @@ Frontend runs at `http://localhost:3000`.
- **Type-Level Contract Testing**: When defining shared TypeScript interfaces/contracts (e.g., in `wwv-plugin-sdk`), you MUST use `expectTypeOf` from `vitest` to assert the actual contract shapes at compile-time instead of writing literal-value identity runtime assertions. You must also enforce `@ts-expect-error` negative type tests to ensure missing or invalid fields trigger compilation errors.
- **Key test files**: `rateLimit.test.ts`, `edition.test.ts`, `demoAdmin.test.ts`, `DeclarativePlugin.test.ts`, `cors.test.ts`, `repository.test.ts`, `marketplaceToken.test.ts`
### E2E Testing (Playwright)
WorldWideView uses Playwright for End-to-End browser testing to verify the complete UI integration including NextAuth.
- **Run**: `pnpm run test:e2e` (Ensure your database is running before executing)
- **Auth Bypass**: Playwright uses a `global.setup.ts` to directly insert a test user into the database and simulate a UI login to capture a `storageState.json` cookie file. This allows all tests to run pre-authenticated without bypassing production security logic.
- **Database Access in Setup**: Because Playwright setup scripts run in a vanilla Node context, importing Next.js backend utilities like `src/lib/db.ts` will crash with `next/headers` resolution errors. You MUST instantiate `PrismaClient` directly using `@prisma/adapter-pg` in any Playwright `setup` or `teardown` scripts.
- **Component Synchronization**: Do not use arbitrary timeouts. Tests MUST wait for the application boot sequence to finish by waiting for the `[data-testid="app-ready"]` marker on the `AppShell` to be attached.
- **Stable Selectors**: Always use `data-testid` properties (e.g. `data-testid="panel-toggle-left"`) for interacting with UI components in E2E tests rather than fragile CSS classes or dynamic text.
- **Worktree Port Conflicts**: If you are testing in a git worktree, configure `playwright.config.ts` to spawn the `webServer` on an alternative port (e.g. `3001`) to avoid colliding with other running worktrees.
## Security Headers
Configured in `next.config.ts` `headers()`:
@@ -248,6 +259,9 @@ The production Coolify instance runs on a local server at `192.168.68.64`. Direc
1. Push to `silvertakana/worldwideview`
2. Coolify webhook triggers → automated BuildKit deployment on the host server.
**GitHub Actions Workflows:**
- **Minimal Permissions:** CodeQL and GitHub security best practices dictate that `GITHUB_TOKEN` permissions should always be explicitly constrained. When creating or modifying `.github/workflows/*.yml` files, you MUST always include an explicit `permissions` block (e.g., `permissions: { contents: read }` or similar required scopes) at the top level or job level to adhere to the principle of least privilege.
**Coolify Deployment Rules & Gotchas (The "Redis 500k" Rule):**
- **Coolify Pulls from GitHub:** Coolify does *not* deploy your local workspace files. It strictly clones the repository from GitHub.
- **Push Before You Deploy:** If you make a critical infrastructure or optimization fix locally (e.g., swapping a massive `HSET` pipeline for a compressed 5-min throttled `setLiveSnapshot`), you **must** `git commit` and `git push` those changes to the `main` branch before triggering a Coolify deployment.
+46
View File
@@ -0,0 +1,46 @@
---
trigger: testing
description: Guidelines and architecture for the Playwright End-to-End (E2E) testing infrastructure.
globs:
- "tests/**"
- "public/e2e-fixtures/**"
- "playwright.config.ts"
---
# E2E Testing Infrastructure
The WorldWideView project uses **Playwright** for end-to-end (E2E) testing. This document outlines the boundaries, architectural decisions, and conventions required when authoring or modifying E2E tests.
## 1. Resource Constraints & Parallelism
- **Worker Limits:** The Playwright configuration (`playwright.config.ts`) is strictly limited to a maximum of **2 workers**.
- **Reasoning:** Running Next.js compilation alongside a heavy Prisma connection pool inside multiple parallel test workers will lead to database connection exhaustion and resource contention on CI and local environments. Do not increase the worker count beyond 2 without careful consideration of the database pool limits.
## 2. Test User Lifecycle
E2E tests require an authenticated user to access core application features. We manage this test user securely to ensure the environment stays pristine:
- **Setup (`tests/global.setup.ts`):** Before tests run, the global setup script defensively deletes any existing test user (`[email protected]`) and creates a fresh instance with the `ADMIN` role. It then performs a UI login to capture the authentication state, which is shared across all test files.
- **Teardown (`tests/global.teardown.ts`):** After the entire test suite completes (regardless of success or failure), the global teardown script runs and completely purges the test user from the database.
- **Safety:** Do not use `[email protected]` for manual testing. It is volatile and intended exclusively for the CI test runner.
## 3. UI Interaction Conventions
- **Strict Selector Usage**: ALWAYS use `data-testid` selectors (e.g., `getByTestId('panel-toggle-left')`) for DOM interactions. **NEVER rely on CSS classes** (like `.layer-item__toggle` or `.dock-btn`) or deep DOM structures, as these are brittle and break during design refactors. If a `data-testid` is missing from an element you need to test, you MUST add it to the React component source code first.
- **Dialog Interception:** WorldWideView relies on heavy frontend plugin discovery and dynamic rendering. For example, the `UnverifiedPluginBatchDialog` may unexpectedly appear and block UI interactions in a fresh browser context.
- *Mitigation:* Ensure your test suites either explicitly handle these dialogs (e.g., in a `beforeEach` block) or inject mock plugins that bypass the verification flow entirely.
## 4. Mock Plugins
- **Data Interface Strictness**: WorldWideView's `PluginManager` is extremely strict. **ALL mock plugins MUST implement `getPollingInterval`, `fetch`, and `renderEntity`**, even if they are purely UI-focused (like a bottom-panel plugin). Failure to implement these will crash the renderer.
- **Capabilities**: If your mock UI plugin needs to be manually activated by the user, ensure its manifest includes the `"ui:sidebar"` capability so it appears in the layer list.
- **Injection:** We inject safe, deterministic mock plugins into the database during the `global.setup.ts` phase to test the core rendering pipeline without relying on external APIs. Ensure your mock plugin is registered in the setup and teardown cleanup arrays.
- **Location:** Mock plugin configurations and manifests are stored in `public/e2e-fixtures/`. When modifying the rendering engine, ensure you also update the mock plugin (`public/e2e-fixtures/mock-plugin.js`) to reflect any changes in the Plugin SDK capabilities.
## 5. Security Permissions
- When integrating Playwright tests into GitHub Actions (e.g., `.github/workflows/playwright.yml`), you MUST include an explicit permissions block (e.g., `permissions: { contents: read }`) to adhere to CodeQL and least-privilege scoping rules.
> [!WARNING]
> If you encounter flaky tests or `ECONNREFUSED` errors during Playwright runs, check if the local Next.js dev server or the Docker engine stack is competing for ports (e.g., port 5432 or 3000). Ensure `pnpm run dev:backends` is running and stable before launching the test suite.
## 6. Execution Environment & Tooling Limitations
The development environment operates on **Windows PowerShell**. Agents MUST adhere to the following strict execution rules when running commands or interacting with the testing infrastructure:
- **No Double Ampersands (`&&`)**: Standard Windows PowerShell (prior to v7) does not support the `&&` operator. Use the semicolon (`;`) to chain commands, or rely on `pnpm` package.json scripts which manage cross-platform execution properly.
- **Avoid Non-existent Database CLI Commands**: Do not attempt to use raw `pg` or `psql` commands unless explicitly verified to exist in the path. Instead, use Prisma (`npx prisma studio`, `npx prisma migrate`) or Docker executions (`docker exec -it wwv-db psql ...`) for database interactions.
- **Creating Test Plugins**: You will repeatedly need to create mock test plugins for verifying different platform features (e.g. bottom-panel resizing, new UI widgets). When doing so, you MUST review this `e2e-testing.md` file to ensure compliance with the `PluginManager` strict interface rules (implementing `getPollingInterval`, `fetch`, and `renderEntity`).
@@ -0,0 +1,72 @@
---
name: playwright-testing
description: Use when creating or modifying Playwright end-to-end tests, especially when injecting mock plugins to test platform features.
---
# Playwright E2E Testing & Mock Plugin Guide
When you are tasked with testing a new feature or plugin in WorldWideView using Playwright, you must use this skill to ensure you follow the strict architecture rules of the platform.
## 1. Mock Plugin Requirements
When creating a mock plugin (e.g., `public/e2e-fixtures/my-mock-plugin.js`) to test a specific UI feature, **you MUST implement the full Data Plugin interface**.
WorldWideView's `PluginManager` throws fatal runtime errors if a plugin is missing core data fetching methods, even if your plugin only tests a UI component like a bottom panel.
**Required Methods for EVERY Mock Plugin:**
```javascript
export default {
id: "my-mock-plugin",
name: "My Mock Plugin",
// ...
// MUST BE INCLUDED:
fetch: async (timeRange) => { return []; },
getPollingInterval: () => { return 60000; },
getLayerConfig: () => { return { color: "#FFF", clusterEnabled: false, clusterDistance: 50 }; },
renderEntity: (entity) => { return { type: "point", color: "#FFF", size: 5 }; },
// Your UI testing component (e.g., Sidebar, Bottom Panel)
getBottomPanelComponent: () => { ... }
}
```
## 2. Mock Plugin Manifest Capabilities
If your mock plugin needs to be toggled by the user in the Layers list, you MUST include the `"ui:sidebar"` capability in its `manifest.json`.
```json
{
"capabilities": ["ui:bottom-panel", "ui:sidebar"],
"extends": ["sidebar"]
}
```
## 3. Database Injection
The frontend reads plugins from the database. You MUST inject your mock plugin during `tests/global.setup.ts` using Prisma:
```typescript
const manifestPath = path.join(process.cwd(), 'public', 'e2e-fixtures', 'my-mock-plugin-manifest.json');
const manifestStr = fs.readFileSync(manifestPath, 'utf-8');
await prisma.installedPlugin.create({
data: {
pluginId: 'my-mock-plugin',
version: '1.0.0',
config: manifestStr,
enabled: true
}
});
```
Make sure to add your new mock plugin ID to the cleanup logic in `global.setup.ts` as well:
```typescript
await prisma.installedPlugin.deleteMany({
where: { pluginId: { in: ['e2e-mock-plugin', 'my-mock-plugin'] } }
});
```
## 4. UI Selectors
**DO NOT use CSS classes for your locators.** CSS classes change frequently (e.g., `.dock-btn`, `.layer-item__toggle`).
You MUST either:
1. Add explicit `data-testid` attributes to the React components you are testing.
2. Use stable accessibility locators (e.g., `getByRole('button', { name: /Text/ })`).
## 5. Execution Environment
- Ensure `pnpm run dev:backends` is running before you execute tests locally.
- Run tests using `pnpm run test:e2e` or `npx playwright test tests/your-test.spec.ts`.
- **PowerShell Warning**: Remember you are running in Windows PowerShell. Do NOT chain commands with `&&`. Use `;` instead.
+51
View File
@@ -0,0 +1,51 @@
name: Playwright Tests
on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]
permissions:
contents: read
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: 9.15.4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Install Playwright Browsers
run: pnpm exec playwright install --with-deps
- name: Run Project Setup
run: pnpm run setup
- name: Boot Database
run: |
docker network create coolify || true
pnpm run predev
- name: Run Playwright tests
run: pnpm test:e2e --project=${{ matrix.browser }}
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-report-${{ matrix.browser }}
path: playwright-report/
retention-days: 30
+6 -1
View File
@@ -127,4 +127,9 @@ skills-lock.json
/wwv-seeders/
/wwv-seeders-private/
/wwv-test/
worldwideview.code-workspace
worldwideview.code-workspace
# Playwright
/playwright-report/
/test-results/
/playwright/.auth/
+1
View File
@@ -155,6 +155,7 @@ Read the relevant rule file when working in that domain:
| `continuous-improvement` | When to create/update rules, skills, or workflows | `.agents/rules/continuous-improvement.md` |
| `context-and-memory` | How to orient and maintain project context between sessions | `.agents/rules/context-and-memory.md` |
| `troubleshooting-and-debugging` | Resolving plugin latency, namespace collisions, or deployment issues | `.agents/rules/troubleshooting-and-debugging.md` |
| `e2e-testing` | Guidelines and architecture for the Playwright End-to-End (E2E) testing infrastructure | `.agents/rules/e2e-testing.md` |
---
+51
View File
@@ -0,0 +1,51 @@
# Design System: WorldWideView
**Project ID:** local-worldwideview-app
## 1. Visual Theme & Atmosphere
The WorldWideView platform employs an **"Airy, High-Tech, and Geospatial-Focused"** aesthetic. The design philosophy centers around "Glassmorphism Pro Max"—keeping the user's primary focus on the rich, underlying 3D globe visualization while providing highly legible, structured, and floating Heads-Up Display (HUD) elements.
The mood is utilitarian yet premium, heavily relying on dense background blurring, delicate inner borders, and vibrant glowing accent states to establish depth, interactivity, and a sense of "live" intelligence.
## 2. Color Palette & Roles
WorldWideView operates using a multi-theme architecture (Default Dark, Pure Black, Legacy OLED, and Light). The core semantic roles for the **Default Dark Theme** are outlined below:
* **Obsidian Canvas** (`#171717`) - `--bg-primary`: The foundational layer behind the application shell and globe.
* **Translucent Slate Glass** (`rgba(38, 38, 38, 0.85)`) - `--bg-glass`: The primary background for floating HUD panels, sidebars, and dialogs. Provides a frosted glass effect that allows the map to bleed through.
* **Frost White** (`#ffffff`) - `--text-primary`: Primary typography for headers, active states, and high-emphasis data.
* **Muted Ash** (`#a3a3a3`) - `--text-muted`: Secondary typography used for labels, subtitles, and inactive states to establish visual hierarchy.
* **Gossamer Edge** (`rgba(255, 255, 255, 0.15)`) - `--border-subtle`: Defines the subtle, crisp edges of glass panels, dividers, and default button states.
* **Starlight Cyan** (`#ffffff` / *Legacy:* `#22d3ee`) - `--accent-cyan`: Used for primary actions, active tabs, timeline scrubbers, and play buttons. Often paired with a diffuse glow (`0 0 24px rgba(255, 255, 255, 0.15)`) for emphasis and technical flair.
* **Telemetry Green** (`#22c55e`) - `--accent-green`: Used for live status indicators, pulsing connectivity badges, and positive data deltas.
* **Warning Amber** (`#f59e0b`) - `--accent-amber`: Used for warnings, "Alpha" badges, or unavailable data states.
## 3. Typography Rules
The system uses a dual-font strategy to balance clean user interfaces with technical precision.
* **UI Font (Inter):** Used for all general interface elements, headers, and buttons.
* Headers and brand elements use a bold `600/700` weight with tight letter-spacing (`-0.02em`) for a sleek, modern feel.
* Section titles, keys, and subtitles use a very small size (`11px`), a medium weight, uppercase transformation, and wide letter-spacing (`0.05em` to `0.1em`) to mimic aerospace or military HUD interfaces.
* **Monospace Font (JetBrains Mono):** Used strictly for data values, coordinates, telemetry, and exact timestamps (`11px` to `12px`). Ensures tabular alignment, clear distinction between similar characters (e.g., 0 and O), and technical precision.
## 4. Component Stylings
* **Glass Panels (Cards/Containers):**
* **Shape:** Generously rounded corners (`16px` / `var(--radius-lg)`).
* **Surface:** Dense frosted background blur (`24px`).
* **Depth:** Elevated significantly above the map using a dual-layered drop shadow (`0 8px 32px rgba(0, 0, 0, 0.4)` combined with `0 2px 8px rgba(0, 0, 0, 0.2)`). Features a crisp inner border (`inset 0 1px 1px rgba(255, 255, 255, 0.1)`) to simulate physical glass thickness.
* **Buttons:**
* **Shape:** Subtly rounded corners (`12px` / `var(--radius-md)`) with a standard height of `36px`.
* **Surface:** Translucent glass background with a subtle border.
* **Behavior:** Smooth, spring-based transitions. On hover, the background brightens, the element scales up/translates slightly (`translateY(-1px)`), and primary buttons emit a vivid neon glow. On click (active), buttons physically depress (`scale(0.97)`).
* **Tabs & Selectors:**
* **Shape:** Softly rounded (`8px` / `var(--radius-sm)`).
* **Surface:** Clean, flat, and transparent by default.
* **Behavior:** Transitions to a soft glass hover or active state. Active tabs use a highlighted background (`rgba(var(--accent-rgb), 0.1)`) and bright cyan text with increased font weight.
* **Timeline Scrubber:**
* **Track:** Slender `4px` tall track with softly rounded edges.
* **Handle:** A circular `14px` handle that emits a cyan glow, expanding dynamically on hover (`scale(1.2)`).
## 5. Layout Principles
* **Absolute Overlays:** The UI does not push the map; instead, it floats over a full-screen, `z-index: 0` globe canvas. Elements are anchored to the edges (Header to top, Sidebar to sides, Timeline to bottom).
* **Strict 4/8dp Rhythm:** All spacing adheres to an 8-point grid base (`4px`, `8px`, `12px`, `16px`, `24px`, `32px`, `48px`).
* **Dynamic Containment:** Sidebars and bottom panels push each other dynamically to prevent overlap and optimize map visibility (e.g., when the bottom panel opens, sidebars slide upward).
* **Whitespace & Density:** Panels use a dense `16px` padding globally to maximize the amount of intelligence data visible while maintaining clear breathing room between individual data rows. Scrollable areas hide scrollbars until hovered to maintain the clean glass aesthetic.
+7 -9
View File
@@ -1,7 +1,7 @@
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import nextTypeScript from "eslint-config-next/typescript";
export default [
const config = [
{
ignores: [
"node_modules/**",
@@ -16,6 +16,8 @@ export default [
"local-seeders/**",
".agents/**",
".claude/**",
".gemini/**",
"*.cjs",
],
},
...nextCoreWebVitals,
@@ -33,20 +35,16 @@ export default [
// Pre-existing — flagged in the original code review (#96):
"@typescript-eslint/no-explicit-any": "warn",
"no-console": "warn",
"no-console": "off",
// React 19 hook-purity rules from eslint-plugin-react-hooks 7+:
"react-hooks/purity": "warn",
"react-hooks/refs": "warn",
"react-hooks/set-state-in-effect": "warn",
"react-hooks/immutability": "warn",
"react-hooks/static-components": "warn",
// (These were previously hallucinated or require extra plugins)
// Misc one-offs across the codebase:
"react/no-unescaped-entities": "warn",
"@typescript-eslint/ban-ts-comment": "warn",
"@next/next/no-assign-module-variable": "warn",
"prefer-const": "warn",
},
},
];
export default config;
-2
View File
@@ -93,6 +93,4 @@ const nextConfig: NextConfig = {
},
};
import { withSentryConfig } from "@sentry/nextjs";
export default nextConfig;
+14 -2
View File
@@ -1,7 +1,7 @@
{
"name": "worldwideview",
"version": "2.14.1",
"private": true,
"version": "2.15.12",
"private": true,
"type": "module",
"packageManager": "[email protected]",
"scripts": {
@@ -18,6 +18,7 @@
"build": "next build --webpack",
"start": "next start",
"test": "vitest run",
"test:e2e": "playwright test",
"test:mutate": "stryker run",
"lint": "eslint .",
"db:reset": "npx prisma migrate reset --force",
@@ -60,6 +61,9 @@
"zustand": "^5.0.13"
},
"devDependencies": {
"@eslint/compat": "^2.1.0",
"@eslint/eslintrc": "^3.3.5",
"@playwright/test": "^1.60.0",
"@stryker-mutator/core": "^9.6.1",
"@stryker-mutator/vitest-runner": "^9.6.1",
"@testing-library/dom": "^10.4.1",
@@ -70,12 +74,20 @@
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/ws": "^8.18.1",
"@typescript-eslint/eslint-plugin": "^8.59.3",
"@typescript-eslint/parser": "^8.59.3",
"@vitejs/plugin-react": "^5.1.4",
"@vitest/coverage-v8": "4.1.6",
"concurrently": "^9.2.1",
"copy-webpack-plugin": "^14.0.0",
"eslint": "^9",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^18.0.0",
"eslint-config-next": "^16.2.6",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"fast-check": "^4.8.0",
"jsdom": "^28.1.0",
"rollup-plugin-external-globals": "^0.13.0",
+1
View File
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { Command } from 'commander';
import { saveConfig } from '../utils/config.js';
+1
View File
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { Command } from 'commander';
import fs from 'fs';
import path from 'path';
+3 -2
View File
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { Command } from 'commander';
import { execSync } from 'child_process';
import path from 'path';
@@ -50,7 +51,7 @@ export const publishCommand = new Command('publish')
process.exit(1);
}
let originalName = pkgContent.name;
const originalName = pkgContent.name;
let publishedName = originalName;
// Determine organization
@@ -66,7 +67,7 @@ export const publishCommand = new Command('publish')
try {
const whoami = execSync('npm whoami', { stdio: 'pipe' }).toString().trim();
targetOrg = whoami;
} catch (e) {
} catch (_e) {
// Not logged in or errored, ignore
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-lib-aviation",
"version": "1.0.1",
"version": "1.0.2",
"description": "Shared abstract base classes for WorldWideView aviation plugins (commercial, military, specialized)",
"main": "src/index.ts",
"types": "src/index.ts",
-1
View File
@@ -69,7 +69,6 @@ export abstract class BaseAviationPlugin implements WorldPlugin {
return {
type: "model",
iconUrl: this.iconUrl,
size: isAirborne ? 8 : 5,
modelUrl: this.modelUrl,
modelScale: 2.56,
modelMinPixelSize: 16,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-lib-incidents",
"version": "1.0.1",
"version": "1.0.2",
"description": "Shared abstract base classes for WorldWideView incident plugins (earthquakes, wildfires, conflicts)",
"main": "src/index.ts",
"types": "src/index.ts",
+1 -3
View File
@@ -75,9 +75,7 @@ export abstract class BaseIncidentPlugin implements WorldPlugin {
type: "billboard",
iconUrl: this.iconUrls[cacheKey],
color,
size,
outlineColor: "#000000",
outlineWidth: 1,
iconScale: size / 30,
labelText: entity.label || undefined,
labelFont: "11px JetBrains Mono, monospace" // Adds optional label standard
};
+55
View File
@@ -1,3 +1,10 @@
/**
* @file index.ts
* @description Core SDK for WorldWideView plugin development.
* Defines the foundational types, interfaces, and utilities required
* to build data seeders, visualizers, and UI extensions.
* @module @worldwideview/wwv-plugin-sdk
*/
import type { ComponentType } from "react";
/** Standard SVG icon size (px) used by createSvgIconUrl when no size is given. */
export declare const DEFAULT_ICON_SIZE = 32;
@@ -24,16 +31,30 @@ export interface TimeRange {
end: Date;
}
export type TimeWindow = "1h" | "6h" | "24h" | "48h" | "7d";
/**
* @interface GeoEntity
* @description The primary data primitive representing a geospatial object.
*/
export interface GeoEntity {
/** Globally unique identifier for this specific entity instance. */
id: string;
/** The ID of the plugin that owns this entity. */
pluginId: string;
/** WGS84 Latitude. */
latitude: number;
/** WGS84 Longitude. */
longitude: number;
/** Altitude in meters above ellipsoid (optional). */
altitude?: number;
/** Heading/Rotation in degrees (optional). */
heading?: number;
/** Speed in knots or meters/sec depending on domain (optional). */
speed?: number;
/** The moment this data was captured. */
timestamp: Date;
/** Short display string for labels. */
label?: string;
/** Arbitrary metadata associated with the entity. */
properties: Record<string, unknown>;
}
export interface WsStreamPayload {
@@ -164,6 +185,11 @@ export type FilterValue = {
type: "boolean";
value: boolean;
};
/**
* @interface WorldPlugin
* @description The core lifecycle interface for all WorldWideView extensions.
* Every plugin (built-in or marketplace) must implement this interface.
*/
export interface WorldPlugin {
id: string;
name: string;
@@ -203,6 +229,15 @@ export interface WorldPlugin {
viewer: any;
enabled: boolean;
}>;
/**
* Returns a React component to be rendered inside the Bottom Panel when this plugin's
* dock button is selected. The panel is resizable and can be expanded to fullscreen.
* If not provided, the plugin will not appear in the bottom dock.
*/
getBottomPanelComponent?(): ComponentType<{
pluginId: string;
enabled: boolean;
}>;
requiresConfiguration?(settings: unknown): boolean;
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
@@ -213,6 +248,16 @@ export type DataBusEvents = {
pluginId: string;
defaultInterval: number;
};
pluginUnregistered: {
pluginId: string;
};
dynamicPluginCreate: {
plugin: WorldPlugin;
autoEnable?: boolean;
};
dynamicPluginRemove: {
pluginId: string;
};
dataUpdated: {
pluginId: string;
entities: GeoEntity[];
@@ -244,6 +289,16 @@ export type DataBusEvents = {
heading?: number;
};
globeReady: Record<string, never>;
pluginError: {
pluginId?: string;
message: string;
error?: Error;
};
layerLoadingChanged: {
pluginId: string;
loading: boolean;
};
};
export * from "./viteGlobals";
export * from "./auth-contracts";
//# sourceMappingURL=index.d.ts.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,O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C;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBAAmB,CAAC;IAGLine truncated
+9 -3
View File
@@ -1,7 +1,11 @@
"use strict";
// ─── WorldWideView Plugin SDK ─────────────────────────────────
// The public API for building WorldWideView plugins.
// Import from "@worldwideview/wwv-plugin-sdk" in your plugin.
/**
* @file index.ts
* @description Core SDK for WorldWideView plugin development.
* Defines the foundational types, interfaces, and utilities required
* to build data seeders, visualizers, and UI extensions.
* @module @worldwideview/wwv-plugin-sdk
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -61,3 +65,5 @@ function createSvgIconUrl(Icon, opts = {}) {
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(wrappedSvg)}`;
}
__exportStar(require("./viteGlobals"), exports);
// ─── Auth Contracts ──────────────────────────────────────────
__exportStar(require("./auth-contracts"), exports);
+11
View File
@@ -1,3 +1,10 @@
/**
* @file manifest.ts
* @description Schema and types for the WorldWideView plugin manifest (plugin.json).
* Defines the contract between the platform and external modules,
* covering capabilities, security tiers, and data source configurations.
* @module @worldwideview/wwv-plugin-sdk
*/
import type { PluginCategory } from "./index";
export type PluginFormat = "declarative" | "static" | "bundle";
export type PluginType = "data-layer" | "extension";
@@ -42,6 +49,10 @@ export interface RenderingConfig {
minZoomLevel?: number;
maxEntities?: number;
}
/**
* @interface PluginManifest
* @description The structural definition of a plugin.json file.
*/
export interface PluginManifest {
id: string;
name: string;
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,MAAM,YAAY,GAAG,aAAa,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC/D,MAAM,MAAM,UAAU,GAAG,YAAY,GAAG,WAAW,CAAC;AACpD,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,YAAY,CAAC;AAE/D,MAAM,MAAM,gBAAgB,GACtB,UAAU,GACV,aAAa,MAAM,EAAE,GACrB,iBAAiB,GACjB,YAAY,GACZ,YAAY,GACZ,aAAa,GACb,eAAe,GACf,cAAc,GACd,cAAc,GACd,eAAe,GACf,eAAe,CAAC;AAEtB,MAAM,WAAW,gBAAgB;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,CAAC;IACnC,IAAI,CAAC,EAAE;QAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6FAA6F;IAC7F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,C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MAAM,CAAC;IACd,aAAa,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1C,QAAQ,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAClC,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACtB"}
+7 -3
View File
@@ -1,5 +1,9 @@
"use strict";
// ─── Plugin Manifest Types ───────────────────────────────────
// Schema for plugin.json manifest files.
// Three formats: declarative (JSON-only), static (GeoJSON), bundle (JS code).
/**
* @file manifest.ts
* @description Schema and types for the WorldWideView plugin manifest (plugin.json).
* Defines the contract between the platform and external modules,
* covering capabilities, security tiers, and data source configurations.
* @module @worldwideview/wwv-plugin-sdk
*/
Object.defineProperty(exports, "__esModule", { value: true });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@worldwideview/wwv-plugin-sdk",
"version": "1.6.0",
"version": "1.7.1",
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@@ -1,3 +1,4 @@
import { describe, it, expectTypeOf } from "vitest";
import type {
TokenExchangeRequest,
@@ -21,7 +22,8 @@ describe("Auth Contracts", () => {
expectTypeOf<TokenExchangeRequest>().toHaveProperty("audience").toEqualTypeOf<string>();
// @ts-expect-error - missing required apiKey
const badReq: TokenExchangeRequest = { audience: "engine-123" };
const _badReq: TokenExchangeRequest = { audience: "engine-123" };
void _badReq;
});
it("TokenExchangeResponse has exact required properties", () => {
@@ -31,7 +33,8 @@ describe("Auth Contracts", () => {
expectTypeOf<TokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
// @ts-expect-error - missing required token
const badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
const _badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
void _badRes;
});
it("WebSocketAuthMessage has exact required properties including protocol version", () => {
@@ -40,10 +43,12 @@ describe("Auth Contracts", () => {
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
// @ts-expect-error - missing version
const badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
const _badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
void _badMsg;
// @ts-expect-error - wrong version
const badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
const _badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
void _badVersion;
});
it("WebSocketMessage is a discriminated union correctly containing WebSocketAuthMessage", () => {
+6 -1
View File
@@ -282,7 +282,7 @@ export interface WorldPlugin {
* dock button is selected. The panel is resizable and can be expanded to fullscreen.
* If not provided, the plugin will not appear in the bottom dock.
*/
getBottomPanelComponent?(): ComponentType<{ pluginId: string }>;
getBottomPanelComponent?(): ComponentType<{ pluginId: string; enabled: boolean }>;
requiresConfiguration?(settings: unknown): boolean;
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
@@ -294,6 +294,9 @@ export type GlobePlugin = WorldPlugin;
// ─── Data Bus Event Types ────────────────────────────────────
export type DataBusEvents = {
pluginRegistered: { pluginId: string; defaultInterval: number };
pluginUnregistered: { pluginId: string };
dynamicPluginCreate: { plugin: WorldPlugin; autoEnable?: boolean };
dynamicPluginRemove: { pluginId: string };
dataUpdated: { pluginId: string; entities: GeoEntity[] };
entitySelected: { entity: GeoEntity | null };
layerToggled: { pluginId: string; enabled: boolean };
@@ -302,6 +305,8 @@ export type DataBusEvents = {
cameraFaceTowards: { lat: number; lon: number; alt: number };
cameraGoTo: { lat: number; lon: number; alt: number; distance?: number; maxPitch?: number; heading?: number };
globeReady: Record<string, never>;
pluginError: { pluginId?: string; message: string; error?: Error };
layerLoadingChanged: { pluginId: string; loading: boolean };
};
export * from "./viteGlobals";
+66
View File
@@ -0,0 +1,66 @@
import { defineConfig, devices } from '@playwright/test';
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
timeout: 60000,
expect: {
timeout: 10000,
},
globalSetup: './tests/global.setup.ts',
globalTeardown: './tests/global.teardown.ts',
testDir: './tests',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. Restrict to 2 locally to prevent Next.js compilation overload. */
workers: process.env.CI ? 1 : 2,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://localhost:3001',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json'
},
},
{
name: 'firefox',
use: {
...devices['Desktop Firefox'],
storageState: 'playwright/.auth/user.json'
},
},
{
name: 'webkit',
use: {
...devices['Desktop Safari'],
storageState: 'playwright/.auth/user.json'
},
},
],
/* Run your local dev server before starting the tests */
webServer: {
command: 'pnpm dev',
env: { PORT: '3001' },
url: 'http://localhost:3001',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
});
+1123 -16
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,14 @@
{
"id": "e2e-mock-bottom-panel",
"name": "E2E Bottom Panel Mock",
"version": "1.0.0",
"description": "A static mock plugin used for Playwright E2E tests focusing on the bottom panel.",
"author": "WorldWideView Automated Tests",
"type": "extension",
"format": "bundle",
"trust": "unverified",
"entry": "/e2e-fixtures/e2e-mock-bottom-panel.js",
"capabilities": ["ui:bottom-panel", "ui:sidebar"],
"extends": ["bottom-panel", "sidebar"],
"category": "utility"
}
@@ -0,0 +1,74 @@
// This file is loaded by the plugin manager in the E2E test environment.
// It bypasses the build step and directly uses the host's injected React instance.
export default {
id: "e2e-mock-bottom-panel",
name: "E2E Bottom Panel Mock",
description: "A mock plugin for Bottom Panel E2E testing.",
icon: "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=", // Empty SVG as fallback
category: "custom",
version: "1.0.0",
// Lifecycle
initialize: async (ctx) => {
console.log("[e2e-mock-bottom-panel] Initialized");
},
destroy: () => {
console.log("[e2e-mock-bottom-panel] Destroyed");
},
// Data
fetch: async (timeRange) => {
return []; // No entities for this mock
},
getPollingInterval: () => {
return 60000;
},
// Rendering
getLayerConfig: () => {
return {
color: "#0000FF",
clusterEnabled: false,
clusterDistance: 50
};
},
renderEntity: (entity) => {
return {
type: "point",
color: "#0000FF",
size: 5
};
},
// Provide a bottom panel UI component using the host's React instance
getBottomPanelComponent: () => {
// Access React from the global host object injected by WorldWideView
const React = globalThis.__WWV_HOST__.React;
if (!React) {
console.error("[e2e-mock-bottom-panel] Failed to resolve React from __WWV_HOST__");
return null;
}
// Return a component function
return function MockBottomPanel() {
return React.createElement(
"div",
{
"data-testid": "e2e-bottom-panel-content",
style: {
padding: "16px",
background: "rgba(0, 0, 255, 0.1)",
border: "1px solid blue",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center"
}
},
"Mock Bottom Panel Active"
);
};
}
};
+14
View File
@@ -0,0 +1,14 @@
{
"id": "e2e-mock-plugin",
"name": "E2E Mock Plugin",
"version": "1.0.0",
"description": "A static mock plugin used for Playwright E2E tests.",
"author": "WorldWideView Automated Tests",
"type": "extension",
"format": "bundle",
"trust": "unverified",
"entry": "/e2e-fixtures/mock-plugin.js",
"capabilities": ["ui:sidebar"],
"category": "utility",
"extends": ["sidebar"]
}
+64
View File
@@ -0,0 +1,64 @@
// This file is loaded by the plugin manager in the E2E test environment.
// It bypasses the build step and directly uses the host's injected React instance.
export default {
// Basic plugin metadata required by WorldPlugin interface
id: "e2e-mock-plugin",
name: "E2E Mock Plugin",
description: "A mock plugin for E2E testing.",
icon: "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=", // Empty SVG as fallback
category: "custom",
version: "1.0.0",
// Lifecycle
initialize: async (ctx) => {
console.log("[e2e-mock-plugin] Initialized");
},
destroy: () => {
console.log("[e2e-mock-plugin] Destroyed");
},
// Data
fetch: async (timeRange) => {
return []; // No entities for this mock
},
getPollingInterval: () => {
return 60000;
},
// Rendering
getLayerConfig: () => {
return {
color: "#00FF00",
clusterEnabled: false,
clusterDistance: 50
};
},
renderEntity: (entity) => {
return {
type: "point",
color: "#00FF00",
size: 5
};
},
// Provide a UI component using the host's React instance
getSidebarComponent: () => {
// Access React from the global host object injected by WorldWideView
const React = globalThis.__WWV_HOST__.React;
if (!React) {
console.error("[e2e-mock-plugin] Failed to resolve React from __WWV_HOST__");
return null;
}
// Return a component function, not just an element
return function MockSidebar() {
return React.createElement(
"div",
{ "data-testid": "e2e-mock-panel", style: { padding: "16px", background: "rgba(0, 255, 0, 0.1)", border: "1px solid green" } },
"Mock Panel (E2E Test)"
);
};
}
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

+1 -1
View File
@@ -15,7 +15,7 @@ function copyDir(src, dest) {
}
const entries = fs.readdirSync(src, { withFileTypes: true });
for (let entry of entries) {
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
+2 -2
View File
@@ -7,7 +7,7 @@
*/
import concurrently from 'concurrently';
import kill from 'tree-kill';
import kill from 'tree-kill/index.js';
import { execSync } from 'child_process';
import fs from 'fs';
import process from 'process';
@@ -40,7 +40,7 @@ const teardownDbOnExit = process.env.WWV_TEARDOWN_DB_ON_EXIT === 'true' || proce
const { result, commands } = concurrently(
[
{ command: 'pnpm run dev:plugins', name: 'plugins', prefixColor: 'magenta' },
{ command: 'next dev', name: 'next', prefixColor: 'blue' }
{ command: 'pnpm exec next dev', name: 'next', prefixColor: 'blue' }
],
{
prefix: 'name',
+7
View File
@@ -1,6 +1,13 @@
import { execSync } from 'child_process';
const dbUrl = process.env.DATABASE_URL || '';
if (!dbUrl) {
console.error("❌ ERROR: DATABASE_URL is missing.");
console.error(" Did you forget to run 'pnpm run setup' to generate your .env file?");
process.exit(1);
}
const isLocal = dbUrl.includes('localhost') || dbUrl.includes('127.0.0.1') || dbUrl.includes('host.docker.internal') || dbUrl.includes('postgres:postgres@db:5432');
if (!isLocal) {
+1 -1
View File
@@ -60,7 +60,7 @@ export function discoverLocalPlugins() {
* into a single ES module, externalizing shared host dependencies.
*/
export async function buildPlugin({ dir, manifest, pluginDir }) {
const devEntry = manifest.dev_entry || "src/index.ts";
const devEntry = manifest.dev_entry || "index.ts";
let entryFile = path.join(pluginDir, devEntry);
// Fallback: check for .tsx
+6 -6
View File
@@ -50,11 +50,11 @@ function isAgentAction(v: unknown): v is AgentAction {
if (!v || typeof v !== "object") return false;
const a = (v as { action?: unknown }).action;
return (
a === "fly_to" ||
a === "face_towards" ||
a === "layer_toggle" ||
a === "highlight_layer" ||
a === "select_entity" ||
a === "ping"
a === "fly_to"
|| a === "face_towards"
|| a === "layer_toggle"
|| a === "highlight_layer"
|| a === "select_entity"
|| a === "ping"
);
}
+1 -1
View File
@@ -62,7 +62,7 @@ export async function GET() {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
"Connection": "keep-alive",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
+6 -8
View File
@@ -22,14 +22,12 @@ function readMaybe(p: string): string | null {
}
}
const BUILD_ID =
process.env.NEXT_PUBLIC_WWV_BUILD_ID ??
readMaybe(path.join(process.cwd(), ".build-id")) ??
"dev";
const BUILD_AT =
process.env.NEXT_PUBLIC_WWV_BUILD_AT ??
readMaybe(path.join(process.cwd(), ".build-at")) ??
null;
const BUILD_ID = process.env.NEXT_PUBLIC_WWV_BUILD_ID
?? readMaybe(path.join(process.cwd(), ".build-id"))
?? "dev";
const BUILD_AT = process.env.NEXT_PUBLIC_WWV_BUILD_AT
?? readMaybe(path.join(process.cwd(), ".build-at"))
?? null;
export async function GET() {
return NextResponse.json({
+4 -6
View File
@@ -14,8 +14,7 @@
import type { CameraAdapter, CameraFeature } from "./types";
const BULK_URL = "https://eapps.ncdot.gov/services/traffic-prod/v1/cameras";
const DETAIL_URL = (id: number) =>
`https://eapps.ncdot.gov/services/traffic-prod/v1/cameras/${id}`;
const DETAIL_URL = (id: number) => `https://eapps.ncdot.gov/services/traffic-prod/v1/cameras/${id}`;
const CONCURRENCY = 20;
@@ -64,7 +63,8 @@ async function mapWithConcurrency<T, R>(
let next = 0;
async function run() {
while (next < items.length) {
const i = next++;
const i = next;
next += 1;
results[i] = await worker(items[i]);
}
}
@@ -113,9 +113,7 @@ export const ncdotAdapter: CameraAdapter = {
const bulk = (await bulkRes.json()) as BulkRecord[];
if (!Array.isArray(bulk)) return [];
const details = await mapWithConcurrency(bulk, CONCURRENCY, (b) =>
fetchDetail(b.id),
);
const details = await mapWithConcurrency(bulk, CONCURRENCY, (b) => fetchDetail(b.id),);
const features: CameraFeature[] = [];
for (const d of details) {
@@ -55,8 +55,7 @@ export const osmSurveillanceAdapter: CameraAdapter = {
if (!res.ok) throw new Error(`overpass ${res.status}`);
const data = (await res.json()) as { elements?: OverpassNode[] };
const nodes = (data.elements ?? []).filter(
(e): e is OverpassNode =>
e.type === "node" && typeof e.lat === "number",
(e): e is OverpassNode => e.type === "node" && typeof e.lat === "number",
);
return nodes.map<CameraFeature>((n) => {
+2 -4
View File
@@ -113,12 +113,10 @@ export async function fetchAdapter(adapter: CameraAdapter): Promise<CameraFeatur
try {
const data = await Promise.race([
adapter.fetch(),
new Promise<CameraFeature[]>((_resolve, reject) =>
setTimeout(
new Promise<CameraFeature[]>((_resolve, reject) => setTimeout(
() => reject(new Error(`Adapter ${adapter.id} timed out after ${ADAPTER_FETCH_TIMEOUT_MS}ms`)),
ADAPTER_FETCH_TIMEOUT_MS,
),
),
),),
]);
cache.set(adapter.id, {
data,
+2 -3
View File
@@ -29,7 +29,7 @@ export async function GET(req: NextRequest) {
const ajaxRes = await fetch(ajaxUrl, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": targetUrl
Referer: targetUrl
}
});
const ajaxHtml = await ajaxRes.text();
@@ -37,9 +37,8 @@ export async function GET(req: NextRequest) {
const streamMatch = ajaxHtml.match(/src:\s*'([^']+m3u8[^']+)'/);
if (streamMatch && streamMatch[1]) {
return NextResponse.json({ streamUrl: streamMatch[1] });
} else {
return NextResponse.json({ error: "Could not find m3u8 stream on balticlivecam backend" }, { status: 404 });
}
return NextResponse.json({ error: "Could not find m3u8 stream on balticlivecam backend" }, { status: 404 });
}
return NextResponse.json({ error: "Unsupported extractor platform" }, { status: 400 });
+2 -3
View File
@@ -5,9 +5,8 @@
* until all features are retrieved.
*/
const GDOT_BASE =
"https://services1.arcgis.com/2iUE8l8JKrP2tygQ/arcgis/rest/services" +
"/GDOT_Live_Traffic_Cameras/FeatureServer/0/query";
const GDOT_BASE = "https://services1.arcgis.com/2iUE8l8JKrP2tygQ/arcgis/rest/services"
+ "/GDOT_Live_Traffic_Cameras/FeatureServer/0/query";
const PAGE_SIZE = 2000;
+3 -3
View File
@@ -29,9 +29,9 @@ export async function GET(req: NextRequest) {
try {
const upstream = await fetch(targetUrl, {
headers: {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
},
signal: AbortSignal.timeout(MAX_IFRAME_DURATION_MS),
@@ -45,7 +45,7 @@ export async function GET(req: NextRequest) {
}
const contentType = upstream.headers.get("content-type") || "text/html";
// If it's not HTML, just proxy the stream directly (fallback)
if (!contentType.includes("text/html")) {
return new Response(upstream.body as ReadableStream, {
+1 -1
View File
@@ -27,7 +27,7 @@ export async function GET(req: NextRequest) {
const response = await safeFetch(targetUrl, {
headers: {
"User-Agent": "WorldWideView/1.0",
"Accept": "application/json, text/plain, */*",
Accept: "application/json, text/plain, */*",
},
maxSize: 5 * 1024 * 1024, // 5MB
timeout: 10000 // 10s
+1 -2
View File
@@ -48,8 +48,7 @@ export async function GET(req: NextRequest) {
);
}
const contentType =
upstream.headers.get("content-type") || "application/octet-stream";
const contentType = upstream.headers.get("content-type") || "application/octet-stream";
return new Response(upstream.body as ReadableStream, {
status: 200,
+14 -12
View File
@@ -8,7 +8,7 @@ function isPrivateUrl(urlStr: string): boolean {
const parsed = new URL(urlStr);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return true;
const host = parsed.hostname;
// If developer overrides local restrictions, bypass checks
if (process.env.WWV_PROXY_ALLOW_LOCAL === "true") return false;
@@ -47,18 +47,19 @@ export async function GET(req: NextRequest) {
headers: { "User-Agent": "WorldWideView/1.0" },
signal: AbortSignal.timeout(TIMEOUT_MS)
});
} catch (headError: any) {
// Primitive IP camera servers (like Insecam sources) often aggressively drop the TCP connection
// instead of returning 405 when they see an unsupported HTTP method like HEAD.
} catch (headError: unknown) {
const err = headError as Error & { cause?: { code?: string } };
// Primitive IP camera servers (like Insecam sources) often aggressively drop the TCP connection
// instead of returning 405 when they see an unsupported HTTP method like HEAD.
// If the socket was closed unexpectedly, retry with GET.
if (headError.cause?.code === 'UND_ERR_SOCKET' || headError.message?.includes('fetch failed')) {
if (err.cause?.code === 'UND_ERR_SOCKET' || err.message?.includes('fetch failed')) {
response = await fetch(url, {
method: "GET",
headers: { "User-Agent": "WorldWideView/1.0" },
signal: AbortSignal.timeout(TIMEOUT_MS)
});
} else {
throw headError;
throw err;
}
}
@@ -81,13 +82,14 @@ export async function GET(req: NextRequest) {
contentType: response.headers.get("content-type"),
latencyMs: Date.now() - startTime
});
} catch (error: any) {
const realError = error.cause || error;
const code = realError?.code || error?.code || realError?.name || error?.name;
} catch (error: unknown) {
const err = error as Error & { cause?: { code?: string, message?: string, name?: string }, code?: string };
const realError = err.cause || err;
const code = realError?.code || err?.code || realError?.name || err?.name;
let displayError = error?.message || "Unknown error";
let displayError = err?.message || "Unknown error";
if (code && code !== 'TypeError' && code !== 'Error') {
displayError = `[${code}] ${realError?.message || error?.message || ""}`;
displayError = `[${code}] ${realError?.message || err?.message || ""}`;
}
// Make sure we don't accidentally categorize a malformed HTTP response as a timeout
@@ -95,7 +97,7 @@ export async function GET(req: NextRequest) {
return NextResponse.json({ status: "error", error: displayError, latencyMs: Date.now() - startTime });
}
if (error?.name === "TimeoutError" || displayError.includes("timeout") || code === "UND_ERR_CONNECT_TIMEOUT") {
if (err?.name === "TimeoutError" || displayError.includes("timeout") || code === "UND_ERR_CONNECT_TIMEOUT") {
return NextResponse.json({ status: "timeout", error: "Connection timed out", latencyMs: Date.now() - startTime });
}
+3 -4
View File
@@ -13,8 +13,7 @@
import type { GdotCameraFeature } from "../gdot/gdotFetcher";
const WSDOT_BASE =
"https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson";
const WSDOT_BASE = "https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson";
interface WsdotCamera {
CameraID: number;
@@ -78,8 +77,8 @@ export async function fetchWsdotCameras(): Promise<GdotCameraFeature[]> {
if (!key) {
if (!warnedMissingKey) {
console.warn(
"[WSDOT] WSDOT_API_KEY not set — skipping. " +
"Get a free key at https://wsdot.wa.gov/traffic/api/",
"[WSDOT] WSDOT_API_KEY not set — skipping. "
+ "Get a free key at https://wsdot.wa.gov/traffic/api/",
);
warnedMissingKey = true;
}
+2 -2
View File
@@ -30,10 +30,10 @@ export async function POST(request: Request) {
try {
const body = await request.json();
// Convert wwv-manifest.json format to PluginManifest format
const manifest = parseWwvManifest(body);
// Dev-loaded plugins are unverified by default
manifest.trust = "unverified";
@@ -12,7 +12,7 @@ export async function GET(
// Await params as required in Next.js 15+
const resolvedParams = await params;
const subdomain = resolvedParams.subdomain;
const {subdomain} = resolvedParams;
try {
const workspace = await prisma.workspace.findUnique({
+88
View File
@@ -0,0 +1,88 @@
import { NextResponse } from "next/server";
export const revalidate = 60;
const WTIA_POSITIONS_URL = "https://api.wheretheiss.at/v1/satellites/25544/positions";
const MAX_TIMESTAMPS = 10;
function isValidPosition(item: any): boolean {
return (
item != null
&& typeof item === "object"
&& Number.isFinite(item.latitude)
&& Number.isFinite(item.longitude)
&& Number.isFinite(item.altitude)
&& Number.isFinite(item.velocity)
&& Number.isFinite(item.timestamp)
);
}
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const timestampsParam = searchParams.get("timestamps");
if (!timestampsParam) {
return NextResponse.json(
{ error: "Missing required 'timestamps' query parameter" },
{ status: 400 },
);
}
const timestamps = timestampsParam
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+$/.test(t));
if (timestamps.length === 0) {
return NextResponse.json(
{ error: "No valid timestamps provided" },
{ status: 400 },
);
}
if (timestamps.length > MAX_TIMESTAMPS) {
return NextResponse.json(
{ error: `Maximum ${MAX_TIMESTAMPS} timestamps allowed per request` },
{ status: 400 },
);
}
try {
const url = `${WTIA_POSITIONS_URL}?timestamps=${timestamps.join(",")}&units=kilometers`;
const response = await fetch(url, {
headers: {
Accept: "application/json",
"User-Agent": "WorldWideView/1.0",
},
next: { revalidate },
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to fetch ISS positions" },
{ status: 502 },
);
}
const data = await response.json();
const positions = (Array.isArray(data) ? data : [])
.filter(isValidPosition)
.map((p) => ({
latitude: p.latitude,
longitude: p.longitude,
altitude: p.altitude,
velocity: p.velocity,
visibility: p.visibility,
timestamp: p.timestamp,
}));
return NextResponse.json({ positions });
} catch (error) {
console.error("[IssPositionsRoute] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch ISS positions" },
{ status: 502 },
);
}
}
+64
View File
@@ -0,0 +1,64 @@
import { NextResponse } from "next/server";
export const revalidate = 10;
const WTIA_URL = "https://api.wheretheiss.at/v1/satellites/25544";
function isValidResponse(data: any): boolean {
return (
data != null
&& typeof data === "object"
&& Number.isFinite(data.latitude)
&& Number.isFinite(data.longitude)
&& Number.isFinite(data.altitude)
&& Number.isFinite(data.velocity)
&& Number.isFinite(data.timestamp)
);
}
export async function GET() {
try {
const response = await fetch(WTIA_URL, {
headers: {
Accept: "application/json",
"User-Agent": "WorldWideView/1.0",
},
next: { revalidate },
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to fetch ISS position" },
{ status: 502 },
);
}
const data = await response.json();
if (!isValidResponse(data)) {
return NextResponse.json(
{ error: "Invalid ISS position data" },
{ status: 502 },
);
}
return NextResponse.json({
id: data.id,
name: data.name,
latitude: data.latitude,
longitude: data.longitude,
altitude: data.altitude,
velocity: data.velocity,
visibility: data.visibility,
footprint: data.footprint,
timestamp: data.timestamp,
units: data.units,
});
} catch (error) {
console.error("[IssRoute] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch ISS position" },
{ status: 502 },
);
}
}
+60
View File
@@ -0,0 +1,60 @@
import { NextResponse } from "next/server";
export const revalidate = 3600;
const WTIA_TLE_URL = "https://api.wheretheiss.at/v1/satellites/25544/tles/latest";
function isValidTle(data: any): boolean {
return (
data != null
&& typeof data === "object"
&& typeof data.line1 === "string"
&& typeof data.line2 === "string"
&& data.line1.length > 0
&& data.line2.length > 0
&& Number.isFinite(data.tle_timestamp)
);
}
export async function GET() {
try {
const response = await fetch(WTIA_TLE_URL, {
headers: {
Accept: "application/json",
"User-Agent": "WorldWideView/1.0",
},
next: { revalidate },
});
if (!response.ok) {
return NextResponse.json(
{ error: "Failed to fetch ISS TLE data" },
{ status: 502 },
);
}
const data = await response.json();
if (!isValidTle(data)) {
return NextResponse.json(
{ error: "Invalid ISS TLE data" },
{ status: 502 },
);
}
return NextResponse.json({
id: data.id,
name: data.name,
header: data.header,
line1: data.line1,
line2: data.line2,
tleTimestamp: data.tle_timestamp,
});
} catch (error) {
console.error("[IssTleRoute] Error:", error);
return NextResponse.json(
{ error: "Failed to fetch ISS TLE data" },
{ status: 502 },
);
}
}
+10 -9
View File
@@ -2,22 +2,23 @@ import { NextRequest, NextResponse } from "next/server";
import * as client from "openid-client";
import { encryptCredential } from "@/lib/auth/encryption";
import { prisma as db } from "@/lib/db";
export async function GET(req: NextRequest) {
const isHttps = req.nextUrl.protocol === "https:";
const cookiePrefix = isHttps ? "__Host-" : "";
const stateCookie = req.cookies.get(`${cookiePrefix}pkce_state`)?.value;
const verifierCookie = req.cookies.get(`${cookiePrefix}pkce_verifier`)?.value;
const urlState = req.nextUrl.searchParams.get("state");
if (!stateCookie || urlState !== stateCookie) {
return NextResponse.json({ error: "State mismatch" }, { status: 400 });
}
if (!verifierCookie) {
return NextResponse.json({ error: "Missing code_verifier" }, { status: 400 });
}
const marketplaceUrl = process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL || "https://app.worldwideview.dev";
const issuer = new URL(marketplaceUrl);
const server = {
@@ -33,7 +34,7 @@ export async function GET(req: NextRequest) {
new URL(req.url),
{ expectedState: stateCookie, pkceCodeVerifier: verifierCookie }
);
if (tokens.access_token) {
const encrypted = await encryptCredential(tokens.access_token);
await db.marketplaceCredential.upsert({
@@ -57,9 +58,9 @@ export async function GET(req: NextRequest) {
console.error("[PKCE] Exchange failed:", err.message);
return NextResponse.json({ error: "Failed to exchange authorization code" }, { status: 500 });
}
const res = NextResponse.redirect(new URL("/", req.nextUrl.origin), 302);
res.cookies.set(`${cookiePrefix}pkce_state`, "", {
httpOnly: true,
secure: isHttps,
@@ -67,7 +68,7 @@ export async function GET(req: NextRequest) {
path: "/api/marketplace/callback",
maxAge: 0
});
res.cookies.set(`${cookiePrefix}pkce_verifier`, "", {
httpOnly: true,
secure: isHttps,
@@ -75,6 +76,6 @@ export async function GET(req: NextRequest) {
path: "/api/marketplace/callback",
maxAge: 0
});
return res;
}
@@ -12,7 +12,7 @@ export async function GET(request: Request) {
try {
// Fetch currently installed plugins from PostgreSQL
const installedPlugins = await getInstalledPlugins();
// Exclude built-in versions, only check genuine semver strings or unverified records.
const updatablePlugins = installedPlugins.filter((p: any) => p.version !== "built-in");
@@ -24,13 +24,13 @@ export async function GET(request: Request) {
const res = await fetch(`${MARKETPLACE_URL}/api/plugins`, {
next: { revalidate: 60 } // Cache for 60 seconds
});
if (!res.ok) {
throw new Error(`Marketplace returned ${res.status}`);
}
const marketplacePlugins = await res.json();
// Build a lookup map of Market versions
const marketVersions = new Map();
for (const p of marketplacePlugins) {
@@ -42,7 +42,7 @@ export async function GET(request: Request) {
// Compare and flag updates
for (const localPlugin of updatablePlugins) {
const marketVersion = marketVersions.get(localPlugin.pluginId);
// Only suggest an update if marketplace version exists and differs
if (marketVersion && marketVersion !== "0.0.0" && marketVersion !== localPlugin.version) {
updates[localPlugin.pluginId] = marketVersion;
+7 -7
View File
@@ -5,9 +5,9 @@ export async function GET(req: NextRequest) {
const state = client.randomState();
const code_verifier = client.randomPKCECodeVerifier();
const code_challenge = await client.calculatePKCECodeChallenge(code_verifier);
const marketplaceUrl = process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL || "https://app.worldwideview.dev";
const url = new URL("/oauth/authorize", marketplaceUrl);
url.searchParams.set("client_id", "local-app");
url.searchParams.set("response_type", "code");
@@ -16,12 +16,12 @@ export async function GET(req: NextRequest) {
url.searchParams.set("state", state);
url.searchParams.set("redirect_uri", `${req.nextUrl.origin}/api/marketplace/callback`);
url.searchParams.set("scope", "plugins:read");
const res = NextResponse.redirect(url.toString(), 302);
const isHttps = req.nextUrl.protocol === "https:";
const cookiePrefix = isHttps ? "__Host-" : "";
res.cookies.set(`${cookiePrefix}pkce_state`, state, {
httpOnly: true,
secure: isHttps,
@@ -29,7 +29,7 @@ export async function GET(req: NextRequest) {
path: "/api/marketplace/callback",
maxAge: 60 * 10 // 10 minutes
});
res.cookies.set(`${cookiePrefix}pkce_verifier`, code_verifier, {
httpOnly: true,
secure: isHttps,
@@ -37,6 +37,6 @@ export async function GET(req: NextRequest) {
path: "/api/marketplace/callback",
maxAge: 60 * 10 // 10 minutes
});
return res;
}
+3 -3
View File
@@ -17,8 +17,8 @@ function isSafeRedirect(url: string): boolean {
try {
const parsed = new URL(url);
return (
ALLOWED_REDIRECT_HOSTS.has(parsed.hostname) ||
parsed.hostname.endsWith(".worldwideview.dev")
ALLOWED_REDIRECT_HOSTS.has(parsed.hostname)
|| parsed.hostname.endsWith(".worldwideview.dev")
);
} catch {
return false;
@@ -53,7 +53,7 @@ export async function GET(request: NextRequest) {
if (!session?.user) {
const origin = getRequestOrigin(request);
const loginUrl = new URL("/login", origin);
// Construct a relative path for callback to ensure it redirects back to the identical host
const callbackPath = request.nextUrl.pathname + request.nextUrl.search;
loginUrl.searchParams.set("callbackUrl", callbackPath);
@@ -24,7 +24,7 @@ if (process.env.ALLOWED_DEV_ORIGIN) {
function isSafeRedirect(url: string): boolean {
try {
const parsed = new URL(url);
const hostname = parsed.hostname;
const {hostname} = parsed;
return ALLOWED_REDIRECT_HOSTS.has(hostname) || hostname.endsWith(".worldwideview.dev");
} catch {
return false;
@@ -126,7 +126,6 @@ export async function GET(request: NextRequest) {
// Token in fragment — never sent to server in logs/referer
return NextResponse.redirect(`${successUrl.toString()}#token=${token}`);
} catch (err) {
// Top-level catch: log and redirect to marketplace with error, don't expose raw 500
console.error("[install-redirect] Unexpected error:", err);
+5 -7
View File
@@ -21,8 +21,6 @@ export async function POST(request: Request) {
);
}
const rateLimited = marketplaceApiLimiter.check(getClientIp(request));
if (rateLimited) return withCors(rateLimited, request);
@@ -53,9 +51,9 @@ export async function POST(request: Request) {
if (res.ok) {
const card = await res.json();
finalManifest = { ...card };
// Reconstruct entry URL for plugins that are distributed via NPM.
// We also forcefully coerce format to "bundle" here because
// We also forcefully coerce format to "bundle" here because
// the marketplace cache might still return "static" for plugins we recently converted.
if (finalManifest.npmPackage) {
const targetVersion = version || finalManifest.version || "1.0.0";
@@ -73,9 +71,9 @@ export async function POST(request: Request) {
const validation = validateManifest(finalManifest);
if (!validation.valid) {
console.error(
`[Marketplace Install Route] ❌ MANIFEST VALIDATION FAILED for ${pluginId}\n` +
`Errors: ${validation.errors.join(", ")}\n` +
`Evaluated Payload:\n${JSON.stringify(finalManifest, null, 2)}`
`[Marketplace Install Route] ❌ MANIFEST VALIDATION FAILED for ${pluginId}\n`
+ `Errors: ${validation.errors.join(", ")}\n`
+ `Evaluated Payload:\n${JSON.stringify(finalManifest, null, 2)}`
);
return withCors(
NextResponse.json(
+6 -9
View File
@@ -65,9 +65,7 @@ export async function GET(request: Request) {
}
const allRecords = [...records, ...localPlugins];
const manifests = allRecords
.map((r: any): PluginManifest | null => {
try {
@@ -92,10 +90,10 @@ export async function GET(request: Request) {
// Skip bundle plugins whose entry is a bare module specifier
// (e.g. "camera") — cannot be dynamically imported in the browser.
if (
m.format === "bundle" &&
!m.entry.startsWith("/") &&
!m.entry.startsWith("./") &&
!m.entry.startsWith("http")
m.format === "bundle"
&& !m.entry.startsWith("/")
&& !m.entry.startsWith("./")
&& !m.entry.startsWith("http")
) return false;
// For anything that looks like a real manifest, validate it and log if it fails
@@ -103,7 +101,7 @@ export async function GET(request: Request) {
if (!validation.valid) {
const errorMessage = `Manifest validation failed for ${m.id}`;
console.error(`[Marketplace API] ${errorMessage}:`, validation.errors);
// Capture in Sentry so we have visibility into malformed third-party plugins
Sentry.captureMessage(errorMessage, {
level: "error",
@@ -131,7 +129,7 @@ export async function GET(request: Request) {
if (m.format === "declarative" && m.dataSource) {
// Only omit headers and potentially sensitive auth params.
// The URL might be needed by the client for polling, but headers like Bearer tokens shouldn't leak.
// If the audit explicitly asks to strip URL, maybe just replace it entirely if it's sensitive,
// If the audit explicitly asks to strip URL, maybe just replace it entirely if it's sensitive,
// but usually headers are the sensitive part. We strip headers.
if (m.dataSource.headers) {
m.dataSource.headers = {};
@@ -146,4 +144,3 @@ export async function GET(request: Request) {
return withCors(NextResponse.json({ manifests: [] }), request);
}
}
+12 -10
View File
@@ -1,4 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import {
describe, it, expect, vi, beforeEach
} from "vitest";
import { NextRequest } from "next/server";
import { GET as connectRoute } from "./connect/route";
import { GET as callbackRoute } from "./callback/route";
@@ -39,14 +41,14 @@ describe("PKCE Flow", () => {
it("should generate PKCE parameters and redirect with secure cookies", async () => {
const req = new NextRequest("https://localhost:3000/api/marketplace/connect");
const res = await connectRoute(req);
expect(res.status).toBe(302);
// Check redirect URL
const location = res.headers.get("Location");
expect(location).toContain("response_type=code");
expect(location).toContain("code_challenge_method=S256");
// Check cookie flags
const cookies = res.headers.get("Set-Cookie");
expect(cookies).toBeDefined();
@@ -63,7 +65,7 @@ describe("PKCE Flow", () => {
it("should reject if state does not match", async () => {
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=wrong-state&code=test-code");
req.cookies.set("__Host-pkce_state", "correct-state");
const res = await callbackRoute(req);
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: "State mismatch" });
@@ -73,7 +75,7 @@ describe("PKCE Flow", () => {
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
req.cookies.set("__Host-pkce_state", "correct-state");
// code_verifier cookie is intentionally omitted
const res = await callbackRoute(req);
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: "Missing code_verifier" });
@@ -83,19 +85,19 @@ describe("PKCE Flow", () => {
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
req.cookies.set("__Host-pkce_state", "correct-state");
req.cookies.set("__Host-pkce_verifier", "mock-verifier");
const res = await callbackRoute(req);
const cookies = res.headers.get("Set-Cookie");
expect(cookies).toContain("__Host-pkce_state=;");
expect(cookies).toContain("Max-Age=0");
});
it("should perform openid-client exchange and save encrypted token", async () => {
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
req.cookies.set("__Host-pkce_state", "correct-state");
req.cookies.set("__Host-pkce_verifier", "mock-verifier");
const res = await callbackRoute(req);
expect(res.status).toBe(302); // Redirect back to marketplace or app
});
+1 -2
View File
@@ -44,8 +44,7 @@ export async function GET(request: Request) {
const authError = await validateMarketplaceAuth(request);
canManagePlugins = authError === null;
}
return withCors(NextResponse.json({ plugins: [], canManagePlugins }), request);
}
}
@@ -19,8 +19,6 @@ export async function POST(request: Request) {
);
}
const rateLimited = marketplaceApiLimiter.check(getClientIp(request));
if (rateLimited) return withCors(rateLimited, request);
@@ -59,4 +57,3 @@ export async function POST(request: Request) {
);
}
}
+6 -6
View File
@@ -1,18 +1,18 @@
import { NextResponse } from "next/server";
import https from "https";
const OVERPASS_MIRRORS = [
"https://overpass-api.de/api/interpreter",
"https://lz4.overpass-api.de/api/interpreter",
"https://overpass.kumi.systems/api/interpreter"
];
import https from "https";
async function tryMirror(urlStr: string, query: string, timeoutMs: number) {
return new Promise<any>((resolve, reject) => {
const url = new URL(urlStr);
const bodyStr = `data=${encodeURIComponent(query)}`;
const req = https.request(url, {
method: "POST",
family: 4, // Force IPv4 to avoid Docker IPv6 dropout
@@ -24,7 +24,7 @@ async function tryMirror(urlStr: string, query: string, timeoutMs: number) {
timeout: timeoutMs,
}, (res) => {
let data = "";
res.on("data", chunk => data += chunk);
res.on("data", (chunk) => data += chunk);
res.on("end", () => {
resolve({
ok: res.statusCode && res.statusCode >= 200 && res.statusCode < 300,
@@ -41,7 +41,7 @@ async function tryMirror(urlStr: string, query: string, timeoutMs: number) {
req.destroy();
reject(new Error("Request timed out"));
});
req.write(bodyStr);
req.end();
});
@@ -92,7 +92,7 @@ export async function POST(req: Request) {
}
return NextResponse.json(
{ error: "All Overpass mirrors failed or timed out. The OSM servers are likely under heavy load." },
{ error: "All Overpass mirrors failed or timed out. The OSM servers are likely under heavy load." },
{ status: 504 }
);
} catch (e: any) {
+1 -1
View File
@@ -7,7 +7,7 @@ export async function GET() {
const response = await fetch("https://www.submarinecablemap.com/api/v3/cable/cable-geo.json", {
headers: {
"User-Agent": "WorldWideView/1.0",
"Accept": "application/json",
Accept: "application/json",
},
});
+7 -5
View File
@@ -13,7 +13,7 @@ export async function GET(request: Request) {
where: { userId: session.user.id },
orderBy: { lastSeen: "desc" }
});
return NextResponse.json(favorites);
} catch (e) {
console.error("GET Favorites Error:", e);
@@ -29,7 +29,9 @@ export async function POST(request: Request) {
try {
const body = await request.json();
const { entityId, pluginId, label, pluginName } = body;
const {
entityId, pluginId, label, pluginName
} = body;
if (!entityId || !pluginId || !label || !pluginName) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
@@ -39,7 +41,7 @@ export async function POST(request: Request) {
where: {
userId_entityId: {
userId: session.user.id,
entityId: entityId
entityId
}
},
update: {
@@ -70,7 +72,7 @@ export async function DELETE(request: Request) {
try {
const { searchParams } = new URL(request.url);
const entityId = searchParams.get("entityId");
if (!entityId) {
return NextResponse.json({ error: "Missing entityId" }, { status: 400 });
}
@@ -79,7 +81,7 @@ export async function DELETE(request: Request) {
where: {
userId_entityId: {
userId: session.user.id,
entityId: entityId
entityId
}
}
});
+225 -3
View File
@@ -218,7 +218,7 @@ html, body {
.sidebar {
position: fixed;
top: 80px; /* Reduced to ~12px gap from header */
bottom: 140px; /* Reduced gap from timeline */
bottom: var(--sidebar-bottom, 140px); /* Dynamically pushed by BottomPanelManager */
width: 280px;
z-index: 50;
padding: var(--space-lg);
@@ -230,8 +230,16 @@ html, body {
bottom var(--duration-slow) var(--ease-smooth);
}
.timeline-closed .sidebar {
bottom: var(--space-lg);
body.is-dragging-bottom-panel .sidebar {
transition: transform var(--duration-slow) var(--ease-smooth),
opacity var(--duration-slow) var(--ease-smooth);
}
/* Force animation when crossing the threshold (overrides is-dragging) */
body.sidebar-force-transition .sidebar {
transition: transform var(--duration-slow) var(--ease-smooth),
opacity var(--duration-slow) var(--ease-smooth),
bottom var(--duration-slow) var(--ease-smooth) !important;
}
.sidebar--left {
@@ -1912,3 +1920,217 @@ body.is-resizing-sidebar .sidebar {
background: rgba(255, 255, 255, 0.1);
}
/* ─── Bottom Panel Manager ───────────────────────────────── */
.bottom-panel-system {
position: absolute;
bottom: var(--space-lg, 20px);
left: var(--space-lg, 20px);
right: calc(var(--ad-strip-inset, 0px) + var(--space-lg, 20px));
display: flex;
flex-direction: column;
align-items: center;
z-index: 1000;
pointer-events: none;
}
.bottom-panel-dock {
display: flex;
margin-bottom: 0; /* Flush with panel */
pointer-events: auto;
transition: transform var(--duration-normal) var(--ease-smooth), gap var(--duration-fast) var(--ease-smooth);
/* Centered, horizontally scrollable container */
max-width: 100%;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE/Edge */
/* Safely center items but prevent left-side clipping on overflow */
justify-content: safe center;
/* Small negative gap so the slanted bases touch/overlap nicely */
gap: -4px;
padding: 0 12px;
}
.bottom-panel-dock::-webkit-scrollbar {
display: none; /* Safari/Chrome */
}
/* The actual button container (transparent, straight rectangle) */
.dock-btn {
position: relative;
flex-shrink: 0;
height: 36px;
padding: 0 24px; /* Wider padding to account for slanted sides */
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
background: transparent;
border: none;
color: var(--text-secondary);
cursor: pointer;
font-size: 11px;
font-weight: 500;
letter-spacing: 0.05em;
text-transform: uppercase;
isolation: isolate; /* Create new stacking context so pseudo-elements don't escape */
transition: color var(--duration-fast) var(--ease-smooth), padding var(--duration-fast) var(--ease-smooth);
}
/* The angled background shape using 3D perspective */
.dock-btn::before {
content: '';
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
z-index: -1;
background: var(--bg-glass);
backdrop-filter: blur(var(--glass-blur, 24px));
border: var(--glass-border);
border-bottom: none;
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
/* Create the trapezoid slant by rotating back on the X axis */
transform: perspective(20px) rotateX(5deg);
transform-origin: bottom;
transition: all var(--duration-fast) var(--ease-smooth);
opacity: 0.6; /* More transparent when inactive */
}
.dock-btn:hover {
color: var(--text-primary);
}
.dock-btn:hover::before {
background: var(--bg-glass-hover);
opacity: 0.85;
}
.dock-btn.active {
color: var(--accent-cyan);
font-weight: 600;
z-index: 2; /* Bring active tab to front */
}
.dock-btn.active::before {
background: var(--bg-glass-active);
border-color: rgba(var(--accent-rgb), 0.5);
box-shadow: inset 0 0 40px rgba(var(--accent-rgb), 0.08), 0 -4px 15px rgba(var(--accent-rgb), 0.15); /* Tint + Glow upwards */
opacity: 1; /* Fully opaque (relative to the rgba alpha) when active */
}
.dock-btn-label {
white-space: nowrap;
}
/* ─── Floating Pills Mode (when no panel is active) ─── */
.bottom-panel-dock.floating-pills {
gap: 8px; /* Give them breathing room */
}
.bottom-panel-dock.floating-pills .dock-btn {
padding: 0 16px; /* Less horizontal padding since it's not a trapezoid */
}
.bottom-panel-dock.floating-pills .dock-btn::before {
border-radius: var(--radius-full);
transform: none; /* Remove trapezoid slant */
border-bottom: var(--glass-border); /* Restore full border */
}
.bottom-panel {
width: 100%;
/* border-radius: var(--radius-lg); - handled by .glass-panel */
display: flex;
flex-direction: column;
pointer-events: auto;
overflow: hidden;
position: relative;
/* Transition applied to height in style, but we can animate opacity/transform too */
transition: height var(--duration-slow) var(--ease-smooth), opacity var(--duration-normal) var(--ease-smooth);
/* Removed background override so it inherits .glass-panel perfectly */
margin-top: -1px; /* Overlap the 1px border so tabs sit perfectly flush */
}
/* Disable height transition during drag to prevent lag */
body.is-dragging-bottom-panel .bottom-panel {
transition: opacity var(--duration-normal) var(--ease-smooth);
}
.bottom-panel.closed {
opacity: 0;
pointer-events: none;
border: none;
}
.bottom-panel.open {
opacity: 1;
}
.bottom-panel-resize-handle {
height: 12px;
width: 100%;
cursor: ns-resize;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
background: transparent;
z-index: 10;
}
.bottom-panel-resize-handle:hover .resize-grip {
background: rgba(255, 255, 255, 0.5);
}
.resize-grip {
width: 40px;
height: 4px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.2);
transition: background 0.2s;
}
.bottom-panel-close-btn {
position: absolute;
top: 12px;
right: 12px;
background: transparent;
border: none;
color: rgba(255, 255, 255, 0.5);
cursor: pointer;
padding: 4px;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
transition: all 0.2s ease;
}
.bottom-panel-close-btn:hover {
color: white;
background: rgba(255, 255, 255, 0.1);
}
.bottom-panel-content {
padding: 24px;
flex: 1;
overflow-y: auto;
/* Ensure the content sits below the resize handle */
margin-top: 12px;
display: flex;
flex-direction: column;
}
/* Timeline adjustments inside the new panel */
.timeline__content {
display: flex;
flex-direction: column;
gap: 12px;
height: 100%;
}
+2 -2
View File
@@ -38,9 +38,9 @@ export default function RootLayout({
)}
{/* Load CesiumJS base styles (optional, but helps with UI widgets if used later) */}
<link rel="stylesheet" href="/cesium/Widgets/widgets.css" />
<Script
<script
id="theme-hydration"
strategy="beforeInteractive"
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: `
try {
+2 -3
View File
@@ -27,10 +27,10 @@ export async function loginAction(formData: FormData): Promise<LoginResult> {
email,
password,
});
if (error) return { success: false, error: error.message };
return { success: true };
} else {
}
try {
await signIn("credentials", {
email,
@@ -49,5 +49,4 @@ export async function loginAction(formData: FormData): Promise<LoginResult> {
}
throw error;
}
}
}
+37 -38
View File
@@ -2,8 +2,8 @@
import { Suspense, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { loginAction } from "./actions";
import { isDemo } from "@/core/edition";
import { loginAction } from "./actions";
import styles from "../setup/setup.module.css";
/** Allow relative paths or absolute URLs on the same origin. */
@@ -48,52 +48,51 @@ function LoginForm() {
}
return (
<div className={styles.container}>
<div className={styles.card}>
<div className={styles.logo}>W</div>
<h1 className={styles.title}>Sign in to WorldWideView</h1>
<p className={styles.subtitle}>Enter your credentials to continue</p>
<div className={styles.container}>
<div className={styles.card}>
<div className={styles.logo}>W</div>
<h1 className={styles.title}>Sign in to WorldWideView</h1>
<p className={styles.subtitle}>Enter your credentials to continue</p>
<form onSubmit={handleSubmit} method="post" className={styles.form}>
<label className={styles.label} htmlFor="email">
{isDemo ? "Username" : "Email"}
</label>
<input
id="email"
name="email"
type={isDemo ? "text" : "email"}
required
className={styles.input}
placeholder={isDemo ? "admin" : "[email protected]"}
/>
<form onSubmit={handleSubmit} method="post" className={styles.form}>
<label className={styles.label} htmlFor="email">
{isDemo ? "Username" : "Email"}
<input
id="email"
name="email"
type={isDemo ? "text" : "email"}
required
className={styles.input}
placeholder={isDemo ? "admin" : "[email protected]"}
/>
</label>
<label className={styles.label} htmlFor="password">
Password
</label>
<input
id="password"
name="password"
type="password"
required
className={styles.input}
/>
<label className={styles.label} htmlFor="password">
Password
<input
id="password"
name="password"
type="password"
required
className={styles.input}
/>
</label>
{error && <p className={styles.error}>{error}</p>}
{error && <p className={styles.error}>{error}</p>}
<button type="submit" disabled={loading} className={styles.button}>
{loading ? "Signing in..." : "Sign In"}
</button>
</form>
</div>
<button type="submit" disabled={loading} className={styles.button}>
{loading ? "Signing in..." : "Sign In"}
</button>
</form>
</div>
</div>
);
}
export default function LoginPage() {
return (
<Suspense>
<LoginForm />
</Suspense>
<Suspense>
<LoginForm />
</Suspense>
);
}
+3 -1
View File
@@ -32,7 +32,9 @@ export async function createAdminAccount(formData: FormData): Promise<SetupResul
const hashedPassword = hashSync(password, 12);
await prisma.user.create({
data: { name, email, hashedPassword, role: "admin" },
data: {
name, email, hashedPassword, role: "admin"
},
});
return { success: true };
+57 -64
View File
@@ -27,76 +27,69 @@ export default function SetupPage() {
}
return (
<div className={styles.container}>
<div className={styles.card}>
<div className={styles.logo}>W</div>
<h1 className={styles.title}>Welcome to WorldWideView</h1>
<p className={styles.subtitle}>Create your admin account to get started</p>
<div className={styles.container}>
<div className={styles.card}>
<div className={styles.logo}>W</div>
<h1 className={styles.title}>Welcome to WorldWideView</h1>
<p className={styles.subtitle}>Create your admin account to get started</p>
{/* Legacy Data Detection Banner */}
<div className={styles.legacyNotice}>
<strong>💡 Upgrading from an older version?</strong>
<p>We've detected legacy SQLite data. Once your new Postgres database is connected, you can import your favorites by running the migration command in your terminal.</p>
<code>docker compose exec wwv node scripts/migrate-legacy.mjs</code>
</div>
<form onSubmit={handleSubmit} className={styles.form}>
<label className={styles.label} htmlFor="name">
Display Name
<input
id="name"
name="name"
type="text"
required
className={styles.input}
placeholder="Admin"
/>
</label>
<form onSubmit={handleSubmit} className={styles.form}>
<label className={styles.label} htmlFor="name">
Display Name
</label>
<input
id="name"
name="name"
type="text"
required
className={styles.input}
placeholder="Admin"
/>
<label className={styles.label} htmlFor="email">
Email
<input
id="email"
name="email"
type="email"
required
className={styles.input}
placeholder="[email protected]"
/>
</label>
<label className={styles.label} htmlFor="email">
Email
</label>
<input
id="email"
name="email"
type="email"
required
className={styles.input}
placeholder="[email protected]"
/>
<label className={styles.label} htmlFor="password">
Password
<input
id="password"
name="password"
type="password"
required
minLength={8}
className={styles.input}
placeholder="Min. 8 characters"
/>
</label>
<label className={styles.label} htmlFor="password">
Password
</label>
<input
id="password"
name="password"
type="password"
required
minLength={8}
className={styles.input}
placeholder="Min. 8 characters"
/>
<label className={styles.label} htmlFor="confirm">
Confirm Password
<input
id="confirm"
name="confirm"
type="password"
required
minLength={8}
className={styles.input}
/>
</label>
<label className={styles.label} htmlFor="confirm">
Confirm Password
</label>
<input
id="confirm"
name="confirm"
type="password"
required
minLength={8}
className={styles.input}
/>
{error && <p className={styles.error}>{error}</p>}
{error && <p className={styles.error}>{error}</p>}
<button type="submit" disabled={loading} className={styles.button}>
{loading ? "Creating..." : "Create Admin Account"}
</button>
</form>
</div>
<button type="submit" disabled={loading} className={styles.button}>
{loading ? "Creating..." : "Create Admin Account"}
</button>
</form>
</div>
</div>
);
}
-24
View File
@@ -103,27 +103,3 @@
.button:hover { opacity: 0.9; }
.button:disabled { opacity: 0.5; cursor: not-allowed; }
.legacyNotice {
margin: 1.5rem 0;
padding: 1rem;
background: rgba(255, 191, 0, 0.05);
border: 1px solid rgba(255, 191, 0, 0.3);
text-align: left;
font-size: 0.8rem;
color: #ffbf00;
}
.legacyNotice strong {
display: block;
margin-bottom: 0.4rem;
}
.legacyNotice code {
display: block;
margin-top: 0.75rem;
padding: 0.5rem;
background: #000;
color: #0f0;
font-family: 'JetBrains Mono', monospace;
word-break: break-all;
}
+73 -51
View File
@@ -1,16 +1,24 @@
import React, { useState, useEffect } from "react";
import styles from "./page.module.css";
import { CameraStream } from "@/components/video/CameraStream";
import styles from "./page.module.css";
import type { TestResult } from "./types";
const LiveTimer = ({ start }: { start: number }) => {
const [now, setNow] = useState(Date.now());
function LiveTimer({ start }: { start?: number }) {
const [now, setNow] = useState(() => Date.now());
const [fallbackStart] = useState(() => Date.now());
const effectiveStart = start || fallbackStart;
useEffect(() => {
const interval = setInterval(() => setNow(Date.now()), 100);
return () => clearInterval(interval);
}, []);
return <span>{(Math.max(0, now - start) / 1000).toFixed(1)}s</span>;
};
return (
<span>
{(Math.max(0, now - effectiveStart) / 1000).toFixed(1)}
s
</span>
);
}
interface CameraTestCardProps {
result: TestResult;
@@ -21,8 +29,12 @@ interface CameraTestCardProps {
onRetest: (globalIndex: number) => void;
}
export function CameraTestCard({ result, index, globalIndex, previewId, onSetPreview, onRetest }: CameraTestCardProps) {
const { feature, status, httpStatus, contentType, latencyMs, errorMsg } = result;
export function CameraTestCard({
result, index, globalIndex, previewId, onSetPreview, onRetest
}: CameraTestCardProps) {
const {
feature, status, httpStatus, contentType, latencyMs, errorMsg
} = result;
const { stream, name, source } = feature.properties;
const id = stream + index.toString();
@@ -33,69 +45,79 @@ export function CameraTestCard({ result, index, globalIndex, previewId, onSetPre
else if (status === "testing") statusClass += ` ${styles.badgeTesting}`;
return (
<div className={styles.card}>
<div className={styles.cardHeader}>
<h3 className={styles.title} title={name}>{name || "Unknown Camera"}</h3>
<span className={styles.badge}>{source}</span>
</div>
<div className={styles.card}>
<div className={styles.cardHeader}>
<h3 className={styles.title} title={name}>{name || "Unknown Camera"}</h3>
<span className={styles.badge}>{source}</span>
</div>
<div className={styles.badges}>
<span className={statusClass}>
{status === "testing" ? (
<>Testing... <LiveTimer start={result.testStartTime || Date.now()} /></>
<div className={styles.badges}>
<span className={statusClass}>
{status === "testing" ? (
<>
Testing...
<LiveTimer start={result.testStartTime} />
</>
) : (
status.toUpperCase()
)}
{httpStatus && ` (${httpStatus})`}
</span>
{latencyMs !== undefined && <span className={styles.badge}>{latencyMs}ms</span>}
{contentType && <span className={styles.badge}>{contentType.split(';')[0]}</span>}
</div>
{httpStatus && ` (${httpStatus})`}
</span>
{latencyMs !== undefined && (
<span className={styles.badge}>
{latencyMs}
ms
</span>
)}
{contentType && <span className={styles.badge}>{contentType.split(';')[0]}</span>}
</div>
<div className={styles.url}>
{stream || "No stream URL"}
</div>
<div className={styles.url}>
{stream || "No stream URL"}
</div>
{errorMsg && <div className={styles.errorMsg}>{errorMsg}</div>}
{errorMsg && <div className={styles.errorMsg}>{errorMsg}</div>}
<div style={{ marginTop: 'auto', display: 'flex', gap: '0.5rem' }}>
<button
className={styles.button}
style={{
<div style={{ marginTop: 'auto', display: 'flex', gap: '0.5rem' }}>
<button
type="button"
className={styles.button}
style={{
padding: '0.4rem 0.8rem',
fontSize: '0.8rem',
flex: 1,
justifyContent: 'center',
background: 'rgba(255,255,255,0.1)'
}}
onClick={() => onRetest(globalIndex)}
>
🔄 Retest
</button>
<button
className={styles.button}
style={{
onClick={() => onRetest(globalIndex)}
>
🔄 Retest
</button>
<button
type="button"
className={styles.button}
style={{
padding: '0.4rem 0.8rem',
fontSize: '0.8rem',
flex: 2,
justifyContent: 'center',
background: previewId === id ? 'rgba(255,255,255,0.15)' : '#334155'
}}
onClick={() => onSetPreview(previewId === id ? null : id)}
disabled={!stream}
>
{previewId === id ? "Close Preview" : "Live Preview"}
</button>
</div>
{previewId === id && stream && (
<div className={styles.preview}>
<CameraStream
streamUrl={stream}
label={name}
/>
</div>
)}
onClick={() => onSetPreview(previewId === id ? null : id)}
disabled={!stream}
>
{previewId === id ? "Close Preview" : "Live Preview"}
</button>
</div>
{previewId === id && stream && (
<div className={styles.preview}>
<CameraStream
streamUrl={stream}
label={name}
/>
</div>
)}
</div>
);
}
+173 -96
View File
@@ -12,119 +12,195 @@ export default function CameraTestPage() {
const [testStatuses, setTestStatuses] = useState<string[]>(["all"]);
const [previewId, setPreviewId] = useState<string | null>(null);
const { cameras, loading, testing, runTests, stopTests, retestCamera } = useCameraTestRunner(testSources, testStatuses);
const {
cameras, loading, testing, runTests, stopTests, retestCamera
} = useCameraTestRunner(testSources, testStatuses);
const filtered = cameras.filter(c => {
const filtered = cameras.filter((c) => {
const sourceMatches = filterSources.includes("all") || filterSources.includes(c.feature.properties.source || "Unknown");
const statusMatches = filterStatuses.includes("all") || filterStatuses.includes(c.status);
return sourceMatches && statusMatches;
});
const handleMultiSelect = (e: React.ChangeEvent<HTMLSelectElement>, setter: React.Dispatch<React.SetStateAction<string[]>>) => {
const selected = Array.from(e.target.selectedOptions, o => o.value);
const selected = Array.from(e.target.selectedOptions, (o) => o.value);
if (selected.length === 0) setter(["all"]);
else setter(selected);
};
const stats = {
total: cameras.length,
ok: cameras.filter(c => c.status === "ok").length,
error: cameras.filter(c => c.status === "error").length,
timeout: cameras.filter(c => c.status === "timeout").length,
pending: cameras.filter(c => c.status === "pending").length,
testing: cameras.filter(c => c.status === "testing").length
ok: cameras.filter((c) => c.status === "ok").length,
error: cameras.filter((c) => c.status === "error").length,
timeout: cameras.filter((c) => c.status === "timeout").length,
pending: cameras.filter((c) => c.status === "pending").length,
testing: cameras.filter((c) => c.status === "testing").length
};
const dStats = {
total: filtered.length,
ok: filtered.filter(c => c.status === "ok").length,
error: filtered.filter(c => c.status === "error").length,
timeout: filtered.filter(c => c.status === "timeout").length,
pending: filtered.filter(c => c.status === "pending").length,
testing: filtered.filter(c => c.status === "testing").length
ok: filtered.filter((c) => c.status === "ok").length,
error: filtered.filter((c) => c.status === "error").length,
timeout: filtered.filter((c) => c.status === "timeout").length,
pending: filtered.filter((c) => c.status === "pending").length,
testing: filtered.filter((c) => c.status === "testing").length
};
const sources = Array.from(new Set(cameras.map(c => c.feature.properties.source || "Unknown"))).sort();
const sources = Array.from(new Set(cameras.map((c) => c.feature.properties.source || "Unknown"))).sort();
return (
<div className={styles.container}>
<div className={styles.header}>
<h1>Camera Stream Diagnostics</h1>
<p>Run parallel checks on all traffic camera streams to detect compatibility and offline issues.</p>
</div>
<div className={styles.container}>
<div className={styles.header}>
<h1>Camera Stream Diagnostics</h1>
<p>Run parallel checks on all traffic camera streams to detect compatibility and offline issues.</p>
</div>
<div className={styles.stats}>
<div className={styles.statCard}><h3>Total Cameras</h3><p>{stats.total} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.total} shown)</span></p></div>
<div className={styles.statCard}><h3>Responsive (OK)</h3><p className={styles.badgeOk} style={{ background: 'none', padding: 0, border: 'none' }}>{stats.ok} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.ok} shown)</span></p></div>
<div className={styles.statCard}><h3>Errors / Blocked</h3><p className={styles.badgeError} style={{ background: 'none', padding: 0, border: 'none' }}>{stats.error} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.error} shown)</span></p></div>
<div className={styles.statCard}><h3>Timeouts</h3><p className={styles.badgeWarn} style={{ background: 'none', padding: 0, border: 'none' }}>{stats.timeout} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.timeout} shown)</span></p></div>
<div className={styles.statCard}><h3>Pending</h3><p className={stats.testing > 0 ? styles.badgeTesting : ''} style={{ background: 'none', padding: 0, border: 'none', color: stats.testing > 0 ? '#60a5fa' : 'inherit' }}>{stats.pending + stats.testing} <span style={{ fontSize: '0.8rem', opacity: 0.7 }}>({dStats.pending + dStats.testing} shown)</span></p></div>
</div>
<div className={styles.stats}>
<div className={styles.statCard}>
<h3>Total Cameras</h3>
<p>
{stats.total}
{' '}
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
(
{dStats.total}
{' '}
shown)
</span>
</p>
</div>
<div className={styles.statCard}>
<h3>Responsive (OK)</h3>
<p className={styles.badgeOk} style={{ background: 'none', padding: 0, border: 'none' }}>
{stats.ok}
{' '}
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
(
{dStats.ok}
{' '}
shown)
</span>
</p>
</div>
<div className={styles.statCard}>
<h3>Errors / Blocked</h3>
<p className={styles.badgeError} style={{ background: 'none', padding: 0, border: 'none' }}>
{stats.error}
{' '}
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
(
{dStats.error}
{' '}
shown)
</span>
</p>
</div>
<div className={styles.statCard}>
<h3>Timeouts</h3>
<p className={styles.badgeWarn} style={{ background: 'none', padding: 0, border: 'none' }}>
{stats.timeout}
{' '}
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
(
{dStats.timeout}
{' '}
shown)
</span>
</p>
</div>
<div className={styles.statCard}>
<h3>Pending</h3>
<p
className={stats.testing > 0 ? styles.badgeTesting : ''}
style={{
background: 'none', padding: 0, border: 'none', color: stats.testing > 0 ? '#60a5fa' : 'inherit'
}}
>
{stats.pending + stats.testing}
{' '}
<span style={{ fontSize: '0.8rem', opacity: 0.7 }}>
(
{dStats.pending + dStats.testing}
{' '}
shown)
</span>
</p>
</div>
</div>
<div className={styles.controls} style={{ borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '1.5rem', marginBottom: '0.5rem', alignItems: 'flex-start' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
<span style={{ fontWeight: 600 }}>Target Tests:</span>
<span style={{ fontSize: '0.75rem', opacity: 0.7 }}>Hold Ctrl/Cmd to select multiple</span>
</div>
<div
className={styles.controls}
style={{
borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '1.5rem', marginBottom: '0.5rem', alignItems: 'flex-start'
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
<span style={{ fontWeight: 600 }}>Target Tests:</span>
<span style={{ fontSize: '0.75rem', opacity: 0.7 }}>Hold Ctrl/Cmd to select multiple</span>
</div>
<select multiple className={styles.select} style={{ height: '120px' }} value={testSources} onChange={e => handleMultiSelect(e, setTestSources)} disabled={testing}>
<option value="all">🌍 All Sources</option>
{sources.map(src => (
<option key={src as string} value={src as string}>
{String(src).toUpperCase()}
</option>
<select multiple className={styles.select} style={{ height: '120px' }} value={testSources} onChange={(e) => handleMultiSelect(e, setTestSources)} disabled={testing}>
<option value="all">🌍 All Sources</option>
{sources.map((src) => (
<option key={src as string} value={src as string}>
{String(src).toUpperCase()}
</option>
))}
</select>
</select>
<select multiple className={styles.select} style={{ height: '120px' }} value={testStatuses} onChange={e => handleMultiSelect(e, setTestStatuses)} disabled={testing}>
<option value="all">🔍 All Statuses</option>
<option value="ok">✅ OK</option>
<option value="error">❌ Error</option>
<option value="timeout">⏱️ Timeout</option>
<option value="pending">⏳ Pending</option>
</select>
<select multiple className={styles.select} style={{ height: '120px' }} value={testStatuses} onChange={(e) => handleMultiSelect(e, setTestStatuses)} disabled={testing}>
<option value="all">🔍 All Statuses</option>
<option value="ok">✅ OK</option>
<option value="error">❌ Error</option>
<option value="timeout">⏱️ Timeout</option>
<option value="pending">⏳ Pending</option>
</select>
{loading ? (
<button className={styles.button} disabled>
<span>Loading Cameras...</span>
</button>
{loading ? (
<button type="button" className={styles.button} disabled>
<span>Loading Cameras...</span>
</button>
) : testing ? (
<button className={styles.button} onClick={stopTests} style={{ background: '#ef4444' }}>
🛑 Stop Tests
</button>
<button type="button" className={styles.button} onClick={stopTests} style={{ background: '#ef4444' }}>
🛑 Stop Tests
</button>
) : (
<button className={styles.button} onClick={runTests} disabled={cameras.length === 0}>
▶ Run Tests
</button>
<button type="button" className={styles.button} onClick={runTests} disabled={cameras.length === 0}>
▶ Run Tests
</button>
)}
</div>
</div>
<div className={styles.controls} style={{ alignItems: 'flex-start' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
<span style={{ fontWeight: 600 }}>Display View:</span>
<span style={{ fontSize: '0.75rem', opacity: 0.7 }}>Hold Ctrl/Cmd to select multiple</span>
</div>
<div className={styles.controls} style={{ alignItems: 'flex-start' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
<span style={{ fontWeight: 600 }}>Display View:</span>
<span style={{ fontSize: '0.75rem', opacity: 0.7 }}>Hold Ctrl/Cmd to select multiple</span>
</div>
<select multiple className={styles.select} style={{ height: '140px' }} value={filterSources} onChange={e => handleMultiSelect(e, setFilterSources)}>
<option value="all">🌍 Show All Sources</option>
{sources.map(src => (
<option key={src as string} value={src as string}>
{String(src).toUpperCase()}
</option>
<select multiple className={styles.select} style={{ height: '140px' }} value={filterSources} onChange={(e) => handleMultiSelect(e, setFilterSources)}>
<option value="all">🌍 Show All Sources</option>
{sources.map((src) => (
<option key={src as string} value={src as string}>
{String(src).toUpperCase()}
</option>
))}
</select>
</select>
<select multiple className={styles.select} style={{ height: '140px' }} value={filterStatuses} onChange={e => handleMultiSelect(e, setFilterStatuses)}>
<option value="all">🔍 Show All Statuses</option>
<option value="ok">✅ OK</option>
<option value="error">❌ Error</option>
<option value="timeout">⏱️ Timeout</option>
<option value="pending">⏳ Pending</option>
<option value="testing">🔄 Testing</option>
</select>
<select multiple className={styles.select} style={{ height: '140px' }} value={filterStatuses} onChange={(e) => handleMultiSelect(e, setFilterStatuses)}>
<option value="all">🔍 Show All Statuses</option>
<option value="ok">✅ OK</option>
<option value="error">❌ Error</option>
<option value="timeout">⏱️ Timeout</option>
<option value="pending">⏳ Pending</option>
<option value="testing">🔄 Testing</option>
</select>
<button className={styles.button} style={{ background: 'rgba(255,255,255,0.1)', marginLeft: 'auto' }} onClick={() => {
const exportData = cameras.map(c => ({
<button
type="button"
className={styles.button}
style={{ background: 'rgba(255,255,255,0.1)', marginLeft: 'auto' }}
onClick={() => {
const exportData = cameras.map((c) => ({
id: c.feature.properties.name,
source: c.feature.properties.source,
url: c.feature.properties.stream,
@@ -139,24 +215,25 @@ export default function CameraTestPage() {
a.href = url;
a.download = `camera-diagnostics-${new Date().toISOString().split('T')[0]}.json`;
a.click();
}}>
⬇ Export Report
</button>
</div>
<div className={styles.grid}>
{filtered.map((c, i) => (
<CameraTestCard
key={c.feature.properties.stream + i}
result={c}
index={i}
globalIndex={cameras.indexOf(c)}
previewId={previewId}
onSetPreview={setPreviewId}
onRetest={retestCamera}
/>
))}
</div>
}}
>
⬇ Export Report
</button>
</div>
<div className={styles.grid}>
{filtered.map((c, i) => (
<CameraTestCard
key={c.feature.properties.stream + i}
result={c}
index={i}
globalIndex={cameras.indexOf(c)}
previewId={previewId}
onSetPreview={setPreviewId}
onRetest={retestCamera}
/>
))}
</div>
</div>
);
}
+52 -37
View File
@@ -1,5 +1,8 @@
import { useState, useRef, useEffect, useCallback } from "react";
import {
useState, useRef, useEffect, useCallback
} from "react";
import type { TestResult } from "./types";
import type { GdotCameraFeature } from "@/app/api/camera/gdot/gdotFetcher";
export function useCameraTestRunner(testSources: string[], testStatuses: string[]) {
const [cameras, setCameras] = useState<TestResult[]>([]);
@@ -13,44 +16,48 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
const res = await fetch("/api/camera/traffic");
const data = await res.json();
let staticFeatures: any[] = [];
let staticFeatures: GdotCameraFeature[] = [];
try {
const staticRes = await fetch("/public-cameras.json");
if (staticRes.ok) {
const staticData = await staticRes.json();
if (staticData.features) {
staticFeatures = staticData.features.map((f: any) => ({
...f,
properties: {
...f.properties,
name: f.properties.city || f.properties.region || "Public Camera",
source: f.properties.source || "cameras_json"
}
}));
staticFeatures = staticData.features.map((f: Record<string, unknown>) => {
const props = (f.properties || {}) as Record<string, unknown>;
return {
...f,
properties: {
...props,
name: props.city || props.region || "Public Camera",
source: props.source || "cameras_json"
}
} as unknown as GdotCameraFeature;
});
}
}
} catch (staticErr) {
console.error("Failed to fetch static cameras:", staticErr);
void staticErr; // Ignore static fetch errors
}
let combinedFeatures: any[] = [];
let combinedFeatures: GdotCameraFeature[] = [];
if (data.cameras) {
combinedFeatures = [...data.cameras];
}
combinedFeatures = [...combinedFeatures, ...staticFeatures];
setCameras(combinedFeatures.map((c: any) => ({
setCameras(combinedFeatures.map((c: GdotCameraFeature) => ({
feature: c,
status: "pending"
})));
} catch (err) {
console.error(err);
void err; // Ignore errors
}
setLoading(false);
}, []);
useEffect(() => {
fetchCameras();
// eslint-disable-next-line react-hooks/set-state-in-effect
void fetchCameras();
}, [fetchCameras]);
const runTests = async () => {
@@ -61,7 +68,7 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
abortControllerRef.current.abort();
}
abortControllerRef.current = new AbortController();
const signal = abortControllerRef.current.signal;
const {signal} = abortControllerRef.current;
const maxConcurrent = 20;
let index = 0;
@@ -75,10 +82,12 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
return sourceMatches && statusMatches;
});
setCameras(prev => {
setCameras((prev) => {
const nextState = [...prev];
for (const { originalIndex } of itemsToTest) {
nextState[originalIndex] = { ...nextState[originalIndex], status: "pending", testStartTime: undefined, latencyMs: undefined, errorMsg: undefined, httpStatus: undefined, contentType: undefined };
nextState[originalIndex] = {
...nextState[originalIndex], status: "pending", testStartTime: undefined, latencyMs: undefined, errorMsg: undefined, httpStatus: undefined, contentType: undefined
};
}
return nextState;
});
@@ -90,15 +99,16 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
return;
}
while (active < maxConcurrent && index < itemsToTest.length) {
const item = itemsToTest[index++];
const item = itemsToTest[index];
index += 1;
const currentIndex = item.originalIndex;
active++;
active += 1;
const cam = item.c;
let streamUrl = cam.feature.properties.stream;
const streamUrl = cam.feature.properties.stream;
if (!streamUrl) {
setCameras(prev => {
setCameras((prev) => {
const nextState = [...prev];
nextState[currentIndex] = {
...nextState[currentIndex],
@@ -107,21 +117,21 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
};
return nextState;
});
active--;
active -= 1;
next();
continue;
}
setCameras(prev => {
setCameras((prev) => {
const nextState = [...prev];
nextState[currentIndex] = { ...nextState[currentIndex], status: "testing", testStartTime: Date.now() };
return nextState;
});
fetch(`/api/camera/test?url=${encodeURIComponent(streamUrl)}`, { signal })
.then(res => res.json())
.then(data => {
setCameras(prev => {
.then((res) => res.json())
.then((data) => {
setCameras((prev) => {
const nextState = [...prev];
const isOk = data.status === 200 || data.status === 204 || data.status === 206;
nextState[currentIndex] = {
@@ -135,9 +145,9 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
return nextState;
});
})
.catch(err => {
.catch((err) => {
if (err.name === 'AbortError') return;
setCameras(prev => {
setCameras((prev) => {
const nextState = [...prev];
nextState[currentIndex] = {
...nextState[currentIndex],
@@ -148,7 +158,7 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
});
})
.finally(() => {
active--;
active -= 1;
next();
});
}
@@ -175,16 +185,18 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
const streamUrl = cam.feature.properties.stream;
if (!streamUrl) return;
setCameras(prev => {
setCameras((prev) => {
const nextState = [...prev];
nextState[globalIndex] = { ...nextState[globalIndex], status: "testing", testStartTime: Date.now(), latencyMs: undefined, errorMsg: undefined, httpStatus: undefined, contentType: undefined };
nextState[globalIndex] = {
...nextState[globalIndex], status: "testing", testStartTime: Date.now(), latencyMs: undefined, errorMsg: undefined, httpStatus: undefined, contentType: undefined
};
return nextState;
});
try {
const res = await fetch(`/api/camera/test?url=${encodeURIComponent(streamUrl)}`);
const data = await res.json();
setCameras(prev => {
setCameras((prev) => {
const nextState = [...prev];
const isOk = data.status === 200 || data.status === 204 || data.status === 206;
nextState[globalIndex] = {
@@ -197,18 +209,21 @@ export function useCameraTestRunner(testSources: string[], testStatuses: string[
};
return nextState;
});
} catch (err: any) {
setCameras(prev => {
} catch (err: unknown) {
const errorMsg = err instanceof Error ? err.message : String(err);
setCameras((prev) => {
const nextState = [...prev];
nextState[globalIndex] = {
...nextState[globalIndex],
status: "error",
errorMsg: err.message
errorMsg
};
return nextState;
});
}
};
return { cameras, loading, testing, runTests, stopTests, retestCamera };
return {
cameras, loading, testing, runTests, stopTests, retestCamera
};
}
+37 -20
View File
@@ -2,7 +2,7 @@
/**
* @file AdUnit.tsx
* @description Standardized Google AdSense wrapper component.
* @description Standardized Google AdSense wrapper component.
* Handles client-side script pushing and provides a development-mode mock UI.
* @module src/components/ads
*/
@@ -19,23 +19,25 @@ interface AdUnitProps {
/**
* @component AdUnit
* @description Renders a Google AdSense advertisement unit.
*
*
* @param {AdUnitProps} props - Component properties.
* @param {string} props.adSlot - The AdSense slot ID.
* @param {string} [props.adFormat="auto"] - The AdSense format (auto, rectangle, etc).
* @param {React.CSSProperties} [props.style] - Optional inline styles for the container.
* @param {string} [props.className] - Optional CSS class for the container.
*/
export function AdUnit({ adSlot, adFormat = "auto", style, className }: AdUnitProps) {
export function AdUnit({
adSlot, adFormat, style, className
}: AdUnitProps) {
const insRef = useRef<HTMLModElement>(null);
const pushed = useRef(false);
const clientId = process.env.NEXT_PUBLIC_ADSENSE_CLIENT_ID;
useEffect(() => {
if (pushed.current || !clientId) return;
// Next.js Dev / CSS injection often causes a brief moment where
// the ad container has 0 width. Wait until the browser calculates
// the ad container has 0 width. Wait until the browser calculates
// the true CSS width before asking AdSense to fetch an ad.
const timer = setInterval(() => {
if (insRef.current && insRef.current.offsetWidth > 0) {
@@ -62,24 +64,39 @@ export function AdUnit({ adSlot, adFormat = "auto", style, className }: AdUnitPr
// Google AdSense natively returns 400 Bad Request if requested from localhost.
if (process.env.NODE_ENV === "development") {
return (
<div className={className} style={{ ...style, display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "rgba(255, 255, 255, 0.05)", color: "#888", fontSize: "12px", border: "1px dashed rgba(255, 255, 255, 0.1)", textAlign: "center", padding: "1rem", minHeight: "250px" }}>
<span>AdSense Mock<br/>(Disabled on Localhost)</span>
</div>
<div
className={className}
style={{
...style, display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "rgba(255, 255, 255, 0.05)", color: "#888", fontSize: "12px", border: "1px dashed rgba(255, 255, 255, 0.1)", textAlign: "center", padding: "1rem", minHeight: "250px"
}}
>
<span>
AdSense Mock
<br />
(Disabled on Localhost)
</span>
</div>
);
}
return (
<div className={className} style={style}>
<ins
ref={insRef}
className="adsbygoogle"
style={{ display: "block" }}
data-ad-client={clientId}
data-ad-slot={adSlot}
data-ad-format={adFormat}
data-full-width-responsive="true"
data-adtest="on"
/>
</div>
<div className={className} style={style}>
<ins
ref={insRef}
className="adsbygoogle"
style={{ display: "block" }}
data-ad-client={clientId}
data-ad-slot={adSlot}
data-ad-format={adFormat}
data-full-width-responsive="true"
data-adtest="on"
/>
</div>
);
}
AdUnit.defaultProps = {
adFormat: "auto",
style: {},
className: "",
};
+47 -48
View File
@@ -2,7 +2,7 @@
/**
* @file DemoAdStrip.tsx
* @description specialized sidebar for the demo edition that hosts AdSense
* @description specialized sidebar for the demo edition that hosts AdSense
* units and a small banner explaining the monetization model.
* @module src/components/ads
*/
@@ -10,8 +10,8 @@
import React, { useState, useEffect } from "react";
import { isDemo } from "@/core/edition";
import { dataBus } from "@/core/data/DataBus";
import { AdUnit } from "./AdUnit";
import { X } from "lucide-react";
import { AdUnit } from "./AdUnit";
import "./DemoAdStrip.css";
/** Ad slot IDs — replace with your AdSense slot IDs. */
@@ -68,63 +68,62 @@ export function DemoAdStrip() {
if (!isDemo || !ENABLE_ADS) return null;
return (
<aside
className="demo-ad-strip"
aria-label="Sponsored content"
style={{
opacity: isReady ? 1 : 0,
<aside
className="demo-ad-strip"
aria-label="Sponsored content"
style={{
opacity: isReady ? 1 : 0,
pointerEvents: isReady ? "auto" : "none",
transition: "opacity 1200ms var(--ease-smooth)"
transition: "opacity 1200ms var(--ease-smooth)"
}}
>
<AdUnit
adSlot={TOP_AD_SLOT}
adFormat="auto"
className="demo-ad-strip__ad"
/>
{!isShortScreen && (
<AdUnit
adSlot={BOTTOM_AD_SLOT}
adFormat="auto"
className="demo-ad-strip__ad"
/>
>
<AdUnit
adSlot={TOP_AD_SLOT}
adFormat="auto"
className="demo-ad-strip__ad"
/>
{!isShortScreen && (
<AdUnit
adSlot={BOTTOM_AD_SLOT}
adFormat="auto"
className="demo-ad-strip__ad"
/>
)}
{!bannerDismissed && (
<div
className="demo-ad-strip__banner"
onClick={() => setShowMessage((prev) => !prev)}
role="button"
tabIndex={0}
onKeyDown={(e: React.KeyboardEvent<HTMLDivElement>) => {
{!bannerDismissed && (
<div
className="demo-ad-strip__banner"
onClick={() => setShowMessage((prev) => !prev)}
role="button"
tabIndex={0}
onKeyDown={(e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === "Enter") setShowMessage((prev) => !prev);
}}
>
<button
className="demo-ad-strip__close"
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
>
<button
className="demo-ad-strip__close"
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
setBannerDismissed(true);
}}
aria-label="Dismiss banner"
>
<X size={12} />
</button>
<span className="demo-ad-strip__banner-label">Why ads?</span>
{showMessage ? (
<span className="demo-ad-strip__banner-text">
This isn&apos;t permanent — it&apos;s temporary
because I&apos;m a single dev and need to cover
hosting costs. Thank you for understanding.
</span>
aria-label="Dismiss banner"
>
<X size={12} />
</button>
<span className="demo-ad-strip__banner-label">Why ads?</span>
{showMessage ? (
<span className="demo-ad-strip__banner-text">
This isn&apos;t permanent — it&apos;s temporary
because I&apos;m a single dev and need to cover
hosting costs. Thank you for understanding.
</span>
) : (
<span className="demo-ad-strip__banner-text">
Click to learn more
</span>
<span className="demo-ad-strip__banner-text">
Click to learn more
</span>
)}
</div>
</div>
)}
</aside>
</aside>
);
}
+13 -13
View File
@@ -20,23 +20,23 @@ interface BootOverlayProps {
/**
* @component BootOverlay
* @description Animated splash screen for initial system boot.
*
*
* @param {BootOverlayProps} props - Component properties.
*/
export function BootOverlay({ visible }: BootOverlayProps) {
return (
<div className={`boot-overlay ${visible ? "" : "boot-overlay--hidden"}`}>
{/* Orbital rings */}
<div className="boot-overlay__rings">
<div className="boot-overlay__ring boot-overlay__ring--1" />
<div className="boot-overlay__ring boot-overlay__ring--2" />
<div className="boot-overlay__ring boot-overlay__ring--3" />
<div className="boot-overlay__core" />
</div>
{/* Brand + status */}
<div className="boot-overlay__title">WorldWideView</div>
<div className="boot-overlay__status">Initializing Systems...</div>
<div className={`boot-overlay ${visible ? "" : "boot-overlay--hidden"}`}>
{/* Orbital rings */}
<div className="boot-overlay__rings">
<div className="boot-overlay__ring boot-overlay__ring--1" />
<div className="boot-overlay__ring boot-overlay__ring--2" />
<div className="boot-overlay__ring boot-overlay__ring--3" />
<div className="boot-overlay__core" />
</div>
{/* Brand + status */}
<div className="boot-overlay__title">WorldWideView</div>
<div className="boot-overlay__status">Initializing Systems...</div>
</div>
);
}
+18 -13
View File
@@ -15,22 +15,27 @@ interface DiscordIconProps {
/**
* Renders the Discord logo as an SVG.
*
*
* @param props - Component properties.
* @returns React component rendering the Discord icon.
*/
export function DiscordIcon({ size = 18, className }: DiscordIconProps) {
export function DiscordIcon({ size, className }: DiscordIconProps) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="currentColor"
className={className}
aria-hidden="true"
>
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.947 2.418-2.157 2.418z" />
</svg>
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="currentColor"
className={className}
aria-hidden="true"
>
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.947 2.418-2.157 2.418z" />
</svg>
);
}
DiscordIcon.defaultProps = {
size: 18,
className: "",
};
+183 -154
View File
@@ -1,7 +1,7 @@
/**
* @file FeedbackDialog.tsx
* @description A comprehensive feedback and bug reporting interface.
* Supports categorization, screenshot capture via getDisplayMedia,
* Supports categorization, screenshot capture via getDisplayMedia,
* file uploads, and automatic diagnostic log attachment.
*/
@@ -9,16 +9,17 @@
import React, { useState, useEffect, useRef } from "react";
import { X, Paperclip, Upload } from "lucide-react";
import Image from "next/image";
import { useStore } from "@/core/state/store";
import { getCapturedLogs } from "@/lib/logCatcher";
import styles from "./FeedbackDialog.module.css";
import { trackEvent } from "@/lib/analytics";
import styles from "./FeedbackDialog.module.css";
/**
* A modal dialog that allows users to submit bug reports, feature requests,
* and general feedback. The component captures application state, diagnostic
* A modal dialog that allows users to submit bug reports, feature requests,
* and general feedback. The component captures application state, diagnostic
* logs, and user-provided visuals to facilitate debugging.
*
*
* @returns React component for the feedback portal.
*/
export function FeedbackDialog() {
@@ -30,18 +31,18 @@ export function FeedbackDialog() {
const [description, setDescription] = useState("");
const [steps, setSteps] = useState("");
const [attachLogs, setAttachLogs] = useState(true);
const [email, setEmail] = useState("");
const [email, setEmail] = useState(() => {
if (typeof window !== "undefined") {
return localStorage.getItem("wwv_feedback_email") || "";
}
return "";
});
const [screenshots, setScreenshots] = useState<string[]>([]);
const [takingScreenshot, setTakingScreenshot] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const savedEmail = localStorage.getItem("wwv_feedback_email");
if (savedEmail) {
setEmail(savedEmail);
}
}, []);
// Initial state set via useState initializer
const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newEmail = e.target.value;
@@ -53,44 +54,42 @@ export function FeedbackDialog() {
const files = Array.from(e.target.files || []);
if (files.length === 0) return;
const readers = files.map(file => {
return new Promise<string>((resolve) => {
const readers = files.map((file) => new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve((event.target?.result as string) || "");
};
reader.readAsDataURL(file);
});
}));
Promise.all(readers).then((dataUrls) => {
setScreenshots((prev) => [...prev, ...dataUrls.filter(Boolean)]);
});
Promise.all(readers).then(dataUrls => {
setScreenshots(prev => [...prev, ...dataUrls.filter(Boolean)]);
});
// Reset input
e.target.value = "";
};
const handleTakeScreenshot = async () => {
setTakingScreenshot(true);
// Wait for React to render the hidden dialog state
await new Promise(r => setTimeout(r, 50));
await new Promise((r) => { setTimeout(r, 50); });
try {
// @ts-ignore - preferCurrentTab is a recent addition
// @ts-expect-error - preferCurrentTab is a recent addition
const stream = await navigator.mediaDevices.getDisplayMedia({ video: { preferCurrentTab: true } });
const video = document.createElement("video");
video.srcObject = stream;
video.play();
await new Promise((resolve) => {
video.onloadedmetadata = resolve;
});
// Wait 800ms to allow the browser's native "Choose what to share" dialog
// Wait 800ms to allow the browser's native "Choose what to share" dialog
// to completely finish its fade-out animation from the OS before we capture the frame.
await new Promise(r => setTimeout(r, 800));
await new Promise((r) => { setTimeout(r, 800); });
const canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
@@ -98,10 +97,10 @@ export function FeedbackDialog() {
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
setScreenshots(prev => [...prev, canvas.toDataURL("image/jpeg", 0.9)]);
setScreenshots((prev) => [...prev, canvas.toDataURL("image/jpeg", 0.9)]);
}
stream.getTracks().forEach(t => t.stop());
stream.getTracks().forEach((t) => t.stop());
} catch (err) {
console.error("Screen capture failed or was cancelled:", err);
} finally {
@@ -110,7 +109,7 @@ export function FeedbackDialog() {
};
const removeScreenshot = (index: number) => {
setScreenshots(prev => prev.filter((_, i) => i !== index));
setScreenshots((prev) => prev.filter((_, i) => i !== index));
};
if (!feedbackDialogOpen || takingScreenshot) return null;
@@ -119,7 +118,7 @@ export function FeedbackDialog() {
const handleSubmit = async () => {
if (!isFormValid) return;
setIsSubmitting(true);
try {
const payload = {
@@ -134,7 +133,7 @@ export function FeedbackDialog() {
};
const webhookUrl = process.env.NEXT_PUBLIC_FEEDBACK_WEBHOOK_URL || "https://n8n.arfquant.com/webhook/feedback";
const response = await fetch(webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -162,139 +161,169 @@ export function FeedbackDialog() {
};
return (
<div className={styles.overlay} onClick={() => setFeedbackDialogOpen(false)}>
<div className={styles.dialog} onClick={(e) => e.stopPropagation()}>
<div className={styles.header}>
<div className={styles.title}>Provide Feedback</div>
<button className={styles.closeButton} onClick={() => setFeedbackDialogOpen(false)}>
<X size={18} />
</button>
</div>
<div
className={styles.overlay}
onClick={() => setFeedbackDialogOpen(false)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
setFeedbackDialogOpen(false);
}
}}
role="button"
tabIndex={0}
aria-label="Close dialog"
>
<div
className={styles.dialog}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
role="presentation"
>
<div className={styles.header}>
<div className={styles.title}>Provide Feedback</div>
<button type="button" className={styles.closeButton} onClick={() => setFeedbackDialogOpen(false)}>
<X size={18} />
</button>
</div>
<div className={styles.content}>
<div className={styles.section}>
<div className={styles.label}>Feedback Type</div>
<div className={styles.radioGroup}>
{["Bug Report", "Feature Request", "Auth and Billing", "General Feedback"].map((opt) => (
<label key={opt} className={styles.radioOption}>
<input
type="radio"
name="feedbackType"
value={opt}
checked={type === opt}
onChange={(e) => setType(e.target.value)}
className={styles.radioInput}
/>
<span className={styles.radioLabel}>{opt}</span>
</label>
<div className={styles.content}>
<div className={styles.section}>
<div className={styles.label}>Feedback Type</div>
<div className={styles.radioGroup}>
{["Bug Report", "Feature Request", "Auth and Billing", "General Feedback"].map((opt) => (
<label key={opt} className={styles.radioOption}>
<input
type="radio"
name="feedbackType"
value={opt}
checked={type === opt}
onChange={(e) => setType(e.target.value)}
className={styles.radioInput}
/>
<span className={styles.radioLabel}>{opt}</span>
</label>
))}
</div>
</div>
</div>
</div>
<div className={styles.section}>
<div className={styles.label}>Description</div>
<div className={styles.description}>
Please describe the issue in detail. The more actionable your feedback, the quicker our team can address your request. Some helpful information includes:
<ul className={styles.descriptionList}>
<li>Steps to reproduce the issue</li>
<li>Expected behavior</li>
<li>Actual behavior</li>
<li>Any error messages</li>
<li>Any relevant information</li>
</ul>
</div>
<div className={styles.textareaContainer}>
<textarea
className={styles.textarea}
placeholder="Describe the bug you encountered..."
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div className={`${styles.charCount} ${isFormValid ? styles.valid : ""}`}>
{description.length}/50
</div>
</div>
</div>
<div className={styles.section}>
<div className={styles.label}>Description</div>
<div className={styles.description}>
Please describe the issue in detail. The more actionable your feedback, the quicker our team can address your request. Some helpful information includes:
<ul className={styles.descriptionList}>
<li>Steps to reproduce the issue</li>
<li>Expected behavior</li>
<li>Actual behavior</li>
<li>Any error messages</li>
<li>Any relevant information</li>
</ul>
</div>
<div className={styles.textareaContainer}>
<textarea
className={styles.textarea}
placeholder="Describe the bug you encountered..."
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div className={`${styles.charCount} ${isFormValid ? styles.valid : ""}`}>
{description.length}
/50
</div>
</div>
</div>
<div className={styles.section}>
<div className={styles.label}>Steps to Reproduce</div>
<div className={styles.textareaContainer}>
<textarea
className={styles.textarea}
placeholder="Please list the steps to reproduce the issue"
value={steps}
onChange={(e) => setSteps(e.target.value)}
style={{ minHeight: "80px" }}
/>
</div>
</div>
<div className={styles.section}>
<div className={styles.label}>Steps to Reproduce</div>
<div className={styles.textareaContainer}>
<textarea
className={styles.textarea}
placeholder="Please list the steps to reproduce the issue"
value={steps}
onChange={(e) => setSteps(e.target.value)}
style={{ minHeight: "80px" }}
/>
</div>
</div>
<div className={styles.checkboxGroup}>
{screenshots.length > 0 && (
<div className={styles.previewList}>
{screenshots.map((src, i) => (
<div key={i} className={styles.previewContainer}>
<img src={src} alt={`Screenshot ${i + 1}`} className={styles.previewImage} />
<button className={styles.removeScreenshot} onClick={() => removeScreenshot(i)} title="Remove screenshot">
<X size={10} strokeWidth={3} />
</button>
</div>
<div className={styles.checkboxGroup}>
{screenshots.length > 0 && (
<div className={styles.previewList}>
{screenshots.map((src, i) => (
<div key={i} className={styles.previewContainer}>
<Image
src={src}
alt={`Screenshot ${i + 1}`}
className={styles.previewImage}
width={100}
height={60}
unoptimized
/>
<button
type="button"
className={styles.removeScreenshot}
onClick={() => removeScreenshot(i)}
title="Remove screenshot"
>
<X size={10} strokeWidth={3} />
</button>
</div>
))}
</div>
</div>
)}
<div className={styles.actionRow}>
<button className={styles.attachAction} onClick={handleTakeScreenshot}>
<Paperclip size={16} />
<span>Take screenshot</span>
</button>
<button className={styles.attachAction} onClick={() => fileInputRef.current?.click()}>
<Upload size={16} />
<span>Upload image</span>
</button>
<input
type="file"
accept="image/*"
multiple
ref={fileInputRef}
style={{ display: "none" }}
onChange={handleFileUpload}
/>
</div>
<div className={styles.actionRow}>
<button type="button" className={styles.attachAction} onClick={handleTakeScreenshot}>
<Paperclip size={16} />
<span>Take screenshot</span>
</button>
<button type="button" className={styles.attachAction} onClick={() => fileInputRef.current?.click()}>
<Upload size={16} />
<span>Upload image</span>
</button>
<input
type="file"
accept="image/*"
multiple
ref={fileInputRef}
style={{ display: "none" }}
onChange={handleFileUpload}
/>
</div>
<label className={styles.checkboxOption}>
<input
type="checkbox"
checked={attachLogs}
onChange={(e) => setAttachLogs(e.target.checked)}
className={styles.checkboxInput}
/>
<span className={styles.checkboxLabel}>Attach WorldWideView diagnostic logs and information</span>
</label>
</div>
<div className={styles.section}>
<div className={styles.label}>Email Address</div>
<input
type="email"
className={styles.input}
placeholder="[email protected]"
value={email}
onChange={handleEmailChange}
/>
</div>
</div>
<div className={styles.footer}>
<button
className={`${styles.submitButton} ${isSubmitting ? styles.submitting : ""} ${isFormValid ? styles.enabled : ""}`}
onClick={handleSubmit}
disabled={isSubmitting || !isFormValid}
>
{isSubmitting ? "Submitting..." : "Submit"}
</button>
</div>
<label className={styles.checkboxOption}>
<input
type="checkbox"
checked={attachLogs}
onChange={(e) => setAttachLogs(e.target.checked)}
className={styles.checkboxInput}
/>
<span className={styles.checkboxLabel}>Attach WorldWideView diagnostic logs and information</span>
</label>
</div>
<div className={styles.section}>
<div className={styles.label}>Email Address</div>
<input
type="email"
className={styles.input}
placeholder="[email protected]"
value={email}
onChange={handleEmailChange}
/>
</div>
</div>
<div className={styles.footer}>
<button
type="button"
className={`${styles.submitButton} ${isSubmitting ? styles.submitting : ""} ${isFormValid ? styles.enabled : ""} `}
onClick={handleSubmit}
disabled={isSubmitting || !isFormValid}
>
{isSubmitting ? "Submitting..." : "Submit"}
</button>
</div>
</div>
</div>
);
}
+48 -40
View File
@@ -7,7 +7,9 @@
"use client";
import React, { useState, useEffect, useRef, useCallback } from "react";
import React, {
useState, useEffect, useRef, useCallback
} from "react";
import { X } from "lucide-react";
/**
@@ -38,7 +40,7 @@ interface FloatingWindowProps {
* @component FloatingWindow
* @description A floating, interactive container used for data streams and secondary tools.
* Implements a custom drag-and-resize engine compatible with both desktop and mobile.
*
*
* @param {FloatingWindowProps} props - Component properties.
*/
export const FloatingWindow: React.FC<FloatingWindowProps> = ({
@@ -85,7 +87,7 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
} else if (isResizing) {
const deltaX = e.clientX - dragStart.current.x;
const deltaY = e.clientY - dragStart.current.y;
setSize(prev => ({
setSize((prev) => ({
width: Math.max(minWidth, prev.width + deltaX),
height: Math.max(minHeight, prev.height + deltaY),
}));
@@ -138,7 +140,7 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
} else if (isResizing) {
const deltaX = touch.clientX - dragStart.current.x;
const deltaY = touch.clientY - dragStart.current.y;
setSize(prev => ({
setSize((prev) => ({
width: Math.max(minWidth, prev.width + deltaX),
height: Math.max(minHeight, prev.height + deltaY),
}));
@@ -170,9 +172,9 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
}, [isDragging, isResizing, handleTouchMove, handleTouchEnd]);
return (
<div
ref={windowRef}
style={{
<div
ref={windowRef}
style={{
position: "fixed",
left: pos.x,
top: pos.y,
@@ -190,10 +192,10 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
color: "white",
touchAction: "none", // prevent browser gestures on the window itself
}}
>
{/* Header / Title Bar */}
<div
style={{
>
{/* Header / Title Bar */}
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
@@ -204,17 +206,20 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
userSelect: "none",
touchAction: "none",
}}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStartDrag}
>
<span style={{ fontSize: "12px", fontWeight: 600, color: "rgba(255, 255, 255, 0.8)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{title}
</span>
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStartDrag}
>
<span style={{
fontSize: "12px", fontWeight: 600, color: "rgba(255, 255, 255, 0.8)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
}}
>
{title}
</span>
<div className="window-controls" style={{ display: "flex", gap: "8px" }}>
<button
onClick={onClose}
style={{
<div className="window-controls" style={{ display: "flex", gap: "8px" }}>
<button
onClick={onClose}
style={{
background: "none",
border: "none",
color: "rgba(255, 255, 255, 0.4)",
@@ -226,28 +231,28 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
borderRadius: "4px",
transition: "all 0.2s"
}}
onMouseEnter={(e) => {
onMouseEnter={(e) => {
e.currentTarget.style.color = "#ef4444";
e.currentTarget.style.backgroundColor = "rgba(239, 68, 68, 0.1)";
}}
onMouseLeave={(e) => {
onMouseLeave={(e) => {
e.currentTarget.style.color = "rgba(255, 255, 255, 0.4)";
e.currentTarget.style.backgroundColor = "transparent";
}}
>
<X size={14} />
</button>
</div>
</div>
>
<X size={14} />
</button>
</div>
</div>
{/* Content Area */}
<div style={{ flex: 1, position: "relative", overflow: "hidden" }}>
{children}
</div>
{/* Content Area */}
<div style={{ flex: 1, position: "relative", overflow: "hidden" }}>
{children}
</div>
{/* Resize Handle */}
<div
style={{
{/* Resize Handle */}
<div
style={{
position: "absolute",
bottom: 0,
right: 0,
@@ -261,11 +266,14 @@ export const FloatingWindow: React.FC<FloatingWindowProps> = ({
padding: "4px",
touchAction: "none",
}}
onMouseDown={handleResizeMouseDown}
onTouchStart={handleTouchStartResize}
>
<div style={{ width: "6px", height: "6px", backgroundColor: "rgba(255, 255, 255, 0.3)", borderRadius: "1px" }} />
</div>
onMouseDown={handleResizeMouseDown}
onTouchStart={handleTouchStartResize}
>
<div style={{
width: "6px", height: "6px", backgroundColor: "rgba(255, 255, 255, 0.3)", borderRadius: "1px"
}}
/>
</div>
</div>
);
};
+45 -44
View File
@@ -1,6 +1,6 @@
/**
* @file PannableView.tsx
* @description A high-performance 2D navigation container providing panning and
* @description A high-performance 2D navigation container providing panning and
* pinch-zoom capabilities for inner content.
* @module src/components/common
*/
@@ -26,7 +26,7 @@ const ZOOM_STEP = 0.15;
* @component PannableView
* @description Wraps content in a 2D viewport that supports infinite panning and multi-touch zoom.
* Ideal for secondary maps, floor plans, or large interactive diagrams.
*
*
* @param {PannableViewProps} props - Component properties.
*/
export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
@@ -38,7 +38,7 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
const activePointers = useRef<Map<number, { x: number; y: number }>>(new Map());
const initialPinchDistance = useRef<number | null>(null);
const initialPinchZoom = useRef<number>(1);
const containerRef = useRef<HTMLDivElement>(null);
const clampPan = useCallback((x: number, y: number, z: number) => {
@@ -82,7 +82,7 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
const handlePointerDown = useCallback((e: React.PointerEvent) => {
e.preventDefault();
(e.target as HTMLElement).setPointerCapture(e.pointerId);
activePointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (activePointers.current.size === 1) {
@@ -97,7 +97,7 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
setIsPanning(false); // disable single pan flag
initialPinchDistance.current = getPointersDistance(activePointers.current);
initialPinchZoom.current = zoom;
const center = getPointersCenter(activePointers.current);
dragStart.current = center;
panStart.current = { ...pan };
@@ -106,7 +106,7 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
const handlePointerMove = useCallback((e: React.PointerEvent) => {
if (!activePointers.current.has(e.pointerId)) return;
activePointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (activePointers.current.size === 1 && isPanning && containerRef.current) {
@@ -121,12 +121,12 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
const currentDistance = getPointersDistance(activePointers.current);
const scale = currentDistance / initialPinchDistance.current;
const newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, initialPinchZoom.current * scale));
const center = getPointersCenter(activePointers.current);
const rect = containerRef.current.getBoundingClientRect();
const dx = (((center.x - dragStart.current.x) / rect.width) * 100) / newZoom;
const dy = (((center.y - dragStart.current.y) / rect.height) * 100) / newZoom;
setZoom(newZoom);
if (newZoom <= 1) {
setPan({ x: 0, y: 0 });
@@ -138,11 +138,11 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
const handlePointerUp = useCallback((e: React.PointerEvent) => {
activePointers.current.delete(e.pointerId);
if (activePointers.current.size < 2) {
initialPinchDistance.current = null;
}
if (activePointers.current.size === 1) {
const remainingPointer = Array.from(activePointers.current.values())[0];
dragStart.current = { x: remainingPointer.x, y: remainingPointer.y };
@@ -157,7 +157,7 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
return currentZoom;
});
}
if (activePointers.current.size === 0) {
setIsPanning(false);
}
@@ -172,14 +172,14 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
const isZoomed = zoom > 1.01;
return (
<div
ref={containerRef}
onWheel={handleWheel}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
style={{
<div
ref={containerRef}
onWheel={handleWheel}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
style={{
width: "100%",
height: "100%",
overflow: "hidden",
@@ -188,9 +188,9 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
position: "relative",
userSelect: "none",
}}
>
<div
style={{
>
<div
style={{
width: "100%",
height: "100%",
transform: `scale(${zoom}) translate(${pan.x}%, ${pan.y}%)`,
@@ -200,13 +200,13 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
// If zoom > 1, we capture drags, so we may need pointer-events: none on children to avoid them eating the drag
pointerEvents: isZoomed ? "none" : "auto",
}}
>
{children}
</div>
>
{children}
</div>
{/* Zoom level indicator */}
{isZoomed && (
<div style={{
{/* Zoom level indicator */}
{isZoomed && (
<div style={{
position: "absolute",
bottom: 8,
left: 8,
@@ -219,17 +219,19 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
borderRadius: "var(--radius-sm)",
border: "1px solid var(--border-subtle)",
pointerEvents: "none",
}}>
{zoom.toFixed(1)}×
</div>
}}
>
{zoom.toFixed(1)}
×
</div>
)}
{/* Reset button */}
{isZoomed && (
<button
onClick={handleReset}
title="Reset zoom"
style={{
{/* Reset button */}
{isZoomed && (
<button
onClick={handleReset}
title="Reset zoom"
style={{
position: "absolute",
bottom: 8,
right: 8,
@@ -245,19 +247,18 @@ export const PannableView: React.FC<PannableViewProps> = ({ children }) => {
alignItems: "center",
justifyContent: "center",
}}
onMouseEnter={(e) => {
onMouseEnter={(e) => {
e.currentTarget.style.color = "var(--text-primary)";
e.currentTarget.style.background = "var(--bg-glass-hover)";
}}
onMouseLeave={(e) => {
onMouseLeave={(e) => {
e.currentTarget.style.color = "var(--text-secondary)";
e.currentTarget.style.background = "var(--bg-glass)";
}}
>
<RotateCcw size={12} />
</button>
>
<RotateCcw size={12} />
</button>
)}
</div>
</div>
);
};
@@ -29,8 +29,8 @@ interface State {
/**
* @component PluginErrorBoundary
* @description A standard React error boundary used to isolate failures in third-party
* or dynamic plugin components. When a crash occurs, the boundary renders
* @description A standard React error boundary used to isolate failures in third-party
* or dynamic plugin components. When a crash occurs, the boundary renders
* nothing (null), allowing the rest of the UI (sidebar, globe) to remain functional.
*/
export class PluginErrorBoundary extends Component<Props, State> {
+5 -5
View File
@@ -1,6 +1,6 @@
/**
* @file PluginIcon.tsx
* @description Central icon resolver for plugins. Supports Lucide string names,
* @description Central icon resolver for plugins. Supports Lucide string names,
* emoji fallbacks, and custom React component icons.
*/
@@ -15,8 +15,8 @@ const FallbackIcon = icons.Package;
* Props for the PluginIcon component.
*/
interface PluginIconProps {
/**
* The icon to render. Can be a Lucide icon name (e.g., "Airplay"),
/**
* The icon to render. Can be a Lucide icon name (e.g., "Airplay"),
* a raw emoji string, or a React component.
*/
icon: string | ComponentType<{ size?: number; color?: string }>;
@@ -28,9 +28,9 @@ interface PluginIconProps {
/**
* Renders a consistent icon representation for plugins.
* Dynamically resolves Lucide icons by name to allow plugins to declare
* Dynamically resolves Lucide icons by name to allow plugins to declare
* icons in their manifests without bundling dependencies.
*
*
* @param props - Component properties.
* @returns React component for the plugin icon.
*/
+4 -4
View File
@@ -88,11 +88,9 @@ function applyAction(msg: AgentMessage): void {
const entities = pluginManager.getEntities(msg.pluginId);
const entity = entities.find((e) => e.id === msg.entityId);
if (entity) dataBus.emit("entitySelected", { entity });
return;
}
case "ping":
// No-op — useful for an external tool to verify the channel is alive.
return;
}
}
@@ -103,8 +101,8 @@ export function AgentBusSubscriber() {
// of looking like a feature regression.
const buildId = process.env.NEXT_PUBLIC_WWV_BUILD_ID ?? "dev";
const builtAt = process.env.NEXT_PUBLIC_WWV_BUILD_AT ?? "";
const agentBusEnabled =
process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true";
const agentBusEnabled = process.env.NEXT_PUBLIC_WWV_AGENT_BUS_ENABLED === "true";
// eslint-disable-next-line no-console
console.log(
`[wwv build] id=${buildId} built_at=${builtAt} agent_bus=${agentBusEnabled ? "on" : "off"}`,
);
@@ -118,12 +116,14 @@ export function AgentBusSubscriber() {
const msg = JSON.parse(event.data) as AgentMessage;
applyAction(msg);
} catch (err) {
// eslint-disable-next-line no-console
console.warn("[AgentBus] malformed message", err);
}
};
es.onerror = (err) => {
// EventSource auto-reconnects on its own with the `retry:` value
// we send from the server. Just log; don't tear down.
// eslint-disable-next-line no-console
console.debug("[AgentBus] stream error (auto-reconnecting)", err);
};
+129 -123
View File
@@ -1,23 +1,28 @@
/**
* @file ApiKeysTab.tsx
* @description Manages user-provided API keys and license verification.
* Allows users to override default keys for services like Google Maps or
* Allows users to override default keys for services like Google Maps or
* proprietary data sources.
* @module src/components/layout
*/
import { useState, useCallback, useEffect, useRef } from "react";
import { Eye, EyeOff, Trash2, Key, CheckCircle, XCircle, Loader, ShieldCheck } from "lucide-react";
import {
useState, useCallback, useEffect, useRef
} from "react";
import {
Eye, EyeOff, Trash2, Key, CheckCircle, XCircle, Loader, ShieldCheck
} from "lucide-react";
import {
API_KEY_REGISTRY,
getUserApiKey,
setUserApiKey,
clearAllUserApiKeys,
} from "@/lib/userApiKeys";
import { sectionHeaderStyle, inputGroupStyle, labelStyle } from "../panels/DataConfig/sharedStyles";
import ReloadToast from "@/components/ui/ReloadToast";
import { useStore } from "@/core/state/store";
import { verifyLicenseKey } from "@/core/license/verifyLicense";
import { sectionHeaderStyle, inputGroupStyle, labelStyle } from "../panels/DataConfig/sharedStyles";
type VerifyStatus = "idle" | "verifying" | "valid" | "invalid";
const keyInputStyle: React.CSSProperties = {
@@ -54,15 +59,15 @@ const MIN_KEY_LENGTH = 20;
*/
function StatusIcon({ status }: { status: VerifyStatus }) {
if (status === "verifying")
return (
<span style={{ display: "flex", alignItems: "center", color: "var(--text-muted)" }}>
<Loader size={13} style={{ animation: "spin 1s linear infinite" }} />
</span>
);
{ return (
<span style={{ display: "flex", alignItems: "center", color: "var(--text-muted)" }}>
<Loader size={13} style={{ animation: "spin 1s linear infinite" }} />
</span>
); }
if (status === "valid")
return <CheckCircle size={13} style={{ color: "#22c55e", flexShrink: 0 }} />;
{ return <CheckCircle size={13} style={{ color: "#22c55e", flexShrink: 0 }} />; }
if (status === "invalid")
return <XCircle size={13} style={{ color: "#ef4444", flexShrink: 0 }} />;
{ return <XCircle size={13} style={{ color: "#ef4444", flexShrink: 0 }} />; }
return null;
}
@@ -181,137 +186,138 @@ export function ApiKeysTab() {
const hasAnyKey = Object.values(keys).some((v) => v.length > 0);
return (
<>
<style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
<div style={{ marginBottom: "var(--space-lg)" }}>
<div style={sectionHeaderStyle}>
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
License Key
</div>
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
Current Tier: <strong style={{ color: "var(--text-primary)", textTransform: "capitalize" }}>{activeTier}</strong>
</div>
<>
<style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
<div style={{ marginBottom: "var(--space-lg)" }}>
<div style={sectionHeaderStyle}>
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
License Key
</div>
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
Current Tier:
{' '}
<strong style={{ color: "var(--text-primary)", textTransform: "capitalize" }}>{activeTier}</strong>
</div>
<div style={{ marginBottom: "var(--space-md)" }}>
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
<input
type="password"
value={licenseInput}
placeholder="eyJhbGciOiJSUzI1NiI..."
onChange={(e) => setLicenseInput(e.target.value)}
style={{
...keyInputStyle,
border: `1px solid ${licenseStatus === "valid" ? "rgba(34,197,94,0.5)" : licenseStatus === "invalid" ? "rgba(239,68,68,0.5)" : "var(--border-subtle)"}`
<div style={{ marginBottom: "var(--space-md)" }}>
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
<input
type="password"
value={licenseInput}
placeholder="eyJhbGciOiJSUzI1NiI..."
onChange={(e) => setLicenseInput(e.target.value)}
style={{
...keyInputStyle,
border: `1px solid ${licenseStatus === "valid" ? "rgba(34,197,94,0.5)" : licenseStatus === "invalid" ? "rgba(239,68,68,0.5)" : "var(--border-subtle)"}`
}}
spellCheck={false}
autoComplete="off"
/>
<StatusIcon status={licenseStatus} />
<button
onClick={handleVerifyLicense}
disabled={!licenseInput || licenseStatus === "verifying"}
title="Verify license"
style={{
spellCheck={false}
autoComplete="off"
/>
<StatusIcon status={licenseStatus} />
<button
onClick={handleVerifyLicense}
disabled={!licenseInput || licenseStatus === "verifying"}
title="Verify license"
style={{
...toggleBtnStyle,
color: licenseStatus === "valid" ? "#22c55e" : licenseStatus === "invalid" ? "#ef4444" : "var(--text-muted)",
opacity: (!licenseInput || licenseStatus === "verifying") ? 0.4 : 1,
cursor: (!licenseInput || licenseStatus === "verifying") ? "not-allowed" : "pointer",
}}
>
<ShieldCheck size={14} />
</button>
{licenseInput && (
<button
style={toggleBtnStyle}
onClick={handleClearLicense}
title="Clear License"
>
<Trash2 size={14} />
</button>
>
<ShieldCheck size={14} />
</button>
{licenseInput && (
<button
style={toggleBtnStyle}
onClick={handleClearLicense}
title="Clear License"
>
<Trash2 size={14} />
</button>
)}
</div>
{licenseStatus === "invalid" && licenseError && (
<div style={{ fontSize: 10, color: "#ef4444", marginTop: 3 }}>{licenseError}</div>
)}
{licenseStatus === "valid" && (
<div style={{ fontSize: 10, color: "#22c55e", marginTop: 3 }}>License verified ✓</div>
)}
</div>
</div>
{licenseStatus === "invalid" && licenseError && (
<div style={{ fontSize: 10, color: "#ef4444", marginTop: 3 }}>{licenseError}</div>
)}
{licenseStatus === "valid" && (
<div style={{ fontSize: 10, color: "#22c55e", marginTop: 3 }}>License verified ✓</div>
)}
</div>
</div>
<div style={{ marginBottom: "var(--space-lg)" }}>
<div style={sectionHeaderStyle}>
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
Your API Keys
</div>
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
Optional — if set, your key is used instead of the shared default.
Keys are stored only in your browser.
</div>
<div style={{ marginBottom: "var(--space-lg)" }}>
<div style={sectionHeaderStyle}>
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
Your API Keys
</div>
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
Optional — if set, your key is used instead of the shared default.
Keys are stored only in your browser.
</div>
{API_KEY_REGISTRY.map((entry) => {
{API_KEY_REGISTRY.map((entry) => {
const st = status[entry.service] ?? "idle";
const err = errors[entry.service];
const borderColor =
st === "valid" ? "rgba(34,197,94,0.5)"
const borderColor = st === "valid" ? "rgba(34,197,94,0.5)"
: st === "invalid" ? "rgba(239,68,68,0.5)"
: "var(--border-subtle)";
return (
<div key={entry.service} style={{ marginBottom: "var(--space-md)" }}>
<div style={{ ...inputGroupStyle, marginBottom: "var(--space-xs)" }}>
<label style={labelStyle}>{entry.label}</label>
</div>
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
<input
type={visible[entry.service] ? "text" : "password"}
value={keys[entry.service]}
placeholder={entry.placeholder}
onChange={(e) => handleChange(entry.service, e.target.value)}
style={{ ...keyInputStyle, border: `1px solid ${borderColor}` }}
spellCheck={false}
autoComplete="new-password"
data-form-type="other"
data-lpignore="true"
name={`wwv-apikey-${entry.service}`}
/>
<StatusIcon status={st} />
<button
onClick={() => handleManualVerify(entry.service)}
disabled={!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying"}
title="Verify key"
style={{
<div key={entry.service} style={{ marginBottom: "var(--space-md)" }}>
<div style={{ ...inputGroupStyle, marginBottom: "var(--space-xs)" }}>
<label style={labelStyle}>{entry.label}</label>
</div>
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
<input
type={visible[entry.service] ? "text" : "password"}
value={keys[entry.service]}
placeholder={entry.placeholder}
onChange={(e) => handleChange(entry.service, e.target.value)}
style={{ ...keyInputStyle, border: `1px solid ${borderColor}` }}
spellCheck={false}
autoComplete="new-password"
data-form-type="other"
data-lpignore="true"
name={`wwv-apikey-${entry.service}`}
/>
<StatusIcon status={st} />
<button
onClick={() => handleManualVerify(entry.service)}
disabled={!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying"}
title="Verify key"
style={{
...toggleBtnStyle,
color: st === "valid" ? "#22c55e" : st === "invalid" ? "#ef4444" : "var(--text-muted)",
opacity: (!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying") ? 0.4 : 1,
cursor: (!keys[entry.service] || keys[entry.service].length < MIN_KEY_LENGTH || st === "verifying") ? "not-allowed" : "pointer",
}}
>
<ShieldCheck size={14} />
</button>
<button
style={toggleBtnStyle}
onClick={() => toggleVisibility(entry.service)}
title={visible[entry.service] ? "Hide" : "Show"}
>
{visible[entry.service] ? <EyeOff size={14} /> : <Eye size={14} />}
</button>
</div>
{st === "invalid" && err && (
<div style={{ fontSize: 10, color: "#ef4444", marginTop: 3 }}>{err}</div>
)}
{st === "valid" && (
<div style={{ fontSize: 10, color: "#22c55e", marginTop: 3 }}>Key verified ✓</div>
)}
>
<ShieldCheck size={14} />
</button>
<button
style={toggleBtnStyle}
onClick={() => toggleVisibility(entry.service)}
title={visible[entry.service] ? "Hide" : "Show"}
>
{visible[entry.service] ? <EyeOff size={14} /> : <Eye size={14} />}
</button>
</div>
{st === "invalid" && err && (
<div style={{ fontSize: 10, color: "#ef4444", marginTop: 3 }}>{err}</div>
)}
{st === "valid" && (
<div style={{ fontSize: 10, color: "#22c55e", marginTop: 3 }}>Key verified ✓</div>
)}
</div>
);
})}
</div>
</div>
{hasAnyKey && (
<button
onClick={handleClearAll}
style={{
{hasAnyKey && (
<button
onClick={handleClearAll}
style={{
display: "flex",
alignItems: "center",
gap: 6,
@@ -325,13 +331,13 @@ export function ApiKeysTab() {
width: "100%",
justifyContent: "center",
}}
>
<Trash2 size={12} />
Clear All Keys
</button>
>
<Trash2 size={12} />
Clear All Keys
</button>
)}
{needsReload && <ReloadToast message="Google Maps API Key validated. Reload to apply." />}
</>
{needsReload && <ReloadToast message="Google Maps API Key validated. Reload to apply." />}
</>
);
}
+41 -40
View File
@@ -1,7 +1,7 @@
/**
* @file AppShell.tsx
* @description The root layout and orchestration component for WorldWideView.
* Responsible for platform initialization, plugin registration, global state hydration,
* Responsible for platform initialization, plugin registration, global state hydration,
* and managing the transition from boot sequence to interactive state.
* @module src/components/layout
*/
@@ -9,7 +9,6 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Header } from "./Header";
import { LayerPanel } from "@/components/panels/LayerPanel";
import { EntityInfoCard } from "@/components/panels/EntityInfoCard";
import { DataConfigPanel } from "@/components/panels/DataConfig";
@@ -24,13 +23,10 @@ import { dataBus } from "@/core/data/DataBus";
import { PanelToggleArrows } from "@/components/layout/PanelToggleArrows";
import { FloatingVideoManager } from "@/components/video/FloatingVideoManager";
import { BootOverlay } from "@/components/common/BootOverlay";
import { useBootSequence } from "@/core/hooks/useBootSequence";
import { useIsMobile } from "@/core/hooks/useIsMobile";
import { useMarketplaceSync } from "@/core/hooks/useMarketplaceSync";
import { DataBusSubscriber } from "./DataBusSubscriber";
import { AgentBusSubscriber } from "./AgentBusSubscriber";
import { MobileHudBar } from "./MobileHudBar";
import { MobileCameraStats } from "./MobileCameraStats";
import dynamic from "next/dynamic";
import { trackEvent } from "@/lib/analytics";
import ReloadToast from "@/components/ui/ReloadToast";
@@ -41,6 +37,11 @@ import { isDemo } from "@/core/edition";
import { injectHostGlobals } from "@/core/plugins/hostGlobals";
import { initLogCatcher } from "@/lib/logCatcher";
import { MobileCameraStats } from "./MobileCameraStats";
import { MobileHudBar } from "./MobileHudBar";
import { AgentBusSubscriber } from "./AgentBusSubscriber";
import { DataBusSubscriber } from "./DataBusSubscriber";
import { Header } from "./Header";
const GlobeView = dynamic(() => import("@/core/globe/GlobeView"), {
ssr: false,
@@ -48,8 +49,8 @@ const GlobeView = dynamic(() => import("@/core/globe/GlobeView"), {
/**
* @component AppShell
* @description The primary application wrapper.
*
* @description The primary application wrapper.
*
* Orchestrates the following:
* 1. Theme hydration from localStorage.
* 2. Injection of host globals for dynamic ES module plugins.
@@ -61,9 +62,11 @@ export function AppShell() {
const initLayer = useStore((s) => s.initLayer);
const boot = useBootSequence();
const isMobile = useIsMobile();
const bootStartRef = useRef(Date.now());
const [bootStart] = useState(() => Date.now());
const [hostReady, setHostReady] = useState(false);
const { needsReload, pendingUnverified, approveSelected, denyAll } = useMarketplaceSync(hostReady);
const {
needsReload, pendingUnverified, approveSelected, denyAll
} = useMarketplaceSync(hostReady);
const setTheme = useStore((s) => s.setTheme);
// Hydrate theme on mount
@@ -73,7 +76,7 @@ export function AppShell() {
if (storedTheme === "light" || storedTheme === "dark") {
setTheme(storedTheme);
}
} catch (e) {}
} catch { /* ignore hydration errors */ }
}, [setTheme]);
useEffect(() => {
@@ -101,14 +104,12 @@ export function AppShell() {
const demoDefaultPlugins = new Set<string>();
if (isDemo) {
const envVar = process.env.NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS || "";
envVar.split(",").forEach(s => {
envVar.split(",").forEach((s) => {
const clean = s.trim();
if (clean) demoDefaultPlugins.add(clean);
});
}
await pluginManager.init();
for (const plugin of pluginRegistry.getAll()) {
@@ -152,10 +153,10 @@ export function AppShell() {
// Track when boot completes
useEffect(() => {
if (boot.phase === "ready") {
const duration = Date.now() - bootStartRef.current;
const duration = Date.now() - bootStart;
trackEvent("platform-boot", { duration });
}
}, [boot.phase]);
}, [boot.phase, bootStart]);
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
const rootClasses = [
@@ -169,37 +170,37 @@ export function AppShell() {
].filter(Boolean).join(" ");
return (
<div className={rootClasses}>
<div className={rootClasses} data-testid={!isBooting ? "app-ready" : undefined}>
<BootOverlay visible={boot.phase === "loading"} />
<div className="app-shell__globe">
<GlobeView />
</div>
<TimelineSync />
<DataBusSubscriber />
<AgentBusSubscriber />
<TimelineSync />
<DataBusSubscriber />
<AgentBusSubscriber />
<Header />
{isMobile && <MobileHudBar />}
{isMobile && <MobileCameraStats />}
<PanelToggleArrows />
<LayerPanel />
<DataConfigPanel />
{!isMobile && <CameraStatsPanel />}
<EntityInfoCard />
<BottomPanelManager />
<FloatingVideoManager />
{needsReload && <ReloadToast />}
<ErrorToast />
<FeedbackDialog />
{pendingUnverified.length > 0 && (
<UnverifiedPluginBatchDialog
manifests={pendingUnverified}
onApproveSelected={approveSelected}
onDenyAll={denyAll}
/>
<Header />
{isMobile && <MobileHudBar />}
{isMobile && <MobileCameraStats />}
<PanelToggleArrows />
<LayerPanel />
<DataConfigPanel />
{!isMobile && <CameraStatsPanel />}
<EntityInfoCard />
<BottomPanelManager />
<FloatingVideoManager />
{needsReload && <ReloadToast />}
<ErrorToast />
<FeedbackDialog />
{pendingUnverified.length > 0 && (
<UnverifiedPluginBatchDialog
manifests={pendingUnverified}
onApproveSelected={approveSelected}
onDenyAll={denyAll}
/>
)}
</div>
</div>
);
}
@@ -1,135 +0,0 @@
.bottom-panel-system {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
align-items: center;
z-index: 1000;
pointer-events: none;
width: calc(100% - 40px);
max-width: 1200px;
}
.bottom-panel-dock {
display: flex;
gap: 8px;
margin-bottom: 12px;
pointer-events: auto;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.dock-btn {
width: 48px;
height: 48px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.7);
cursor: pointer;
transition: all 0.2s ease;
}
.dock-btn:hover {
background: rgba(255, 255, 255, 0.15);
color: white;
}
.dock-btn.active {
background: rgba(43, 115, 255, 0.2);
border-color: rgba(43, 115, 255, 0.5);
color: #4b8df8;
box-shadow: 0 0 15px rgba(43, 115, 255, 0.3);
}
.bottom-panel {
width: 100%;
border-radius: 12px;
display: flex;
flex-direction: column;
pointer-events: auto;
overflow: hidden;
position: relative;
/* Transition applied to height in style, but we can animate opacity/transform too */
transition: height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.bottom-panel.closed {
opacity: 0;
pointer-events: none;
border: none;
}
.bottom-panel.open {
opacity: 1;
}
.bottom-panel-resize-handle {
height: 12px;
width: 100%;
cursor: ns-resize;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
background: transparent;
z-index: 10;
}
.bottom-panel-resize-handle:hover .resize-grip {
background: rgba(255, 255, 255, 0.5);
}
.resize-grip {
width: 40px;
height: 4px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.2);
transition: background 0.2s;
}
.bottom-panel-close-btn {
position: absolute;
top: 12px;
right: 12px;
background: transparent;
border: none;
color: rgba(255, 255, 255, 0.5);
cursor: pointer;
padding: 4px;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
transition: all 0.2s ease;
}
.bottom-panel-close-btn:hover {
color: white;
background: rgba(255, 255, 255, 0.1);
}
.bottom-panel-content {
padding: 24px;
flex: 1;
overflow-y: auto;
/* Ensure the content sits below the resize handle */
margin-top: 12px;
display: flex;
flex-direction: column;
}
/* Timeline adjustments inside the new panel */
.timeline__content {
display: flex;
flex-direction: column;
gap: 12px;
height: 100%;
}
+91 -17
View File
@@ -4,30 +4,55 @@ import React, { useRef, useState, useEffect } from "react";
import { useStore } from "@/core/state/store";
import { pluginManager } from "@/core/plugins/PluginManager";
import { Timeline } from "@/components/timeline/Timeline";
import "./BottomPanelManager.css";
import { PluginErrorBoundary } from "@/components/common/PluginErrorBoundary";
export function BottomPanelManager() {
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
const setActiveBottomPanel = useStore((s) => s.setActiveBottomPanel);
const bottomPanelHeight = useStore((s) => s.bottomPanelHeight);
const setBottomPanelHeight = useStore((s) => s.setBottomPanelHeight);
const layers = useStore((s) => s.layers);
const [mountedPanel, setMountedPanel] = useState<string | null>(activeBottomPanel);
const [isDragging, setIsDragging] = useState(false);
const resizeRef = useRef<HTMLDivElement>(null);
// Get all registered plugins that provide a bottom panel component
const plugins = pluginManager.getAllPlugins().map((p) => p.plugin);
const dockablePlugins = plugins.filter((p) => p.getBottomPanelComponent !== undefined);
const dockablePlugins = plugins.filter(
(p) => p.getBottomPanelComponent !== undefined && layers[p.id]?.enabled
);
const isCoveredRef = useRef(false);
useEffect(() => {
if (activeBottomPanel) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setMountedPanel(activeBottomPanel);
} else {
// Keep the panel mounted for the duration of the CSS exit transition (400ms)
const timer = setTimeout(() => {
setMountedPanel(null);
}, 400);
return () => clearTimeout(timer);
}
}, [activeBottomPanel]);
// Handle mouse drag for resizing the panel
useEffect(() => {
if (!isDragging) return;
if (!isDragging) {
document.body.classList.remove("is-dragging-bottom-panel");
return;
}
document.body.classList.add("is-dragging-bottom-panel");
const handleMouseMove = (e: MouseEvent) => {
// Calculate new height based on distance from bottom of window
const newHeight = window.innerHeight - e.clientY;
// Clamp between min 200px and max window height - 100px
const clampedHeight = Math.max(200, Math.min(newHeight, window.innerHeight - 100));
// Clamp between min 120px and max window height - 100px
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
setBottomPanelHeight(clampedHeight);
};
@@ -41,9 +66,47 @@ export function BottomPanelManager() {
return () => {
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
document.body.classList.remove("is-dragging-bottom-panel");
};
}, [isDragging, setBottomPanelHeight]);
// Dynamically push sidebars up based on bottom panel height
useEffect(() => {
const threshold = 400; // Point where panel covers the sidebars
const panelBottomOffset = 16; // Distance from screen bottom to panel bottom
const gap = 16; // Desired gap between the top of the panel and the bottom of the sidebars
if (activeBottomPanel) {
const shouldBeCovered = bottomPanelHeight > threshold;
if (shouldBeCovered !== isCoveredRef.current) {
isCoveredRef.current = shouldBeCovered;
document.body.classList.add("sidebar-force-transition");
setTimeout(() => {
document.body.classList.remove("sidebar-force-transition");
}, 400); // var(--duration-slow) is 400ms
}
if (!shouldBeCovered) {
// Push sidebars up with gap
document.documentElement.style.setProperty("--sidebar-bottom", `${bottomPanelHeight + panelBottomOffset + gap}px`);
} else {
// Drop sidebars back down to be covered
document.documentElement.style.setProperty("--sidebar-bottom", `${panelBottomOffset}px`);
}
} else {
// Panel closed
if (isCoveredRef.current) {
isCoveredRef.current = false;
document.body.classList.add("sidebar-force-transition");
setTimeout(() => {
document.body.classList.remove("sidebar-force-transition");
}, 400);
}
document.documentElement.style.setProperty("--sidebar-bottom", `${panelBottomOffset}px`);
}
}, [activeBottomPanel, bottomPanelHeight]);
// Handle mobile auto-close on load (legacy behavior from Timeline)
useEffect(() => {
if (window.innerWidth < 768 && activeBottomPanel !== null) {
@@ -53,14 +116,23 @@ export function BottomPanelManager() {
// Render active panel content
const renderActivePanelContent = () => {
if (activeBottomPanel === "timeline") {
if (!mountedPanel) return null;
if (mountedPanel === "timeline") {
return <Timeline />;
}
const activePlugin = dockablePlugins.find(p => p.id === activeBottomPanel);
if (activePlugin && activePlugin.getBottomPanelComponent) {
const Component = activePlugin.getBottomPanelComponent();
return <Component pluginId={activePlugin.id} />;
const managed = pluginManager.getPlugin(mountedPanel);
if (managed && managed.plugin.getBottomPanelComponent) {
const Comp = managed.plugin.getBottomPanelComponent();
return (
<PluginErrorBoundary pluginId={mountedPanel}>
<Comp
pluginId={mountedPanel}
enabled={activeBottomPanel === mountedPanel ? managed.enabled : false}
/>
</PluginErrorBoundary>
);
}
return null;
@@ -69,30 +141,31 @@ export function BottomPanelManager() {
return (
<div className="bottom-panel-system">
{/* Dock: Always visible above the panel */}
<div className="bottom-panel-dock">
<div className={`bottom-panel-dock ${!activeBottomPanel ? "floating-pills" : ""}`}>
<button
className={`dock-btn glass-panel ${activeBottomPanel === "timeline" ? "active" : ""}`}
className={`dock-btn ${activeBottomPanel === "timeline" ? "active" : ""}`}
onClick={() => setActiveBottomPanel(activeBottomPanel === "timeline" ? null : "timeline")}
title="Timeline"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10" />
<polyline points="12 6 12 12 16 14" />
</svg>
<span className="dock-btn-label">Timeline</span>
</button>
{dockablePlugins.map((plugin) => (
<button
key={plugin.id}
className={`dock-btn glass-panel ${activeBottomPanel === plugin.id ? "active" : ""}`}
className={`dock-btn ${activeBottomPanel === plugin.id ? "active" : ""}`}
onClick={() => setActiveBottomPanel(activeBottomPanel === plugin.id ? null : plugin.id)}
title={plugin.name || plugin.id}
>
{/* Placeholder icon, a real implementation might use an icon provided by the plugin metadata */}
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
<path d="M3 9h18" />
</svg>
<span className="dock-btn-label">{plugin.name || plugin.id}</span>
</button>
))}
</div>
@@ -102,10 +175,11 @@ export function BottomPanelManager() {
className={`bottom-panel glass-panel ${activeBottomPanel ? "open" : "closed"}`}
style={{ height: activeBottomPanel ? `${bottomPanelHeight}px` : "0px" }}
>
{activeBottomPanel && (
{mountedPanel && (
<>
<div
className="bottom-panel-resize-handle"
data-testid="bottom-panel-resize-handle"
ref={resizeRef}
onMouseDown={() => setIsDragging(true)}
>
+29 -1
View File
@@ -24,6 +24,10 @@ export function DataBusSubscriber() {
const setPollingInterval = useStore((s) => s.setPollingInterval);
const setEntities = useStore((s) => s.setEntities);
const setEntityCount = useStore((s) => s.setEntityCount);
const clearEntities = useStore((s) => s.clearEntities);
const removeLayer = useStore((s) => s.removeLayer);
const setLayerLoading = useStore((s) => s.setLayerLoading);
const showErrorToast = useStore((s) => s.showErrorToast);
const cacheMaxAge = useStore((s) => s.dataConfig.cacheMaxAge);
useEffect(() => {
@@ -65,12 +69,36 @@ export function DataBusSubscriber() {
}
});
const unsubUnreg = dataBus.on("pluginUnregistered", ({ pluginId }) => {
setTimeout(() => {
clearEntities(pluginId);
removeLayer(pluginId);
}, 0);
});
const unsubLoading = dataBus.on("layerLoadingChanged", ({ pluginId, loading }) => {
setTimeout(() => {
setLayerLoading(pluginId, loading);
}, 0);
});
const unsubError = dataBus.on("pluginError", ({ message }) => {
setTimeout(() => {
if (showErrorToast) {
showErrorToast(message);
}
}, 0);
});
return () => {
unsubReg();
unsubUnreg();
unsubData();
unsubToggle();
unsubLoading();
unsubError();
};
}, [setPollingInterval, setEntities, setEntityCount]);
}, [setPollingInterval, setEntities, setEntityCount, clearEntities, removeLayer, setLayerLoading, showErrorToast]);
return null;
}
+3 -5
View File
@@ -12,9 +12,9 @@ import { useStore } from "@/core/state/store";
/**
* Headless component that listens for plugin updates over a local WebSocket.
* Only active in `development` environments. Allows for real-time plugin
* Only active in `development` environments. Allows for real-time plugin
* addition and reloading without full page refreshes.
*
*
* @returns null
*/
export function DevModeSubscriber() {
@@ -40,13 +40,12 @@ export function DevModeSubscriber() {
ws.onmessage = async (event) => {
try {
const data = JSON.parse(event.data);
if (data.type === "plugin:added") {
console.log(`[DevMode] Plugin added from CLI: ${data.manifest.id}`);
await pluginManager.loadFromManifest(data.manifest);
initLayer(data.manifest.id, true);
await pluginManager.enablePlugin(data.manifest.id);
} else if (data.type === "plugin:updated") {
console.log(`[DevMode] Reloading plugin: ${data.pluginId}`);
// Destroy and re-load from manifest for dev hot-reload
@@ -56,7 +55,6 @@ export function DevModeSubscriber() {
initLayer(data.manifest.id, true);
await pluginManager.enablePlugin(data.manifest.id);
}
} else if (data.type === "plugin:error") {
console.error(`[DevMode] Dev Server Build Error: ${data.error}`);
useStore.getState().showErrorToast?.(`Build Error in ${data.pluginId}: ${data.error}`);
+232 -179
View File
@@ -2,7 +2,7 @@
/**
* @file Header.tsx
* @description Primary application header providing branding, search, region presets,
* @description Primary application header providing branding, search, region presets,
* theme selection, and system-wide controls.
* @module src/components/layout
*/
@@ -11,14 +11,17 @@ import { useEffect, useRef, useState } from "react";
import { useStore } from "@/core/state/store";
import { dataBus } from "@/core/data/DataBus";
import { pluginManager } from "@/core/plugins/PluginManager";
import { Globe, Key, Sun, Moon, Monitor } from "lucide-react";
import {
Globe, Key, Sun, Moon, Monitor
} from "lucide-react";
import { trackEvent } from "@/lib/analytics";
import { isDemo, DEMO_ADMIN_ROLE } from "@/core/edition";
import { SearchBar } from "./SearchBar";
import Image from "next/image";
import { useIsMobile } from "@/core/hooks/useIsMobile";
import { SearchBar } from "./SearchBar";
import { ApiKeysTab } from "./ApiKeysTab";
import "./timeSelect.css"
import "./timeSelect.css";
const REGIONS = [
{ id: "global", label: "Global", icon: Globe },
@@ -45,7 +48,7 @@ const TIME_WINDOWS = ["1h", "6h", "24h", "48h", "7d"] as const;
* @description The main navigation and control bar of the application.
* Handles responsive layout between mobile and desktop, including time windows,
* theme selection, and region-based camera presets.
*
*
* @example
* ```tsx
* <Header />
@@ -97,27 +100,35 @@ export function Header() {
// Mobile: compact header with persistent centered search
if (isMobile) {
return (
<>
<>
<header className="header header--mobile glass-panel">
<div className="header__brand">
<a href="https://worldwideview.dev/" target="_blank" rel="noopener noreferrer" style={{ display: "flex", alignItems: "center", gap: "8px", textDecoration: "none", color: "inherit" }}>
<img src="/logo/logo-icon.svg" alt="Logo" style={{ width: 20, height: 20, objectFit: "contain" }} />
<div className="header__logo header__logo--compact">WWV</div>
</a>
<span className="alpha-badge">ALPHA</span>
{isDemoAdmin && <span className="alpha-badge" style={{ background: "var(--accent-orange, #f59e0b)" }}>ADMIN</span>}
</div>
<div className="header__brand">
<a
href="https://worldwideview.dev/"
target="_blank"
rel="noopener noreferrer"
style={{
display: "flex", alignItems: "center", gap: "8px", textDecoration: "none", color: "inherit"
}}
>
<Image src="/logo/logo-icon.svg" alt="Logo" width={20} height={20} style={{ objectFit: "contain" }} />
<div className="header__logo header__logo--compact">WWV</div>
</a>
<span className="alpha-badge">ALPHA</span>
{isDemoAdmin && <span className="alpha-badge" style={{ background: "var(--accent-orange, #f59e0b)" }}>ADMIN</span>}
</div>
<div className="header__search-center">
<SearchBar />
</div>
<div className="header__search-center">
<SearchBar />
</div>
<div className="header__actions" style={{ display: "flex", gap: "8px", alignItems: "center" }}>
<div style={{ position: "relative" }}>
<button
ref={themeButtonRef}
className="btn btn--glow"
onClick={() => {
<div className="header__actions" style={{ display: "flex", gap: "8px", alignItems: "center" }}>
<div style={{ position: "relative" }}>
<button
ref={themeButtonRef}
className="btn btn--glow"
type="button"
onClick={() => {
if (!themeOpen && themeButtonRef.current) {
const rect = themeButtonRef.current.getBoundingClientRect();
setThemePos({
@@ -127,8 +138,8 @@ export function Header() {
}
setThemeOpen((v) => !v);
}}
title="Theme Selection"
style={{
title="Theme Selection"
style={{
display: "flex",
alignItems: "center",
padding: "6px",
@@ -137,105 +148,122 @@ export function Header() {
color: "var(--text-secondary)",
gap: "4px"
}}
>
{theme === "dark" && <Moon size={16} />}
{theme === "black" && <Moon size={16} />}
{theme === "light" && <Sun size={16} />}
{theme === "legacy" && <Monitor size={16} />}
<svg width="10" height="10" viewBox="0 0 10 10" style={{ transform: themeOpen ? "rotate(180deg)" : "rotate(0deg)", transition: "transform 0.2s ease", opacity: 0.6 }}>
<path d="M1 3 L5 7 L9 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</button>
</div>
<div className="status-badge">
<span className="status-badge__dot" />
LIVE
</div>
>
{theme === "dark" && <Moon size={16} />}
{theme === "black" && <Moon size={16} />}
{theme === "light" && <Sun size={16} />}
{theme === "legacy" && <Monitor size={16} />}
<svg width="10" height="10" viewBox="0 0 10 10" style={{ transform: themeOpen ? "rotate(180deg)" : "rotate(0deg)", transition: "transform 0.2s ease", opacity: 0.6 }}>
<path d="M1 3 L5 7 L9 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</button>
</div>
<div className="status-badge">
<span className="status-badge__dot" />
LIVE
</div>
</div>
</header>
{themeOpen && (
<div className="dropdown-menu" style={{ top: themePos.top, right: themePos.right - 2 }}>
{THEMES.map((th) => {
<div className="dropdown-menu" style={{ top: themePos.top, right: themePos.right - 2 }}>
{THEMES.map((th) => {
const Icon = th.icon;
return (
<div
key={th.id}
className={`dropdown-option ${th.id === theme ? "active" : ""}`}
style={{ display: "flex", alignItems: "center", gap: "8px", justifyContent: "flex-start" }}
onClick={() => {
setTheme(th.id);
setThemeOpen(false);
}}
>
<Icon size={14} />
{th.label}
</div>
<button
type="button"
key={th.id}
className={`dropdown-option ${th.id === theme ? "active" : ""}`}
style={{
display: "flex",
alignItems: "center",
gap: "8px",
justifyContent: "flex-start",
width: "100%",
border: "none",
background: "transparent",
color: "inherit",
cursor: "pointer"
}}
onClick={() => {
setTheme(th.id);
setThemeOpen(false);
}}
>
<Icon size={14} />
{th.label}
</button>
);
})}
</div>
</div>
)}
</>
</>
);
}
// Desktop: full header
return (
<>
<>
<header className="header glass-panel">
<div className="header__brand">
<a href="https://worldwideview.dev/" target="_blank" rel="noopener noreferrer" style={{ textDecoration: "none", color: "inherit", cursor: "pointer" }}>
<div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
<img src="/logo/logo-icon.svg" alt="Logo" style={{ width: 22, height: 22, objectFit: "contain" }} />
<div className="header__logo">WORLD WIDE VIEW</div>
<span className="alpha-badge">ALPHA</span>
{isDemoAdmin && <span className="alpha-badge" style={{ background: "var(--accent-orange, #f59e0b)" }}>ADMIN</span>}
</div>
<div className="header__subtitle">Geospatial Intelligence</div>
</a>
<div style={{ marginLeft: "var(--space-xl)" }}>
<SearchBar />
</div>
<div className="header__brand">
<a href="https://worldwideview.dev/" target="_blank" rel="noopener noreferrer" style={{ textDecoration: "none", color: "inherit", cursor: "pointer" }}>
<div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
<Image src="/logo/logo-icon.svg" alt="Logo" width={22} height={22} style={{ objectFit: "contain" }} />
<div className="header__logo">WORLD WIDE VIEW</div>
<span className="alpha-badge">ALPHA</span>
{isDemoAdmin && <span className="alpha-badge" style={{ background: "var(--accent-orange, #f59e0b)" }}>ADMIN</span>}
</div>
<div className="header__subtitle">Geospatial Intelligence</div>
</a>
<div style={{ marginLeft: "var(--space-xl)" }}>
<SearchBar />
</div>
<div className="header__controls">
<div className="header__controls-scroll" ref={scrollContainerRef}>
{REGIONS.map((r) => {
</div>
<div className="header__controls">
<div className="header__controls-scroll" ref={scrollContainerRef}>
{REGIONS.map((r) => {
const Icon = r.icon;
return (
<button
key={r.id}
className="btn btn--glow"
onClick={() => {
<button
type="button"
key={r.id}
className="btn btn--glow"
onClick={() => {
dataBus.emit("cameraPreset", { presetId: r.id });
trackEvent("region-select", { region: r.id });
}}
title={r.label}
style={{ display: "flex", alignItems: "center", gap: "6px", flexShrink: 0 }}
>
<Icon size={14} />
{r.label}
</button>
title={r.label}
style={{
display: "flex", alignItems: "center", gap: "6px", flexShrink: 0
}}
>
<Icon size={14} />
{r.label}
</button>
);
})}
<div style={{ width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0 }} />
<button
className="btn btn--glow"
onClick={() => setShowApiKeys(true)}
title="API Keys"
style={{
<div style={{
width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0
}}
/>
<button
type="button"
className="btn btn--glow"
onClick={() => setShowApiKeys(true)}
title="API Keys"
style={{
display: "flex",
alignItems: "center",
gap: "6px",
}}
>
<Key size={14} />
</button>
<div style={{ position: "relative", flexShrink: 0 }}>
<button
ref={themeButtonRef}
className="btn btn--glow"
onClick={() => {
>
<Key size={14} />
</button>
<div style={{ position: "relative", flexShrink: 0 }}>
<button
type="button"
ref={themeButtonRef}
className="btn btn--glow"
onClick={() => {
if (!themeOpen && themeButtonRef.current) {
const rect = themeButtonRef.current.getBoundingClientRect();
setThemePos({
@@ -245,29 +273,32 @@ export function Header() {
}
setThemeOpen((v) => !v);
}}
title="Theme Selection"
style={{
title="Theme Selection"
style={{
display: "flex",
alignItems: "center",
gap: "6px",
}}
>
{theme === "dark" && <Moon size={14} />}
{theme === "black" && <Moon size={14} />}
{theme === "light" && <Sun size={14} />}
{theme === "legacy" && <Monitor size={14} />}
<svg width="10" height="10" viewBox="0 0 10 10" style={{ transform: themeOpen ? "rotate(180deg)" : "rotate(0deg)", transition: "transform 0.2s ease", opacity: 0.6 }}>
<path d="M1 3 L5 7 L9 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</button>
</div>
<div style={{ width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0 }} />
<div style={{ position: "relative", flexShrink: 0 }} ref={timeRef}>
<button
ref={timeButtonRef}
className="btn btn--glow"
type="button"
onClick={() => {
>
{theme === "dark" && <Moon size={14} />}
{theme === "black" && <Moon size={14} />}
{theme === "light" && <Sun size={14} />}
{theme === "legacy" && <Monitor size={14} />}
<svg width="10" height="10" viewBox="0 0 10 10" style={{ transform: themeOpen ? "rotate(180deg)" : "rotate(0deg)", transition: "transform 0.2s ease", opacity: 0.6 }}>
<path d="M1 3 L5 7 L9 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</button>
</div>
<div style={{
width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0
}}
/>
<div style={{ position: "relative", flexShrink: 0 }} ref={timeRef}>
<button
ref={timeButtonRef}
className="btn btn--glow"
type="button"
onClick={() => {
if (!timeOpen && timeButtonRef.current) {
const rect = timeButtonRef.current.getBoundingClientRect();
setTimePos({
@@ -277,39 +308,50 @@ export function Header() {
}
setTimeOpen((v) => !v);
}}
style={{ display: "flex", alignItems: "center", gap: "6px" }}
>
{timeWindow}
<svg
width="10"
height="10"
viewBox="0 0 10 10"
style={{
style={{ display: "flex", alignItems: "center", gap: "6px" }}
>
{timeWindow}
<svg
width="10"
height="10"
viewBox="0 0 10 10"
style={{
transform: timeOpen ? "rotate(180deg)" : "rotate(0deg)",
transition: "transform 0.2s ease",
opacity: 0.6,
}}
>
<path d="M1 3 L5 7 L9 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</button>
</div>
</div>
<div style={{ width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0 }} />
<div className="header__actions">
<div className="status-badge">
<span className="status-badge__dot" />
LIVE
</div>
</div>
>
<path d="M1 3 L5 7 L9 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</button>
</div>
</div>
<div style={{
width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0
}}
/>
<div className="header__actions">
<div className="status-badge">
<span className="status-badge__dot" />
LIVE
</div>
</div>
</div>
</header>
{timeOpen && (
<div className="dropdown-menu" style={{ top: timePos.top, right: timePos.right - 2 }}>
{TIME_WINDOWS.map((tw) => (
<div
<button
type="button"
key={tw}
className={`dropdown-option ${tw === timeWindow ? "active" : ""}`}
style={{
width: "100%",
border: "none",
background: "transparent",
color: "inherit",
cursor: "pointer"
}}
onClick={() => {
setTimeWindow(tw);
const range = useStore.getState().timeRange;
@@ -319,34 +361,45 @@ export function Header() {
}}
>
{tw}
</div>
</button>
))}
</div>
)}
{themeOpen && (
<div className="dropdown-menu" style={{ top: themePos.top, right: themePos.right - 2 }}>
{THEMES.map((th) => {
<div className="dropdown-menu" style={{ top: themePos.top, right: themePos.right - 2 }}>
{THEMES.map((th) => {
const Icon = th.icon;
return (
<div
key={th.id}
className={`dropdown-option ${th.id === theme ? "active" : ""}`}
style={{ display: "flex", alignItems: "center", gap: "8px", justifyContent: "flex-start" }}
onClick={() => {
<button
type="button"
key={th.id}
className={`dropdown-option ${th.id === theme ? "active" : ""}`}
style={{
display: "flex",
alignItems: "center",
gap: "8px",
justifyContent: "flex-start",
width: "100%",
border: "none",
background: "transparent",
color: "inherit",
cursor: "pointer"
}}
onClick={() => {
setTheme(th.id);
setThemeOpen(false);
}}
>
<Icon size={14} />
{th.label}
</div>
>
<Icon size={14} />
{th.label}
</button>
);
})}
</div>
</div>
)}
{showApiKeys && (
<div
style={{
<div
style={{
position: "fixed",
inset: 0,
background: "rgba(0,0,0,0.45)",
@@ -358,12 +411,12 @@ export function Header() {
overflowY: "auto",
zIndex: 9999,
}}
onClick={() => setShowApiKeys(false)}
>
<div
className="glass-panel"
onClick={(e) => e.stopPropagation()}
style={{
onClick={() => setShowApiKeys(false)}
>
<div
className="glass-panel"
onClick={(e) => e.stopPropagation()}
style={{
width: "min(700px, 90vw)",
maxHeight: "80vh",
overflowY: "auto",
@@ -371,30 +424,30 @@ export function Header() {
borderRadius: "16px",
margin: "20px",
}}
>
<div
style={{
>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "16px",
}}
>
<h2 style={{ margin: 0 }}>API Keys</h2>
<button
className="btn"
onClick={() => setShowApiKeys(false)}
>
Close
</button>
</div>
<ApiKeysTab />
</div>
</div>
>
<h2 style={{ margin: 0 }}>API Keys</h2>
<button
type="button"
className="btn"
onClick={() => setShowApiKeys(false)}
>
Close
</button>
</div>
<ApiKeysTab />
</div>
</div>
)}
</>
</>
);
}
+44 -40
View File
@@ -18,51 +18,55 @@ export function MobileCameraStats() {
const fps = useStore((s) => s.fps);
const fmtCoord = (v: number) => v.toFixed(4);
const fmtAlt = (v: number) =>
v > 10000 ? `${(v / 1000).toFixed(1)}km` : `${v.toFixed(0)}m`;
const fmtAlt = (v: number) => (v > 10000 ? `${(v / 1000).toFixed(1)}km` : `${v.toFixed(0)}m`);
const fmtDeg = (v: number) => `${v.toFixed(1)}°`;
return (
<div
className={`mobile-camera-stats glass-panel ${collapsed ? "mobile-camera-stats--collapsed" : ""}`}
onClick={() => setCollapsed(!collapsed)}
>
{collapsed ? (
<div className="mobile-camera-stats__tab">
<span>HUD</span>
<svg
width="10" height="10" viewBox="0 0 24 24"
fill="none" stroke="currentColor"
strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
>
<polyline points="6 9 12 15 18 9" />
</svg>
</div>
<div
className={`mobile-camera-stats glass-panel ${collapsed ? "mobile-camera-stats--collapsed" : ""}`}
onClick={() => setCollapsed(!collapsed)}
>
{collapsed ? (
<div className="mobile-camera-stats__tab">
<span>HUD</span>
<svg
width="10"
height="10"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="6 9 12 15 18 9" />
</svg>
</div>
) : (
<div className="mobile-camera-stats__row">
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">LAT</span>
<span className="mobile-camera-stats__value">{fmtCoord(cameraLat)}</span>
</div>
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">LON</span>
<span className="mobile-camera-stats__value">{fmtCoord(cameraLon)}</span>
</div>
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">ALT</span>
<span className="mobile-camera-stats__value">{fmtAlt(cameraAlt)}</span>
</div>
<div className="mobile-camera-stats__sep" />
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">HDG</span>
<span className="mobile-camera-stats__value">{fmtDeg(cameraHeading)}</span>
</div>
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">FPS</span>
<span className="mobile-camera-stats__value">{fps}</span>
</div>
<div className="mobile-camera-stats__row">
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">LAT</span>
<span className="mobile-camera-stats__value">{fmtCoord(cameraLat)}</span>
</div>
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">LON</span>
<span className="mobile-camera-stats__value">{fmtCoord(cameraLon)}</span>
</div>
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">ALT</span>
<span className="mobile-camera-stats__value">{fmtAlt(cameraAlt)}</span>
</div>
<div className="mobile-camera-stats__sep" />
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">HDG</span>
<span className="mobile-camera-stats__value">{fmtDeg(cameraHeading)}</span>
</div>
<div className="mobile-camera-stats__item">
<span className="mobile-camera-stats__label">FPS</span>
<span className="mobile-camera-stats__value">{fps}</span>
</div>
</div>
)}
</div>
</div>
);
}
+22 -22
View File
@@ -27,36 +27,36 @@ export function MobileHudBar() {
const setTimeWindow = useStore((s) => s.setTimeWindow);
return (
<div className="mobile-hud-bar glass-panel">
<div className="mobile-hud-bar__scroll">
{REGIONS.map((r) => (
<button
key={r.id}
className="btn btn--glow"
onClick={() => dataBus.emit("cameraPreset", { presetId: r.id })}
title={r.label}
>
<Globe size={14} />
{r.label}
</button>
<div className="mobile-hud-bar glass-panel">
<div className="mobile-hud-bar__scroll">
{REGIONS.map((r) => (
<button
key={r.id}
className="btn btn--glow"
onClick={() => dataBus.emit("cameraPreset", { presetId: r.id })}
title={r.label}
>
<Globe size={14} />
{r.label}
</button>
))}
<div className="mobile-hud-bar__divider" />
<div className="mobile-hud-bar__divider" />
{TIME_WINDOWS.map((tw) => (
<button
key={tw}
className={`btn ${timeWindow === tw ? "btn--active" : ""}`}
onClick={() => {
{TIME_WINDOWS.map((tw) => (
<button
key={tw}
className={`btn ${timeWindow === tw ? "btn--active" : ""}`}
onClick={() => {
setTimeWindow(tw);
const range = useStore.getState().timeRange;
pluginManager.updateTimeRange(range);
}}
>
{tw}
</button>
>
{tw}
</button>
))}
</div>
</div>
</div>
);
}
+9 -10
View File
@@ -16,9 +16,7 @@ export function PanelToggleArrows() {
const toggleConfigPanel = useStore((s) => s.toggleConfigPanel);
const setOpenMobilePanel = useStore((s) => s.setOpenMobilePanel);
const filterCount = useStore((s) =>
Object.values(s.filters).reduce((sum, pf) => sum + Object.keys(pf).length, 0)
);
const filterCount = useStore((s) => Object.values(s.filters).reduce((sum, pf) => sum + Object.keys(pf).length, 0));
const handleLeftToggle = () => {
if (isMobile) {
@@ -48,6 +46,7 @@ export function PanelToggleArrows() {
className={`panel-toggle-btn panel-toggle-btn--left ${isLeftOpen ? "panel-toggle-btn--open" : ""} ${isMobile ? "panel-toggle-btn--mobile" : ""}`}
onClick={handleLeftToggle}
title="Toggle Layers Panel"
data-testid="panel-toggle-left"
>
{isLeftOpen ? <ChevronLeft size={24} /> : <ChevronRight size={24} />}
</button>
@@ -57,16 +56,16 @@ export function PanelToggleArrows() {
className={`panel-toggle-btn panel-toggle-btn--right ${isRightOpen ? "panel-toggle-btn--open" : ""} ${isMobile ? "panel-toggle-btn--mobile" : ""} ${isMobile && mobileRightPanelGlow ? "panel-toggle-btn--glow" : ""}`}
onClick={handleRightToggle}
title="Toggle Data Configuration"
data-testid="panel-toggle-right"
>
{isRightOpen ? <ChevronRight size={24} /> : <ChevronLeft size={24} />}
{filterCount > 0 && !isRightOpen && (
<span className="filter-badge filter-badge--toggle">
{filterCount}
</span>
{filterCount > 0 && !isRightOpen && (
<span className="filter-badge filter-badge--toggle">
{filterCount}
</span>
)}
</button>
</>
</button>
</>
);
}
+74 -57
View File
@@ -2,16 +2,16 @@
/**
* @file SearchBar.tsx
* @description Integrated search component providing geocoding, entity lookup,
* @description Integrated search component providing geocoding, entity lookup,
* and history functionality with a high-performance dropdown interface.
* @module src/components/layout
*/
import { useState, useEffect, useRef } from "react";
import { Search, MapPin } from "lucide-react";
import { useIsMobile } from "@/core/hooks/useIsMobile";
import { useSearch } from "./useSearch";
import type { SearchResult, SearchSection } from "./useSearch";
import { useIsMobile } from "@/core/hooks/useIsMobile";
/**
* @function HighlightMatch
@@ -29,11 +29,9 @@ function HighlightMatch({ text, query }: { text: string; query: string }) {
const parts = text.split(new RegExp(`(${safeQuery})`, 'gi'));
return (
<>
{parts.map((part, i) =>
part.toLowerCase() === safeQuery.toLowerCase() ? <strong key={i} style={{ color: "var(--accent-cyan)", fontWeight: 700 }}>{part}</strong> : part
)}
</>
<>
{parts.map((part, i) => (part.toLowerCase() === safeQuery.toLowerCase() ? <strong key={i} style={{ color: "var(--accent-cyan)", fontWeight: 700 }}>{part}</strong> : part))}
</>
);
}
@@ -100,20 +98,25 @@ export function SearchBar() {
}, [selectedIndex, isOpen]);
return (
<div className="search-bar" ref={containerRef} style={{ position: "relative", width: "100%", maxWidth: "250px" }}>
<div className="search-bar__input-wrapper" style={{ display: "flex", alignItems: "center", background: "rgba(255, 255, 255, 0.05)", borderRadius: "var(--radius-md)", padding: "4px 8px", border: "1px solid var(--border-subtle)", width: "100%" }}>
<Search size={16} color="var(--text-muted)" style={{ marginRight: "8px", flexShrink: 0 }} />
<input
type="text"
value={query}
onChange={(e) => {
<div className="search-bar" ref={containerRef} style={{ position: "relative", width: "100%", maxWidth: "250px" }}>
<div
className="search-bar__input-wrapper"
style={{
display: "flex", alignItems: "center", background: "rgba(255, 255, 255, 0.05)", borderRadius: "var(--radius-md)", padding: "4px 8px", border: "1px solid var(--border-subtle)", width: "100%"
}}
>
<Search size={16} color="var(--text-muted)" style={{ marginRight: "8px", flexShrink: 0 }} />
<input
type="text"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setIsOpen(true);
}}
onFocus={() => setIsOpen(true)}
onKeyDown={handleKeyDown}
placeholder="Search places, addresses, flights..."
style={{
onFocus={() => setIsOpen(true)}
onKeyDown={handleKeyDown}
placeholder="Search places, addresses, flights..."
style={{
background: "transparent",
border: "none",
color: "var(--text-main)",
@@ -122,14 +125,14 @@ export function SearchBar() {
minWidth: "120px",
fontSize: "0.9rem"
}}
/>
</div>
/>
</div>
{isOpen && sections.length > 0 && (
<div
ref={dropdownRef}
className="search-bar__dropdown glass-panel"
style={{
{isOpen && sections.length > 0 && (
<div
ref={dropdownRef}
className="search-bar__dropdown glass-panel"
style={{
position: "absolute",
top: "calc(100% + 8px)",
left: 0,
@@ -145,23 +148,28 @@ export function SearchBar() {
gap: "12px",
padding: "12px"
}}
>
{sections.map((section) => (
<div key={section.title} className="search-section">
<div
className="search-section__header"
style={{
display: "flex", alignItems: "center", gap: "6px", fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--text-muted)", marginBottom: "6px"
}}
>
{sections.map((section) => (
<div key={section.title} className="search-section">
<div className="search-section__header" style={{ display: "flex", alignItems: "center", gap: "6px", fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--text-muted)", marginBottom: "6px" }}>
{section.icon}
{section.title}
</div>
<div className="search-section__results" style={{ display: "flex", flexDirection: "column", gap: "2px" }}>
{section.results.map((result) => {
{section.icon}
{section.title}
</div>
<div className="search-section__results" style={{ display: "flex", flexDirection: "column", gap: "2px" }}>
{section.results.map((result) => {
const isSelected = flatResults[selectedIndex]?.id === result.id;
return (
<button
key={result.id}
className="search-result-item"
onClick={() => handleSelect(result)}
data-selected={isSelected}
style={{
<button
key={result.id}
className="search-result-item"
onClick={() => handleSelect(result)}
data-selected={isSelected}
style={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
@@ -176,26 +184,34 @@ export function SearchBar() {
textAlign: "left",
width: "100%"
}}
onMouseEnter={() => setSelectedIndex(flatResults.findIndex(r => r.id === result.id))}
onMouseEnter={() => setSelectedIndex(flatResults.findIndex((r) => r.id === result.id))}
>
<span style={{
fontWeight: 500, fontSize: "0.85rem", width: "100%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
}}
>
<span style={{ fontWeight: 500, fontSize: "0.85rem", width: "100%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<HighlightMatch text={result.label} query={query} />
</span>
{result.subLabel && (
<span style={{ fontSize: "0.75rem", color: "var(--text-muted)", width: "100%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<HighlightMatch text={result.subLabel} query={query} />
</span>
<HighlightMatch text={result.label} query={query} />
</span>
{result.subLabel && (
<span style={{
fontSize: "0.75rem", color: "var(--text-muted)", width: "100%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
}}
>
<HighlightMatch text={result.subLabel} query={query} />
</span>
)}
</button>
</button>
);
})}
</div>
</div>
))}
</div>
</div>
))}
</div>
)}
{isOpen && query.trim() && sections.length === 0 && (
<div className="search-bar__dropdown glass-panel" style={{
{isOpen && query.trim() && sections.length === 0 && (
<div
className="search-bar__dropdown glass-panel"
style={{
position: "absolute",
top: "calc(100% + 8px)",
left: 0,
@@ -208,10 +224,11 @@ export function SearchBar() {
textAlign: "center",
color: "var(--text-muted)",
fontSize: "0.85rem"
}}>
No results found.
</div>
)}
}}
>
No results found.
</div>
)}
</div>
);
}
+3 -5
View File
@@ -71,10 +71,9 @@ function haversineMetres(a: LatLng, b: LatLng): number {
const toRad = (d: number) => (d * Math.PI) / 180;
const dLat = toRad(b.lat - a.lat);
const dLng = toRad(b.lng - a.lng);
const h =
Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) *
Math.sin(dLng / 2) ** 2;
const h = Math.sin(dLat / 2) ** 2
+ Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat))
* Math.sin(dLng / 2) ** 2;
return 2 * EARTH_RADIUS_M * Math.asin(Math.sqrt(h));
}
@@ -106,4 +105,3 @@ export function getZoomForTypes(
const category = categorizePlace(types);
return ZOOM_BY_CATEGORY[category];
}
Loaded 100 of 278 files, more files were not shown because too many files have changed in this diff. Show more